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++

fg-gpu-home: PC 游戏模式 (click-through screen capture); borderless monitor capture

Veyra Goal Agent0f1b5de2e92d
diff --git a/apps/veyra-qml/main.cpp b/apps/veyra-qml/main.cpp
index b5f3ff2a..52c78683 100644
--- a/apps/veyra-qml/main.cpp
+++ b/apps/veyra-qml/main.cpp
@@ -767,6 +767,7 @@ static int runApplication(int argc, char** argv, QString& restartProgram, QStrin
return 1;
}
if (testSize.isValid()) window->resize(testSize);
+ bridge.attachMainWindow(static_cast<qulonglong>(window->winId()));
// Fullscreen must own the whole monitor. Without telling the shell, the taskbar
// stayed above the fullscreen picture on some systems (field report with the
diff --git a/i18n/catalog.json b/i18n/catalog.json
index fcce0ba9..e5a05f10 100644
--- a/i18n/catalog.json
+++ b/i18n/catalog.json
@@ -638,11 +638,11 @@
"ja": "DLSS フレーム生成"
},
{
- "zh": "DXGI 为显示器兼容方式,无鼠标指针",
+ "zh": "DXGI 为显示器兼容方式,无鼠标指针;捕获显示器时不显示黄色边框,Veyra 自己也不会出现在截图和录屏里",
"src": "qml/DialogHost.qml",
- "zh-TW": "DXGI 為顯示器相容方式,無滑鼠指標",
- "en": "DXGI is the display-compatible mode, without the mouse pointer",
- "ja": "DXGI はディスプレイ互換モードで、マウスポインターは映りません"
+ "zh-TW": "DXGI 為顯示器相容方式,無滑鼠指標;擷取顯示器時不顯示黃色邊框,Veyra 自己也不會出現在截圖和錄影裡",
+ "en": "DXGI is the display-compatible mode, without the mouse pointer. A display capture shows no yellow border, and Veyra itself stays out of screenshots and recordings",
+ "ja": "DXGI はディスプレイ互換モードで、マウスポインターは映りません。ディスプレイのキャプチャでは黄色い枠を表示せず、Veyra 自身もスクリーンショットや録画に映りません"
},
{
"zh": "Dolby / DTS 位流",
@@ -16024,6 +16024,97 @@
"zh-TW": "運算顯示卡已恢復預設(效能最強的顯示卡),重新開啟影片後生效",
"en": "Compute GPU back to the default (the most powerful GPU); it applies after reopening the video",
"ja": "処理用 GPU を既定(最も高性能な GPU)に戻しました。動画を開き直すと反映されます"
+ },
+ {
+ "zh": "Home 已被其它软件占用:游戏模式里不能用 Home 呼出调整面板,按 Ctrl+Alt+Home 退出后再调整",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "Home 已被其他軟體佔用:遊戲模式裡不能用 Home 叫出調整面板,按 Ctrl+Alt+Home 退出後再調整",
+ "en": "Another program has taken Home: in game mode Home cannot open the adjust panel; press Ctrl+Alt+Home to leave, then adjust",
+ "ja": "Home が他のソフトに使われています。ゲームモード中は Home で調整パネルを開けません。Ctrl+Alt+Home で終了してから調整してください"
+ },
+ {
+ "zh": "Ctrl+Alt+Home 已被其它软件占用,游戏模式不能穿透操作;关闭占用它的软件后重新全屏",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "Ctrl+Alt+Home 已被其他軟體佔用,遊戲模式不能穿透操作;關閉佔用它的軟體後重新全螢幕",
+ "en": "Another program has taken Ctrl+Alt+Home, so game mode cannot pass input through; close that program and go fullscreen again",
+ "ja": "Ctrl+Alt+Home が他のソフトに使われているため、ゲームモードで操作を通せません。そのソフトを閉じてから全画面にし直してください"
+ },
+ {
+ "zh": "界面卡住超过 3 秒,已退出游戏模式",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "介面卡住超過 3 秒,已退出遊戲模式",
+ "en": "The interface stopped responding for more than 3 s; game mode was left",
+ "ja": "画面が 3 秒以上応答しなかったため、ゲームモードを終了しました"
+ },
+ {
+ "zh": "捕获已结束,已退出游戏模式",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "擷取已結束,已退出遊戲模式",
+ "en": "The capture ended; game mode was left",
+ "ja": "キャプチャが終了したため、ゲームモードを終了しました"
+ },
+ {
+ "zh": "游戏模式用真实指针,画面里不再画一个",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "遊戲模式使用真實指標,畫面裡不再畫一個",
+ "en": "Game mode uses the real pointer, so the picture does not draw a second one",
+ "ja": "ゲームモードでは実際のポインターを使い、映像には描きません"
+ },
+ {
+ "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": "游戏",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "遊戲",
+ "en": "Game",
+ "ja": "ゲーム"
+ },
+ {
+ "zh": "游戏模式",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "遊戲模式",
+ "en": "Game mode",
+ "ja": "ゲームモード"
+ },
+ {
+ "zh": "开始后 Veyra 在这块屏幕上全屏,键鼠和手柄直接操作屏幕上的任何程序,就像直接用电脑;Home 调整画面,Ctrl+Alt+Home 退出",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "開始後 Veyra 在這塊螢幕上全螢幕,鍵鼠和手把直接操作螢幕上的任何程式,就像直接用電腦;Home 調整畫面,Ctrl+Alt+Home 退出",
+ "en": "Veyra goes fullscreen on this screen; keyboard, mouse and gamepad work every program on it as if you used the computer directly. Home adjusts the picture, Ctrl+Alt+Home leaves",
+ "ja": "開始すると Veyra がこの画面で全画面になり、キーボード・マウス・ゲームパッドで画面上のどのソフトもそのまま操作できます。Home で映像を調整、Ctrl+Alt+Home で終了"
+ },
+ {
+ "zh": "开始后 Veyra 在游戏所在的屏幕上全屏盖住游戏,键鼠和手柄照常操作游戏;Home 调整画面,Ctrl+Alt+Home 退出。游戏请设为无边框全屏",
+ "src": "qml/DialogHost.qml",
+ "zh-TW": "開始後 Veyra 在遊戲所在的螢幕上全螢幕蓋住遊戲,鍵鼠和手把照常操作遊戲;Home 調整畫面,Ctrl+Alt+Home 退出。遊戲請設為無邊框全螢幕",
+ "en": "Veyra goes fullscreen over the game on its screen; keyboard, mouse and gamepad still play the game. Home adjusts the picture, Ctrl+Alt+Home leaves. Set the game to borderless fullscreen",
+ "ja": "開始すると Veyra がゲームのある画面で全画面になってゲームを覆い、キーボード・マウス・ゲームパッドはそのままゲームを操作します。Home で映像を調整、Ctrl+Alt+Home で終了。ゲームはボーダーレス全画面にしてください"
+ },
+ {
+ "zh": "游戏模式:调整画面 / 退出",
+ "src": "qml/SettingsPage.qml",
+ "zh-TW": "遊戲模式:調整畫面 / 退出",
+ "en": "Game mode: adjust picture / leave",
+ "ja": "ゲームモード:映像を調整 / 終了"
+ },
+ {
+ "zh": "检测到独占全屏的游戏:Windows 不允许其它窗口盖在它上面,请把游戏改成无边框窗口或窗口化",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "偵測到獨佔全螢幕的遊戲:Windows 不允許其他視窗蓋在它上面,請把遊戲改成無邊框視窗或視窗化",
+ "en": "An exclusive-fullscreen game is running: Windows lets no other window cover it. Switch the game to borderless or windowed mode",
+ "ja": "排他的フルスクリーンのゲームを検出しました。Windows は他のウィンドウを重ねられません。ゲームをボーダーレスまたはウィンドウモードにしてください"
+ },
+ {
+ "zh": "游戏窗口没有铺满屏幕:画面会放大显示,鼠标点到的位置可能和看到的不一致;建议把游戏设为无边框全屏",
+ "src": "src/ui/QmlPlayerBridge.cpp",
+ "zh-TW": "遊戲視窗沒有鋪滿螢幕:畫面會放大顯示,滑鼠點到的位置可能和看到的不一致;建議把遊戲設為無邊框全螢幕",
+ "en": "The game window does not fill the screen: the picture is enlarged, so clicks may not land where you see them. Set the game to borderless fullscreen",
+ "ja": "ゲームのウィンドウが画面全体を覆っていません。映像が拡大されるため、クリック位置が見た位置とずれることがあります。ゲームをボーダーレス全画面にしてください"
}
]
}
diff --git a/include/veyra/source/ScreenCaptureSource.h b/include/veyra/source/ScreenCaptureSource.h
index 3793089a..9ef207cd 100644
--- a/include/veyra/source/ScreenCaptureSource.h
+++ b/include/veyra/source/ScreenCaptureSource.h
@@ -12,6 +12,9 @@ struct ScreenCaptureOptions {
uint64_t target=0;
unsigned fps=0; // 0 follows the captured target's display refresh rate
bool cursor=true;
+ // No yellow WGC capture border (Windows 11). Monitor captures always drop it;
+ // a window capture drops it in 游戏模式. Carried in the URI's cursor field (bit 1).
+ bool borderless=false;
unsigned left=0,top=0,right=0,bottom=0; // crop margins in source pixels
std::wstring uri() const;
static bool parse(const std::wstring&,ScreenCaptureOptions&);
@@ -24,6 +27,10 @@ struct ScreenCaptureTarget {
unsigned width=0,height=0,refresh=0;
};
struct ScreenCaptureMetrics {uint64_t received=0,delivered=0,dropped=0;double ageMs=0;};
+// While a monitor capture runs, Veyra's own windows are excluded from it. A window
+// shown after the capture opened (the control pill appears ~0.1 s later) is passed
+// here by the GUI thread before it becomes visible; outside a capture it is a no-op.
+void excludeWindowFromScreenCapture(void* window); // an HWND
class ScreenCaptureSource final:public IFrameSource {
public:
ScreenCaptureSource();~ScreenCaptureSource() override;
diff --git a/include/veyra/ui/GamePassthrough.h b/include/veyra/ui/GamePassthrough.h
new file mode 100644
index 00000000..f1c05c63
--- /dev/null
+++ b/include/veyra/ui/GamePassthrough.h
@@ -0,0 +1,359 @@
+#pragma once
+// 游戏模式 (屏幕捕获 → "游戏模式"): Veyra's fullscreen picture stays above what it
+// shows while that program keeps the foreground, so a game - or, for a monitor
+// 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
+// (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
+// visible Veyra window click-through too. Home, a system hotkey while the picture is
+// in front, opens the adjust panel and takes the input back; closing the panel hands
+// it to the program again. Ctrl+Alt+Home leaves. RegisterHotKey, not a low-level
+// keyboard hook: nothing else is listened to, and there is no hook thread.
+//
+// Everything is in-process on the GUI thread, so a crash takes the windows with it
+// and no click-through window can be left behind. A GUI thread that stops answering
+// for 3 s gets the picture cloaked by a watchdog thread, so the screen is never left
+// covered by a picture nobody can dismiss. The idea of the four styles comes from a
+// user's external VeyraOverlay tool (2026-10-09); this is an independent implementation.
+#include <QAbstractNativeEventFilter>
+#include <QByteArray>
+#include <windows.h>
+#include <dwmapi.h>
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <format>
+#include <functional>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <utility>
+#include <vector>
+#include "veyra/Log.h"
+#include "veyra/source/ScreenCaptureSource.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 };
+ enum class Event { PanelHotkey, ExitHotkey, HomeUnavailable, ExitUnavailable, HangReleased };
+ std::function<void(Event)> onEvent;
+
+ GamePassthrough() { s_instance = this; }
+ ~GamePassthrough() override {
+ stopWatchdog();
+ apply(Mode::Off);
+ if (s_instance == this) s_instance = nullptr;
+ }
+ GamePassthrough(const GamePassthrough&) = delete;
+ GamePassthrough& operator=(const GamePassthrough&) = delete;
+
+ void attach(HWND main) { main_ = main; }
+ // 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) {
+ target_ = window; monitor_ = monitor; monitorCapture_ = monitorCapture;
+ }
+ Mode mode() const { return mode_; }
+
+ // Entering from Off: the exit hotkey must exist before anything may become
+ // click-through. False (and ExitUnavailable) when another program owns it.
+ bool arm() {
+ if (!main_) return false;
+ if (exitRegistered_) return true;
+ exitRegistered_ = RegisterHotKey(main_, kExitId, MOD_CONTROL | MOD_ALT | MOD_NOREPEAT, VK_HOME) != 0;
+ if (!exitRegistered_) {
+ veyra::log::warn("game-mode", std::format("Ctrl+Alt+Home unavailable err={}; click-through refused", GetLastError()));
+ if (onEvent) onEvent(Event::ExitUnavailable);
+ return false;
+ }
+ return true;
+ }
+ // The caller publishes the new mode first, so Qt has applied (or removed) the
+ // main window's click-through flags before the foreground moves.
+ void apply(Mode next) {
+ if (!main_ || next == mode_) return;
+ const Mode previous = mode_;
+ if (next == Mode::Off) {
+ setTransparent(false);
+ noActivate(false);
+ sunk_ = false;
+ topmost(false);
+ setPanelHotkey(false);
+ if (exitRegistered_) { UnregisterHotKey(main_, kExitId); exitRegistered_ = false; }
+ if (hook_) { UnhookWinEvent(hook_); hook_ = nullptr; }
+ armed_.store(false);
+ mode_ = Mode::Off;
+ keepTaskbarButton();
+ focus(main_, "Veyra");
+ log("off");
+ return;
+ }
+ if (previous == Mode::Off) {
+ if (!arm()) return;
+ topmostBefore_ = (GetWindowLongPtrW(main_, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
+ hook_ = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, nullptr, &GamePassthrough::winEvent, 0, 0, WINEVENT_OUTOFCONTEXT);
+ panelWarned_ = false;
+ startWatchdog();
+ }
+ mode_ = next;
+ sunk_ = false;
+ topmost(true);
+ keepTaskbarButton();
+ if (next == Mode::Through) {
+ setTransparent(true);
+ noActivate(true);
+ focus(focusTarget(), "program");
+ } else {
+ setTransparent(false);
+ noActivate(false);
+ focus(main_, "Veyra");
+ }
+ updatePanelHotkey(GetForegroundWindow());
+ log(next == Mode::Through ? "click-through" : "panel");
+ }
+
+ // GUI thread, every 250 ms while the bridge runs.
+ void heartbeat() {
+ beat_.store(GetTickCount64());
+ if (cloaked_.exchange(false)) {
+ BOOL cloak = FALSE;
+ DwmSetWindowAttribute(main_, DWMWA_CLOAK, &cloak, sizeof cloak);
+ veyra::log::warn("game-mode", "GUI answering again: picture uncloaked, leaving game mode");
+ if (onEvent) onEvent(Event::HangReleased); // the bridge publishes Off, then calls apply(Off)
+ return;
+ }
+ // Something (Qt, another topmost program) may have taken the top back.
+ 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 {
+ if (type != "windows_generic_MSG") return false;
+ const auto* msg = static_cast<const MSG*>(message);
+ switch (msg->message) {
+ case WM_HOTKEY:
+ if (msg->wParam != kPanelId && msg->wParam != kExitId) return false;
+ if (onEvent) onEvent(msg->wParam == kPanelId ? Event::PanelHotkey : Event::ExitHotkey);
+ if (result) *result = 0;
+ return true;
+ case WM_SHOWWINDOW:
+ if (msg->wParam) shown(msg->hwnd);
+ return false;
+ case WM_WINDOWPOSCHANGING: {
+ const auto* pos = reinterpret_cast<const WINDOWPOS*>(msg->lParam);
+ if (pos && (pos->flags & SWP_SHOWWINDOW)) shown(msg->hwnd);
+ return false;
+ }
+ default:
+ return false;
+ }
+ }
+
+private:
+ static constexpr int kPanelId = 0x5647; // "VG"
+ static constexpr int kExitId = 0x5658; // "VX"
+ static constexpr ULONGLONG kHangMs = 3000;
+ static inline GamePassthrough* s_instance = nullptr;
+
+ HWND main_ = nullptr, target_ = nullptr;
+ HMONITOR monitor_ = nullptr;
+ bool monitorCapture_ = false;
+ Mode mode_ = Mode::Off;
+ bool exitRegistered_ = false, panelRegistered_ = false, panelWarned_ = false;
+ bool topmostBefore_ = false, sunk_ = false;
+ HWINEVENTHOOK hook_ = nullptr;
+ std::vector<std::pair<HWND, LONG_PTR>> changed_; // windows made click-through, with their original style
+
+ std::thread watchdog_;
+ std::mutex watchMutex_;
+ std::condition_variable watchWake_;
+ bool watchStop_ = false;
+ std::atomic<ULONGLONG> beat_{0};
+ std::atomic<bool> armed_{false}, cloaked_{false};
+
+ 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={} panelHotkey={} exitHotkey={}",
+ what, monitorCapture_, uint64_t(uintptr_t(target_)), uint64_t(ex), changed_.size(), panelRegistered_, exitRegistered_));
+ }
+ static bool ours(HWND w) {
+ DWORD pid = 0;
+ return w && GetWindowThreadProcessId(w, &pid) && pid == GetCurrentProcessId();
+ }
+ bool isTarget(HWND w) const {
+ if (!w || !target_) return false;
+ if (GetAncestor(w, GA_ROOT) == target_) return true;
+ DWORD a = 0, b = 0;
+ GetWindowThreadProcessId(w, &a); GetWindowThreadProcessId(target_, &b);
+ return a && a == b;
+ }
+ // The Start menu, Alt+Tab, the taskbar, notifications and the desktop come and
+ // go above or below everything; they never move the picture.
+ static bool shellSurface(HWND w) {
+ if (!w || w == GetShellWindow() || w == GetDesktopWindow()) return true;
+ if (GetWindowLongPtrW(w, GWL_EXSTYLE) & (WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE)) return true;
+ wchar_t name[64]{};
+ GetClassNameW(w, name, 64);
+ const std::wstring_view cls(name);
+ return cls == L"Progman" || cls == L"WorkerW" || cls == L"Shell_TrayWnd" || cls == L"Shell_SecondaryTrayWnd" ||
+ cls == L"Windows.UI.Core.CoreWindow" || cls == L"XamlExplorerHostIslandWindow" || cls == L"ForegroundStaging" ||
+ cls == L"MultitaskingViewFrame" || cls == L"TaskSwitcherWnd";
+ }
+ void topmost(bool on) {
+ const bool want = on || topmostBefore_;
+ SetWindowPos(main_, want ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+ }
+ // Qt::WindowDoesNotAcceptFocus stops Qt's own activation but does not set
+ // WS_EX_NOACTIVATE on this window; without it Veyra could still take the
+ // foreground from the game (a shell activation, a raise). Set after Qt's flags.
+ void noActivate(bool on) {
+ const LONG_PTR ex = GetWindowLongPtrW(main_, GWL_EXSTYLE);
+ if (on == ((ex & WS_EX_NOACTIVATE) != 0)) return;
+ SetWindowLongPtrW(main_, GWL_EXSTYLE, on ? ex | WS_EX_NOACTIVATE : ex & ~LONG_PTR(WS_EX_NOACTIVATE));
+ }
+ // A Qt flag change rebuilds the window style; the taskbar button's minimise
+ // bits (main.cpp, allowTaskbarMinimise) are put back as on a fullscreen switch.
+ void keepTaskbarButton() {
+ const LONG_PTR style = GetWindowLongPtrW(main_, GWL_STYLE);
+ if ((style & (WS_MINIMIZEBOX | WS_SYSMENU)) != (WS_MINIMIZEBOX | WS_SYSMENU))
+ SetWindowLongPtrW(main_, GWL_STYLE, style | WS_MINIMIZEBOX | WS_SYSMENU);
+ }
+ // Windows other than the main one (normally hidden while the picture is in
+ // front): only a layered window lets clicks through, so a plain one is layered
+ // here at full opacity and gets its exact style back afterwards.
+ void markTransparent(HWND w, bool requireVisible) {
+ if (w == main_ || !ours(w) || (requireVisible && !IsWindowVisible(w)) || (GetWindowLongPtrW(w, GWL_STYLE) & WS_CHILD)) return;
+ for (const auto& c : changed_) if (c.first == w) return;
+ const LONG_PTR ex = GetWindowLongPtrW(w, GWL_EXSTYLE);
+ changed_.emplace_back(w, ex);
+ SetWindowLongPtrW(w, GWL_EXSTYLE, ex | WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE);
+ if (!(ex & WS_EX_LAYERED) && !SetLayeredWindowAttributes(w, 0, 255, LWA_ALPHA))
+ veyra::log::warn("game-mode", std::format("layered attributes failed hwnd=0x{:X} err={}", uint64_t(uintptr_t(w)), GetLastError()));
+ }
+ void setTransparent(bool on) {
+ if (on) {
+ EnumWindows([](HWND w, LPARAM self) -> BOOL {
+ reinterpret_cast<GamePassthrough*>(self)->markTransparent(w, true);
+ return TRUE;
+ }, reinterpret_cast<LPARAM>(this));
+ return;
+ }
+ constexpr LONG_PTR bits = WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE;
+ for (const auto& [w, ex] : changed_)
+ if (IsWindow(w)) SetWindowLongPtrW(w, GWL_EXSTYLE, (GetWindowLongPtrW(w, GWL_EXSTYLE) & ~bits) | (ex & bits));
+ changed_.clear();
+ }
+ void shown(HWND w) {
+ if (GetWindowLongPtrW(w, GWL_STYLE) & WS_CHILD) return;
+ source::excludeWindowFromScreenCapture(w);
+ if (mode_ == Mode::Through) markTransparent(w, false);
+ }
+ // Window capture: the captured window. Monitor capture: the first ordinary window
+ // on that monitor in z-order (what the user was using before Veyra's dialog), else
+ // the desktop.
+ HWND focusTarget() const {
+ if (!monitorCapture_) return target_ && IsWindow(target_) ? target_ : nullptr;
+ struct Find { HMONITOR monitor; HWND hit; } find{monitor_, nullptr};
+ EnumWindows([](HWND w, LPARAM p) -> BOOL {
+ auto& f = *reinterpret_cast<Find*>(p);
+ if (ours(w) || !IsWindowVisible(w) || IsIconic(w) || shellSurface(w) || GetWindowTextLengthW(w) == 0) return TRUE;
+ DWORD cloaked = 0;
+ DwmGetWindowAttribute(w, DWMWA_CLOAKED, &cloaked, sizeof cloaked);
+ if (cloaked || MonitorFromWindow(w, MONITOR_DEFAULTTONULL) != f.monitor) return TRUE;
+ f.hit = w;
+ return FALSE;
+ }, reinterpret_cast<LPARAM>(&find));
+ return find.hit ? find.hit : GetShellWindow();
+ }
+ void focus(HWND w, const char* what) {
+ if (!w || !IsWindow(w)) return;
+ if (IsIconic(w)) ShowWindow(w, SW_RESTORE);
+ bool ok = SetForegroundWindow(w) && GetForegroundWindow() == w;
+ if (!ok) {
+ // Refused unless this thread owns the foreground: borrowing the
+ // foreground thread's input state lifts that.
+ const HWND fg = GetForegroundWindow();
+ const DWORD fgThread = fg ? GetWindowThreadProcessId(fg, nullptr) : 0, self = GetCurrentThreadId();
+ const bool attached = fgThread && fgThread != self && AttachThreadInput(fgThread, self, TRUE);
+ BringWindowToTop(w);
+ SetForegroundWindow(w);
+ if (attached) AttachThreadInput(fgThread, self, FALSE);
+ ok = GetForegroundWindow() == w;
+ }
+ veyra::log::info("game-mode", std::format("focus -> {} 0x{:X} ok={}", what, uint64_t(uintptr_t(w)), ok));
+ }
+ void setPanelHotkey(bool on) {
+ if (on == panelRegistered_) return;
+ if (!on) { UnregisterHotKey(main_, kPanelId); panelRegistered_ = false; return; }
+ panelRegistered_ = RegisterHotKey(main_, kPanelId, MOD_NOREPEAT, VK_HOME) != 0;
+ if (!panelRegistered_ && !panelWarned_) {
+ panelWarned_ = true;
+ veyra::log::warn("game-mode", std::format("Home unavailable err={}", GetLastError()));
+ if (onEvent) onEvent(Event::HomeUnavailable);
+ }
+ }
+ // Home belongs to Veyra while the user is "inside" the picture: the captured
+ // program (window capture) or anything on that monitor (monitor capture). In
+ // other programs it stays theirs.
+ void updatePanelHotkey(HWND fg) {
+ bool want = mode_ == Mode::Panel || ours(fg);
+ if (!want && mode_ == Mode::Through)
+ want = monitorCapture_ ? MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) == monitor_ : isTarget(fg);
+ setPanelHotkey(want);
+ }
+ static void CALLBACK winEvent(HWINEVENTHOOK, DWORD event, HWND hwnd, LONG object, LONG, DWORD, DWORD) {
+ if (event == EVENT_SYSTEM_FOREGROUND && object == OBJID_WINDOW && s_instance) s_instance->foregroundChanged(hwnd);
+ }
+ void foregroundChanged(HWND fg) {
+ if (mode_ == Mode::Off) return;
+ updatePanelHotkey(fg);
+ if (mode_ != Mode::Through || monitorCapture_ || ours(fg)) return;
+ if (isTarget(fg)) {
+ if (sunk_) { sunk_ = false; topmost(true); log("program back in front: picture on top"); }
+ return;
+ }
+ // Another program on this monitor came forward (Alt+Tab, a chat window): the
+ // picture steps behind it, still above the game, until the game is back.
+ if (sunk_ || shellSurface(fg) || MonitorFromWindow(fg, MONITOR_DEFAULTTONEAREST) != monitor_) return;
+ sunk_ = true;
+ const HWND front = GetAncestor(fg, GA_ROOT);
+ SetWindowPos(main_, front ? front : fg, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+ if (target_ && IsWindow(target_)) SetWindowPos(target_, main_, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
+ log("another program in front: picture behind it");
+ }
+ void startWatchdog() {
+ beat_.store(GetTickCount64());
+ armed_.store(true);
+ if (watchdog_.joinable()) return;
+ watchdog_ = std::thread([this] {
+ std::unique_lock lock(watchMutex_);
+ while (!watchStop_) {
+ watchWake_.wait_for(lock, std::chrono::milliseconds(250));
+ if (watchStop_) break;
+ if (!armed_.load() || cloaked_.load()) continue;
+ const ULONGLONG stale = GetTickCount64() - beat_.load();
+ 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);
+ cloaked_.store(SUCCEEDED(hr));
+ veyra::log::warn("game-mode", std::format("GUI silent for {} ms: picture cloaked hr=0x{:08X}", stale, unsigned(hr)));
+ }
+ });
+ }
+ void stopWatchdog() {
+ { std::lock_guard lock(watchMutex_); watchStop_ = true; }
+ watchWake_.notify_all();
+ if (watchdog_.joinable()) watchdog_.join();
+ }
+};
+
+} // namespace veyra::ui
diff --git a/include/veyra/ui/QmlPlayerBridge.h b/include/veyra/ui/QmlPlayerBridge.h
index 382270d9..75f4d196 100644
--- a/include/veyra/ui/QmlPlayerBridge.h
+++ b/include/veyra/ui/QmlPlayerBridge.h
@@ -151,6 +151,11 @@ class QmlPlayerBridge : public QObject {
// method 0 WGC / 1 DXGI (monitor only), fps cap index into {follow,30,60,120,144,240},
// pointer, crop margins in source pixels, and "fill the window".
Q_PROPERTY(QVariantMap screenOptions READ screenOptions NOTIFY captureChanged)
+ // 游戏模式 (screen option "passthrough", ui/GamePassthrough.h): gameMode while the
+ // current source is such a capture (opening or live); passthroughActive while the
+ // 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)
// Subtitles (P4-c): the engine's SubtitleLoader reads the embedded tracks and
// the same-name external file; the old shell's SubtitleOverlay draws them as a
@@ -626,6 +631,14 @@ public:
Q_INVOKABLE bool startCaptureSession();
Q_INVOKABLE bool setScreenOption(const QString& key, const QVariant& value);
Q_INVOKABLE bool startScreenCapture();
+ bool gameMode() const;
+ bool passthroughActive() const;
+ // The Home panel is open: the picture stays on top but takes the input back.
+ Q_INVOKABLE void setGamePanelOpen(bool open);
+ // Index into Qt.application.screens of the monitor 游戏模式 covers, or -1.
+ Q_INVOKABLE int gameModeScreenIndex() const;
+ // Test only (VEYRA_TEST_UI_BLOCK): blocks the GUI thread to exercise the hang release.
+ Q_INVOKABLE void testBlockUi(int ms);
QVariantList screenTargets() const;
QString screenTargetId() const;
@@ -1052,6 +1065,8 @@ public:
// window of the QML window and hands it over; the bridge never draws QML
// into it and Qt never touches its swapchain.
void attachVideoWindow(qulonglong nativeHandle);
+ // The QML main window: 游戏模式 changes its styles and owns its hotkeys.
+ void attachMainWindow(qulonglong nativeHandle);
// Run immediately before the engine opens a source. The presenter reads the
// host window's client size once, when it initialises, and builds the
@@ -1182,8 +1197,15 @@ signals:
void overlayRestartSuggested(const QString& kind);
// The UI moves to a page by name when a command implies it.
void navigate(const QString& page);
+ void gameModeChanged();
+ // 游戏模式 hotkeys: 0 = Home (adjust panel), 1 = Ctrl+Alt+Home (leave).
+ void gameHotkey(int which);
+ // The game-mode capture ended or failed, or the GUI hung, while the picture was in
+ // front: the UI leaves fullscreen and shows the reason.
+ void gameModeStopped(const QString& reason);
private:
+ void updateGameMode();
// The settings the UI is showing: the facade's pending copy, which the
// engine has been asked to apply. Every settings property reads this, so
// they can never disagree with each other.
diff --git a/qml/Veyra/DialogHost.qml b/qml/Veyra/DialogHost.qml
index 8a6f657e..27ca1f67 100644
--- a/qml/Veyra/DialogHost.qml
+++ b/qml/Veyra/DialogHost.qml
@@ -1185,11 +1185,25 @@ Item {
}
}
}
+ DSection { text: qsTr("游戏") }
+ DGroup {
+ VRow {
+ label: qsTr("游戏模式")
+ hint: screenDialog.o.kind === 1
+ ? qsTr("开始后 Veyra 在这块屏幕上全屏,键鼠和手柄直接操作屏幕上的任何程序,就像直接用电脑;Home 调整画面,Ctrl+Alt+Home 退出")
+ : qsTr("开始后 Veyra 在游戏所在的屏幕上全屏盖住游戏,键鼠和手柄照常操作游戏;Home 调整画面,Ctrl+Alt+Home 退出。游戏请设为无边框全屏")
+ VSwitch {
+ objectName: "screen-game-mode"
+ checked: screenDialog.o.passthrough === true
+ onToggled: checked => veyra.setScreenOption("passthrough", checked)
+ }
+ }
+ }
DSection { text: qsTr("采集") }
DGroup {
VRow {
label: qsTr("采集方式")
- hint: screenDialog.o.kind === 1 ? qsTr("DXGI 为显示器兼容方式,无鼠标指针") : qsTr("窗口只能用 Windows Graphics Capture")
+ hint: screenDialog.o.kind === 1 ? qsTr("DXGI 为显示器兼容方式,无鼠标指针;捕获显示器时不显示黄色边框,Veyra 自己也不会出现在截图和录屏里") : qsTr("窗口只能用 Windows Graphics Capture")
VSeg {
enabled: screenDialog.o.kind === 1
opacity: enabled ? 1 : 0.5
@@ -1208,17 +1222,21 @@ Item {
}
VRow {
label: qsTr("显示鼠标指针")
+ hint: screenDialog.o.passthrough === true ? qsTr("游戏模式用真实指针,画面里不再画一个") : ""
VSwitch {
- enabled: screenDialog.o.method === 0
- checked: screenDialog.o.cursor === true
+ enabled: screenDialog.o.method === 0 && screenDialog.o.passthrough !== true
+ opacity: enabled ? 1 : 0.5
+ checked: screenDialog.o.cursor === true && screenDialog.o.passthrough !== true
onToggled: checked => veyra.setScreenOption("cursor", checked)
}
}
VRow {
label: qsTr("裁剪(像素)")
- hint: qsTr("左 / 上 / 右 / 下,按源像素")
+ hint: screenDialog.o.passthrough === true ? qsTr("游戏模式不裁剪,画面和屏幕一一对应,点到哪里就是哪里") : qsTr("左 / 上 / 右 / 下,按源像素")
RowLayout {
spacing: 4
+ enabled: screenDialog.o.passthrough !== true
+ opacity: enabled ? 1 : 0.5
Repeater {
model: ["left", "top", "right", "bottom"]
delegate: VTextField {
diff --git a/qml/Veyra/Main.qml b/qml/Veyra/Main.qml
index b44d234e..7d4dd9a7 100644
--- a/qml/Veyra/Main.qml
+++ b/qml/Veyra/Main.qml
@@ -29,7 +29,10 @@ Window {
// The software scene graph cannot draw the Shape background. Keep the native
// window opaque as well, including while its first frame is being produced.
color: typeof vySoftwareUi !== "undefined" && vySoftwareUi ? (cinema ? Theme.videoBlack : Theme.bgOuter) : "transparent"
+ // 游戏模式 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)
title: "Veyra " + veyra.version
// Page ids match the prototype's PAGES keys so a design screenshot and an
@@ -300,7 +303,10 @@ Window {
onStartPs5: if (root.page === "home") root.goPage("min")
onStartMoonlight: if (root.page === "home") root.goPage("min")
onStartXbox: if (root.page === "home") root.goPage("min")
- onStartScreen: if (root.page === "home") root.goPage("min")
+ onStartScreen: {
+ if (root.page === "home") root.goPage("min")
+ if (veyra.screenOptions.passthrough === true) root.enterGameFullscreen()
+ }
}
// The dock floats above every page and retracts on its own.
@@ -403,7 +409,47 @@ Window {
quickPanel = false
if (quickReturnPage !== "") { const p = quickReturnPage; quickReturnPage = ""; switchPageInstantly(p) }
}
- onQuickPanelShownChanged: veyra.logUi("ui-fullscreen", "quick panel shown=" + quickPanelShown)
+ onQuickPanelShownChanged: {
+ veyra.logUi("ui-fullscreen", "quick panel shown=" + quickPanelShown)
+ veyra.setGamePanelOpen(quickPanelShown)
+ }
+ // 游戏模式 (屏幕捕获 → 游戏模式): fullscreen on the captured monitor (or the
+ // monitor of the captured window); the bridge then makes the picture click-through
+ // so the program underneath keeps the keyboard, mouse and gamepad.
+ function enterGameFullscreen() {
+ const i = veyra.gameModeScreenIndex()
+ const screens = Qt.application.screens
+ if (i >= 0 && i < screens.length) {
+ const s = screens[i]
+ const inside = x + width / 2 >= s.virtualX && x + width / 2 < s.virtualX + s.width &&
+ y + height / 2 >= s.virtualY && y + height / 2 < s.virtualY + s.height
+ if (!inside) {
+ if (fullscreen) toggleFullscreen()
+ x = s.virtualX + Math.max(0, Math.round((s.width - width) / 2))
+ y = s.virtualY + Math.max(0, Math.round((s.height - height) / 2))
+ }
+ }
+ if (!fullscreen) toggleFullscreen()
+ veyra.logUi("game-mode", "fullscreen for game mode on screen " + i)
+ }
+ Connections {
+ target: veyra
+ // 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 (!root.fullscreen) return
+ if (which === 1) { root.closeQuickPanel(); root.toggleFullscreen(); return }
+ root.fullLocked = false
+ root.toggleQuickPanel()
+ }
+ function onGameModeStopped(reason) {
+ if (root.fullscreen) root.toggleFullscreen()
+ toast.show(reason, true)
+ }
+ function onGameModeChanged() {
+ if (veyra.passthroughActive && playlistWindow.visible) playlistWindow.hide()
+ }
+ }
onFullscreenChanged: {
veyra.setPresentationFullscreen(fullscreen)
fullTarget = fullscreen
@@ -519,6 +565,8 @@ Window {
if (root.page !== "min" && root.page !== "pro" && root.page !== "node" && !root.fullscreen) return
if (dialogs.dialog !== "" || !veyra.hasSource) return
if (root.fullscreen && root.quickPanelShown && (proPage.overlayContains(p.x, p.y) || nodePage.overlayContains(p.x, p.y))) return
+ // 游戏模式: a click on the picture beside the panel returns to the game.
+ if (root.fullscreen && root.quickPanelShown && veyra.gameMode) { root.closeQuickPanel(); return }
if (!root.fullscreen && !root.pictureContains(p)) return
root.contentItem.forceActiveFocus()
if (veyra.isCapture || veyra.duration <= 0) return
@@ -588,7 +636,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 && (root.fullscreen ? root.fullControls && !root.fullLocked
+ shown: veyra.hasSource && !root.pillHidden && !veyra.passthroughActive && (root.fullscreen ? root.fullControls && !root.fullLocked
: root.cinema && root.shownPage === "min"
&& root.leavingPage === "" && dialogs.dialog === ""
&& root.visibility !== Window.Minimized)
@@ -629,7 +677,12 @@ Window {
onActivated: root.goPage(root.page === "min" ? "pro" : "min")
}
Shortcut { sequences: ["F11", "Alt+Return", "Alt+Enter"]; onActivated: root.toggleFullscreen() }
- Shortcut { sequence: "Esc"; enabled: root.fullscreen; onActivated: root.toggleFullscreen() }
+ // In 游戏模式 Esc closes the adjust panel and gives the input back to the game.
+ Shortcut {
+ sequence: "Esc"
+ enabled: root.fullscreen
+ onActivated: veyra.gameMode && root.quickPanelShown ? root.closeQuickPanel() : root.toggleFullscreen()
+ }
// Home: the fullscreen quick-adjust panel, from 极简 or 专业 (list or node view).
Shortcut {
sequence: "Home"
diff --git a/qml/Veyra/SettingsPage.qml b/qml/Veyra/SettingsPage.qml
index fe3cf6ae..6331b5e6 100644
--- a/qml/Veyra/SettingsPage.qml
+++ b/qml/Veyra/SettingsPage.qml
@@ -868,7 +868,8 @@ VPage {
{ a: qsTr("音量"), k: "↑ / ↓" },
{ a: qsTr("打开文件 / 导出页"), k: "Ctrl+O / Ctrl+E" },
{ a: qsTr("字幕开关 / 主轨 / 副轨"), k: "B / T / Y" },
- { a: qsTr("字幕延时 50 ms(Shift = 1 s)"), k: "Z / X" }
+ { a: qsTr("字幕延时 50 ms(Shift = 1 s)"), k: "Z / X" },
+ { a: qsTr("游戏模式:调整画面 / 退出"), k: "Home / Ctrl+Alt+Home" }
]
delegate: VRow {
required property var modelData
diff --git a/src/source/ScreenCaptureSource.cpp b/src/source/ScreenCaptureSource.cpp
index 042fbb49..10db1634 100644
--- a/src/source/ScreenCaptureSource.cpp
+++ b/src/source/ScreenCaptureSource.cpp
@@ -34,26 +34,41 @@ int64_t host100ns(){return std::chrono::duration_cast<std::chrono::nanoseconds>(
int64_t qpc100ns(){LARGE_INTEGER q{},f{};QueryPerformanceCounter(&q);QueryPerformanceFrequency(&f);return int64_t(static_cast<long double>(q.QuadPart)*10000000/f.QuadPart);}
void check(HRESULT hr,const char* op){if(FAILED(hr)){log::error("screen",std::format("{} hr=0x{:08X}",op,uint32_t(hr)));winrt::check_hresult(hr);}}
struct NativeHandle {HANDLE value=nullptr;~NativeHandle(){if(value)CloseHandle(value);}};
+// The list is shared with the GUI thread, which excludes windows shown during a
+// capture. This thread never calls a window function while holding the lock, so it
+// can never wait on a GUI thread that waits on the lock.
std::mutex exclusionMutex;
unsigned exclusionUsers=0;
std::vector<std::pair<HWND,DWORD>> excludedWindows;
+bool qtWindow(HWND w){wchar_t name[8]{};return GetClassNameW(w,name,8)>=2&&name[0]==L'Q'&&name[1]==L't';}
+bool listed(HWND w){for(const auto& entry:excludedWindows)if(entry.first==w)return true;return false;}
+bool exclude(HWND w,DWORD& previous){
+ if(GetWindowDisplayAffinity(w,&previous)&&SetWindowDisplayAffinity(w,WDA_EXCLUDEFROMCAPTURE))return true;
+ log::warn("screen",std::format("window exclusion failed hwnd={} error={}",uint64_t(w),GetLastError()));return false;
+}
void excludeOwnWindows(){
- std::lock_guard lock(exclusionMutex);
- if(exclusionUsers++!=0)return;
- EnumWindows([](HWND w,LPARAM)->BOOL{
+ {std::lock_guard lock(exclusionMutex);if(exclusionUsers++!=0)return;}
+ // Every visible window, and every Qt window even while hidden: the control
+ // pill is shown just after the capture opens and was captured into the
+ // picture. A window created later is excluded when it is shown.
+ std::vector<HWND> own;
+ EnumWindows([](HWND w,LPARAM list)->BOOL{
DWORD pid=0;GetWindowThreadProcessId(w,&pid);
- if(pid!=GetCurrentProcessId()||!IsWindowVisible(w))return TRUE;
- DWORD previous=0;
- if(GetWindowDisplayAffinity(w,&previous)&&SetWindowDisplayAffinity(w,WDA_EXCLUDEFROMCAPTURE))excludedWindows.emplace_back(w,previous);
- else log::warn("screen",std::format("window exclusion failed hwnd={} error={}",uint64_t(w),GetLastError()));
+ if(pid==GetCurrentProcessId()&&(IsWindowVisible(w)||qtWindow(w)))reinterpret_cast<std::vector<HWND>*>(list)->push_back(w);
return TRUE;
- },0);
+ },reinterpret_cast<LPARAM>(&own));
+ size_t count=0;
+ for(HWND w:own){
+ DWORD previous=0;if(!exclude(w,previous))continue;
+ std::lock_guard lock(exclusionMutex);
+ if(!listed(w)){excludedWindows.emplace_back(w,previous);++count;}
+ }
+ log::info("screen",std::format("own windows excluded from capture: {} of {}",count,own.size()));
}
void restoreOwnWindows(){
- std::lock_guard lock(exclusionMutex);
- if(!exclusionUsers||--exclusionUsers)return;
- for(auto [window,affinity]:excludedWindows)if(IsWindow(window)&&!SetWindowDisplayAffinity(window,affinity))log::warn("screen","window exclusion restore failed");
- excludedWindows.clear();
+ std::vector<std::pair<HWND,DWORD>> restore;
+ {std::lock_guard lock(exclusionMutex);if(!exclusionUsers||--exclusionUsers)return;restore.swap(excludedWindows);}
+ for(auto [window,affinity]:restore)if(IsWindow(window)&&!SetWindowDisplayAffinity(window,affinity))log::warn("screen","window exclusion restore failed");
}
struct Surface {
ComPtr<ID3D11Texture2D> producer;
@@ -99,17 +114,26 @@ bool hdrMonitor(HMONITOR monitor){
}return false;
}
}
+void excludeWindowFromScreenCapture(void* handle){
+ const auto window=static_cast<HWND>(handle);
+ if(!window||(GetWindowLongPtrW(window,GWL_STYLE)&WS_CHILD))return;
+ // GUI thread, on its own window: holding the lock across the call is safe here.
+ std::lock_guard lock(exclusionMutex);
+ if(!exclusionUsers||listed(window))return;
+ DWORD previous=0;
+ if(exclude(window,previous)){excludedWindows.emplace_back(window,previous);log::info("screen",std::format("late window excluded from capture hwnd={}",uint64_t(window)));}
+}
std::wstring ScreenCaptureOptions::uri()const{
- return std::format(L"screen:{}:{}:{}:{}:{}:{}:{}:{}:{}",unsigned(kind),target,unsigned(method),fps,unsigned(cursor),left,top,right,bottom);
+ return std::format(L"screen:{}:{}:{}:{}:{}:{}:{}:{}:{}",unsigned(kind),target,unsigned(method),fps,unsigned(cursor)|(borderless?2u:0u),left,top,right,bottom);
}
bool ScreenCaptureOptions::parse(const std::wstring& uri,ScreenCaptureOptions& out){
if(!uri.starts_with(L"screen:"))return false;
auto body=uri.substr(7);std::replace(body.begin(),body.end(),L':',L' ');
std::wistringstream in(body);unsigned kind=0,method=0,cursor=0;ScreenCaptureOptions v;
if(!(in>>kind>>v.target>>method>>v.fps>>cursor>>v.left>>v.top>>v.right>>v.bottom))return false;
- in>>std::ws;if(!in.eof()||kind>1||method>1||cursor>1||!v.target||v.fps>240||
+ in>>std::ws;if(!in.eof()||kind>1||method>1||cursor>3||!v.target||v.fps>240||
v.left>16384||v.top>16384||v.right>16384||v.bottom>16384||(!kind&&method))return false;
- v.kind=ScreenTargetKind(kind);v.method=ScreenCaptureMethod(method);v.cursor=cursor!=0;out=v;return true;
+ v.kind=ScreenTargetKind(kind);v.method=ScreenCaptureMethod(method);v.cursor=(cursor&1)!=0;v.borderless=(cursor&2)!=0;out=v;return true;
}
std::vector<ScreenCaptureTarget> ScreenCaptureSource::targets(ScreenTargetKind kind){
std::vector<ScreenCaptureTarget> result;
@@ -177,6 +201,21 @@ struct ScreenCaptureSource::Impl {
}return slot;
}return {};
}
+ // Windows 11 lets a desktop app turn the yellow capture border off after asking
+ // for borderless access (granted without a prompt outside the app store). Older
+ // systems keep the border; the capture itself is unaffected either way.
+ void dropBorder(){
+ try{
+ if(!winrt::Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent(L"Windows.Graphics.Capture.GraphicsCaptureSession",L"IsBorderRequired")){
+ log::info("screen","capture border: kept (this Windows has no IsBorderRequired)");return;
+ }
+ const auto access=GraphicsCaptureAccess::RequestAccessAsync(GraphicsCaptureAccessKind::Borderless).get();
+ session.IsBorderRequired(false);
+ log::info("screen",std::format("capture border: off access={} required={}",int(access),session.IsBorderRequired()));
+ }catch(const winrt::hresult_error& e){
+ log::warn("screen",std::format("capture border kept hr=0x{:08X} {}",uint32_t(e.code()),winrt::to_string(e.message())));
+ }
+ }
void startDuplication(){
ComPtr<IDXGIDevice> dxgi;check(device.As(&dxgi),"DXGI device");ComPtr<IDXGIAdapter> adapter;check(dxgi->GetAdapter(&adapter),"adapter");
for(UINT i=0;;++i){ComPtr<IDXGIOutput> output;const auto hr=adapter->EnumOutputs(i,&output);if(hr==DXGI_ERROR_NOT_FOUND)break;check(hr,"EnumOutputs");
@@ -218,7 +257,9 @@ bool ScreenCaptureSource::open(const SourceOpenDesc& desc){
ComPtr<IDXGIDevice> dxgi;check(device.As(&dxgi),"DXGI device");winrt::com_ptr<IInspectable> inspectable;
check(CreateDirect3D11DeviceFromDXGIDevice(dxgi.Get(),inspectable.put()),"WinRT device");p.wrapped=inspectable.as<winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice>();
p.poolSize=p.item.Size();p.pool=Direct3D11CaptureFramePool::CreateFreeThreaded(p.wrapped,DirectXPixelFormat(p.format),2,p.poolSize);
- p.session=p.pool.CreateCaptureSession(p.item);p.session.IsCursorCaptureEnabled(o.cursor);p.session.StartCapture();
+ p.session=p.pool.CreateCaptureSession(p.item);p.session.IsCursorCaptureEnabled(o.cursor);
+ if(o.borderless||o.kind==ScreenTargetKind::Monitor)p.dropBorder();
+ p.session.StartCapture();
}
if(p.poolSize.Width<=int(o.left+o.right)||p.poolSize.Height<=int(o.top+o.bottom))throw winrt::hresult_error(E_INVALIDARG,L"裁剪范围超出画面");
p.info.opened=true;p.info.kind=pipeline::SourceKind::ScreenCapture;p.info.width=p.poolSize.Width-o.left-o.right;p.info.height=p.poolSize.Height-o.top-o.bottom;p.info.displayAspect=(p.poolSize.Height-o.top-o.bottom)>0?double(p.poolSize.Width-o.left-o.right)/(p.poolSize.Height-o.top-o.bottom):0.0;
@@ -226,7 +267,7 @@ bool ScreenCaptureSource::open(const SourceOpenDesc& desc){
p.info.videoDecodePath=o.method==ScreenCaptureMethod::Wgc?"WGC shared GPU":"DXGI duplication shared GPU";
p.info.containerName="screen";p.info.videoCodecName="GPU RGB";p.info.videoPixelFormatName=p.hdr?"scRGB FP16":"BGRA8 sRGB";p.color();
p.clockOffset=host100ns()-qpc100ns();p.frame=av_frame_alloc();if(!p.frame)throw std::bad_alloc();
- log::info("screen",std::format("opened method={} target={} size={}x{} hdr={} fpsLimit={:.3f} followDisplay={} cursor={} pool=6 cpuReadback=0 audioCapture=0",unsigned(o.method),o.target,p.info.width,p.info.height,p.hdr,p.info.averageFps,o.fps==0,o.cursor));
+ log::info("screen",std::format("opened method={} target={} size={}x{} hdr={} fpsLimit={:.3f} followDisplay={} cursor={} borderless={} pool=6 cpuReadback=0 audioCapture=0",unsigned(o.method),o.target,p.info.width,p.info.height,p.hdr,p.info.averageFps,o.fps==0,o.cursor,o.borderless||o.kind==ScreenTargetKind::Monitor));
return true;
}catch(const winrt::hresult_error& e){p.message=std::format(L"屏幕采集失败 0x{:08X}:{}",uint32_t(e.code()),e.message().c_str());log::error("screen",winrt::to_string(p.message));}
catch(const std::exception& e){p.message=L"屏幕采集资源分配失败";log::error("screen",e.what());}
diff --git a/src/ui/QmlPlayerBridge.cpp b/src/ui/QmlPlayerBridge.cpp
index 5f9bc9d0..9a0fecc8 100644
--- a/src/ui/QmlPlayerBridge.cpp
+++ b/src/ui/QmlPlayerBridge.cpp
@@ -3,6 +3,11 @@
#include "veyra/gfx/NvidiaVrr.h"
#include "veyra/ngx/DlssgLite.h"
#include "veyra/RuntimePaths.h"
+#include "veyra/ui/GamePassthrough.h"
+#include <QGuiApplication>
+#include <QScreen>
+#include <QtGui/qscreen_platform.h>
+#include <shellapi.h>
#include <QElapsedTimer>
#include "veyra/ui/EffectAvailability.h"
#include "veyra/engine/FrameGenerationSelection.h"
@@ -450,6 +455,13 @@ struct QmlPlayerBridge::Impl {
id.toStdString(), uint32_t(d.AdapterLuid.HighPart), d.AdapterLuid.LowPart, d.DedicatedVideoMemory >> 20));
}
}
+ // 游戏模式: the native side, the capture it belongs to and what the UI reported.
+ ui::GamePassthrough game;
+ 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;
+ HMONITOR gameMonitor = nullptr;
// The monitored GPU also computes when 设置 -> "同时用这块显卡运算" is on
// and a specific GPU (not 自动) is chosen; otherwise the default order.
QString computeGpuName;
@@ -1133,6 +1145,30 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
impl_->engine.setFullscreenMemoryProtection(impl_->prefBool("fullscreenMemoryProtection",false));
connect(&impl_->exportQueue,&QmlExportQueueModel::changed,this,&QmlPlayerBridge::exportChanged);
if (qApp) qApp->installEventFilter(this);
+ // 游戏模式. The native filter also keeps windows shown during a monitor capture
+ // out of that capture, so it is installed for every run.
+ if (qApp) qApp->installNativeEventFilter(&impl_->game);
+ impl_->game.onEvent = [this](ui::GamePassthrough::Event event) {
+ using E = ui::GamePassthrough::Event;
+ switch (event) {
+ case E::PanelHotkey: emit gameHotkey(0); break;
+ case E::ExitHotkey: emit gameHotkey(1); break;
+ case E::HomeUnavailable:
+ emit notice(tr("Home 已被其它软件占用:游戏模式里不能用 Home 呼出调整面板,按 Ctrl+Alt+Home 退出后再调整"), true); break;
+ case E::ExitUnavailable:
+ emit notice(tr("Ctrl+Alt+Home 已被其它软件占用,游戏模式不能穿透操作;关闭占用它的软件后重新全屏"), 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_->game.apply(ui::GamePassthrough::Mode::Off);
+ emit gameModeStopped(tr("界面卡住超过 3 秒,已退出游戏模式")); break;
+ }
+ };
+ auto* gameBeat = new QTimer(this);
+ connect(gameBeat, &QTimer::timeout, this, [this] { impl_->game.heartbeat(); });
+ gameBeat->start(250);
#ifdef VEYRA_ENABLE_MOONLIGHT
setupMoonlight();
#endif
@@ -1415,6 +1451,7 @@ QmlPlayerBridge::QmlPlayerBridge(engine::EngineController& engine, std::filesyst
// snapshot is not part of the player snapshot.
if (impl_->exportQueue.queue().needsTick()) pollExport();
tickPlaylist();
+ updateGameMode();
});
impl_->timer->start(16);
startGpuSampler();
@@ -2456,6 +2493,10 @@ void QmlPlayerBridge::openSourceUri(const std::wstring& uri, const std::wstring&
impl_->engine.previewView({});
impl_->engine.open(impl_->videoWindow, uri, impl_->options);
impl_->openingSessionId = impl_->engine.snapshot().sessionId;
+ // Only the exact capture startScreenCapture opened in 游戏模式 is one.
+ impl_->gameModeSessionId = !impl_->gameModeUri.empty() && uri == impl_->gameModeUri ? impl_->openingSessionId : 0;
+ impl_->gameModeLive = false;
+ impl_->gameModeUri.clear();
refreshSubtitles({});
});
}
@@ -2522,7 +2563,7 @@ QVariantList QmlPlayerBridge::screenTargets() const {
}
QVariantMap QmlPlayerBridge::screenOptions() const {
QVariantMap d{{"kind", 0}, {"method", 0}, {"fps", 0}, {"cursor", true}, {"fill", false},
- {"left", 0}, {"top", 0}, {"right", 0}, {"bottom", 0}};
+ {"left", 0}, {"top", 0}, {"right", 0}, {"bottom", 0}, {"passthrough", false}};
const auto saved = impl_->prefs.value("screen").toMap();
for (auto it = saved.begin(); it != saved.end(); ++it) if (d.contains(it.key())) d[it.key()] = it.value();
if (d.value("kind").toInt() == 0) d["method"] = 0; // DXGI is monitors only
@@ -2538,7 +2579,7 @@ bool QmlPlayerBridge::setScreenOption(const QString& key, const QVariant& value)
const auto [low, high] = ranges.value(key);
if (!ok || n < low || n > high) { emit notice(tr("数值超出范围"), true); return false; }
saved[key] = n;
- } else if (key == QLatin1String("cursor") || key == QLatin1String("fill")) {
+ } else if (key == QLatin1String("cursor") || key == QLatin1String("fill") || key == QLatin1String("passthrough")) {
saved[key] = value.toBool();
} else return false;
impl_->prefs["screen"] = saved;
@@ -2560,14 +2601,98 @@ bool QmlPlayerBridge::startScreenCapture() {
value.cursor = o.value("cursor").toBool();
value.left = o.value("left").toUInt(); value.top = o.value("top").toUInt();
value.right = o.value("right").toUInt(); value.bottom = o.value("bottom").toUInt();
- veyra::log::info("screen-ui", std::format("start kind={} method={} fps={} cursor={} crop={},{},{},{} fill={}", int(value.kind), int(value.method),
- value.fps, value.cursor, value.left, value.top, value.right, value.bottom, o.value("fill").toBool()));
+ // 游戏模式: the real pointer is drawn on top, so the picture carries none (a
+ // second, late pointer otherwise), the picture must match the screen 1:1 for
+ // clicks to land where they are seen (no crop), and the yellow border goes.
+ const bool game = o.value("passthrough").toBool();
+ if (game) {
+ value.cursor = false; value.borderless = true;
+ value.left = value.top = value.right = value.bottom = 0;
+ const HWND window = value.kind == source::ScreenTargetKind::Window ? reinterpret_cast<HWND>(value.target) : nullptr;
+ impl_->gameMonitor = window ? MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST) : reinterpret_cast<HMONITOR>(value.target);
+ impl_->game.setTarget(window, impl_->gameMonitor, !window);
+ impl_->gameModeUri = value.uri();
+ // Two cases the picture cannot cover well, said up front.
+ QUERY_USER_NOTIFICATION_STATE state{};
+ if (SUCCEEDED(SHQueryUserNotificationState(&state)) && state == QUNS_RUNNING_D3D_FULL_SCREEN)
+ emit notice(tr("检测到独占全屏的游戏:Windows 不允许其它窗口盖在它上面,请把游戏改成无边框窗口或窗口化"), true);
+ MONITORINFO monitor{}; monitor.cbSize = sizeof(monitor);
+ RECT client{}; POINT origin{};
+ if (window && GetMonitorInfoW(impl_->gameMonitor, &monitor) && GetClientRect(window, &client) && ClientToScreen(window, &origin) &&
+ (origin.x != monitor.rcMonitor.left || origin.y != monitor.rcMonitor.top ||
+ client.right != monitor.rcMonitor.right - monitor.rcMonitor.left || client.bottom != monitor.rcMonitor.bottom - monitor.rcMonitor.top)) {
+ veyra::log::info("game-mode", std::format("captured window does not fill its monitor: client={}x{} at {},{}", client.right, client.bottom, origin.x, origin.y));
+ emit notice(tr("游戏窗口没有铺满屏幕:画面会放大显示,鼠标点到的位置可能和看到的不一致;建议把游戏设为无边框全屏"), false);
+ }
+ } 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 = o.value("fill").toBool();
impl_->screenFitClient = impl_->screenFitImage = QSize();
rememberSource(QStringLiteral("screen"), screenTargetLabel());
return true;
}
+bool QmlPlayerBridge::gameMode() const { return impl_->gameModeSessionId != 0; }
+bool QmlPlayerBridge::passthroughActive() const { return impl_->passthroughShown; }
+void QmlPlayerBridge::attachMainWindow(qulonglong nativeHandle) { impl_->game.attach(reinterpret_cast<HWND>(nativeHandle)); }
+void QmlPlayerBridge::setGamePanelOpen(bool open) {
+ if (impl_->gamePanelOpen == open) return;
+ impl_->gamePanelOpen = open;
+ updateGameMode();
+}
+int QmlPlayerBridge::gameModeScreenIndex() const {
+ if (!impl_->gameMonitor) return -1;
+ const auto screens = QGuiApplication::screens();
+ for (int i = 0; i < screens.size(); ++i) {
+ const auto* native = screens[i]->nativeInterface<QNativeInterface::QWindowsScreen>();
+ if (native && native->handle() == impl_->gameMonitor) return i;
+ }
+ return -1;
+}
+void QmlPlayerBridge::testBlockUi(int ms) {
+ if (GetEnvironmentVariableW(L"VEYRA_TEST_UI_BLOCK", nullptr, 0) == 0) return;
+ veyra::log::warn("game-mode", std::format("test: GUI thread blocked for {} ms", ms));
+ Sleep(DWORD(std::clamp(ms, 0, 20000)));
+}
+// 游戏模式 state: click-through while the game-mode capture is live and the picture
+// is fullscreen, the panel while the Home panel is open, otherwise a normal window.
+void QmlPlayerBridge::updateGameMode() {
+ using Mode = ui::GamePassthrough::Mode;
+ auto& i = *impl_;
+ const auto& s = i.snapshot;
+ 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;
+ 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.game.apply(Mode::Off);
+ const QString why = s.failed ? uiText(s.status) : QString();
+ emit gameModeStopped(why.isEmpty() ? tr("捕获已结束,已退出游戏模式") : why);
+ }
+ }
+ }
+ 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;
+ // A refusal (the exit hotkey is taken) holds until fullscreen is left.
+ if (want != Mode::Off && i.game.mode() == Mode::Off && !i.game.arm()) { i.gameRefused = true; want = Mode::Off; }
+ if (want != i.game.mode()) {
+ // 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(); }
+ i.game.apply(want);
+ }
+ const bool mode = i.gameModeSessionId != 0;
+ if (mode != i.gameModeShown) { i.gameModeShown = mode; emit gameModeChanged(); }
+}
QString QmlPlayerBridge::screenTargetId() const { return impl_->screenTarget; }
void QmlPlayerBridge::setScreenTargetId(const QString& value) {
impl_->screenTarget = value;
@@ -5464,11 +5589,37 @@ void QmlPlayerBridge::applyPreference(const QString& key) {
// the card cannot run are switched off with their parameters kept.
auto candidate = impl_->currentSession();
const auto previous = candidate;
+ // Switching back gives the list mode its frame generation again (DLSS 4X
+ // moved to FSR 2X by the last switch returns as DLSS 4X) once the card runs it.
+ const auto caps = currentEffectCapabilities();
+ const auto runs = [&](const QString& id) { return caps.value(id).toMap().value("available").toBool(); };
+ auto& active = candidate.configurations[size_t(candidate.active)];
+ const bool listMode = !active.editor;
+ const auto memory = impl_->prefs.value(QStringLiteral("computeFgMemory")).toMap();
+ bool restored = false;
+ if (listMode && !memory.isEmpty()) {
+ const auto backend = engine::FrameGenerationBackend(memory.value(QStringLiteral("backend")).toInt());
+ const auto flow = engine::OpticalFlowBackend(memory.value(QStringLiteral("flow")).toInt());
+ if (runs(fgEffectId(backend))) {
+ active.fgBackend = backend;
+ active.chain.fgMultiplier = memory.value(QStringLiteral("multiplier")).toUInt();
+ if (flow != engine::OpticalFlowBackend::Nvidia || runs(QStringLiteral("flow0"))) active.opticalFlowBackend = flow;
+ impl_->prefs.remove(QStringLiteral("computeFgMemory"));
+ restored = true;
+ veyra::log::info("effect-availability", std::format("compute gpu switch restored backend={} multiplier={}",
+ engine::frameGenerationBackendName(backend), active.chain.fgMultiplier));
+ }
+ }
QStringList disabled;
for (auto& configuration : candidate.configurations) {
const auto reason = disableUnavailableEffects(configuration);
if (!reason.isEmpty()) disabled << reason;
}
+ const auto& before = previous.configurations[size_t(previous.active)];
+ if (listMode && !restored && (before.fgBackend != active.fgBackend || before.opticalFlowBackend != active.opticalFlowBackend))
+ impl_->prefs[QStringLiteral("computeFgMemory")] = QVariantMap{{QStringLiteral("backend"), int(before.fgBackend)},
+ {QStringLiteral("multiplier"), int(before.chain.fgMultiplier)}, {QStringLiteral("flow"), int(before.opticalFlowBackend)}};
+ if (!impl_->savePrefs()) veyra::log::warn("ui-prefs", "compute gpu frame generation memory not saved");
if (candidate != previous) {
auto next = impl_->facade.pendingSettings();
const auto& configuration = candidate.configurations[size_t(candidate.active)];
@@ -6883,6 +7034,7 @@ void QmlPlayerBridge::setPresentationFullscreen(bool value) {
impl_->presentation.fullscreen=value;
impl_->engine.requestPresentation(impl_->presentation);
emit presentationChanged();
+ updateGameMode();
}
double QmlPlayerBridge::previewAspect() const {
const int mode=impl_->screenFillActive?2:impl_->aspectMode;
diff --git a/tests/integration/ScreenCaptureTests.cpp b/tests/integration/ScreenCaptureTests.cpp
index e02a800b..c3f69960 100644
--- a/tests/integration/ScreenCaptureTests.cpp
+++ b/tests/integration/ScreenCaptureTests.cpp
@@ -54,6 +54,9 @@ int wmain(int argc,wchar_t** argv){
if(!ctx.initialize(dd,st)||!ring.initialize(ctx.device(),ctx.directQueue(),ctx.fence(),ctx.fenceEvent(),4,st))return 4;
source::ScreenCaptureOptions options;check(options.fps==0,"default follows display refresh");options.target=uint64_t(child.window);options.fps=60;options.cursor=false;
source::ScreenCaptureOptions parsed;check(source::ScreenCaptureOptions::parse(options.uri(),parsed)&&parsed.target==options.target,"URI round trip");check(!source::ScreenCaptureOptions::parse(options.uri()+L":3",parsed),"reject malformed URI");
+ {source::ScreenCaptureOptions game=options;game.borderless=true;game.cursor=false;source::ScreenCaptureOptions back;
+ check(source::ScreenCaptureOptions::parse(game.uri(),back)&&back.borderless&&!back.cursor&&back.target==game.target,"borderless URI round trip");
+ game.borderless=false;game.cursor=true;check(source::ScreenCaptureOptions::parse(game.uri(),back)&&!back.borderless&&back.cursor,"old cursor field keeps the border");}
source::SourceOpenDesc desc;desc.path=options.uri();desc.d3d12Device=ctx.device();desc.d3d12Queue=ctx.directQueue();source::ScreenCaptureSource source;
bool opened=source.open(desc);check(opened,"WGC open");if(!opened){std::wcerr<<source.status()<<std::endl;return 5;}
pipeline::FramePacket p;const AVFrame* f=nullptr;bool frame=next(source,p,&f);check(frame,"WGC first real frame");if(!frame)return 6;