Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

Fix window game capture entry, recovery and resize geometry

golem Z1295d6bc6c90
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 881e0a0b..e3e30a8d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1103,6 +1103,9 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
add_executable(veyra_qml_data_tests tests/unit/QmlDataDirectoryTests.cpp src/ui/QmlDataDirectory.cpp)
add_executable(veyra_game_passthrough_tests tests/integration/GamePassthroughTests.cpp)
+ add_executable(veyra_game_mode_policy_tests tests/unit/GameModePolicyTests.cpp)
+ target_compile_features(veyra_game_mode_policy_tests PRIVATE cxx_std_20)
+ target_include_directories(veyra_game_mode_policy_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_compile_features(veyra_game_passthrough_tests PRIVATE cxx_std_20)
target_compile_options(veyra_game_passthrough_tests PRIVATE /utf-8)
target_link_libraries(veyra_game_passthrough_tests PRIVATE veyra_qml_bridge)
diff --git a/docs/WINDOW_GAME_FIXES_2026-10-17.md b/docs/WINDOW_GAME_FIXES_2026-10-17.md
new file mode 100644
index 00000000..b1fb7560
--- /dev/null
+++ b/docs/WINDOW_GAME_FIXES_2026-10-17.md
@@ -0,0 +1,78 @@
+# 窗口捕获游戏模式修正(2026-10-17)
+
+用户要求取消进入穿透前的等待,修正窗口捕获拉伸、退出穿透快捷键与源窗口缩放跟随;任务栏残留暂缓,用户正在远程操作。
+
+基线 `d68d6be9c37127350698a1d4d47fc01b36b29475`,分支 `codex/window-game-fixes-20261017`,隔离工作树 `/workspace/veyra-window-fixes`。原 `/workspace/Veyra-NRVideo` 的 main 和文件不变。本轮为 Linux 云环境源码修改,没有连接用户 Windows、改变真实偏好、运行库、模型或驱动。未打包、合并 main、推送或发布。
+
+## 进入与退出
+
+主线没有固定的 3 秒入口倒计时;原来穿透需要等待引擎 running(包含增强初始化),从首页还会等待 820ms 页面动画。本轮游戏模式绕过动画等待,在捕获会话已创建、全屏且键盘监听就绪时立即接管输入,增强继续异步初始化。不承诺视频首帧或模型初始化耗时为零。
+
+保留原有 3 秒 GUI 卡死保护,它是异常恢复机制。停止/失败的 Opening 会话也释放输入。
+
+全局键盘钩子投递到生命周期稳定的 message-only HWND,不再依赖 QML 主窗口 HWND。检测投递失败后恢复普通输入。Qt 平台窗口创建/替换时更新控制器绑定;看门狗通过原子 HWND 读取目标。
+
+退出动作先由控制器清除穿透/不激活状态,再通知 QML 退出全屏。QML 不再因 fullscreen 状态已变化而忽略退出动作。快捷键沿用用户配置。
+
+## 显示与输入
+
+- 捕获对话框“贴合原窗口”:画面按源窗口原尺寸和位置显示,支持真实鼠标精确穿透。
+- “填满屏幕”及后续面板的拉伸、原生像素、固定比例选择真正应用到显示器大小的视频区域,不再被游戏模式强制改为模式 0。
+- 全屏缩放时,源窗口继续获得键盘/手柄焦点,鼠标点击由宿主拦截,避免放大画面上的位置误点到未放大的源窗口。对话框及首次进入缩放状态提示此限制;切回适应模式恢复原窗口对齐与精确穿透。
+- “填满”沿用模式 2(保比例覆盖,可能裁边),面板“拉伸”沿用模式 3(两个方向填充),二者不混用。
+- 新捕获以对话框选择为初始显示方式,不继承上一个影片的拉伸状态;之后的面板选择可替换该会话设置。
+
+本轮**没有实现任意缩放窗口的绝对鼠标坐标映射**,没有向游戏注入或重发鼠标消息。需要鼠标操作的窗口游戏使用贴合原窗口,或让游戏本身使用无边框全屏。真实键盘/手柄兼容性仍需实机验收。
+
+## 源窗口缩放
+
+WGC 交付新尺寸帧时同时更新 SourceInfo 的 width、height、displayAspect 和 Resize 标记;引擎重建处理图时同步更新屏幕捕获的 UI 快照源尺寸/宽高比。显示比例缓存增加 DAR,避免固定输出尺寸未变时继续沿用旧比例。
+
+保留 300ms 尺寸稳定等待和 250ms 几何心跳,不增加逐帧 GPU 等待或提高 UI 轮询频率。拖拽期间仍可能按旧尺寸裁切/补边;停止拖拽后更新实际采集尺寸,模型资源重建耗时需实测。
+
+任务栏 Shell 标记与原 fullscreen 实现未修改。显示器大小的视频区域属于缩放所需布局,不代表本轮修复或验收了任务栏问题。
+
+## 修改范围
+
+`GameModePolicy.h` 封装无平台依赖的输入状态规则;`GameHotkeys.h`、`GamePassthrough.h` 管理接收端、失败恢复、平台窗口重绑定和缩放输入模式;`QmlPlayerBridge.h/.cpp` 修改入口、退出、显示方式和比例缓存。`ScreenCaptureSource.cpp`、`EngineController.cpp` 补齐尺寸元数据传播;`Main.qml`、`DialogHost.qml` 与 catalog 同步输入状态和提示。CMake 与三个测试文件加入针对性回归。
+
+## 本轮验证
+
+回执目录 `/workspace/scratch/veyra-window-checks`,不引用历史 Windows 测试作为本轮通过证据。
+
+| 检查 | 结果 |
+| --- | --- |
+| Linux C++20 编译运行 GameModePolicyTests | 44 项通过,覆盖 Opening、退出/失败、面板、缩放输入及实际 PreviewView 几何 |
+| Qt 6.8.3 qmlcachegen:Main / DialogHost | 字节码与 basic-block 验证通过 |
+| `python -B scripts/i18n/extract.py --check` | 2428 条,繁中/英/日缺失均 0,占位符问题 0 |
+| `git diff --check` | 通过 |
+| MinGW-w64 GCC14 Windows 目标语法检查 GamePassthroughTests | 通过,包含真实热键/穿透头文件 |
+| 同一翻译单元的 Windows 对象编译 | 通过,生成 x86-64 COFF;命令/退出码见 windows-object-command.json |
+| 完整产品 Windows/MSVC 构建与链接 | 未执行 |
+| Windows WGC/GPU/实际 QML bridge/真实游戏运行 | 未执行 |
+
+实际便携检查命令:
+
+```sh
+g++ -std=c++20 -Wall -Wextra -Werror -Wno-misleading-indentation -I include tests/unit/GameModePolicyTests.cpp -o /workspace/scratch/veyra-window-checks/game-mode-policy-tests
+/workspace/scratch/veyra-window-checks/game-mode-policy-tests
+python -B scripts/i18n/extract.py --check
+git diff --check
+```
+
+Qt 命令为 `/workspace/shared/veyra-qt-tools/PySide6/Qt/libexec/qmlcachegen --only-bytecode --validate-basic-blocks -o <scratch输出> <QML文件>`,两个文件分别执行,命令及退出码在 checks.json。
+
+Linux 原生 CMake 配置已尝试,在 project 阶段因缺少 RC 编译器停止,没有记作产品构建成功。交叉工具准备时 apt 索引不含所需包,改用公开 Debian 工具包并核对 SHA;Qt 使用公开 6.8.2 头文件及对应上游 Windows 公共头。工具仅在 `/workspace/shared/veyra-cross-check`,不进入源码 Git。首次对象编译因缺少 Windows 汇编器调用了 Linux 汇编器,已保存失败日志并补齐工具;最终对象编译结果单列回执。这些检查不替代 MSVC、Windows Qt 链接或运行。
+
+## Windows 待执行验收
+
+新增但本轮未运行的回归:
+
+- `veyra_game_passthrough_tests`:保留原发键用例,增加真实 QQuickWindow 全屏/穿透标志切换、面板恢复、源窗口缩放、缩放输入样式、强制平台窗口替换后的退出组合键与原生样式恢复。此测试验证 Qt 宿主和 GamePassthrough,不等同于完整播放器端到端验收。
+- `veyra_screen_capture_tests`:源宽高比更新、横向转纵向的 Resize 标记和真实 RGB 内容;`--engine` 再验证增强运行时的 UI 尺寸/比例快照与持续帧输出。
+
+在隔离 Windows 构建目录构建 `veyra_qml_ui`、上述集成测试与 `veyra_game_mode_policy_tests`,每测试不超过 300 秒、每构建不超过 900 秒。实际播放器连续操作“捕获 A → 全屏 → 面板键 → 调整 A 大小 → 关闭面板 → 退出键”,分别检查原尺寸鼠标落点、填满/拉伸输出、帧号持续更新和退出后原生输入样式;普通窗口、独立 Raw Input 程序、真实窗口化/无边框游戏分开记录。显示器捕获作为对照。
+
+远程测试需确认组合键送达目标机:部分远程客户端截获 Ctrl+Alt+Home;未转发的按键无法被目标机钩子接收,此时使用已有设置换键。混合 DPI、跨显示器、不同权限和真实硬件输入尚未验收。
+
+下一条唯一任务:Windows 隔离构建及上述连续流程实测,按失败证据定点修正;通过前不生成“已验收”发布包。
diff --git a/docs/WORKLOG.md b/docs/WORKLOG.md
index 5e516785..e42ea3bc 100644
--- a/docs/WORKLOG.md
+++ b/docs/WORKLOG.md
@@ -1,5 +1,17 @@
# WORKLOG
+## 2026-10-17 窗口捕获游戏模式修正(Linux 源码候选)
+
+按用户最新要求取消进入穿透的初始化/动画等待,修正退出热键接收和先释放后退出、全屏拉伸/填满与源窗口 resize 元数据;任务栏问题暂缓。以 origin/main d68d6be 在隔离 codex/window-game-fixes-20261017、/workspace/veyra-window-fixes 实施,原 main/用户文件/运行组件保持。源码、输入边界和验收记录见 docs/WINDOW_GAME_FIXES_2026-10-17.md。
+
+无固定3秒入口倒计时可删;取消等待引擎running及游戏模式首页820ms动画,保留3秒GUI卡死保护。热键改用message-only接收窗口,退出动作先原生恢复;Qt句柄替换重绑定,投递失败可恢复。缩放实际生效,键盘/手柄前台保留,鼠标点击拦截以免坐标错位;原尺寸模式保留精确穿透,未实现任意缩放鼠标映射。SourceInfo/DAR、UI快照和比例缓存同步更新,300ms去抖/250ms几何节奏保持;没有改NR/SR/FG算法或任务栏Shell标记。
+
+实际运行Linux g++ C++20 GameModePolicyTests:44检查0失败;Qt6.8.3 qmlcachegen两文件字节码/basic-block通过;i18n extract --check:2428条三语缺失0/占位符0;diff --check通过。MinGW14 Windows目标语法检查GamePassthroughTests通过。回执/workspace/scratch/veyra-window-checks/{checks.json,windows-syntax.log}。原生CMake配置因Linux缺RC编译器失败;交叉对象编译最初缺Windows汇编器,保留失败证据并补齐工具,最终结果另记。工具安装/公开头文件只在shared,不进源码库。
+
+补齐目标汇编器后,GamePassthroughTests及其真实热键/穿透头文件Windows对象编译通过,生成x86-64 COFF;windows-object-command.json记录实际命令/返回0,windows-object.log为空,首次失败日志保留。此对象未链接或运行。
+
+新增Qt Quick宿主连续切换与WGC源/engine resize回归,但本轮未在Windows运行;完整MSVC构建、实际QML bridge/GPU、真实游戏/远程热键、DPI跨屏均未执行,不宣称已实机复现或修复验收。下一步唯一任务是Windows隔离构建和用户操作顺序实测;无打包/合并main/push/Release/关机。
+
## 2026-10-10 VFG 优化(Claude,任务一)
- 授权:用户“开始进行优化吧,全部搞定掉”“开始之前先创建存档,然后开分支弄,如果是结果是性能反而倒退,直接退回”。开工前打标签 checkpoint/pre-claude-perf-20261010(main 5ba186a),E 盘 archives/claude-perf-20261010 存 source-before.bundle(已 verify)和 start.json(46 工作树、495 脏文件逐项 SHA)。分支 claude/vfg-20261010 只改 VFG;软件链路在 claude/pipeline-20261010 独立实施。
diff --git a/i18n/catalog.json b/i18n/catalog.json
index 9dae2452..096023a4 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -3563,6 +3563,13 @@
"en": "Fullscreen (double-click the picture / F11)",
"ja": "全画面表示(映像をダブルクリック / F11)"
},
+ {
+ "zh": "全屏缩放已启用:键盘和手柄控制源窗口,鼠标点击已拦截以免错位;需要鼠标穿透时切回贴合原窗口",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "全螢幕縮放已啟用:鍵盤和手把控制來源視窗,滑鼠點擊已攔截以免錯位;需要滑鼠穿透時切回貼合原視窗",
+ "en": "Fullscreen scaling is active. Keyboard and gamepad control the source window; mouse clicks are blocked to avoid misalignment. Return to original-window alignment for mouse passthrough.",
+ "ja": "全画面拡大を有効にしました。キーボードとゲームパッドは元のウィンドウを操作し、位置ずれを防ぐためマウスクリックを遮断します。マウス透過には元のウィンドウに合わせる表示へ戻してください。"
+ },
{
"zh": "全屏(双击画面 / F11)· 全屏后按 %1 打开快速调节",
"src": "qml/ProPage.qml",
@@ -5342,6 +5349,20 @@
"en": "Fill and crop",
"ja": "フィル(切り取り)"
},
+ {
+ "zh": "填满屏幕",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "填滿螢幕",
+ "en": "Fill screen",
+ "ja": "画面全体に表示"
+ },
+ {
+ "zh": "填满屏幕支持键盘和手柄;需要精确鼠标穿透时请选择贴合原窗口",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "填滿螢幕支援鍵盤和手把;需要精確滑鼠穿透時請選擇貼合原視窗",
+ "en": "Fill screen supports keyboard and gamepad. Choose original-window alignment for precise mouse passthrough.",
+ "ja": "画面全体に表示する場合はキーボードとゲームパッドを使用できます。正確なマウス透過には元のウィンドウに合わせてください。"
+ },
{
"zh": "填满窗口",
"src": "qml/DialogHost.qml",
@@ -11077,11 +11098,11 @@
"ja": "ゲームモード"
},
{
- "zh": "游戏模式不裁剪,画面和屏幕一一对应,点到哪里就是哪里",
+ "zh": "游戏模式不裁剪;贴合原窗口时画面与鼠标位置一一对应",
"src": "qml/DialogHost.qml",
- "zh-TW": "遊戲模式不裁切,畫面和螢幕一一對應,點到哪裡就是哪裡",
- "en": "Game mode does not crop: the picture matches the screen, so clicks land where you see them",
- "ja": "ゲームモードでは切り抜きません。映像と画面が一致し、見た位置をそのままクリックできます"
+ "zh-TW": "遊戲模式不裁剪;貼合原視窗時畫面與滑鼠位置一一對應",
+ "en": "Game mode does not crop the source. Original-window alignment preserves exact mouse positions.",
+ "ja": "ゲームモードではソースを切り抜きません。元のウィンドウに合わせると映像とマウス位置が一致します。"
},
{
"zh": "游戏模式用真实指针,画面里不再画一个",
@@ -11091,11 +11112,11 @@
"ja": "ゲームモードでは実際のポインターを使い、映像には描きません"
},
{
- "zh": "游戏模式键盘监听启动失败,未开启鼠标穿透;请退出全屏后重试",
+ "zh": "游戏模式键盘监听不可用,已退出鼠标穿透;请退出全屏后重试",
"src": "src/ui/QmlPlayerBridge.cpp",
- "zh-TW": "遊戲模式鍵盤監聽啟動失敗,未開啟滑鼠穿透;請退出全螢幕後重試",
- "en": "Game mode keyboard listener could not start. Mouse passthrough is off; leave fullscreen and try again.",
- "ja": "ゲームモードのキー監視を開始できません。マウス透過はオフです。全画面を解除して再試行してください。"
+ "zh-TW": "遊戲模式鍵盤監聽無法使用,已退出滑鼠穿透;請退出全螢幕後重試",
+ "en": "Game-mode keyboard listener is unavailable. Mouse passthrough has been released; leave fullscreen and retry.",
+ "ja": "ゲームモードのキーボード監視を利用できません。マウス透過を解除しました。全画面を終了して再試行してください。"
},
{
"zh": "游戏模式:调整画面",
@@ -11482,13 +11503,6 @@
"en": "Image correction controls temporal stability; this setting returns when correction is off",
"ja": "画質調整が時間方向の安定化を制御中。オフにするとこの設定に戻ります。"
},
- {
- "zh": "画面贴合游戏窗口的位置,键鼠和手柄照常操作游戏;%1 调整画面,%2 退出。独占全屏请改为无边框窗口",
- "src": "qml/DialogHost.qml",
- "zh-TW": "畫面貼合遊戲視窗位置,鍵鼠與手把照常操作遊戲;%1 調整畫面,%2 退出。獨佔全螢幕請改為無邊框視窗",
- "en": "The picture follows the game window position. Use the keyboard, mouse and controller normally; %1 adjusts the picture and %2 exits. Use borderless mode instead of exclusive fullscreen.",
- "ja": "ゲームウィンドウの位置に画面を合わせます。通常どおり操作し、%1 で画面調整、%2 で解除。排他全画面ではなくボーダーレスにしてください。"
- },
{
"zh": "界面卡住超过 3 秒,已退出游戏模式",
"src": "src/ui/QmlPlayerBridge.cpp",
@@ -13960,6 +13974,20 @@
"en": "Rate control",
"ja": "品質の方式"
},
+ {
+ "zh": "贴合原窗口",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "貼合原視窗",
+ "en": "Align to source window",
+ "ja": "元のウィンドウに合わせる"
+ },
+ {
+ "zh": "贴合原窗口时可精确穿透鼠标;填满或拉伸支持键盘和手柄,鼠标点击会被拦截以免错位。%1 调整画面,%2 退出;独占全屏请改为无边框窗口",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "貼合原視窗時可精確穿透滑鼠;填滿或拉伸支援鍵盤和手把,滑鼠點擊會被攔截以免錯位。%1 調整畫面,%2 退出;獨佔全螢幕請改為無邊框視窗",
+ "en": "Original-window alignment supports precise mouse passthrough. Fill/stretch supports keyboard and gamepad; mouse clicks are blocked to prevent misalignment. %1 adjusts the picture; %2 exits. Use borderless instead of exclusive fullscreen.",
+ "ja": "元のウィンドウに合わせると正確なマウス透過を利用できます。塗りつぶし・引き伸ばしではキーボードとゲームパッドに対応し、位置ずれを防ぐためマウスクリックを遮断します。%1 で画面調整、%2 で終了。排他全画面ではなくボーダーレスにしてください。"
+ },
{
"zh": "资源不可用",
"src": "src/pipeline/EnhanceGraph.cpp",
diff --git a/include/veyra/ui/GameHotkeys.h b/include/veyra/ui/GameHotkeys.h
index 73e9f36c..7cfa5b9b 100644
--- a/include/veyra/ui/GameHotkeys.h
+++ b/include/veyra/ui/GameHotkeys.h
@@ -72,10 +72,13 @@ public:
}
void panelOwned(bool on) { panelOwned_.store(on); }
bool running() const { return running_.load(); }
+ DWORD takeDeliveryError() { return deliveryError_.exchange(0); }
bool current(LPARAM epoch) const { return running() && uint64_t(epoch) == epoch_.load(); }
bool start(HWND target) {
if (running()) return true;
stop(); target_ = target;
+ deliveryError_.store(0);
+ if (!IsWindow(target_)) return false;
stopEvent_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!stopEvent_) return false;
std::promise<bool> ready; auto initialized = ready.get_future();
@@ -111,6 +114,7 @@ private:
HANDLE stopEvent_ = nullptr;
std::thread thread_;
std::atomic<bool> running_{false}, panelOwned_{false};
+ std::atomic<DWORD> deliveryError_{0};
std::atomic<uint64_t> config_{uint64_t(VK_HOME) | (uint64_t(VK_HOME) << 16) | (3ull << 24)}, epoch_{0};
GameKeyState state_;
static inline thread_local GameHotkeyListener* self_ = nullptr;
@@ -124,7 +128,12 @@ private:
const GameKey panel{unsigned(config & 255), unsigned((config >> 8) & 15)};
const GameKey exit{unsigned((config >> 16) & 255), unsigned((config >> 24) & 15)};
const auto result = self.state_.input(key->vkCode, down, panel, exit, self.panelOwned_.load());
- if (result.action >= 0 && epoch == self.epoch_.load()) PostMessageW(self.target_, message, WPARAM(result.action), LPARAM(epoch));
+ if (result.action >= 0 && epoch == self.epoch_.load() &&
+ !PostMessageW(self.target_, message, WPARAM(result.action), LPARAM(epoch))) {
+ const DWORD error = GetLastError();
+ self.deliveryError_.store(error ? error : ERROR_INVALID_WINDOW_HANDLE);
+ return CallNextHookEx(nullptr, code, wp, lp);
+ }
if (result.consume) return 1;
}
}
diff --git a/include/veyra/ui/GameModePolicy.h b/include/veyra/ui/GameModePolicy.h
new file mode 100644
index 00000000..568173f2
--- /dev/null
+++ b/include/veyra/ui/GameModePolicy.h
@@ -0,0 +1,19 @@
+#pragma once
+
+namespace veyra::ui {
+// Scaled output must not pass absolute mouse positions to an unscaled window.
+// Keyboard/gamepad input can still belong to the foreground capture target.
+enum class GameInputMode { Off, Panel, Through, Scaled };
+
+constexpr bool gameViewportScaled(bool fill, int aspectMode) {
+ return fill || aspectMode != 0;
+}
+
+constexpr GameInputMode gameInputMode(bool session, bool fullscreen, bool refused,
+ bool panel, bool scaled) {
+ // Opening a source is sufficient; feature initialization is not an entry delay.
+ if (!session || !fullscreen || refused) return GameInputMode::Off;
+ if (panel) return GameInputMode::Panel;
+ return scaled ? GameInputMode::Scaled : GameInputMode::Through;
+}
+}
diff --git a/include/veyra/ui/GamePassthrough.h b/include/veyra/ui/GamePassthrough.h
index 26563496..9864ca04 100644
--- a/include/veyra/ui/GamePassthrough.h
+++ b/include/veyra/ui/GamePassthrough.h
@@ -4,12 +4,13 @@
// capture, the whole desktop - gets the real keyboard, mouse and gamepad (Raw Input
// and DirectInput only report to the foreground window; posted input does not work).
//
-// The main window becomes click-through through Qt's own flags
+// The 1:1 main window becomes click-through through Qt's own flags
// (Qt::WindowTransparentForInput | Qt::WindowDoesNotAcceptFocus, bound in Main.qml to
// passthroughActive), so Qt keeps WS_EX_LAYERED | WS_EX_TRANSPARENT itself - with the
// software interface it drops a layered bit set behind its back. Qt does not set
// WS_EX_NOACTIVATE on it, so this class adds that bit, makes the window topmost,
-// hands the foreground over, owns the hotkeys and the watchdog, and makes any other
+// Scaled output retains keyboard/gamepad foreground but blocks mouse clicks.
+// This class hands the foreground over, owns the hotkeys and the watchdog, and makes any other
// visible Veyra window click-through too. The configurable panel key while the picture is
// in front, opens the adjust panel and takes the input back; closing the panel hands
// it to the program again. The configurable exit key leaves. The keyboard hook has
@@ -37,14 +38,15 @@
#include "veyra/Log.h"
#include "veyra/source/ScreenCaptureSource.h"
#include "veyra/ui/GameHotkeys.h"
+#include "veyra/ui/GameModePolicy.h"
namespace veyra::ui {
class GamePassthrough final : public QAbstractNativeEventFilter {
public:
// Off: a normal window. Panel: on top and interactive (Home panel open).
- // Through: on top, click-through, the captured program has the foreground.
- enum class Mode { Off, Panel, Through };
+ // Through: exact click-through. Scaled: blocks mouse, target retains keyboard/gamepad.
+ using Mode = GameInputMode;
enum class Event { PanelHotkey, ExitHotkey, ExitUnavailable, HangReleased };
std::function<void(Event)> onEvent;
@@ -53,12 +55,20 @@ public:
stopWatchdog();
apply(Mode::Off);
keys_.stop();
+ if (receiver_) DestroyWindow(receiver_);
if (s_instance == this) s_instance = nullptr;
}
GamePassthrough(const GamePassthrough&) = delete;
GamePassthrough& operator=(const GamePassthrough&) = delete;
- void attach(HWND main) { main_ = main; }
+ void attach(HWND main) {
+ if (main_ == main) return;
+ const Mode previous = mode_;
+ apply(Mode::Off);
+ main_ = main;
+ watchedMain_.store(main);
+ if (previous != Mode::Off) apply(previous);
+ }
// window: the captured window (window capture), else nullptr. monitor: where the
// picture is shown (the captured monitor, or the monitor of the captured window).
void setTarget(HWND window, HMONITOR monitor, bool monitorCapture) {
@@ -87,9 +97,9 @@ public:
// The listener must exist before anything may become click-through.
bool arm() {
- if (!main_) return false;
+ if (!main_ || !IsWindow(main_)) return false;
if (keys_.running()) return true;
- if (!keys_.start(main_)) {
+ if (!ensureReceiver() || !keys_.start(receiver_)) {
veyra::log::warn("game-mode", "keyboard listener unavailable; click-through refused");
if (onEvent) onEvent(Event::ExitUnavailable);
return false;
@@ -127,8 +137,8 @@ public:
sunk_ = false;
topmost(true);
keepTaskbarButton();
- if (next == Mode::Through) {
- setTransparent(true);
+ if (next == Mode::Through || next == Mode::Scaled) {
+ setTransparent(next == Mode::Through);
noActivate(true);
focus(focusTarget(), "program");
} else {
@@ -137,12 +147,17 @@ public:
focus(main_, "Veyra");
}
updatePanelHotkey(GetForegroundWindow());
- log(next == Mode::Through ? "click-through" : "panel");
+ log(next == Mode::Through ? "click-through" : next == Mode::Scaled ? "scaled keyboard/gamepad" : "panel");
}
// GUI thread, every 250 ms while the bridge runs.
void heartbeat() {
beat_.store(GetTickCount64());
+ if (const DWORD error = keys_.takeDeliveryError(); error && mode_ != Mode::Off) {
+ veyra::log::warn("game-mode", std::format("hotkey delivery failed err={}; releasing input", error));
+ if (onEvent) onEvent(Event::ExitUnavailable);
+ return;
+ }
if (cloaked_.exchange(false)) {
BOOL cloak = FALSE;
DwmSetWindowAttribute(main_, DWMWA_CLOAK, &cloak, sizeof cloak);
@@ -154,16 +169,10 @@ public:
if (mode_ != Mode::Off && !sunk_ && main_ && !(GetWindowLongPtrW(main_, GWL_EXSTYLE) & WS_EX_TOPMOST)) topmost(true);
}
- bool nativeEventFilter(const QByteArray& type, void* message, qintptr* result) override {
+ bool nativeEventFilter(const QByteArray& type, void* message, qintptr*) override {
if (type != "windows_generic_MSG") return false;
const auto* msg = static_cast<const MSG*>(message);
switch (msg->message) {
- case GameHotkeyListener::message:
- if (!keys_.current(msg->lParam) || mode_ == Mode::Off || msg->wParam > 1 ||
- (msg->wParam == 0 && !panelOwned_)) return false;
- if (onEvent) onEvent(msg->wParam == 0 ? Event::PanelHotkey : Event::ExitHotkey);
- if (result) *result = 0;
- return true;
case WM_SHOWWINDOW:
if (msg->wParam) shown(msg->hwnd);
return false;
@@ -182,6 +191,8 @@ private:
static inline GamePassthrough* s_instance = nullptr;
HWND main_ = nullptr, target_ = nullptr;
+ HWND receiver_ = nullptr; // message-only HWND; unaffected by Qt flags/fullscreen
+ std::atomic<HWND> watchedMain_{nullptr};
HMONITOR monitor_ = nullptr;
bool monitorCapture_ = false;
Mode mode_ = Mode::Off;
@@ -198,6 +209,34 @@ private:
std::atomic<ULONGLONG> beat_{0};
std::atomic<bool> armed_{false}, cloaked_{false};
+ static LRESULT CALLBACK receiverProc(HWND window, UINT message, WPARAM wp, LPARAM lp) {
+ if (message == WM_NCCREATE) {
+ const auto* create = reinterpret_cast<const CREATESTRUCTW*>(lp);
+ SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(create->lpCreateParams));
+ }
+ auto* self = reinterpret_cast<GamePassthrough*>(GetWindowLongPtrW(window, GWLP_USERDATA));
+ if (self && message == GameHotkeyListener::message) {
+ if (self->keys_.current(lp) && self->mode_ != Mode::Off && wp <= 1 &&
+ (wp == 1 || self->panelOwned_)) {
+ veyra::log::info("game-mode", std::format("hotkey received action={} epoch={}", wp, lp));
+ if (self->onEvent) self->onEvent(wp == 0 ? Event::PanelHotkey : Event::ExitHotkey);
+ }
+ return 0;
+ }
+ return DefWindowProcW(window, message, wp, lp);
+ }
+ bool ensureReceiver() {
+ if (receiver_ && IsWindow(receiver_)) return true;
+ WNDCLASSW wc{};
+ wc.lpfnWndProc = &GamePassthrough::receiverProc;
+ wc.hInstance = GetModuleHandleW(nullptr);
+ wc.lpszClassName = L"Veyra.GameHotkeyReceiver";
+ if (!RegisterClassW(&wc) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return false;
+ receiver_ = CreateWindowExW(0, wc.lpszClassName, L"", 0, 0, 0, 0, 0,
+ HWND_MESSAGE, nullptr, wc.hInstance, this);
+ return receiver_ != nullptr;
+ }
+
void log(const char* what) {
const LONG_PTR ex = main_ ? GetWindowLongPtrW(main_, GWL_EXSTYLE) : 0;
veyra::log::info("game-mode", std::format("{} monitorCapture={} target=0x{:X} exstyle=0x{:X} windows={} panelOwned={} exitHook={}",
@@ -319,7 +358,7 @@ private:
// other programs it stays theirs.
void updatePanelHotkey(HWND fg) {
bool want = mode_ == Mode::Panel || ours(fg);
- if (!want && mode_ == Mode::Through)
+ if (!want && (mode_ == Mode::Through || mode_ == Mode::Scaled))
want = monitorCapture_ ? MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) == monitor_ : isTarget(fg);
setPanelHotkey(want);
}
@@ -329,7 +368,7 @@ private:
void foregroundChanged(HWND fg) {
if (mode_ == Mode::Off) return;
updatePanelHotkey(fg);
- if (mode_ != Mode::Through || monitorCapture_ || ours(fg)) return;
+ if ((mode_ != Mode::Through && mode_ != Mode::Scaled) || monitorCapture_ || ours(fg)) return;
if (isTarget(fg)) {
if (sunk_) { sunk_ = false; topmost(true); log("program back in front: picture on top"); }
return;
@@ -357,7 +396,8 @@ private:
if (stale < kHangMs) continue;
// DWM cloaking needs nothing from the stuck GUI thread.
BOOL cloak = TRUE;
- const HRESULT hr = DwmSetWindowAttribute(main_, DWMWA_CLOAK, &cloak, sizeof cloak);
+ const HWND main = watchedMain_.load();
+ const HRESULT hr = main && ours(main) ? DwmSetWindowAttribute(main, DWMWA_CLOAK, &cloak, sizeof cloak) : E_HANDLE;
cloaked_.store(SUCCEEDED(hr));
veyra::log::warn("game-mode", std::format("GUI silent for {} ms: picture cloaked hr=0x{:08X}", stale, unsigned(hr)));
}
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index f4cfe121..40f192dd 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -167,6 +167,8 @@ class QmlPlayerBridge : public QObject {
// fullscreen picture is click-through and the captured program has the input.
Q_PROPERTY(bool gameMode READ gameMode NOTIFY gameModeChanged)
Q_PROPERTY(bool passthroughActive READ passthroughActive NOTIFY gameModeChanged)
+ Q_PROPERTY(bool gameInputActive READ gameInputActive NOTIFY gameModeChanged)
+ Q_PROPERTY(bool gameScaledPreview READ gameScaledPreview NOTIFY gameModeChanged)
Q_PROPERTY(QRectF gameVideoRect READ gameVideoRect NOTIFY gameModeChanged)
// Subtitles (P4-c): the engine's SubtitleLoader reads the embedded tracks and
@@ -691,6 +693,8 @@ public:
Q_INVOKABLE bool startScreenCapture();
bool gameMode() const;
bool passthroughActive() const;
+ bool gameInputActive() const;
+ bool gameScaledPreview() const;
QRectF gameVideoRect() const;
// The Home panel is open: the picture stays on top but takes the input back.
Q_INVOKABLE void setGamePanelOpen(bool open);
@@ -1377,7 +1381,7 @@ private:
#endif
void queryCapture(int kind, std::wstring device);
// Opens a device/stream URI (capture, screen) the way openPath opens a file.
- void openSourceUri(const std::wstring& uri, const std::wstring& label);
+ void openSourceUri(const std::wstring& uri, const std::wstring& label, bool screenFill = false);
struct Impl;
std::unique_ptr<Impl> impl_;
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index a701118c..928a2a00 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -1364,7 +1364,7 @@ Item {
label: qsTr("游戏模式")
hint: screenDialog.o.kind === 1
? qsTr("开始后 Veyra 在这块屏幕上全屏,键鼠和手柄直接操作屏幕上的程序;%1 调整画面,%2 退出").arg(veyra.shortcuts.gamePanel).arg(veyra.shortcuts.gameExit)
- : qsTr("画面贴合游戏窗口的位置,键鼠和手柄照常操作游戏;%1 调整画面,%2 退出。独占全屏请改为无边框窗口").arg(veyra.shortcuts.gamePanel).arg(veyra.shortcuts.gameExit)
+ : qsTr("贴合原窗口时可精确穿透鼠标;填满或拉伸支持键盘和手柄,鼠标点击会被拦截以免错位。%1 调整画面,%2 退出;独占全屏请改为无边框窗口").arg(veyra.shortcuts.gamePanel).arg(veyra.shortcuts.gameExit)
VSwitch {
objectName: "screen-game-mode"
checked: screenDialog.o.passthrough === true
@@ -1408,7 +1408,7 @@ Item {
}
VRow {
label: qsTr("裁剪(像素)")
- hint: screenDialog.o.passthrough === true ? qsTr("游戏模式不裁剪,画面和屏幕一一对应,点到哪里就是哪里") : qsTr("左 / 上 / 右 / 下,按源像素")
+ hint: screenDialog.o.passthrough === true ? qsTr("游戏模式不裁剪;贴合原窗口时画面与鼠标位置一一对应") : qsTr("左 / 上 / 右 / 下,按源像素")
RowLayout {
spacing: 4
enabled: screenDialog.o.passthrough !== true
@@ -1426,8 +1426,10 @@ Item {
}
VRow {
label: qsTr("画面")
+ hint: screenDialog.o.passthrough === true ? qsTr("填满屏幕支持键盘和手柄;需要精确鼠标穿透时请选择贴合原窗口") : ""
VSeg {
- options: [{ id: "fit", label: qsTr("适应窗口") }, { id: "fill", label: qsTr("填满窗口") }]
+ options: [{ id: "fit", label: screenDialog.o.passthrough === true ? qsTr("贴合原窗口") : qsTr("适应窗口") },
+ { id: "fill", label: screenDialog.o.passthrough === true ? qsTr("填满屏幕") : qsTr("填满窗口") }]
current: screenDialog.o.fill ? "fill" : "fit"
onPicked: id => veyra.setScreenOption("fill", id === "fill")
}
diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qml
index e30991f1..a256acf1 100644
--- a/qml/Veyra/Main.qml
+++ b/qml/Veyra/Main.qml
@@ -32,7 +32,8 @@ Window {
// 游戏模式 click-through (ui/GamePassthrough.h): Qt's own flags, so Qt keeps the
// window's layered/transparent/no-activate styles in both interface renderers.
flags: Qt.Window | Qt.FramelessWindowHint
- | (veyra.passthroughActive ? (Qt.WindowTransparentForInput | Qt.WindowDoesNotAcceptFocus) : 0)
+ | (veyra.passthroughActive ? Qt.WindowTransparentForInput : 0)
+ | (veyra.gameInputActive ? Qt.WindowDoesNotAcceptFocus : 0)
title: "Veyra " + veyra.version
// Page ids match the prototype's PAGES keys so a design screenshot and an
@@ -66,7 +67,7 @@ Window {
// 16:9 until a source reports its own shape: a PS5 / capture session has no
// aspect while it connects, and 2.39 then left a thin black strip.
property real filmAspect: 16 / 9
- readonly property bool gameAligned: fullscreen && veyra.gameMode
+ readonly property bool gameAligned: fullscreen && veyra.gameMode && !veyra.gameScaledPreview
readonly property real reportedAspect: veyra.previewAspect
onReportedAspectChanged: if (reportedAspect < 0.2) fitToFilm(16 / 9)
property string lastPage: "home"
@@ -440,8 +441,12 @@ Window {
// Home: the adjust panel takes the input back / gives it to the program again.
// Ctrl+Alt+Home: leave the fullscreen picture (and with it the click-through).
function onGameHotkey(which) {
+ if (which === 1) {
+ root.closeQuickPanel()
+ if (root.fullscreen) root.toggleFullscreen()
+ return
+ }
if (!root.fullscreen) return
- if (which === 1) { root.closeQuickPanel(); root.toggleFullscreen(); return }
root.fullLocked = false
root.toggleQuickPanel()
}
@@ -451,7 +456,7 @@ Window {
}
function onGameModeChanged() {
videoHost.syncRect()
- if (veyra.passthroughActive && playlistWindow.visible) playlistWindow.hide()
+ if (veyra.gameInputActive && playlistWindow.visible) playlistWindow.hide()
}
}
onFullscreenChanged: {
@@ -640,7 +645,7 @@ Window {
// an open dialog, which lives in the main window below it.
cinema: root.cinema && !root.fullscreen
pillTop: (root.maximized ? root.height : root.pictureHeight) - 46
- shown: veyra.hasSource && !root.pillHidden && !veyra.passthroughActive && (root.fullscreen ? root.fullControls && !root.fullLocked
+ shown: veyra.hasSource && !root.pillHidden && !veyra.gameInputActive && (root.fullscreen ? root.fullControls && !root.fullLocked
: root.cinema && root.shownPage === "min"
&& root.leavingPage === "" && dialogs.dialog === ""
&& root.visibility !== Window.Minimized)
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 82b994d5..b3685551 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -1867,6 +1867,10 @@ void EngineController::run(HWND window,std::wstring path,PlayerOptions options,s
if(nativeCapture){
captureGraphColor=activeSource->info().color;gd.rgbInput=captureGraphColor.pixelFormat==pipeline::SourcePixelFormat::Bgra8;
gd.yuy2Input=false;gd.packedInput=pipeline::packedInputCode(captureGraphColor.pixelFormat);gd.captureBitDepth=ingressBitDepth(captureGraphColor.pixelFormat);
+ }
+ // Window capture publishes the same geometry used to rebuild
+ // the graph, rather than retaining its opening DAR.
+ if(isScreen||nativeCapture){
std::lock_guard lock(mutex_);snapshot_.sourceWidth=width;snapshot_.sourceHeight=height;snapshot_.sourceHdr=gd.hdrInput;snapshot_.sourceMasteringPeakNits=resizeMastering;snapshot_.sourceMaxCllNits=resizeCll;snapshot_.sourceMaxFallNits=resizeFall;snapshot_.sourceDisplayAspect=activeSource->info().displayAspect;
}
if(!presenter.prepareGraphChange()){status(L"输入尺寸切换呈现排空失败",true);break;}
diff --git a/src/source/ScreenCaptureSource.cpp b/src/source/ScreenCaptureSource.cpp
index 382fc152..aafa69e6 100644
--- a/src/source/ScreenCaptureSource.cpp
+++ b/src/source/ScreenCaptureSource.cpp
@@ -356,7 +356,10 @@ SourceReadStatus ScreenCaptureSource::read(pipeline::FramePacket& packet,const A
packet.sourceKind=pipeline::SourceKind::ScreenCapture;packet.colorInfo=p.info.color;
packet.arrivalHost100ns=host100ns();packet.decodedHost100ns=packet.arrivalHost100ns;
if(p.sequence==1)packet.flags|=uint32_t(pipeline::FrameFlagBits::Open);
- if(w!=p.info.width||h!=p.info.height){packet.flags|=uint32_t(pipeline::FrameFlagBits::Resize);p.info.width=w;p.info.height=h;}
+ if(w!=p.info.width||h!=p.info.height){
+ packet.flags|=uint32_t(pipeline::FrameFlagBits::Resize);
+ p.info.width=w;p.info.height=h;p.info.displayAspect=double(w)/h;
+ }
if(p.wasWaiting||p.lastPts&&pts-p.lastPts>std::max<int64_t>(p.interval()*2,1000000))packet.flags|=uint32_t(pipeline::FrameFlagBits::Discontinuity);
packet.hardwareSurface={slot->consumer.Get(),0,p.fence.Get(),p.signal,w,h};
p.nextPts=std::max(p.nextPts+p.interval(),pts+p.interval()/2);
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index 317bb5ea..1e3b23b0 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -27,6 +27,7 @@
#include <QCursor>
#include <QScreen>
#include <QWindow>
+#include <QPlatformSurfaceEvent>
#include <QPointer>
#include <QDateTime>
@@ -447,6 +448,7 @@ struct QmlPlayerBridge::Impl {
std::vector<source::ScreenCaptureTarget> screenList;
bool screenFillActive = false;
QSize screenFitClient, screenFitImage;
+ double screenFitAspect = -1;
// --- image batch ---
QStringList imageFiles;
QString imageFolder, imageTarget, imageStatus;
@@ -526,7 +528,7 @@ struct QmlPlayerBridge::Impl {
std::wstring gameModeUri; // the screen URI startScreenCapture opened in game mode
uint64_t gameModeSessionId = 0; // its engine session once the open ran
bool gameModeLive = false, gamePanelOpen = false, gameRefused = false;
- bool gameModeShown = false, passthroughShown = false;
+ bool gameModeShown = false, passthroughShown = false, gameInputShown = false;
QRectF gameVideoRect;
QPointer<QWindow> gameWindow;
HMONITOR gameMonitor = nullptr;
@@ -1227,14 +1229,22 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
using E = ui::GamePassthrough::Event;
switch (event) {
case E::PanelHotkey: emit gameHotkey(0); break;
- case E::ExitHotkey: emit gameHotkey(1); break;
+ case E::ExitHotkey:
case E::ExitUnavailable:
- emit notice(tr("游戏模式键盘监听启动失败,未开启鼠标穿透;请退出全屏后重试"), true); break;
+ // Restore input before QML processes its fullscreen notification.
+ impl_->gameRefused = true;
+ impl_->gameInputShown = impl_->passthroughShown = false;
+ emit gameModeChanged();
+ impl_->game.apply(ui::GamePassthrough::Mode::Off);
+ if (event == E::ExitHotkey) emit gameHotkey(1);
+ else emit notice(tr("游戏模式键盘监听不可用,已退出鼠标穿透;请退出全屏后重试"), true);
+ break;
case E::HangReleased:
// Publish Off before the foreground goes back to Veyra; stay out of
// click-through until fullscreen is left.
impl_->gameRefused = true;
- if (impl_->passthroughShown) { impl_->passthroughShown = false; emit gameModeChanged(); }
+ impl_->gameInputShown = impl_->passthroughShown = false;
+ emit gameModeChanged();
impl_->game.apply(ui::GamePassthrough::Mode::Off);
emit gameModeStopped(tr("界面卡住超过 3 秒,已退出游戏模式")); break;
}
@@ -2653,13 +2663,16 @@ bool QmlPlayerBridge::startCaptureSession() {
emit snapshotChanged();
return true;
}
-void QmlPlayerBridge::openSourceUri(const std::wstring& uri, const std::wstring& label) {
+void QmlPlayerBridge::openSourceUri(const std::wstring& uri, const std::wstring& label, bool screenFill) {
rememberPosition(true);
impl_->openingSource = true;
impl_->openingSessionId = 0;
impl_->sourceLabel = label;
impl_->resumeSession = 0;
- impl_->screenFillActive = false;
+ impl_->screenFillActive = screenFill;
+ // Honor the dialog's initial viewport before input can be taken over.
+ // Later explicit aspect choices still replace this session preset.
+ if (!impl_->gameModeUri.empty() && uri == impl_->gameModeUri) impl_->aspectMode = 0;
const bool screen = uri.find(L"screen") != std::wstring::npos;
veyra::log::info("capture-ui", "open uri " + QString::fromStdWString(uri).toStdString());
openAfterCinema(screen ? tr("正在开始屏幕捕获…") : tr("正在打开采集设备 · %1").arg(utf8Of(label)), [this, uri] {
@@ -2671,6 +2684,7 @@ void QmlPlayerBridge::openSourceUri(const std::wstring& uri, const std::wstring&
impl_->gameModeSessionId = !impl_->gameModeUri.empty() && uri == impl_->gameModeUri ? impl_->openingSessionId : 0;
impl_->gameModeLive = false;
impl_->gameModeUri.clear();
+ updateGameMode();
refreshSubtitles({});
});
}
@@ -2678,7 +2692,11 @@ void QmlPlayerBridge::openSourceUri(const std::wstring& uri, const std::wstring&
void QmlPlayerBridge::openAfterCinema(const QString& pending, std::function<void()> open) {
const int gen = ++impl_->liveOpenGen;
const bool fromHome = impl_->currentPage.isEmpty() || impl_->currentPage == QLatin1String("home");
- if (!fromHome) { impl_->pendingLiveText.clear(); open(); return; }
+ if (!fromHome || !impl_->gameModeUri.empty()) {
+ // Game mode does not wait for the cinema animation or feature startup.
+ if (fromHome) emit navigate(QStringLiteral("min"));
+ impl_->pendingLiveText.clear(); open(); return;
+ }
// User report 2026-09-29: the window blacked out and jumped into 极简 when
// the engine opened in the same instant as the page switch and the window's
// height spring. Switch first, say that it is connecting, then open once
@@ -2793,14 +2811,19 @@ bool QmlPlayerBridge::startScreenCapture() {
} else impl_->gameModeUri.clear();
veyra::log::info("screen-ui", std::format("start kind={} method={} fps={} cursor={} crop={},{},{},{} fill={} gameMode={}", int(value.kind), int(value.method),
value.fps, value.cursor, value.left, value.top, value.right, value.bottom, o.value("fill").toBool(), game));
- openSourceUri(value.uri(), wideOf(screenTargetLabel()));
- impl_->screenFillActive = !game && o.value("fill").toBool();
+ openSourceUri(value.uri(), wideOf(screenTargetLabel()), o.value("fill").toBool());
impl_->screenFitClient = impl_->screenFitImage = QSize();
+ if (gameMode()) { updateGameGeometry(); updateGameMode(); emit gameModeChanged(); }
+ emit compareChanged();
rememberSource(QStringLiteral("screen"), screenTargetLabel());
return true;
}
bool QmlPlayerBridge::gameMode() const { return impl_->gameModeSessionId != 0; }
bool QmlPlayerBridge::passthroughActive() const { return impl_->passthroughShown; }
+bool QmlPlayerBridge::gameInputActive() const { return impl_->gameInputShown; }
+bool QmlPlayerBridge::gameScaledPreview() const {
+ return gameMode() && ui::gameViewportScaled(impl_->screenFillActive, impl_->aspectMode);
+}
QRectF QmlPlayerBridge::gameVideoRect() const { return impl_->gameVideoRect; }
void QmlPlayerBridge::attachMainWindow(qulonglong nativeHandle) {
impl_->game.attach(reinterpret_cast<HWND>(nativeHandle));
@@ -2809,7 +2832,14 @@ void QmlPlayerBridge::attachMainWindow(qulonglong nativeHandle) {
}
void QmlPlayerBridge::updateGameGeometry() {
if (!gameMode() || !impl_->presentation.fullscreen || !impl_->gameWindow) return;
- const RECT r=impl_->game.pictureBounds();
+ RECT r=impl_->game.pictureBounds();
+ if (gameScaledPreview()) {
+ const HWND main = reinterpret_cast<HWND>(impl_->gameWindow->winId());
+ POINT origin{};
+ MONITORINFO info{sizeof(info)};
+ if (!GetMonitorInfoW(impl_->gameMonitor, &info) || !ClientToScreen(main, &origin)) return;
+ r=info.rcMonitor; OffsetRect(&r,-origin.x,-origin.y);
+ }
const qreal scale=impl_->gameWindow->devicePixelRatio();
if (scale<=0) return;
const QRectF rect(r.left/scale,r.top/scale,(r.right-r.left)/scale,(r.bottom-r.top)/scale);
@@ -2845,13 +2875,15 @@ void QmlPlayerBridge::updateGameMode() {
if (i.gameModeSessionId) {
const bool same = s.sessionId == i.gameModeSessionId;
if (same && s.running && !s.failed) i.gameModeLive = true;
- const bool ended = (same && (s.failed || (i.gameModeLive && !s.running))) || s.sessionId > i.gameModeSessionId;
+ const bool ended = (same && (s.failed || s.transport == engine::TransportState::Stopping ||
+ s.transport == engine::TransportState::Empty || (i.gameModeLive && !s.running))) || s.sessionId > i.gameModeSessionId;
if (ended) {
const bool shown = i.game.mode() != Mode::Off;
veyra::log::info("game-mode", std::format("capture session {} ended failed={} pictureInFront={}", i.gameModeSessionId, s.failed, shown));
i.gameModeSessionId = 0; i.gameModeLive = false;
if (shown) {
- if (i.passthroughShown) { i.passthroughShown = false; emit gameModeChanged(); }
+ i.gameInputShown = i.passthroughShown = false;
+ emit gameModeChanged();
i.game.apply(Mode::Off);
const QString why = s.failed ? uiText(s.status) : QString();
emit gameModeStopped(why.isEmpty() ? tr("捕获已结束,已退出游戏模式") : why);
@@ -2859,9 +2891,8 @@ void QmlPlayerBridge::updateGameMode() {
}
}
if (!i.presentation.fullscreen) i.gameRefused = false;
- Mode want = Mode::Off;
- if (i.gameModeSessionId && i.gameModeLive && i.presentation.fullscreen && !i.gameRefused)
- want = i.gamePanelOpen ? Mode::Panel : Mode::Through;
+ Mode want = ui::gameInputMode(i.gameModeSessionId != 0, i.presentation.fullscreen,
+ i.gameRefused, i.gamePanelOpen, gameScaledPreview());
if (want!=Mode::Off && i.gameVideoRect.isEmpty()) updateGameGeometry();
// A listener failure holds until fullscreen is left.
if (want != Mode::Off && i.game.mode() == Mode::Off && !i.game.arm()) { i.gameRefused = true; want = Mode::Off; }
@@ -2869,7 +2900,12 @@ void QmlPlayerBridge::updateGameMode() {
// QML binds the window's click-through flags to passthroughActive: publish
// first, so Qt has changed the window before the foreground moves.
const bool through = want == Mode::Through;
- if (through != i.passthroughShown) { i.passthroughShown = through; emit gameModeChanged(); }
+ const bool input = through || want == Mode::Scaled;
+ if (through != i.passthroughShown || input != i.gameInputShown) {
+ i.passthroughShown = through; i.gameInputShown = input; emit gameModeChanged();
+ }
+ if (want == Mode::Scaled && i.game.mode() != Mode::Panel)
+ emit notice(tr("全屏缩放已启用:键盘和手柄控制源窗口,鼠标点击已拦截以免错位;需要鼠标穿透时切回贴合原窗口"), false);
i.game.apply(want);
}
const bool mode = i.gameModeSessionId != 0;
@@ -6585,6 +6621,16 @@ void QmlPlayerBridge::openReleasesPage() {
QObject* QmlPlayerBridge::updates() const { return updates_; }
bool QmlPlayerBridge::eventFilter(QObject* watched, QEvent* event) {
const auto type = event->type();
+ if (watched == impl_->gameWindow && (type == QEvent::WinIdChange ||
+ (type == QEvent::PlatformSurface && static_cast<QPlatformSurfaceEvent*>(event)->surfaceEventType() ==
+ QPlatformSurfaceEvent::SurfaceCreated))) {
+ // Rebind after Qt's platform-window transition, never during teardown.
+ QMetaObject::invokeMethod(this, [this] {
+ if (!impl_->gameWindow || !impl_->gameWindow->handle()) return;
+ impl_->game.attach(reinterpret_cast<HWND>(impl_->gameWindow->winId()));
+ updateGameGeometry(); updateGameMode();
+ }, Qt::QueuedConnection);
+ }
if (type == QEvent::KeyPress || type == QEvent::KeyRelease) {
auto* key = static_cast<QKeyEvent*>(event);
if (!key->isAutoRepeat() && qobject_cast<QWindow*>(watched)) {
@@ -7876,7 +7922,7 @@ void QmlPlayerBridge::setPresentationFullscreen(bool value) {
else updateGameMode();
}
double QmlPlayerBridge::previewAspect() const {
- const int mode=gameMode()&&impl_->presentation.fullscreen?0:impl_->screenFillActive?2:impl_->aspectMode;
+ const int mode=impl_->screenFillActive?2:impl_->aspectMode;
if(mode==4)return 16.0/9;if(mode==5)return 4.0/3;if(mode==6)return 21.0/9;
const auto e=impl_->snapshot.metrics.resolution.output;
if(mode==1&&e.height){
@@ -7980,28 +8026,30 @@ void QmlPlayerBridge::setCompareSplitAt(double fx) {
if (!i.holdKeyDown) i.engine.comparison(i.compareMode, i.compareBase, float(i.compareSplit));
emit compareChanged();
}
-int QmlPlayerBridge::aspectMode() const { return impl_->aspectMode; }
+int QmlPlayerBridge::aspectMode() const { return impl_->screenFillActive ? 2 : impl_->aspectMode; }
void QmlPlayerBridge::setAspectMode(int value) {
- if (value < 0 || value > 6 || impl_->aspectMode == value) return;
+ if (value < 0 || value > 6 || (impl_->aspectMode == value && !impl_->screenFillActive)) return;
impl_->aspectMode = value;
+ impl_->screenFillActive = false;
impl_->prefs[QStringLiteral("aspect")] = value;
if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "aspect mode not saved");
applyAspect(true);
+ if (gameMode()) { updateGameGeometry(); updateGameMode(); emit gameModeChanged(); }
emit compareChanged();
}
void QmlPlayerBridge::applyAspect(bool force) {
auto& i = *impl_;
- const bool aligned=gameMode()&&i.presentation.fullscreen;
- const int mode = aligned ? 0 : i.screenFillActive ? 2 : i.aspectMode;
+ const bool aligned=gameMode()&&i.presentation.fullscreen&&!gameScaledPreview();
+ const int mode = i.screenFillActive ? 2 : i.aspectMode;
if (!i.videoWindow) return;
RECT r{}; GetClientRect(i.videoWindow, &r);
const auto e = i.snapshot.metrics.resolution.output;
const QSize client(r.right, r.bottom), image(int(e.width), int(e.height));
- if (!force && mode == i.aspectApplied && client == i.screenFitClient && image == i.screenFitImage) return;
- i.screenFitClient = client; i.screenFitImage = image; i.aspectApplied = mode;
+ const double dar=sourceAspect();
+ if (!force && mode == i.aspectApplied && client == i.screenFitClient && image == i.screenFitImage && dar == i.screenFitAspect) return;
+ i.screenFitClient = client; i.screenFitImage = image; i.aspectApplied = mode; i.screenFitAspect = dar;
auto view=force||aligned?engine::PreviewView{}:i.engine.previewView();
view.mode=mode;
- const double dar=sourceAspect();
view.displayAspect=dar>0&&image.height()>0&&std::abs(dar-double(image.width())/image.height())>.001?dar:0;
i.engine.previewView(view);
veyra::log::info("ui-aspect", std::format("mode={} zoom={:.3f} dar={:.4f} client={}x{} image={}x{}",mode,view.zoom,dar,
diff --git a/tests/integration/GamePassthroughTests.cpp b/tests/integration/GamePassthroughTests.cpp
index 34253ea7..7ba8c1cb 100644
--- a/tests/integration/GamePassthroughTests.cpp
+++ b/tests/integration/GamePassthroughTests.cpp
@@ -1,5 +1,6 @@
#include "veyra/ui/GamePassthrough.h"
-#include <QCoreApplication>
+#include <QGuiApplication>
+#include <QQuickWindow>
#include <iostream>
using namespace veyra::ui;
@@ -12,7 +13,7 @@ LRESULT CALLBACK proc(HWND w,UINT m,WPARAM wp,LPARAM lp){
std::cout<<"EVENT action="<<wp<<" epoch="<<lp<<" current="<<current<<" panels="<<panels<<" exits="<<exits<<std::endl;return 0;}
return DefWindowProcW(w,m,wp,lp);
}
-void pump(unsigned ms){const auto end=GetTickCount64()+ms;do{MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}Sleep(1);}while(GetTickCount64()<end);}
+void pump(unsigned ms){const auto end=GetTickCount64()+ms;do{QCoreApplication::processEvents();MSG m;while(PeekMessageW(&m,nullptr,0,0,PM_REMOVE)){TranslateMessage(&m);DispatchMessageW(&m);}Sleep(1);}while(GetTickCount64()<end);}
bool key(WORD vk,bool up=false){INPUT i{};i.type=INPUT_KEYBOARD;i.ki.wVk=vk;i.ki.dwFlags=up?KEYEVENTF_KEYUP:0;return SendInput(1,&i,sizeof(i))==1;}
bool send(std::initializer_list<std::pair<WORD,bool>> keys){
// Do not block the receiving window's message pump inside SendInput. In
@@ -22,9 +23,65 @@ bool send(std::initializer_list<std::pair<WORD,bool>> keys){
while(!done.load())pump(1);sender.join();pump(20);return ok;
}
void tap(WORD vk){check(send({{vk,false},{vk,true}}),"SendInput reaches our test foreground");pump(80);}
+void quickWindowSequence(HWND target){
+ QQuickWindow host;
+ host.setGeometry(0,0,960,600);
+ host.show();pump(100);
+ GamePassthrough game;
+ game.attach(reinterpret_cast<HWND>(host.winId()));
+ game.setTarget(target,MonitorFromWindow(target,MONITOR_DEFAULTTONEAREST),false);
+ game.setHotkeys({VK_F9,0},{VK_F10,3});
+ int panelEvents=0,exitEvents=0;
+ const auto apply=[&](GameInputMode mode){
+ Qt::WindowFlags flags=Qt::Window|Qt::FramelessWindowHint;
+ if(mode==GameInputMode::Through)flags|=Qt::WindowTransparentForInput;
+ if(mode==GameInputMode::Through||mode==GameInputMode::Scaled)flags|=Qt::WindowDoesNotAcceptFocus;
+ host.setFlags(flags);
+ if(mode==GameInputMode::Off)host.showNormal();else host.showFullScreen();
+ game.attach(reinterpret_cast<HWND>(host.winId()));
+ game.apply(mode);
+ };
+ game.onEvent=[&](GamePassthrough::Event event){
+ if(event==GamePassthrough::Event::PanelHotkey){
+ ++panelEvents;apply(game.mode()==GameInputMode::Panel?GameInputMode::Through:GameInputMode::Panel);
+ }else if(event==GamePassthrough::Event::ExitHotkey){++exitEvents;apply(GameInputMode::Off);}
+ else {check(false,"quick window listener remains available");apply(GameInputMode::Off);}
+ };
+ ShowWindow(target,SW_SHOW);
+ check(game.arm(),"message-only receiver arms before fullscreen flag changes");
+ apply(GameInputMode::Through);pump(100);
+ check(GetForegroundWindow()==target,"Qt fullscreen gives foreground to capture target");
+ for(int i=0;i<3;++i){
+ tap(VK_F9);
+ check(game.mode()==GameInputMode::Panel,"fullscreen hotkey restores interactive panel");
+ SetWindowPos(target,nullptr,420,300,720+i*20,400+i*30,SWP_NOACTIVATE|SWP_NOZORDER);
+ const auto geometry=game.pictureBounds();RECT source{};
+ DwmGetWindowAttribute(target,DWMWA_EXTENDED_FRAME_BOUNDS,&source,sizeof(source));
+ check(geometry.right-geometry.left==source.right-source.left&&geometry.bottom-geometry.top==source.bottom-source.top,
+ "source resize is reflected while passthrough is paused");
+ tap(VK_F9);
+ check(game.mode()==GameInputMode::Through,"panel closes back into passthrough");
+ }
+ check(panelEvents==6,"Qt flag transitions preserve all panel hotkey events");
+ apply(GameInputMode::Scaled);pump(80);
+ const auto scaledStyle=GetWindowLongPtrW(reinterpret_cast<HWND>(host.winId()),GWL_EXSTYLE);
+ check(!(scaledStyle&WS_EX_TRANSPARENT)&&(scaledStyle&WS_EX_NOACTIVATE)&&GetForegroundWindow()==target,
+ "scaled output keeps keyboard/gamepad foreground and blocks incorrect mouse passthrough");
+ // Force a platform-window replacement rather than assuming this Qt backend
+ // always replaces its HWND for an input-flag change.
+ host.destroy();host.create();
+ apply(GameInputMode::Through);pump(100);
+ check(send({{VK_LCONTROL,false},{VK_LMENU,false},{VK_F10,false},{VK_F10,true},{VK_LMENU,true},{VK_LCONTROL,true}}),
+ "exit chord reaches listener after platform-window replacement");pump(100);
+ const auto restoredStyle=GetWindowLongPtrW(reinterpret_cast<HWND>(host.winId()),GWL_EXSTYLE);
+ check(exitEvents==1&&game.mode()==GameInputMode::Off&&!(restoredStyle&(WS_EX_TRANSPARENT|WS_EX_NOACTIVATE)),
+ "exit restores real native input styles after fullscreen and handle changes");
+ game.onEvent={};game.apply(GameInputMode::Off);host.hide();
+}
}
int main(int argc,char** argv){
- QCoreApplication app(argc,argv);
+ QQuickWindow::setGraphicsApi(QSGRendererInterface::Software);
+ QGuiApplication app(argc,argv);
check(gameKey(QKeySequence("Home"))==GameKey{VK_HOME,0},"default panel maps to Home");
check(gameKey(QKeySequence("Ctrl+Alt+Home"))==GameKey{VK_HOME,3},"default exit maps to Ctrl Alt Home");
for(const auto* invalid:{"Ctrl", "Meta+F9", "F9, F10", "UnknownKey", "Ctrl++"})check(gameKey(QKeySequence(invalid)).vk==0,"unsupported bindings cannot arm listener");
@@ -78,6 +135,7 @@ int main(int argc,char** argv){
hook.stop();tap(VK_F9);check(panels==3&&!hook.running(),"stopped listener does not consume or trigger keys");
check(hook.start(window),"listener can reenter after exit");hook.panelOwned(true);tap(VK_F9);check(panels==4,"new session responds to custom key");hook.stop();
}
- listener=nullptr;DestroyWindow(target);DestroyWindow(window);if(IsWindow(previous))SetForegroundWindow(previous);
+ listener=nullptr;quickWindowSequence(target);
+ DestroyWindow(target);DestroyWindow(window);if(IsWindow(previous))SetForegroundWindow(previous);
std::cout<<"TOTAL failures="<<failures<<std::endl;return failures?1:0;
}
diff --git a/tests/integration/ScreenCaptureTests.cpp b/tests/integration/ScreenCaptureTests.cpp
index c3f69960..eb38f5c7 100644
--- a/tests/integration/ScreenCaptureTests.cpp
+++ b/tests/integration/ScreenCaptureTests.cpp
@@ -74,6 +74,15 @@ int wmain(int argc,wchar_t** argv){
SetWindowPos(child.window,nullptr,40,40,820,510,SWP_NOZORDER);end=GetTickCount64()+3000;bool resized=false;
while(GetTickCount64()<end&&next(source,p,&f)){if(f->width>660){resized=true;break;}}
check(resized&&unsigned(f->width)==source.info().width,"resize updates dimensions");check(content(ctx,ring,source,p,f),"resize retains RGB content");
+ check(resized&&std::abs(source.info().displayAspect-double(f->width)/f->height)<1e-9,"resize updates source display aspect");
+ SetWindowPos(child.window,nullptr,40,40,460,720,SWP_NOZORDER);end=GetTickCount64()+4000;resized=false;
+ while(GetTickCount64()<end&&next(source,p,&f)){
+ if(f->height>f->width){resized=true;break;}
+ }
+ check(resized&&pipeline::hasFrameFlag(p.flags,pipeline::FrameFlagBits::Resize)&&
+ std::abs(source.info().displayAspect-double(f->width)/f->height)<1e-9,
+ "portrait resize publishes new DAR and temporal reset flag together");
+ check(resized&&content(ctx,ring,source,p,f),"portrait resize retains actual RGB content");
source.close();options.left=30;options.right=30;options.top=20;options.bottom=20;desc.path=options.uri();check(source.open(desc)&&next(source,p,&f)&&f->width<820,"cropped source opens");source.close();
options.left=options.right=options.top=options.bottom=0;
options.fps=0;check(source::ScreenCaptureOptions::parse(options.uri(),parsed)&&parsed.fps==0,"automatic rate URI round trip");
@@ -88,6 +97,16 @@ int wmain(int argc,wchar_t** argv){
HWND host=CreateWindowW(L"STATIC",L"Screen engine test",WS_OVERLAPPEDWINDOW|WS_VISIBLE,880,40,720,480,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
SetWindowDisplayAffinity(host,WDA_EXCLUDEFROMCAPTURE);engine::EngineController engine;engine::PlayerOptions settings;settings.nr=true;settings.fg=true;settings.fgMultiplier=4;engine.open(host,options.uri(),settings);
end=GetTickCount64()+20000;while(GetTickCount64()<end){pump();Sleep(10);}auto snapshot=engine.snapshot();check(snapshot.running&&!snapshot.failed&&snapshot.frames>100&&snapshot.generated>100&&snapshot.nrEvaluated>100,"screen NR and DLSS4x actual evaluation");std::wcout<<L"ENGINE "<<snapshot.status<<L" frames="<<snapshot.frames<<L" generated="<<snapshot.generated<<L" nr="<<snapshot.nrEvaluated<<std::endl;
+ const auto framesBeforeResize=snapshot.frames;
+ SetWindowPos(child.window,nullptr,40,40,820,510,SWP_NOZORDER);
+ end=GetTickCount64()+10000;bool engineResized=false;
+ while(GetTickCount64()<end){
+ pump();Sleep(10);snapshot=engine.snapshot();
+ if(snapshot.sourceWidth>snapshot.sourceHeight&&snapshot.sourceWidth>700&&snapshot.frames>framesBeforeResize+5){engineResized=true;break;}
+ if(snapshot.failed)break;
+ }
+ check(engineResized&&std::abs(snapshot.sourceDisplayAspect-double(snapshot.sourceWidth)/snapshot.sourceHeight)<1e-9,
+ "engine window resize refreshes UI dimensions and DAR while frames advance");
engine.stop();end=GetTickCount64()+10000;while(!engine.idle()&&GetTickCount64()<end){pump();Sleep(10);}check(engine.idle(),"engine stop drains");DestroyWindow(host);
}
HWND excluded=CreateWindowW(L"STATIC",L"Screen exclusion test",WS_OVERLAPPEDWINDOW|WS_VISIBLE,880,40,200,160,nullptr,nullptr,GetModuleHandleW(nullptr),nullptr);
diff --git a/tests/unit/GameModePolicyTests.cpp b/tests/unit/GameModePolicyTests.cpp
new file mode 100644
index 00000000..b27394f5
--- /dev/null
+++ b/tests/unit/GameModePolicyTests.cpp
@@ -0,0 +1,49 @@
+#include "veyra/ui/GameModePolicy.h"
+#include "veyra/engine/PreviewView.h"
+#include <cmath>
+#include <iostream>
+
+int main() {
+ using namespace veyra::ui;
+ int failures = 0, checks = 0;
+ const auto check = [&](bool ok, const char* text) {
+ ++checks;
+ if (!ok) { ++failures; std::cerr << "FAIL " << text << '\n'; }
+ };
+ // This matrix includes opening (no first video frame yet), all exit paths,
+ // panel takeover, and the two different input contracts for scaled output.
+ for (bool session : {false, true})
+ for (bool fullscreen : {false, true})
+ for (bool refused : {false, true})
+ for (bool panel : {false, true})
+ for (bool scaled : {false, true}) {
+ const auto mode = gameInputMode(session, fullscreen, refused, panel, scaled);
+ if (!session || !fullscreen || refused)
+ check(mode == GameInputMode::Off, "exit/failure always restores input");
+ else if (panel)
+ check(mode == GameInputMode::Panel, "panel owns input regardless of scale");
+ else
+ check(mode == (scaled ? GameInputMode::Scaled : GameInputMode::Through),
+ "opening can take over without waiting for enhancement startup");
+ }
+ check(!gameViewportScaled(false, 0), "default keeps exact source coordinates");
+ check(gameViewportScaled(true, 0), "dialog fill enables fullscreen viewport");
+ for (int mode = 1; mode <= 6; ++mode)
+ check(gameViewportScaled(false, mode), "explicit transforms cannot use absolute mouse passthrough");
+
+ veyra::engine::PreviewView view;
+ view.mode = 3;
+ const auto stretched = view.renderedSize(1920, 1080, 800, 600);
+ check(stretched.first == 1920 && stretched.second == 1080, "stretch fills both monitor dimensions");
+ const auto corner = view.sourcePoint(1920, 1080, 1920, 1080, 800, 600);
+ check(corner.first == 1 && corner.second == 1, "stretch retains the bottom-right source corner");
+ view.mode = 2;
+ const auto filled = view.renderedSize(1920, 1080, 800, 600);
+ check(filled.first >= 1920 && filled.second >= 1080, "fill covers the monitor and may crop");
+ view.mode = 0;
+ const auto portrait = view.renderedSize(1920, 1080, 600, 900);
+ check(std::abs(portrait.first - 720) < .01 && portrait.second == 1080,
+ "portrait source fits with the resized aspect rather than the opening aspect");
+ std::cout << "Game mode policy: " << checks << " checks, " << failures << " failures\n";
+ return failures ? 1 : 0;
+}