mirror of
https://github.com/kunkundi/crossdesk.git
synced 2026-10-16 00:33:22 +08:00
Compare commits
43
Commits
ios-support
...
v1.5.1-1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e263aab10d | ||
|
|
9abdfbf684 | ||
|
|
31a0b86cee | ||
|
|
fb34f42744 | ||
|
|
4302ab291c | ||
|
|
4bf92c9e2c | ||
|
|
28de4cf938 | ||
|
|
ce7a3c178e | ||
|
|
d9116200fe | ||
|
|
1d9242515a | ||
|
|
ad62e60b9a | ||
|
|
c4aca303c8 | ||
|
|
57bb91dba3 | ||
|
|
57cab3979e | ||
|
|
d8ccdbaa38 | ||
|
|
f3e67d7d6e | ||
|
|
d648585891 | ||
|
|
e40c7fca98 | ||
|
|
f6324416ec | ||
|
|
0977bd4195 | ||
|
|
f4e094cb35 | ||
|
|
1fe706c5fc | ||
|
|
5fd928ddba | ||
|
|
977899b240 | ||
|
|
7fc1344756 | ||
|
|
73e3bf709d | ||
|
|
6d90c28513 | ||
|
|
c944db6519 | ||
|
|
fc921c9ca1 | ||
|
|
ba2afc982b | ||
|
|
c6635fbdc8 | ||
|
|
3c403f6162 | ||
|
|
b54d32ef41 | ||
|
|
28e9626e0d | ||
|
|
a6e325f190 | ||
|
|
23bf2ff8b8 | ||
|
|
56ebfdf8e7 | ||
|
|
99ae0fc811 | ||
|
|
9af7417c46 | ||
|
|
ceb0a1654a | ||
|
|
4f200095f4 | ||
|
|
bd0a7aa2f6 | ||
|
|
b87ab025be |
@@ -271,7 +271,7 @@ jobs:
|
||||
|
||||
- name: Build CrossDesk
|
||||
run: |
|
||||
xmake f --target_minver=${MACOSX_DEPLOYMENT_TARGET} --CROSSDESK_VERSION=${VERSION_NUM} --USE_CUDA=false -y
|
||||
xmake f --target_minver=${MACOSX_DEPLOYMENT_TARGET} --CROSSDESK_VERSION=${VERSION_NUM} --USE_CUDA=false -vyD
|
||||
xmake b -vy crossdesk
|
||||
|
||||
- name: Package CrossDesk app
|
||||
@@ -682,7 +682,9 @@ jobs:
|
||||
$portableFiles = @(
|
||||
@("crossdesk.exe", "CrossDesk.exe"),
|
||||
@("crossdesk_service.exe", "crossdesk_service.exe"),
|
||||
@("crossdesk_session_helper.exe", "crossdesk_session_helper.exe")
|
||||
@("crossdesk_session_helper.exe", "crossdesk_session_helper.exe"),
|
||||
@("crossdesk_privacy_cursor_helper.exe", "crossdesk_privacy_cursor_helper.exe"),
|
||||
@("crossdesk_privacy_window.dll", "crossdesk_privacy_window.dll")
|
||||
)
|
||||
|
||||
foreach ($file in $portableFiles) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
IDI_CROSSDESK_LOGO ICON "crossdesk.ico"
|
||||
|
||||
#define CROSSDESK_FILE_DESCRIPTION "CrossDesk Privacy Window"
|
||||
#define CROSSDESK_ORIGINAL_FILENAME "crossdesk_privacy_window.dll"
|
||||
#define CROSSDESK_FILE_TYPE VFT_DLL
|
||||
|
||||
#include "version_info.rcinc"
|
||||
@@ -87,7 +87,7 @@ if [[ ! -x "$BUILD_BINARY" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for command_name in readelf ldd dpkg-deb; do
|
||||
for command_name in readelf ldd dpkg-deb strip; do
|
||||
if ! command -v "$command_name" >/dev/null 2>&1; then
|
||||
echo "Required packaging command is missing: $command_name" >&2
|
||||
exit 1
|
||||
@@ -128,6 +128,9 @@ if [[ -n "$SLINT_NEEDED" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
install -m 0755 "$SLINT_LIBRARY" "$PRIVATE_DIR/$SLINT_NEEDED"
|
||||
# Keep dynamic exports/relocations while removing unneeded symbols from the
|
||||
# staged copy. Never strip Xmake's cached runtime in place.
|
||||
strip --strip-unneeded "$PRIVATE_DIR/$SLINT_NEEDED"
|
||||
fi
|
||||
|
||||
cat > "$BIN_DIR/$PKG_NAME" <<'EOF'
|
||||
@@ -161,7 +164,7 @@ Architecture: $DEBIAN_ARCH
|
||||
Maintainer: $MAINTAINER
|
||||
Description: $DESCRIPTION
|
||||
Depends: libc6 (>= 2.31), libstdc++6 (>= 10), libx11-6, libxext6,
|
||||
libxrender1, libxft2, libxrandr2, libxfixes3, libxcursor1, libxcb1, libxcb-randr0,
|
||||
libxrender1, libxft2, libxrandr2, libxfixes3, libxcursor1, libxi6, libxcb1, libxcb-randr0,
|
||||
libxcb-xtest0, libxcb-xinerama0, libxcb-shape0, libxcb-xkb1,
|
||||
libxcb-xfixes0, libxv1, libxtst6, $ALSA_RUNTIME_DEP, libsndio7.0,
|
||||
libxcb-shm0, libpulse0, libdrm2, libdbus-1-3, libgl1
|
||||
|
||||
@@ -11,7 +11,7 @@ EXPECTED_ARCH="$2"
|
||||
APP_EXECUTABLE="$APP_BUNDLE/Contents/MacOS/CrossDesk"
|
||||
FRAMEWORKS_DIR="$APP_BUNDLE/Contents/Frameworks"
|
||||
|
||||
for command_name in codesign install_name_tool lipo otool; do
|
||||
for command_name in codesign install_name_tool lipo otool strip; do
|
||||
if ! command -v "$command_name" >/dev/null 2>&1; then
|
||||
echo "Required bundling command is missing: $command_name" >&2
|
||||
exit 1
|
||||
@@ -123,7 +123,11 @@ if ! otool -l "$APP_EXECUTABLE" | awk '
|
||||
install_name_tool -add_rpath "@executable_path/../Frameworks" "$APP_EXECUTABLE"
|
||||
fi
|
||||
|
||||
# install_name_tool invalidates the linker's ad-hoc signature. Sign nested code
|
||||
# Strip only the staged runtime, retaining exported symbols for Slint's C ABI.
|
||||
# The package cache remains intact for debugging and other consumers.
|
||||
strip -S -x "$FRAMEWORKS_DIR/$SLINT_NAME"
|
||||
|
||||
# install_name_tool and strip invalidate the linker's ad-hoc signature. Sign nested code
|
||||
# first, then seal the complete app bundle so local packages remain launchable.
|
||||
codesign --force --sign - "$FRAMEWORKS_DIR/$SLINT_NAME"
|
||||
codesign --force --deep --sign - "$APP_BUNDLE"
|
||||
|
||||
@@ -88,8 +88,10 @@ installApp:
|
||||
; Bundle service-side binaries required by the Windows service flow
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_service.exe"
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_session_helper.exe"
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_privacy_cursor_helper.exe"
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_privacy_window.dll"
|
||||
; Bundle runtime DLLs from the release output directory
|
||||
File "..\..\..\..\build\windows\x64\release\*.dll"
|
||||
File /x crossdesk_privacy_window.dll "..\..\..\..\build\windows\x64\release\*.dll"
|
||||
|
||||
Call RegisterInstalledService
|
||||
|
||||
@@ -145,6 +147,8 @@ uninstallApp:
|
||||
Delete "$INSTDIR\CrossDesk.exe"
|
||||
Delete "$INSTDIR\crossdesk_service.exe"
|
||||
Delete "$INSTDIR\crossdesk_session_helper.exe"
|
||||
Delete "$INSTDIR\crossdesk_privacy_cursor_helper.exe"
|
||||
Delete "$INSTDIR\crossdesk_privacy_window.dll"
|
||||
Delete "$INSTDIR\uninstall.exe"
|
||||
|
||||
; Recursively delete installation directory
|
||||
|
||||
@@ -22,8 +22,13 @@
|
||||
#include "config_center.h"
|
||||
#include "daemon.h"
|
||||
#include "path_manager.h"
|
||||
#include "rd_log.h"
|
||||
#include "render.h"
|
||||
|
||||
#ifdef __linux__
|
||||
#include "platform/linux/privacy/privacy_guard.h"
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
namespace {
|
||||
|
||||
@@ -175,11 +180,27 @@ int HandleServiceCliCommand(const std::string& command) {
|
||||
#endif
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
#ifdef __linux__
|
||||
// Run before GUI, configuration, logging or daemon initialization. The
|
||||
// guard owns native privacy resources and restores them if this app exits.
|
||||
if (argc == 2 &&
|
||||
std::strcmp(argv[1], crossdesk::kLinuxPrivacyGuardArgument) == 0) {
|
||||
return crossdesk::RunLinuxPrivacyGuard();
|
||||
}
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
if (argc == 2 &&
|
||||
std::strcmp(argv[1], crossdesk::kSlintRendererProbeArgument) == 0) {
|
||||
return crossdesk::RunSlintRendererProbe();
|
||||
}
|
||||
#endif
|
||||
|
||||
// Service operations and config migration can log before the GUI starts.
|
||||
// Configure the directory first, including CLI and daemon child paths.
|
||||
auto path_manager = std::make_unique<crossdesk::PathManager>("CrossDesk");
|
||||
crossdesk::InitLogger(path_manager->GetLogPath().string());
|
||||
|
||||
#ifdef _WIN32
|
||||
if (argc > 1 && IsServiceCliCommand(argv[1])) {
|
||||
return HandleServiceCliCommand(argv[1]);
|
||||
}
|
||||
@@ -206,7 +227,6 @@ int main(int argc, char* argv[]) {
|
||||
#endif
|
||||
|
||||
bool enable_daemon = false;
|
||||
auto path_manager = std::make_unique<crossdesk::PathManager>("CrossDesk");
|
||||
if (path_manager) {
|
||||
std::string cache_path = path_manager->GetCachePath().string();
|
||||
crossdesk::ConfigCenter config_center(cache_path + "/config.ini");
|
||||
@@ -233,4 +253,4 @@ int main(int argc, char* argv[]) {
|
||||
crossdesk::Render render;
|
||||
render.Run();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,14 @@ int ConfigCenter::Load() {
|
||||
video_frame_rate_ = static_cast<VIDEO_FRAME_RATE>(ini_.GetLongValue(
|
||||
section_, "video_frame_rate", static_cast<long>(video_frame_rate_)));
|
||||
|
||||
const long screen_capture_method_value = ini_.GetLongValue(
|
||||
section_, "screen_capture_method",
|
||||
static_cast<long>(ScreenCaptureMethod::Auto));
|
||||
screen_capture_method_ = IsValidScreenCaptureMethod(screen_capture_method_value)
|
||||
? static_cast<ScreenCaptureMethod>(
|
||||
screen_capture_method_value)
|
||||
: ScreenCaptureMethod::Auto;
|
||||
|
||||
const long video_adaptation_policy_value = ini_.GetLongValue(
|
||||
section_, "video_adaptation_policy",
|
||||
static_cast<long>(video_adaptation_policy_));
|
||||
@@ -95,7 +103,12 @@ int ConfigCenter::Load() {
|
||||
ini_.SetLongValue(section_, "turn_mode", static_cast<long>(turn_mode_));
|
||||
persist_config_migration = true;
|
||||
}
|
||||
enable_srtp_ = ini_.GetBoolValue(section_, "enable_srtp", enable_srtp_);
|
||||
// Migrate the former user switch. Keep true in the file for older builds,
|
||||
// while the current application always requests encrypted native media.
|
||||
if (!ini_.GetBoolValue(section_, "enable_srtp", false)) {
|
||||
ini_.SetBoolValue(section_, "enable_srtp", true);
|
||||
persist_config_migration = true;
|
||||
}
|
||||
enable_self_hosted_ =
|
||||
ini_.GetBoolValue(section_, "enable_self_hosted", enable_self_hosted_);
|
||||
|
||||
@@ -116,19 +129,11 @@ int ConfigCenter::Load() {
|
||||
} else {
|
||||
signal_server_port_ = 0;
|
||||
}
|
||||
const char* coturn_server_port_value =
|
||||
ini_.GetValue(section_, "coturn_server_port", nullptr);
|
||||
if (coturn_server_port_value != nullptr &&
|
||||
strlen(coturn_server_port_value) > 0) {
|
||||
coturn_server_port_ =
|
||||
static_cast<int>(ini_.GetLongValue(section_, "coturn_server_port", 0));
|
||||
} else {
|
||||
coturn_server_port_ = 0;
|
||||
}
|
||||
|
||||
enable_autostart_ =
|
||||
ini_.GetBoolValue(section_, "enable_autostart", enable_autostart_);
|
||||
enable_daemon_ = ini_.GetBoolValue(section_, "enable_daemon", enable_daemon_);
|
||||
enable_privacy_screen_.store(
|
||||
ini_.GetBoolValue(section_, "enable_privacy_screen", true));
|
||||
portable_service_prompt_suppressed_ =
|
||||
ini_.GetBoolValue(section_, "portable_service_prompt_suppressed",
|
||||
portable_service_prompt_suppressed_);
|
||||
@@ -155,6 +160,8 @@ int ConfigCenter::Save() {
|
||||
static_cast<long>(video_quality_));
|
||||
ini_.SetLongValue(section_, "video_frame_rate",
|
||||
static_cast<long>(video_frame_rate_));
|
||||
ini_.SetLongValue(section_, "screen_capture_method",
|
||||
static_cast<long>(screen_capture_method_));
|
||||
ini_.SetLongValue(section_, "video_adaptation_policy",
|
||||
static_cast<long>(video_adaptation_policy_));
|
||||
ini_.SetLongValue(section_, "video_encode_format",
|
||||
@@ -163,7 +170,7 @@ int ConfigCenter::Save() {
|
||||
ini_.SetLongValue(section_, "turn_mode", static_cast<long>(turn_mode_));
|
||||
ini_.SetBoolValue(section_, "enable_turn",
|
||||
turn_mode_ != TURN_MODE::DISABLED);
|
||||
ini_.SetBoolValue(section_, "enable_srtp", enable_srtp_);
|
||||
ini_.SetBoolValue(section_, "enable_srtp", true);
|
||||
ini_.SetBoolValue(section_, "enable_self_hosted", enable_self_hosted_);
|
||||
|
||||
// only save when self hosted
|
||||
@@ -171,12 +178,12 @@ int ConfigCenter::Save() {
|
||||
ini_.SetValue(section_, "signal_server_host", signal_server_host_.c_str());
|
||||
ini_.SetLongValue(section_, "signal_server_port",
|
||||
static_cast<long>(signal_server_port_));
|
||||
ini_.SetLongValue(section_, "coturn_server_port",
|
||||
static_cast<long>(coturn_server_port_));
|
||||
}
|
||||
|
||||
ini_.SetBoolValue(section_, "enable_autostart", enable_autostart_);
|
||||
ini_.SetBoolValue(section_, "enable_daemon", enable_daemon_);
|
||||
ini_.SetBoolValue(section_, "enable_privacy_screen",
|
||||
enable_privacy_screen_.load());
|
||||
ini_.SetBoolValue(section_, "portable_service_prompt_suppressed",
|
||||
portable_service_prompt_suppressed_);
|
||||
|
||||
@@ -225,6 +232,20 @@ int ConfigCenter::SetVideoFrameRate(VIDEO_FRAME_RATE video_frame_rate) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetScreenCaptureMethod(ScreenCaptureMethod method) {
|
||||
if (!IsValidScreenCaptureMethod(static_cast<long>(method))) {
|
||||
return -1;
|
||||
}
|
||||
ini_.SetLongValue(section_, "screen_capture_method", static_cast<long>(method));
|
||||
if (ini_.SaveFile(config_path_.c_str()) < 0) {
|
||||
ini_.SetLongValue(section_, "screen_capture_method",
|
||||
static_cast<long>(screen_capture_method_));
|
||||
return -1;
|
||||
}
|
||||
screen_capture_method_ = method;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetVideoAdaptationPolicy(
|
||||
VIDEO_ADAPTATION_POLICY policy) {
|
||||
video_adaptation_policy_ = policy;
|
||||
@@ -285,16 +306,6 @@ int ConfigCenter::SetTurn(bool enable_turn) {
|
||||
return SetTurnMode(turn_mode_);
|
||||
}
|
||||
|
||||
int ConfigCenter::SetSrtp(bool enable_srtp) {
|
||||
enable_srtp_ = enable_srtp;
|
||||
ini_.SetBoolValue(section_, "enable_srtp", enable_srtp_);
|
||||
SI_Error rc = ini_.SaveFile(config_path_.c_str());
|
||||
if (rc < 0) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetServerHost(const std::string& signal_server_host) {
|
||||
signal_server_host_ = signal_server_host;
|
||||
ini_.SetValue(section_, "signal_server_host", signal_server_host_.c_str());
|
||||
@@ -316,17 +327,6 @@ int ConfigCenter::SetServerPort(int signal_server_port) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetCoturnServerPort(int coturn_server_port) {
|
||||
coturn_server_port_ = coturn_server_port;
|
||||
ini_.SetLongValue(section_, "coturn_server_port",
|
||||
static_cast<long>(coturn_server_port_));
|
||||
SI_Error rc = ini_.SaveFile(config_path_.c_str());
|
||||
if (rc < 0) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetSelfHosted(bool enable_self_hosted) {
|
||||
enable_self_hosted_ = enable_self_hosted;
|
||||
ini_.SetBoolValue(section_, "enable_self_hosted", enable_self_hosted_);
|
||||
@@ -346,19 +346,9 @@ int ConfigCenter::SetSelfHosted(bool enable_self_hosted) {
|
||||
signal_server_port_ = static_cast<int>(
|
||||
ini_.GetLongValue(section_, "signal_server_port", 0));
|
||||
}
|
||||
const char* coturn_server_port_value =
|
||||
ini_.GetValue(section_, "coturn_server_port", nullptr);
|
||||
if (coturn_server_port_value != nullptr &&
|
||||
strlen(coturn_server_port_value) > 0) {
|
||||
coturn_server_port_ = static_cast<int>(
|
||||
ini_.GetLongValue(section_, "coturn_server_port", 0));
|
||||
}
|
||||
|
||||
ini_.SetValue(section_, "signal_server_host", signal_server_host_.c_str());
|
||||
ini_.SetLongValue(section_, "signal_server_port",
|
||||
static_cast<long>(signal_server_port_));
|
||||
ini_.SetLongValue(section_, "coturn_server_port",
|
||||
static_cast<long>(coturn_server_port_));
|
||||
}
|
||||
|
||||
SI_Error rc = ini_.SaveFile(config_path_.c_str());
|
||||
@@ -403,6 +393,21 @@ int ConfigCenter::SetDaemon(bool enable_daemon) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetPrivacyScreen(bool enable_privacy_screen) {
|
||||
const bool previous = enable_privacy_screen_.load();
|
||||
if (previous == enable_privacy_screen) return 0;
|
||||
ini_.SetBoolValue(section_, "enable_privacy_screen", enable_privacy_screen);
|
||||
if (ini_.SaveFile(config_path_.c_str()) < 0) {
|
||||
ini_.SetBoolValue(section_, "enable_privacy_screen", previous);
|
||||
LOG_ERROR("Failed to save automatic privacy screen preference");
|
||||
return -1;
|
||||
}
|
||||
// RTC callbacks read only the value committed by the settings thread.
|
||||
enable_privacy_screen_.store(enable_privacy_screen);
|
||||
LOG_INFO("Privacy screen on incoming connection: {}", enable_privacy_screen);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetPortableServicePromptSuppressed(bool suppressed) {
|
||||
portable_service_prompt_suppressed_ = suppressed;
|
||||
ini_.SetBoolValue(section_, "portable_service_prompt_suppressed",
|
||||
@@ -427,6 +432,10 @@ ConfigCenter::VIDEO_FRAME_RATE ConfigCenter::GetVideoFrameRate() const {
|
||||
return video_frame_rate_;
|
||||
}
|
||||
|
||||
ScreenCaptureMethod ConfigCenter::GetScreenCaptureMethod() const {
|
||||
return screen_capture_method_;
|
||||
}
|
||||
|
||||
ConfigCenter::VIDEO_ADAPTATION_POLICY
|
||||
ConfigCenter::GetVideoAdaptationPolicy() const {
|
||||
return video_adaptation_policy_;
|
||||
@@ -436,8 +445,18 @@ ConfigCenter::VIDEO_ENCODE_FORMAT ConfigCenter::GetVideoEncodeFormat() const {
|
||||
return video_encode_format_;
|
||||
}
|
||||
|
||||
bool ConfigCenter::IsHardwareVideoCodecAvailable() {
|
||||
#if (((defined(_WIN32) || defined(__linux__)) && !defined(__aarch64__) && \
|
||||
!defined(__arm__) && USE_CUDA) || \
|
||||
defined(__APPLE__))
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool ConfigCenter::IsHardwareVideoCodec() const {
|
||||
return hardware_video_codec_;
|
||||
return IsHardwareVideoCodecAvailable() && hardware_video_codec_;
|
||||
}
|
||||
|
||||
ConfigCenter::TURN_MODE ConfigCenter::GetTurnMode() const {
|
||||
@@ -448,7 +467,7 @@ bool ConfigCenter::IsEnableTurn() const {
|
||||
return turn_mode_ != TURN_MODE::DISABLED;
|
||||
}
|
||||
|
||||
bool ConfigCenter::IsEnableSrtp() const { return enable_srtp_; }
|
||||
bool ConfigCenter::IsEnableSrtp() const { return true; }
|
||||
|
||||
std::string ConfigCenter::GetSignalServerHost() const {
|
||||
return signal_server_host_;
|
||||
@@ -456,8 +475,6 @@ std::string ConfigCenter::GetSignalServerHost() const {
|
||||
|
||||
int ConfigCenter::GetSignalServerPort() const { return signal_server_port_; }
|
||||
|
||||
int ConfigCenter::GetCoturnServerPort() const { return coturn_server_port_; }
|
||||
|
||||
std::string ConfigCenter::GetDefaultServerHost() const {
|
||||
return signal_server_host_default_;
|
||||
}
|
||||
@@ -466,16 +483,16 @@ int ConfigCenter::GetDefaultSignalServerPort() const {
|
||||
return server_port_default_;
|
||||
}
|
||||
|
||||
int ConfigCenter::GetDefaultCoturnServerPort() const {
|
||||
return coturn_server_port_default_;
|
||||
}
|
||||
|
||||
bool ConfigCenter::IsSelfHosted() const { return enable_self_hosted_; }
|
||||
|
||||
bool ConfigCenter::IsEnableAutostart() const { return enable_autostart_; }
|
||||
|
||||
bool ConfigCenter::IsEnableDaemon() const { return enable_daemon_; }
|
||||
|
||||
bool ConfigCenter::IsEnablePrivacyScreen() const {
|
||||
return enable_privacy_screen_.load();
|
||||
}
|
||||
|
||||
bool ConfigCenter::IsPortableServicePromptSuppressed() const {
|
||||
return portable_service_prompt_suppressed_;
|
||||
}
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
#ifndef _CONFIG_CENTER_H_
|
||||
#define _CONFIG_CENTER_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <string>
|
||||
|
||||
#include "SimpleIni.h"
|
||||
#include "screen_capturer/screen_capture_method.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -39,18 +41,18 @@ class ConfigCenter {
|
||||
int SetLanguage(LANGUAGE language);
|
||||
int SetVideoQuality(VIDEO_QUALITY video_quality);
|
||||
int SetVideoFrameRate(VIDEO_FRAME_RATE video_frame_rate);
|
||||
int SetScreenCaptureMethod(ScreenCaptureMethod method);
|
||||
int SetVideoAdaptationPolicy(VIDEO_ADAPTATION_POLICY policy);
|
||||
int SetVideoEncodeFormat(VIDEO_ENCODE_FORMAT video_encode_format);
|
||||
int SetHardwareVideoCodec(bool hardware_video_codec);
|
||||
int SetTurnMode(TURN_MODE turn_mode);
|
||||
int SetTurn(bool enable_turn);
|
||||
int SetSrtp(bool enable_srtp);
|
||||
int SetServerHost(const std::string& signal_server_host);
|
||||
int SetServerPort(int signal_server_port);
|
||||
int SetCoturnServerPort(int coturn_server_port);
|
||||
int SetSelfHosted(bool enable_self_hosted);
|
||||
int SetAutostart(bool enable_autostart);
|
||||
int SetDaemon(bool enable_daemon);
|
||||
int SetPrivacyScreen(bool enable_privacy_screen);
|
||||
int SetPortableServicePromptSuppressed(bool suppressed);
|
||||
int SetFileTransferSavePath(const std::string& path);
|
||||
|
||||
@@ -59,21 +61,23 @@ class ConfigCenter {
|
||||
LANGUAGE GetLanguage() const;
|
||||
VIDEO_QUALITY GetVideoQuality() const;
|
||||
VIDEO_FRAME_RATE GetVideoFrameRate() const;
|
||||
ScreenCaptureMethod GetScreenCaptureMethod() const;
|
||||
VIDEO_ADAPTATION_POLICY GetVideoAdaptationPolicy() const;
|
||||
VIDEO_ENCODE_FORMAT GetVideoEncodeFormat() const;
|
||||
// Whether this build includes a hardware video codec backend.
|
||||
static bool IsHardwareVideoCodecAvailable();
|
||||
bool IsHardwareVideoCodec() const;
|
||||
TURN_MODE GetTurnMode() const;
|
||||
bool IsEnableTurn() const;
|
||||
bool IsEnableSrtp() const;
|
||||
std::string GetSignalServerHost() const;
|
||||
int GetSignalServerPort() const;
|
||||
int GetCoturnServerPort() const;
|
||||
std::string GetDefaultServerHost() const;
|
||||
int GetDefaultSignalServerPort() const;
|
||||
int GetDefaultCoturnServerPort() const;
|
||||
bool IsSelfHosted() const;
|
||||
bool IsEnableAutostart() const;
|
||||
bool IsEnableDaemon() const;
|
||||
bool IsEnablePrivacyScreen() const;
|
||||
bool IsPortableServicePromptSuppressed() const;
|
||||
std::string GetFileTransferSavePath() const;
|
||||
|
||||
@@ -88,21 +92,20 @@ class ConfigCenter {
|
||||
LANGUAGE language_ = LANGUAGE::CHINESE;
|
||||
VIDEO_QUALITY video_quality_ = VIDEO_QUALITY::HIGH;
|
||||
VIDEO_FRAME_RATE video_frame_rate_ = VIDEO_FRAME_RATE::FPS_60;
|
||||
ScreenCaptureMethod screen_capture_method_ = ScreenCaptureMethod::Auto;
|
||||
VIDEO_ADAPTATION_POLICY video_adaptation_policy_ =
|
||||
VIDEO_ADAPTATION_POLICY::QUALITY_PRIORITY;
|
||||
VIDEO_ENCODE_FORMAT video_encode_format_ = VIDEO_ENCODE_FORMAT::H264;
|
||||
bool hardware_video_codec_ = false;
|
||||
TURN_MODE turn_mode_ = TURN_MODE::AUTO_UDP_TCP;
|
||||
bool enable_srtp_ = false;
|
||||
std::string signal_server_host_ = "";
|
||||
std::string signal_server_host_default_ = "api.crossdesk.cn";
|
||||
int signal_server_port_ = 0;
|
||||
int server_port_default_ = 9099;
|
||||
int coturn_server_port_ = 0;
|
||||
int coturn_server_port_default_ = 3478;
|
||||
bool enable_self_hosted_ = false;
|
||||
bool enable_autostart_ = false;
|
||||
bool enable_daemon_ = false;
|
||||
std::atomic<bool> enable_privacy_screen_{true};
|
||||
bool portable_service_prompt_suppressed_ = false;
|
||||
std::string file_transfer_save_path_ = "";
|
||||
};
|
||||
|
||||
@@ -42,6 +42,9 @@ class KeyboardCapturer : public DeviceController {
|
||||
|
||||
virtual int Hook(OnKeyAction on_key_action, void* user_ptr) = 0;
|
||||
virtual int Unhook() = 0;
|
||||
// Backends with an asynchronous capture loop override this so the UI can
|
||||
// fall back to window events if that loop stops unexpectedly.
|
||||
virtual bool IsHookActive() const { return true; }
|
||||
virtual int SendKeyboardCommand(int key_code, bool is_down,
|
||||
uint32_t scan_code = 0,
|
||||
bool extended = false) = 0;
|
||||
|
||||
@@ -66,10 +66,7 @@ struct InteractionState {
|
||||
bool mouse_controller_is_started_ = false;
|
||||
bool start_screen_capturer_ = false;
|
||||
bool screen_capturer_is_started_ = false;
|
||||
bool start_speaker_capturer_ = false;
|
||||
bool speaker_capturer_is_started_ = false;
|
||||
bool start_keyboard_capturer_ = false;
|
||||
bool show_cursor_ = false;
|
||||
bool keyboard_capturer_is_started_ = false;
|
||||
bool keyboard_capturer_uses_window_events_ = false;
|
||||
bool foucs_on_main_window_ = false;
|
||||
@@ -198,4 +195,4 @@ struct ApplicationState : MainWindowState,
|
||||
|
||||
} // namespace crossdesk::gui_detail
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -34,11 +34,13 @@
|
||||
#include "platform.h"
|
||||
#include "platform/video_renderer.h"
|
||||
#include "rendering/slint_video_presenter.h"
|
||||
#include "runtime/privacy_control_state.h"
|
||||
#if _WIN32
|
||||
#include <windows.h>
|
||||
|
||||
#include "platform/windows/gui/slint_backend.h"
|
||||
#include "platform/windows/gui/tray/win_tray.h"
|
||||
#include "platform/windows/gui/window_icons.h"
|
||||
#elif defined(__APPLE__)
|
||||
#include "platform/macos/gui/tray/mac_tray.h"
|
||||
#include "platform/window_drag.h"
|
||||
@@ -949,10 +951,10 @@ int GuiApplication::Run() {
|
||||
}
|
||||
exec_log_path_ = path_manager_->GetLogPath().string();
|
||||
dll_log_path_ = exec_log_path_;
|
||||
InitializeLogger();
|
||||
cache_path_ = path_manager_->GetCachePath().string();
|
||||
config_center_ = std::make_unique<ConfigCenter>(cache_path_ + "/config.ini");
|
||||
|
||||
InitializeLogger();
|
||||
LOG_INFO("CrossDesk version: {} (Slint UI)", CROSSDESK_VERSION);
|
||||
|
||||
strncpy(signal_server_ip_self_, config_center_->GetSignalServerHost().c_str(),
|
||||
@@ -1012,6 +1014,9 @@ int GuiApplication::Run() {
|
||||
// when deciding whether the last hidden window should stop the event loop.
|
||||
// Keep the loop alive until the tray's explicit Exit action requests quit.
|
||||
ui_->main->show();
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons(ui_->main->window().win32_hwnd());
|
||||
#endif
|
||||
slint::run_event_loop(slint::EventLoopMode::RunUntilQuit);
|
||||
Cleanup();
|
||||
return 0;
|
||||
@@ -1027,6 +1032,8 @@ void GuiApplication::InitializeSettings() {
|
||||
language_button_value_ = localization_language_index_;
|
||||
localization_language_ =
|
||||
static_cast<ConfigCenter::LANGUAGE>(localization_language_index_);
|
||||
privacy_.SetText({
|
||||
localization::privacy_screen_unlock_hint[localization_language_index_]});
|
||||
}
|
||||
|
||||
bool GuiApplication::InitializeSDL() {
|
||||
@@ -1152,6 +1159,9 @@ void GuiApplication::InitializeSystemTray() {
|
||||
return;
|
||||
}
|
||||
ui_->main->show();
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons(ui_->main->window().win32_hwnd());
|
||||
#endif
|
||||
ui_->main->window().set_minimized(false);
|
||||
#if defined(__APPLE__)
|
||||
MacActivateWindow(ui_->main->window().appkit_view());
|
||||
@@ -1221,16 +1231,30 @@ void GuiApplication::ResetSettingsUi() {
|
||||
ui_->main->set_adaptation_policy_index(
|
||||
video_adaptation_policy_button_value_);
|
||||
ui_->main->set_codec_index(video_encode_format_button_value_);
|
||||
ui_->main->set_hardware_codec_enabled(enable_hardware_video_codec_);
|
||||
const bool hardware_codec_available =
|
||||
ConfigCenter::IsHardwareVideoCodecAvailable();
|
||||
ui_->main->set_hardware_codec_available(hardware_codec_available);
|
||||
ui_->main->set_hardware_codec_enabled(hardware_codec_available &&
|
||||
enable_hardware_video_codec_);
|
||||
ui_->main->set_turn_enabled(enable_turn_);
|
||||
ui_->main->set_srtp_enabled(enable_srtp_);
|
||||
ui_->main->set_self_hosted_enabled(enable_self_hosted_);
|
||||
ui_->main->set_autostart_enabled(enable_autostart_);
|
||||
ui_->main->set_daemon_enabled(enable_daemon_);
|
||||
ui_->main->set_privacy_on_connect_enabled(
|
||||
config_center_->IsEnablePrivacyScreen());
|
||||
#ifdef _WIN32
|
||||
ui_->main->set_capture_method_visible(true);
|
||||
ui_->main->set_capture_method_index(
|
||||
static_cast<int>(config_center_->GetScreenCaptureMethod()));
|
||||
#endif
|
||||
#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__)
|
||||
ui_->main->set_privacy_setting_available(true);
|
||||
#else
|
||||
ui_->main->set_privacy_setting_available(false);
|
||||
#endif
|
||||
ui_->main->set_file_save_path(file_transfer_save_path_buf_);
|
||||
ui_->main->set_server_host(signal_server_ip_self_);
|
||||
ui_->main->set_server_port(signal_server_port_self_);
|
||||
ui_->main->set_coturn_port(coturn_server_port_self_);
|
||||
}
|
||||
|
||||
void GuiApplication::BindMainCallbacks() {
|
||||
@@ -1388,7 +1412,6 @@ void GuiApplication::BindMainCallbacks() {
|
||||
main->on_save_self_hosted_settings([this] {
|
||||
const std::string host(ui_->main->get_server_host());
|
||||
const auto signal_port = ParsePort(ui_->main->get_server_port());
|
||||
const auto coturn_port = ParsePort(ui_->main->get_coturn_port());
|
||||
if (!host.empty()) {
|
||||
config_center_->SetServerHost(host);
|
||||
std::memset(signal_server_ip_self_, 0, sizeof(signal_server_ip_self_));
|
||||
@@ -1405,25 +1428,14 @@ void GuiApplication::BindMainCallbacks() {
|
||||
std::snprintf(signal_server_port_, sizeof(signal_server_port_), "%d",
|
||||
*signal_port);
|
||||
}
|
||||
if (coturn_port) {
|
||||
config_center_->SetCoturnServerPort(*coturn_port);
|
||||
std::snprintf(coturn_server_port_self_, sizeof(coturn_server_port_self_),
|
||||
"%d", *coturn_port);
|
||||
std::snprintf(coturn_server_port_, sizeof(coturn_server_port_), "%d",
|
||||
*coturn_port);
|
||||
}
|
||||
});
|
||||
main->on_cancel_self_hosted_settings([this] {
|
||||
const std::string host = config_center_->GetSignalServerHost();
|
||||
ui_->main->set_server_host(UiText(host));
|
||||
const int signal_port = config_center_->GetSignalServerPort();
|
||||
const int coturn_port = config_center_->GetCoturnServerPort();
|
||||
ui_->main->set_server_port(signal_port > 0
|
||||
? UiText(std::to_string(signal_port))
|
||||
: slint::SharedString{});
|
||||
ui_->main->set_coturn_port(coturn_port > 0
|
||||
? UiText(std::to_string(coturn_port))
|
||||
: slint::SharedString{});
|
||||
});
|
||||
main->on_open_download([this] { OpenUrl("https://crossdesk.cn"); });
|
||||
main->on_connection_cancel([this] {
|
||||
@@ -1579,6 +1591,10 @@ void GuiApplication::BindStreamCallbacks() {
|
||||
return;
|
||||
}
|
||||
props->selected_display_ = index;
|
||||
{
|
||||
std::lock_guard lock(props->remote_cursor_state_mutex_);
|
||||
props->cursor_presentation_ = {};
|
||||
}
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::display_id;
|
||||
action.d = index;
|
||||
@@ -1600,6 +1616,36 @@ void GuiApplication::BindStreamCallbacks() {
|
||||
SendReliableDataFrame(props->peer_, message.c_str(), message.size(),
|
||||
props->control_data_label_.c_str());
|
||||
});
|
||||
stream->on_toggle_privacy([this] {
|
||||
auto props = SelectedSession();
|
||||
if (!props || !props->peer_ || !props->control_mouse_ ||
|
||||
props->connection_status_.load() != ConnectionStatus::Connected) return;
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::privacy_command;
|
||||
{
|
||||
std::lock_guard lock(props->privacy_status_mutex_);
|
||||
const auto& status = props->privacy_status_;
|
||||
const uint64_t now = SDL_GetTicks();
|
||||
const auto controls = GetPrivacyControlState(
|
||||
status, props->privacy_status_received_, props->privacy_command_pending_,
|
||||
now - props->privacy_status_tick_, now - props->privacy_command_tick_);
|
||||
if (!controls.can_toggle) return;
|
||||
action.pc.flag = controls.active ? PrivacyCommandFlag::disable
|
||||
: PrivacyCommandFlag::enable;
|
||||
action.pc.block_local_input = true;
|
||||
props->privacy_command_pending_ = true;
|
||||
props->privacy_command_tick_ = now;
|
||||
props->privacy_request_revision_ = status.revision;
|
||||
}
|
||||
const auto message = action.to_json();
|
||||
if (SendReliableDataFrame(props->peer_, message.data(), message.size(),
|
||||
props->control_data_label_.c_str()) != 0) {
|
||||
std::lock_guard lock(props->privacy_status_mutex_);
|
||||
props->privacy_command_pending_ = false;
|
||||
props->privacy_status_received_ = false;
|
||||
LOG_WARN("Privacy command send failed, remote_id={}", props->remote_id_);
|
||||
}
|
||||
});
|
||||
stream->on_toggle_mouse_control([this] {
|
||||
auto props = SelectedSession();
|
||||
if (!props || !props->connection_established_) {
|
||||
@@ -1609,6 +1655,7 @@ void GuiApplication::BindStreamCallbacks() {
|
||||
props->enable_mouse_control_ = props->control_mouse_;
|
||||
start_keyboard_capturer_ = props->control_mouse_;
|
||||
if (!props->control_mouse_) {
|
||||
devices_.StopKeyboardCapturer();
|
||||
keyboard_.ForceReleasePressedKeys();
|
||||
}
|
||||
});
|
||||
@@ -1807,6 +1854,7 @@ void GuiApplication::Tick() {
|
||||
HandleConnectionStatusChange();
|
||||
HandlePendingPresenceProbe();
|
||||
HandlePresenceProbeTimeout();
|
||||
HandlePrivacy();
|
||||
HandleWindowsServiceIntegration();
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
SyncXWaylandWindowActivation();
|
||||
@@ -1846,9 +1894,20 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
}
|
||||
|
||||
CursorState sampled{};
|
||||
if (!cursor_state_provider_.Sample(devices_.display_info_list(),
|
||||
selected_display_, &sampled)) {
|
||||
return;
|
||||
const bool sample_ok = cursor_state_provider_.Sample(
|
||||
devices_.display_info_list(), selected_display_, &sampled);
|
||||
if (!sample_ok) {
|
||||
sampled.render_mode = CursorRenderMode::unknown;
|
||||
if (sampled.hidden_reason == CursorHiddenReason::unspecified) {
|
||||
sampled.hidden_reason = CursorHiddenReason::sampling_failed;
|
||||
}
|
||||
} else if (sampled.render_mode == CursorRenderMode::legacy) {
|
||||
// Providers without platform-specific presentation metadata only need to
|
||||
// sample visible/shape; normalize that common case once for every peer.
|
||||
sampled.render_mode = sampled.visible ? CursorRenderMode::separate
|
||||
: CursorRenderMode::hidden;
|
||||
sampled.hidden_reason = sampled.visible ? CursorHiddenReason::unspecified
|
||||
: CursorHiddenReason::system_hidden;
|
||||
}
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
@@ -1887,21 +1946,23 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
|
||||
const CursorState& previous = delivery.last_sent;
|
||||
const bool shape_changed =
|
||||
!delivery.has_sent || sampled.visible != previous.visible ||
|
||||
sampled.shape != previous.shape ||
|
||||
std::abs(sampled.visual_offset_x - previous.visual_offset_x) >
|
||||
kCursorPositionEpsilon ||
|
||||
std::abs(sampled.visual_offset_y - previous.visual_offset_y) >
|
||||
kCursorPositionEpsilon;
|
||||
!delivery.has_sent || sampled.render_mode != previous.render_mode ||
|
||||
sampled.hidden_reason != previous.hidden_reason ||
|
||||
(sample_ok &&
|
||||
(sampled.visible != previous.visible || sampled.shape != previous.shape ||
|
||||
std::abs(sampled.visual_offset_x - previous.visual_offset_x) >
|
||||
kCursorPositionEpsilon ||
|
||||
std::abs(sampled.visual_offset_y - previous.visual_offset_y) >
|
||||
kCursorPositionEpsilon));
|
||||
// Preserve sub-point cursor motion. At 10x client zoom, the old roughly
|
||||
// one-logical-pixel threshold became several visible phone points.
|
||||
const bool position_changed =
|
||||
!delivery.has_sent ||
|
||||
sampled.position_valid != previous.position_valid ||
|
||||
sampled.display_id != previous.display_id ||
|
||||
(sampled.position_valid && previous.position_valid &&
|
||||
(std::abs(sampled.x - previous.x) > kCursorPositionEpsilon ||
|
||||
std::abs(sampled.y - previous.y) > kCursorPositionEpsilon));
|
||||
sample_ok &&
|
||||
(!delivery.has_sent || sampled.position_valid != previous.position_valid ||
|
||||
sampled.display_id != previous.display_id ||
|
||||
(sampled.position_valid && previous.position_valid &&
|
||||
(std::abs(sampled.x - previous.x) > kCursorPositionEpsilon ||
|
||||
std::abs(sampled.y - previous.y) > kCursorPositionEpsilon)));
|
||||
const bool position_update_due =
|
||||
position_changed &&
|
||||
(delivery.last_sent_time.time_since_epoch().count() == 0 ||
|
||||
@@ -1909,16 +1970,12 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
const bool heartbeat_due =
|
||||
delivery.last_sent_time.time_since_epoch().count() == 0 ||
|
||||
now - delivery.last_sent_time >= kCursorStateHeartbeatInterval;
|
||||
if (suppress_position) {
|
||||
// Cursor appearance is independent of cursor position. Continue sending
|
||||
// shape changes to every controller while withholding only the sampled
|
||||
// position from the connection that originated recent input.
|
||||
if (shape_changed || heartbeat_due) {
|
||||
recipients.push_back({remote_id, false});
|
||||
}
|
||||
} else if (delivery.feedback_pending || shape_changed ||
|
||||
position_update_due || heartbeat_due) {
|
||||
recipients.push_back({remote_id, true});
|
||||
// Position feedback waits for a good sample and the echo-suppression
|
||||
// interval. Appearance changes and heartbeats are independent of both.
|
||||
const bool include_position = sample_ok && !suppress_position;
|
||||
if (shape_changed || heartbeat_due ||
|
||||
(include_position && (delivery.feedback_pending || position_update_due))) {
|
||||
recipients.push_back({remote_id, include_position});
|
||||
}
|
||||
}
|
||||
if (recipients.empty()) return;
|
||||
@@ -1927,6 +1984,18 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
for (const auto& recipient : recipients) {
|
||||
auto& delivery = cursor_delivery_states_[recipient.remote_id];
|
||||
CursorState outgoing = sampled;
|
||||
if (!sample_ok) {
|
||||
// Explicitly report unknown to new receivers, but retain the last
|
||||
// presentation for peers that only understand visible/shape.
|
||||
outgoing = delivery.has_sent ? delivery.last_sent : CursorState{};
|
||||
if (!delivery.has_sent) {
|
||||
outgoing.visible = true;
|
||||
outgoing.shape = RemoteCursorShape::default_cursor;
|
||||
}
|
||||
outgoing.seq = sampled.seq;
|
||||
outgoing.render_mode = sampled.render_mode;
|
||||
outgoing.hidden_reason = sampled.hidden_reason;
|
||||
}
|
||||
outgoing.position_update = recipient.include_position;
|
||||
if (!recipient.include_position) {
|
||||
// Keep legacy receivers at their last acknowledged position as well.
|
||||
@@ -1945,7 +2014,7 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
action.type = ControlType::cursor_state;
|
||||
action.cs = outgoing;
|
||||
const std::string message = action.to_json();
|
||||
const int result = SendDataFrameToPeer(
|
||||
const int result = SendReliableDataFrameToPeer(
|
||||
peer_, message.c_str(), message.size(), mouse_label_.c_str(),
|
||||
recipient.remote_id.c_str(), recipient.remote_id.size());
|
||||
if (result != 0) {
|
||||
@@ -1954,6 +2023,13 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!delivery.has_sent ||
|
||||
delivery.last_sent.render_mode != outgoing.render_mode ||
|
||||
delivery.last_sent.hidden_reason != outgoing.hidden_reason) {
|
||||
LOG_INFO("Send cursor presentation to [{}]: mode={}, reason={}",
|
||||
recipient.remote_id, static_cast<int>(outgoing.render_mode),
|
||||
static_cast<int>(outgoing.hidden_reason));
|
||||
}
|
||||
delivery.last_sent = outgoing;
|
||||
delivery.has_sent = true;
|
||||
if (recipient.include_position) {
|
||||
@@ -2093,6 +2169,9 @@ void GuiApplication::SyncMainWindow() {
|
||||
if (!ui_) {
|
||||
return;
|
||||
}
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons(ui_->main->window().win32_hwnd());
|
||||
#endif
|
||||
#if defined(__APPLE__)
|
||||
if (ui_->main_native_titlebar_attempts > 0) {
|
||||
if (HideDisabledMainWindowZoomButton()) {
|
||||
@@ -2117,15 +2196,7 @@ void GuiApplication::SyncMainWindow() {
|
||||
ui_->main->set_latest_version(UiText(latest_version_));
|
||||
ui_->main->set_release_name(UiText(release_name_));
|
||||
ui_->main->set_release_date(UiText(release_date_));
|
||||
ui_->main->set_settings_session_active(stream_window_inited_);
|
||||
#if (((defined(_WIN32) || defined(__linux__)) && !defined(__aarch64__) && \
|
||||
!defined(__arm__) && USE_CUDA) || \
|
||||
defined(__APPLE__))
|
||||
ui_->main->set_hardware_codec_available(true);
|
||||
#else
|
||||
ui_->main->set_hardware_codec_available(false);
|
||||
#endif
|
||||
|
||||
ui_->main->set_settings_session_active(HasActiveSession());
|
||||
if (show_offline_warning_window_) {
|
||||
ui_->main->set_offline_warning(UiText(offline_warning_text_));
|
||||
show_offline_warning_window_ = false;
|
||||
@@ -2335,6 +2406,7 @@ void GuiApplication::SetStreamKeyboardFocus(bool focused) {
|
||||
|
||||
focus_on_stream_window_ = focused;
|
||||
if (!focused) {
|
||||
devices_.StopKeyboardCapturer();
|
||||
keyboard_.ForceReleasePressedKeys();
|
||||
}
|
||||
}
|
||||
@@ -2389,8 +2461,10 @@ void GuiApplication::SyncStreamWindow() {
|
||||
if (!ui_->stream) {
|
||||
return;
|
||||
}
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons((*ui_->stream)->window().win32_hwnd());
|
||||
#endif
|
||||
(*ui_->stream)->set_window_maximized((*ui_->stream)->window().is_maximized());
|
||||
(*ui_->stream)->set_srtp_enabled(enable_srtp_);
|
||||
#if defined(__APPLE__)
|
||||
if (ui_->stream_live_resize_configuration_attempts > 0) {
|
||||
if (ConfigureStreamWindowLiveResize(
|
||||
@@ -2520,6 +2594,29 @@ void GuiApplication::SyncStreamWindow() {
|
||||
? localization::receiving_screen[localization_language_index_]
|
||||
: std::string{}));
|
||||
(*ui_->stream)->set_mouse_control_enabled(props->control_mouse_);
|
||||
{
|
||||
std::lock_guard lock(props->privacy_status_mutex_);
|
||||
const auto& status = props->privacy_status_;
|
||||
const uint64_t now = SDL_GetTicks();
|
||||
const auto controls = GetPrivacyControlState(
|
||||
status, props->privacy_status_received_, props->privacy_command_pending_,
|
||||
now - props->privacy_status_tick_, now - props->privacy_command_tick_);
|
||||
const bool connected =
|
||||
props->connection_status_.load() == ConnectionStatus::Connected;
|
||||
(*ui_->stream)->set_privacy_active(controls.active);
|
||||
(*ui_->stream)->set_privacy_off(connected && controls.off);
|
||||
(*ui_->stream)->set_privacy_unsupported(controls.unsupported);
|
||||
(*ui_->stream)->set_privacy_can_toggle(
|
||||
props->control_mouse_ && connected && controls.can_toggle);
|
||||
const int language = localization_language_index_;
|
||||
std::string text = !connected || !props->privacy_status_received_
|
||||
? localization::privacy_screen[language]
|
||||
: controls.unsupported ? localization::privacy_unsupported[language]
|
||||
: controls.enabled ? localization::privacy_on[language]
|
||||
: controls.off ? localization::privacy_off[language]
|
||||
: localization::privacy_screen[language];
|
||||
(*ui_->stream)->set_privacy_status_text(UiText(text));
|
||||
}
|
||||
int remote_cursor_shape =
|
||||
static_cast<int>(RemoteCursorShape::default_cursor);
|
||||
bool remote_cursor_active = false;
|
||||
@@ -2530,9 +2627,7 @@ void GuiApplication::SyncStreamWindow() {
|
||||
props->remote_cursor_state_received_;
|
||||
if (remote_cursor_active) {
|
||||
remote_cursor_shape = static_cast<int>(
|
||||
props->remote_cursor_state_.visible
|
||||
? props->remote_cursor_state_.shape
|
||||
: RemoteCursorShape::none);
|
||||
props->cursor_presentation_.Resolve(SDL_GetTicks()));
|
||||
}
|
||||
}
|
||||
(*ui_->stream)->set_remote_cursor_active(remote_cursor_active);
|
||||
@@ -2557,6 +2652,8 @@ void GuiApplication::SyncStreamWindow() {
|
||||
(*ui_->stream)->set_selected_display(props->selected_display_);
|
||||
|
||||
const auto& net = props->net_traffic_stats_;
|
||||
(*ui_->stream)->set_stats_encryption_enabled(
|
||||
status == ConnectionStatus::Connected && net.srtp_active);
|
||||
std::vector<ui::NetworkStatsRow> stats_rows;
|
||||
stats_rows.reserve(4);
|
||||
const auto append_stats_row = [&](const std::string& label,
|
||||
@@ -2763,7 +2860,19 @@ void GuiApplication::SyncServerWindow() {
|
||||
});
|
||||
}
|
||||
|
||||
if (has_connected_controller && !ui_->server) {
|
||||
// Privacy protects local display output while preserving capture.
|
||||
// Keep the panel alive throughout privacy transitions so remote
|
||||
// controllers can still see and operate it without resetting its UI state.
|
||||
bool show_controller_window = has_connected_controller;
|
||||
#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__linux__)
|
||||
// Preserve the existing panel behavior on other platforms.
|
||||
const auto privacy_status = privacy_.Snapshot();
|
||||
const bool privacy_covering = privacy_status.overlay_active ||
|
||||
privacy_status.state == PrivacyState::starting ||
|
||||
privacy_status.state == PrivacyState::stopping;
|
||||
show_controller_window = show_controller_window && !privacy_covering;
|
||||
#endif
|
||||
if (show_controller_window && !ui_->server) {
|
||||
ui_->server.emplace(ui::ServerWindow::create());
|
||||
RegisterFontAwesome((*ui_->server)->window());
|
||||
(*ui_->server)->set_controllers(ui_->controller_model);
|
||||
@@ -2787,7 +2896,7 @@ void GuiApplication::SyncServerWindow() {
|
||||
server_window_created_ = true;
|
||||
server_window_inited_ = true;
|
||||
}
|
||||
if (!has_connected_controller && ui_->server) {
|
||||
if (!show_controller_window && ui_->server) {
|
||||
(*ui_->server)->hide();
|
||||
ui_->server.reset();
|
||||
server_window_created_ = false;
|
||||
@@ -2801,6 +2910,10 @@ void GuiApplication::SyncServerWindow() {
|
||||
return;
|
||||
}
|
||||
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons((*ui_->server)->window().win32_hwnd());
|
||||
#endif
|
||||
|
||||
std::vector<ui::ControllerEntry> controllers;
|
||||
std::vector<slint::SharedString> names;
|
||||
ui_->controller_ids.clear();
|
||||
@@ -2920,9 +3033,9 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
video_adaptation_policy_button_value_ =
|
||||
std::clamp(main->get_adaptation_policy_index(), 0, 2);
|
||||
video_encode_format_button_value_ = std::clamp(main->get_codec_index(), 0, 1);
|
||||
enable_hardware_video_codec_ = main->get_hardware_codec_enabled();
|
||||
enable_hardware_video_codec_ = ConfigCenter::IsHardwareVideoCodecAvailable() &&
|
||||
main->get_hardware_codec_enabled();
|
||||
enable_turn_ = main->get_turn_enabled();
|
||||
enable_srtp_ = main->get_srtp_enabled();
|
||||
enable_self_hosted_ = main->get_self_hosted_enabled();
|
||||
enable_autostart_ = main->get_autostart_enabled();
|
||||
enable_daemon_ = main->get_daemon_enabled();
|
||||
@@ -2931,6 +3044,8 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
static_cast<ConfigCenter::LANGUAGE>(language_button_value_);
|
||||
localization_language_index_ = language_button_value_;
|
||||
config_center_->SetLanguage(localization_language_);
|
||||
privacy_.SetText({
|
||||
localization::privacy_screen_unlock_hint[localization_language_index_]});
|
||||
config_center_->SetVideoQuality(
|
||||
static_cast<ConfigCenter::VIDEO_QUALITY>(video_quality_button_value_));
|
||||
config_center_->SetVideoFrameRate(static_cast<ConfigCenter::VIDEO_FRAME_RATE>(
|
||||
@@ -2943,10 +3058,27 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
video_encode_format_button_value_));
|
||||
config_center_->SetHardwareVideoCodec(enable_hardware_video_codec_);
|
||||
config_center_->SetTurn(enable_turn_);
|
||||
config_center_->SetSrtp(enable_srtp_);
|
||||
config_center_->SetSelfHosted(enable_self_hosted_);
|
||||
config_center_->SetAutostart(enable_autostart_);
|
||||
config_center_->SetDaemon(enable_daemon_);
|
||||
#ifdef _WIN32
|
||||
if (!HasActiveSession()) {
|
||||
const auto capture_method = static_cast<ScreenCaptureMethod>(
|
||||
std::clamp(main->get_capture_method_index(), 0, 3));
|
||||
if (config_center_->SetScreenCaptureMethod(capture_method) != 0) {
|
||||
LOG_ERROR("Failed to save screen capture method");
|
||||
}
|
||||
}
|
||||
main->set_capture_method_index(
|
||||
static_cast<int>(config_center_->GetScreenCaptureMethod()));
|
||||
#endif
|
||||
#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__)
|
||||
if (config_center_->SetPrivacyScreen(main->get_privacy_on_connect_enabled()) !=
|
||||
0) {
|
||||
main->set_privacy_on_connect_enabled(
|
||||
config_center_->IsEnablePrivacyScreen());
|
||||
}
|
||||
#endif
|
||||
|
||||
const std::string path(main->get_file_save_path());
|
||||
std::memset(file_transfer_save_path_buf_, 0,
|
||||
@@ -2962,9 +3094,6 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
if (const auto port = ParsePort(main->get_server_port())) {
|
||||
config_center_->SetServerPort(*port);
|
||||
}
|
||||
if (const auto port = ParsePort(main->get_coturn_port())) {
|
||||
config_center_->SetCoturnServerPort(*port);
|
||||
}
|
||||
|
||||
language_button_value_last_ = language_button_value_;
|
||||
video_quality_button_value_last_ = video_quality_button_value_;
|
||||
@@ -2974,14 +3103,13 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
video_encode_format_button_value_last_ = video_encode_format_button_value_;
|
||||
enable_hardware_video_codec_last_ = enable_hardware_video_codec_;
|
||||
enable_turn_last_ = enable_turn_;
|
||||
enable_srtp_last_ = enable_srtp_;
|
||||
enable_self_hosted_last_ = enable_self_hosted_;
|
||||
enable_autostart_last_ = enable_autostart_;
|
||||
enable_daemon_last_ = enable_daemon_;
|
||||
file_transfer_save_path_last_ = path;
|
||||
ui_->localized_language = -1;
|
||||
|
||||
if (!stream_window_inited_) {
|
||||
if (!HasActiveSession()) {
|
||||
CloseAllRemoteSessions();
|
||||
CreateConnectionPeer();
|
||||
}
|
||||
@@ -3018,6 +3146,7 @@ void GuiApplication::SelectStreamTab(int index) {
|
||||
bool renderer_selection_changed = false;
|
||||
if (!controlled_remote_id_.empty() &&
|
||||
controlled_remote_id_ != selected_remote_id) {
|
||||
devices_.StopKeyboardCapturer();
|
||||
keyboard_.ForceReleasePressedKeys();
|
||||
}
|
||||
focused_remote_id_ = selected_remote_id;
|
||||
@@ -3187,8 +3316,12 @@ void GuiApplication::SendPointerInput(int button, int kind, float x, float y) {
|
||||
|
||||
controlled_remote_id_ = props->remote_id_;
|
||||
const std::string message = action.to_json();
|
||||
SendDataFrame(props->peer_, message.c_str(), message.size(),
|
||||
props->mouse_label_.c_str());
|
||||
{
|
||||
std::lock_guard lock(props->remote_cursor_state_mutex_);
|
||||
props->cursor_presentation_.NoteInput(SDL_GetTicks());
|
||||
}
|
||||
SendReliableDataFrame(props->peer_, message.c_str(), message.size(),
|
||||
props->mouse_label_.c_str());
|
||||
}
|
||||
|
||||
void GuiApplication::SendScrollInput(float delta_x, float delta_y, float x,
|
||||
@@ -3225,10 +3358,14 @@ void GuiApplication::SendScrollInput(float delta_x, float delta_y, float x,
|
||||
if (action.m.s == 0) {
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(props->remote_cursor_state_mutex_);
|
||||
props->cursor_presentation_.NoteInput(SDL_GetTicks());
|
||||
}
|
||||
controlled_remote_id_ = props->remote_id_;
|
||||
const std::string message = action.to_json();
|
||||
SendDataFrame(props->peer_, message.c_str(), message.size(),
|
||||
props->mouse_label_.c_str());
|
||||
SendReliableDataFrame(props->peer_, message.c_str(), message.size(),
|
||||
props->mouse_label_.c_str());
|
||||
}
|
||||
|
||||
void GuiApplication::SendKeyInput(const std::string& text, bool pressed,
|
||||
@@ -3283,9 +3420,12 @@ void GuiApplication::Cleanup() {
|
||||
#if _WIN32 && CROSSDESK_PORTABLE
|
||||
JoinPortableWindowsServiceInstallThread();
|
||||
#endif
|
||||
privacy_.Disable();
|
||||
clipboard_.Shutdown();
|
||||
keyboard_.ForceReleasePressedKeys();
|
||||
keyboard_.ReleaseAllRemotePressedKeys("application_exit");
|
||||
devices_.DestroyDevices();
|
||||
privacy_.Shutdown();
|
||||
devices_.DestroyFactories();
|
||||
CloseAllRemoteSessions();
|
||||
WaitForSessionCleanup();
|
||||
|
||||
@@ -366,8 +366,8 @@ int GuiApplication::ProcessMouseEvent(const SDL_Event &event) {
|
||||
}
|
||||
if (props->peer_) {
|
||||
std::string msg = remote_action.to_json();
|
||||
SendDataFrame(props->peer_, msg.c_str(), msg.size(),
|
||||
props->mouse_label_.c_str());
|
||||
SendReliableDataFrame(props->peer_, msg.c_str(), msg.size(),
|
||||
props->mouse_label_.c_str());
|
||||
}
|
||||
} else if (SDL_EVENT_MOUSE_WHEEL == event.type &&
|
||||
last_mouse_event.button.x >= render_rect.x &&
|
||||
@@ -412,8 +412,8 @@ int GuiApplication::ProcessMouseEvent(const SDL_Event &event) {
|
||||
}
|
||||
if (props->peer_) {
|
||||
std::string msg = remote_action.to_json();
|
||||
SendDataFrame(props->peer_, msg.c_str(), msg.size(),
|
||||
props->mouse_label_.c_str());
|
||||
SendReliableDataFrame(props->peer_, msg.c_str(), msg.size(),
|
||||
props->mouse_label_.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,8 +53,6 @@
|
||||
#define ENABLE_HARDWARE_VIDEO_CODEC_CHECKBOX_PADDING_EN 218 * dpi_scale_
|
||||
#define ENABLE_TURN_CHECKBOX_PADDING_CN 171 * dpi_scale_
|
||||
#define ENABLE_TURN_CHECKBOX_PADDING_EN 218 * dpi_scale_
|
||||
#define ENABLE_SRTP_CHECKBOX_PADDING_CN 171 * dpi_scale_
|
||||
#define ENABLE_SRTP_CHECKBOX_PADDING_EN 218 * dpi_scale_
|
||||
#define ENABLE_SELF_HOSTED_SERVER_CHECKBOX_PADDING_CN 171 * dpi_scale_
|
||||
#define ENABLE_SELF_HOSTED_SERVER_CHECKBOX_PADDING_EN 218 * dpi_scale_
|
||||
#define ENABLE_AUTOSTART_PADDING_CN 171 * dpi_scale_
|
||||
|
||||
@@ -57,8 +57,6 @@
|
||||
#define ENABLE_HARDWARE_VIDEO_CODEC_CHECKBOX_PADDING_EN 218
|
||||
#define ENABLE_TURN_CHECKBOX_PADDING_CN 171
|
||||
#define ENABLE_TURN_CHECKBOX_PADDING_EN 218
|
||||
#define ENABLE_SRTP_CHECKBOX_PADDING_CN 171
|
||||
#define ENABLE_SRTP_CHECKBOX_PADDING_EN 218
|
||||
#define ENABLE_SELF_HOSTED_SERVER_CHECKBOX_PADDING_CN 171
|
||||
#define ENABLE_SELF_HOSTED_SERVER_CHECKBOX_PADDING_EN 218
|
||||
#define ENABLE_AUTOSTART_PADDING_CN 171
|
||||
|
||||
@@ -20,6 +20,12 @@ struct TranslationRow {
|
||||
|
||||
// Single source of truth for all UI strings.
|
||||
#define CROSSDESK_LOCALIZATION_ALL(X) \
|
||||
X(privacy_screen, u8"隐私屏", "Privacy screen", u8"Приватный экран") \
|
||||
X(privacy_enable, u8"开启隐私屏", "Enable privacy screen", u8"Включить приватный экран") \
|
||||
X(privacy_disable, u8"关闭隐私屏", "Disable privacy screen", u8"Выключить приватный экран") \
|
||||
X(privacy_on, u8"隐私屏:已开启", "Privacy screen: on", u8"Приватный экран: включён") \
|
||||
X(privacy_off, u8"隐私屏:已关闭", "Privacy screen: off", u8"Приватный экран: выключен") \
|
||||
X(privacy_unsupported, u8"隐私屏:不可用", "Privacy screen: unavailable", u8"Приватный экран: недоступен") \
|
||||
X(local_desktop, u8"本桌面", "Local Desktop", u8"Локальный рабочий стол") \
|
||||
X(local_id, u8"本机ID", "Local ID", u8"Локальный ID") \
|
||||
X(local_id_copied_to_clipboard, u8"已复制到剪贴板", "Copied to clipboard", \
|
||||
@@ -120,6 +126,9 @@ struct TranslationRow {
|
||||
u8"стола") \
|
||||
X(settings, u8"设置", "Settings", u8"Настройки") \
|
||||
X(language, u8"语言:", "Language:", u8"Язык:") \
|
||||
X(screen_capture_method, u8"采集方式:", "Capture Method:", \
|
||||
u8"Способ захвата:") \
|
||||
X(screen_capture_method_auto, u8"自动", "Auto", u8"Авто") \
|
||||
X(video_quality, u8"画面质量:", "Video Quality:", u8"Качество видео:") \
|
||||
X(video_frame_rate, u8"画面采集帧率:", \
|
||||
"Video Capture Frame Rate:", u8"Частота захвата видео:") \
|
||||
@@ -140,7 +149,6 @@ struct TranslationRow {
|
||||
"Enable Hardware Video Codec:", u8"Использовать аппаратный кодек:") \
|
||||
X(enable_turn, u8"启用中继服务:", \
|
||||
"Enable TURN Service:", u8"Включить TURN-сервис:") \
|
||||
X(enable_srtp, u8"启用SRTP:", "Enable SRTP:", u8"Включить SRTP:") \
|
||||
X(self_hosted_server_config, u8"自托管配置", "Self-Hosted Config", \
|
||||
u8"Конфигурация self-hosted") \
|
||||
X(self_hosted_server_settings, u8"自托管设置", "Self-Hosted Settings", \
|
||||
@@ -149,8 +157,6 @@ struct TranslationRow {
|
||||
"Server Address:", u8"Адрес сервера:") \
|
||||
X(self_hosted_server_port, u8"信令服务端口:", \
|
||||
"Signal Service Port:", u8"Порт сигнального сервиса:") \
|
||||
X(self_hosted_server_coturn_server_port, u8"中继服务端口:", \
|
||||
"Relay Service Port:", u8"Порт реле-сервиса:") \
|
||||
X(ok, u8"确认", "OK", u8"ОК") \
|
||||
X(cancel, u8"取消", "Cancel", u8"Отмена") \
|
||||
X(new_password, u8"请输入六位密码:", \
|
||||
@@ -204,6 +210,8 @@ struct TranslationRow {
|
||||
"Confirm to delete this connection", u8"Удалить это подключение?") \
|
||||
X(enable_autostart, u8"开机自启:", "Auto Start:", u8"Автозапуск:") \
|
||||
X(enable_daemon, u8"启用守护进程:", "Enable Daemon:", u8"Включить демон:") \
|
||||
X(privacy_on_connect, u8"被连接时开启隐私屏:", "Privacy screen on connect:", \
|
||||
u8"Приватность при подключении:") \
|
||||
X(takes_effect_after_restart, u8"重启后生效", "Takes effect after restart", \
|
||||
u8"Вступит в силу после перезапуска") \
|
||||
X(select_file, u8"选择文件发送", "Select File to Send", \
|
||||
@@ -225,6 +233,9 @@ struct TranslationRow {
|
||||
X(connection_mode, u8"连接模式", "Mode", u8"Режим") \
|
||||
X(connection_mode_direct, u8"直连", "Direct", u8"Прямой") \
|
||||
X(connection_mode_relay, u8"中继", "Relay", u8"Релейный") \
|
||||
X(transport_encryption, u8"加密传输", "Encryption", u8"Шифрование") \
|
||||
X(transport_encryption_enabled, u8"已开启", "Enabled", u8"Включено") \
|
||||
X(transport_encryption_disabled, u8"未开启", "Disabled", u8"Выключено") \
|
||||
X(online, u8"在线", "Online", u8"Онлайн") \
|
||||
X(offline, u8"离线", "Offline", u8"Офлайн") \
|
||||
X(device_offline, u8"设备离线", "Device Offline", u8"Устройство офлайн") \
|
||||
@@ -239,6 +250,9 @@ struct TranslationRow {
|
||||
u8"Для работы приложения требуются следующие разрешения:") \
|
||||
X(show_main_window, u8"显示主界面", "Show Main Window", \
|
||||
u8"Показать главное окно") \
|
||||
X(privacy_screen_unlock_hint, u8"按下快捷键,解除隐私屏", \
|
||||
"To turn off the privacy screen, press", \
|
||||
u8"Чтобы отключить приватный экран, нажмите") \
|
||||
X(exit_program, u8"退出", "Exit", u8"Выход")
|
||||
|
||||
inline constexpr TranslationRow kTranslationRows[] = {
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
#include "features/devices/session_device_manager.h"
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include <remote_action.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include "platform.h"
|
||||
#include "rd_log.h"
|
||||
#include "runtime/gui_runtime.h"
|
||||
#include "speaker_capturer_factory.h"
|
||||
#ifdef _WIN32
|
||||
#include "platform/windows/screen_capturer/screen_capturer_win.h"
|
||||
#include "platform/windows/input/mouse/mouse_controller.h"
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
@@ -19,7 +25,23 @@ constexpr auto kFrameDeadlineTolerance = std::chrono::milliseconds(1);
|
||||
|
||||
} // namespace
|
||||
|
||||
SessionDeviceManager::SessionDeviceManager(GuiRuntime &owner) : owner_(owner) {}
|
||||
SessionDeviceManager::SessionDeviceManager(GuiRuntime &owner)
|
||||
: owner_(owner),
|
||||
speaker_capture_(
|
||||
[] {
|
||||
return std::unique_ptr<SpeakerCapturer>(
|
||||
SpeakerCapturerFactory().Create());
|
||||
},
|
||||
[this](unsigned char *data, size_t size, const char *) {
|
||||
if (!owner_.peer_) return;
|
||||
MiniRtcAudioFrame frame{};
|
||||
frame.data = reinterpret_cast<const char *>(data);
|
||||
frame.size = size;
|
||||
frame.captured_timestamp = GetSystemTimeMicros(owner_.peer_);
|
||||
SendAudioFrame(owner_.peer_, &frame, owner_.audio_label_.c_str());
|
||||
}) {}
|
||||
|
||||
SessionDeviceManager::~SessionDeviceManager() { speaker_capture_.Shutdown(); }
|
||||
|
||||
bool SessionDeviceManager::ShouldSendCapturedFrame(
|
||||
std::chrono::steady_clock::time_point now, int fps) {
|
||||
@@ -38,10 +60,56 @@ bool SessionDeviceManager::ShouldSendCapturedFrame(
|
||||
return true;
|
||||
}
|
||||
|
||||
void SessionDeviceManager::RecordCaptureCadence(
|
||||
std::chrono::steady_clock::time_point now, int fps,
|
||||
bool from_secure_desktop) {
|
||||
std::lock_guard<std::mutex> lock(capture_metrics_mutex_);
|
||||
if (capture_metrics_started_ == std::chrono::steady_clock::time_point{})
|
||||
capture_metrics_started_ = now;
|
||||
const auto elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
now - capture_metrics_started_)
|
||||
.count();
|
||||
if (elapsed_us >= 2000000) {
|
||||
if (capture_forwarded_) {
|
||||
const char* source = capture_secure_callbacks_ == 0 ? "normal_desktop"
|
||||
: capture_secure_callbacks_ == capture_callbacks_
|
||||
? "secure_desktop"
|
||||
: "mixed";
|
||||
LOG_INFO(
|
||||
"Capture delivery: source={} normal_callbacks={} secure_callbacks={} "
|
||||
"target_fps={} input_fps={:.2f} "
|
||||
"forwarded_fps={:.2f} callbacks={} rate_dropped={} "
|
||||
"forwarded={} send_errors={} max_callback_gap_us={} "
|
||||
"send_avg_us={} send_max_us={} window_ms={}",
|
||||
source, capture_callbacks_ - capture_secure_callbacks_,
|
||||
capture_secure_callbacks_, fps,
|
||||
capture_callbacks_ * 1000000.0 / elapsed_us,
|
||||
capture_forwarded_ * 1000000.0 / elapsed_us, capture_callbacks_,
|
||||
capture_rate_drops_, capture_forwarded_, capture_send_errors_,
|
||||
capture_max_gap_us_, capture_send_us_ / capture_forwarded_,
|
||||
capture_max_send_us_, elapsed_us / 1000);
|
||||
}
|
||||
capture_metrics_started_ = now;
|
||||
capture_callbacks_ = capture_rate_drops_ = capture_forwarded_ = 0;
|
||||
capture_secure_callbacks_ = 0;
|
||||
capture_send_errors_ = 0;
|
||||
capture_max_gap_us_ = capture_send_us_ = capture_max_send_us_ = 0;
|
||||
}
|
||||
if (last_capture_callback_ != std::chrono::steady_clock::time_point{}) {
|
||||
capture_max_gap_us_ =
|
||||
std::max<int64_t>(capture_max_gap_us_,
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
now - last_capture_callback_)
|
||||
.count());
|
||||
}
|
||||
last_capture_callback_ = std::max(last_capture_callback_, now);
|
||||
++capture_callbacks_;
|
||||
if (from_secure_desktop) ++capture_secure_callbacks_;
|
||||
}
|
||||
|
||||
void SessionDeviceManager::Initialize() {
|
||||
InitializeAudioOutput();
|
||||
screen_capturer_factory_ = new ScreenCapturerFactory();
|
||||
speaker_capturer_factory_ = new SpeakerCapturerFactory();
|
||||
device_controller_factory_ = new DeviceControllerFactory();
|
||||
keyboard_capturer_ =
|
||||
static_cast<KeyboardCapturer *>(device_controller_factory_->Create(
|
||||
@@ -59,9 +127,20 @@ int SessionDeviceManager::InitializeScreenCapturer() {
|
||||
screen_capturer_ =
|
||||
static_cast<ScreenCapturer *>(screen_capturer_factory_->Create());
|
||||
}
|
||||
screen_capturer_->SetPrivacyController(&owner_.privacy_);
|
||||
#ifdef _WIN32
|
||||
if (auto windows = dynamic_cast<ScreenCapturerWin*>(screen_capturer_)) {
|
||||
windows->SetCaptureMethod(owner_.config_center_->GetScreenCaptureMethod());
|
||||
}
|
||||
#endif
|
||||
|
||||
last_frame_time_ = {};
|
||||
next_frame_deadline_ = {};
|
||||
capture_metrics_started_ = last_capture_callback_ = {};
|
||||
capture_callbacks_ = capture_rate_drops_ = capture_forwarded_ = 0;
|
||||
capture_secure_callbacks_ = 0;
|
||||
capture_send_errors_ = 0;
|
||||
capture_max_gap_us_ = capture_send_us_ = capture_max_send_us_ = 0;
|
||||
const int fps = owner_.config_center_->GetVideoFrameRate() ==
|
||||
ConfigCenter::VIDEO_FRAME_RATE::FPS_30
|
||||
? 30
|
||||
@@ -77,7 +156,15 @@ int SessionDeviceManager::InitializeScreenCapturer() {
|
||||
const char *display_name,
|
||||
const MiniRtcNativeVideoFrame *native_frame) {
|
||||
const auto now_time = std::chrono::steady_clock::now();
|
||||
bool from_secure_desktop = false;
|
||||
#ifdef _WIN32
|
||||
from_secure_desktop =
|
||||
ScreenCapturerWin::CurrentFrameIsFromSecureDesktop();
|
||||
#endif
|
||||
RecordCaptureCadence(now_time, fps, from_secure_desktop);
|
||||
if (!ShouldSendCapturedFrame(now_time, fps)) {
|
||||
std::lock_guard<std::mutex> lock(capture_metrics_mutex_);
|
||||
++capture_rate_drops_;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -144,9 +231,24 @@ int SessionDeviceManager::InitializeScreenCapturer() {
|
||||
frame.height = height;
|
||||
frame.captured_timestamp = GetSystemTimeMicros(owner_.peer_);
|
||||
frame.native_frame = native_frame;
|
||||
const auto send_started = std::chrono::steady_clock::now();
|
||||
uint64_t send_errors = 0;
|
||||
for (const std::string &remote_id : connected_remote_ids) {
|
||||
SendVideoFrameToPeer(owner_.peer_, &frame, stream_id.c_str(),
|
||||
remote_id.data(), remote_id.size());
|
||||
if (SendVideoFrameToPeer(owner_.peer_, &frame, stream_id.c_str(),
|
||||
remote_id.data(), remote_id.size()) != 0)
|
||||
++send_errors;
|
||||
}
|
||||
const auto send_us =
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(
|
||||
std::chrono::steady_clock::now() - send_started)
|
||||
.count();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(capture_metrics_mutex_);
|
||||
++capture_forwarded_;
|
||||
capture_send_errors_ += send_errors;
|
||||
capture_send_us_ += send_us;
|
||||
capture_max_send_us_ =
|
||||
std::max<int64_t>(capture_max_send_us_, send_us);
|
||||
}
|
||||
last_video_frame_stream_id_ = stream_id;
|
||||
last_frame_time_ = now_time;
|
||||
@@ -169,6 +271,15 @@ int SessionDeviceManager::InitializeScreenCapturer() {
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool SessionDeviceManager::ShouldCaptureCursor() const {
|
||||
std::shared_lock lock(owner_.connection_status_mutex_);
|
||||
return std::any_of(owner_.connection_status_.begin(),
|
||||
owner_.connection_status_.end(), [](const auto& entry) {
|
||||
return entry.second == ConnectionStatus::Connected &&
|
||||
entry.first.find("web") != std::string::npos;
|
||||
});
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StartScreenCapturer() {
|
||||
#ifdef __APPLE__
|
||||
if (!owner_.EnsureMacScreenRecordingPermission()) {
|
||||
@@ -184,8 +295,11 @@ int SessionDeviceManager::StartScreenCapturer() {
|
||||
}
|
||||
}
|
||||
|
||||
LOG_INFO("Start screen capturer, show cursor: {}", owner_.show_cursor_);
|
||||
const int ret = screen_capturer_->Start(owner_.show_cursor_);
|
||||
// Clear before sampling, so a change arriving after the sample remains pending.
|
||||
cursor_capture_dirty_.store(false, std::memory_order_relaxed);
|
||||
const bool show_cursor = ShouldCaptureCursor();
|
||||
LOG_INFO("Start screen capturer, show cursor: {}", show_cursor);
|
||||
const int ret = screen_capturer_->Start(show_cursor);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Start screen capturer failed: {}", ret);
|
||||
}
|
||||
@@ -200,45 +314,19 @@ int SessionDeviceManager::StopScreenCapturer() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StartSpeakerCapturer() {
|
||||
if (!speaker_capturer_) {
|
||||
speaker_capturer_ =
|
||||
static_cast<SpeakerCapturer *>(speaker_capturer_factory_->Create());
|
||||
const int init_ret = speaker_capturer_->Init(
|
||||
[this](unsigned char *data, size_t size, const char *audio_name) {
|
||||
MiniRtcAudioFrame frame{};
|
||||
frame.data = reinterpret_cast<const char *>(data);
|
||||
frame.size = size;
|
||||
frame.captured_timestamp = GetSystemTimeMicros(owner_.peer_);
|
||||
SendAudioFrame(owner_.peer_, &frame, owner_.audio_label_.c_str());
|
||||
});
|
||||
#ifdef _WIN32
|
||||
void SessionDeviceManager::ReleaseRemoteMouseButtons() {
|
||||
if (auto mouse = dynamic_cast<PlatformMouseController*>(mouse_controller_))
|
||||
mouse->ReleasePressedButtons();
|
||||
}
|
||||
#endif
|
||||
|
||||
if (init_ret != 0) {
|
||||
speaker_capturer_->Destroy();
|
||||
delete speaker_capturer_;
|
||||
speaker_capturer_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
if (!speaker_capturer_) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const int ret = speaker_capturer_->Start();
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Start speaker capturer failed: {}", ret);
|
||||
return ret;
|
||||
}
|
||||
owner_.start_speaker_capturer_ = true;
|
||||
return 0;
|
||||
void SessionDeviceManager::StartSpeakerCapturer() {
|
||||
speaker_capture_.SetEnabled(true);
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StopSpeakerCapturer() {
|
||||
if (speaker_capturer_) {
|
||||
speaker_capturer_->Stop();
|
||||
owner_.start_speaker_capturer_ = false;
|
||||
}
|
||||
return 0;
|
||||
void SessionDeviceManager::StopSpeakerCapturer() {
|
||||
speaker_capture_.SetEnabled(false);
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StartMouseController() {
|
||||
@@ -301,6 +389,7 @@ int SessionDeviceManager::StopMouseController() {
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StartKeyboardCapturer() {
|
||||
ClearCapturedKeyboardInput();
|
||||
owner_.keyboard_capturer_uses_window_events_ = false;
|
||||
|
||||
#ifdef __APPLE__
|
||||
@@ -336,6 +425,7 @@ int SessionDeviceManager::StartKeyboardCapturer() {
|
||||
},
|
||||
this);
|
||||
if (hook_ret != 0) {
|
||||
keyboard_capturer_->Unhook();
|
||||
owner_.keyboard_capturer_uses_window_events_ = true;
|
||||
LOG_WARN(
|
||||
"Start keyboard capturer failed, falling back to Slint keyboard events");
|
||||
@@ -346,6 +436,9 @@ int SessionDeviceManager::StartKeyboardCapturer() {
|
||||
}
|
||||
|
||||
int SessionDeviceManager::StopKeyboardCapturer() {
|
||||
owner_.keyboard_capturer_is_started_ = false;
|
||||
if (keyboard_capturer_) keyboard_capturer_->Unhook();
|
||||
ClearCapturedKeyboardInput();
|
||||
if (owner_.keyboard_capturer_uses_window_events_) {
|
||||
owner_.keyboard_capturer_uses_window_events_ = false;
|
||||
LOG_INFO("Stop keyboard capturer with Slint keyboard backend");
|
||||
@@ -353,8 +446,6 @@ int SessionDeviceManager::StopKeyboardCapturer() {
|
||||
}
|
||||
|
||||
if (keyboard_capturer_) {
|
||||
keyboard_capturer_->Unhook();
|
||||
ClearCapturedKeyboardInput();
|
||||
LOG_INFO("Stop keyboard capturer");
|
||||
}
|
||||
return 0;
|
||||
@@ -424,6 +515,15 @@ void SessionDeviceManager::PushAudio(const char *data, size_t size) {
|
||||
}
|
||||
|
||||
void SessionDeviceManager::UpdateInteractions() {
|
||||
#ifdef _WIN32
|
||||
if (owner_.screen_capturer_is_started_ &&
|
||||
cursor_capture_dirty_.load(std::memory_order_relaxed)) {
|
||||
if (auto* windows = dynamic_cast<ScreenCapturerWin*>(screen_capturer_)) {
|
||||
cursor_capture_dirty_.store(false, std::memory_order_relaxed);
|
||||
windows->SetCursorCapture(ShouldCaptureCursor());
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
const bool is_wayland_session = IsWaylandSession();
|
||||
const bool stop_wayland_mouse_before_screen =
|
||||
@@ -448,16 +548,6 @@ void SessionDeviceManager::UpdateInteractions() {
|
||||
owner_.screen_capturer_is_started_ = false;
|
||||
}
|
||||
|
||||
if (owner_.start_speaker_capturer_ && !owner_.speaker_capturer_is_started_) {
|
||||
if (StartSpeakerCapturer() == 0) {
|
||||
owner_.speaker_capturer_is_started_ = true;
|
||||
}
|
||||
} else if (!owner_.start_speaker_capturer_ &&
|
||||
owner_.speaker_capturer_is_started_) {
|
||||
StopSpeakerCapturer();
|
||||
owner_.speaker_capturer_is_started_ = false;
|
||||
}
|
||||
|
||||
if (owner_.start_mouse_controller_ && !owner_.mouse_controller_is_started_) {
|
||||
if (StartMouseController() == 0) {
|
||||
owner_.mouse_controller_is_started_ = true;
|
||||
@@ -484,6 +574,14 @@ void SessionDeviceManager::UpdateInteractions() {
|
||||
owner_.keyboard_capturer_is_started_ = true;
|
||||
}
|
||||
if (owner_.keyboard_capturer_is_started_) {
|
||||
if (!owner_.keyboard_capturer_uses_window_events_ &&
|
||||
(!keyboard_capturer_ || !keyboard_capturer_->IsHookActive())) {
|
||||
StopKeyboardCapturer();
|
||||
owner_.keyboard_.ForceReleasePressedKeys();
|
||||
owner_.keyboard_capturer_uses_window_events_ = true;
|
||||
owner_.keyboard_capturer_is_started_ = true;
|
||||
LOG_WARN("Native keyboard capture stopped; using Slint keyboard events");
|
||||
}
|
||||
DrainCapturedKeyboardInput();
|
||||
owner_.keyboard_.SendHeartbeat(false);
|
||||
}
|
||||
@@ -515,6 +613,7 @@ void SessionDeviceManager::DrainCapturedKeyboardInput() {
|
||||
std::lock_guard<std::mutex> lock(captured_keyboard_inputs_mutex_);
|
||||
inputs.swap(captured_keyboard_inputs_);
|
||||
}
|
||||
if (owner_.privacy_.Snapshot().input_blocked) return;
|
||||
for (const CapturedKeyboardInput &input : inputs) {
|
||||
owner_.keyboard_.SendKeyCommand(input.key_code, input.is_down,
|
||||
input.scan_code, input.extended);
|
||||
@@ -556,6 +655,7 @@ SessionDeviceManager::display_info_list() const {
|
||||
}
|
||||
|
||||
void SessionDeviceManager::DestroyDevices() {
|
||||
speaker_capture_.Shutdown();
|
||||
if (mouse_controller_) {
|
||||
mouse_controller_->Destroy();
|
||||
delete mouse_controller_;
|
||||
@@ -566,11 +666,6 @@ void SessionDeviceManager::DestroyDevices() {
|
||||
delete screen_capturer_;
|
||||
screen_capturer_ = nullptr;
|
||||
}
|
||||
if (speaker_capturer_) {
|
||||
speaker_capturer_->Destroy();
|
||||
delete speaker_capturer_;
|
||||
speaker_capturer_ = nullptr;
|
||||
}
|
||||
if (keyboard_capturer_) {
|
||||
delete keyboard_capturer_;
|
||||
keyboard_capturer_ = nullptr;
|
||||
@@ -580,8 +675,6 @@ void SessionDeviceManager::DestroyDevices() {
|
||||
void SessionDeviceManager::DestroyFactories() {
|
||||
delete screen_capturer_factory_;
|
||||
screen_capturer_factory_ = nullptr;
|
||||
delete speaker_capturer_factory_;
|
||||
speaker_capturer_factory_ = nullptr;
|
||||
delete device_controller_factory_;
|
||||
device_controller_factory_ = nullptr;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
#ifndef CROSSDESK_GUI_SESSION_DEVICE_MANAGER_H_
|
||||
#define CROSSDESK_GUI_SESSION_DEVICE_MANAGER_H_
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-09
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SESSION_DEVICE_MANAGER_H_
|
||||
#define _SESSION_DEVICE_MANAGER_H_
|
||||
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
@@ -17,7 +25,7 @@
|
||||
#include "device_controller_factory.h"
|
||||
#include "display_info.h"
|
||||
#include "screen_capturer_factory.h"
|
||||
#include "speaker_capturer_factory.h"
|
||||
#include "speaker_capture_controller.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -29,17 +37,28 @@ class GuiRuntime;
|
||||
class SessionDeviceManager {
|
||||
public:
|
||||
explicit SessionDeviceManager(GuiRuntime &owner);
|
||||
~SessionDeviceManager();
|
||||
|
||||
void Initialize();
|
||||
void UpdateInteractions();
|
||||
// Call after changing the controller map. UpdateInteractions consumes this
|
||||
// notification on the UI thread before reading the map under its mutex.
|
||||
void OnControllerConnectionsChanged() {
|
||||
cursor_capture_dirty_.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
void DestroyDevices();
|
||||
void DestroyFactories();
|
||||
|
||||
int InitializeScreenCapturer();
|
||||
int StartScreenCapturer();
|
||||
int StopScreenCapturer();
|
||||
int StartSpeakerCapturer();
|
||||
int StopSpeakerCapturer();
|
||||
#ifdef _WIN32
|
||||
void ReleaseRemoteMouseButtons();
|
||||
#endif
|
||||
// Requests are asynchronous; Stop drains/revokes audio delivery before
|
||||
// returning so the connection peer can be destroyed safely.
|
||||
void StartSpeakerCapturer();
|
||||
void StopSpeakerCapturer();
|
||||
int StartMouseController();
|
||||
int StopMouseController();
|
||||
int StartKeyboardCapturer();
|
||||
@@ -71,13 +90,16 @@ private:
|
||||
void ClearCapturedKeyboardInput();
|
||||
bool ShouldSendCapturedFrame(std::chrono::steady_clock::time_point now,
|
||||
int fps);
|
||||
bool ShouldCaptureCursor() const;
|
||||
void RecordCaptureCadence(std::chrono::steady_clock::time_point now, int fps,
|
||||
bool from_secure_desktop);
|
||||
|
||||
GuiRuntime &owner_;
|
||||
SDL_AudioStream *output_stream_ = nullptr;
|
||||
ScreenCapturerFactory *screen_capturer_factory_ = nullptr;
|
||||
ScreenCapturer *screen_capturer_ = nullptr;
|
||||
SpeakerCapturerFactory *speaker_capturer_factory_ = nullptr;
|
||||
SpeakerCapturer *speaker_capturer_ = nullptr;
|
||||
std::atomic<bool> cursor_capture_dirty_{true};
|
||||
SpeakerCaptureController speaker_capture_;
|
||||
DeviceControllerFactory *device_controller_factory_ = nullptr;
|
||||
MouseController *mouse_controller_ = nullptr;
|
||||
KeyboardCapturer *keyboard_capturer_ = nullptr;
|
||||
@@ -87,10 +109,18 @@ private:
|
||||
std::mutex captured_keyboard_inputs_mutex_;
|
||||
std::chrono::steady_clock::time_point last_frame_time_{};
|
||||
std::chrono::steady_clock::time_point next_frame_deadline_{};
|
||||
std::mutex capture_metrics_mutex_;
|
||||
std::chrono::steady_clock::time_point capture_metrics_started_{};
|
||||
std::chrono::steady_clock::time_point last_capture_callback_{};
|
||||
uint64_t capture_callbacks_ = 0, capture_rate_drops_ = 0;
|
||||
uint64_t capture_secure_callbacks_ = 0;
|
||||
uint64_t capture_forwarded_ = 0, capture_send_errors_ = 0;
|
||||
int64_t capture_max_gap_us_ = 0;
|
||||
int64_t capture_send_us_ = 0, capture_max_send_us_ = 0;
|
||||
std::string last_video_frame_stream_id_;
|
||||
bool invalid_video_stream_id_logged_ = false;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // CROSSDESK_GUI_SESSION_DEVICE_MANAGER_H_
|
||||
#endif
|
||||
|
||||
@@ -213,6 +213,9 @@ int KeyboardController::SendKeyCommand(int key_code, bool is_down,
|
||||
bool KeyboardController::InjectRemoteKey(int key_code, bool is_down,
|
||||
uint32_t scan_code, bool extended) {
|
||||
#if _WIN32
|
||||
if (owner_.privacy_.Engaged() && !IsWindowsPrivacyDesktopAvailable()) {
|
||||
owner_.privacy_.Fail("Secure desktop or locked session; privacy screen will turn off");
|
||||
}
|
||||
if (owner_.local_service_status_received_ &&
|
||||
IsSecureDesktopInteractionRequired(owner_.local_interactive_stage_)) {
|
||||
const std::string response = SendCrossDeskSecureDesktopKeyInput(
|
||||
@@ -246,6 +249,7 @@ bool KeyboardController::InjectRemoteKey(int key_code, bool is_down,
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
// Recheck after the desktop query; key-up cleanup remains allowed while paused.
|
||||
return owner_.devices_.SendKeyboardCommand(key_code, is_down, scan_code,
|
||||
extended);
|
||||
}
|
||||
@@ -342,11 +346,50 @@ void KeyboardController::ReleaseRemotePressedKeys(const std::string& remote_id,
|
||||
keys_to_release.size(), remote_id, reason ? reason : "unknown");
|
||||
}
|
||||
for (const PressedKey& key : keys_to_release) {
|
||||
InjectRemoteKey(key.key_code, false, key.scan_code, key.extended);
|
||||
if (!InjectRemoteKey(key.key_code, false, key.scan_code, key.extended)) {
|
||||
#ifdef _WIN32
|
||||
if (owner_.privacy_.Engaged()) {
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
pending_privacy_releases_[key.key_code] = key;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardController::ReleaseAllRemotePressedKeys(const char* reason) {
|
||||
std::vector<std::string> remotes;
|
||||
{
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
for (const auto& [id, state] : remote_states_) remotes.push_back(id);
|
||||
}
|
||||
for (const auto& id : remotes) ReleaseRemotePressedKeys(id, reason);
|
||||
CheckRemoteTimeouts();
|
||||
}
|
||||
|
||||
void KeyboardController::CheckRemoteTimeouts() {
|
||||
#ifdef _WIN32
|
||||
bool pending = false;
|
||||
{
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
pending = !pending_privacy_releases_.empty();
|
||||
}
|
||||
// A key-up rejected on the secure desktop is retained until the ordinary
|
||||
// desktop returns. Never route cleanup through the security UI helper.
|
||||
if (pending && IsWindowsPrivacyDesktopAvailable()) {
|
||||
std::unordered_map<int, PressedKey> releases;
|
||||
{
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
releases.swap(pending_privacy_releases_);
|
||||
}
|
||||
for (const auto& [code, key] : releases) {
|
||||
if (!owner_.devices_.SendKeyboardCommand(code, false, key.scan_code, key.extended)) {
|
||||
std::lock_guard lock(remote_states_mutex_);
|
||||
pending_privacy_releases_[code] = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
const uint32_t now = static_cast<uint32_t>(SDL_GetTicks());
|
||||
std::vector<std::string> timed_out_remotes;
|
||||
{
|
||||
|
||||
@@ -30,6 +30,7 @@ public:
|
||||
const RemoteAction &remote_action);
|
||||
void ReleaseRemotePressedKeys(const std::string &remote_id,
|
||||
const char *reason);
|
||||
void ReleaseAllRemotePressedKeys(const char* reason);
|
||||
void CheckRemoteTimeouts();
|
||||
|
||||
private:
|
||||
@@ -58,6 +59,9 @@ private:
|
||||
uint32_t last_heartbeat_tick_ = 0;
|
||||
std::unordered_map<std::string, RemoteState> remote_states_;
|
||||
std::mutex remote_states_mutex_;
|
||||
#ifdef _WIN32
|
||||
std::unordered_map<int, PressedKey> pending_privacy_releases_;
|
||||
#endif
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -308,7 +308,6 @@ int SettingsManager::Load() {
|
||||
owner_.enable_hardware_video_codec_ =
|
||||
owner_.config_center_->IsHardwareVideoCodec();
|
||||
owner_.enable_turn_ = owner_.config_center_->IsEnableTurn();
|
||||
owner_.enable_srtp_ = owner_.config_center_->IsEnableSrtp();
|
||||
owner_.enable_self_hosted_ = owner_.config_center_->IsSelfHosted();
|
||||
owner_.enable_autostart_ = owner_.config_center_->IsEnableAutostart();
|
||||
owner_.enable_daemon_ = owner_.config_center_->IsEnableDaemon();
|
||||
@@ -335,7 +334,6 @@ int SettingsManager::Load() {
|
||||
owner_.enable_hardware_video_codec_last_ =
|
||||
owner_.enable_hardware_video_codec_;
|
||||
owner_.enable_turn_last_ = owner_.enable_turn_;
|
||||
owner_.enable_srtp_last_ = owner_.enable_srtp_;
|
||||
owner_.enable_self_hosted_last_ = owner_.enable_self_hosted_;
|
||||
owner_.enable_autostart_last_ = owner_.enable_autostart_;
|
||||
|
||||
|
||||
@@ -25,6 +25,16 @@ constexpr auto kPresenceRefreshInterval = std::chrono::seconds(30);
|
||||
constexpr auto kPresenceRetryInterval = std::chrono::seconds(1);
|
||||
} // namespace
|
||||
|
||||
bool GuiRuntime::HasActiveSession() {
|
||||
if (stream_window_inited_) return true;
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
return std::any_of(connection_status_.begin(), connection_status_.end(),
|
||||
[](const auto& entry) {
|
||||
return entry.second == ConnectionStatus::Connecting ||
|
||||
entry.second == ConnectionStatus::Connected;
|
||||
});
|
||||
}
|
||||
|
||||
void GuiRuntime::HandleConnectionStatusChange() {
|
||||
if (!signal_connected_ || !peer_) {
|
||||
return;
|
||||
@@ -121,36 +131,41 @@ void GuiRuntime::HandlePresenceProbeTimeout() {
|
||||
void GuiRuntime::HandleServerControllerDisconnected(
|
||||
const std::string& remote_id, const char* reason) {
|
||||
keyboard_.ReleaseRemotePressedKeys(remote_id, reason);
|
||||
#ifdef _WIN32
|
||||
devices_.ReleaseRemoteMouseButtons();
|
||||
#endif
|
||||
{
|
||||
std::lock_guard lock(remote_pointer_input_mutex_);
|
||||
last_remote_pointer_input_time_.erase(remote_id);
|
||||
}
|
||||
|
||||
bool has_connected_controller = false;
|
||||
bool has_web_controller = false;
|
||||
std::string remaining_controller_id;
|
||||
{
|
||||
std::unique_lock lock(connection_status_mutex_);
|
||||
connection_status_.erase(remote_id);
|
||||
devices_.OnControllerConnectionsChanged();
|
||||
connection_host_names_.erase(remote_id);
|
||||
privacy_sessions_.Disconnected(remote_id);
|
||||
for (const auto& [id, status] : connection_status_) {
|
||||
if (status != ConnectionStatus::Connected) {
|
||||
continue;
|
||||
}
|
||||
has_connected_controller = true;
|
||||
has_web_controller =
|
||||
has_web_controller || id.find("web") != std::string::npos;
|
||||
if (remaining_controller_id.empty()) {
|
||||
remaining_controller_id = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
show_cursor_ = has_web_controller;
|
||||
if (has_connected_controller) {
|
||||
remote_client_id_ = remaining_controller_id;
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO("Last remote controller disconnected; recovering privacy, reason={}",
|
||||
reason ? reason : "unknown");
|
||||
privacy_.Disconnected();
|
||||
|
||||
need_to_create_server_window_.store(false, std::memory_order_release);
|
||||
need_to_destroy_server_window_.store(true, std::memory_order_release);
|
||||
is_server_mode_ = false;
|
||||
@@ -168,14 +183,11 @@ void GuiRuntime::HandleServerControllerDisconnected(
|
||||
#else
|
||||
start_screen_capturer_ = false;
|
||||
#endif
|
||||
start_speaker_capturer_ = false;
|
||||
devices_.StopSpeakerCapturer();
|
||||
start_mouse_controller_ = false;
|
||||
start_keyboard_capturer_ = false;
|
||||
remote_client_id_.clear();
|
||||
if (audio_capture_) {
|
||||
devices_.StopSpeakerCapturer();
|
||||
audio_capture_ = false;
|
||||
}
|
||||
audio_capture_ = false;
|
||||
devices_.ResetToInitialDisplay();
|
||||
}
|
||||
|
||||
@@ -423,6 +435,7 @@ void GuiRuntime::ResetRemoteSessionResources(
|
||||
std::lock_guard<std::mutex> lock(props->remote_cursor_state_mutex_);
|
||||
props->remote_cursor_state_ = {};
|
||||
props->remote_cursor_state_received_ = false;
|
||||
props->cursor_presentation_ = {};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -505,7 +518,7 @@ int GuiRuntime::ConnectTo(const std::string& remote_id, const char* password,
|
||||
}
|
||||
AddAudioStream(props->peer_, props->audio_label_.c_str());
|
||||
AddDataStream(props->peer_, props->data_label_.c_str(), false);
|
||||
AddDataStream(props->peer_, props->mouse_label_.c_str(), false);
|
||||
AddDataStream(props->peer_, props->mouse_label_.c_str(), true);
|
||||
AddDataStream(props->peer_, props->keyboard_label_.c_str(), true);
|
||||
AddDataStream(props->peer_, props->control_data_label_.c_str(), true);
|
||||
AddDataStream(props->peer_, props->file_label_.c_str(), true);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-16
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CURSOR_PRESENTATION_H_
|
||||
#define _CURSOR_PRESENTATION_H_
|
||||
|
||||
#include <remote_action.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// All times use one monotonic millisecond clock. The owning session's cursor
|
||||
// mutex protects this policy from the transport and UI threads.
|
||||
class CursorPresentation {
|
||||
public:
|
||||
static constexpr uint64_t kStateTimeoutMs = 1500; // Three 500ms heartbeats.
|
||||
static constexpr uint64_t kInputActivityMs = 1500;
|
||||
|
||||
void Observe(const CursorState& state, uint64_t now) {
|
||||
if (state.render_mode == CursorRenderMode::unknown) {
|
||||
// Repeated unavailable samples must not extend the recovery deadline.
|
||||
if (!sample_unavailable_) stale_at_ = now + kStateTimeoutMs;
|
||||
sample_unavailable_ = true;
|
||||
return;
|
||||
}
|
||||
sample_unavailable_ = false;
|
||||
stale_at_ = now + kStateTimeoutMs;
|
||||
const bool separate =
|
||||
state.render_mode == CursorRenderMode::separate ||
|
||||
(state.render_mode == CursorRenderMode::legacy && state.visible);
|
||||
// Old senders cannot distinguish embedded from hidden. Only explicit
|
||||
// metadata from a new sender can establish the no-device compatibility
|
||||
// case.
|
||||
no_device_ = state.render_mode == CursorRenderMode::hidden &&
|
||||
state.hidden_reason == CursorHiddenReason::no_pointing_device;
|
||||
held_shape_ = separate ? state.shape : RemoteCursorShape::none;
|
||||
if (held_shape_ != RemoteCursorShape::none) {
|
||||
last_visible_shape_ = held_shape_;
|
||||
}
|
||||
if (!no_device_) fallback_engaged_ = false;
|
||||
}
|
||||
|
||||
void NoteInput(uint64_t now) { last_input_ = now; }
|
||||
|
||||
RemoteCursorShape Resolve(uint64_t now) {
|
||||
if (!stale_at_) return RemoteCursorShape::default_cursor;
|
||||
|
||||
const bool recent_input =
|
||||
last_input_ && now - *last_input_ < kInputActivityMs;
|
||||
const bool can_recover =
|
||||
now >= *stale_at_ || (!sample_unavailable_ && no_device_);
|
||||
if (can_recover && recent_input) {
|
||||
fallback_engaged_ = true;
|
||||
}
|
||||
// Once needed, retain the locator while idle until a good non-compatibility
|
||||
// sample arrives. Otherwise it would blink off whenever input pauses.
|
||||
return fallback_engaged_ ? last_visible_shape_ : held_shape_;
|
||||
}
|
||||
|
||||
private:
|
||||
bool sample_unavailable_ = false;
|
||||
bool no_device_ = false;
|
||||
bool fallback_engaged_ = false;
|
||||
std::optional<uint64_t> stale_at_;
|
||||
std::optional<uint64_t> last_input_;
|
||||
RemoteCursorShape held_shape_ = RemoteCursorShape::default_cursor;
|
||||
RemoteCursorShape last_visible_shape_ = RemoteCursorShape::default_cursor;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -6,39 +6,17 @@
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include "platform/windows/input/windows_cursor_state.h"
|
||||
#include "platform/windows/screen_capturer/captured_cursor_state.h"
|
||||
#include "platform/windows/screen_capturer/dxgi_cursor_state.h"
|
||||
#include "platform/windows/screen_capturer/secure_desktop_cursor_state.h"
|
||||
#include "runtime/cursor_position.h"
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
bool IsSystemCursor(HCURSOR cursor, LPCWSTR resource) {
|
||||
return cursor != nullptr && cursor == LoadCursorW(nullptr, resource);
|
||||
}
|
||||
|
||||
RemoteCursorShape ShapeFromWindowsCursor(HCURSOR cursor) {
|
||||
if (IsSystemCursor(cursor, IDC_HELP)) return RemoteCursorShape::help;
|
||||
if (IsSystemCursor(cursor, IDC_HAND)) return RemoteCursorShape::pointer;
|
||||
if (IsSystemCursor(cursor, IDC_APPSTARTING))
|
||||
return RemoteCursorShape::progress;
|
||||
if (IsSystemCursor(cursor, IDC_WAIT)) return RemoteCursorShape::wait;
|
||||
if (IsSystemCursor(cursor, IDC_CROSS)) return RemoteCursorShape::crosshair;
|
||||
if (IsSystemCursor(cursor, IDC_IBEAM)) return RemoteCursorShape::text;
|
||||
if (IsSystemCursor(cursor, IDC_NO))
|
||||
return RemoteCursorShape::not_allowed;
|
||||
if (IsSystemCursor(cursor, IDC_SIZEALL)) return RemoteCursorShape::move;
|
||||
if (IsSystemCursor(cursor, IDC_SIZEWE)) return RemoteCursorShape::ew_resize;
|
||||
if (IsSystemCursor(cursor, IDC_SIZENS)) return RemoteCursorShape::ns_resize;
|
||||
if (IsSystemCursor(cursor, IDC_SIZENESW))
|
||||
return RemoteCursorShape::nesw_resize;
|
||||
if (IsSystemCursor(cursor, IDC_SIZENWSE))
|
||||
return RemoteCursorShape::nwse_resize;
|
||||
if (IsSystemCursor(cursor, IDC_UPARROW)) return RemoteCursorShape::n_resize;
|
||||
return RemoteCursorShape::default_cursor;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct CursorStateProvider::Impl {};
|
||||
struct CursorStateProvider::Impl {
|
||||
WindowsCursorState cursor;
|
||||
};
|
||||
|
||||
CursorStateProvider::CursorStateProvider() : impl_(std::make_unique<Impl>()) {}
|
||||
CursorStateProvider::~CursorStateProvider() = default;
|
||||
@@ -47,16 +25,39 @@ bool CursorStateProvider::Sample(const std::vector<DisplayInfo>& displays,
|
||||
int preferred_display, CursorState* state) {
|
||||
if (!state) return false;
|
||||
|
||||
SecureDesktopCursorSnapshot secure_cursor{};
|
||||
if (SharedSecureDesktopCursorState().Get(&secure_cursor)) {
|
||||
if (!secure_cursor.valid) {
|
||||
state->hidden_reason = CursorHiddenReason::secure_desktop_pending;
|
||||
return false;
|
||||
}
|
||||
state->seq = 0;
|
||||
NormalizeCursorPosition(secure_cursor.x, secure_cursor.y, displays,
|
||||
preferred_display, state);
|
||||
state->visible = secure_cursor.visible != 0;
|
||||
state->render_mode = static_cast<CursorRenderMode>(secure_cursor.render_mode);
|
||||
state->hidden_reason =
|
||||
static_cast<CursorHiddenReason>(secure_cursor.hidden_reason);
|
||||
state->shape = state->visible
|
||||
? static_cast<RemoteCursorShape>(secure_cursor.shape)
|
||||
: RemoteCursorShape::none;
|
||||
return true;
|
||||
}
|
||||
|
||||
CURSORINFO info{};
|
||||
info.cbSize = sizeof(info);
|
||||
if (!GetCursorInfo(&info)) return false;
|
||||
|
||||
state->seq = 0;
|
||||
state->visible = (info.flags & CURSOR_SHOWING) != 0;
|
||||
state->shape = state->visible ? ShapeFromWindowsCursor(info.hCursor)
|
||||
: RemoteCursorShape::none;
|
||||
NormalizeCursorPosition(info.ptScreenPos.x, info.ptScreenPos.y, displays,
|
||||
preferred_display, state);
|
||||
void* cursor_monitor = state->position_valid
|
||||
? displays[state->display_id].handle
|
||||
: nullptr;
|
||||
const bool embedded = SharedCapturedCursorState().IsEmbedded(cursor_monitor) ||
|
||||
((info.flags & CURSOR_SHOWING) != 0 &&
|
||||
!SharedDxgiCursorState().ShouldDrawCursor(true, cursor_monitor));
|
||||
impl_->cursor.Sample(info, embedded, state);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,12 +34,10 @@ int GuiRuntime::CreateConnectionPeer() {
|
||||
|
||||
std::string signal_server_ip;
|
||||
int signal_server_port;
|
||||
int coturn_server_port;
|
||||
|
||||
if (config_center_->IsSelfHosted()) {
|
||||
signal_server_ip = config_center_->GetSignalServerHost();
|
||||
signal_server_port = config_center_->GetSignalServerPort();
|
||||
coturn_server_port = config_center_->GetCoturnServerPort();
|
||||
|
||||
std::string current_self_hosted_ip = config_center_->GetSignalServerHost();
|
||||
const bool use_cached_id = settings_.LoadCachedSelfHostedIdentity();
|
||||
@@ -64,7 +62,6 @@ int GuiRuntime::CreateConnectionPeer() {
|
||||
} else {
|
||||
signal_server_ip = config_center_->GetDefaultServerHost();
|
||||
signal_server_port = config_center_->GetDefaultSignalServerPort();
|
||||
coturn_server_port = config_center_->GetDefaultCoturnServerPort();
|
||||
settings_.ActivateCachedPublicIdentity();
|
||||
params_.user_id = client_id_with_password_;
|
||||
}
|
||||
@@ -115,34 +112,11 @@ int GuiRuntime::CreateConnectionPeer() {
|
||||
} else {
|
||||
signal_server_port_self_[0] = '\0';
|
||||
}
|
||||
int coturn_port = config_center_->GetCoturnServerPort();
|
||||
if (coturn_port > 0) {
|
||||
strncpy(coturn_server_port_self_, std::to_string(coturn_port).c_str(),
|
||||
sizeof(coturn_server_port_self_) - 1);
|
||||
coturn_server_port_self_[sizeof(coturn_server_port_self_) - 1] = '\0';
|
||||
} else {
|
||||
coturn_server_port_self_[0] = '\0';
|
||||
}
|
||||
|
||||
// peer config
|
||||
strncpy((char *)params_.signal_server_ip, signal_server_ip.c_str(),
|
||||
sizeof(params_.signal_server_ip) - 1);
|
||||
params_.signal_server_ip[sizeof(params_.signal_server_ip) - 1] = '\0';
|
||||
params_.signal_server_port = signal_server_port;
|
||||
strncpy((char *)params_.stun_server_ip, signal_server_ip.c_str(),
|
||||
sizeof(params_.stun_server_ip) - 1);
|
||||
params_.stun_server_ip[sizeof(params_.stun_server_ip) - 1] = '\0';
|
||||
params_.stun_server_port = coturn_server_port;
|
||||
strncpy((char *)params_.turn_server_ip, signal_server_ip.c_str(),
|
||||
sizeof(params_.turn_server_ip) - 1);
|
||||
params_.turn_server_ip[sizeof(params_.turn_server_ip) - 1] = '\0';
|
||||
params_.turn_server_port = coturn_server_port;
|
||||
// TURN credentials are issued by the signaling server after login. Keep the
|
||||
// initial values empty so a reusable static password is never embedded in
|
||||
// the client binary.
|
||||
params_.turn_server_username[0] = '\0';
|
||||
params_.turn_server_password[0] = '\0';
|
||||
|
||||
strncpy(params_.log_path, dll_log_path_.c_str(),
|
||||
sizeof(params_.log_path) - 1);
|
||||
params_.log_path[sizeof(params_.log_path) - 1] = '\0';
|
||||
@@ -225,7 +199,7 @@ int GuiRuntime::CreateConnectionPeer() {
|
||||
|
||||
AddAudioStream(peer_, audio_label_.c_str());
|
||||
AddDataStream(peer_, data_label_.c_str(), false);
|
||||
AddDataStream(peer_, mouse_label_.c_str(), false);
|
||||
AddDataStream(peer_, mouse_label_.c_str(), true);
|
||||
AddDataStream(peer_, keyboard_label_.c_str(), true);
|
||||
AddDataStream(peer_, control_data_label_.c_str(), true);
|
||||
AddDataStream(peer_, file_label_.c_str(), true);
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#define _GUI_RUNTIME_H_
|
||||
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
@@ -16,8 +17,10 @@
|
||||
#include "features/file_transfer/file_transfer_manager.h"
|
||||
#include "features/input/keyboard_controller.h"
|
||||
#include "features/settings/settings_manager.h"
|
||||
#include "privacy_controller.h"
|
||||
#include "runtime/gui_state.h"
|
||||
#include "runtime/peer_event_handler.h"
|
||||
#include "runtime/privacy_session_policy.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -55,9 +58,14 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
void HandleConnectionStatusChange();
|
||||
void HandlePendingPresenceProbe();
|
||||
void HandlePresenceProbeTimeout();
|
||||
bool HasActiveSession();
|
||||
void HandleServerControllerDisconnected(const std::string& remote_id,
|
||||
const char* reason);
|
||||
void HandleWindowsServiceIntegration();
|
||||
void HandlePrivacy();
|
||||
bool IsAuthorizedController(const std::string& remote_id);
|
||||
void SetControllerPrivacySupport(const std::string& remote_id, bool supported);
|
||||
void QueuePrivacyCommand(const std::string& remote_id, const PrivacyCommand& command);
|
||||
|
||||
void CloseRemoteSession(std::shared_ptr<RemoteSession> props);
|
||||
void CloseAllRemoteSessions();
|
||||
@@ -87,6 +95,12 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
bool EnsureMacAccessibilityPermission();
|
||||
#endif
|
||||
|
||||
PrivacyController privacy_;
|
||||
PrivacySessionPolicy privacy_sessions_;
|
||||
std::mutex privacy_commands_mutex_;
|
||||
std::deque<std::pair<std::string, PrivacyCommand>> privacy_commands_;
|
||||
uint32_t last_privacy_revision_ = 0;
|
||||
uint64_t last_privacy_status_tick_ = 0;
|
||||
ClipboardController clipboard_;
|
||||
SessionDeviceManager devices_;
|
||||
FileTransferManager transfers_;
|
||||
|
||||
@@ -147,6 +147,46 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
}
|
||||
|
||||
std::string remote_id(user_id, user_id_size);
|
||||
if (remote_action.type == ControlType::privacy_status) {
|
||||
if (auto props = runtime->FindRemoteSession(remote_id)) {
|
||||
if (source_id != props->control_data_label_) return;
|
||||
std::lock_guard lock(props->privacy_status_mutex_);
|
||||
if (!props->privacy_status_received_ ||
|
||||
static_cast<int32_t>(remote_action.ps.revision - props->privacy_status_.revision) >= 0) {
|
||||
props->privacy_status_ = remote_action.ps;
|
||||
props->privacy_status_received_ = true;
|
||||
props->privacy_status_tick_ = SDL_GetTicks();
|
||||
if (static_cast<int32_t>(remote_action.ps.revision - props->privacy_request_revision_) > 0 &&
|
||||
remote_action.ps.state != PrivacyState::starting &&
|
||||
remote_action.ps.state != PrivacyState::stopping)
|
||||
props->privacy_command_pending_ = false;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (remote_action.type == ControlType::privacy_command) {
|
||||
if (source_id == runtime->control_data_label_)
|
||||
runtime->QueuePrivacyCommand(remote_id, remote_action.pc);
|
||||
return;
|
||||
}
|
||||
const bool operates_host = remote_action.type == ControlType::mouse ||
|
||||
remote_action.type == ControlType::keyboard || remote_action.type == ControlType::keyboard_state ||
|
||||
remote_action.type == ControlType::service_command || remote_action.type == ControlType::display_id ||
|
||||
remote_action.type == ControlType::audio_capture;
|
||||
if (operates_host) {
|
||||
if (!runtime->IsAuthorizedController(remote_id)) return;
|
||||
#ifdef _WIN32
|
||||
// KeyboardController checks the desktop immediately before each native
|
||||
// key injection, including state reconciliation and cleanup. Avoid a
|
||||
// second synchronous session query for every received keyboard packet.
|
||||
const bool keyboard_input = remote_action.type == ControlType::keyboard ||
|
||||
remote_action.type == ControlType::keyboard_state;
|
||||
if (!keyboard_input && runtime->privacy_.Engaged() &&
|
||||
!IsWindowsPrivacyDesktopAvailable()) {
|
||||
runtime->privacy_.Fail("Secure desktop or lock screen; privacy screen will turn off");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if (remote_action.type == ControlType::service_status) {
|
||||
if (auto props = runtime->FindRemoteSession(remote_id)) {
|
||||
runtime->ApplyRemoteServiceStatus(*props, remote_action.ss);
|
||||
@@ -155,6 +195,9 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
}
|
||||
|
||||
if (remote_action.type == ControlType::service_command) {
|
||||
if (runtime->privacy_.Engaged()) {
|
||||
runtime->privacy_.Fail("Security shortcut requested; privacy screen will turn off");
|
||||
}
|
||||
#if _WIN32
|
||||
if (remote_action.c.flag == ServiceCommandFlag::send_sas) {
|
||||
runtime->pending_windows_service_sas_.store(true,
|
||||
@@ -191,7 +234,11 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
const bool changed =
|
||||
!props->remote_cursor_state_received_ ||
|
||||
props->remote_cursor_state_.visible != remote_action.cs.visible ||
|
||||
props->remote_cursor_state_.shape != remote_action.cs.shape;
|
||||
props->remote_cursor_state_.shape != remote_action.cs.shape ||
|
||||
props->remote_cursor_state_.render_mode !=
|
||||
remote_action.cs.render_mode ||
|
||||
props->remote_cursor_state_.hidden_reason !=
|
||||
remote_action.cs.hidden_reason;
|
||||
CursorState merged = remote_action.cs;
|
||||
if (!remote_action.cs.position_update &&
|
||||
props->remote_cursor_state_received_) {
|
||||
@@ -202,10 +249,14 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
}
|
||||
props->remote_cursor_state_ = merged;
|
||||
props->remote_cursor_state_received_ = true;
|
||||
props->cursor_presentation_.Observe(merged, SDL_GetTicks());
|
||||
if (changed) {
|
||||
LOG_INFO("Received cursor state: seq={}, visible={}, shape={}",
|
||||
LOG_INFO("Received cursor state: seq={}, visible={}, shape={}, "
|
||||
"mode={}, reason={}",
|
||||
remote_action.cs.seq, remote_action.cs.visible,
|
||||
static_cast<int>(remote_action.cs.shape));
|
||||
static_cast<int>(remote_action.cs.shape),
|
||||
static_cast<int>(remote_action.cs.render_mode),
|
||||
static_cast<int>(remote_action.cs.hidden_reason));
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -247,6 +298,10 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
runtime->connection_host_names_[remote_id] = host_name;
|
||||
}
|
||||
LOG_INFO("Remote hostname: [{}]", host_name);
|
||||
if (source_id == runtime->control_data_label_) {
|
||||
runtime->SetControllerPrivacySupport(
|
||||
remote_id, remote_action.i.supports_privacy_screen);
|
||||
}
|
||||
remote_action_codec::Free(remote_action);
|
||||
}
|
||||
} else {
|
||||
@@ -298,9 +353,9 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
runtime->devices_.SendMouseCommand(remote_action,
|
||||
runtime->selected_display_);
|
||||
} else if (remote_action.type == ControlType::audio_capture) {
|
||||
if (remote_action.a && !runtime->start_speaker_capturer_)
|
||||
if (remote_action.a)
|
||||
runtime->devices_.StartSpeakerCapturer();
|
||||
else if (!remote_action.a && runtime->start_speaker_capturer_)
|
||||
else
|
||||
runtime->devices_.StopSpeakerCapturer();
|
||||
} else if (remote_action.type == ControlType::keyboard) {
|
||||
runtime->keyboard_.ApplyRemoteEvent(remote_id, remote_action);
|
||||
|
||||
@@ -262,9 +262,11 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
std::lock_guard lock(props->remote_cursor_state_mutex_);
|
||||
props->remote_cursor_state_ = {};
|
||||
props->remote_cursor_state_received_ = false;
|
||||
props->cursor_presentation_ = {};
|
||||
}
|
||||
{
|
||||
RemoteAction remote_action;
|
||||
RemoteAction remote_action{};
|
||||
remote_action.i.supports_privacy_screen = true;
|
||||
remote_action.i.display_num =
|
||||
runtime->devices_.display_info_list().size();
|
||||
remote_action.i.display_list =
|
||||
@@ -330,6 +332,7 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
std::lock_guard lock(props->remote_cursor_state_mutex_);
|
||||
props->remote_cursor_state_ = {};
|
||||
props->remote_cursor_state_received_ = false;
|
||||
props->cursor_presentation_ = {};
|
||||
}
|
||||
|
||||
std::shared_ptr<std::vector<unsigned char>> native_snapshot;
|
||||
@@ -405,7 +408,18 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
runtime->show_connection_status_window_ = true;
|
||||
{
|
||||
std::unique_lock lock(runtime->connection_status_mutex_);
|
||||
if (status == ConnectionStatus::Connected) {
|
||||
// Wait for explicit desktop capability before enabling privacy or
|
||||
// sending privacy messages. Legacy and web controllers never opt in.
|
||||
runtime->privacy_sessions_.Connected(
|
||||
remote_id, runtime->config_center_->IsEnablePrivacyScreen());
|
||||
if (!runtime->privacy_sessions_.CanEnable() &&
|
||||
runtime->privacy_.Engaged()) {
|
||||
runtime->privacy_.Disable();
|
||||
}
|
||||
}
|
||||
runtime->connection_status_[remote_id] = status;
|
||||
runtime->devices_.OnControllerConnectionsChanged();
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
@@ -414,7 +428,8 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
runtime->last_windows_service_status_tick_ = 0;
|
||||
#endif
|
||||
{
|
||||
RemoteAction remote_action;
|
||||
RemoteAction remote_action{};
|
||||
remote_action.i.supports_privacy_screen = true;
|
||||
remote_action.i.display_num =
|
||||
runtime->devices_.display_info_list().size();
|
||||
remote_action.i.display_list =
|
||||
@@ -468,19 +483,9 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
std::memory_order_release);
|
||||
runtime->is_server_mode_ = true;
|
||||
runtime->start_screen_capturer_ = true;
|
||||
runtime->start_speaker_capturer_ = true;
|
||||
runtime->devices_.StartSpeakerCapturer();
|
||||
runtime->remote_client_id_ = remote_id;
|
||||
runtime->start_mouse_controller_ = true;
|
||||
{
|
||||
std::shared_lock lock(runtime->connection_status_mutex_);
|
||||
if (std::all_of(runtime->connection_status_.begin(),
|
||||
runtime->connection_status_.end(),
|
||||
[](const auto& kv) {
|
||||
return kv.first.find("web") != std::string::npos;
|
||||
})) {
|
||||
runtime->show_cursor_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-12
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_CONTROL_STATE_H_
|
||||
#define _PRIVACY_CONTROL_STATE_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "remote_action.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
struct PrivacyControlState {
|
||||
bool active = false;
|
||||
bool enabled = false;
|
||||
bool off = false;
|
||||
bool unsupported = false;
|
||||
bool can_toggle = false;
|
||||
};
|
||||
|
||||
// Use the same host-confirmed state for presentation and command admission.
|
||||
// Missing confirmation or a failure makes only this toolbar control unavailable.
|
||||
inline PrivacyControlState GetPrivacyControlState(
|
||||
const PrivacyStatus& status, bool received, bool command_pending,
|
||||
uint64_t status_age_ms, uint64_t command_age_ms) {
|
||||
PrivacyControlState result;
|
||||
const bool timeout = command_pending && command_age_ms > 15000;
|
||||
result.unsupported = timeout ||
|
||||
(received && (status_age_ms > 5000 || !status.supported ||
|
||||
status.state == PrivacyState::failed));
|
||||
if (result.unsupported) return result;
|
||||
|
||||
result.active = status.overlay_active || status.remote_paused ||
|
||||
status.state == PrivacyState::on ||
|
||||
status.state == PrivacyState::starting ||
|
||||
status.state == PrivacyState::stopping ||
|
||||
status.state == PrivacyState::failed;
|
||||
// A command in flight only gates repeated clicks; it adds no display state.
|
||||
result.enabled = received &&
|
||||
status.state == PrivacyState::on && status.overlay_active &&
|
||||
!status.remote_paused;
|
||||
result.off = received &&
|
||||
status.state == PrivacyState::off && !result.active;
|
||||
result.can_toggle = !command_pending && (result.active || received);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include <cstring>
|
||||
#include <shared_mutex>
|
||||
|
||||
#include "rd_log.h"
|
||||
#include "runtime/gui_runtime.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
bool GuiRuntime::IsAuthorizedController(const std::string& remote_id) {
|
||||
// Connections appear here only after the existing password/signalling/RTC
|
||||
// admission path. Outgoing/viewer sessions live in remote_sessions_ instead.
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
const auto found = connection_status_.find(remote_id);
|
||||
return found != connection_status_.end() &&
|
||||
found->second == ConnectionStatus::Connected;
|
||||
}
|
||||
|
||||
void GuiRuntime::SetControllerPrivacySupport(const std::string& remote_id,
|
||||
bool supported) {
|
||||
std::unique_lock lock(connection_status_mutex_);
|
||||
const auto found = connection_status_.find(remote_id);
|
||||
if (found == connection_status_.end() ||
|
||||
found->second != ConnectionStatus::Connected) return;
|
||||
|
||||
const bool automatic_enable =
|
||||
privacy_sessions_.SetSupported(remote_id, supported);
|
||||
if (!privacy_sessions_.CanEnable()) {
|
||||
if (privacy_.Engaged()) privacy_.Disable();
|
||||
} else if (automatic_enable && config_center_->IsEnablePrivacyScreen()) {
|
||||
privacy_.EnableOnConnection();
|
||||
}
|
||||
}
|
||||
|
||||
void GuiRuntime::QueuePrivacyCommand(const std::string& remote_id,
|
||||
const PrivacyCommand& command) {
|
||||
std::shared_lock session_lock(connection_status_mutex_);
|
||||
const auto found = connection_status_.find(remote_id);
|
||||
if (found == connection_status_.end() ||
|
||||
found->second != ConnectionStatus::Connected ||
|
||||
!privacy_sessions_.Supports(remote_id)) return;
|
||||
std::lock_guard lock(privacy_commands_mutex_);
|
||||
if (privacy_commands_.size() < 32)
|
||||
privacy_commands_.emplace_back(remote_id, command);
|
||||
}
|
||||
|
||||
void GuiRuntime::HandlePrivacy() {
|
||||
std::deque<std::pair<std::string, PrivacyCommand>> commands;
|
||||
{
|
||||
std::lock_guard lock(privacy_commands_mutex_);
|
||||
commands.swap(privacy_commands_);
|
||||
}
|
||||
for (const auto& [remote_id, command] : commands) {
|
||||
// Keep admission and activation under the connection lock so an unknown
|
||||
// controller cannot join between the capability check and enabling.
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
const auto found = connection_status_.find(remote_id);
|
||||
if (found == connection_status_.end() ||
|
||||
found->second != ConnectionStatus::Connected ||
|
||||
!privacy_sessions_.Supports(remote_id)) continue;
|
||||
if (command.flag == PrivacyCommandFlag::enable) {
|
||||
if (privacy_sessions_.CanEnable())
|
||||
privacy_.Enable(command.block_local_input);
|
||||
} else if (command.flag == PrivacyCommandFlag::disable) {
|
||||
privacy_.Disable();
|
||||
}
|
||||
last_privacy_status_tick_ = 0;
|
||||
}
|
||||
auto status = privacy_.Snapshot();
|
||||
const uint64_t now = SDL_GetTicks();
|
||||
if (!peer_ || (last_privacy_status_tick_ != 0 &&
|
||||
status.revision == last_privacy_revision_ &&
|
||||
now - last_privacy_status_tick_ < 1000))
|
||||
return;
|
||||
std::vector<std::string> controllers;
|
||||
{
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
for (const auto& [id, state] : connection_status_)
|
||||
if (state == ConnectionStatus::Connected && privacy_sessions_.Supports(id))
|
||||
controllers.push_back(id);
|
||||
if (!privacy_sessions_.CanEnable()) {
|
||||
status.state = PrivacyState::unsupported;
|
||||
status.supported = false;
|
||||
status.input_block_supported = false;
|
||||
std::strcpy(status.reason,
|
||||
"A connected controller does not support privacy screen");
|
||||
}
|
||||
}
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::privacy_status;
|
||||
action.ps = status;
|
||||
const auto message = action.to_json();
|
||||
bool sent = true;
|
||||
for (const auto& id : controllers) {
|
||||
const int result = SendReliableDataFrameToPeer(
|
||||
peer_, message.data(), message.size(), control_data_label_.c_str(),
|
||||
id.data(), id.size());
|
||||
if (result != 0) {
|
||||
sent = false;
|
||||
LOG_WARN("Privacy status send failed, peer={}, ret={}", id, result);
|
||||
}
|
||||
}
|
||||
if (sent) {
|
||||
last_privacy_revision_ = status.revision;
|
||||
last_privacy_status_tick_ = now;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-15
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_SESSION_POLICY_H_
|
||||
#define _PRIVACY_SESSION_POLICY_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Guarded by GuiRuntime's connection_status_mutex_. Privacy covers the shared
|
||||
// desktop, so every connected controller must explicitly support it.
|
||||
class PrivacySessionPolicy {
|
||||
public:
|
||||
void Connected(const std::string& remote_id, bool automatic_privacy) {
|
||||
const auto [entry, inserted] = controllers_.try_emplace(remote_id, false);
|
||||
if (inserted && controllers_.size() == 1 && automatic_privacy) {
|
||||
automatic_controller_ = remote_id;
|
||||
}
|
||||
}
|
||||
|
||||
void Disconnected(const std::string& remote_id) {
|
||||
controllers_.erase(remote_id);
|
||||
if (automatic_controller_ == remote_id) automatic_controller_.clear();
|
||||
}
|
||||
|
||||
// Consume automatic activation once, on the first controller's host info.
|
||||
// Repeated metadata or a later join must not undo an explicit privacy exit.
|
||||
bool SetSupported(const std::string& remote_id, bool supported) {
|
||||
const auto entry = controllers_.find(remote_id);
|
||||
if (entry == controllers_.end()) return false;
|
||||
entry->second = supported && remote_id.find("web") == std::string::npos;
|
||||
if (automatic_controller_ != remote_id) return false;
|
||||
automatic_controller_.clear();
|
||||
return CanEnable();
|
||||
}
|
||||
|
||||
bool Supports(const std::string& remote_id) const {
|
||||
const auto entry = controllers_.find(remote_id);
|
||||
return entry != controllers_.end() && entry->second;
|
||||
}
|
||||
|
||||
bool CanEnable() const {
|
||||
return !controllers_.empty() &&
|
||||
std::all_of(controllers_.begin(), controllers_.end(),
|
||||
[](const auto& entry) { return entry.second; });
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, bool> controllers_;
|
||||
std::string automatic_controller_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -55,6 +55,7 @@ bool Deserialize(const char *data, size_t size, RemoteAction &out) {
|
||||
out.type = static_cast<ControlType>(data[offset++]);
|
||||
|
||||
if (out.type == ControlType::host_infomation) {
|
||||
out.i.supports_privacy_screen = false;
|
||||
size_t name_len;
|
||||
if (!read(&name_len, sizeof(size_t)) ||
|
||||
name_len >= sizeof(out.i.host_name)) {
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <remote_action.h>
|
||||
#include <stream_names.h>
|
||||
#include "display_info.h"
|
||||
#include "cursor_presentation.h"
|
||||
#include "minirtc.h"
|
||||
|
||||
namespace crossdesk { class PeerEventHandler; }
|
||||
@@ -157,6 +158,13 @@ struct RemoteSession {
|
||||
std::string audio_capture_button_label_ = "Audio Capture";
|
||||
std::string remote_host_name_;
|
||||
bool remote_service_status_received_ = false;
|
||||
std::mutex privacy_status_mutex_;
|
||||
PrivacyStatus privacy_status_{};
|
||||
bool privacy_status_received_ = false;
|
||||
bool privacy_command_pending_ = false;
|
||||
uint64_t privacy_command_tick_ = 0;
|
||||
uint32_t privacy_request_revision_ = 0;
|
||||
uint64_t privacy_status_tick_ = 0;
|
||||
bool remote_service_available_ = false;
|
||||
std::string remote_interactive_stage_;
|
||||
std::vector<DisplayInfo> display_info_list_;
|
||||
@@ -166,6 +174,7 @@ struct RemoteSession {
|
||||
std::mutex remote_cursor_state_mutex_;
|
||||
CursorState remote_cursor_state_{};
|
||||
bool remote_cursor_state_received_ = false;
|
||||
CursorPresentation cursor_presentation_;
|
||||
// Shared by minirtc callbacks, Slint rendering and SDL audio callbacks.
|
||||
std::atomic<ConnectionStatus> connection_status_ = ConnectionStatus::Closed;
|
||||
TraversalMode traversal_mode_ = TraversalMode::UnknownMode;
|
||||
@@ -184,4 +193,4 @@ using RemoteSessionPtr = std::shared_ptr<RemoteSession>;
|
||||
|
||||
} // namespace crossdesk::gui_detail
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -136,10 +136,8 @@ struct UserSettingsState {
|
||||
int video_encode_format_button_value_ = 0;
|
||||
bool enable_hardware_video_codec_ = true;
|
||||
bool enable_turn_ = true;
|
||||
bool enable_srtp_ = false;
|
||||
char signal_server_ip_[256] = "api.crossdesk.cn";
|
||||
char signal_server_port_[6] = "9099";
|
||||
char coturn_server_port_[6] = "3478";
|
||||
bool enable_self_hosted_ = false;
|
||||
int language_button_value_last_ = 0;
|
||||
int video_quality_button_value_last_ = 0;
|
||||
@@ -148,7 +146,6 @@ struct UserSettingsState {
|
||||
int video_encode_format_button_value_last_ = 0;
|
||||
bool enable_hardware_video_codec_last_ = false;
|
||||
bool enable_turn_last_ = true;
|
||||
bool enable_srtp_last_ = false;
|
||||
bool enable_self_hosted_last_ = false;
|
||||
bool enable_autostart_ = false;
|
||||
bool enable_autostart_last_ = false;
|
||||
@@ -158,7 +155,6 @@ struct UserSettingsState {
|
||||
std::string file_transfer_save_path_last_;
|
||||
char signal_server_ip_self_[256] = "";
|
||||
char signal_server_port_self_[6] = "";
|
||||
char coturn_server_port_self_[6] = "";
|
||||
bool settings_window_pos_reset_ = true;
|
||||
bool self_hosted_server_config_window_pos_reset_ = true;
|
||||
std::string selected_current_file_path_;
|
||||
|
||||
@@ -45,6 +45,7 @@ export global FontAwesomeIcons {
|
||||
out property <string> shield-halved: "\u{f3ed}";
|
||||
out property <string> square-full: "\u{f45c}";
|
||||
out property <string> trash-can: "\u{f2ed}";
|
||||
out property <string> user-secret: "\u{f21b}";
|
||||
out property <string> volume-high: "\u{f028}";
|
||||
out property <string> volume-xmark: "\u{f6a9}";
|
||||
out property <string> xmark: "\u{f00d}";
|
||||
|
||||
@@ -39,6 +39,8 @@ export global UiStrings {
|
||||
in-out property <string> language: "Language";
|
||||
in-out property <string> video-quality: "Video quality";
|
||||
in-out property <string> frame-rate: "Frame rate";
|
||||
in-out property <string> capture-method: "Capture method";
|
||||
in-out property <string> capture-method-auto: "Auto";
|
||||
in-out property <string> adaptation-policy: "Video preference";
|
||||
in-out property <string> priority-frame-rate: "Frame rate";
|
||||
in-out property <string> priority-quality: "Quality";
|
||||
@@ -46,15 +48,14 @@ export global UiStrings {
|
||||
in-out property <string> codec: "Video codec";
|
||||
in-out property <string> hardware-codec: "Hardware video codec";
|
||||
in-out property <string> turn-relay: "TURN relay";
|
||||
in-out property <string> srtp: "SRTP encryption";
|
||||
in-out property <string> self-hosted: "Self-hosted server";
|
||||
in-out property <string> autostart: "Start with system";
|
||||
in-out property <string> daemon: "Run in background";
|
||||
in-out property <string> privacy-on-connect: "Privacy screen on connect";
|
||||
in-out property <string> file-save-path: "File save path";
|
||||
in-out property <string> default-desktop: "Desktop";
|
||||
in-out property <string> server-host: "Server host";
|
||||
in-out property <string> server-port: "Signal port";
|
||||
in-out property <string> coturn-port: "TURN port";
|
||||
in-out property <string> version: "Version";
|
||||
in-out property <string> copyright: "© 2026 by JUNKUN DI. All right reserved.";
|
||||
in-out property <string> license: "Licensed under GNU GPL v3.";
|
||||
@@ -239,18 +240,21 @@ export component MainWindow inherits Window {
|
||||
in-out property <int> language-index: 0;
|
||||
in-out property <int> video-quality-index: 2;
|
||||
in-out property <int> frame-rate-index: 1;
|
||||
in property <bool> capture-method-visible: false;
|
||||
in-out property <int> capture-method-index: 0;
|
||||
in-out property <int> adaptation-policy-index: 1;
|
||||
in-out property <int> codec-index: 0;
|
||||
in-out property <bool> hardware-codec-enabled: true;
|
||||
in-out property <bool> turn-enabled: true;
|
||||
in-out property <bool> srtp-enabled: false;
|
||||
in-out property <bool> self-hosted-enabled: false;
|
||||
in-out property <bool> autostart-enabled: false;
|
||||
in-out property <bool> daemon-enabled: false;
|
||||
// Show the preference on every platform; only adapted hosts can change it.
|
||||
in property <bool> privacy-setting-available: false;
|
||||
in-out property <bool> privacy-on-connect-enabled: true;
|
||||
in-out property <string> file-save-path: "";
|
||||
in-out property <string> server-host: "";
|
||||
in-out property <string> server-port: "";
|
||||
in-out property <string> coturn-port: "";
|
||||
in property <bool> settings-session-active: false;
|
||||
// Keep the setting visible on every platform. Unsupported builds expose it
|
||||
// as disabled so the fixed settings layout never turns into a blank row.
|
||||
@@ -1447,6 +1451,11 @@ export component MainWindow inherits Window {
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 94px : 162px; height: 24px; text: UiStrings.language; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
CompactComboBox { x: root.compact-language ? 106px : 174px; y: 2px; model: ["中文", "English", "Русский"]; current-index <=> root.language-index; }
|
||||
}
|
||||
if root.capture-method-visible: Rectangle {
|
||||
height: 30px;
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 94px : 162px; height: 24px; text: UiStrings.capture-method; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
CompactComboBox { x: root.compact-language ? 106px : 174px; y: 2px; enabled: !root.settings-session-active; model: [UiStrings.capture-method-auto, "DXGI", "WGC", "GDI"]; current-index <=> root.capture-method-index; }
|
||||
}
|
||||
Rectangle {
|
||||
height: 30px;
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 94px : 162px; height: 24px; text: UiStrings.video-quality; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
@@ -1479,8 +1488,8 @@ export component MainWindow inherits Window {
|
||||
}
|
||||
Rectangle {
|
||||
height: 30px;
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 145px : 212px; height: 24px; text: UiStrings.srtp; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
ImGuiCheckBox { x: root.compact-language ? 157px : 224px; y: 3px; checked <=> root.srtp-enabled; enabled: !root.settings-session-active; }
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 145px : 212px; height: 24px; text: UiStrings.privacy-on-connect; color: root.privacy-setting-available ? #202124 : #8b8f95; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
ImGuiCheckBox { x: root.compact-language ? 157px : 224px; y: 3px; checked <=> root.privacy-on-connect-enabled; enabled: root.privacy-setting-available; }
|
||||
}
|
||||
Rectangle {
|
||||
height: 30px;
|
||||
@@ -1519,7 +1528,7 @@ export component MainWindow inherits Window {
|
||||
x: root.compact-language ? 190px : 140px;
|
||||
y: 105px;
|
||||
width: root.compact-language ? 260px : 360px;
|
||||
height: 168px;
|
||||
height: 138px;
|
||||
border-radius: 7px;
|
||||
|
||||
Rectangle {
|
||||
@@ -1559,21 +1568,8 @@ export component MainWindow inherits Window {
|
||||
LineEdit { x: 1px; y: 1.5px; width: parent.width - 2px; height: parent.height - 2px; text <=> root.server-port; input-type: InputType.number; font-size: ImGuiFontStyle.body; }
|
||||
LineEditFocusUnderlineMask { x: 5px; y: parent.height - 3px; width: parent.width - 10px; }
|
||||
}
|
||||
Text { x: 8px; y: 91px; width: root.compact-language ? 88px : 165px; height: 24px; text: UiStrings.coturn-port; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
Rectangle {
|
||||
x: root.compact-language ? 100px : 173px;
|
||||
y: 90px;
|
||||
width: root.compact-language ? 152px : 179px;
|
||||
height: 24px;
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
border-radius: 4px;
|
||||
LineEdit { x: 1px; y: 1.5px; width: parent.width - 2px; height: parent.height - 2px; text <=> root.coturn-port; input-type: InputType.number; font-size: ImGuiFontStyle.body; }
|
||||
LineEditFocusUnderlineMask { x: 5px; y: parent.height - 3px; width: parent.width - 10px; }
|
||||
}
|
||||
CompactButton { x: root.compact-language ? 93px : 135px; y: 130px; primary: true; text: UiStrings.ok; clicked => { root.save-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
CompactButton { x: root.compact-language ? 134px : 176px; y: 130px; width: root.compact-language ? 34px : 56px; text: UiStrings.cancel; clicked => { root.cancel-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
CompactButton { x: root.compact-language ? 93px : 135px; y: 100px; primary: true; text: UiStrings.ok; clicked => { root.save-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
CompactButton { x: root.compact-language ? 134px : 176px; y: 100px; width: root.compact-language ? 34px : 56px; text: UiStrings.cancel; clicked => { root.cancel-self-hosted-settings(); root.self-host-settings-open = false; } }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ export struct NetworkStatsRow {
|
||||
export global StreamStrings {
|
||||
in-out property <string> select-display: "Select Display";
|
||||
in-out property <string> send-shortcut: "Send Shortcut";
|
||||
in-out property <string> privacy-enable: "Enable privacy screen";
|
||||
in-out property <string> privacy-disable: "Turn privacy off / recover";
|
||||
in-out property <string> control-mouse: "Control Mouse";
|
||||
in-out property <string> release-mouse: "Release Mouse";
|
||||
in-out property <string> audio: "Audio Capture";
|
||||
@@ -43,6 +45,14 @@ export global StreamStrings {
|
||||
in-out property <string> stats-loss-rate: "Loss Rate";
|
||||
in-out property <string> stats-resolution: "Res";
|
||||
in-out property <string> stats-connection-mode: "Mode";
|
||||
in-out property <string> stats-encryption: "Encryption";
|
||||
in-out property <string> stats-encryption-enabled: "Enabled";
|
||||
in-out property <string> stats-encryption-disabled: "Disabled";
|
||||
}
|
||||
|
||||
struct ControlBarTooltip {
|
||||
text: string,
|
||||
anchor-x: length,
|
||||
}
|
||||
|
||||
// The legacy ImGui control bar uses 24px buttons with Font Awesome rendered
|
||||
@@ -54,19 +64,27 @@ component ControlBarButton inherits Rectangle {
|
||||
in property <string> tooltip: "";
|
||||
in property <bool> selected: false;
|
||||
in property <bool> slashed: false;
|
||||
in property <bool> action-enabled: true;
|
||||
// Capability and temporary command availability have different visuals.
|
||||
in property <bool> muted: false;
|
||||
in property <length> icon-size: 16px;
|
||||
out property <bool> has-hover: touch.has-hover;
|
||||
out property <ControlBarTooltip> tooltip-info: {
|
||||
text: root.visible && touch.has-hover && !touch.pressed ? root.tooltip : "",
|
||||
anchor-x: root.x + root.width / 2,
|
||||
};
|
||||
callback clicked;
|
||||
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
background: touch.pressed ? #0f87fa
|
||||
background: root.muted ? #eef0f3 : touch.pressed && root.action-enabled ? #0f87fa
|
||||
: touch.has-hover ? #4296fa
|
||||
: root.selected ? #4296fa : #4296fa66;
|
||||
border-radius: 3px;
|
||||
|
||||
Text {
|
||||
text: root.icon;
|
||||
color: #24272d;
|
||||
color: root.muted ? #8a8f96 : #24272d;
|
||||
font-family: "Font Awesome 6 Free";
|
||||
font-weight: 900;
|
||||
font-size: root.icon-size;
|
||||
@@ -105,7 +123,8 @@ component ControlBarButton inherits Rectangle {
|
||||
}
|
||||
|
||||
touch := TouchArea {
|
||||
clicked => { root.clicked(); }
|
||||
// Keep disabled controls hit-testable so clicks cannot reach the peer.
|
||||
clicked => { if root.action-enabled { root.clicked(); } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,17 +153,23 @@ export component StreamWindow inherits Window {
|
||||
in property <[string]> displays;
|
||||
in-out property <int> selected-display: 0;
|
||||
in property <bool> mouse-control-enabled: true;
|
||||
in property <bool> privacy-can-toggle: false;
|
||||
in property <bool> privacy-active: false;
|
||||
in property <bool> privacy-off: false;
|
||||
in property <bool> privacy-unsupported: false;
|
||||
// Privacy feedback stays on its toolbar button and hover tooltip.
|
||||
in property <string> privacy-status-text: "Privacy screen";
|
||||
// Numeric values mirror crossdesk::RemoteCursorShape and Slint's MouseCursor.
|
||||
in property <bool> remote-cursor-active: false;
|
||||
in property <int> remote-cursor-shape: 0;
|
||||
in property <bool> audio-enabled: true;
|
||||
in property <bool> srtp-enabled: false;
|
||||
in property <bool> fullscreen-enabled: false;
|
||||
in property <bool> stats-visible: false;
|
||||
in property <[NetworkStatsRow]> stats-rows;
|
||||
in property <string> stats-fps: "0";
|
||||
in property <string> stats-resolution: "";
|
||||
in property <string> stats-connection-mode: "";
|
||||
in property <bool> stats-encryption-enabled: false;
|
||||
in property <bool> file-transfer-visible: false;
|
||||
in property <[FileTransferEntry]> file-transfers;
|
||||
|
||||
@@ -154,6 +179,7 @@ export component StreamWindow inherits Window {
|
||||
callback switch-display(int);
|
||||
callback send-shortcut(string);
|
||||
callback toggle-mouse-control;
|
||||
callback toggle-privacy;
|
||||
callback toggle-audio;
|
||||
callback select-file;
|
||||
callback close-file-transfer;
|
||||
@@ -172,10 +198,35 @@ export component StreamWindow inherits Window {
|
||||
callback keyboard-focus-changed(bool);
|
||||
|
||||
private property <bool> control-expanded: true;
|
||||
private property <length> control-toolbar-height: 38px;
|
||||
private property <length> control-button-step: 32px;
|
||||
private property <length> stats-row-height: 18px;
|
||||
private property <length> stats-header-height: 18px;
|
||||
private property <length> stats-content-height:
|
||||
root.stats-header-height + root.stats-rows.length * root.stats-row-height + 44px;
|
||||
private property <bool> display-menu-open: false;
|
||||
private property <bool> display-menu-animation-enabled: false;
|
||||
private property <float> display-menu-progress: 0.0;
|
||||
private property <bool> shortcut-menu-open: false;
|
||||
private property <bool> control-tooltip-visible: false;
|
||||
private property <ControlBarTooltip> hovered-control: {
|
||||
if root.window-active && !root.control-dragging
|
||||
&& !root.display-menu-open && !root.shortcut-menu-open {
|
||||
if collapse-button.has-hover { return collapse-button.tooltip-info; }
|
||||
if root.control-expanded {
|
||||
if display-button.has-hover { return display-button.tooltip-info; }
|
||||
if shortcut-button.has-hover { return shortcut-button.tooltip-info; }
|
||||
if mouse-button.has-hover { return mouse-button.tooltip-info; }
|
||||
if privacy-button.has-hover { return privacy-button.tooltip-info; }
|
||||
if audio-button.has-hover { return audio-button.tooltip-info; }
|
||||
if file-button.has-hover { return file-button.tooltip-info; }
|
||||
if stats-button.has-hover { return stats-button.tooltip-info; }
|
||||
if fullscreen-button.has-hover { return fullscreen-button.tooltip-info; }
|
||||
if close-button.has-hover { return close-button.tooltip-info; }
|
||||
}
|
||||
}
|
||||
return { text: "", anchor-x: 0px };
|
||||
}
|
||||
// A popup can remove itself from the scene in its clicked callback before
|
||||
// the video input layer observes the same pointer release. Remember that
|
||||
// the press belonged to local UI so that release cannot reach the peer.
|
||||
@@ -215,6 +266,20 @@ export component StreamWindow inherits Window {
|
||||
}
|
||||
}
|
||||
|
||||
changed hovered-control => {
|
||||
root.control-tooltip-visible = false;
|
||||
control-tooltip-timer.running = root.hovered-control.text != "";
|
||||
if root.hovered-control.text != "" { control-tooltip-timer.restart(); }
|
||||
}
|
||||
control-tooltip-timer := Timer {
|
||||
interval: 450ms;
|
||||
running: false;
|
||||
triggered => {
|
||||
self.running = false;
|
||||
root.control-tooltip-visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
is-local-control-area(pointer-x, pointer-y) => {
|
||||
let over-control = pointer-x >= control.x
|
||||
&& pointer-x <= control.x + control.width
|
||||
@@ -228,11 +293,11 @@ export component StreamWindow inherits Window {
|
||||
&& pointer-x <= display-menu-x + 180px
|
||||
&& pointer-y >= display-menu-y
|
||||
&& pointer-y <= display-menu-y + display-menu-height;
|
||||
let shortcut-menu-x = control.x + (root.control-docked-left ? 41px : 74px);
|
||||
let shortcut-menu-x = control.x + shortcut-button.x;
|
||||
let shortcut-menu-y = control.y + 40px;
|
||||
let over-shortcut-menu = root.shortcut-menu-open
|
||||
&& pointer-x >= shortcut-menu-x
|
||||
&& pointer-x <= shortcut-menu-x + 150px
|
||||
&& pointer-x <= shortcut-menu-x + 180px
|
||||
&& pointer-y >= shortcut-menu-y
|
||||
&& pointer-y <= shortcut-menu-y + 68px;
|
||||
return over-control || over-display-menu || over-shortcut-menu;
|
||||
@@ -450,20 +515,8 @@ export component StreamWindow inherits Window {
|
||||
width: parent.width - 27px;
|
||||
height: parent.height;
|
||||
background: transparent;
|
||||
if root.srtp-enabled: Text {
|
||||
x: 0px;
|
||||
width: 12px;
|
||||
height: parent.height;
|
||||
text: FontAwesomeIcons.shield-halved;
|
||||
color: #30343b;
|
||||
font-family: "Font Awesome 6 Free";
|
||||
font-weight: 900;
|
||||
font-size: ImGuiFontStyle.base;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
x: root.srtp-enabled ? 16px : 0px;
|
||||
x: 0px;
|
||||
width: parent.width - self.x;
|
||||
height: parent.height;
|
||||
text: tab.title;
|
||||
@@ -639,8 +692,10 @@ export component StreamWindow inherits Window {
|
||||
control := Rectangle {
|
||||
x: root.control-dragging ? root.control-drag-x : root.control-docked-left ? 0px : parent.width - self.width;
|
||||
y: min(max(0px, root.control-pos-y), parent.height - self.height);
|
||||
width: root.control-expanded ? min(300px, parent.width) : 20px;
|
||||
height: root.stats-visible && root.control-expanded ? min(180px, parent.height) : 38px;
|
||||
width: root.control-expanded ? min(76px + 8 * root.control-button-step, parent.width) : 20px;
|
||||
height: root.stats-visible && root.control-expanded
|
||||
? min(root.control-toolbar-height + root.stats-content-height + 8px, parent.height)
|
||||
: root.control-toolbar-height;
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
@@ -657,7 +712,8 @@ export component StreamWindow inherits Window {
|
||||
background: ImGuiLineStyle.control-separator;
|
||||
}
|
||||
|
||||
if root.control-expanded: display-button := ControlBarButton {
|
||||
display-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: root.control-docked-left ? 9px : 42px; y: 7px;
|
||||
icon: FontAwesomeIcons.display;
|
||||
badge: root.selected-display + 1;
|
||||
@@ -673,8 +729,9 @@ export component StreamWindow inherits Window {
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.control-expanded: shortcut-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 41px : 74px; y: 7px;
|
||||
shortcut-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.keyboard; tooltip: StreamStrings.send-shortcut;
|
||||
clicked => {
|
||||
display-menu-open-timer.running = false;
|
||||
@@ -684,47 +741,53 @@ export component StreamWindow inherits Window {
|
||||
root.display-menu-open = false;
|
||||
}
|
||||
}
|
||||
if root.control-expanded: mouse-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 73px : 106px; y: 7px;
|
||||
mouse-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 2 * root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.computer-mouse; slashed: !root.mouse-control-enabled;
|
||||
tooltip: root.mouse-control-enabled ? StreamStrings.release-mouse : StreamStrings.control-mouse;
|
||||
clicked => { root.toggle-mouse-control(); }
|
||||
}
|
||||
if root.control-expanded: audio-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 105px : 138px; y: 7px;
|
||||
audio-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 4 * root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.volume-high; slashed: !root.audio-enabled;
|
||||
tooltip: root.audio-enabled ? StreamStrings.mute : StreamStrings.audio;
|
||||
clicked => { root.toggle-audio(); }
|
||||
}
|
||||
if root.control-expanded: file-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 137px : 170px; y: 7px;
|
||||
file-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 5 * root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.folder-open; tooltip: StreamStrings.select-file;
|
||||
clicked => { root.select-file(); }
|
||||
}
|
||||
if root.control-expanded: stats-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 169px : 202px; y: 7px;
|
||||
stats-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 6 * root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.signal; selected: root.stats-visible;
|
||||
tooltip: root.stats-visible ? StreamStrings.hide-stats : StreamStrings.show-stats;
|
||||
clicked => { root.toggle-stats(); }
|
||||
}
|
||||
if root.control-expanded: fullscreen-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 201px : 234px; y: 7px;
|
||||
fullscreen-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 7 * root.control-button-step; y: 7px;
|
||||
icon: root.fullscreen-enabled ? FontAwesomeIcons.compress : FontAwesomeIcons.expand;
|
||||
tooltip: root.fullscreen-enabled ? StreamStrings.exit-fullscreen : StreamStrings.fullscreen;
|
||||
clicked => { root.toggle-fullscreen(); }
|
||||
}
|
||||
if root.control-expanded: close-button := ControlBarButton {
|
||||
x: root.control-docked-left ? 233px : 266px; y: 7px;
|
||||
close-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 8 * root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.xmark; tooltip: StreamStrings.disconnect;
|
||||
clicked => { root.disconnect(); }
|
||||
}
|
||||
|
||||
if root.control-expanded && root.control-docked-left: Rectangle {
|
||||
x: 267px; y: 12px; width: 2px; height: 15px;
|
||||
x: parent.width - 33px; y: 12px; width: 2px; height: 15px;
|
||||
background: ImGuiLineStyle.control-separator;
|
||||
}
|
||||
collapse-button := ControlBarButton {
|
||||
x: root.control-expanded ? (root.control-docked-left ? 275px : 10px) : 2px;
|
||||
x: root.control-expanded ? (root.control-docked-left ? parent.width - 25px : 10px) : 2px;
|
||||
y: 7px;
|
||||
width: 15px;
|
||||
icon: root.control-expanded
|
||||
@@ -734,76 +797,124 @@ export component StreamWindow inherits Window {
|
||||
clicked => { root.control-expanded = !root.control-expanded; }
|
||||
}
|
||||
|
||||
privacy-button := ControlBarButton {
|
||||
visible: root.control-expanded;
|
||||
x: (root.control-docked-left ? 9px : 42px) + 3 * root.control-button-step; y: 7px;
|
||||
icon: FontAwesomeIcons.user-secret;
|
||||
slashed: root.privacy-off && !root.privacy-unsupported;
|
||||
muted: root.privacy-unsupported;
|
||||
action-enabled: root.privacy-can-toggle;
|
||||
tooltip: root.privacy-status-text
|
||||
+ (root.privacy-can-toggle ? "\n" + (root.privacy-active
|
||||
? StreamStrings.privacy-disable : StreamStrings.privacy-enable) : "");
|
||||
clicked => { root.toggle-privacy(); }
|
||||
}
|
||||
|
||||
if root.stats-visible && root.control-expanded: stats-table := Rectangle {
|
||||
x: 14px;
|
||||
y: 38px;
|
||||
width: parent.width - 28px;
|
||||
height: 128px;
|
||||
x: 8px;
|
||||
y: root.control-toolbar-height + 2px;
|
||||
width: parent.width - 16px;
|
||||
height: root.stats-content-height;
|
||||
background: transparent;
|
||||
private property <length> row-height: 16px;
|
||||
private property <length> label-column-width: 60px;
|
||||
private property <length> loss-column-width: 66px;
|
||||
private property <length> row-height: root.stats-row-height;
|
||||
private property <length> label-column-width: 50px;
|
||||
private property <length> loss-column-width:
|
||||
max((self.width - self.label-column-width) / 3,
|
||||
stats-loss-label.preferred-width + 8px);
|
||||
private property <length> value-column-width:
|
||||
(self.width - self.label-column-width - self.loss-column-width) / 2;
|
||||
private property <length> details-right-width:
|
||||
right-label-width-probe.preferred-width + 6px
|
||||
+ max(resolution-width-probe.preferred-width,
|
||||
encryption-width-probe.preferred-width
|
||||
+ (root.stats-encryption-enabled ? 14px : 0px));
|
||||
private property <length> details-right-x: self.width / 2;
|
||||
|
||||
Rectangle {
|
||||
y: 0px;
|
||||
height: 1px;
|
||||
background: ImGuiLineStyle.border;
|
||||
left-label-width-probe := Text {
|
||||
visible: false;
|
||||
text: "FPS\n" + StreamStrings.stats-connection-mode;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
}
|
||||
right-label-width-probe := Text {
|
||||
visible: false;
|
||||
text: StreamStrings.stats-resolution + "\n" + StreamStrings.stats-encryption;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
}
|
||||
resolution-width-probe := Text {
|
||||
visible: false;
|
||||
text: root.stats-resolution;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: 600;
|
||||
}
|
||||
encryption-width-probe := Text {
|
||||
visible: false;
|
||||
text: root.stats-encryption-enabled
|
||||
? StreamStrings.stats-encryption-enabled : StreamStrings.stats-encryption-disabled;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
height: stats-table.row-height;
|
||||
width: parent.width;
|
||||
height: root.stats-header-height;
|
||||
background: #f3f5f8;
|
||||
border-radius: 4px;
|
||||
Text {
|
||||
x: stats-table.label-column-width + 4px;
|
||||
width: stats-table.value-column-width - 8px;
|
||||
text: StreamStrings.stats-in;
|
||||
color: #30343b;
|
||||
color: #667085;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
x: stats-table.label-column-width + stats-table.value-column-width + 4px;
|
||||
width: stats-table.value-column-width - 8px;
|
||||
text: StreamStrings.stats-out;
|
||||
color: #30343b;
|
||||
color: #667085;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
stats-loss-label := Text {
|
||||
x: stats-table.label-column-width + stats-table.value-column-width * 2 + 4px;
|
||||
width: stats-table.loss-column-width - 8px;
|
||||
text: StreamStrings.stats-loss-rate;
|
||||
color: #30343b;
|
||||
color: #667085;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
Rectangle {
|
||||
y: parent.height - 1px;
|
||||
height: 1px;
|
||||
background: ImGuiLineStyle.border;
|
||||
}
|
||||
}
|
||||
|
||||
for row[index] in root.stats-rows: Rectangle {
|
||||
y: (index + 1) * stats-table.row-height;
|
||||
x: 0px;
|
||||
y: root.stats-header-height + index * stats-table.row-height;
|
||||
width: parent.width;
|
||||
height: stats-table.row-height;
|
||||
background: index == root.stats-rows.length - 1 ? #edf3fc : transparent;
|
||||
border-radius: 4px;
|
||||
Text {
|
||||
x: 4px;
|
||||
width: stats-table.label-column-width - 8px;
|
||||
text: row.label;
|
||||
color: #30343b;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
color: #475467;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: index == root.stats-rows.length - 1 ? 600 : 400;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
x: stats-table.label-column-width + 4px;
|
||||
width: stats-table.value-column-width - 8px;
|
||||
text: row.inbound;
|
||||
color: #30343b;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
color: #253247;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: index == root.stats-rows.length - 1 ? 600 : 400;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
@@ -811,8 +922,10 @@ export component StreamWindow inherits Window {
|
||||
x: stats-table.label-column-width + stats-table.value-column-width + 4px;
|
||||
width: stats-table.value-column-width - 8px;
|
||||
text: row.outbound;
|
||||
color: #30343b;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
color: #253247;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: index == root.stats-rows.length - 1 ? 600 : 400;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
@@ -820,46 +933,73 @@ export component StreamWindow inherits Window {
|
||||
x: stats-table.label-column-width + stats-table.value-column-width * 2 + 4px;
|
||||
width: stats-table.loss-column-width - 8px;
|
||||
text: row.loss-rate;
|
||||
color: #30343b;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
color: #475467;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: index == root.stats-rows.length - 1 ? 600 : 400;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
Rectangle {
|
||||
if index < root.stats-rows.length - 2: Rectangle {
|
||||
x: 4px;
|
||||
y: parent.height - 1px;
|
||||
width: parent.width - 8px;
|
||||
height: 1px;
|
||||
background: ImGuiLineStyle.border;
|
||||
background: #edf0f4;
|
||||
}
|
||||
}
|
||||
|
||||
for metric[index] in [
|
||||
{ label: "FPS:", value: root.stats-fps },
|
||||
{ label: StreamStrings.stats-resolution + ":", value: root.stats-resolution },
|
||||
{ label: StreamStrings.stats-connection-mode + ":", value: root.stats-connection-mode },
|
||||
{ label: "FPS", value: root.stats-fps },
|
||||
{ label: StreamStrings.stats-resolution, value: root.stats-resolution },
|
||||
{ label: StreamStrings.stats-connection-mode, value: root.stats-connection-mode },
|
||||
{ label: StreamStrings.stats-encryption, value: root.stats-encryption-enabled
|
||||
? StreamStrings.stats-encryption-enabled : StreamStrings.stats-encryption-disabled },
|
||||
]: Rectangle {
|
||||
y: (index + 5) * stats-table.row-height;
|
||||
height: stats-table.row-height;
|
||||
Text {
|
||||
x: 4px;
|
||||
width: stats-table.label-column-width - 8px;
|
||||
private property <length> encryption-icon-width:
|
||||
index == 3 && root.stats-encryption-enabled ? 14px : 0px;
|
||||
x: mod(index, 2) == 1 ? stats-table.details-right-x : 6px;
|
||||
y: root.stats-header-height + root.stats-rows.length * stats-table.row-height
|
||||
+ 2px + floor(index / 2) * 21px;
|
||||
width: mod(index, 2) == 1 ? stats-table.details-right-width
|
||||
: stats-table.details-right-x - 14px;
|
||||
height: 21px;
|
||||
metric-label := Text {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
width: mod(index, 2) == 1 ? right-label-width-probe.preferred-width
|
||||
: left-label-width-probe.preferred-width;
|
||||
height: parent.height;
|
||||
text: metric.label;
|
||||
color: #30343b;
|
||||
color: #667085;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
x: stats-table.label-column-width + 4px;
|
||||
width: stats-table.value-column-width - 8px;
|
||||
metric-value := Text {
|
||||
x: metric-label.width + 6px;
|
||||
y: 0px;
|
||||
height: parent.height;
|
||||
width: parent.width - self.x - parent.encryption-icon-width;
|
||||
text: metric.value;
|
||||
color: #30343b;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
color: index == 3 && root.stats-encryption-enabled ? #18794e : #253247;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: left;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
Rectangle {
|
||||
y: parent.height - 1px;
|
||||
height: 1px;
|
||||
background: ImGuiLineStyle.border;
|
||||
if index == 3 && root.stats-encryption-enabled: Text {
|
||||
x: metric-value.x + min(metric-value.preferred-width, metric-value.width) + 4px;
|
||||
y: metric-value.y + (metric-value.height - self.height) / 2;
|
||||
width: 10px;
|
||||
height: 12px;
|
||||
text: FontAwesomeIcons.shield-halved;
|
||||
font-family: "Font Awesome 6 Free";
|
||||
font-weight: 900;
|
||||
font-size: 10px;
|
||||
color: #238653;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -943,7 +1083,7 @@ export component StreamWindow inherits Window {
|
||||
}
|
||||
|
||||
if root.shortcut-menu-open: Rectangle {
|
||||
x: control.x + (root.control-docked-left ? 41px : 74px); y: control.y + 40px; width: 150px; height: 68px;
|
||||
x: control.x + shortcut-button.x; y: control.y + 40px; width: 180px; height: 68px;
|
||||
background: white; border-width: 1px; border-color: ImGuiLineStyle.border; border-radius: 5px; z: 11;
|
||||
VerticalLayout {
|
||||
padding: 4px; spacing: 1px;
|
||||
@@ -962,6 +1102,30 @@ export component StreamWindow inherits Window {
|
||||
}
|
||||
}
|
||||
|
||||
// Measure unwrapped text so short hints stay compact. Render outside
|
||||
// the clipped control bar, capping longer hints before wrapping.
|
||||
control-tooltip-width-probe := Text {
|
||||
visible: false;
|
||||
text: root.hovered-control.text;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
}
|
||||
if root.hovered-control.text != "" && root.control-tooltip-visible: Rectangle {
|
||||
width: min(240px, video.width - 8px,
|
||||
control-tooltip-width-probe.preferred-width + 16px);
|
||||
x: min(max(4px, control.x + root.hovered-control.anchor-x - self.width / 2),
|
||||
video.width - self.width - 4px);
|
||||
height: control-tip.preferred-height + 12px;
|
||||
// Anchor to the button row so expanded stats stay beneath the tooltip.
|
||||
y: control.y + root.control-toolbar-height + self.height + 8px <= video.height
|
||||
? control.y + root.control-toolbar-height + 4px : max(4px, control.y - self.height - 4px);
|
||||
background: #30343bf5; border-radius: 5px; z: 12;
|
||||
control-tip := Text {
|
||||
x: 8px; y: 6px; width: parent.width - 16px;
|
||||
text: root.hovered-control.text;
|
||||
color: white; font-size: ImGuiFontStyle.body; wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
|
||||
// Transfer progress overlay at bottom-left.
|
||||
if root.file-transfer-visible: Rectangle {
|
||||
x: 18px; y: parent.height - min(210px, parent.height * 0.35); width: min(430px, parent.width * 0.6); height: min(190px, parent.height * 0.32);
|
||||
|
||||
@@ -54,6 +54,9 @@ inline int ApplyMainWindowStrings(
|
||||
strings.set_language(Text(localization::language[language]));
|
||||
strings.set_video_quality(Text(localization::video_quality[language]));
|
||||
strings.set_frame_rate(Text(localization::video_frame_rate[language]));
|
||||
strings.set_capture_method(Text(localization::screen_capture_method[language]));
|
||||
strings.set_capture_method_auto(
|
||||
Text(localization::screen_capture_method_auto[language]));
|
||||
strings.set_adaptation_policy(
|
||||
Text(localization::video_adaptation_policy[language]));
|
||||
strings.set_priority_frame_rate(
|
||||
@@ -66,11 +69,11 @@ inline int ApplyMainWindowStrings(
|
||||
strings.set_hardware_codec(
|
||||
Text(localization::enable_hardware_video_codec[language]));
|
||||
strings.set_turn_relay(Text(localization::enable_turn[language]));
|
||||
strings.set_srtp(Text(localization::enable_srtp[language]));
|
||||
strings.set_self_hosted(
|
||||
Text(localization::self_hosted_server_config[language]));
|
||||
strings.set_autostart(Text(localization::enable_autostart[language]));
|
||||
strings.set_daemon(Text(localization::enable_daemon[language]));
|
||||
strings.set_privacy_on_connect(Text(localization::privacy_on_connect[language]));
|
||||
strings.set_file_save_path(
|
||||
Text(localization::file_transfer_save_path[language]));
|
||||
strings.set_default_desktop(Text(localization::default_desktop[language]));
|
||||
@@ -78,8 +81,6 @@ inline int ApplyMainWindowStrings(
|
||||
Text(localization::self_hosted_server_address[language]));
|
||||
strings.set_server_port(
|
||||
Text(localization::self_hosted_server_port[language]));
|
||||
strings.set_coturn_port(
|
||||
Text(localization::self_hosted_server_coturn_server_port[language]));
|
||||
strings.set_version(Text(localization::version[language]));
|
||||
strings.set_signal_connected(Text(localization::signal_connected[language]));
|
||||
strings.set_signal_disconnected(
|
||||
@@ -140,6 +141,8 @@ inline int ApplyStreamWindowStrings(
|
||||
auto& strings = window->template global<ui::StreamStrings>();
|
||||
strings.set_select_display(Text(localization::select_display[language]));
|
||||
strings.set_send_shortcut(Text(localization::send_shortcut[language]));
|
||||
strings.set_privacy_enable(Text(localization::privacy_enable[language]));
|
||||
strings.set_privacy_disable(Text(localization::privacy_disable[language]));
|
||||
strings.set_control_mouse(Text(localization::control_mouse[language]));
|
||||
strings.set_release_mouse(Text(localization::release_mouse[language]));
|
||||
strings.set_audio(Text(localization::audio_capture[language]));
|
||||
@@ -163,10 +166,16 @@ inline int ApplyStreamWindowStrings(
|
||||
strings.set_stats_resolution(Text(localization::resolution[language]));
|
||||
strings.set_stats_connection_mode(
|
||||
Text(localization::connection_mode[language]));
|
||||
strings.set_stats_encryption(
|
||||
Text(localization::transport_encryption[language]));
|
||||
strings.set_stats_encryption_enabled(
|
||||
Text(localization::transport_encryption_enabled[language]));
|
||||
strings.set_stats_encryption_disabled(
|
||||
Text(localization::transport_encryption_disabled[language]));
|
||||
return language;
|
||||
}
|
||||
|
||||
} // namespace crossdesk::ui_localization
|
||||
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -268,25 +268,6 @@ int GuiApplication::SettingWindow() {
|
||||
|
||||
ImGui::Separator();
|
||||
|
||||
{
|
||||
settings_items_offset += settings_items_padding;
|
||||
ImGui::SetCursorPosY(settings_items_offset);
|
||||
ImGui::AlignTextToFramePadding();
|
||||
ImGui::Text(
|
||||
"%s",
|
||||
localization::enable_srtp[localization_language_index_].c_str());
|
||||
ImGui::SameLine();
|
||||
if (ConfigCenter::LANGUAGE::CHINESE == localization_language_) {
|
||||
ImGui::SetCursorPosX(title_bar_button_width_ * 4.275f);
|
||||
} else {
|
||||
ImGui::SetCursorPosX(title_bar_button_width_ * 5.955f);
|
||||
}
|
||||
|
||||
ImGui::Checkbox("##enable_srtp", &enable_srtp_);
|
||||
}
|
||||
|
||||
ImGui::Separator();
|
||||
|
||||
{
|
||||
settings_items_offset += settings_items_padding;
|
||||
ImGui::SetCursorPosY(settings_items_offset + 1);
|
||||
@@ -569,14 +550,6 @@ int GuiApplication::SettingWindow() {
|
||||
}
|
||||
enable_turn_last_ = enable_turn_;
|
||||
|
||||
// SRTP
|
||||
if (enable_srtp_) {
|
||||
config_center_->SetSrtp(true);
|
||||
} else {
|
||||
config_center_->SetSrtp(false);
|
||||
}
|
||||
enable_srtp_last_ = enable_srtp_;
|
||||
|
||||
if (enable_self_hosted_) {
|
||||
config_center_->SetSelfHosted(true);
|
||||
} else {
|
||||
|
||||
@@ -36,12 +36,12 @@ int GuiApplication::SelfHostedServerWindow() {
|
||||
ImGui::SetNextWindowPos(
|
||||
ImVec2(io.DisplaySize.x * 0.298f, io.DisplaySize.y * 0.25f));
|
||||
ImGui::SetNextWindowSize(
|
||||
ImVec2(io.DisplaySize.x * 0.407f, io.DisplaySize.y * 0.35f));
|
||||
ImVec2(io.DisplaySize.x * 0.407f, io.DisplaySize.y * 0.29f));
|
||||
} else {
|
||||
ImGui::SetNextWindowPos(
|
||||
ImVec2(io.DisplaySize.x * 0.27f, io.DisplaySize.y * 0.3f));
|
||||
ImGui::SetNextWindowSize(
|
||||
ImVec2(io.DisplaySize.x * 0.465f, io.DisplaySize.y * 0.35f));
|
||||
ImVec2(io.DisplaySize.x * 0.465f, io.DisplaySize.y * 0.29f));
|
||||
}
|
||||
|
||||
self_hosted_server_config_window_pos_reset_ = false;
|
||||
@@ -101,25 +101,6 @@ int GuiApplication::SelfHostedServerWindow() {
|
||||
IM_ARRAYSIZE(signal_server_port_self_));
|
||||
}
|
||||
|
||||
ImGui::Separator();
|
||||
|
||||
{
|
||||
ImGui::AlignTextToFramePadding();
|
||||
ImGui::Text("%s", localization::self_hosted_server_coturn_server_port
|
||||
[localization_language_index_]
|
||||
.c_str());
|
||||
ImGui::SameLine();
|
||||
if (ConfigCenter::LANGUAGE::CHINESE == localization_language_) {
|
||||
ImGui::SetCursorPosX(title_bar_button_width_ * 2.5f);
|
||||
} else {
|
||||
ImGui::SetCursorPosX(title_bar_button_width_ * 3.43f);
|
||||
}
|
||||
ImGui::SetNextItemWidth(title_bar_button_width_ * 3.8f);
|
||||
|
||||
ImGui::InputText("##coturn_server_port_self_", coturn_server_port_self_,
|
||||
IM_ARRAYSIZE(coturn_server_port_self_));
|
||||
}
|
||||
|
||||
if (stream_window_inited_) {
|
||||
ImGui::EndDisabled();
|
||||
}
|
||||
@@ -141,17 +122,12 @@ int GuiApplication::SelfHostedServerWindow() {
|
||||
|
||||
config_center_->SetServerHost(signal_server_ip_self_);
|
||||
config_center_->SetServerPort(atoi(signal_server_port_self_));
|
||||
config_center_->SetCoturnServerPort(atoi(coturn_server_port_self_));
|
||||
strncpy(signal_server_ip_, signal_server_ip_self_,
|
||||
sizeof(signal_server_ip_) - 1);
|
||||
signal_server_ip_[sizeof(signal_server_ip_) - 1] = '\0';
|
||||
strncpy(signal_server_port_, signal_server_port_self_,
|
||||
sizeof(signal_server_port_) - 1);
|
||||
signal_server_port_[sizeof(signal_server_port_) - 1] = '\0';
|
||||
strncpy(coturn_server_port_, coturn_server_port_self_,
|
||||
sizeof(coturn_server_port_) - 1);
|
||||
coturn_server_port_[sizeof(coturn_server_port_) - 1] = '\0';
|
||||
|
||||
self_hosted_server_config_window_pos_reset_ = true;
|
||||
}
|
||||
|
||||
@@ -173,14 +149,6 @@ int GuiApplication::SelfHostedServerWindow() {
|
||||
} else {
|
||||
signal_server_port_self_[0] = '\0';
|
||||
}
|
||||
int coturn_port = config_center_->GetCoturnServerPort();
|
||||
if (coturn_port > 0) {
|
||||
strncpy(coturn_server_port_self_, std::to_string(coturn_port).c_str(),
|
||||
sizeof(coturn_server_port_self_) - 1);
|
||||
coturn_server_port_self_[sizeof(coturn_server_port_self_) - 1] = '\0';
|
||||
} else {
|
||||
coturn_server_port_self_[0] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
|
||||
@@ -136,10 +136,7 @@ int GuiApplication::StreamWindow() {
|
||||
continue;
|
||||
}
|
||||
|
||||
std::string tab_label =
|
||||
enable_srtp_
|
||||
? std::string(ICON_FA_SHIELD_HALVED) + " " + props->remote_id_
|
||||
: props->remote_id_;
|
||||
const std::string& tab_label = props->remote_id_;
|
||||
if (ImGui::BeginTabItem(tab_label.c_str(), &props->tab_opened_)) {
|
||||
props->tab_selected_ = true;
|
||||
ImGui::SetWindowFontScale(0.6f);
|
||||
@@ -308,4 +305,4 @@ int GuiApplication::StreamWindow() {
|
||||
|
||||
return 0;
|
||||
}
|
||||
} // namespace crossdesk
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#include "rd_log.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -9,26 +8,38 @@ namespace {
|
||||
|
||||
std::string g_log_dir = "logs";
|
||||
std::once_flag g_logger_once_flag;
|
||||
std::mutex g_logger_mutex;
|
||||
std::shared_ptr<spdlog::logger> g_logger;
|
||||
std::atomic<bool> g_logger_created{false};
|
||||
|
||||
std::string NormalizeLogDirectory(const std::string& log_dir) {
|
||||
const std::filesystem::path path = log_dir.empty() ? "logs" : log_dir;
|
||||
std::error_code ec;
|
||||
const auto absolute = std::filesystem::absolute(path, ec);
|
||||
return (ec ? path : absolute).lexically_normal().string();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void InitLogger(const std::string& log_dir) {
|
||||
if (g_logger_created.load()) {
|
||||
LOG_WARN(
|
||||
"InitLogger called after logger initialized. Ignoring log_dir: {}, "
|
||||
"using previous log_dir: {}",
|
||||
log_dir, g_log_dir);
|
||||
const auto directory = NormalizeLogDirectory(log_dir);
|
||||
std::lock_guard<std::mutex> lock(g_logger_mutex);
|
||||
if (g_logger) {
|
||||
if (directory != g_log_dir) {
|
||||
g_logger->warn(
|
||||
"InitLogger called after logger initialized. Ignoring log_dir: {}, "
|
||||
"using previous log_dir: {}",
|
||||
directory, g_log_dir);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
g_log_dir = log_dir;
|
||||
g_log_dir = directory;
|
||||
}
|
||||
|
||||
std::shared_ptr<spdlog::logger> get_logger() {
|
||||
std::call_once(g_logger_once_flag, []() {
|
||||
g_logger_created.store(true);
|
||||
std::lock_guard<std::mutex> lock(g_logger_mutex);
|
||||
g_log_dir = NormalizeLogDirectory(g_log_dir);
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(g_log_dir, ec);
|
||||
@@ -54,10 +65,12 @@ std::shared_ptr<spdlog::logger> get_logger() {
|
||||
sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
|
||||
filename, 5 * 1024 * 1024, 3));
|
||||
|
||||
g_logger = std::make_shared<spdlog::logger>(LOGGER_NAME, sinks.begin(),
|
||||
sinks.end());
|
||||
g_logger->flush_on(spdlog::level::info);
|
||||
spdlog::register_logger(g_logger);
|
||||
auto logger = std::make_shared<spdlog::logger>(LOGGER_NAME, sinks.begin(),
|
||||
sinks.end());
|
||||
logger->flush_on(spdlog::level::info);
|
||||
spdlog::register_logger(logger);
|
||||
logger->info("Logger initialized: path={}", filename);
|
||||
g_logger = std::move(logger);
|
||||
});
|
||||
|
||||
return g_logger;
|
||||
|
||||
@@ -122,6 +122,11 @@ struct OpenGlFunctions {
|
||||
PFNGLUNIFORM4FPROC uniform_4f = nullptr;
|
||||
PFNGLUSEPROGRAMPROC use_program = nullptr;
|
||||
PFNGLVERTEXATTRIBPOINTERPROC vertex_attrib_pointer = nullptr;
|
||||
PFNGLGENFRAMEBUFFERSPROC gen_framebuffers = nullptr;
|
||||
PFNGLDELETEFRAMEBUFFERSPROC delete_framebuffers = nullptr;
|
||||
PFNGLBINDFRAMEBUFFERPROC bind_framebuffer = nullptr;
|
||||
PFNGLFRAMEBUFFERTEXTURE2DPROC framebuffer_texture_2d = nullptr;
|
||||
PFNGLCHECKFRAMEBUFFERSTATUSPROC check_framebuffer_status = nullptr;
|
||||
#if CROSSDESK_OPENGL_CUDA_INTEROP
|
||||
PFNGLFENCESYNCPROC fence_sync = nullptr;
|
||||
PFNGLCLIENTWAITSYNCPROC client_wait_sync = nullptr;
|
||||
@@ -163,6 +168,15 @@ struct OpenGlFunctions {
|
||||
LoadOpenGlFunction(&vertex_attrib_pointer, "glVertexAttribPointer");
|
||||
}
|
||||
|
||||
bool LoadFramebufferFunctions() {
|
||||
return LoadOpenGlFunction(&gen_framebuffers, "glGenFramebuffers") &&
|
||||
LoadOpenGlFunction(&delete_framebuffers, "glDeleteFramebuffers") &&
|
||||
LoadOpenGlFunction(&bind_framebuffer, "glBindFramebuffer") &&
|
||||
LoadOpenGlFunction(&framebuffer_texture_2d, "glFramebufferTexture2D") &&
|
||||
LoadOpenGlFunction(&check_framebuffer_status,
|
||||
"glCheckFramebufferStatus");
|
||||
}
|
||||
|
||||
#if CROSSDESK_OPENGL_CUDA_INTEROP
|
||||
bool LoadSyncFunctions() {
|
||||
return LoadOpenGlFunction(&fence_sync, "glFenceSync") &&
|
||||
@@ -287,6 +301,17 @@ struct OpenGlVideoRenderer::Impl {
|
||||
GLint video_rect_location = -1;
|
||||
GLint corner_radius_location = -1;
|
||||
GLint video_enabled_location = -1;
|
||||
GLint source_size_location = -1;
|
||||
GLint filter_direction_location = -1;
|
||||
GLint packed_video_location = -1;
|
||||
GLuint scale_framebuffer = 0;
|
||||
std::array<GLuint, 2> scale_textures{};
|
||||
std::array<std::pair<int, int>, 2> scale_sizes{};
|
||||
uint64_t scaled_sequence = 0;
|
||||
bool scaling_available = false;
|
||||
GLenum framebuffer_target = GL_FRAMEBUFFER;
|
||||
GLenum framebuffer_binding = GL_FRAMEBUFFER_BINDING;
|
||||
std::array<int, 4> logged_render_size{};
|
||||
int texture_width = 0;
|
||||
int texture_height = 0;
|
||||
int cpu_texture_width = 0;
|
||||
@@ -504,6 +529,116 @@ struct OpenGlVideoRenderer::Impl {
|
||||
}
|
||||
#endif
|
||||
|
||||
// The vertex buffer and program are shared with the final underlay draw.
|
||||
void DrawVideo(GLuint y, GLuint uv, int source_width, int source_height,
|
||||
int target_width, int target_height, int video_x, int video_y,
|
||||
int video_width, int video_height, int corner_radius,
|
||||
bool enabled, bool packed, float filter_x = 0.0f,
|
||||
float filter_y = 0.0f) {
|
||||
gl.active_texture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, y);
|
||||
gl.active_texture(GL_TEXTURE1);
|
||||
glBindTexture(GL_TEXTURE_2D, uv);
|
||||
gl.uniform_2f(source_size_location, static_cast<GLfloat>(source_width),
|
||||
static_cast<GLfloat>(source_height));
|
||||
gl.uniform_2f(target_size_location, static_cast<GLfloat>(target_width),
|
||||
static_cast<GLfloat>(target_height));
|
||||
gl.uniform_4f(video_rect_location, static_cast<GLfloat>(video_x),
|
||||
static_cast<GLfloat>(video_y), static_cast<GLfloat>(video_width),
|
||||
static_cast<GLfloat>(video_height));
|
||||
gl.uniform_1f(corner_radius_location, static_cast<GLfloat>(corner_radius));
|
||||
gl.uniform_1f(video_enabled_location, enabled ? 1.0f : 0.0f);
|
||||
gl.uniform_1f(packed_video_location, packed ? 1.0f : 0.0f);
|
||||
gl.uniform_2f(filter_direction_location, filter_x, filter_y);
|
||||
glViewport(0, 0, target_width, target_height);
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
bool PrepareScaleTarget(size_t index, int width, int height) {
|
||||
gl.active_texture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, scale_textures[index]);
|
||||
if (scale_sizes[index] != std::pair{width, height}) {
|
||||
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
|
||||
GL_UNSIGNED_BYTE, nullptr);
|
||||
scale_sizes[index] = {width, height};
|
||||
}
|
||||
gl.framebuffer_texture_2d(framebuffer_target, GL_COLOR_ATTACHMENT0,
|
||||
GL_TEXTURE_2D, scale_textures[index], 0);
|
||||
return gl.check_framebuffer_status(framebuffer_target) ==
|
||||
GL_FRAMEBUFFER_COMPLETE &&
|
||||
glGetError() == GL_NO_ERROR;
|
||||
}
|
||||
|
||||
bool ScaleVideo(GLuint y, GLuint uv, int width, int height, int output_width,
|
||||
int output_height) {
|
||||
if (!scaling_available) {
|
||||
return false;
|
||||
}
|
||||
if (scaled_sequence == uploaded_sequence &&
|
||||
scale_sizes[1] == std::pair{output_width, output_height}) {
|
||||
return true;
|
||||
}
|
||||
|
||||
GLint previous_framebuffer = 0;
|
||||
glGetIntegerv(framebuffer_binding, &previous_framebuffer);
|
||||
if (scale_framebuffer == 0) {
|
||||
gl.gen_framebuffers(1, &scale_framebuffer);
|
||||
glGenTextures(static_cast<GLsizei>(scale_textures.size()),
|
||||
scale_textures.data());
|
||||
gl.active_texture(GL_TEXTURE0);
|
||||
for (const GLuint texture : scale_textures) {
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
}
|
||||
}
|
||||
// A CUDA upload may have left its PBO bound: nullptr below allocates empty
|
||||
// render targets and must never be interpreted as a PBO byte offset.
|
||||
if (pixel_unpack_buffer_available) {
|
||||
gl.bind_buffer(GL_PIXEL_UNPACK_BUFFER, 0);
|
||||
}
|
||||
gl.bind_framebuffer(framebuffer_target, scale_framebuffer);
|
||||
bool success = scale_framebuffer != 0 && scale_textures[0] != 0 &&
|
||||
scale_textures[1] != 0;
|
||||
bool packed = false;
|
||||
while (success && (width != output_width || height != output_height)) {
|
||||
// Bound shader work without truncating the filter for very small windows.
|
||||
const int next_width = std::max(output_width, (width + 3) / 4);
|
||||
const int next_height = std::max(output_height, (height + 3) / 4);
|
||||
if (!PrepareScaleTarget(0, next_width, height)) {
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
DrawVideo(y, uv, width, height, next_width, height, 0, 0, next_width,
|
||||
height, 0, true, packed, 1.0f, 0.0f);
|
||||
if (!PrepareScaleTarget(1, next_width, next_height)) {
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
DrawVideo(scale_textures[0], uv, next_width, height, next_width,
|
||||
next_height, 0, 0, next_width, next_height, 0, true, true,
|
||||
0.0f, 1.0f);
|
||||
success = glGetError() == GL_NO_ERROR;
|
||||
y = scale_textures[1];
|
||||
width = next_width;
|
||||
height = next_height;
|
||||
packed = true;
|
||||
}
|
||||
gl.bind_framebuffer(framebuffer_target,
|
||||
static_cast<GLuint>(previous_framebuffer));
|
||||
if (!success) {
|
||||
scaling_available = false;
|
||||
while (glGetError() != GL_NO_ERROR) {
|
||||
}
|
||||
LOG_WARN("OpenGL video downsampling unavailable; using linear sampling");
|
||||
return false;
|
||||
}
|
||||
scaled_sequence = uploaded_sequence;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ResetGlHandles() {
|
||||
program = 0;
|
||||
vertex_buffer = 0;
|
||||
@@ -517,6 +652,15 @@ struct OpenGlVideoRenderer::Impl {
|
||||
video_rect_location = -1;
|
||||
corner_radius_location = -1;
|
||||
video_enabled_location = -1;
|
||||
source_size_location = -1;
|
||||
filter_direction_location = -1;
|
||||
packed_video_location = -1;
|
||||
scale_framebuffer = 0;
|
||||
scale_textures = {};
|
||||
scale_sizes = {};
|
||||
scaled_sequence = 0;
|
||||
scaling_available = false;
|
||||
logged_render_size = {};
|
||||
texture_width = 0;
|
||||
texture_height = 0;
|
||||
cpu_texture_width = 0;
|
||||
@@ -559,6 +703,10 @@ bool OpenGlVideoRenderer::Setup() {
|
||||
HasOpenGlExtension(extensions, "GL_ARB_pixel_buffer_object")));
|
||||
impl_->unpack_subimage_available = !is_gles || major >= 3 ||
|
||||
HasOpenGlExtension(extensions, "GL_EXT_unpack_subimage");
|
||||
impl_->scaling_available = impl_->gl.LoadFramebufferFunctions();
|
||||
impl_->framebuffer_target = major >= 3 ? GL_DRAW_FRAMEBUFFER : GL_FRAMEBUFFER;
|
||||
impl_->framebuffer_binding =
|
||||
major >= 3 ? GL_DRAW_FRAMEBUFFER_BINDING : GL_FRAMEBUFFER_BINDING;
|
||||
#if CROSSDESK_OPENGL_CUDA_INTEROP
|
||||
// GLX may return entry points even if the current GLES 2 context cannot
|
||||
// use them. Gate CUDA interop on context capabilities as well as symbols.
|
||||
@@ -577,8 +725,8 @@ bool OpenGlVideoRenderer::Setup() {
|
||||
}
|
||||
#endif
|
||||
|
||||
static constexpr char kGlesVertexShader[] = R"glsl(
|
||||
#version 100
|
||||
const std::string vertex_source =
|
||||
std::string(is_gles ? "#version 100\n" : "#version 110\n") + R"glsl(
|
||||
attribute vec2 position;
|
||||
attribute vec2 texcoord;
|
||||
varying vec2 video_texcoord;
|
||||
@@ -587,20 +735,56 @@ void main() {
|
||||
gl_Position = vec4(position, 0.0, 1.0);
|
||||
}
|
||||
)glsl";
|
||||
static constexpr char kGlesFragmentShader[] = R"glsl(
|
||||
#version 100
|
||||
#ifdef GL_FRAGMENT_PRECISION_HIGH
|
||||
precision highp float;
|
||||
#else
|
||||
precision mediump float;
|
||||
#endif
|
||||
const std::string fragment_source =
|
||||
std::string(is_gles ? "#version 100\n"
|
||||
"#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
|
||||
"precision highp float;\n"
|
||||
"#else\nprecision mediump float;\n#endif\n"
|
||||
: "#version 110\n") + R"glsl(
|
||||
uniform sampler2D y_texture;
|
||||
uniform sampler2D uv_texture;
|
||||
uniform vec2 target_size;
|
||||
uniform vec2 source_size;
|
||||
uniform vec2 filter_direction;
|
||||
uniform float packed_video;
|
||||
uniform vec4 video_rect;
|
||||
uniform float corner_radius;
|
||||
uniform float video_enabled;
|
||||
varying vec2 video_texcoord;
|
||||
// A separable Lanczos-2 low-pass filter. Each pass reduces by at most 4x,
|
||||
// so 16 taps cover its complete support even for non-integer scale ratios.
|
||||
float lanczos2(float x) {
|
||||
x = abs(x);
|
||||
if (x < 0.0001) return 1.0;
|
||||
if (x >= 2.0) return 0.0;
|
||||
float p = 3.14159265359 * x;
|
||||
return sin(p) * sin(p * 0.5) / (p * p * 0.5);
|
||||
}
|
||||
vec4 sample_plane(sampler2D plane, vec2 size, vec2 coord) {
|
||||
// FBO textures have the opposite vertical origin to the decoded NV12 planes.
|
||||
if (packed_video > 0.5) coord.y = 1.0 - coord.y;
|
||||
if (filter_direction.x + filter_direction.y < 0.5)
|
||||
return texture2D(plane, coord);
|
||||
float scale = max(1.0, dot(size / video_rect.zw, filter_direction));
|
||||
float center = dot(coord * size - vec2(0.5), filter_direction);
|
||||
float first = floor(center - 2.0 * scale) + 1.0;
|
||||
vec4 sum = vec4(0.0);
|
||||
float weight_sum = 0.0;
|
||||
for (int tap = 0; tap < 16; ++tap) {
|
||||
float offset = first + float(tap) - center;
|
||||
if (offset >= 2.0 * scale) break;
|
||||
float weight = lanczos2(offset / scale);
|
||||
sum += weight * texture2D(plane, coord + filter_direction * offset / size);
|
||||
weight_sum += weight;
|
||||
}
|
||||
return sum / weight_sum;
|
||||
}
|
||||
vec3 sample_video(vec2 coord) {
|
||||
vec4 y_sample = sample_plane(y_texture, source_size, coord);
|
||||
if (packed_video > 0.5) return y_sample.rgb;
|
||||
return vec3(y_sample.r,
|
||||
sample_plane(uv_texture, source_size * 0.5, coord).ra);
|
||||
}
|
||||
void main() {
|
||||
vec2 surface_point = video_texcoord * target_size;
|
||||
vec3 rgb = vec3(0.0);
|
||||
@@ -611,10 +795,14 @@ void main() {
|
||||
surface_point.y <= video_rect.y + video_rect.w) {
|
||||
vec2 frame_texcoord =
|
||||
(surface_point - video_rect.xy) / video_rect.zw;
|
||||
float y = 1.16438356 *
|
||||
(texture2D(y_texture, frame_texcoord).r - 16.0 / 255.0);
|
||||
vec2 uv =
|
||||
texture2D(uv_texture, frame_texcoord).ra - vec2(0.5, 0.5);
|
||||
vec3 yuv = sample_video(frame_texcoord);
|
||||
if (filter_direction.x + filter_direction.y > 0.5) {
|
||||
// Intermediate RGBA textures carry Y/U/V until the final conversion.
|
||||
gl_FragColor = vec4(yuv, 1.0);
|
||||
return;
|
||||
}
|
||||
float y = 1.16438356 * (yuv.x - 16.0 / 255.0);
|
||||
vec2 uv = yuv.yz - vec2(0.5);
|
||||
rgb = clamp(vec3(y + 1.59602678 * uv.y,
|
||||
y - 0.39176229 * uv.x - 0.81296764 * uv.y,
|
||||
y + 2.01723214 * uv.x),
|
||||
@@ -633,67 +821,11 @@ void main() {
|
||||
gl_FragColor = vec4(rgb * coverage, coverage);
|
||||
}
|
||||
)glsl";
|
||||
static constexpr char kDesktopVertexShader[] = R"glsl(
|
||||
#version 110
|
||||
attribute vec2 position;
|
||||
attribute vec2 texcoord;
|
||||
varying vec2 video_texcoord;
|
||||
void main() {
|
||||
video_texcoord = texcoord;
|
||||
gl_Position = vec4(position, 0.0, 1.0);
|
||||
}
|
||||
)glsl";
|
||||
static constexpr char kDesktopFragmentShader[] = R"glsl(
|
||||
#version 110
|
||||
uniform sampler2D y_texture;
|
||||
uniform sampler2D uv_texture;
|
||||
uniform vec2 target_size;
|
||||
uniform vec4 video_rect;
|
||||
uniform float corner_radius;
|
||||
uniform float video_enabled;
|
||||
varying vec2 video_texcoord;
|
||||
void main() {
|
||||
vec2 surface_point = video_texcoord * target_size;
|
||||
vec3 rgb = vec3(0.0);
|
||||
if (video_enabled > 0.5 &&
|
||||
surface_point.x >= video_rect.x &&
|
||||
surface_point.x <= video_rect.x + video_rect.z &&
|
||||
surface_point.y >= video_rect.y &&
|
||||
surface_point.y <= video_rect.y + video_rect.w) {
|
||||
vec2 frame_texcoord =
|
||||
(surface_point - video_rect.xy) / video_rect.zw;
|
||||
float y = 1.16438356 *
|
||||
(texture2D(y_texture, frame_texcoord).r - 16.0 / 255.0);
|
||||
vec2 uv =
|
||||
texture2D(uv_texture, frame_texcoord).ra - vec2(0.5, 0.5);
|
||||
rgb = clamp(vec3(y + 1.59602678 * uv.y,
|
||||
y - 0.39176229 * uv.x - 0.81296764 * uv.y,
|
||||
y + 2.01723214 * uv.x),
|
||||
0.0, 1.0);
|
||||
}
|
||||
float coverage = 1.0;
|
||||
if (corner_radius > 0.0) {
|
||||
vec2 half_size = target_size * 0.5;
|
||||
vec2 corner = abs(surface_point - half_size) -
|
||||
(half_size - vec2(corner_radius));
|
||||
float distance_to_edge =
|
||||
length(max(corner, vec2(0.0))) +
|
||||
min(max(corner.x, corner.y), 0.0) - corner_radius;
|
||||
coverage = clamp(0.5 - distance_to_edge, 0.0, 1.0);
|
||||
}
|
||||
gl_FragColor = vec4(rgb * coverage, coverage);
|
||||
}
|
||||
)glsl";
|
||||
|
||||
const char *vertex_source =
|
||||
is_gles ? kGlesVertexShader : kDesktopVertexShader;
|
||||
const char *fragment_source =
|
||||
is_gles ? kGlesFragmentShader : kDesktopFragmentShader;
|
||||
|
||||
const GLuint vertex_shader =
|
||||
CompileShader(impl_->gl, GL_VERTEX_SHADER, vertex_source);
|
||||
CompileShader(impl_->gl, GL_VERTEX_SHADER, vertex_source.c_str());
|
||||
const GLuint fragment_shader =
|
||||
CompileShader(impl_->gl, GL_FRAGMENT_SHADER, fragment_source);
|
||||
CompileShader(impl_->gl, GL_FRAGMENT_SHADER, fragment_source.c_str());
|
||||
if (vertex_shader == 0 || fragment_shader == 0) {
|
||||
if (vertex_shader != 0)
|
||||
impl_->gl.delete_shader(vertex_shader);
|
||||
@@ -743,11 +875,18 @@ void main() {
|
||||
impl_->gl.get_uniform_location(impl_->program, "corner_radius");
|
||||
impl_->video_enabled_location =
|
||||
impl_->gl.get_uniform_location(impl_->program, "video_enabled");
|
||||
impl_->source_size_location =
|
||||
impl_->gl.get_uniform_location(impl_->program, "source_size");
|
||||
impl_->filter_direction_location =
|
||||
impl_->gl.get_uniform_location(impl_->program, "filter_direction");
|
||||
impl_->packed_video_location =
|
||||
impl_->gl.get_uniform_location(impl_->program, "packed_video");
|
||||
if (impl_->position_location < 0 || impl_->texcoord_location < 0 ||
|
||||
impl_->y_texture_location < 0 || impl_->uv_texture_location < 0 ||
|
||||
impl_->target_size_location < 0 || impl_->video_rect_location < 0 ||
|
||||
impl_->corner_radius_location < 0 ||
|
||||
impl_->video_enabled_location < 0) {
|
||||
impl_->video_enabled_location < 0 || impl_->source_size_location < 0 ||
|
||||
impl_->filter_direction_location < 0 || impl_->packed_video_location < 0) {
|
||||
LOG_ERROR("OpenGL NV12 program is missing required shader bindings");
|
||||
impl_->gl.delete_program(impl_->program);
|
||||
impl_->ResetGlHandles();
|
||||
@@ -817,6 +956,11 @@ void main() {
|
||||
|
||||
void OpenGlVideoRenderer::Teardown() {
|
||||
impl_->ready.store(false, std::memory_order_release);
|
||||
if (impl_->scale_framebuffer != 0) {
|
||||
impl_->gl.delete_framebuffers(1, &impl_->scale_framebuffer);
|
||||
}
|
||||
glDeleteTextures(static_cast<GLsizei>(impl_->scale_textures.size()),
|
||||
impl_->scale_textures.data());
|
||||
#if CROSSDESK_OPENGL_CUDA_INTEROP
|
||||
impl_->ReleaseCudaInterop();
|
||||
#endif
|
||||
@@ -1356,24 +1500,8 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
|
||||
}
|
||||
#endif
|
||||
impl_->gl.use_program(impl_->program);
|
||||
impl_->gl.active_texture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, displayed_y_texture);
|
||||
impl_->gl.uniform_1i(impl_->y_texture_location, 0);
|
||||
impl_->gl.active_texture(GL_TEXTURE1);
|
||||
glBindTexture(GL_TEXTURE_2D, displayed_uv_texture);
|
||||
impl_->gl.uniform_1i(impl_->uv_texture_location, 1);
|
||||
impl_->gl.uniform_2f(impl_->target_size_location,
|
||||
static_cast<GLfloat>(target_width),
|
||||
static_cast<GLfloat>(target_height));
|
||||
impl_->gl.uniform_4f(
|
||||
impl_->video_rect_location, static_cast<GLfloat>(video_x),
|
||||
static_cast<GLfloat>(video_y), static_cast<GLfloat>(video_width),
|
||||
static_cast<GLfloat>(video_height));
|
||||
impl_->gl.uniform_1f(
|
||||
impl_->corner_radius_location,
|
||||
static_cast<GLfloat>(std::clamp(
|
||||
corner_radius_pixels, 0, std::min(target_width, target_height) / 2)));
|
||||
impl_->gl.uniform_1f(impl_->video_enabled_location, has_video ? 1.0f : 0.0f);
|
||||
impl_->gl.bind_buffer(GL_ARRAY_BUFFER, impl_->vertex_buffer);
|
||||
impl_->gl.vertex_attrib_pointer(
|
||||
static_cast<GLuint>(impl_->position_location), 2, GL_FLOAT, GL_FALSE,
|
||||
@@ -1386,7 +1514,25 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
|
||||
static_cast<GLuint>(impl_->position_location));
|
||||
impl_->gl.enable_vertex_attrib_array(
|
||||
static_cast<GLuint>(impl_->texcoord_location));
|
||||
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
|
||||
const bool downscaled = has_video &&
|
||||
(source_width > video_width || source_height > video_height) &&
|
||||
impl_->ScaleVideo(displayed_y_texture, displayed_uv_texture, source_width,
|
||||
source_height, video_width, video_height);
|
||||
impl_->DrawVideo(
|
||||
downscaled ? impl_->scale_textures[1] : displayed_y_texture,
|
||||
displayed_uv_texture, downscaled ? video_width : source_width,
|
||||
downscaled ? video_height : source_height, target_width, target_height,
|
||||
video_x, video_y, video_width, video_height,
|
||||
std::clamp(corner_radius_pixels, 0, std::min(target_width, target_height) / 2),
|
||||
has_video, downscaled);
|
||||
const std::array<int, 4> render_size{
|
||||
source_width, source_height, video_width, video_height};
|
||||
if (has_video && impl_->logged_render_size != render_size) {
|
||||
LOG_INFO("OpenGL video presentation: source={}x{}, display={}x{} physical "
|
||||
"pixels, filter={}", source_width, source_height, video_width,
|
||||
video_height, downscaled ? "Lanczos2" : "linear");
|
||||
impl_->logged_render_size = render_size;
|
||||
}
|
||||
#if CROSSDESK_OPENGL_CUDA_INTEROP
|
||||
if (impl_->displayed_cuda_upload_slot < impl_->cuda_upload_slots.size()) {
|
||||
auto &cuda_slot =
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
namespace crossdesk {
|
||||
|
||||
void GuiRuntime::ResetRemoteServiceStatus(RemoteSession& props) {
|
||||
{
|
||||
std::lock_guard lock(props.privacy_status_mutex_);
|
||||
props.privacy_status_ = {};
|
||||
props.privacy_status_received_ = false;
|
||||
props.privacy_command_pending_ = false;
|
||||
props.privacy_status_tick_ = 0;
|
||||
}
|
||||
props.remote_service_status_received_ = false;
|
||||
props.remote_service_available_ = false;
|
||||
props.remote_interactive_stage_.clear();
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
#include "keyboard_capturer.h"
|
||||
|
||||
#include <X11/XKBlib.h>
|
||||
#include <X11/Xatom.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/extensions/XInput2.h>
|
||||
#include <X11/extensions/XTest.h>
|
||||
#include <X11/keysym.h>
|
||||
|
||||
#include <array>
|
||||
#include <exception>
|
||||
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
|
||||
@@ -15,9 +21,6 @@
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
static OnKeyAction g_on_key_action = nullptr;
|
||||
static void* g_user_ptr = nullptr;
|
||||
|
||||
static KeyCode ResolveX11Keycode(Display* display, int key_code,
|
||||
uint32_t scan_code, bool extended) {
|
||||
if (!display) {
|
||||
@@ -59,36 +62,8 @@ static KeySym NormalizeKeySym(KeySym key_sym) {
|
||||
return key_sym;
|
||||
}
|
||||
|
||||
static int KeyboardEventHandler(Display* display, XEvent* event) {
|
||||
(void)display;
|
||||
if (event->xkey.type == KeyPress || event->xkey.type == KeyRelease) {
|
||||
KeySym key_sym = NormalizeKeySym(XLookupKeysym(&event->xkey, 0));
|
||||
auto key_it = x11KeySymToVkCode.find(static_cast<int>(key_sym));
|
||||
if (key_it == x11KeySymToVkCode.end()) {
|
||||
key_sym = NormalizeKeySym(XLookupKeysym(&event->xkey, 1));
|
||||
key_it = x11KeySymToVkCode.find(static_cast<int>(key_sym));
|
||||
}
|
||||
|
||||
if (key_it == x11KeySymToVkCode.end()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int key_code = key_it->second;
|
||||
bool is_key_down = (event->xkey.type == KeyPress);
|
||||
uint32_t scan_code = 0;
|
||||
bool extended = false;
|
||||
LookupWindowsKeyMetadataFromVk(key_code, &scan_code, &extended);
|
||||
|
||||
if (g_on_key_action) {
|
||||
g_on_key_action(key_code, is_key_down, scan_code, extended, g_user_ptr);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
PlatformKeyboardCapturer::PlatformKeyboardCapturer()
|
||||
: display_(nullptr),
|
||||
root_(0),
|
||||
running_(false),
|
||||
use_wayland_portal_(false),
|
||||
wayland_init_attempted_(false),
|
||||
@@ -121,82 +96,253 @@ PlatformKeyboardCapturer::~PlatformKeyboardCapturer() {
|
||||
}
|
||||
}
|
||||
|
||||
bool PlatformKeyboardCapturer::RefreshXTestDevices() {
|
||||
// XTEST identifies injected input. Do not filter by names such as "virtual":
|
||||
// an xrdp keyboard is a legitimate controller input device.
|
||||
const Atom property = XInternAtom(capture_display_, "XTEST Device", True);
|
||||
if (property == None) return false;
|
||||
int count = 0;
|
||||
XIDeviceInfo* devices = XIQueryDevice(capture_display_, XIAllDevices, &count);
|
||||
if (!devices) return false;
|
||||
xtest_devices_.clear();
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (devices[i].use != XISlaveKeyboard) continue;
|
||||
Atom type = None;
|
||||
int format = 0;
|
||||
unsigned long items = 0, remaining = 0;
|
||||
unsigned char* value = nullptr;
|
||||
const int result = XIGetProperty(
|
||||
capture_display_, devices[i].deviceid, property, 0, 1, False,
|
||||
XA_INTEGER, &type, &format, &items, &remaining, &value);
|
||||
if (result == Success && type == XA_INTEGER && format == 8 &&
|
||||
items == 1 && value && value[0] == 1) {
|
||||
xtest_devices_.insert(devices[i].deviceid);
|
||||
}
|
||||
if (value) XFree(value);
|
||||
}
|
||||
XIFreeDeviceInfo(devices);
|
||||
return true;
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::CaptureKey(int source_id, int x11_keycode,
|
||||
bool is_down) {
|
||||
if (!capture_has_focus_ || xtest_devices_.count(source_id) ||
|
||||
x11_keycode < 8 || x11_keycode > 255)
|
||||
return;
|
||||
|
||||
// The GUI stops capture on focus loss, but its event loop may lag behind
|
||||
// the native input thread. Never forward keys typed into another window.
|
||||
Window focus = None;
|
||||
int revert = 0;
|
||||
XGetInputFocus(capture_display_, &focus, &revert);
|
||||
if (focus != capture_focus_) return;
|
||||
|
||||
const uint64_t identity = (static_cast<uint64_t>(source_id) << 32) |
|
||||
static_cast<uint32_t>(x11_keycode);
|
||||
auto found = captured_keys_.find(identity);
|
||||
if (found == captured_keys_.end()) {
|
||||
// A press can have reached the Slint fallback just before native capture
|
||||
// started. Forward its release too, so that handoff cannot leave a key down.
|
||||
CapturedKey key;
|
||||
// Use unshifted key identity, independently of the local input method.
|
||||
// Preserve it until release, even if the keyboard mapping changes.
|
||||
for (int level = 0; level < 2 && key.key_code == 0; ++level) {
|
||||
const KeySym symbol = NormalizeKeySym(XkbKeycodeToKeysym(
|
||||
capture_display_, static_cast<KeyCode>(x11_keycode), 0, level));
|
||||
if (symbol == XK_KP_Enter) {
|
||||
key = {0x0D, 0x1C, true};
|
||||
} else if (symbol == XK_ISO_Level3_Shift) {
|
||||
key.key_code = 0xA5;
|
||||
} else if (symbol == XK_grave) {
|
||||
key.key_code = 0xC0;
|
||||
} else if (const auto vk = x11KeySymToVkCode.find(symbol);
|
||||
vk != x11KeySymToVkCode.end()) {
|
||||
key.key_code = vk->second;
|
||||
}
|
||||
}
|
||||
if (!key.key_code) return;
|
||||
if (!key.scan_code) {
|
||||
LookupWindowsKeyMetadataFromVk(key.key_code, &key.scan_code, &key.extended);
|
||||
if (!key.scan_code) {
|
||||
const int evdev = LinuxEvdevKeycodeFromWindowsVk(key.key_code);
|
||||
for (uint32_t scan = 1; scan <= 0x58; ++scan) {
|
||||
if (evdev >= 0 &&
|
||||
LinuxEvdevKeycodeFromWindowsScanCode(scan, false) == evdev) {
|
||||
key.scan_code = scan;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found = captured_keys_.emplace(identity, key).first;
|
||||
}
|
||||
const CapturedKey key = found->second;
|
||||
if (!is_down) captured_keys_.erase(found);
|
||||
if (on_key_action_) {
|
||||
on_key_action_(key.key_code, is_down, key.scan_code, key.extended, user_ptr_);
|
||||
}
|
||||
}
|
||||
|
||||
void PlatformKeyboardCapturer::RunCapture() {
|
||||
const int fd = ConnectionNumber(capture_display_);
|
||||
while (running_) {
|
||||
while (running_ && XPending(capture_display_) > 0) {
|
||||
XEvent event{};
|
||||
XNextEvent(capture_display_, &event);
|
||||
if (event.type == xkb_event_base_) {
|
||||
auto* xkb = reinterpret_cast<XkbEvent*>(&event);
|
||||
if (xkb->any.xkb_type == XkbMapNotify)
|
||||
XkbRefreshKeyboardMapping(&xkb->map);
|
||||
} else if (event.type == MappingNotify) {
|
||||
XRefreshKeyboardMapping(&event.xmapping);
|
||||
} else if (event.type == FocusOut) {
|
||||
// Keep focus changes in event order too: a fast switch away and back
|
||||
// may finish before either the GUI or XGetInputFocus observes it.
|
||||
capture_has_focus_ = false;
|
||||
for (const auto& [identity, key] : captured_keys_) {
|
||||
if (on_key_action_)
|
||||
on_key_action_(key.key_code, false, key.scan_code, key.extended,
|
||||
user_ptr_);
|
||||
}
|
||||
captured_keys_.clear();
|
||||
raw_presses_.fill({});
|
||||
} else if (event.type == FocusIn) {
|
||||
capture_has_focus_ = true;
|
||||
} else if (event.type == KeyPress && !event.xkey.send_event &&
|
||||
event.xkey.keycode < raw_presses_.size() &&
|
||||
event.xkey.time != raw_presses_[event.xkey.keycode].time) {
|
||||
// Server-generated repeats have no matching raw press. Subscribe to
|
||||
// core events on the focused window so Slint's core/XIM delivery is
|
||||
// preserved (selecting XI_KeyPress here would take precedence over it).
|
||||
const int source = raw_presses_[event.xkey.keycode].source_id;
|
||||
const uint64_t identity = (static_cast<uint64_t>(source) << 32) |
|
||||
event.xkey.keycode;
|
||||
if (captured_keys_.count(identity))
|
||||
CaptureKey(source, event.xkey.keycode, true);
|
||||
} else if (event.type == GenericEvent &&
|
||||
event.xcookie.extension == xi_opcode_ &&
|
||||
XGetEventData(capture_display_, &event.xcookie)) {
|
||||
if (event.xcookie.evtype == XI_RawKeyPress ||
|
||||
event.xcookie.evtype == XI_RawKeyRelease) {
|
||||
const auto* key = static_cast<XIRawEvent*>(event.xcookie.data);
|
||||
const bool is_down = event.xcookie.evtype == XI_RawKeyPress;
|
||||
if (is_down && key->detail >= 0 &&
|
||||
static_cast<size_t>(key->detail) < raw_presses_.size()) {
|
||||
// Include filtered XTEST presses, so their core events cannot be
|
||||
// mistaken for repeats of a physically held key.
|
||||
raw_presses_[key->detail] = {key->time, key->sourceid};
|
||||
}
|
||||
CaptureKey(key->sourceid, key->detail, is_down);
|
||||
} else if (event.xcookie.evtype == XI_HierarchyChanged &&
|
||||
!RefreshXTestDevices()) {
|
||||
LOG_ERROR("Failed to refresh XInput2 keyboard devices");
|
||||
running_ = false;
|
||||
}
|
||||
XFreeEventData(capture_display_, &event.xcookie);
|
||||
}
|
||||
}
|
||||
if (!running_) break;
|
||||
struct pollfd pfd = {fd, POLLIN, 0};
|
||||
const int result = poll(&pfd, 1, 50);
|
||||
if ((result < 0 && errno != EINTR) ||
|
||||
(result > 0 && (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)))) {
|
||||
LOG_ERROR("XInput2 keyboard capture event connection failed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
running_ = false;
|
||||
}
|
||||
|
||||
int PlatformKeyboardCapturer::Hook(OnKeyAction on_key_action, void* user_ptr) {
|
||||
if (!display_) {
|
||||
LOG_ERROR("Display not initialized.");
|
||||
if (running_) return 0;
|
||||
Unhook();
|
||||
capture_display_ = XOpenDisplay(nullptr);
|
||||
if (!capture_display_ || !on_key_action) {
|
||||
LOG_ERROR("Cannot open X11 keyboard capture display or callback is empty");
|
||||
Unhook();
|
||||
return -1;
|
||||
}
|
||||
|
||||
g_on_key_action = on_key_action;
|
||||
g_user_ptr = user_ptr;
|
||||
|
||||
if (running_) {
|
||||
return 0;
|
||||
int event = 0, error = 0;
|
||||
// XI 2.1 supplies raw-event source IDs, needed to exclude XTEST devices.
|
||||
int major = 2, minor = 1;
|
||||
if (!XQueryExtension(capture_display_, "XInputExtension", &xi_opcode_,
|
||||
&event, &error) ||
|
||||
XIQueryVersion(capture_display_, &major, &minor) != Success || major < 2 ||
|
||||
(major == 2 && minor < 1)) {
|
||||
LOG_WARN("XInput2 keyboard capture is unavailable");
|
||||
Unhook();
|
||||
return -1;
|
||||
}
|
||||
major = XkbMajorVersion;
|
||||
minor = XkbMinorVersion;
|
||||
int xkb_opcode = 0;
|
||||
if (!XkbQueryExtension(capture_display_, &xkb_opcode, &xkb_event_base_,
|
||||
&error, &major, &minor) || !RefreshXTestDevices()) {
|
||||
LOG_WARN("Cannot initialize XKB or enumerate XInput2 keyboard devices");
|
||||
Unhook();
|
||||
return -1;
|
||||
}
|
||||
|
||||
root_ = DefaultRootWindow(display_);
|
||||
XSelectInput(display_, root_, KeyPressMask | KeyReleaseMask);
|
||||
XFlush(display_);
|
||||
int revert = 0;
|
||||
XGetInputFocus(capture_display_, &capture_focus_, &revert);
|
||||
if (capture_focus_ == None || capture_focus_ == PointerRoot) {
|
||||
LOG_WARN("XInput2 keyboard capture requires a focused application window");
|
||||
Unhook();
|
||||
return -1;
|
||||
}
|
||||
capture_has_focus_ = true;
|
||||
|
||||
running_ = true;
|
||||
const int x11_fd = ConnectionNumber(display_);
|
||||
event_thread_ = std::thread([this, x11_fd]() {
|
||||
while (running_) {
|
||||
while (running_ && XPending(display_) > 0) {
|
||||
XEvent event;
|
||||
XNextEvent(display_, &event);
|
||||
KeyboardEventHandler(display_, &event);
|
||||
}
|
||||
|
||||
if (!running_) {
|
||||
break;
|
||||
}
|
||||
|
||||
struct pollfd pfd = {x11_fd, POLLIN, 0};
|
||||
int poll_ret = poll(&pfd, 1, 50);
|
||||
if (poll_ret < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
LOG_ERROR("poll for X11 events failed.");
|
||||
running_ = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (poll_ret == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
|
||||
LOG_ERROR("poll got invalid X11 event fd state.");
|
||||
running_ = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if ((pfd.revents & POLLIN) == 0) {
|
||||
continue;
|
||||
}
|
||||
std::array<unsigned char, XIMaskLen(XI_LASTEVENT)> raw{};
|
||||
std::array<unsigned char, XIMaskLen(XI_LASTEVENT)> hierarchy{};
|
||||
XISetMask(raw.data(), XI_RawKeyPress);
|
||||
XISetMask(raw.data(), XI_RawKeyRelease);
|
||||
XISetMask(hierarchy.data(), XI_HierarchyChanged);
|
||||
XIEventMask masks[] = {
|
||||
{XIAllMasterDevices, static_cast<int>(raw.size()), raw.data()},
|
||||
{XIAllDevices, static_cast<int>(hierarchy.size()), hierarchy.data()}};
|
||||
for (int screen = 0; screen < ScreenCount(capture_display_); ++screen) {
|
||||
if (XISelectEvents(capture_display_, RootWindow(capture_display_, screen),
|
||||
masks, 2) != Success) {
|
||||
LOG_WARN("Cannot subscribe to XInput2 keyboard events");
|
||||
Unhook();
|
||||
return -1;
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
XSelectInput(capture_display_, capture_focus_, KeyPressMask | FocusChangeMask);
|
||||
XkbSelectEvents(capture_display_, XkbUseCoreKbd, XkbMapNotifyMask,
|
||||
XkbMapNotifyMask);
|
||||
XSync(capture_display_, False);
|
||||
on_key_action_ = on_key_action;
|
||||
user_ptr_ = user_ptr;
|
||||
running_ = true;
|
||||
try {
|
||||
event_thread_ = std::thread([this] { RunCapture(); });
|
||||
} catch (const std::exception& error) {
|
||||
LOG_ERROR("Cannot start XInput2 keyboard capture thread: {}", error.what());
|
||||
Unhook();
|
||||
return -1;
|
||||
}
|
||||
LOG_INFO("XInput2 keyboard capture started");
|
||||
return 0;
|
||||
}
|
||||
|
||||
int PlatformKeyboardCapturer::Unhook() {
|
||||
running_ = false;
|
||||
|
||||
if (event_thread_.joinable()) {
|
||||
event_thread_.join();
|
||||
if (event_thread_.joinable()) event_thread_.join();
|
||||
// Closing the private connection removes every subscription and queued
|
||||
// event, so restarting capture cannot forward keys from the previous focus.
|
||||
if (capture_display_) {
|
||||
XCloseDisplay(capture_display_);
|
||||
capture_display_ = nullptr;
|
||||
}
|
||||
|
||||
g_on_key_action = nullptr;
|
||||
g_user_ptr = nullptr;
|
||||
|
||||
if (display_ && root_ != 0) {
|
||||
XSelectInput(display_, root_, 0);
|
||||
XFlush(display_);
|
||||
}
|
||||
|
||||
on_key_action_ = nullptr;
|
||||
user_ptr_ = nullptr;
|
||||
captured_keys_.clear();
|
||||
raw_presses_.fill({});
|
||||
xtest_devices_.clear();
|
||||
capture_focus_ = None;
|
||||
capture_has_focus_ = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,15 @@
|
||||
#ifndef _KEYBOARD_CAPTURER_H_
|
||||
#define _KEYBOARD_CAPTURER_H_
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "device_controller.h"
|
||||
|
||||
@@ -30,11 +33,25 @@ class PlatformKeyboardCapturer final : public KeyboardCapturer {
|
||||
public:
|
||||
virtual int Hook(OnKeyAction on_key_action, void* user_ptr);
|
||||
virtual int Unhook();
|
||||
bool IsHookActive() const override { return running_.load(); }
|
||||
virtual int SendKeyboardCommand(int key_code, bool is_down,
|
||||
uint32_t scan_code = 0,
|
||||
bool extended = false);
|
||||
|
||||
private:
|
||||
struct CapturedKey {
|
||||
int key_code = 0;
|
||||
uint32_t scan_code = 0;
|
||||
bool extended = false;
|
||||
};
|
||||
struct RawKeyPress {
|
||||
unsigned long time = 0;
|
||||
int source_id = 0;
|
||||
};
|
||||
bool RefreshXTestDevices();
|
||||
void CaptureKey(int source_id, int x11_keycode, bool is_down);
|
||||
void RunCapture();
|
||||
|
||||
bool InitWaylandPortal();
|
||||
void CleanupWaylandPortal();
|
||||
int SendWaylandKeyboardCommand(int key_code, bool is_down, uint32_t scan_code,
|
||||
@@ -47,7 +64,17 @@ class PlatformKeyboardCapturer final : public KeyboardCapturer {
|
||||
|
||||
private:
|
||||
_XDisplay* display_;
|
||||
unsigned long root_;
|
||||
// Capture owns a separate connection, including its XKB event queue.
|
||||
_XDisplay* capture_display_ = nullptr;
|
||||
unsigned long capture_focus_ = 0;
|
||||
bool capture_has_focus_ = false;
|
||||
int xi_opcode_ = 0;
|
||||
int xkb_event_base_ = 0;
|
||||
OnKeyAction on_key_action_ = nullptr;
|
||||
void* user_ptr_ = nullptr;
|
||||
std::unordered_set<int> xtest_devices_;
|
||||
std::unordered_map<uint64_t, CapturedKey> captured_keys_;
|
||||
std::array<RawKeyPress, 256> raw_presses_{};
|
||||
std::atomic<bool> running_;
|
||||
std::thread event_thread_;
|
||||
std::mutex x11_injection_mutex_;
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_BACKEND_LINUX_H_
|
||||
#define _PRIVACY_BACKEND_LINUX_H_
|
||||
|
||||
#include <poll.h>
|
||||
#include <spawn.h>
|
||||
#include <sys/eventfd.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
#include "privacy_backend.h"
|
||||
#include "privacy_guard.h"
|
||||
|
||||
extern char** environ;
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
class LinuxPrivacyBackend final : public PrivacyBackend {
|
||||
public:
|
||||
LinuxPrivacyBackend() : wake_(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)) {}
|
||||
~LinuxPrivacyBackend() override {
|
||||
// EOF also recovers after a crash, SIGKILL, or a normal shutdown. Never
|
||||
// terminate the guard: it must finish restoring the saved display ramps.
|
||||
if (socket_ >= 0) close(socket_);
|
||||
if (wake_ >= 0) close(wake_);
|
||||
if (child_ > 0) {
|
||||
const pid_t child = child_;
|
||||
std::thread([child] {
|
||||
while (waitpid(child, nullptr, 0) < 0 && errno == EINTR) {
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
}
|
||||
|
||||
PrivacyCapabilities Query() override {
|
||||
if (wake_ < 0)
|
||||
return {false, false, "Cannot create Linux privacy wake event"};
|
||||
if (!StartGuard()) return {false, false, failure_};
|
||||
if (!Send(LinuxPrivacyCommand::query)) return {false, false, failure_};
|
||||
// The first query also serves automatic privacy on the first connection.
|
||||
// Bound process startup so an unavailable helper cannot stall the GUI.
|
||||
if (!discovered_) {
|
||||
pollfd fd{socket_, POLLIN, 0};
|
||||
poll(&fd, 1, 1000);
|
||||
}
|
||||
ReadReplies();
|
||||
return {reply_.supported, reply_.input_supported,
|
||||
reply_.capability_reason[0] ? reply_.capability_reason
|
||||
: "Checking Linux privacy support"};
|
||||
}
|
||||
|
||||
bool Enable(bool block_input, const PrivacyScreenText&,
|
||||
std::string& error) override {
|
||||
failure_.clear();
|
||||
emergency_ = false;
|
||||
if (!Send(block_input ? LinuxPrivacyCommand::enable_blocking
|
||||
: LinuxPrivacyCommand::enable)) {
|
||||
error = failure_;
|
||||
return false;
|
||||
}
|
||||
engaged_ = true;
|
||||
++generation_;
|
||||
last_reply_ = Clock::now();
|
||||
recovered_ = false;
|
||||
reply_.active = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void Recover() override {
|
||||
ReadReplies();
|
||||
if (recovered_) {
|
||||
failure_.clear();
|
||||
return;
|
||||
}
|
||||
if (recovering_) return;
|
||||
if (Send(LinuxPrivacyCommand::recover)) recovering_ = true;
|
||||
}
|
||||
bool IsRecovered() const override { return recovered_; }
|
||||
bool RecoveryPending() const override { return recovering_; }
|
||||
|
||||
PrivacyHealth Poll() override {
|
||||
ReadReplies();
|
||||
if (engaged_ && Clock::now() - last_reply_ > std::chrono::seconds(1))
|
||||
failure_ = "Linux privacy guard stopped responding";
|
||||
if (engaged_ &&
|
||||
Clock::now() - last_heartbeat_ >= std::chrono::milliseconds(100)) {
|
||||
Send(LinuxPrivacyCommand::heartbeat);
|
||||
last_heartbeat_ = Clock::now();
|
||||
}
|
||||
const bool emergency = emergency_;
|
||||
emergency_ = false;
|
||||
return {failure_, emergency, reply_.active};
|
||||
}
|
||||
|
||||
void WaitForEvents(unsigned timeout_ms) override {
|
||||
pollfd fds[] = {{wake_, POLLIN, 0}, {socket_, POLLIN, 0}};
|
||||
poll(fds, 2, static_cast<int>(timeout_ms));
|
||||
uint64_t value;
|
||||
if (fds[0].revents & POLLIN) {
|
||||
while (read(wake_, &value, sizeof(value)) == sizeof(value)) {
|
||||
}
|
||||
}
|
||||
}
|
||||
void Wake() override {
|
||||
const uint64_t value = 1;
|
||||
if (wake_ >= 0) {
|
||||
const auto ignored = write(wake_, &value, sizeof(value));
|
||||
(void)ignored;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
bool StartGuard() {
|
||||
if (socket_ >= 0) return true;
|
||||
if (child_ > 0) {
|
||||
const auto result = waitpid(child_, nullptr, WNOHANG);
|
||||
if (result == 0) return false;
|
||||
child_ = -1;
|
||||
}
|
||||
int sockets[2];
|
||||
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC | SOCK_NONBLOCK, 0,
|
||||
sockets) != 0) {
|
||||
failure_ = "Cannot create Linux privacy guard socket";
|
||||
return false;
|
||||
}
|
||||
posix_spawn_file_actions_t actions;
|
||||
int result = posix_spawn_file_actions_init(&actions);
|
||||
if (result == 0) {
|
||||
// Close the parent end first: it may occupy the guard's destination fd.
|
||||
result = posix_spawn_file_actions_addclose(&actions, sockets[0]);
|
||||
if (result == 0)
|
||||
result = posix_spawn_file_actions_adddup2(&actions, sockets[1],
|
||||
kLinuxPrivacyGuardSocket);
|
||||
if (result == 0 && sockets[1] != kLinuxPrivacyGuardSocket)
|
||||
result = posix_spawn_file_actions_addclose(&actions, sockets[1]);
|
||||
if (result == 0) {
|
||||
char executable[] = "/proc/self/exe";
|
||||
char* args[] = {executable,
|
||||
const_cast<char*>(kLinuxPrivacyGuardArgument), nullptr};
|
||||
result =
|
||||
posix_spawn(&child_, executable, &actions, nullptr, args, environ);
|
||||
}
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
}
|
||||
close(sockets[1]);
|
||||
if (result != 0) {
|
||||
close(sockets[0]);
|
||||
child_ = -1;
|
||||
failure_ = std::string("Cannot start Linux privacy guard: ") +
|
||||
std::strerror(result);
|
||||
return false;
|
||||
}
|
||||
socket_ = sockets[0];
|
||||
reply_ = {};
|
||||
discovered_ = false;
|
||||
generation_ = 0;
|
||||
failure_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
void LostGuard() {
|
||||
if (socket_ >= 0) close(socket_);
|
||||
socket_ = -1;
|
||||
reply_ = {};
|
||||
recovering_ = false;
|
||||
failure_ =
|
||||
"Linux privacy guard disconnected; local protection is unavailable";
|
||||
// Do not claim successful recovery after an unexpected guard failure.
|
||||
// A normal guard reports restoration before closing its socket.
|
||||
}
|
||||
bool Send(LinuxPrivacyCommand command) {
|
||||
if (socket_ < 0) return false;
|
||||
if (send(socket_, &command, sizeof(command), MSG_NOSIGNAL) ==
|
||||
sizeof(command))
|
||||
return true;
|
||||
if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) LostGuard();
|
||||
return false;
|
||||
}
|
||||
void ReadReplies() {
|
||||
if (socket_ < 0) return;
|
||||
for (;;) {
|
||||
LinuxPrivacyReply next;
|
||||
const auto bytes = recv(socket_, &next, sizeof(next), 0);
|
||||
if (bytes < 0 &&
|
||||
(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
|
||||
return;
|
||||
if (bytes != sizeof(next)) {
|
||||
LostGuard();
|
||||
return;
|
||||
}
|
||||
next.capability_reason[sizeof(next.capability_reason) - 1] = '\0';
|
||||
next.failure[sizeof(next.failure) - 1] = '\0';
|
||||
discovered_ = true;
|
||||
// Ignore queued capability/heartbeat replies from before this enable.
|
||||
// A matching generation can also acknowledge watchdog-driven recovery.
|
||||
if (next.generation != generation_) continue;
|
||||
reply_ = next;
|
||||
last_reply_ = Clock::now();
|
||||
emergency_ = emergency_ || next.emergency;
|
||||
if (next.failure[0]) failure_ = next.failure;
|
||||
recovered_ = next.recovered;
|
||||
if (next.recovered) {
|
||||
recovering_ = false;
|
||||
engaged_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int wake_ = -1;
|
||||
int socket_ = -1;
|
||||
pid_t child_ = -1;
|
||||
LinuxPrivacyReply reply_;
|
||||
uint64_t generation_ = 0;
|
||||
bool engaged_ = false;
|
||||
bool discovered_ = false;
|
||||
bool recovering_ = false;
|
||||
bool recovered_ = true;
|
||||
bool emergency_ = false;
|
||||
std::string failure_;
|
||||
Clock::time_point last_heartbeat_{};
|
||||
Clock::time_point last_reply_{};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<PrivacyBackend> CreateLinuxPrivacyBackend() {
|
||||
return std::make_unique<LinuxPrivacyBackend>();
|
||||
}
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,721 @@
|
||||
/* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved. */
|
||||
#include "privacy_guard.h"
|
||||
|
||||
#include <X11/XKBlib.h>
|
||||
#include <X11/Xatom.h>
|
||||
#include <X11/extensions/XInput.h>
|
||||
#include <X11/extensions/XInput2.h>
|
||||
#include <X11/extensions/XTest.h>
|
||||
#include <X11/extensions/Xfixes.h>
|
||||
#include <X11/extensions/Xrandr.h>
|
||||
#include <X11/keysym.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using Gamma = std::unique_ptr<XRRCrtcGamma, decltype(&XRRFreeGamma)>;
|
||||
using Resources =
|
||||
std::unique_ptr<XRRScreenResources, decltype(&XRRFreeScreenResources)>;
|
||||
using CrtcInfo = std::unique_ptr<XRRCrtcInfo, decltype(&XRRFreeCrtcInfo)>;
|
||||
volatile std::sig_atomic_t stopping = 0;
|
||||
int x_error = 0;
|
||||
|
||||
void StopGuard(int) { stopping = 1; }
|
||||
int OnXError(Display*, XErrorEvent* event) {
|
||||
x_error = event->error_code;
|
||||
return 0;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
void SetText(char (&dest)[N], const std::string& text) {
|
||||
std::strncpy(dest, text.c_str(), N - 1);
|
||||
dest[N - 1] = '\0';
|
||||
}
|
||||
|
||||
struct Output {
|
||||
Window root = 0;
|
||||
RRCrtc crtc = 0;
|
||||
RRMode mode = 0;
|
||||
int x = 0, y = 0;
|
||||
unsigned width = 0, height = 0;
|
||||
Rotation rotation = 0;
|
||||
std::vector<RROutput> connectors;
|
||||
Gamma saved{nullptr, XRRFreeGamma};
|
||||
|
||||
bool SameLayout(const Output& other) const {
|
||||
return std::tie(root, crtc, mode, x, y, width, height, rotation,
|
||||
connectors) == std::tie(other.root, other.crtc, other.mode,
|
||||
other.x, other.y, other.width,
|
||||
other.height, other.rotation,
|
||||
other.connectors);
|
||||
}
|
||||
};
|
||||
|
||||
struct Device {
|
||||
int id = 0, use = 0, attachment = 0;
|
||||
bool keyboard = false, touch = false;
|
||||
std::string name;
|
||||
|
||||
bool operator==(const Device& other) const {
|
||||
return std::tie(id, use, attachment, keyboard, touch, name) ==
|
||||
std::tie(other.id, other.use, other.attachment, other.keyboard,
|
||||
other.touch, other.name);
|
||||
}
|
||||
};
|
||||
|
||||
bool IsBlack(const XRRCrtcGamma* gamma) {
|
||||
if (!gamma || gamma->size <= 0) return false;
|
||||
for (int i = 0; i < gamma->size; ++i)
|
||||
if (gamma->red[i] || gamma->green[i] || gamma->blue[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// This class lives only in the exec'd guard process. Its Xlib error handler is
|
||||
// isolated from the GUI and capture threads' process-global error handlers.
|
||||
class NativePrivacy {
|
||||
public:
|
||||
~NativePrivacy() {
|
||||
Recover();
|
||||
if (display_) XCloseDisplay(display_);
|
||||
}
|
||||
|
||||
void Query() {
|
||||
reply_.supported = reply_.input_supported = false;
|
||||
std::string error;
|
||||
if (!Initialize(error)) {
|
||||
SetText(reply_.capability_reason, error);
|
||||
return;
|
||||
}
|
||||
std::vector<Output> outputs;
|
||||
std::vector<Device> devices;
|
||||
if (!ReadOutputs(outputs, true, error) || !ReadDevices(devices, error)) {
|
||||
SetText(reply_.capability_reason, error);
|
||||
return;
|
||||
}
|
||||
const bool keyboard = std::any_of(devices.begin(), devices.end(),
|
||||
[](const auto& d) { return d.keyboard; });
|
||||
if (!keyboard) {
|
||||
SetText(reply_.capability_reason,
|
||||
"No local keyboard available for privacy recovery");
|
||||
return;
|
||||
}
|
||||
reply_.supported = true;
|
||||
// XIGrabDevice does not suppress XI 2.2 touch delivery. Do not advertise
|
||||
// input protection for touchscreens without a separate touch grab.
|
||||
reply_.input_supported = std::none_of(
|
||||
devices.begin(), devices.end(), [](const auto& d) { return d.touch; });
|
||||
SetText(reply_.capability_reason,
|
||||
reply_.input_supported
|
||||
? "X11 privacy black screen available; local recovery: "
|
||||
"Ctrl+Alt+Shift+F12"
|
||||
: "X11 privacy black screen available; touchscreen input "
|
||||
"blocking is unavailable");
|
||||
}
|
||||
|
||||
void Enable(bool block_input) {
|
||||
++reply_.generation;
|
||||
reply_.failure[0] = '\0';
|
||||
reply_.emergency = false;
|
||||
if (!reply_.recovered) {
|
||||
Fail("Linux privacy resources are still in use");
|
||||
return;
|
||||
}
|
||||
Query();
|
||||
if (!reply_.supported || (block_input && !reply_.input_supported)) {
|
||||
Fail(reply_.capability_reason);
|
||||
return;
|
||||
}
|
||||
std::string error;
|
||||
keys_.clear();
|
||||
if (!Acquire(error) || !ReadOutputs(outputs_, true, error) ||
|
||||
!ReadDevices(devices_, error) || !ProtectInput(block_input, error)) {
|
||||
Fail(error);
|
||||
return;
|
||||
}
|
||||
// No display ramp is changed until every original ramp has been saved.
|
||||
// Gamma is applied at scanout, after XGetImage/DRM framebuffer capture.
|
||||
// There is deliberately no cover window to contaminate remote frames.
|
||||
x_error = 0;
|
||||
for (const auto& output : outputs_) {
|
||||
Gamma black(XRRAllocGamma(output.saved->size), XRRFreeGamma);
|
||||
if (!black) {
|
||||
Fail("Cannot allocate Linux privacy display ramp");
|
||||
return;
|
||||
}
|
||||
std::fill_n(black->red, black->size, 0);
|
||||
std::fill_n(black->green, black->size, 0);
|
||||
std::fill_n(black->blue, black->size, 0);
|
||||
XRRSetCrtcGamma(display_, output.crtc, black.get());
|
||||
}
|
||||
for (int i = 0; i < ScreenCount(display_); ++i) {
|
||||
XFixesHideCursor(display_, RootWindow(display_, i));
|
||||
hidden_roots_.push_back(RootWindow(display_, i));
|
||||
}
|
||||
XSync(display_, False);
|
||||
if (x_error) {
|
||||
Fail("Cannot blank Linux displays or hide the local cursor");
|
||||
return;
|
||||
}
|
||||
// Active slave grabs temporarily detach devices. Snapshot after grabbing,
|
||||
// and monitor subsequent hardware/hierarchy changes during protection.
|
||||
if (!ReadDevices(devices_, error)) {
|
||||
Fail(error);
|
||||
return;
|
||||
}
|
||||
reply_.active = true;
|
||||
Check();
|
||||
}
|
||||
|
||||
void Recover() {
|
||||
reply_.active = false;
|
||||
if (!display_) {
|
||||
reply_.recovered = true;
|
||||
return;
|
||||
}
|
||||
for (int id : grabbed_) XIUngrabDevice(display_, id, CurrentTime);
|
||||
grabbed_.clear();
|
||||
for (Window root : hidden_roots_) XFixesShowCursor(display_, root);
|
||||
hidden_roots_.clear();
|
||||
// Keep failed restorations for retry. Removed CRTCs no longer own a local
|
||||
// output; all still-present CRTCs must acknowledge the original ramp.
|
||||
for (auto it = outputs_.begin(); it != outputs_.end();) {
|
||||
x_error = 0;
|
||||
Resources resources(XRRGetScreenResourcesCurrent(display_, it->root),
|
||||
XRRFreeScreenResources);
|
||||
if (!resources) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
const bool exists =
|
||||
std::find(resources->crtcs, resources->crtcs + resources->ncrtc,
|
||||
it->crtc) != resources->crtcs + resources->ncrtc;
|
||||
if (exists && it->saved) {
|
||||
XRRSetCrtcGamma(display_, it->crtc, it->saved.get());
|
||||
XSync(display_, False);
|
||||
if (x_error) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
it = outputs_.erase(it);
|
||||
}
|
||||
keys_.clear();
|
||||
if (outputs_.empty() && owner_) {
|
||||
XDestroyWindow(display_, owner_);
|
||||
owner_ = 0;
|
||||
}
|
||||
XSync(display_, False);
|
||||
reply_.recovered = outputs_.empty() && !owner_;
|
||||
}
|
||||
|
||||
void Fail(const std::string& reason) {
|
||||
SetText(reply_.failure, reason);
|
||||
Recover();
|
||||
}
|
||||
|
||||
void Poll() {
|
||||
if (!display_) return;
|
||||
while (XPending(display_)) {
|
||||
XEvent event{};
|
||||
XNextEvent(display_, &event);
|
||||
if (event.type != GenericEvent || event.xcookie.extension != xi_opcode_ ||
|
||||
!XGetEventData(display_, &event.xcookie))
|
||||
continue;
|
||||
if (reply_.active) {
|
||||
const int type = event.xcookie.evtype;
|
||||
if (type == XI_KeyPress || type == XI_KeyRelease) {
|
||||
const auto* key = static_cast<XIDeviceEvent*>(event.xcookie.data);
|
||||
Key(key->sourceid, key->detail, type == XI_KeyPress);
|
||||
} else if (!blocking_ &&
|
||||
(type == XI_RawKeyPress || type == XI_RawKeyRelease)) {
|
||||
const auto* key = static_cast<XIRawEvent*>(event.xcookie.data);
|
||||
Key(key->sourceid, key->detail, type == XI_RawKeyPress);
|
||||
}
|
||||
}
|
||||
XFreeEventData(display_, &event.xcookie);
|
||||
}
|
||||
if (reply_.active &&
|
||||
Clock::now() - checked_ >= std::chrono::milliseconds(100))
|
||||
Check();
|
||||
if (!reply_.active && !reply_.recovered) Recover();
|
||||
}
|
||||
|
||||
const LinuxPrivacyReply& Reply() const { return reply_; }
|
||||
int Connection() const { return display_ ? ConnectionNumber(display_) : -1; }
|
||||
void AcknowledgeEmergency() { reply_.emergency = false; }
|
||||
|
||||
private:
|
||||
bool Initialize(std::string& error) {
|
||||
if (initialized_) return true;
|
||||
const char* session = std::getenv("XDG_SESSION_TYPE");
|
||||
const char* wayland = std::getenv("WAYLAND_DISPLAY");
|
||||
if ((session && std::strcmp(session, "wayland") == 0) ||
|
||||
(wayland && *wayland)) {
|
||||
error =
|
||||
"Linux privacy screen requires an X11 session; Wayland is "
|
||||
"unsupported";
|
||||
return false;
|
||||
}
|
||||
const char* address = std::getenv("DISPLAY");
|
||||
if (!address ||
|
||||
(*address != ':' && std::strncmp(address, "unix:", 5) != 0)) {
|
||||
error = "Linux privacy screen requires a local X11 display";
|
||||
return false;
|
||||
}
|
||||
if (!display_) display_ = XOpenDisplay(nullptr);
|
||||
if (!display_) {
|
||||
error = "Cannot open the local X11 display";
|
||||
return false;
|
||||
}
|
||||
int event = 0, code = 0, opcode = 0;
|
||||
int major = 1, minor = 3;
|
||||
if (XQueryExtension(display_, "XWAYLAND", &opcode, &event, &code)) {
|
||||
error = "XWayland cannot protect native Wayland displays";
|
||||
return false;
|
||||
}
|
||||
if (!XRRQueryExtension(display_, &event, &code) ||
|
||||
!XRRQueryVersion(display_, &major, &minor) || major < 1 ||
|
||||
(major == 1 && minor < 3)) {
|
||||
error = "Linux privacy screen requires RandR 1.3 display gamma control";
|
||||
return false;
|
||||
}
|
||||
major = 4;
|
||||
minor = 0;
|
||||
if (!XFixesQueryExtension(display_, &event, &code) ||
|
||||
!XFixesQueryVersion(display_, &major, &minor) || major < 4) {
|
||||
error = "Linux privacy screen requires XFixes 4 cursor hiding";
|
||||
return false;
|
||||
}
|
||||
major = 2;
|
||||
minor = 2;
|
||||
if (!XQueryExtension(display_, "XInputExtension", &xi_opcode_, &event,
|
||||
&code) ||
|
||||
XIQueryVersion(display_, &major, &minor) != Success || major < 2) {
|
||||
error = "Linux privacy screen requires XInput 2 local input monitoring";
|
||||
return false;
|
||||
}
|
||||
xtest_property_ = XInternAtom(display_, "XTEST Device", True);
|
||||
if (!xtest_property_ ||
|
||||
!XTestQueryExtension(display_, &event, &code, &major, &minor)) {
|
||||
error = "Cannot identify X11 remote input devices";
|
||||
return false;
|
||||
}
|
||||
selection_ = XInternAtom(display_, "_CROSSDESK_PRIVACY_GUARD", False);
|
||||
std::array<unsigned char, XIMaskLen(XI_LASTEVENT)> bits{};
|
||||
XISetMask(bits.data(), XI_RawKeyPress);
|
||||
XISetMask(bits.data(), XI_RawKeyRelease);
|
||||
XIEventMask mask{XIAllDevices, static_cast<int>(bits.size()), bits.data()};
|
||||
x_error = 0;
|
||||
for (int i = 0; i < ScreenCount(display_); ++i)
|
||||
XISelectEvents(display_, RootWindow(display_, i), &mask, 1);
|
||||
XSync(display_, False);
|
||||
if (x_error) {
|
||||
error = "Cannot monitor the local privacy recovery shortcut";
|
||||
return false;
|
||||
}
|
||||
initialized_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ReadOutputs(std::vector<Output>& outputs, bool save,
|
||||
std::string& error) {
|
||||
outputs.clear();
|
||||
x_error = 0;
|
||||
for (int screen = 0; screen < ScreenCount(display_); ++screen) {
|
||||
const Window root = RootWindow(display_, screen);
|
||||
Resources resources(XRRGetScreenResourcesCurrent(display_, root),
|
||||
XRRFreeScreenResources);
|
||||
if (!resources) {
|
||||
error = "Cannot enumerate Linux display outputs";
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < resources->ncrtc; ++i) {
|
||||
CrtcInfo info(
|
||||
XRRGetCrtcInfo(display_, resources.get(), resources->crtcs[i]),
|
||||
XRRFreeCrtcInfo);
|
||||
if (!info) {
|
||||
error = "Cannot inspect Linux display controller";
|
||||
return false;
|
||||
}
|
||||
if (!info->mode || !info->noutput) continue;
|
||||
Output output;
|
||||
output.root = root;
|
||||
output.crtc = resources->crtcs[i];
|
||||
output.mode = info->mode;
|
||||
output.x = info->x;
|
||||
output.y = info->y;
|
||||
output.width = info->width;
|
||||
output.height = info->height;
|
||||
output.rotation = info->rotation;
|
||||
output.connectors.assign(info->outputs, info->outputs + info->noutput);
|
||||
std::sort(output.connectors.begin(), output.connectors.end());
|
||||
if (save) {
|
||||
output.saved.reset(XRRGetCrtcGamma(display_, output.crtc));
|
||||
if (!output.saved || output.saved->size <= 0 ||
|
||||
IsBlack(output.saved.get())) {
|
||||
error =
|
||||
"Display gamma control is unavailable or the display is "
|
||||
"already blank";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
outputs.push_back(std::move(output));
|
||||
}
|
||||
}
|
||||
XSync(display_, False);
|
||||
if (x_error || outputs.empty()) {
|
||||
error = "No controllable Linux display outputs";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ReadDevices(std::vector<Device>& devices, std::string& error) {
|
||||
devices.clear();
|
||||
x_error = 0;
|
||||
int count = 0;
|
||||
XIDeviceInfo* info = XIQueryDevice(display_, XIAllDevices, &count);
|
||||
if (!info) {
|
||||
error = "Cannot enumerate local X11 input devices";
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < count; ++i) {
|
||||
const auto& d = info[i];
|
||||
if (!d.enabled || d.use == XIMasterPointer || d.use == XIMasterKeyboard)
|
||||
continue;
|
||||
Atom type = None;
|
||||
int format = 0;
|
||||
unsigned long items = 0, remaining = 0;
|
||||
unsigned char* value = nullptr;
|
||||
const int result =
|
||||
XIGetProperty(display_, d.deviceid, xtest_property_, 0, 1, False,
|
||||
XA_INTEGER, &type, &format, &items, &remaining, &value);
|
||||
const bool injected = result == Success && type == XA_INTEGER &&
|
||||
format == 8 && items == 1 && value && value[0] == 1;
|
||||
if (value) XFree(value);
|
||||
if (injected) continue;
|
||||
Device device;
|
||||
device.id = d.deviceid;
|
||||
device.use = d.use;
|
||||
device.attachment = d.attachment;
|
||||
device.name = d.name ? d.name : "";
|
||||
for (int c = 0; c < d.num_classes; ++c) {
|
||||
device.keyboard |= d.classes[c]->type == XIKeyClass;
|
||||
device.touch |= d.classes[c]->type == XITouchClass;
|
||||
}
|
||||
devices.push_back(std::move(device));
|
||||
}
|
||||
XIFreeDeviceInfo(info);
|
||||
XSync(display_, False);
|
||||
if (x_error) {
|
||||
error = "Cannot verify local X11 input devices";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Acquire(std::string& error) {
|
||||
// A second instance must not save the first instance's black ramps as its
|
||||
// originals. Selection ownership and creation are atomic on this server.
|
||||
XGrabServer(display_);
|
||||
if (XGetSelectionOwner(display_, selection_) == None) {
|
||||
owner_ = XCreateSimpleWindow(display_, DefaultRootWindow(display_), 0, 0,
|
||||
1, 1, 0, 0, 0);
|
||||
XSetSelectionOwner(display_, selection_, owner_, CurrentTime);
|
||||
}
|
||||
XUngrabServer(display_);
|
||||
XSync(display_, False);
|
||||
if (!owner_ || XGetSelectionOwner(display_, selection_) != owner_) {
|
||||
error = "Another CrossDesk instance owns Linux privacy protection";
|
||||
return false;
|
||||
}
|
||||
reply_.recovered = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ProtectInput(bool block_input, std::string& error) {
|
||||
blocking_ = block_input;
|
||||
if (!block_input) return true;
|
||||
for (const auto& device : devices_) {
|
||||
if (device.touch) {
|
||||
error = "Touchscreen privacy input blocking is unavailable";
|
||||
return false;
|
||||
}
|
||||
if (device.keyboard) {
|
||||
// Preserve held local modifiers for the emergency chord independently
|
||||
// of the releases sent to the master keyboard below.
|
||||
XDevice* keyboard = XOpenDevice(display_, device.id);
|
||||
XDeviceState* state =
|
||||
keyboard ? XQueryDeviceState(display_, keyboard) : nullptr;
|
||||
if (!state) {
|
||||
if (keyboard) XCloseDevice(display_, keyboard);
|
||||
error = "Cannot inspect held local keyboard input";
|
||||
return false;
|
||||
}
|
||||
XInputClass* input = state->data;
|
||||
for (int i = 0; i < state->num_classes; ++i) {
|
||||
if (input->c_class == KeyClass) {
|
||||
const auto* keys = reinterpret_cast<XKeyState*>(input);
|
||||
for (int key = 0; key < 256; ++key)
|
||||
keys_[device.id][key] = keys->keys[key / 8] & (1 << (key % 8));
|
||||
}
|
||||
input = reinterpret_cast<XInputClass*>(
|
||||
reinterpret_cast<char*>(input) + input->length);
|
||||
}
|
||||
XFreeDeviceState(state);
|
||||
XCloseDevice(display_, keyboard);
|
||||
}
|
||||
std::array<unsigned char, XIMaskLen(XI_LASTEVENT)> bits{};
|
||||
for (int type : {XI_KeyPress, XI_KeyRelease, XI_ButtonPress,
|
||||
XI_ButtonRelease, XI_Motion})
|
||||
XISetMask(bits.data(), type);
|
||||
XIEventMask mask{device.id, static_cast<int>(bits.size()), bits.data()};
|
||||
const int result = XIGrabDevice(
|
||||
display_, device.id, DefaultRootWindow(display_), CurrentTime, None,
|
||||
GrabModeAsync, GrabModeAsync, False, &mask);
|
||||
if (result != GrabSuccess) {
|
||||
error = "Cannot grab every local X11 input device";
|
||||
return false;
|
||||
}
|
||||
grabbed_.push_back(device.id);
|
||||
}
|
||||
return ReleaseHeldInput(error);
|
||||
}
|
||||
|
||||
bool ReleaseHeldInput(std::string& error) {
|
||||
// Slave grabs float physical devices, but their previous presses can
|
||||
// remain on the master. Release them after all grabs are installed so a
|
||||
// held local Ctrl/button cannot alter the remote controller's next input.
|
||||
int original_pointer = 0, count = 0;
|
||||
XIGetClientPointer(display_, None, &original_pointer);
|
||||
XIDeviceInfo* masters = XIQueryDevice(display_, XIAllMasterDevices, &count);
|
||||
if (!masters) {
|
||||
error = "Cannot inspect held X11 input";
|
||||
return false;
|
||||
}
|
||||
x_error = 0;
|
||||
bool ok = true;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
if (masters[i].use != XIMasterPointer || !masters[i].enabled) continue;
|
||||
XISetClientPointer(display_, None, masters[i].deviceid);
|
||||
char keys[32]{};
|
||||
XQueryKeymap(display_, keys);
|
||||
for (int key = 8; key < 256; ++key)
|
||||
if (keys[key / 8] & (1 << (key % 8)))
|
||||
ok &= XTestFakeKeyEvent(display_, key, False, CurrentTime) != 0;
|
||||
Window root = None, child = None;
|
||||
double root_x = 0, root_y = 0, win_x = 0, win_y = 0;
|
||||
XIButtonState buttons{};
|
||||
XIModifierState modifiers{};
|
||||
XIGroupState group{};
|
||||
XIQueryPointer(display_, masters[i].deviceid, DefaultRootWindow(display_),
|
||||
&root, &child, &root_x, &root_y, &win_x, &win_y, &buttons,
|
||||
&modifiers, &group);
|
||||
for (int button = 1; button < buttons.mask_len * 8; ++button)
|
||||
if (XIMaskIsSet(buttons.mask, button))
|
||||
ok &= XTestFakeButtonEvent(display_, button, False, CurrentTime) != 0;
|
||||
if (buttons.mask) XFree(buttons.mask);
|
||||
XSync(display_, False);
|
||||
XQueryKeymap(display_, keys);
|
||||
for (char pressed : keys) ok &= pressed == 0;
|
||||
buttons = {};
|
||||
XIQueryPointer(display_, masters[i].deviceid, DefaultRootWindow(display_),
|
||||
&root, &child, &root_x, &root_y, &win_x, &win_y, &buttons,
|
||||
&modifiers, &group);
|
||||
for (int byte = 0; byte < buttons.mask_len; ++byte)
|
||||
ok &= buttons.mask[byte] == 0;
|
||||
if (buttons.mask) XFree(buttons.mask);
|
||||
}
|
||||
XIFreeDeviceInfo(masters);
|
||||
if (original_pointer) XISetClientPointer(display_, None, original_pointer);
|
||||
XSync(display_, False);
|
||||
if (!ok || x_error) {
|
||||
error = "Cannot release held X11 input for privacy";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Key(int source, int keycode, bool down) {
|
||||
if (keycode < 0 || keycode >= 256 ||
|
||||
std::none_of(devices_.begin(), devices_.end(), [source](const auto& d) {
|
||||
return d.id == source && d.keyboard;
|
||||
}))
|
||||
return;
|
||||
keys_[source][keycode] = down;
|
||||
bool ctrl = false, alt = false, shift = false;
|
||||
for (const auto& [id, keys] : keys_) {
|
||||
for (int code = 0; code < 256; ++code) {
|
||||
if (!keys[code]) continue;
|
||||
const KeySym symbol = XkbKeycodeToKeysym(display_, code, 0, 0);
|
||||
ctrl |= symbol == XK_Control_L || symbol == XK_Control_R;
|
||||
alt |= symbol == XK_Alt_L || symbol == XK_Alt_R;
|
||||
shift |= symbol == XK_Shift_L || symbol == XK_Shift_R;
|
||||
}
|
||||
}
|
||||
if (down && ctrl && alt && shift &&
|
||||
XkbKeycodeToKeysym(display_, keycode, 0, 0) == XK_F12) {
|
||||
reply_.emergency = true;
|
||||
Recover();
|
||||
}
|
||||
}
|
||||
|
||||
void Check() {
|
||||
checked_ = Clock::now();
|
||||
std::string error;
|
||||
std::vector<Output> current;
|
||||
std::vector<Device> devices;
|
||||
if (!ReadOutputs(current, false, error) || !ReadDevices(devices, error)) {
|
||||
Fail(error);
|
||||
return;
|
||||
}
|
||||
if (current.size() != outputs_.size() ||
|
||||
!std::equal(
|
||||
current.begin(), current.end(), outputs_.begin(),
|
||||
[](const auto& a, const auto& b) { return a.SameLayout(b); })) {
|
||||
Fail("Display topology changed; Linux privacy has been turned off");
|
||||
return;
|
||||
}
|
||||
if (devices != devices_) {
|
||||
Fail("Local input devices changed; Linux privacy has been turned off");
|
||||
return;
|
||||
}
|
||||
x_error = 0;
|
||||
for (const auto& output : outputs_) {
|
||||
Gamma ramp(XRRGetCrtcGamma(display_, output.crtc), XRRFreeGamma);
|
||||
if (!IsBlack(ramp.get())) {
|
||||
Fail(
|
||||
"Display gamma protection was changed; Linux privacy is "
|
||||
"unavailable");
|
||||
return;
|
||||
}
|
||||
}
|
||||
XSync(display_, False);
|
||||
if (x_error || XGetSelectionOwner(display_, selection_) != owner_)
|
||||
Fail("Cannot verify Linux privacy protection");
|
||||
}
|
||||
|
||||
Display* display_ = nullptr;
|
||||
bool initialized_ = false;
|
||||
bool blocking_ = false;
|
||||
int xi_opcode_ = 0;
|
||||
Atom xtest_property_ = None, selection_ = None;
|
||||
Window owner_ = 0;
|
||||
std::vector<Output> outputs_;
|
||||
std::vector<Device> devices_;
|
||||
std::vector<int> grabbed_;
|
||||
std::vector<Window> hidden_roots_;
|
||||
std::map<int, std::array<bool, 256>> keys_;
|
||||
LinuxPrivacyReply reply_;
|
||||
Clock::time_point checked_{};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
int RunLinuxPrivacyGuard() {
|
||||
const int socket = kLinuxPrivacyGuardSocket;
|
||||
int type = 0;
|
||||
socklen_t length = sizeof(type);
|
||||
if (getsockopt(socket, SOL_SOCKET, SO_TYPE, &type, &length) != 0 ||
|
||||
type != SOCK_SEQPACKET)
|
||||
return 1;
|
||||
fcntl(socket, F_SETFD, FD_CLOEXEC);
|
||||
fcntl(socket, F_SETFL, O_NONBLOCK);
|
||||
struct sigaction action {};
|
||||
action.sa_handler = StopGuard;
|
||||
sigemptyset(&action.sa_mask);
|
||||
sigaction(SIGTERM, &action, nullptr);
|
||||
sigaction(SIGINT, &action, nullptr);
|
||||
sigaction(SIGHUP, &action, nullptr);
|
||||
XSetErrorHandler(OnXError);
|
||||
NativePrivacy privacy;
|
||||
auto heartbeat = Clock::now();
|
||||
bool connected = true;
|
||||
bool dirty = false;
|
||||
while (connected && !stopping) {
|
||||
pollfd fds[] = {{socket, POLLIN, 0}, {privacy.Connection(), POLLIN, 0}};
|
||||
poll(fds, 2, privacy.Reply().active ? 25 : 250);
|
||||
if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) break;
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
LinuxPrivacyCommand command;
|
||||
const auto bytes = recv(socket, &command, sizeof(command), 0);
|
||||
if (bytes < 0 &&
|
||||
(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
|
||||
break;
|
||||
if (bytes != sizeof(command)) {
|
||||
connected = false;
|
||||
break;
|
||||
}
|
||||
heartbeat = Clock::now();
|
||||
switch (command) {
|
||||
case LinuxPrivacyCommand::query:
|
||||
if (!privacy.Reply().active) privacy.Query();
|
||||
break;
|
||||
case LinuxPrivacyCommand::enable:
|
||||
privacy.Enable(false);
|
||||
break;
|
||||
case LinuxPrivacyCommand::enable_blocking:
|
||||
privacy.Enable(true);
|
||||
break;
|
||||
case LinuxPrivacyCommand::recover:
|
||||
privacy.Recover();
|
||||
break;
|
||||
case LinuxPrivacyCommand::heartbeat:
|
||||
break;
|
||||
default:
|
||||
connected = false;
|
||||
break;
|
||||
}
|
||||
dirty = true;
|
||||
}
|
||||
if (!connected || stopping) break;
|
||||
const auto before = privacy.Reply();
|
||||
privacy.Poll();
|
||||
if (privacy.Reply().active &&
|
||||
Clock::now() - heartbeat > std::chrono::seconds(3))
|
||||
privacy.Fail(
|
||||
"Privacy controller stopped responding; local desktop and input "
|
||||
"restored");
|
||||
const auto& after = privacy.Reply();
|
||||
dirty |= before.active != after.active ||
|
||||
before.recovered != after.recovered ||
|
||||
before.emergency != after.emergency ||
|
||||
std::strcmp(before.failure, after.failure) != 0;
|
||||
if (dirty) {
|
||||
const auto& reply = privacy.Reply();
|
||||
if (send(socket, &reply, sizeof(reply), MSG_NOSIGNAL) == sizeof(reply)) {
|
||||
dirty = false;
|
||||
privacy.AcknowledgeEmergency();
|
||||
} else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Keep trying if the X server temporarily rejected restoration, even after
|
||||
// the parent exited. Disconnecting releases XI grabs and cursor hiding too.
|
||||
do {
|
||||
privacy.Recover();
|
||||
if (!privacy.Reply().recovered) poll(nullptr, 0, 250);
|
||||
} while (!privacy.Reply().recovered);
|
||||
const auto& reply = privacy.Reply();
|
||||
const auto ignored = send(socket, &reply, sizeof(reply), MSG_NOSIGNAL);
|
||||
(void)ignored;
|
||||
close(socket);
|
||||
return 0;
|
||||
}
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_GUARD_H_
|
||||
#define _PRIVACY_GUARD_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
inline constexpr char kLinuxPrivacyGuardArgument[] = "--linux-privacy-guard";
|
||||
inline constexpr int kLinuxPrivacyGuardSocket = 3;
|
||||
|
||||
// Private protocol over an inherited SOCK_SEQPACKET socket. No listening
|
||||
// socket, shell, elevated privileges or separately installed helper is needed.
|
||||
enum class LinuxPrivacyCommand : uint8_t {
|
||||
query,
|
||||
enable,
|
||||
enable_blocking,
|
||||
recover,
|
||||
heartbeat,
|
||||
};
|
||||
|
||||
struct LinuxPrivacyReply {
|
||||
uint64_t generation = 0;
|
||||
bool supported = false;
|
||||
bool input_supported = false;
|
||||
bool active = false;
|
||||
bool recovered = true;
|
||||
bool emergency = false;
|
||||
char capability_reason[256]{};
|
||||
char failure[256]{};
|
||||
};
|
||||
|
||||
int RunLinuxPrivacyGuard();
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include "platform.h"
|
||||
#include "privacy_controller.h"
|
||||
#include "rd_log.h"
|
||||
#if defined(CROSSDESK_HAS_DRM) && CROSSDESK_HAS_DRM
|
||||
#include "screen_capturer_drm.h"
|
||||
@@ -64,6 +65,13 @@ int ScreenCapturerLinux::Init(const int fps, cb_desktop_data cb) {
|
||||
return;
|
||||
}
|
||||
invalid_stream_id_logged_.store(false, std::memory_order_relaxed);
|
||||
{
|
||||
std::lock_guard lock(privacy_mutex_);
|
||||
if (privacy_ && !capture_paused_ && !capture_announced_) {
|
||||
capture_announced_ = true;
|
||||
privacy_->CaptureChanged(true);
|
||||
}
|
||||
}
|
||||
if (callback_orig_) {
|
||||
callback_orig_(data, size, width, height, mapped_stream_id.c_str(),
|
||||
native_frame);
|
||||
@@ -145,6 +153,7 @@ int ScreenCapturerLinux::Init(const int fps, cb_desktop_data cb) {
|
||||
}
|
||||
|
||||
int ScreenCapturerLinux::Destroy() {
|
||||
Stop();
|
||||
if (impl_) {
|
||||
impl_->Destroy();
|
||||
impl_.reset();
|
||||
@@ -169,6 +178,11 @@ int ScreenCapturerLinux::Start(bool show_cursor) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard lock(privacy_mutex_);
|
||||
capture_paused_ = false;
|
||||
}
|
||||
|
||||
// X11 output names, DRM connectors and Wayland stream handles may all change
|
||||
// after an HDMI hotplug, so rebuild the current backend before each session.
|
||||
const int refresh_ret = RefreshCurrentBackend();
|
||||
@@ -226,6 +240,11 @@ int ScreenCapturerLinux::Stop() {
|
||||
return 0;
|
||||
}
|
||||
const int ret = impl_->Stop();
|
||||
{
|
||||
std::lock_guard lock(privacy_mutex_);
|
||||
capture_announced_ = false;
|
||||
if (privacy_) privacy_->CaptureChanged(false);
|
||||
}
|
||||
UpdateAliasesFromBackend(impl_.get());
|
||||
return ret;
|
||||
}
|
||||
@@ -234,13 +253,25 @@ int ScreenCapturerLinux::Pause(int monitor_index) {
|
||||
if (!impl_) {
|
||||
return -1;
|
||||
}
|
||||
return impl_->Pause(monitor_index);
|
||||
const int ret = impl_->Pause(monitor_index);
|
||||
{
|
||||
// An in-flight frame must not announce running again after a pause.
|
||||
std::lock_guard lock(privacy_mutex_);
|
||||
capture_paused_ = true;
|
||||
capture_announced_ = false;
|
||||
if (privacy_) privacy_->CaptureChanged(false);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int ScreenCapturerLinux::Resume(int monitor_index) {
|
||||
if (!impl_) {
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
std::lock_guard lock(privacy_mutex_);
|
||||
capture_paused_ = false;
|
||||
}
|
||||
return impl_->Resume(monitor_index);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ class ScreenCapturerLinux : public ScreenCapturer {
|
||||
|
||||
public:
|
||||
int Init(const int fps, cb_desktop_data cb) override;
|
||||
void SetPrivacyController(PrivacyController* privacy) override { privacy_ = privacy; }
|
||||
int Destroy() override;
|
||||
int Start(bool show_cursor) override;
|
||||
int Stop() override;
|
||||
@@ -53,6 +54,10 @@ class ScreenCapturerLinux : public ScreenCapturer {
|
||||
|
||||
private:
|
||||
std::unique_ptr<ScreenCapturer> impl_;
|
||||
PrivacyController* privacy_ = nullptr;
|
||||
std::mutex privacy_mutex_;
|
||||
bool capture_announced_ = false;
|
||||
bool capture_paused_ = false;
|
||||
BackendType backend_ = BackendType::kNone;
|
||||
int fps_ = 60;
|
||||
cb_desktop_data callback_;
|
||||
|
||||
@@ -3,269 +3,240 @@
|
||||
#include <pulse/error.h>
|
||||
#include <pulse/introspect.h>
|
||||
|
||||
#include <condition_variable>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
constexpr int kSampleRate = 48000;
|
||||
constexpr pa_sample_format_t kFormat = PA_SAMPLE_S16LE;
|
||||
constexpr int kChannels = 1;
|
||||
namespace {
|
||||
constexpr size_t kFrameSizeBytes = 480 * sizeof(int16_t);
|
||||
constexpr auto kStartupTimeout = std::chrono::seconds(2);
|
||||
constexpr auto kPollInterval = std::chrono::milliseconds(5);
|
||||
|
||||
SpeakerCapturerLinux::SpeakerCapturerLinux()
|
||||
: inited_(false), paused_(false), stop_flag_(false) {}
|
||||
SpeakerCapturerLinux::~SpeakerCapturerLinux() {
|
||||
Stop();
|
||||
Destroy();
|
||||
void ReleaseOperation(pa_operation* operation) {
|
||||
if (!operation) return;
|
||||
if (pa_operation_get_state(operation) == PA_OPERATION_RUNNING)
|
||||
pa_operation_cancel(operation);
|
||||
pa_operation_unref(operation);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
SpeakerCapturerLinux::~SpeakerCapturerLinux() { Destroy(); }
|
||||
|
||||
int SpeakerCapturerLinux::Init(speaker_data_cb cb) {
|
||||
if (inited_) return 0;
|
||||
cb_ = cb;
|
||||
cb_ = std::move(cb);
|
||||
inited_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SpeakerCapturerLinux::Destroy() {
|
||||
inited_ = false;
|
||||
return 0;
|
||||
// Use nonblocking iterations instead of pa_threaded_mainloop_wait(): a server
|
||||
// that never replies, disappears, or never reaches STREAM_READY must not leave
|
||||
// startup/Stop waiting for a signal that will never be delivered.
|
||||
bool SpeakerCapturerLinux::PumpUntil(
|
||||
const std::function<bool()>& ready,
|
||||
std::chrono::steady_clock::time_point deadline) {
|
||||
while (!stop_flag_) {
|
||||
if (ready()) return true;
|
||||
if (std::chrono::steady_clock::now() >= deadline ||
|
||||
!PA_CONTEXT_IS_GOOD(pa_context_get_state(context_)))
|
||||
return false;
|
||||
if (pa_mainloop_iterate(mainloop_, 0, nullptr) < 0) return false;
|
||||
std::this_thread::sleep_for(kPollInterval);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string SpeakerCapturerLinux::GetDefaultMonitorSourceName() {
|
||||
std::string monitor_name;
|
||||
std::mutex mtx;
|
||||
std::condition_variable cv;
|
||||
bool ready = false;
|
||||
bool SpeakerCapturerLinux::Prepare() {
|
||||
const auto deadline = std::chrono::steady_clock::now() + kStartupTimeout;
|
||||
mainloop_ = pa_mainloop_new();
|
||||
if (!mainloop_) return false;
|
||||
context_ =
|
||||
pa_context_new(pa_mainloop_get_api(mainloop_), "CrossDesk system audio");
|
||||
if (!context_ ||
|
||||
pa_context_connect(context_, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0)
|
||||
return false;
|
||||
if (!PumpUntil(
|
||||
[&] { return pa_context_get_state(context_) == PA_CONTEXT_READY; },
|
||||
deadline))
|
||||
return false;
|
||||
|
||||
pa_mainloop* mainloop = pa_mainloop_new();
|
||||
pa_mainloop_api* api = pa_mainloop_get_api(mainloop);
|
||||
pa_context* context = pa_context_new(api, "GetMonitor");
|
||||
|
||||
struct CallbackState {
|
||||
std::string* name;
|
||||
std::mutex* mtx;
|
||||
std::condition_variable* cv;
|
||||
bool* ready;
|
||||
} state{&monitor_name, &mtx, &cv, &ready};
|
||||
|
||||
pa_context_set_state_callback(
|
||||
context,
|
||||
[](pa_context* c, void* userdata) {
|
||||
auto* state = static_cast<CallbackState*>(userdata);
|
||||
if (pa_context_get_state(c) == PA_CONTEXT_READY) {
|
||||
pa_operation* operation = pa_context_get_server_info(
|
||||
c,
|
||||
[](pa_context*, const pa_server_info* info, void* userdata) {
|
||||
auto* state = static_cast<CallbackState*>(userdata);
|
||||
if (info && info->default_sink_name) {
|
||||
*(state->name) =
|
||||
std::string(info->default_sink_name) + ".monitor";
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(*(state->mtx));
|
||||
*(state->ready) = true;
|
||||
}
|
||||
state->cv->notify_one();
|
||||
},
|
||||
userdata);
|
||||
if (operation) {
|
||||
pa_operation_unref(operation);
|
||||
}
|
||||
}
|
||||
struct ServerResult {
|
||||
bool done = false;
|
||||
std::string sink;
|
||||
} server;
|
||||
pa_operation* operation = pa_context_get_server_info(
|
||||
context_,
|
||||
[](pa_context*, const pa_server_info* info, void* data) {
|
||||
auto& result = *static_cast<ServerResult*>(data);
|
||||
if (info && info->default_sink_name)
|
||||
result.sink = info->default_sink_name;
|
||||
result.done = true;
|
||||
},
|
||||
&state);
|
||||
&server);
|
||||
const bool got_server =
|
||||
operation && PumpUntil([&] { return server.done; }, deadline);
|
||||
ReleaseOperation(operation);
|
||||
if (!got_server || server.sink.empty()) return false;
|
||||
|
||||
pa_context_connect(context, nullptr, PA_CONTEXT_NOFLAGS, nullptr);
|
||||
// Query the actual monitor name; a changed/default device need not follow
|
||||
// the "<sink>.monitor" naming convention.
|
||||
struct SinkResult {
|
||||
bool done = false;
|
||||
std::string monitor;
|
||||
} sink;
|
||||
operation = pa_context_get_sink_info_by_name(
|
||||
context_, server.sink.c_str(),
|
||||
[](pa_context*, const pa_sink_info* info, int eol, void* data) {
|
||||
auto& result = *static_cast<SinkResult*>(data);
|
||||
if (info && info->monitor_source_name)
|
||||
result.monitor = info->monitor_source_name;
|
||||
if (eol != 0) result.done = true;
|
||||
},
|
||||
&sink);
|
||||
const bool got_sink =
|
||||
operation && PumpUntil([&] { return sink.done; }, deadline);
|
||||
ReleaseOperation(operation);
|
||||
if (!got_sink || sink.monitor.empty()) return false;
|
||||
|
||||
std::thread loop_thread([&]() {
|
||||
int ret = 0;
|
||||
pa_mainloop_run(mainloop, &ret);
|
||||
});
|
||||
const pa_sample_spec spec{PA_SAMPLE_S16LE, 48000, 1};
|
||||
stream_ = pa_stream_new(context_, "System audio", &spec, nullptr);
|
||||
if (!stream_) return false;
|
||||
pa_stream_set_read_callback(
|
||||
stream_,
|
||||
[](pa_stream* stream, size_t, void* data) {
|
||||
static_cast<SpeakerCapturerLinux*>(data)->ReadAudio(stream);
|
||||
},
|
||||
this);
|
||||
pa_buffer_attr attr{};
|
||||
attr.maxlength = static_cast<uint32_t>(-1);
|
||||
attr.fragsize = static_cast<uint32_t>(kFrameSizeBytes);
|
||||
if (pa_stream_connect_record(stream_, sink.monitor.c_str(), &attr,
|
||||
PA_STREAM_ADJUST_LATENCY) < 0)
|
||||
return false;
|
||||
if (!PumpUntil(
|
||||
[&] {
|
||||
const auto state = pa_stream_get_state(stream_);
|
||||
return state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state);
|
||||
},
|
||||
deadline) ||
|
||||
pa_stream_get_state(stream_) != PA_STREAM_READY)
|
||||
return false;
|
||||
LOG_INFO("System audio monitor ready: {}", sink.monitor);
|
||||
return true;
|
||||
}
|
||||
|
||||
void SpeakerCapturerLinux::Run() {
|
||||
const bool ready = Prepare();
|
||||
running_ = ready && !stop_flag_;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mtx);
|
||||
cv.wait_for(lock, std::chrono::seconds(2), [&] { return ready; });
|
||||
std::lock_guard<std::mutex> lock(state_mtx_);
|
||||
startup_success_ = running_;
|
||||
startup_done_ = true;
|
||||
}
|
||||
|
||||
pa_context_disconnect(context);
|
||||
pa_context_unref(context);
|
||||
pa_mainloop_quit(mainloop, 0);
|
||||
loop_thread.join();
|
||||
pa_mainloop_free(mainloop);
|
||||
|
||||
return monitor_name;
|
||||
startup_wake_.notify_one();
|
||||
if (!ready && !stop_flag_) {
|
||||
LOG_ERROR(
|
||||
"PulseAudio capture startup failed or timed out: {}",
|
||||
context_ ? pa_strerror(pa_context_errno(context_)) : "no context");
|
||||
}
|
||||
while (running_ && !stop_flag_) {
|
||||
if (pa_mainloop_iterate(mainloop_, 0, nullptr) < 0 ||
|
||||
pa_context_get_state(context_) != PA_CONTEXT_READY ||
|
||||
pa_stream_get_state(stream_) != PA_STREAM_READY)
|
||||
break;
|
||||
std::this_thread::sleep_for(kPollInterval);
|
||||
}
|
||||
running_ = false;
|
||||
Cleanup();
|
||||
}
|
||||
|
||||
int SpeakerCapturerLinux::Start() {
|
||||
if (!inited_ || mainloop_thread_.joinable()) return -1;
|
||||
if (!inited_) return -1;
|
||||
if (IsRunning()) return 0;
|
||||
Stop();
|
||||
stop_flag_ = false;
|
||||
|
||||
mainloop_thread_ = std::thread([this]() {
|
||||
std::string monitor_name = GetDefaultMonitorSourceName();
|
||||
if (monitor_name.empty()) {
|
||||
LOG_ERROR("Failed to get monitor source");
|
||||
return;
|
||||
}
|
||||
|
||||
mainloop_ = pa_threaded_mainloop_new();
|
||||
pa_mainloop_api* api = pa_threaded_mainloop_get_api(mainloop_);
|
||||
context_ = pa_context_new(api, "SpeakerCapturer");
|
||||
|
||||
pa_context_set_state_callback(
|
||||
context_,
|
||||
[](pa_context* c, void* userdata) {
|
||||
auto self = static_cast<SpeakerCapturerLinux*>(userdata);
|
||||
pa_context_state_t state = pa_context_get_state(c);
|
||||
if (state == PA_CONTEXT_READY || state == PA_CONTEXT_FAILED ||
|
||||
state == PA_CONTEXT_TERMINATED) {
|
||||
pa_threaded_mainloop_signal(self->mainloop_, 0);
|
||||
}
|
||||
},
|
||||
this);
|
||||
|
||||
if (pa_threaded_mainloop_start(mainloop_) < 0) {
|
||||
LOG_ERROR("Failed to start mainloop");
|
||||
Cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
pa_threaded_mainloop_lock(mainloop_);
|
||||
|
||||
if (pa_context_connect(context_, nullptr, PA_CONTEXT_NOFLAGS, nullptr) <
|
||||
0) {
|
||||
LOG_ERROR("Failed to connect context");
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
Cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
pa_context_state_t state = pa_context_get_state(context_);
|
||||
if (state == PA_CONTEXT_READY) break;
|
||||
if (!PA_CONTEXT_IS_GOOD(state) || stop_flag_) {
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
Cleanup();
|
||||
return;
|
||||
}
|
||||
pa_threaded_mainloop_wait(mainloop_);
|
||||
}
|
||||
|
||||
pa_sample_spec ss = {kFormat, kSampleRate, kChannels};
|
||||
stream_ = pa_stream_new(context_, "Capture", &ss, nullptr);
|
||||
|
||||
pa_stream_set_read_callback(
|
||||
stream_,
|
||||
[](pa_stream* s, size_t len, void* u) {
|
||||
auto self = static_cast<SpeakerCapturerLinux*>(u);
|
||||
if (self->paused_ || self->stop_flag_) return;
|
||||
|
||||
const void* data = nullptr;
|
||||
if (pa_stream_peek(s, &data, &len) < 0 || !data) return;
|
||||
|
||||
const uint8_t* p = static_cast<const uint8_t*>(data);
|
||||
self->frame_cache_.insert(self->frame_cache_.end(), p, p + len);
|
||||
|
||||
while (self->frame_cache_.size() >= kFrameSizeBytes) {
|
||||
std::vector<uint8_t> temp_frame(
|
||||
self->frame_cache_.begin(),
|
||||
self->frame_cache_.begin() + kFrameSizeBytes);
|
||||
self->cb_(temp_frame.data(), kFrameSizeBytes, "audio");
|
||||
self->frame_cache_.erase(
|
||||
self->frame_cache_.begin(),
|
||||
self->frame_cache_.begin() + kFrameSizeBytes);
|
||||
}
|
||||
|
||||
pa_stream_drop(s);
|
||||
},
|
||||
this);
|
||||
|
||||
pa_buffer_attr attr = {.maxlength = (uint32_t)-1,
|
||||
.tlength = 0,
|
||||
.prebuf = 0,
|
||||
.minreq = 0,
|
||||
.fragsize = (uint32_t)kFrameSizeBytes};
|
||||
|
||||
if (pa_stream_connect_record(stream_, monitor_name.c_str(), &attr,
|
||||
PA_STREAM_ADJUST_LATENCY) < 0) {
|
||||
LOG_ERROR("Failed to connect stream");
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
Cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
pa_stream_state_t s = pa_stream_get_state(stream_);
|
||||
if (s == PA_STREAM_READY) break;
|
||||
if (!PA_STREAM_IS_GOOD(s) || stop_flag_) {
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
Cleanup();
|
||||
return;
|
||||
}
|
||||
pa_threaded_mainloop_wait(mainloop_);
|
||||
}
|
||||
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
|
||||
while (!stop_flag_)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
});
|
||||
|
||||
paused_ = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state_mtx_);
|
||||
startup_done_ = false;
|
||||
startup_success_ = false;
|
||||
}
|
||||
mainloop_thread_ = std::thread([this] { Run(); });
|
||||
std::unique_lock<std::mutex> lock(state_mtx_);
|
||||
const bool started =
|
||||
startup_wake_.wait_for(lock, kStartupTimeout + std::chrono::seconds(1),
|
||||
[&] { return startup_done_; }) &&
|
||||
startup_success_;
|
||||
lock.unlock();
|
||||
if (!started) {
|
||||
Stop();
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SpeakerCapturerLinux::Stop() {
|
||||
stop_flag_ = true;
|
||||
|
||||
if (mainloop_) {
|
||||
pa_threaded_mainloop_lock(mainloop_);
|
||||
pa_threaded_mainloop_signal(mainloop_, 0);
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
}
|
||||
|
||||
if (mainloop_thread_.joinable()) {
|
||||
mainloop_thread_.join();
|
||||
}
|
||||
|
||||
Cleanup();
|
||||
if (mainloop_thread_.joinable()) mainloop_thread_.join();
|
||||
running_ = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SpeakerCapturerLinux::Destroy() {
|
||||
Stop();
|
||||
cb_ = nullptr;
|
||||
inited_ = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void SpeakerCapturerLinux::ReadAudio(pa_stream* stream) {
|
||||
const void* data = nullptr;
|
||||
size_t size = 0;
|
||||
if (pa_stream_peek(stream, &data, &size) < 0 || size == 0) return;
|
||||
if (data && !paused_ && !stop_flag_ && cb_) {
|
||||
const auto* bytes = static_cast<const uint8_t*>(data);
|
||||
frame_cache_.insert(frame_cache_.end(), bytes, bytes + size);
|
||||
size_t consumed = 0;
|
||||
while (!stop_flag_ && frame_cache_.size() - consumed >= kFrameSizeBytes) {
|
||||
cb_(frame_cache_.data() + consumed, kFrameSizeBytes, "audio");
|
||||
consumed += kFrameSizeBytes;
|
||||
}
|
||||
frame_cache_.erase(frame_cache_.begin(), frame_cache_.begin() + consumed);
|
||||
} else {
|
||||
frame_cache_.clear();
|
||||
}
|
||||
// Drop holes and paused data too, otherwise the read queue cannot advance.
|
||||
pa_stream_drop(stream);
|
||||
}
|
||||
|
||||
void SpeakerCapturerLinux::Cleanup() {
|
||||
if (stream_) {
|
||||
pa_stream_set_read_callback(stream_, nullptr, nullptr);
|
||||
pa_stream_disconnect(stream_);
|
||||
pa_stream_unref(stream_);
|
||||
stream_ = nullptr;
|
||||
}
|
||||
if (context_) {
|
||||
pa_context_disconnect(context_);
|
||||
pa_context_unref(context_);
|
||||
context_ = nullptr;
|
||||
}
|
||||
if (mainloop_) {
|
||||
pa_threaded_mainloop_stop(mainloop_);
|
||||
pa_threaded_mainloop_lock(mainloop_);
|
||||
|
||||
if (stream_) {
|
||||
pa_stream_disconnect(stream_);
|
||||
pa_stream_unref(stream_);
|
||||
stream_ = nullptr;
|
||||
}
|
||||
|
||||
if (context_) {
|
||||
pa_context_disconnect(context_);
|
||||
pa_context_unref(context_);
|
||||
context_ = nullptr;
|
||||
}
|
||||
|
||||
pa_threaded_mainloop_unlock(mainloop_);
|
||||
pa_threaded_mainloop_free(mainloop_);
|
||||
pa_mainloop_free(mainloop_);
|
||||
mainloop_ = nullptr;
|
||||
}
|
||||
|
||||
frame_cache_.clear();
|
||||
}
|
||||
|
||||
bool SpeakerCapturerLinux::IsRunning() const { return running_; }
|
||||
int SpeakerCapturerLinux::Pause() {
|
||||
paused_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SpeakerCapturerLinux::Resume() {
|
||||
paused_ = false;
|
||||
return 0;
|
||||
}
|
||||
} // namespace crossdesk
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -4,53 +4,59 @@
|
||||
* Copyright (c) 2025 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SPEAKER_CAPTURER_LINUX_H_
|
||||
#define _SPEAKER_CAPTURER_LINUX_H_
|
||||
#ifndef CROSSDESK_SPEAKER_CAPTURER_LINUX_H_
|
||||
#define CROSSDESK_SPEAKER_CAPTURER_LINUX_H_
|
||||
|
||||
#include <pulse/pulseaudio.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "speaker_capturer.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class SpeakerCapturerLinux : public SpeakerCapturer {
|
||||
public:
|
||||
SpeakerCapturerLinux();
|
||||
~SpeakerCapturerLinux();
|
||||
|
||||
SpeakerCapturerLinux() = default;
|
||||
~SpeakerCapturerLinux() override;
|
||||
int Init(speaker_data_cb cb) override;
|
||||
int Destroy() override;
|
||||
int Start() override;
|
||||
int Stop() override;
|
||||
|
||||
bool IsRunning() const override;
|
||||
int Pause();
|
||||
int Resume();
|
||||
|
||||
private:
|
||||
std::string GetDefaultMonitorSourceName();
|
||||
void Run();
|
||||
bool Prepare();
|
||||
bool PumpUntil(const std::function<bool()>& ready,
|
||||
std::chrono::steady_clock::time_point deadline);
|
||||
void Cleanup();
|
||||
void ReadAudio(pa_stream* stream);
|
||||
|
||||
private:
|
||||
speaker_data_cb cb_ = nullptr;
|
||||
|
||||
std::atomic<bool> inited_;
|
||||
std::atomic<bool> paused_;
|
||||
std::atomic<bool> stop_flag_;
|
||||
|
||||
speaker_data_cb cb_;
|
||||
bool inited_ = false;
|
||||
std::atomic<bool> paused_{false};
|
||||
std::atomic<bool> stop_flag_{false};
|
||||
std::atomic<bool> running_{false};
|
||||
std::thread mainloop_thread_;
|
||||
pa_threaded_mainloop* mainloop_ = nullptr;
|
||||
std::mutex state_mtx_;
|
||||
std::condition_variable startup_wake_;
|
||||
bool startup_done_ = false;
|
||||
bool startup_success_ = false;
|
||||
|
||||
// These objects are created, driven and freed exclusively by Run(). Stop
|
||||
// only changes an atomic flag and joins, never races PulseAudio callbacks.
|
||||
pa_mainloop* mainloop_ = nullptr;
|
||||
pa_context* context_ = nullptr;
|
||||
pa_stream* stream_ = nullptr;
|
||||
|
||||
std::mutex state_mtx_;
|
||||
std::vector<uint8_t> frame_cache_;
|
||||
};
|
||||
} // namespace crossdesk
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "runtime/cursor_position.h"
|
||||
#include "../../privacy/privacy_cursor_mac.h"
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
@@ -94,7 +95,7 @@ void AddKnownCursor(std::vector<KnownCursor>* cursors, NSCursor* cursor,
|
||||
|
||||
std::vector<KnownCursor> BuildKnownCursors() {
|
||||
std::vector<KnownCursor> cursors;
|
||||
cursors.reserve(16);
|
||||
cursors.reserve(40);
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
@@ -128,6 +129,55 @@ std::vector<KnownCursor> BuildKnownCursors() {
|
||||
RemoteCursorShape::w_resize);
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 150000
|
||||
if (@available(macOS 15.0, *)) {
|
||||
// Window-frame resize artwork differs from the legacy divider cursors
|
||||
// above. Include every edge/corner and both one-way variants. Inward
|
||||
// arrows point toward the frame's center; outward arrows point away.
|
||||
struct FrameResizeCursorMapping {
|
||||
NSCursorFrameResizePosition position;
|
||||
RemoteCursorShape bidirectional;
|
||||
RemoteCursorShape inward;
|
||||
RemoteCursorShape outward;
|
||||
};
|
||||
constexpr FrameResizeCursorMapping mappings[] = {
|
||||
{NSCursorFrameResizePositionTop, RemoteCursorShape::ns_resize,
|
||||
RemoteCursorShape::s_resize, RemoteCursorShape::n_resize},
|
||||
{NSCursorFrameResizePositionLeft, RemoteCursorShape::ew_resize,
|
||||
RemoteCursorShape::e_resize, RemoteCursorShape::w_resize},
|
||||
{NSCursorFrameResizePositionBottom, RemoteCursorShape::ns_resize,
|
||||
RemoteCursorShape::n_resize, RemoteCursorShape::s_resize},
|
||||
{NSCursorFrameResizePositionRight, RemoteCursorShape::ew_resize,
|
||||
RemoteCursorShape::w_resize, RemoteCursorShape::e_resize},
|
||||
{NSCursorFrameResizePositionTopLeft, RemoteCursorShape::nwse_resize,
|
||||
RemoteCursorShape::se_resize, RemoteCursorShape::nw_resize},
|
||||
{NSCursorFrameResizePositionTopRight, RemoteCursorShape::nesw_resize,
|
||||
RemoteCursorShape::sw_resize, RemoteCursorShape::ne_resize},
|
||||
{NSCursorFrameResizePositionBottomLeft, RemoteCursorShape::nesw_resize,
|
||||
RemoteCursorShape::ne_resize, RemoteCursorShape::sw_resize},
|
||||
{NSCursorFrameResizePositionBottomRight, RemoteCursorShape::nwse_resize,
|
||||
RemoteCursorShape::nw_resize, RemoteCursorShape::se_resize},
|
||||
};
|
||||
for (const FrameResizeCursorMapping& mapping : mappings) {
|
||||
AddKnownCursor(
|
||||
&cursors,
|
||||
[NSCursor frameResizeCursorFromPosition:mapping.position
|
||||
inDirections:NSCursorFrameResizeDirectionsAll],
|
||||
mapping.bidirectional);
|
||||
AddKnownCursor(
|
||||
&cursors,
|
||||
[NSCursor frameResizeCursorFromPosition:mapping.position
|
||||
inDirections:NSCursorFrameResizeDirectionsInward],
|
||||
mapping.inward);
|
||||
AddKnownCursor(
|
||||
&cursors,
|
||||
[NSCursor frameResizeCursorFromPosition:mapping.position
|
||||
inDirections:NSCursorFrameResizeDirectionsOutward],
|
||||
mapping.outward);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return cursors;
|
||||
}
|
||||
|
||||
@@ -161,7 +211,9 @@ bool CursorStateProvider::Sample(const std::vector<DisplayInfo>& displays,
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
NSCursor* cursor = NSCursor.currentSystemCursor;
|
||||
const bool visible = CGCursorIsVisible();
|
||||
const bool privacy_hidden = IsMacPrivacyCursorHidden();
|
||||
const bool visible = CGCursorIsVisible() || privacy_hidden;
|
||||
if (!cursor && privacy_hidden) cursor = NSCursor.arrowCursor;
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
state->seq = 0;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include "keyboard_converter.h"
|
||||
#include "../mac_injected_event.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk {
|
||||
@@ -11,7 +12,6 @@ namespace crossdesk {
|
||||
static OnKeyAction g_on_key_action = nullptr;
|
||||
static void* g_user_ptr = nullptr;
|
||||
static std::unordered_map<int, int> g_unmapped_keycode_to_vk;
|
||||
constexpr int64_t kCrossDeskInjectedKeyboardEvent = 0x43524f5353444553;
|
||||
|
||||
static int VkCodeFromUnicode(UniChar ch) {
|
||||
if (ch >= 'a' && ch <= 'z') {
|
||||
@@ -106,7 +106,7 @@ CGEventRef eventCallback(CGEventTapProxy proxy, CGEventType type,
|
||||
CGEventRef event, void* userInfo) {
|
||||
(void)proxy;
|
||||
if (CGEventGetIntegerValueField(event, kCGEventSourceUserData) ==
|
||||
kCrossDeskInjectedKeyboardEvent) {
|
||||
kCrossDeskInjectedEvent) {
|
||||
return event;
|
||||
}
|
||||
if (!g_on_key_action) {
|
||||
@@ -309,7 +309,7 @@ int PlatformKeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down,
|
||||
|
||||
CGEventSetFlags(event, ToCGEventFlags(injected_flags));
|
||||
CGEventSetIntegerValueField(event, kCGEventSourceUserData,
|
||||
kCrossDeskInjectedKeyboardEvent);
|
||||
kCrossDeskInjectedEvent);
|
||||
CGEventPost(kCGHIDEventTap, event);
|
||||
CFRelease(event);
|
||||
|
||||
@@ -323,7 +323,7 @@ int PlatformKeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down,
|
||||
return -1;
|
||||
}
|
||||
CGEventSetIntegerValueField(fn_release_event, kCGEventSourceUserData,
|
||||
kCrossDeskInjectedKeyboardEvent);
|
||||
kCrossDeskInjectedEvent);
|
||||
CGEventPost(kCGHIDEventTap, fn_release_event);
|
||||
CFRelease(fn_release_event);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _MAC_INJECTED_EVENT_H_
|
||||
#define _MAC_INJECTED_EVENT_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
// Shared by the keyboard/mouse injectors and the privacy input tap.
|
||||
inline constexpr int64_t kCrossDeskInjectedEvent = 0x43524f5353444553;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "mouse_controller.h"
|
||||
#include "../mac_injected_event.h"
|
||||
|
||||
#include <remote_action.h>
|
||||
|
||||
@@ -210,6 +211,8 @@ int PlatformMouseController::SendMouseCommand(RemoteAction remote_action,
|
||||
}
|
||||
|
||||
if (mouse_event) {
|
||||
CGEventSetIntegerValueField(mouse_event, kCGEventSourceUserData,
|
||||
kCrossDeskInjectedEvent);
|
||||
CGEventPost(kCGHIDEventTap, mouse_event);
|
||||
CFRelease(mouse_event);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
/* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved. */
|
||||
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <ApplicationServices/ApplicationServices.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <cstdlib>
|
||||
#include <libproc.h>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "privacy_backend.h"
|
||||
#include "privacy_capture_state.h"
|
||||
#include "privacy_cover_view.h"
|
||||
#include "privacy_cursor_mac.h"
|
||||
#include "rd_log.h"
|
||||
#include "../input/mac_injected_event.h"
|
||||
|
||||
// These windows never take keyboard focus. Remote clicks pass through them;
|
||||
// physical input is intercepted independently on the controller's run loop.
|
||||
@interface CrossDeskPrivacyPanel : NSPanel
|
||||
@end
|
||||
@implementation CrossDeskPrivacyPanel
|
||||
- (BOOL)canBecomeKeyWindow { return NO; }
|
||||
- (BOOL)canBecomeMainWindow { return NO; }
|
||||
@end
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
std::mutex tasks_mutex;
|
||||
std::deque<std::function<void()>> tasks;
|
||||
std::mutex capture_mutex;
|
||||
MacPrivacyCaptureState capture_state;
|
||||
|
||||
void OnMain(std::function<void()> task) {
|
||||
{
|
||||
std::lock_guard lock(tasks_mutex);
|
||||
tasks.push_back(std::move(task));
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), ^{ FlushMacPrivacyTasks(); });
|
||||
}
|
||||
|
||||
void PublishCovers(std::vector<uint32_t> windows, uint32_t cursor_window = 0) {
|
||||
{
|
||||
std::lock_guard lock(capture_mutex);
|
||||
capture_state.excluded_windows = std::move(windows);
|
||||
capture_state.cursor_window = cursor_window;
|
||||
++capture_state.revision;
|
||||
}
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[NSNotificationCenter.defaultCenter postNotificationName:@"CrossDeskPrivacyCoversChanged"
|
||||
object:nil];
|
||||
});
|
||||
}
|
||||
|
||||
struct Monitor {
|
||||
CGDirectDisplayID id = 0;
|
||||
CGRect bounds{}; // CoreGraphics desktop coordinates (points).
|
||||
NSRect frame{}; // AppKit desktop coordinates (bottom left).
|
||||
CrossDeskPrivacyPanel* __strong cover = nil;
|
||||
};
|
||||
struct WindowState {
|
||||
std::mutex mutex;
|
||||
std::vector<Monitor> monitors;
|
||||
bool recovered = true;
|
||||
bool recovering = false;
|
||||
bool covers_shown = false;
|
||||
bool check_queued = false;
|
||||
MacPrivacyCursor cursor;
|
||||
std::string failure;
|
||||
Clock::time_point checked = Clock::now();
|
||||
};
|
||||
|
||||
CrossDeskPrivacyPanel* MakePanel(NSRect frame, NSInteger level) {
|
||||
auto* panel = [[CrossDeskPrivacyPanel alloc]
|
||||
initWithContentRect:frame
|
||||
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
|
||||
backing:NSBackingStoreBuffered defer:NO];
|
||||
panel.releasedWhenClosed = NO;
|
||||
panel.hidesOnDeactivate = NO;
|
||||
panel.opaque = YES;
|
||||
panel.backgroundColor = NSColor.blackColor;
|
||||
panel.hasShadow = NO;
|
||||
panel.ignoresMouseEvents = YES;
|
||||
panel.level = level;
|
||||
panel.animationBehavior = NSWindowAnimationBehaviorNone;
|
||||
panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
|
||||
NSWindowCollectionBehaviorFullScreenAuxiliary |
|
||||
NSWindowCollectionBehaviorStationary |
|
||||
NSWindowCollectionBehaviorIgnoresCycle;
|
||||
// Exclusion is explicit in ScreenCaptureKit. SharingNone alone does not
|
||||
// exclude windows on recent macOS releases, and can hide them from discovery.
|
||||
panel.sharingType = NSWindowSharingReadOnly;
|
||||
return panel;
|
||||
}
|
||||
|
||||
bool IsSystemCursorPlane(NSDictionary* info, CGRect bounds) {
|
||||
const auto layer = [info[(__bridge NSString*)kCGWindowLayer] intValue];
|
||||
// WindowServer's cursor plane also carries small recording indicators.
|
||||
// Validate both its geometry and executable identity before ignoring it.
|
||||
if (layer != CGWindowLevelForKey(kCGCursorWindowLevelKey) ||
|
||||
bounds.size.width <= 0 || bounds.size.height <= 0 ||
|
||||
bounds.size.width > 512 || bounds.size.height > 512)
|
||||
return false;
|
||||
char executable[PROC_PIDPATHINFO_MAXSIZE]{};
|
||||
const auto pid = [info[(__bridge NSString*)kCGWindowOwnerPID] intValue];
|
||||
static const std::string system_executable = [] {
|
||||
char resolved[PROC_PIDPATHINFO_MAXSIZE]{};
|
||||
return realpath("/System/Library/PrivateFrameworks/SkyLight.framework/Resources/WindowServer",
|
||||
resolved) ? std::string(resolved) : std::string();
|
||||
}();
|
||||
return proc_pidpath(pid, executable, sizeof(executable)) > 0 &&
|
||||
!system_executable.empty() && system_executable == executable;
|
||||
}
|
||||
|
||||
std::string CoverageFailure(const std::vector<Monitor>& monitors) {
|
||||
uint32_t count = 0;
|
||||
if (CGGetActiveDisplayList(0, nullptr, &count) != kCGErrorSuccess || !count)
|
||||
return "No active macOS desktop; privacy screen unavailable";
|
||||
std::vector<CGDirectDisplayID> displays(count);
|
||||
if (CGGetActiveDisplayList(count, displays.data(), &count) != kCGErrorSuccess ||
|
||||
count != monitors.size())
|
||||
return "Display topology changed; turn privacy off to recover";
|
||||
for (const auto& m : monitors) {
|
||||
if (std::find(displays.begin(), displays.end(), m.id) == displays.end() ||
|
||||
!CGRectEqualToRect(CGDisplayBounds(m.id), m.bounds) ||
|
||||
!m.cover.visible || !m.cover.isOnActiveSpace ||
|
||||
!NSEqualRects(m.cover.frame, m.frame) || m.cover.alphaValue != 1.0)
|
||||
return "Privacy cover or display geometry changed; privacy screen unavailable";
|
||||
}
|
||||
NSDictionary* session = CFBridgingRelease(CGSessionCopyCurrentDictionary());
|
||||
if (!session || ![session[(__bridge NSString*)kCGSessionOnConsoleKey] boolValue])
|
||||
return "macOS session is not on console; privacy screen unavailable";
|
||||
|
||||
NSArray* windows = CFBridgingRelease(CGWindowListCopyWindowInfo(
|
||||
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
|
||||
kCGNullWindowID));
|
||||
if (!windows) return "Unable to verify macOS privacy window order";
|
||||
for (const auto& m : monitors) {
|
||||
bool found = false;
|
||||
for (NSDictionary* info in windows) {
|
||||
const auto window = [info[(__bridge NSString*)kCGWindowNumber] unsignedIntValue];
|
||||
if (window == m.cover.windowNumber) { found = true; break; }
|
||||
if ([info[(__bridge NSString*)kCGWindowAlpha] doubleValue] <= 0) continue;
|
||||
CGRect bounds{};
|
||||
if (!CGRectMakeWithDictionaryRepresentation(
|
||||
(__bridge CFDictionaryRef)info[(__bridge NSString*)kCGWindowBounds], &bounds))
|
||||
return "Unable to verify a window above the privacy cover";
|
||||
if (CGRectIntersectsRect(bounds, m.bounds)) {
|
||||
if (IsSystemCursorPlane(info, bounds)) continue;
|
||||
LOG_WARN("macOS privacy overlap: window={}, pid={}, layer={}, alpha={}, "
|
||||
"bounds=({}, {}, {}, {}), cover={}, cover_level={}",
|
||||
window,
|
||||
[info[(__bridge NSString*)kCGWindowOwnerPID] intValue],
|
||||
[info[(__bridge NSString*)kCGWindowLayer] intValue],
|
||||
[info[(__bridge NSString*)kCGWindowAlpha] doubleValue],
|
||||
bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height,
|
||||
m.cover.windowNumber, m.cover.level);
|
||||
return "A system or application window overlaps the privacy cover; privacy screen unavailable";
|
||||
}
|
||||
}
|
||||
if (!found) return "Privacy cover disappeared; privacy screen unavailable";
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
class MacPrivacyBackend final : public PrivacyBackend {
|
||||
public:
|
||||
MacPrivacyBackend() : state_(std::make_shared<WindowState>()) {
|
||||
loop_ = CFRunLoopGetCurrent();
|
||||
CFRetain(loop_);
|
||||
CFRunLoopSourceContext context{};
|
||||
wake_source_ = CFRunLoopSourceCreate(nullptr, 0, &context);
|
||||
CFRunLoopAddSource(loop_, wake_source_, kCFRunLoopDefaultMode);
|
||||
}
|
||||
~MacPrivacyBackend() override {
|
||||
Recover();
|
||||
CFRunLoopRemoveSource(loop_, wake_source_, kCFRunLoopDefaultMode);
|
||||
CFRelease(wake_source_);
|
||||
CFRelease(loop_);
|
||||
}
|
||||
PrivacyCapabilities Query() override {
|
||||
if (@available(macOS 14.0, *)) {
|
||||
if (!CGPreflightScreenCaptureAccess())
|
||||
return {false, false, "Grant Screen Recording permission to use privacy screen"};
|
||||
if (!AXIsProcessTrusted())
|
||||
return {false, false, "Grant Accessibility permission to protect local input and enable local recovery"};
|
||||
if (!MacPrivacyCursor::Supported())
|
||||
return {false, false, "Background cursor control unavailable on this macOS version"};
|
||||
return {true, true, "macOS privacy screen available (ScreenCaptureKit)"};
|
||||
}
|
||||
return {false, false, "Privacy screen requires macOS 14 or newer"};
|
||||
}
|
||||
bool Enable(bool block_input, const PrivacyScreenText& text, std::string& error) override {
|
||||
const auto caps = Query();
|
||||
if (!caps.overlay) { error = caps.reason; return false; }
|
||||
block_input_ = block_input;
|
||||
emergency_ = false;
|
||||
tap_failed_ = false;
|
||||
CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) |
|
||||
CGEventMaskBit(kCGEventFlagsChanged) | CGEventMaskBit(kCGEventLeftMouseDown) |
|
||||
CGEventMaskBit(kCGEventLeftMouseUp) | CGEventMaskBit(kCGEventRightMouseDown) |
|
||||
CGEventMaskBit(kCGEventRightMouseUp) | CGEventMaskBit(kCGEventMouseMoved) |
|
||||
CGEventMaskBit(kCGEventLeftMouseDragged) | CGEventMaskBit(kCGEventRightMouseDragged) |
|
||||
CGEventMaskBit(kCGEventOtherMouseDown) | CGEventMaskBit(kCGEventOtherMouseUp) |
|
||||
CGEventMaskBit(kCGEventOtherMouseDragged) | CGEventMaskBit(kCGEventScrollWheel) |
|
||||
CGEventMaskBit(14); // NX_SYSDEFINED: media/brightness keys.
|
||||
tap_ = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap,
|
||||
kCGEventTapOptionDefault, mask, Input, this);
|
||||
if (!tap_) { error = "Cannot install macOS privacy input tap"; return false; }
|
||||
tap_source_ = CFMachPortCreateRunLoopSource(nullptr, tap_, 0);
|
||||
if (!tap_source_) { error = "Cannot create macOS privacy input run loop"; return false; }
|
||||
CFRunLoopAddSource(loop_, tap_source_, kCFRunLoopDefaultMode);
|
||||
CGEventTapEnable(tap_, true);
|
||||
{
|
||||
std::lock_guard lock(state_->mutex);
|
||||
state_->recovered = false;
|
||||
state_->failure.clear();
|
||||
state_->checked = Clock::now();
|
||||
}
|
||||
auto state = state_;
|
||||
OnMain([state, text] {
|
||||
@autoreleasepool {
|
||||
std::lock_guard lock(state->mutex);
|
||||
if (!state->cursor.Prepare()) {
|
||||
state->failure = "Cannot prepare the privacy cursor";
|
||||
return;
|
||||
}
|
||||
std::vector<uint32_t> covers;
|
||||
for (NSScreen* screen in NSScreen.screens) {
|
||||
Monitor m;
|
||||
m.id = [screen.deviceDescription[@"NSScreenNumber"] unsignedIntValue];
|
||||
m.bounds = CGDisplayBounds(m.id);
|
||||
m.frame = screen.frame;
|
||||
NSView* content = CreateMacPrivacyCoverView(
|
||||
NSMakeRect(0, 0, m.frame.size.width, m.frame.size.height),
|
||||
[NSString stringWithUTF8String:text.unlock_hint.c_str()]);
|
||||
if (!content) {
|
||||
state->failure = "Could not load the CrossDesk privacy screen logo";
|
||||
break;
|
||||
}
|
||||
m.cover = MakePanel(m.frame, CGWindowLevelForKey(kCGScreenSaverWindowLevelKey) + 1);
|
||||
m.cover.contentView = content;
|
||||
// Register transparent windows first. Make them opaque only after
|
||||
// SCK has acknowledged exclusion, avoiding a black remote frame.
|
||||
m.cover.alphaValue = 0;
|
||||
[m.cover orderFrontRegardless];
|
||||
covers.push_back(static_cast<uint32_t>(m.cover.windowNumber));
|
||||
state->monitors.push_back(std::move(m));
|
||||
}
|
||||
PublishCovers(std::move(covers), state->cursor.WindowId());
|
||||
if (state->monitors.empty()) state->failure = "No active macOS desktop";
|
||||
state->checked = Clock::now();
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
void Recover() override {
|
||||
if (tap_) { CGEventTapEnable(tap_, false); CFMachPortInvalidate(tap_); }
|
||||
if (tap_source_) {
|
||||
CFRunLoopRemoveSource(loop_, tap_source_, kCFRunLoopDefaultMode);
|
||||
CFRelease(tap_source_); tap_source_ = nullptr;
|
||||
}
|
||||
if (tap_) { CFRelease(tap_); tap_ = nullptr; }
|
||||
{
|
||||
std::lock_guard lock(state_->mutex);
|
||||
if (state_->recovered || state_->recovering) return;
|
||||
state_->recovering = true;
|
||||
}
|
||||
auto state = state_;
|
||||
OnMain([state] {
|
||||
std::lock_guard lock(state->mutex);
|
||||
for (auto& m : state->monitors) {
|
||||
[m.cover orderOut:nil]; [m.cover close]; m.cover = nil;
|
||||
}
|
||||
state->monitors.clear();
|
||||
state->covers_shown = false;
|
||||
state->cursor.Restore();
|
||||
PublishCovers({});
|
||||
state->failure.clear();
|
||||
state->recovering = false;
|
||||
state->recovered = true;
|
||||
});
|
||||
}
|
||||
bool IsRecovered() const override {
|
||||
std::lock_guard lock(state_->mutex);
|
||||
return state_->recovered && !tap_;
|
||||
}
|
||||
bool RecoveryPending() const override {
|
||||
std::lock_guard lock(state_->mutex);
|
||||
return state_->recovering;
|
||||
}
|
||||
PrivacyHealth Poll() override {
|
||||
if (emergency_) { emergency_ = false; return {{}, true}; }
|
||||
if (tap_ && (tap_failed_ || !CGEventTapIsEnabled(tap_) || !AXIsProcessTrusted()))
|
||||
return {"Local input protection interrupted; privacy screen unavailable", false};
|
||||
auto state = state_;
|
||||
std::lock_guard lock(state->mutex);
|
||||
if (state->recovered || state->recovering) return {};
|
||||
if (!state->failure.empty()) return {state->failure, false};
|
||||
const auto age = Clock::now() - state->checked;
|
||||
if (age > std::chrono::seconds(1))
|
||||
return {"macOS privacy window checks stopped responding; privacy screen unavailable", false};
|
||||
if (!state->check_queued && age > std::chrono::milliseconds(100)) {
|
||||
state->check_queued = true;
|
||||
OnMain([state] {
|
||||
std::lock_guard lock(state->mutex);
|
||||
if (!state->recovered && !state->recovering && state->failure.empty()) {
|
||||
const auto capture = GetMacPrivacyCaptureState();
|
||||
if (!state->covers_shown && !state->monitors.empty() &&
|
||||
capture.revision == capture.applied_revision) {
|
||||
if (!state->cursor.Hide()) {
|
||||
state->failure = "Cannot hide the local privacy cursor";
|
||||
state->checked = Clock::now();
|
||||
state->check_queued = false;
|
||||
return;
|
||||
}
|
||||
for (auto& m : state->monitors) {
|
||||
m.cover.alphaValue = 1;
|
||||
[m.cover displayIfNeeded];
|
||||
[m.cover orderFrontRegardless];
|
||||
}
|
||||
state->covers_shown = true;
|
||||
}
|
||||
if (state->covers_shown) {
|
||||
state->failure = state->cursor.Healthy() ? CoverageFailure(state->monitors)
|
||||
: "Cannot keep the local privacy cursor hidden";
|
||||
}
|
||||
}
|
||||
state->checked = Clock::now();
|
||||
state->check_queued = false;
|
||||
});
|
||||
}
|
||||
const auto capture = GetMacPrivacyCaptureState();
|
||||
return {{}, false, state->covers_shown &&
|
||||
capture.revision == capture.applied_revision};
|
||||
}
|
||||
void WaitForEvents(unsigned timeout_ms) override {
|
||||
@autoreleasepool {
|
||||
CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout_ms / 1000.0, true);
|
||||
}
|
||||
}
|
||||
void Wake() override { CFRunLoopSourceSignal(wake_source_); CFRunLoopWakeUp(loop_); }
|
||||
private:
|
||||
static CGEventRef Input(CGEventTapProxy, CGEventType type, CGEventRef event, void* context) {
|
||||
auto* self = static_cast<MacPrivacyBackend*>(context);
|
||||
if (type == kCGEventTapDisabledByTimeout || type == kCGEventTapDisabledByUserInput) {
|
||||
self->tap_failed_ = true;
|
||||
CGEventTapEnable(self->tap_, true); // Keep the local recovery chord usable.
|
||||
return event;
|
||||
}
|
||||
if (!event) return event;
|
||||
if (CGEventGetIntegerValueField(event, kCGEventSourceUserData) == kCrossDeskInjectedEvent &&
|
||||
CGEventGetIntegerValueField(event, kCGEventSourceUnixProcessID) == getpid()) return event;
|
||||
const auto flags = CGEventGetFlags(event);
|
||||
const auto chord = kCGEventFlagMaskControl | kCGEventFlagMaskAlternate | kCGEventFlagMaskShift;
|
||||
if (type == kCGEventKeyDown && (flags & chord) == chord &&
|
||||
CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode) == 53) {
|
||||
self->emergency_ = true;
|
||||
return nullptr;
|
||||
}
|
||||
return self->block_input_ ? nullptr : event;
|
||||
}
|
||||
std::shared_ptr<WindowState> state_;
|
||||
CFRunLoopRef loop_ = nullptr;
|
||||
CFRunLoopSourceRef wake_source_ = nullptr;
|
||||
CFMachPortRef tap_ = nullptr;
|
||||
CFRunLoopSourceRef tap_source_ = nullptr;
|
||||
bool block_input_ = false;
|
||||
bool emergency_ = false;
|
||||
bool tap_failed_ = false;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
void FlushMacPrivacyTasks() {
|
||||
if (![NSThread isMainThread]) return;
|
||||
std::deque<std::function<void()>> pending;
|
||||
{
|
||||
std::lock_guard lock(tasks_mutex);
|
||||
pending.swap(tasks);
|
||||
}
|
||||
@autoreleasepool { for (auto& task : pending) task(); }
|
||||
}
|
||||
MacPrivacyCaptureState GetMacPrivacyCaptureState() {
|
||||
std::lock_guard lock(capture_mutex);
|
||||
return capture_state;
|
||||
}
|
||||
void AcknowledgeMacPrivacyCapture(uint64_t revision) {
|
||||
std::lock_guard lock(capture_mutex);
|
||||
if (revision == capture_state.revision) capture_state.applied_revision = revision;
|
||||
}
|
||||
std::unique_ptr<PrivacyBackend> CreateMacPrivacyBackend() {
|
||||
return std::make_unique<MacPrivacyBackend>();
|
||||
}
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
#ifndef _PRIVACY_CAPTURE_STATE_H_
|
||||
#define _PRIVACY_CAPTURE_STATE_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
struct MacPrivacyCaptureState {
|
||||
uint64_t revision = 0;
|
||||
uint64_t applied_revision = 0;
|
||||
std::vector<uint32_t> excluded_windows;
|
||||
uint32_t cursor_window = 0;
|
||||
};
|
||||
MacPrivacyCaptureState GetMacPrivacyCaptureState();
|
||||
void AcknowledgeMacPrivacyCapture(uint64_t revision);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_COVER_VIEW_H_
|
||||
#define _PRIVACY_COVER_VIEW_H_
|
||||
|
||||
#import <AppKit/AppKit.h>
|
||||
|
||||
namespace crossdesk {
|
||||
// Returns nil if the CrossDesk icon resource cannot be loaded.
|
||||
NSView* CreateMacPrivacyCoverView(NSRect frame, NSString* unlock_hint);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,106 @@
|
||||
/* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved. */
|
||||
|
||||
#include "privacy_cover_view.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
NSImage* LoadPrivacyLogo() {
|
||||
// The macOS installer currently packages the icon as "crossedesk.icns".
|
||||
for (NSString* name in @[@"crossdesk", @"crossedesk"]) {
|
||||
NSString* path = [NSBundle.mainBundle pathForResource:name ofType:@"icns"];
|
||||
if (path) {
|
||||
NSImage* image = [[NSImage alloc] initWithContentsOfFile:path];
|
||||
if (image.valid) return image;
|
||||
}
|
||||
}
|
||||
// Support unbundled development builds, including launches from outside
|
||||
// the repository. No source-tree path is embedded in the executable.
|
||||
NSString* resource = @"apps/desktop/resources/macos/crossdesk.icns";
|
||||
NSString* directory = NSBundle.mainBundle.executablePath.stringByDeletingLastPathComponent;
|
||||
NSMutableArray<NSString*>* paths = [NSMutableArray arrayWithObject:
|
||||
[NSFileManager.defaultManager.currentDirectoryPath stringByAppendingPathComponent:resource]];
|
||||
for (int depth = 0; directory.length && depth <= 4; ++depth) {
|
||||
[paths addObject:[directory stringByAppendingPathComponent:resource]];
|
||||
directory = directory.stringByDeletingLastPathComponent;
|
||||
}
|
||||
for (NSString* path in paths) {
|
||||
NSImage* image = [[NSImage alloc] initWithContentsOfFile:path.stringByStandardizingPath];
|
||||
if (image.valid) return image;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSAttributedString* Text(NSString* value, CGFloat size, NSFontWeight weight, NSColor* color) {
|
||||
NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc] init];
|
||||
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
|
||||
return [[NSAttributedString alloc] initWithString:value attributes:@{
|
||||
NSFontAttributeName: [NSFont systemFontOfSize:size weight:weight],
|
||||
NSForegroundColorAttributeName: color,
|
||||
NSParagraphStyleAttributeName: paragraph}];
|
||||
}
|
||||
constexpr NSStringDrawingOptions kTextOptions =
|
||||
NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
|
||||
|
||||
CGFloat TextHeight(NSAttributedString* text, CGFloat width) {
|
||||
return std::ceil([text boundingRectWithSize:NSMakeSize(width, CGFLOAT_MAX)
|
||||
options:kTextOptions].size.height);
|
||||
}
|
||||
}
|
||||
|
||||
@interface CrossDeskPrivacyCoverView : NSView
|
||||
@property(nonatomic, strong) NSImage* logo;
|
||||
@property(nonatomic, copy) NSString* unlockHint;
|
||||
@end
|
||||
|
||||
@implementation CrossDeskPrivacyCoverView
|
||||
- (BOOL)isOpaque { return YES; }
|
||||
- (BOOL)isFlipped { return YES; }
|
||||
- (void)drawRect:(NSRect)dirtyRect {
|
||||
[NSColor.blackColor setFill];
|
||||
NSRectFill(self.bounds);
|
||||
const CGFloat width = NSWidth(self.bounds), height = NSHeight(self.bounds);
|
||||
if (width <= 0 || height <= 0) return;
|
||||
// Match the Windows cover's sizes, colors and bottom-left alignment.
|
||||
// AppKit coordinates are points; Retina backing scale is applied by AppKit.
|
||||
const CGFloat scale = std::min({CGFloat(1), width / 640, height / 200});
|
||||
const CGFloat margin = 32 * scale, text_width = 398 * scale;
|
||||
NSColor* foreground = [NSColor colorWithSRGBRed:245.0 / 255 green:247.0 / 255
|
||||
blue:250.0 / 255 alpha:1];
|
||||
NSColor* muted = [NSColor colorWithSRGBRed:181.0 / 255 green:190.0 / 255
|
||||
blue:204.0 / 255 alpha:1];
|
||||
NSAttributedString* brand = Text(@"CrossDesk", 14 * scale, NSFontWeightSemibold, foreground);
|
||||
NSAttributedString* hint = Text(self.unlockHint, 16 * scale, NSFontWeightRegular, muted);
|
||||
NSAttributedString* shortcut = Text(@"Control + Option + Shift + Esc", 24 * scale,
|
||||
NSFontWeightSemibold, foreground);
|
||||
const CGFloat logo_size = std::ceil(brand.size.width);
|
||||
const CGFloat brand_height = TextHeight(brand, logo_size);
|
||||
const CGFloat hint_height = TextHeight(hint, text_width);
|
||||
const CGFloat shortcut_height = TextHeight(shortcut, text_width);
|
||||
const CGFloat bottom = height - margin;
|
||||
const CGFloat logo_top = bottom - brand_height - 6 * scale - logo_size;
|
||||
[self.logo drawInRect:NSMakeRect(margin, logo_top, logo_size, logo_size)
|
||||
fromRect:NSZeroRect operation:NSCompositingOperationSourceOver
|
||||
fraction:1 respectFlipped:YES hints:@{NSImageHintInterpolation: @(NSImageInterpolationHigh)}];
|
||||
[brand drawWithRect:NSMakeRect(margin, bottom - brand_height, logo_size, brand_height)
|
||||
options:kTextOptions];
|
||||
const CGFloat text_left = margin + logo_size + 24 * scale;
|
||||
[hint drawWithRect:NSMakeRect(text_left, bottom - shortcut_height - 12 * scale - hint_height,
|
||||
text_width, hint_height) options:kTextOptions];
|
||||
[shortcut drawWithRect:NSMakeRect(text_left, bottom - shortcut_height,
|
||||
text_width, shortcut_height) options:kTextOptions];
|
||||
}
|
||||
@end
|
||||
|
||||
namespace crossdesk {
|
||||
NSView* CreateMacPrivacyCoverView(NSRect frame, NSString* unlock_hint) {
|
||||
NSImage* logo = LoadPrivacyLogo();
|
||||
if (!logo) return nil;
|
||||
auto* view = [[CrossDeskPrivacyCoverView alloc] initWithFrame:frame];
|
||||
view.logo = logo;
|
||||
view.unlockHint = unlock_hint ?: @"To turn off the privacy screen, press";
|
||||
view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
|
||||
return view;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-13
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_CURSOR_MAC_H_
|
||||
#define _PRIVACY_CURSOR_MAC_H_
|
||||
|
||||
#include <memory>
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
// Main-thread resource. Hides only for the lifetime of a local privacy cover;
|
||||
// does not take focus, move the pointer, or suppress remote input.
|
||||
class MacPrivacyCursor {
|
||||
public:
|
||||
MacPrivacyCursor();
|
||||
~MacPrivacyCursor();
|
||||
static bool Supported();
|
||||
bool Prepare();
|
||||
bool Hide();
|
||||
bool Healthy() const;
|
||||
uint32_t WindowId() const;
|
||||
void Restore();
|
||||
private:
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
|
||||
// Local hiding must not be reported as an invisible cursor to controllers.
|
||||
bool IsMacPrivacyCursorHidden();
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,157 @@
|
||||
/* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved. */
|
||||
#include "privacy_cursor_mac.h"
|
||||
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <ApplicationServices/ApplicationServices.h>
|
||||
#include <atomic>
|
||||
#include <dlfcn.h>
|
||||
|
||||
@interface CrossDeskPrivacyCursorPanel : NSPanel
|
||||
@end
|
||||
@implementation CrossDeskPrivacyCursorPanel
|
||||
- (BOOL)canBecomeKeyWindow { return NO; }
|
||||
- (BOOL)canBecomeMainWindow { return NO; }
|
||||
@end
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
std::atomic<bool> hidden_by_privacy{false};
|
||||
struct CursorApi {
|
||||
using Connection = int (*)();
|
||||
using Copy = CGError (*)(int, int, CFStringRef, CFTypeRef*);
|
||||
using Set = CGError (*)(int, int, CFStringRef, CFTypeRef);
|
||||
Connection connection = reinterpret_cast<Connection>(dlsym(RTLD_DEFAULT, "CGSMainConnectionID"));
|
||||
Copy copy = reinterpret_cast<Copy>(dlsym(RTLD_DEFAULT, "CGSCopyConnectionProperty"));
|
||||
Set set = reinterpret_cast<Set>(dlsym(RTLD_DEFAULT, "CGSSetConnectionProperty"));
|
||||
};
|
||||
const CursorApi& Api() { static const CursorApi api; return api; }
|
||||
CFStringRef const kBackgroundCursor = CFSTR("SetsCursorInBackground");
|
||||
}
|
||||
|
||||
struct MacPrivacyCursor::Impl {
|
||||
int connection = 0;
|
||||
bool previous_background = false;
|
||||
bool background_changed = false;
|
||||
unsigned hide_count = 0;
|
||||
unsigned visible_ticks = 0;
|
||||
bool healthy = true;
|
||||
NSTimer* __strong timer = nil;
|
||||
CrossDeskPrivacyCursorPanel* __strong panel = nil;
|
||||
NSImageView* __strong view = nil;
|
||||
|
||||
void UpdateImage() {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
NSCursor* cursor = NSCursor.currentSystemCursor ?: NSCursor.arrowCursor;
|
||||
#pragma clang diagnostic pop
|
||||
NSImage* image = cursor.image;
|
||||
if (!image || image.size.width <= 0 || image.size.height <= 0) return;
|
||||
const NSPoint point = NSEvent.mouseLocation;
|
||||
const NSSize size = image.size;
|
||||
[panel setFrame:NSMakeRect(point.x - cursor.hotSpot.x,
|
||||
point.y - size.height + cursor.hotSpot.y, size.width, size.height) display:NO];
|
||||
view.image = image;
|
||||
[panel displayIfNeeded];
|
||||
}
|
||||
|
||||
bool KeepHidden() {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
if (hide_count && !CGCursorIsVisible()) { visible_ticks = 0; return true; }
|
||||
#pragma clang diagnostic pop
|
||||
if (++visible_ticks > 6 ||
|
||||
CGDisplayHideCursor(kCGDirectMainDisplay) != kCGErrorSuccess) return false;
|
||||
++hide_count;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
MacPrivacyCursor::MacPrivacyCursor() : impl_(std::make_unique<Impl>()) {}
|
||||
MacPrivacyCursor::~MacPrivacyCursor() { Restore(); }
|
||||
bool MacPrivacyCursor::Supported() {
|
||||
return Api().connection && Api().copy && Api().set;
|
||||
}
|
||||
bool MacPrivacyCursor::Prepare() {
|
||||
if (impl_->panel) return true;
|
||||
if (!Supported()) return false;
|
||||
// A cursor sprite below the local cover is captured only for clients that
|
||||
// request an embedded cursor. Desktop clients exclude it and use metadata.
|
||||
impl_->panel = [[CrossDeskPrivacyCursorPanel alloc] initWithContentRect:NSMakeRect(0, 0, 32, 32)
|
||||
styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel
|
||||
backing:NSBackingStoreBuffered defer:NO];
|
||||
auto* panel = impl_->panel;
|
||||
panel.releasedWhenClosed = NO;
|
||||
panel.hidesOnDeactivate = NO;
|
||||
panel.opaque = NO;
|
||||
panel.backgroundColor = NSColor.clearColor;
|
||||
panel.hasShadow = NO;
|
||||
panel.ignoresMouseEvents = YES;
|
||||
panel.level = CGWindowLevelForKey(kCGScreenSaverWindowLevelKey);
|
||||
panel.animationBehavior = NSWindowAnimationBehaviorNone;
|
||||
panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
|
||||
NSWindowCollectionBehaviorFullScreenAuxiliary | NSWindowCollectionBehaviorStationary |
|
||||
NSWindowCollectionBehaviorIgnoresCycle;
|
||||
panel.sharingType = NSWindowSharingReadOnly;
|
||||
impl_->view = [[NSImageView alloc] initWithFrame:panel.contentView.bounds];
|
||||
impl_->view.imageScaling = NSImageScaleNone;
|
||||
impl_->view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
|
||||
panel.contentView = impl_->view;
|
||||
panel.alphaValue = 0;
|
||||
impl_->UpdateImage();
|
||||
[panel orderFrontRegardless];
|
||||
return panel != nil && panel.windowNumber > 0;
|
||||
}
|
||||
bool MacPrivacyCursor::Hide() {
|
||||
if (impl_->timer) return true;
|
||||
if (!Prepare()) return false;
|
||||
impl_->connection = Api().connection();
|
||||
impl_->previous_background = false;
|
||||
CFTypeRef previous = nullptr;
|
||||
if (Api().copy(impl_->connection, impl_->connection, kBackgroundCursor, &previous) == kCGErrorSuccess && previous)
|
||||
impl_->previous_background = CFEqual(previous, kCFBooleanTrue);
|
||||
if (previous) CFRelease(previous);
|
||||
// This connection-scoped WindowServer property is also used by Deskflow.
|
||||
// Resolve it dynamically: an unavailable API disables optional privacy only.
|
||||
if (Api().set(impl_->connection, impl_->connection, kBackgroundCursor, kCFBooleanTrue) != kCGErrorSuccess)
|
||||
return false;
|
||||
impl_->background_changed = true;
|
||||
impl_->healthy = true;
|
||||
impl_->visible_ticks = 0;
|
||||
hidden_by_privacy = true;
|
||||
if (!impl_->KeepHidden()) { Restore(); return false; }
|
||||
impl_->UpdateImage();
|
||||
impl_->panel.alphaValue = 1;
|
||||
auto* state = impl_.get();
|
||||
impl_->timer = [NSTimer timerWithTimeInterval:1.0 / 60 repeats:YES block:^(NSTimer*) {
|
||||
if (state->healthy) state->healthy = state->KeepHidden();
|
||||
state->UpdateImage();
|
||||
}];
|
||||
[[NSRunLoop mainRunLoop] addTimer:impl_->timer forMode:NSRunLoopCommonModes];
|
||||
return true;
|
||||
}
|
||||
bool MacPrivacyCursor::Healthy() const { return impl_->timer && impl_->healthy; }
|
||||
uint32_t MacPrivacyCursor::WindowId() const {
|
||||
return impl_->panel ? static_cast<uint32_t>(impl_->panel.windowNumber) : 0;
|
||||
}
|
||||
void MacPrivacyCursor::Restore() {
|
||||
[impl_->timer invalidate];
|
||||
impl_->timer = nil;
|
||||
[impl_->panel orderOut:nil];
|
||||
[impl_->panel close];
|
||||
impl_->panel = nil;
|
||||
impl_->view = nil;
|
||||
// Balance only our own successful hide calls, including re-hides after
|
||||
// WindowServer changes cursor ownership when a remote click activates an app.
|
||||
while (impl_->hide_count) {
|
||||
CGDisplayShowCursor(kCGDirectMainDisplay);
|
||||
--impl_->hide_count;
|
||||
}
|
||||
hidden_by_privacy = false;
|
||||
if (impl_->background_changed) {
|
||||
Api().set(impl_->connection, impl_->connection, kBackgroundCursor,
|
||||
impl_->previous_background ? kCFBooleanTrue : kCFBooleanFalse);
|
||||
impl_->background_changed = false;
|
||||
}
|
||||
}
|
||||
bool IsMacPrivacyCursorHidden() { return hidden_by_privacy.load(); }
|
||||
}
|
||||
@@ -7,6 +7,12 @@ namespace crossdesk {
|
||||
ScreenCapturerSck::ScreenCapturerSck() {}
|
||||
ScreenCapturerSck::~ScreenCapturerSck() {}
|
||||
|
||||
void ScreenCapturerSck::SetPrivacyController(PrivacyController* privacy) {
|
||||
privacy_ = privacy;
|
||||
if (screen_capturer_sck_impl_)
|
||||
screen_capturer_sck_impl_->SetPrivacyController(privacy);
|
||||
}
|
||||
|
||||
int ScreenCapturerSck::Init(const int fps, cb_desktop_data cb) {
|
||||
if (cb) {
|
||||
on_data_ = cb;
|
||||
@@ -16,6 +22,7 @@ int ScreenCapturerSck::Init(const int fps, cb_desktop_data cb) {
|
||||
}
|
||||
|
||||
screen_capturer_sck_impl_ = CreateScreenCapturerSck();
|
||||
screen_capturer_sck_impl_->SetPrivacyController(privacy_);
|
||||
const int ret = screen_capturer_sck_impl_->Init(fps, on_data_);
|
||||
if (ret != 0) {
|
||||
screen_capturer_sck_impl_.reset();
|
||||
|
||||
@@ -25,6 +25,7 @@ class ScreenCapturerSck : public ScreenCapturer {
|
||||
|
||||
public:
|
||||
int Init(const int fps, cb_desktop_data cb) override;
|
||||
void SetPrivacyController(PrivacyController* privacy) override;
|
||||
int Destroy() override;
|
||||
int Start(bool show_cursor) override;
|
||||
int Stop() override;
|
||||
@@ -57,6 +58,7 @@ class ScreenCapturerSck : public ScreenCapturer {
|
||||
|
||||
private:
|
||||
std::unique_ptr<ScreenCapturer> screen_capturer_sck_impl_;
|
||||
PrivacyController* privacy_ = nullptr;
|
||||
};
|
||||
} // namespace crossdesk
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -26,6 +26,9 @@
|
||||
#include "display_info.h"
|
||||
#include <display_stream_id.h>
|
||||
#include "rd_log.h"
|
||||
#include "privacy_controller.h"
|
||||
#include "../privacy/privacy_capture_state.h"
|
||||
#include <algorithm>
|
||||
|
||||
using namespace crossdesk;
|
||||
|
||||
@@ -110,13 +113,18 @@ API_AVAILABLE(macos(14.0))
|
||||
|
||||
- (instancetype)initWithCapturer:(ScreenCapturerSckImpl *)capturer;
|
||||
|
||||
- (void)onShareableContentCreated:(SCShareableContent *)content;
|
||||
- (void)onShareableContentCreated:(SCShareableContent *)content generation:(uint64_t)generation
|
||||
revision:(uint64_t)revision;
|
||||
|
||||
// Called just before the capturer is destroyed. This avoids a dangling pointer,
|
||||
// and prevents any new calls into a deleted capturer. If any method-call on the
|
||||
// capturer is currently running on a different thread, this blocks until it
|
||||
// completes.
|
||||
- (void)releaseCapturer;
|
||||
- (void)privacyCoversChanged:(NSNotification*)notification;
|
||||
- (void)configurationFinished:(SCStream*)stream generation:(uint64_t)generation
|
||||
revision:(uint64_t)revision complete:(BOOL)complete
|
||||
configuration:(SCStreamConfiguration*)configuration error:(NSError*)error;
|
||||
@end
|
||||
|
||||
class API_AVAILABLE(macos(14.0)) ScreenCapturerSckImpl : public ScreenCapturer {
|
||||
@@ -129,6 +137,7 @@ class API_AVAILABLE(macos(14.0)) ScreenCapturerSckImpl : public ScreenCapturer {
|
||||
|
||||
public:
|
||||
int Init(const int fps, cb_desktop_data cb) override;
|
||||
void SetPrivacyController(PrivacyController* privacy) override { privacy_ = privacy; }
|
||||
|
||||
int Start(bool show_cursor) override;
|
||||
|
||||
@@ -156,11 +165,30 @@ class API_AVAILABLE(macos(14.0)) ScreenCapturerSckImpl : public ScreenCapturer {
|
||||
bool capture_requested_ = false;
|
||||
bool invalid_stream_id_logged_ = false;
|
||||
bool native_output_logged_ = false;
|
||||
PrivacyController* privacy_ = nullptr;
|
||||
uint64_t configuration_generation_ = 0;
|
||||
bool configuration_in_flight_ = false;
|
||||
bool reconfigure_pending_ = false;
|
||||
SCStreamConfiguration* __strong applied_configuration_ = nil;
|
||||
|
||||
public:
|
||||
// Called by SckHelper when shareable content is returned by ScreenCaptureKit. `content` will be
|
||||
// nil if an error occurred. May run on an arbitrary thread.
|
||||
void OnShareableContentCreated(SCShareableContent *content);
|
||||
void OnShareableContentCreated(SCShareableContent *content, uint64_t generation,
|
||||
uint64_t revision);
|
||||
void ConfigurationFinished(SCStream* source, uint64_t generation, uint64_t revision,
|
||||
bool complete, SCStreamConfiguration* configuration,
|
||||
NSError* error);
|
||||
void RetryPrivacyFilter();
|
||||
void PrivacyCoversChanged() { StartOrReconfigureCapturer(); }
|
||||
void CaptureStopped(SCStream* source, NSError* error) {
|
||||
{
|
||||
std::lock_guard lock(lock_);
|
||||
if (!capture_requested_ || source != stream_) return;
|
||||
}
|
||||
LOG_ERROR("ScreenCaptureKit stream stopped: {}", NSErrorToString(error));
|
||||
if (privacy_) privacy_->Fail("ScreenCaptureKit stream stopped");
|
||||
}
|
||||
// Called by SckHelper to notify of a newly captured frame. May run on an arbitrary thread.
|
||||
// void OnNewIOSurface(IOSurfaceRef io_surface, CFDictionaryRef attachment);
|
||||
void OnNewCVPixelBuffer(CVPixelBufferRef pixelBuffer, CFDictionaryRef attachment);
|
||||
@@ -389,6 +417,7 @@ int ScreenCapturerSckImpl::Start(bool show_cursor) {
|
||||
capture_requested_ = true;
|
||||
invalid_stream_id_logged_ = false;
|
||||
}
|
||||
if (privacy_) privacy_->CaptureChanged(true);
|
||||
StartOrReconfigureCapturer();
|
||||
return 0;
|
||||
}
|
||||
@@ -446,6 +475,7 @@ int ScreenCapturerSckImpl::ResetToInitialMonitor() {
|
||||
}
|
||||
|
||||
int ScreenCapturerSckImpl::Destroy() {
|
||||
if (privacy_) privacy_->CaptureChanged(false);
|
||||
SckHelper *helper_to_release = nil;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(lock_);
|
||||
@@ -455,6 +485,9 @@ int ScreenCapturerSckImpl::Destroy() {
|
||||
stream_ = nil;
|
||||
}
|
||||
capture_requested_ = false;
|
||||
configuration_in_flight_ = reconfigure_pending_ = false;
|
||||
applied_configuration_ = nil;
|
||||
++configuration_generation_;
|
||||
current_display_ = 0;
|
||||
current_stream_id_.clear();
|
||||
permanent_error_ = false;
|
||||
@@ -469,8 +502,12 @@ int ScreenCapturerSckImpl::Destroy() {
|
||||
}
|
||||
|
||||
int ScreenCapturerSckImpl::Stop() {
|
||||
if (privacy_) privacy_->CaptureChanged(false);
|
||||
std::lock_guard<std::mutex> lock(lock_);
|
||||
capture_requested_ = false;
|
||||
configuration_in_flight_ = reconfigure_pending_ = false;
|
||||
applied_configuration_ = nil;
|
||||
++configuration_generation_;
|
||||
if (stream_) {
|
||||
LOG_INFO("Stopping stream");
|
||||
[stream_ stopCaptureWithCompletionHandler:nil];
|
||||
@@ -481,24 +518,36 @@ int ScreenCapturerSckImpl::Stop() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void ScreenCapturerSckImpl::OnShareableContentCreated(SCShareableContent *content) {
|
||||
void ScreenCapturerSckImpl::OnShareableContentCreated(SCShareableContent *content,
|
||||
uint64_t generation, uint64_t revision) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(lock_);
|
||||
if (!capture_requested_) {
|
||||
if (!capture_requested_ || generation != configuration_generation_) {
|
||||
LOG_INFO("Ignoring stale ScreenCaptureKit display refresh after stop");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// The window list belongs to the privacy revision present when the request
|
||||
// was issued. A newer cover must be enumerated by a new request.
|
||||
if (GetMacPrivacyCaptureState().revision != revision) {
|
||||
StartOrReconfigureCapturer();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
LOG_ERROR("getShareableContent failed");
|
||||
permanent_error_ = true;
|
||||
if (privacy_) privacy_->Fail("Could not refresh ScreenCaptureKit privacy content");
|
||||
std::lock_guard lock(lock_);
|
||||
if (!stream_) permanent_error_ = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!content.displays || content.displays.count == 0) {
|
||||
LOG_ERROR("getShareableContent returned no displays");
|
||||
permanent_error_ = true;
|
||||
if (privacy_) privacy_->Fail("No shareable displays available for privacy");
|
||||
std::lock_guard lock(lock_);
|
||||
if (!stream_) permanent_error_ = true;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -506,7 +555,7 @@ void ScreenCapturerSckImpl::OnShareableContentCreated(SCShareableContent *conten
|
||||
bool show_cursor = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(lock_);
|
||||
if (!capture_requested_) return;
|
||||
if (!capture_requested_ || generation != configuration_generation_) return;
|
||||
|
||||
int logical_index = current_monitor_index_;
|
||||
if (logical_index < 0 ||
|
||||
@@ -576,8 +625,40 @@ void ScreenCapturerSckImpl::OnShareableContentCreated(SCShareableContent *conten
|
||||
return;
|
||||
}
|
||||
|
||||
const auto privacy_capture = GetMacPrivacyCaptureState();
|
||||
// The cursor sprite is included only when this stream embeds the cursor.
|
||||
// Other controllers receive the unchanged cursor metadata separately.
|
||||
auto excluded_ids = privacy_capture.excluded_windows;
|
||||
if (!show_cursor && privacy_capture.cursor_window)
|
||||
excluded_ids.push_back(privacy_capture.cursor_window);
|
||||
NSMutableArray<SCWindow*>* excluded = [NSMutableArray array];
|
||||
for (SCWindow* window in content.windows) {
|
||||
if (std::find(excluded_ids.begin(), excluded_ids.end(), window.windowID) != excluded_ids.end())
|
||||
[excluded addObject:window];
|
||||
}
|
||||
// Newly registered transparent covers may need another enumeration. Never
|
||||
// acknowledge a partial exclusion or remove an active cover's filter.
|
||||
const bool privacy_filter_complete = excluded.count == excluded_ids.size();
|
||||
LOG_INFO("macOS privacy filter: generation={}, revision={}, requested={}, excluded={}",
|
||||
generation, privacy_capture.revision, excluded_ids.size(),
|
||||
excluded.count);
|
||||
if (!privacy_filter_complete) {
|
||||
bool have_stream;
|
||||
{ std::lock_guard lock(lock_); have_stream = stream_ != nil; }
|
||||
if (privacy_capture.applied_revision == privacy_capture.revision) {
|
||||
if (privacy_) privacy_->Fail("ScreenCaptureKit could not enumerate every privacy cover");
|
||||
return; // Preserve the existing exclusion until recovery removes covers.
|
||||
}
|
||||
if (have_stream) {
|
||||
RetryPrivacyFilter();
|
||||
return; // Transparent covers are still being registered by WindowServer.
|
||||
}
|
||||
// Start ordinary capture even if a newly created, still-transparent cover
|
||||
// is not enumerable yet. Retry exclusion after start; never acknowledge it.
|
||||
[excluded removeAllObjects];
|
||||
}
|
||||
SCContentFilter *filter = [[SCContentFilter alloc] initWithDisplay:captured_display
|
||||
excludingWindows:@[]];
|
||||
excludingWindows:excluded];
|
||||
if (!filter) {
|
||||
LOG_ERROR("Failed to create SCContentFilter");
|
||||
permanent_error_ = true;
|
||||
@@ -598,13 +679,39 @@ void ScreenCapturerSckImpl::OnShareableContentCreated(SCShareableContent *conten
|
||||
config.captureResolution = SCCaptureResolutionAutomatic;
|
||||
config.minimumFrameInterval = CMTimeMake(1, fps_);
|
||||
|
||||
std::lock_guard<std::mutex> lock(lock_);
|
||||
if (!capture_requested_) return;
|
||||
std::unique_lock<std::mutex> lock(lock_);
|
||||
if (!capture_requested_ || generation != configuration_generation_) return;
|
||||
if (configuration_in_flight_) { reconfigure_pending_ = true; return; }
|
||||
if (GetMacPrivacyCaptureState().revision != revision) {
|
||||
lock.unlock();
|
||||
RetryPrivacyFilter();
|
||||
return;
|
||||
}
|
||||
configuration_in_flight_ = true;
|
||||
|
||||
if (stream_) {
|
||||
LOG_INFO("Updating stream configuration");
|
||||
[stream_ updateContentFilter:filter completionHandler:nil];
|
||||
[stream_ updateConfiguration:config completionHandler:nil];
|
||||
SckHelper* helper = helper_;
|
||||
SCStream* source = stream_;
|
||||
auto finished = ^(NSError* error) {
|
||||
[helper configurationFinished:source generation:generation revision:revision
|
||||
complete:privacy_filter_complete configuration:config error:error];
|
||||
};
|
||||
// Apply configuration before its filter and acknowledge the final update.
|
||||
// Privacy-only toggles do not need a configuration change.
|
||||
const bool same_config = applied_configuration_ &&
|
||||
applied_configuration_.width == config.width &&
|
||||
applied_configuration_.height == config.height &&
|
||||
applied_configuration_.showsCursor == config.showsCursor &&
|
||||
applied_configuration_.pixelFormat == config.pixelFormat &&
|
||||
CMTimeCompare(applied_configuration_.minimumFrameInterval, config.minimumFrameInterval) == 0;
|
||||
if (same_config) {
|
||||
[source updateContentFilter:filter completionHandler:finished];
|
||||
} else {
|
||||
[source updateConfiguration:config completionHandler:^(NSError* error) {
|
||||
if (error) finished(error);
|
||||
else [source updateContentFilter:filter completionHandler:finished];
|
||||
}];
|
||||
}
|
||||
} else {
|
||||
stream_ = [[SCStream alloc] initWithFilter:filter configuration:config delegate:helper_];
|
||||
|
||||
@@ -618,28 +725,62 @@ void ScreenCapturerSckImpl::OnShareableContentCreated(SCShareableContent *conten
|
||||
error:&add_stream_output_error];
|
||||
|
||||
if (!add_stream_output_result) {
|
||||
configuration_in_flight_ = false;
|
||||
stream_ = nil;
|
||||
LOG_ERROR("addStreamOutput failed: {}", NSErrorToString(add_stream_output_error));
|
||||
permanent_error_ = true;
|
||||
return;
|
||||
}
|
||||
|
||||
SckHelper* helper = helper_;
|
||||
SCStream* source = stream_;
|
||||
auto handler = ^(NSError *error) {
|
||||
if (error) {
|
||||
// It should be safe to access `this` here, because the C++ destructor
|
||||
// calls stopCaptureWithCompletionHandler on the stream, which cancels
|
||||
// this handler.
|
||||
permanent_error_ = true;
|
||||
LOG_ERROR("startCaptureWithCompletionHandler failed: {}", NSErrorToString(error));
|
||||
} else {
|
||||
LOG_INFO("Capture started");
|
||||
}
|
||||
[helper configurationFinished:source generation:generation revision:revision
|
||||
complete:privacy_filter_complete configuration:config error:error];
|
||||
};
|
||||
|
||||
[stream_ startCaptureWithCompletionHandler:handler];
|
||||
}
|
||||
}
|
||||
|
||||
void ScreenCapturerSckImpl::RetryPrivacyFilter() {
|
||||
SckHelper* helper;
|
||||
{
|
||||
std::lock_guard lock(lock_);
|
||||
if (!capture_requested_) return;
|
||||
helper = helper_;
|
||||
}
|
||||
// The retained helper safely ignores this callback after Destroy().
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC),
|
||||
dispatch_get_main_queue(), ^{ [helper privacyCoversChanged:nil]; });
|
||||
}
|
||||
|
||||
void ScreenCapturerSckImpl::ConfigurationFinished(SCStream* source, uint64_t generation,
|
||||
uint64_t revision, bool complete,
|
||||
SCStreamConfiguration* configuration,
|
||||
NSError* error) {
|
||||
bool refresh = false;
|
||||
{
|
||||
std::lock_guard lock(lock_);
|
||||
if (!capture_requested_ || source != stream_) return;
|
||||
configuration_in_flight_ = false;
|
||||
const auto current = GetMacPrivacyCaptureState();
|
||||
refresh = reconfigure_pending_ || current.revision != revision;
|
||||
reconfigure_pending_ = false;
|
||||
if (!error) {
|
||||
applied_configuration_ = configuration;
|
||||
if (complete && !refresh && generation == configuration_generation_)
|
||||
AcknowledgeMacPrivacyCapture(revision);
|
||||
refresh = refresh || !complete;
|
||||
}
|
||||
LOG_INFO("macOS privacy filter completed: generation={}, revision={}, complete={}, refresh={}, error={}",
|
||||
generation, revision, complete, refresh, NSErrorToString(error));
|
||||
}
|
||||
if (error && privacy_)
|
||||
privacy_->Fail("ScreenCaptureKit privacy filter: " + NSErrorToString(error));
|
||||
if (refresh) RetryPrivacyFilter();
|
||||
}
|
||||
|
||||
void ScreenCapturerSckImpl::OnNewCVPixelBuffer(CVPixelBufferRef pixelBuffer,
|
||||
CFDictionaryRef attachment) {
|
||||
(void)attachment;
|
||||
@@ -727,7 +868,18 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
}
|
||||
}
|
||||
|
||||
SckHelper *local_helper = helper_;
|
||||
SckHelper *local_helper;
|
||||
uint64_t generation;
|
||||
uint64_t revision;
|
||||
{
|
||||
std::lock_guard lock(lock_);
|
||||
if (!capture_requested_) return;
|
||||
if (configuration_in_flight_) { reconfigure_pending_ = true; return; }
|
||||
reconfigure_pending_ = false;
|
||||
local_helper = helper_;
|
||||
generation = ++configuration_generation_;
|
||||
revision = GetMacPrivacyCaptureState().revision;
|
||||
}
|
||||
if (!local_helper) {
|
||||
LOG_ERROR("Cannot reconfigure capturer: helper is null");
|
||||
return;
|
||||
@@ -736,12 +888,14 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
auto handler = ^(SCShareableContent *content, NSError *error) {
|
||||
if (error) {
|
||||
LOG_ERROR("getShareableContent failed: {}", NSErrorToString(error));
|
||||
[local_helper onShareableContentCreated:nil];
|
||||
[local_helper onShareableContentCreated:nil generation:generation revision:revision];
|
||||
return;
|
||||
}
|
||||
[local_helper onShareableContentCreated:content];
|
||||
[local_helper onShareableContentCreated:content generation:generation revision:revision];
|
||||
};
|
||||
[SCShareableContent getShareableContentWithCompletionHandler:handler];
|
||||
[SCShareableContent getShareableContentExcludingDesktopWindows:NO
|
||||
onScreenWindowsOnly:NO
|
||||
completionHandler:handler];
|
||||
}
|
||||
|
||||
@implementation SckHelper {
|
||||
@@ -755,14 +909,28 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_capturer = capturer;
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(privacyCoversChanged:)
|
||||
name:@"CrossDeskPrivacyCoversChanged" object:nil];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)onShareableContentCreated:(SCShareableContent *)content {
|
||||
- (void)privacyCoversChanged:(NSNotification*)notification {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer) _capturer->PrivacyCoversChanged();
|
||||
}
|
||||
- (void)configurationFinished:(SCStream*)stream generation:(uint64_t)generation
|
||||
revision:(uint64_t)revision complete:(BOOL)complete
|
||||
configuration:(SCStreamConfiguration*)configuration error:(NSError*)error {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer)
|
||||
_capturer->ConfigurationFinished(stream, generation, revision, complete, configuration, error);
|
||||
}
|
||||
- (void)onShareableContentCreated:(SCShareableContent *)content generation:(uint64_t)generation
|
||||
revision:(uint64_t)revision {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer) {
|
||||
_capturer->OnShareableContentCreated(content);
|
||||
_capturer->OnShareableContentCreated(content, generation, revision);
|
||||
} else {
|
||||
LOG_ERROR("Invalid capturer");
|
||||
}
|
||||
@@ -797,10 +965,16 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
}
|
||||
|
||||
- (void)releaseCapturer {
|
||||
[NSNotificationCenter.defaultCenter removeObserver:self];
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
_capturer = nullptr;
|
||||
}
|
||||
|
||||
- (void)stream:(SCStream*)stream didStopWithError:(NSError*)error {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer) _capturer->CaptureStopped(stream, error);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
std::unique_ptr<ScreenCapturer> ScreenCapturerSck::CreateScreenCapturerSck() {
|
||||
|
||||
@@ -17,21 +17,19 @@ namespace crossdesk {
|
||||
class SpeakerCapturerMacosx : public SpeakerCapturer {
|
||||
public:
|
||||
SpeakerCapturerMacosx();
|
||||
~SpeakerCapturerMacosx();
|
||||
~SpeakerCapturerMacosx() override;
|
||||
|
||||
public:
|
||||
virtual int Init(speaker_data_cb cb);
|
||||
virtual int Destroy();
|
||||
virtual int Start();
|
||||
virtual int Stop();
|
||||
int Init(speaker_data_cb cb) override;
|
||||
int Destroy() override;
|
||||
int Start() override;
|
||||
int Stop() override;
|
||||
bool IsRunning() const override;
|
||||
|
||||
int Pause();
|
||||
int Resume();
|
||||
|
||||
public:
|
||||
speaker_data_cb cb_ = nullptr;
|
||||
bool inited_ = false;
|
||||
|
||||
private:
|
||||
class Impl;
|
||||
Impl* impl_ = nullptr;
|
||||
};
|
||||
|
||||
@@ -2,47 +2,98 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ScreenCaptureKit/ScreenCaptureKit.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
|
||||
#include "rd_log.h"
|
||||
#include "speaker_capturer_macosx.h"
|
||||
|
||||
namespace crossdesk {
|
||||
class SpeakerCapturerMacosx;
|
||||
namespace {
|
||||
constexpr auto kCaptureTimeout = std::chrono::seconds(2);
|
||||
|
||||
std::string NSErrorToString(NSError* error) {
|
||||
if (!error) return "";
|
||||
NSString* message = [NSString
|
||||
stringWithFormat:@"%@ (%@:%ld), reason=%@", error.localizedDescription, error.domain,
|
||||
(long)error.code, error.localizedFailureReason ?: @""];
|
||||
return message.UTF8String ?: "";
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string NSErrorToString(NSError* error) {
|
||||
if (!error) {
|
||||
return "";
|
||||
// Late system replies own only their result, never the capturer or stack data.
|
||||
// Complete() also tells a late successful start to stop its abandoned stream.
|
||||
template <typename T>
|
||||
class CaptureReply {
|
||||
public:
|
||||
bool Complete(T value) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (expired_) return false;
|
||||
value_ = std::move(value);
|
||||
ready_ = true;
|
||||
wake_.notify_one();
|
||||
return true;
|
||||
}
|
||||
bool Wait(T& value) {
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
if (!wake_.wait_for(lock, kCaptureTimeout, [&] { return ready_; })) {
|
||||
expired_ = true;
|
||||
return false;
|
||||
}
|
||||
value = value_;
|
||||
return true;
|
||||
}
|
||||
|
||||
const char* description = [error.localizedDescription UTF8String];
|
||||
return description ? description : "";
|
||||
}
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
std::condition_variable wake_;
|
||||
bool ready_ = false;
|
||||
bool expired_ = false;
|
||||
T value_{};
|
||||
};
|
||||
|
||||
struct ContentReply {
|
||||
SCShareableContent* content = nil;
|
||||
NSError* error = nil;
|
||||
};
|
||||
struct StreamReply {
|
||||
NSError* error = nil;
|
||||
};
|
||||
struct AudioCallbackState {
|
||||
std::mutex mutex;
|
||||
crossdesk::SpeakerCapturer::speaker_data_cb callback;
|
||||
std::atomic<bool> running{false};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
@interface SpeakerCaptureDelegate : NSObject <SCStreamDelegate, SCStreamOutput>
|
||||
@property(nonatomic, assign) crossdesk::SpeakerCapturerMacosx* owner;
|
||||
- (instancetype)initWithOwner:(crossdesk::SpeakerCapturerMacosx*)owner;
|
||||
@interface SpeakerCaptureDelegate : NSObject <SCStreamDelegate, SCStreamOutput> {
|
||||
std::shared_ptr<AudioCallbackState> state_;
|
||||
}
|
||||
- (instancetype)initWithState:(std::shared_ptr<AudioCallbackState>)state;
|
||||
@end
|
||||
|
||||
@implementation SpeakerCaptureDelegate
|
||||
- (instancetype)initWithOwner:(crossdesk::SpeakerCapturerMacosx*)owner {
|
||||
- (instancetype)initWithState:(std::shared_ptr<AudioCallbackState>)state {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_owner = owner;
|
||||
}
|
||||
if (self) state_ = std::move(state);
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)stream:(SCStream*)stream didStopWithError:(NSError*)error {
|
||||
state_->running = false;
|
||||
SPDLOG_LOGGER_WARN(crossdesk::get_logger(), "System audio stream stopped: {}",
|
||||
NSErrorToString(error));
|
||||
}
|
||||
|
||||
- (void)stream:(SCStream*)stream
|
||||
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
|
||||
ofType:(SCStreamOutputType)type {
|
||||
if (type != SCStreamOutputTypeAudio) return;
|
||||
|
||||
crossdesk::SpeakerCapturerMacosx* owner = _owner;
|
||||
if (!owner || !owner->cb_) {
|
||||
return;
|
||||
}
|
||||
const auto state = state_;
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
if (!state->callback || !state->running) return;
|
||||
|
||||
CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer);
|
||||
if (!blockBuffer) {
|
||||
@@ -51,8 +102,7 @@ std::string NSErrorToString(NSError* error) {
|
||||
|
||||
size_t length = CMBlockBufferGetDataLength(blockBuffer);
|
||||
char* dataPtr = NULL;
|
||||
OSStatus dataStatus =
|
||||
CMBlockBufferGetDataPointer(blockBuffer, 0, NULL, NULL, &dataPtr);
|
||||
OSStatus dataStatus = CMBlockBufferGetDataPointer(blockBuffer, 0, NULL, NULL, &dataPtr);
|
||||
if (dataStatus != noErr || dataPtr == nullptr || length == 0) {
|
||||
return;
|
||||
}
|
||||
@@ -68,7 +118,7 @@ std::string NSErrorToString(NSError* error) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (owner->cb_) {
|
||||
if (state->callback) {
|
||||
std::vector<short> out_pcm16;
|
||||
if (asbd->mFormatFlags & kAudioFormatFlagIsFloat) {
|
||||
int channels = asbd->mChannelsPerFrame;
|
||||
@@ -118,191 +168,156 @@ std::string NSErrorToString(NSError* error) {
|
||||
size_t total_bytes = out_pcm16.size() * sizeof(short);
|
||||
unsigned char* p = (unsigned char*)out_pcm16.data();
|
||||
for (size_t offset = 0; offset + frame_bytes <= total_bytes; offset += frame_bytes) {
|
||||
if (!owner->cb_) {
|
||||
if (!state->callback) {
|
||||
return;
|
||||
}
|
||||
owner->cb_(p + offset, frame_bytes, "audio");
|
||||
state->callback(p + offset, frame_bytes, "audio");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class SpeakerCapturerMacosx::Impl {
|
||||
public:
|
||||
SCStreamConfiguration* config = nil;
|
||||
speaker_data_cb callback;
|
||||
SCStream* stream = nil;
|
||||
SpeakerCaptureDelegate* delegate = nil;
|
||||
dispatch_queue_t queue = nil;
|
||||
SCShareableContent* content = nil;
|
||||
SCDisplay* mainDisplay = nil;
|
||||
|
||||
~Impl() {
|
||||
if (stream) {
|
||||
[stream stopCaptureWithCompletionHandler:^(NSError* _Nullable error){
|
||||
}];
|
||||
stream = nil;
|
||||
}
|
||||
delegate = nil;
|
||||
if (queue) {
|
||||
queue = nil;
|
||||
}
|
||||
content = nil;
|
||||
mainDisplay = nil;
|
||||
config = nil;
|
||||
}
|
||||
std::shared_ptr<AudioCallbackState> state;
|
||||
};
|
||||
|
||||
SpeakerCapturerMacosx::SpeakerCapturerMacosx() {
|
||||
impl_ = new Impl();
|
||||
inited_ = false;
|
||||
cb_ = nullptr;
|
||||
}
|
||||
|
||||
SpeakerCapturerMacosx::SpeakerCapturerMacosx() : impl_(new Impl) {}
|
||||
SpeakerCapturerMacosx::~SpeakerCapturerMacosx() {
|
||||
Destroy();
|
||||
delete impl_;
|
||||
impl_ = nullptr;
|
||||
}
|
||||
|
||||
int SpeakerCapturerMacosx::Init(speaker_data_cb cb) {
|
||||
if (inited_) {
|
||||
return 0;
|
||||
}
|
||||
cb_ = cb;
|
||||
|
||||
impl_->config = [[SCStreamConfiguration alloc] init];
|
||||
impl_->config.capturesAudio = YES;
|
||||
impl_->config.sampleRate = 48000;
|
||||
impl_->config.channelCount = 1;
|
||||
|
||||
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
|
||||
__block NSError* error = nil;
|
||||
[SCShareableContent
|
||||
getShareableContentWithCompletionHandler:^(SCShareableContent* c, NSError* e) {
|
||||
impl_->content = c;
|
||||
error = e;
|
||||
dispatch_semaphore_signal(sema);
|
||||
}];
|
||||
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
|
||||
|
||||
if (error || !impl_->content) {
|
||||
LOG_ERROR("Failed to get shareable content: {}",
|
||||
NSErrorToString(error));
|
||||
return -1;
|
||||
}
|
||||
|
||||
CGDirectDisplayID mainDisplayId = CGMainDisplayID();
|
||||
impl_->mainDisplay = nil;
|
||||
for (SCDisplay* d in impl_->content.displays) {
|
||||
if (d.displayID == mainDisplayId) {
|
||||
impl_->mainDisplay = d;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!impl_->mainDisplay) {
|
||||
LOG_ERROR("Main display not found");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!impl_->queue) {
|
||||
impl_->callback = std::move(cb);
|
||||
if (!impl_->queue)
|
||||
impl_->queue = dispatch_queue_create("SpeakerAudio.Queue", DISPATCH_QUEUE_SERIAL);
|
||||
}
|
||||
|
||||
inited_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int SpeakerCapturerMacosx::Start() {
|
||||
if (!inited_) {
|
||||
return -1;
|
||||
}
|
||||
@autoreleasepool {
|
||||
if (!impl_->callback) return -1;
|
||||
if (IsRunning()) return 0;
|
||||
if (Stop() != 0) return -1;
|
||||
|
||||
if (impl_->stream) {
|
||||
dispatch_semaphore_t semaStop = dispatch_semaphore_create(0);
|
||||
[impl_->stream stopCaptureWithCompletionHandler:^(NSError* error) {
|
||||
dispatch_semaphore_signal(semaStop);
|
||||
}];
|
||||
dispatch_semaphore_wait(semaStop, DISPATCH_TIME_FOREVER);
|
||||
impl_->stream = nil;
|
||||
impl_->delegate = nil;
|
||||
}
|
||||
|
||||
impl_->delegate = [[SpeakerCaptureDelegate alloc] initWithOwner:this];
|
||||
SCContentFilter* filter = [[SCContentFilter alloc] initWithDisplay:impl_->mainDisplay
|
||||
excludingWindows:@[]];
|
||||
impl_->stream = [[SCStream alloc] initWithFilter:filter
|
||||
configuration:impl_->config
|
||||
delegate:impl_->delegate];
|
||||
|
||||
NSError* addOutputError = nil;
|
||||
BOOL ok = [impl_->stream addStreamOutput:impl_->delegate
|
||||
type:SCStreamOutputTypeAudio
|
||||
sampleHandlerQueue:impl_->queue
|
||||
error:&addOutputError];
|
||||
if (!ok || addOutputError) {
|
||||
LOG_ERROR("addStreamOutput error: {}",
|
||||
NSErrorToString(addOutputError));
|
||||
impl_->stream = nil;
|
||||
impl_->delegate = nil;
|
||||
return -1;
|
||||
}
|
||||
|
||||
dispatch_semaphore_t semaStart = dispatch_semaphore_create(0);
|
||||
__block int ret = 0;
|
||||
[impl_->stream startCaptureWithCompletionHandler:^(NSError* _Nullable error) {
|
||||
if (error) {
|
||||
LOG_ERROR("startCaptureWithCompletionHandler error: {}",
|
||||
NSErrorToString(error));
|
||||
ret = -1;
|
||||
// A cached SCDisplay becomes invalid after hotplug, sleep or a display
|
||||
// reconfiguration. Obtain a fresh snapshot on every start/reconnection.
|
||||
auto content_reply = std::make_shared<CaptureReply<ContentReply>>();
|
||||
[SCShareableContent
|
||||
getShareableContentWithCompletionHandler:^(SCShareableContent* content, NSError* error) {
|
||||
content_reply->Complete({content, error});
|
||||
}];
|
||||
ContentReply content;
|
||||
if (!content_reply->Wait(content)) {
|
||||
LOG_ERROR("Timed out refreshing system audio capture displays");
|
||||
return -1;
|
||||
}
|
||||
dispatch_semaphore_signal(semaStart);
|
||||
}];
|
||||
dispatch_semaphore_wait(semaStart, DISPATCH_TIME_FOREVER);
|
||||
if (content.error || !content.content) {
|
||||
LOG_ERROR("Failed to refresh system audio capture displays: {}",
|
||||
NSErrorToString(content.error));
|
||||
return -1;
|
||||
}
|
||||
SCDisplay* display = nil;
|
||||
const auto main_id = CGMainDisplayID();
|
||||
for (SCDisplay* candidate in content.content.displays) {
|
||||
if (candidate.displayID == main_id) {
|
||||
display = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!display) display = content.content.displays.firstObject;
|
||||
if (!display) {
|
||||
LOG_ERROR("No display available for system audio capture");
|
||||
return -1;
|
||||
}
|
||||
LOG_INFO("Starting system audio capture with current display {}", display.displayID);
|
||||
|
||||
return ret;
|
||||
SCStreamConfiguration* config = [[SCStreamConfiguration alloc] init];
|
||||
config.capturesAudio = YES;
|
||||
config.sampleRate = 48000;
|
||||
config.channelCount = 1;
|
||||
SCContentFilter* filter = [[SCContentFilter alloc] initWithDisplay:display
|
||||
excludingWindows:@[]];
|
||||
impl_->state = std::make_shared<AudioCallbackState>();
|
||||
impl_->state->callback = impl_->callback;
|
||||
impl_->delegate = [[SpeakerCaptureDelegate alloc] initWithState:impl_->state];
|
||||
impl_->stream = [[SCStream alloc] initWithFilter:filter
|
||||
configuration:config
|
||||
delegate:impl_->delegate];
|
||||
NSError* output_error = nil;
|
||||
if (!impl_->stream || ![impl_->stream addStreamOutput:impl_->delegate
|
||||
type:SCStreamOutputTypeAudio
|
||||
sampleHandlerQueue:impl_->queue
|
||||
error:&output_error]) {
|
||||
LOG_ERROR("Failed to attach system audio output: {}", NSErrorToString(output_error));
|
||||
Stop();
|
||||
return -1;
|
||||
}
|
||||
|
||||
auto start_reply = std::make_shared<CaptureReply<StreamReply>>();
|
||||
SCStream* stream = impl_->stream;
|
||||
impl_->state->running = true;
|
||||
[stream startCaptureWithCompletionHandler:^(NSError* error) {
|
||||
if (!start_reply->Complete({error}) && !error) {
|
||||
[stream stopCaptureWithCompletionHandler:nil];
|
||||
}
|
||||
}];
|
||||
StreamReply started;
|
||||
if (!start_reply->Wait(started)) {
|
||||
LOG_ERROR("Timed out starting system audio capture");
|
||||
Stop();
|
||||
return -1;
|
||||
}
|
||||
if (started.error || !impl_->state->running) {
|
||||
LOG_ERROR("Failed to start system audio capture: {}", NSErrorToString(started.error));
|
||||
Stop();
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int SpeakerCapturerMacosx::Stop() {
|
||||
if (!inited_) return -1;
|
||||
if (!impl_->stream) return -1;
|
||||
|
||||
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
|
||||
[impl_->stream stopCaptureWithCompletionHandler:^(NSError* error) {
|
||||
if (error) {
|
||||
LOG_ERROR("stopCaptureWithCompletionHandler error: {}",
|
||||
NSErrorToString(error));
|
||||
@autoreleasepool {
|
||||
if (auto state = std::exchange(impl_->state, {})) {
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
state->running = false;
|
||||
state->callback = nullptr;
|
||||
}
|
||||
dispatch_semaphore_signal(sema);
|
||||
}];
|
||||
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
|
||||
|
||||
impl_->stream = nil;
|
||||
impl_->delegate.owner = nullptr;
|
||||
impl_->delegate = nil;
|
||||
|
||||
return 0;
|
||||
SCStream* stream = impl_->stream;
|
||||
impl_->stream = nil;
|
||||
impl_->delegate = nil;
|
||||
if (!stream) return 0;
|
||||
auto stop_reply = std::make_shared<CaptureReply<StreamReply>>();
|
||||
[stream stopCaptureWithCompletionHandler:^(NSError* error) {
|
||||
stop_reply->Complete({error});
|
||||
}];
|
||||
StreamReply stopped;
|
||||
if (!stop_reply->Wait(stopped)) {
|
||||
LOG_ERROR("Timed out stopping system audio capture; callbacks revoked");
|
||||
return -1;
|
||||
}
|
||||
// A start failure or daemon restart can leave an already stopped stream.
|
||||
// Its references have been discarded, so future starts can recover.
|
||||
if (stopped.error) LOG_WARN("System audio stop reply: {}", NSErrorToString(stopped.error));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool SpeakerCapturerMacosx::IsRunning() const { return impl_->state && impl_->state->running; }
|
||||
|
||||
int SpeakerCapturerMacosx::Destroy() {
|
||||
Stop();
|
||||
cb_ = nullptr;
|
||||
|
||||
if (impl_) {
|
||||
impl_->config = nil;
|
||||
impl_->content = nil;
|
||||
impl_->mainDisplay = nil;
|
||||
if (impl_->queue) {
|
||||
impl_->queue = nil;
|
||||
}
|
||||
}
|
||||
inited_ = false;
|
||||
return 0;
|
||||
const int result = Stop();
|
||||
impl_->callback = nullptr;
|
||||
impl_->queue = nil;
|
||||
return result;
|
||||
}
|
||||
|
||||
int SpeakerCapturerMacosx::Pause() { return 0; }
|
||||
|
||||
int SpeakerCapturerMacosx::Pause() { return Stop(); }
|
||||
int SpeakerCapturerMacosx::Resume() { return Start(); }
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -114,6 +114,9 @@ void GuiRuntime::HandleWindowsServiceIntegration() {
|
||||
|
||||
bool force_broadcast = false;
|
||||
if (pending_windows_service_sas_.exchange(false, std::memory_order_relaxed)) {
|
||||
if (privacy_.Engaged()) {
|
||||
privacy_.Fail("Security shortcut requested; privacy screen will turn off");
|
||||
}
|
||||
const std::string response =
|
||||
QueryCrossDeskService("sas", kWindowsServiceSasTimeoutMs);
|
||||
auto json = nlohmann::json::parse(response, nullptr, false);
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#include "window_icons.h"
|
||||
|
||||
#include <commctrl.h>
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
constexpr UINT_PTR kIconSubclassId = 1;
|
||||
|
||||
struct WindowIcons {
|
||||
HICON small_icon = nullptr;
|
||||
HICON large_icon = nullptr;
|
||||
|
||||
~WindowIcons() {
|
||||
if (small_icon) DestroyIcon(small_icon);
|
||||
if (large_icon) DestroyIcon(large_icon);
|
||||
}
|
||||
|
||||
bool Load(UINT dpi) {
|
||||
const HMODULE module = GetModuleHandleW(nullptr);
|
||||
small_icon = static_cast<HICON>(LoadImageW(
|
||||
module, L"IDI_ICON1", IMAGE_ICON,
|
||||
GetSystemMetricsForDpi(SM_CXSMICON, dpi),
|
||||
GetSystemMetricsForDpi(SM_CYSMICON, dpi), 0));
|
||||
large_icon = static_cast<HICON>(LoadImageW(
|
||||
module, L"IDI_ICON1", IMAGE_ICON,
|
||||
GetSystemMetricsForDpi(SM_CXICON, dpi),
|
||||
GetSystemMetricsForDpi(SM_CYICON, dpi), 0));
|
||||
return small_icon && large_icon;
|
||||
}
|
||||
|
||||
void Apply(HWND window) const {
|
||||
// Do not destroy the replaced handles: Slint/winit owns those images.
|
||||
SendMessageW(window, WM_SETICON, ICON_SMALL,
|
||||
reinterpret_cast<LPARAM>(small_icon));
|
||||
SendMessageW(window, WM_SETICON, ICON_BIG,
|
||||
reinterpret_cast<LPARAM>(large_icon));
|
||||
}
|
||||
};
|
||||
|
||||
LRESULT CALLBACK IconSubclassProc(HWND window, UINT message, WPARAM wparam,
|
||||
LPARAM lparam, UINT_PTR subclass_id,
|
||||
DWORD_PTR reference_data) {
|
||||
auto* icons = reinterpret_cast<WindowIcons*>(reference_data);
|
||||
if (message == WM_SETICON) {
|
||||
// Slint supplies the same PNG for both sizes, including during deferred
|
||||
// window initialization. Keep using the matching frames from our ICO.
|
||||
if (wparam == ICON_SMALL) {
|
||||
lparam = reinterpret_cast<LPARAM>(icons->small_icon);
|
||||
} else if (wparam == ICON_BIG) {
|
||||
lparam = reinterpret_cast<LPARAM>(icons->large_icon);
|
||||
}
|
||||
return DefSubclassProc(window, message, wparam, lparam);
|
||||
}
|
||||
if (message == WM_DPICHANGED) {
|
||||
WindowIcons next;
|
||||
if (next.Load(HIWORD(wparam))) {
|
||||
std::swap(icons->small_icon, next.small_icon);
|
||||
std::swap(icons->large_icon, next.large_icon);
|
||||
icons->Apply(window);
|
||||
// 'next' releases the previous pair only after both were replaced.
|
||||
}
|
||||
}
|
||||
if (message == WM_NCDESTROY) {
|
||||
const LRESULT result = DefSubclassProc(window, message, wparam, lparam);
|
||||
RemoveWindowSubclass(window, IconSubclassProc, subclass_id);
|
||||
delete icons;
|
||||
return result;
|
||||
}
|
||||
return DefSubclassProc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ConfigureWindowsWindowIcons(HWND window) {
|
||||
if (!window) {
|
||||
return false;
|
||||
}
|
||||
DWORD_PTR existing = 0;
|
||||
if (GetWindowSubclass(window, IconSubclassProc, kIconSubclassId, &existing)) {
|
||||
return true;
|
||||
}
|
||||
auto icons = std::make_unique<WindowIcons>();
|
||||
const UINT dpi = GetDpiForWindow(window);
|
||||
if (!dpi || !icons->Load(dpi) ||
|
||||
!SetWindowSubclass(window, IconSubclassProc, kIconSubclassId,
|
||||
reinterpret_cast<DWORD_PTR>(icons.get()))) {
|
||||
return false;
|
||||
}
|
||||
// The subclass owns the pair until WM_NCDESTROY, even if Slint hides and
|
||||
// recreates its native window while the component itself stays alive.
|
||||
auto* installed = icons.release();
|
||||
installed->Apply(window);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef CROSSDESK_WINDOWS_WINDOW_ICONS_H_
|
||||
#define CROSSDESK_WINDOWS_WINDOW_ICONS_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Call on the window's UI thread once its native handle exists. Repeated calls
|
||||
// are harmless. Icons follow DPI changes and are released with the window.
|
||||
bool ConfigureWindowsWindowIcons(HWND window);
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // CROSSDESK_WINDOWS_WINDOW_ICONS_H_
|
||||
@@ -1,16 +1,20 @@
|
||||
#include "mouse_controller.h"
|
||||
|
||||
#include <Windows.h>
|
||||
#include <remote_action.h>
|
||||
|
||||
#include <Windows.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#include "../../windows_thread_dpi.h"
|
||||
#include "rd_log.h"
|
||||
#include "windows_input_marker.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
PlatformMouseController::PlatformMouseController() {}
|
||||
|
||||
PlatformMouseController::~PlatformMouseController() {}
|
||||
PlatformMouseController::~PlatformMouseController() { Destroy(); }
|
||||
|
||||
int PlatformMouseController::Init(std::vector<DisplayInfo> display_info_list) {
|
||||
display_info_list_ = display_info_list;
|
||||
@@ -18,10 +22,27 @@ int PlatformMouseController::Init(std::vector<DisplayInfo> display_info_list) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int PlatformMouseController::Destroy() { return 0; }
|
||||
int PlatformMouseController::Destroy() { return ReleasePressedButtons(); }
|
||||
|
||||
int PlatformMouseController::ReleasePressedButtons() {
|
||||
const unsigned pressed = pressed_buttons_.load();
|
||||
if (!pressed) return 0;
|
||||
INPUT input{};
|
||||
input.type = INPUT_MOUSE;
|
||||
input.mi.dwExtraInfo = kInjectedMouseInputMarker;
|
||||
if (pressed & 1) input.mi.dwFlags |= MOUSEEVENTF_LEFTUP;
|
||||
if (pressed & 2) input.mi.dwFlags |= MOUSEEVENTF_RIGHTUP;
|
||||
if (pressed & 4) input.mi.dwFlags |= MOUSEEVENTF_MIDDLEUP;
|
||||
if (SendInput(1, &input, sizeof(INPUT)) != 1) {
|
||||
LOG_WARN("Release remote mouse buttons failed, error={}", GetLastError());
|
||||
return -1;
|
||||
}
|
||||
pressed_buttons_.fetch_and(~pressed);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int PlatformMouseController::SendMouseCommand(RemoteAction remote_action,
|
||||
int display_index) {
|
||||
int display_index) {
|
||||
if (display_index < 0 ||
|
||||
display_index >= static_cast<int>(display_info_list_.size())) {
|
||||
LOG_WARN("Mouse command skipped, invalid display_index={}, displays={}",
|
||||
@@ -30,69 +51,83 @@ int PlatformMouseController::SendMouseCommand(RemoteAction remote_action,
|
||||
}
|
||||
|
||||
INPUT ip = {0};
|
||||
ScopedWindowsPhysicalCoordinates physical_coordinates;
|
||||
|
||||
if (remote_action.type == ControlType::mouse) {
|
||||
ip.type = INPUT_MOUSE;
|
||||
ip.mi.dx =
|
||||
(LONG)(remote_action.m.x * display_info_list_[display_index].width) +
|
||||
display_info_list_[display_index].left;
|
||||
ip.mi.dy =
|
||||
(LONG)(remote_action.m.y * display_info_list_[display_index].height) +
|
||||
display_info_list_[display_index].top;
|
||||
if (remote_action.type != ControlType::mouse) return 0;
|
||||
if (!std::isfinite(remote_action.m.x) || !std::isfinite(remote_action.m.y))
|
||||
return -1;
|
||||
ip.type = INPUT_MOUSE;
|
||||
ip.mi.dx = (LONG)(std::clamp(remote_action.m.x, 0.0f, 1.0f) *
|
||||
(display_info_list_[display_index].width - 1)) +
|
||||
display_info_list_[display_index].left;
|
||||
ip.mi.dy = (LONG)(std::clamp(remote_action.m.y, 0.0f, 1.0f) *
|
||||
(display_info_list_[display_index].height - 1)) +
|
||||
display_info_list_[display_index].top;
|
||||
|
||||
switch (remote_action.m.flag) {
|
||||
case MouseFlag::left_down:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE;
|
||||
break;
|
||||
case MouseFlag::left_up:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE;
|
||||
break;
|
||||
case MouseFlag::right_down:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_ABSOLUTE;
|
||||
break;
|
||||
case MouseFlag::right_up:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_RIGHTUP | MOUSEEVENTF_ABSOLUTE;
|
||||
break;
|
||||
case MouseFlag::middle_down:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_ABSOLUTE;
|
||||
break;
|
||||
case MouseFlag::middle_up:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_MIDDLEUP | MOUSEEVENTF_ABSOLUTE;
|
||||
break;
|
||||
case MouseFlag::wheel_vertical:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_WHEEL;
|
||||
ip.mi.mouseData = remote_action.m.s * 120;
|
||||
break;
|
||||
case MouseFlag::wheel_horizontal:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_HWHEEL;
|
||||
ip.mi.mouseData = remote_action.m.s * 120;
|
||||
break;
|
||||
default:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_MOVE;
|
||||
break;
|
||||
}
|
||||
|
||||
ip.mi.time = 0;
|
||||
|
||||
if (!SetCursorPos(ip.mi.dx, ip.mi.dy)) {
|
||||
LOG_WARN("SetCursorPos failed for mouse x={}, y={}, flag={}, err={}",
|
||||
ip.mi.dx, ip.mi.dy, static_cast<int>(remote_action.m.flag),
|
||||
GetLastError());
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (ip.mi.dwFlags != MOUSEEVENTF_MOVE) {
|
||||
UINT sent = SendInput(1, &ip, sizeof(INPUT));
|
||||
if (sent != 1) {
|
||||
LOG_WARN(
|
||||
"SendInput failed for mouse x={}, y={}, wheel={}, flag={}, err={}",
|
||||
ip.mi.dx, ip.mi.dy, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag), GetLastError());
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
switch (remote_action.m.flag) {
|
||||
case MouseFlag::left_down:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
|
||||
break;
|
||||
case MouseFlag::left_up:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_LEFTUP;
|
||||
break;
|
||||
case MouseFlag::right_down:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
|
||||
break;
|
||||
case MouseFlag::right_up:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
|
||||
break;
|
||||
case MouseFlag::middle_down:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
|
||||
break;
|
||||
case MouseFlag::middle_up:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
|
||||
break;
|
||||
case MouseFlag::wheel_vertical:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_WHEEL;
|
||||
ip.mi.mouseData = remote_action.m.s * 120;
|
||||
break;
|
||||
case MouseFlag::wheel_horizontal:
|
||||
ip.mi.dwFlags = MOUSEEVENTF_HWHEEL;
|
||||
ip.mi.mouseData = remote_action.m.s * 120;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
const int virtual_left = GetSystemMetrics(SM_XVIRTUALSCREEN);
|
||||
const int virtual_top = GetSystemMetrics(SM_YVIRTUALSCREEN);
|
||||
const int virtual_width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
|
||||
const int virtual_height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
|
||||
if (virtual_width <= 0 || virtual_height <= 0) {
|
||||
LOG_WARN("Remote mouse skipped: invalid virtual desktop geometry");
|
||||
return -1;
|
||||
}
|
||||
// Pixel centres in the virtual desktop, including negative monitor origins.
|
||||
// SetCursorPos cannot carry dwExtraInfo through the privacy mouse hook.
|
||||
ip.mi.dx = static_cast<LONG>(
|
||||
(static_cast<int64_t>(ip.mi.dx - virtual_left) * 65536 + 32768) /
|
||||
virtual_width);
|
||||
ip.mi.dy = static_cast<LONG>(
|
||||
(static_cast<int64_t>(ip.mi.dy - virtual_top) * 65536 + 32768) /
|
||||
virtual_height);
|
||||
ip.mi.dwFlags |=
|
||||
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
|
||||
ip.mi.dwExtraInfo = kInjectedMouseInputMarker;
|
||||
const UINT sent = SendInput(1, &ip, sizeof(INPUT));
|
||||
if (sent != 1) {
|
||||
LOG_WARN("SendInput failed for mouse x={}, y={}, wheel={}, flag={}, err={}",
|
||||
ip.mi.dx, ip.mi.dy, remote_action.m.s,
|
||||
static_cast<int>(remote_action.m.flag), GetLastError());
|
||||
return -1;
|
||||
}
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_LEFTDOWN) pressed_buttons_.fetch_or(1);
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_RIGHTDOWN) pressed_buttons_.fetch_or(2);
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_MIDDLEDOWN) pressed_buttons_.fetch_or(4);
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_LEFTUP) pressed_buttons_.fetch_and(~1u);
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_RIGHTUP) pressed_buttons_.fetch_and(~2u);
|
||||
if (ip.mi.dwFlags & MOUSEEVENTF_MIDDLEUP) pressed_buttons_.fetch_and(~4u);
|
||||
|
||||
return 0;
|
||||
}
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#define _MOUSE_CONTROLLER_H_
|
||||
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
|
||||
#include <remote_action.h>
|
||||
|
||||
@@ -25,9 +26,11 @@ class PlatformMouseController final : public MouseController {
|
||||
virtual int Init(std::vector<DisplayInfo> display_info_list);
|
||||
virtual int Destroy();
|
||||
virtual int SendMouseCommand(RemoteAction remote_action, int display_index);
|
||||
int ReleasePressedButtons();
|
||||
|
||||
private:
|
||||
std::vector<DisplayInfo> display_info_list_;
|
||||
std::atomic<unsigned> pressed_buttons_{0};
|
||||
};
|
||||
} // namespace crossdesk
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef CROSSDESK_WINDOWS_CURSOR_SHAPE_H_
|
||||
#define CROSSDESK_WINDOWS_CURSOR_SHAPE_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <remote_cursor_shape.h>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
inline RemoteCursorShape ShapeFromWindowsCursor(HCURSOR cursor) {
|
||||
const auto is_system_cursor = [cursor](LPCWSTR resource) {
|
||||
return cursor != nullptr && cursor == LoadCursorW(nullptr, resource);
|
||||
};
|
||||
if (is_system_cursor(IDC_HELP)) return RemoteCursorShape::help;
|
||||
if (is_system_cursor(IDC_HAND)) return RemoteCursorShape::pointer;
|
||||
if (is_system_cursor(IDC_APPSTARTING)) return RemoteCursorShape::progress;
|
||||
if (is_system_cursor(IDC_WAIT)) return RemoteCursorShape::wait;
|
||||
if (is_system_cursor(IDC_CROSS)) return RemoteCursorShape::crosshair;
|
||||
if (is_system_cursor(IDC_IBEAM)) return RemoteCursorShape::text;
|
||||
if (is_system_cursor(IDC_NO)) return RemoteCursorShape::not_allowed;
|
||||
if (is_system_cursor(IDC_SIZEALL)) return RemoteCursorShape::move;
|
||||
if (is_system_cursor(IDC_SIZEWE)) return RemoteCursorShape::ew_resize;
|
||||
if (is_system_cursor(IDC_SIZENS)) return RemoteCursorShape::ns_resize;
|
||||
if (is_system_cursor(IDC_SIZENESW)) return RemoteCursorShape::nesw_resize;
|
||||
if (is_system_cursor(IDC_SIZENWSE)) return RemoteCursorShape::nwse_resize;
|
||||
if (is_system_cursor(IDC_UPARROW)) return RemoteCursorShape::n_resize;
|
||||
return RemoteCursorShape::default_cursor;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // CROSSDESK_WINDOWS_CURSOR_SHAPE_H_
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-16
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _WINDOWS_CURSOR_STATE_H_
|
||||
#define _WINDOWS_CURSOR_STATE_H_
|
||||
|
||||
#include <remote_action.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
|
||||
#include "windows_cursor_shape.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Used by both ordinary and secure-desktop capture. Device absence is only a
|
||||
// compatibility hint: a hidden cursor with a null handle, or touch/pen
|
||||
// suppression, must retain the application's normal hiding behavior.
|
||||
class WindowsCursorState {
|
||||
public:
|
||||
void Sample(const CURSORINFO& info, bool embedded, CursorState* state) {
|
||||
const bool showing = (info.flags & CURSOR_SHOWING) != 0;
|
||||
state->render_mode = embedded ? CursorRenderMode::embedded
|
||||
: showing ? CursorRenderMode::separate
|
||||
: CursorRenderMode::hidden;
|
||||
state->visible = state->render_mode == CursorRenderMode::separate;
|
||||
state->shape = state->visible ? ShapeFromWindowsCursor(info.hCursor)
|
||||
: RemoteCursorShape::none;
|
||||
state->hidden_reason = CursorHiddenReason::unspecified;
|
||||
if (!showing && !embedded) {
|
||||
state->hidden_reason = (info.flags & CURSOR_SUPPRESSED)
|
||||
? CursorHiddenReason::system_suppressed
|
||||
: info.hCursor && NoPointingDevice()
|
||||
? CursorHiddenReason::no_pointing_device
|
||||
: CursorHiddenReason::system_hidden;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// Query only for potentially recoverable hidden cursors, at most once per
|
||||
// second. Require two successful absent observations. Query failures, RDP
|
||||
// (whose devices may be absent from Raw Input), and present mice all disallow
|
||||
// fallback and break the sequence of absent observations.
|
||||
bool NoPointingDevice() {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now < next_device_check_) return absence_confirmed_;
|
||||
next_device_check_ = now + std::chrono::seconds(1);
|
||||
const bool absent = DetectDeviceAbsence();
|
||||
absence_confirmed_ = absent && absent_before_;
|
||||
absent_before_ = absent;
|
||||
return absence_confirmed_;
|
||||
}
|
||||
|
||||
static bool DetectDeviceAbsence() {
|
||||
if (GetSystemMetrics(SM_MOUSEPRESENT) ||
|
||||
GetSystemMetrics(SM_REMOTESESSION)) {
|
||||
return false;
|
||||
}
|
||||
UINT count = 0;
|
||||
if (GetRawInputDeviceList(nullptr, &count, sizeof(RAWINPUTDEVICELIST)) ==
|
||||
static_cast<UINT>(-1) ||
|
||||
count > 4096)
|
||||
return false;
|
||||
if (count == 0) return true;
|
||||
std::vector<RAWINPUTDEVICELIST> devices(count);
|
||||
const UINT read = GetRawInputDeviceList(devices.data(), &count,
|
||||
sizeof(RAWINPUTDEVICELIST));
|
||||
if (read == static_cast<UINT>(-1) || read > devices.size()) return false;
|
||||
for (UINT i = 0; i < read; ++i) {
|
||||
if (devices[i].dwType == RIM_TYPEMOUSE) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool absent_before_ = false;
|
||||
bool absence_confirmed_ = false;
|
||||
std::chrono::steady_clock::time_point next_device_check_{};
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -9,6 +9,7 @@ namespace crossdesk {
|
||||
// keyboard input so the controller hook can ignore only its own injections
|
||||
// while still accepting input from accessibility tools or remote sessions.
|
||||
inline constexpr std::uintptr_t kInjectedKeyboardInputMarker = 0x4353444B;
|
||||
inline constexpr std::uintptr_t kInjectedMouseInputMarker = 0x4353444D;
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include <Windows.h>
|
||||
#include <dwmapi.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cwchar>
|
||||
#include <vector>
|
||||
|
||||
#include "../../windows_thread_dpi.h"
|
||||
#include "../privacy_band_ipc.h"
|
||||
#include "privacy_cover_renderer.h"
|
||||
|
||||
namespace {
|
||||
using namespace crossdesk;
|
||||
constexpr wchar_t kWindowClass[] = L"CrossDesk.HighBandPrivacy";
|
||||
constexpr DWORD kCoverStyles = WS_EX_TOPMOST | WS_EX_NOACTIVATE |
|
||||
WS_EX_TOOLWINDOW | WS_EX_LAYERED |
|
||||
WS_EX_TRANSPARENT;
|
||||
HMODULE module = nullptr;
|
||||
|
||||
bool SameRect(const RECT& a, const RECT& b) {
|
||||
return a.left == b.left && a.top == b.top && a.right == b.right &&
|
||||
a.bottom == b.bottom;
|
||||
}
|
||||
|
||||
class Windows {
|
||||
public:
|
||||
explicit Windows(PrivacyBandShared* shared) : shared_(shared) {}
|
||||
~Windows() {
|
||||
for (const auto& window : windows_)
|
||||
DestroyWindow(reinterpret_cast<HWND>(window.hwnd));
|
||||
if (atom_) UnregisterClassW(kWindowClass, module);
|
||||
}
|
||||
bool Fail(const wchar_t* operation, DWORD code = GetLastError()) {
|
||||
wcsncpy_s(shared_->operation, operation, _TRUNCATE);
|
||||
InterlockedExchange(&shared_->error, code ? code : ERROR_GEN_FAILURE);
|
||||
return false;
|
||||
}
|
||||
bool Initialize() {
|
||||
const HMODULE user = GetModuleHandleW(L"user32.dll");
|
||||
create_ = reinterpret_cast<CreatePrivacyWindowInBand>(
|
||||
GetProcAddress(user, "CreateWindowInBand"));
|
||||
get_band_ = reinterpret_cast<GetPrivacyWindowBand>(
|
||||
GetProcAddress(user, "GetWindowBand"));
|
||||
if (!create_ || !get_band_)
|
||||
return Fail(L"Resolve high-band APIs", ERROR_PROC_NOT_FOUND);
|
||||
WNDCLASSEXW cls{sizeof(cls)};
|
||||
cls.hInstance = module;
|
||||
cls.lpfnWndProc = WindowProc;
|
||||
cls.lpszClassName = kWindowClass;
|
||||
cls.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH));
|
||||
atom_ = RegisterClassExW(&cls);
|
||||
return atom_ ? Reconcile() : Fail(L"Register high-band window class");
|
||||
}
|
||||
bool Reconcile() {
|
||||
std::vector<RECT> monitors;
|
||||
if (!EnumDisplayMonitors(
|
||||
nullptr, nullptr,
|
||||
[](HMONITOR, HDC, LPRECT rect, LPARAM data) -> BOOL {
|
||||
auto& result = *reinterpret_cast<std::vector<RECT>*>(data);
|
||||
if (result.size() >= kPrivacyMaxMonitors) return FALSE;
|
||||
result.push_back(*rect);
|
||||
return TRUE;
|
||||
},
|
||||
reinterpret_cast<LPARAM>(&monitors)) ||
|
||||
monitors.empty())
|
||||
return Fail(L"Enumerate high-band displays");
|
||||
bool changed = monitors.size() != windows_.size();
|
||||
for (const auto& rect : monitors) {
|
||||
const auto found =
|
||||
std::find_if(windows_.begin(), windows_.end(),
|
||||
[&](const auto& w) { return SameRect(w.rect, rect); });
|
||||
if (found != windows_.end()) continue;
|
||||
changed = true;
|
||||
HWND hwnd = create_(kCoverStyles, atom_, L"CrossDesk Privacy", WS_POPUP,
|
||||
rect.left, rect.top, rect.right - rect.left,
|
||||
rect.bottom - rect.top, nullptr, nullptr, module,
|
||||
this, kPrivacyWindowBand);
|
||||
if (!hwnd) return Fail(L"CreateWindowInBand ZBID_ABOVELOCK_UX");
|
||||
windows_.push_back({reinterpret_cast<uint64_t>(hwnd), rect});
|
||||
if (!SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA))
|
||||
return Fail(L"Make high-band cover opaque");
|
||||
if (!SetWindowDisplayAffinity(hwnd, 0x11))
|
||||
return Fail(L"Exclude high-band cover from capture");
|
||||
const BOOL yes = TRUE;
|
||||
const HRESULT peek = DwmSetWindowAttribute(hwnd, DWMWA_EXCLUDED_FROM_PEEK,
|
||||
&yes, sizeof(yes));
|
||||
if (FAILED(peek)) return Fail(L"Exclude high-band cover from Peek", peek);
|
||||
if (!SetWindowPos(hwnd, nullptr, rect.left, rect.top,
|
||||
rect.right - rect.left, rect.bottom - rect.top,
|
||||
SWP_NOZORDER | SWP_NOACTIVATE | SWP_SHOWWINDOW) ||
|
||||
!RedrawWindow(hwnd, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW))
|
||||
return Fail(L"Present high-band cover");
|
||||
}
|
||||
if (changed) {
|
||||
const HRESULT result = DwmFlush();
|
||||
if (FAILED(result))
|
||||
return Fail(L"Flush high-band cover presentation", result);
|
||||
// New areas are covered before old windows are removed.
|
||||
for (auto it = windows_.begin(); it != windows_.end();) {
|
||||
if (std::none_of(
|
||||
monitors.begin(), monitors.end(),
|
||||
[&](const auto& rect) { return SameRect(rect, it->rect); })) {
|
||||
if (!DestroyWindow(reinterpret_cast<HWND>(it->hwnd)))
|
||||
return Fail(L"Destroy obsolete high-band cover");
|
||||
it = windows_.erase(it);
|
||||
} else
|
||||
++it;
|
||||
}
|
||||
}
|
||||
if (!Validate()) return false;
|
||||
if (changed) {
|
||||
InterlockedIncrement(&shared_->sequence);
|
||||
shared_->count = static_cast<uint32_t>(windows_.size());
|
||||
std::copy(windows_.begin(), windows_.end(), shared_->windows);
|
||||
InterlockedIncrement(&shared_->sequence);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool Validate() {
|
||||
if (paint_failed_) return false;
|
||||
for (const auto& w : windows_) {
|
||||
HWND hwnd = reinterpret_cast<HWND>(w.hwnd);
|
||||
DWORD band = 0, affinity = 0, flags = 0, cloaked = 0;
|
||||
BYTE alpha = 0;
|
||||
RECT rect{};
|
||||
if ((GetWindowLongPtrW(hwnd, GWL_EXSTYLE) & kCoverStyles) !=
|
||||
kCoverStyles ||
|
||||
!get_band_(hwnd, &band) || band != kPrivacyWindowBand ||
|
||||
!GetWindowDisplayAffinity(hwnd, &affinity) || affinity != 0x11 ||
|
||||
!GetLayeredWindowAttributes(hwnd, nullptr, &alpha, &flags) ||
|
||||
alpha != 255 || flags != LWA_ALPHA || !IsWindowVisible(hwnd) ||
|
||||
!GetWindowRect(hwnd, &rect) || !SameRect(rect, w.rect) ||
|
||||
FAILED(DwmGetWindowAttribute(hwnd, DWMWA_CLOAKED, &cloaked,
|
||||
sizeof(cloaked))) ||
|
||||
cloaked)
|
||||
return Fail(L"High-band cover lost style/band/affinity/visibility",
|
||||
ERROR_INVALID_STATE);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool changed = false;
|
||||
|
||||
private:
|
||||
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wp,
|
||||
LPARAM lp) {
|
||||
if (message == WM_NCCREATE) {
|
||||
auto create = reinterpret_cast<CREATESTRUCTW*>(lp);
|
||||
SetWindowLongPtrW(hwnd, GWLP_USERDATA,
|
||||
reinterpret_cast<LONG_PTR>(create->lpCreateParams));
|
||||
}
|
||||
auto self =
|
||||
reinterpret_cast<Windows*>(GetWindowLongPtrW(hwnd, GWLP_USERDATA));
|
||||
if (message == WM_MOUSEACTIVATE) return MA_NOACTIVATE;
|
||||
if (message == WM_NCHITTEST) return HTTRANSPARENT;
|
||||
if (message == WM_SETCURSOR) {
|
||||
SetCursor(nullptr);
|
||||
return TRUE;
|
||||
}
|
||||
if (message == WM_CLOSE) return 0;
|
||||
if ((message == WM_DISPLAYCHANGE || message == WM_DPICHANGED) && self) {
|
||||
self->changed = true;
|
||||
InvalidateRect(hwnd, nullptr, TRUE);
|
||||
return 0;
|
||||
}
|
||||
if (message == WM_PAINT) {
|
||||
PAINTSTRUCT paint{};
|
||||
HDC dc = BeginPaint(hwnd, &paint);
|
||||
RECT rect{};
|
||||
GetClientRect(hwnd, &rect);
|
||||
if (self && !DrawPrivacyCover(dc, rect, PrivacyWindowDpi(hwnd), module,
|
||||
self->shared_->unlock_hint)) {
|
||||
self->paint_failed_ = true;
|
||||
self->Fail(L"Paint privacy logo and unlock instructions");
|
||||
}
|
||||
EndPaint(hwnd, &paint);
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(hwnd, message, wp, lp);
|
||||
}
|
||||
PrivacyBandShared* shared_;
|
||||
bool paint_failed_ = false;
|
||||
std::vector<PrivacyBandWindow> windows_;
|
||||
ATOM atom_ = 0;
|
||||
CreatePrivacyWindowInBand create_ = nullptr;
|
||||
GetPrivacyWindowBand get_band_ = nullptr;
|
||||
};
|
||||
|
||||
DWORD Run() {
|
||||
wchar_t bootstrap[256]{};
|
||||
if (!GetEnvironmentVariableW(kPrivacyBandBootstrap, bootstrap, 256))
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
SetEnvironmentVariableW(kPrivacyBandBootstrap, nullptr);
|
||||
std::array<HANDLE, 4> handles{};
|
||||
wchar_t* item = bootstrap;
|
||||
for (size_t i = 0; i < handles.size(); ++i) {
|
||||
wchar_t* end = nullptr;
|
||||
const auto value = wcstoull(item, &end, 10);
|
||||
if (!value || end == item ||
|
||||
(i + 1 == handles.size() ? *end != 0 : *end != L','))
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
handles[i] = reinterpret_cast<HANDLE>(value);
|
||||
item = end + 1;
|
||||
}
|
||||
HANDLE parent = handles[0], stop = handles[1], ready = handles[2],
|
||||
mapping = handles[3];
|
||||
auto shared = static_cast<PrivacyBandShared*>(MapViewOfFile(
|
||||
mapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(PrivacyBandShared)));
|
||||
if (!shared) return GetLastError();
|
||||
if (shared->magic != kPrivacyBandMagic ||
|
||||
shared->version != kPrivacyBandVersion ||
|
||||
shared->size != sizeof(PrivacyBandShared) ||
|
||||
shared->broker_pid != GetCurrentProcessId() ||
|
||||
shared->parent_pid != GetProcessId(parent) ||
|
||||
WaitForSingleObject(parent, 0) != WAIT_TIMEOUT) {
|
||||
UnmapViewOfFile(shared);
|
||||
return ERROR_INVALID_DATA;
|
||||
}
|
||||
DWORD exit_code = ERROR_SUCCESS;
|
||||
{
|
||||
ScopedWindowsPhysicalCoordinates dpi;
|
||||
Windows windows(shared);
|
||||
try {
|
||||
bool healthy = dpi.active() && windows.Initialize();
|
||||
const bool initialized = healthy;
|
||||
if (!dpi.active()) windows.Fail(L"Set high-band thread DPI context");
|
||||
InterlockedExchange64(&shared->heartbeat, GetTickCount64());
|
||||
if (healthy) {
|
||||
InterlockedExchange(&shared->error, ERROR_SUCCESS);
|
||||
InterlockedExchange(&shared->active, 1);
|
||||
}
|
||||
SetEvent(ready);
|
||||
auto last_check = GetTickCount64();
|
||||
HANDLE watched[] = {parent, stop};
|
||||
// Once enabled, retain surviving covers on a validation/layout fault.
|
||||
// The parent releases privacy after reading the latched error. Only an
|
||||
// explicit stop or parent death tears the remaining windows down.
|
||||
while (initialized) {
|
||||
const DWORD wait = MsgWaitForMultipleObjectsEx(
|
||||
2, watched, 100, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
|
||||
if (wait == WAIT_OBJECT_0 || wait == WAIT_OBJECT_0 + 1) break;
|
||||
if (wait == WAIT_FAILED) {
|
||||
windows.Fail(L"Wait for high-band lifecycle");
|
||||
break;
|
||||
}
|
||||
MSG message{};
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
if (message.message == WM_QUIT) healthy = false;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
const auto now = GetTickCount64();
|
||||
if (healthy && (windows.changed || now - last_check >= 250)) {
|
||||
windows.changed = false;
|
||||
last_check = now;
|
||||
healthy = windows.Reconcile();
|
||||
}
|
||||
InterlockedExchange64(&shared->heartbeat, now);
|
||||
}
|
||||
} catch (...) {
|
||||
windows.Fail(L"High-band window thread exception",
|
||||
ERROR_UNHANDLED_EXCEPTION);
|
||||
SetEvent(ready);
|
||||
}
|
||||
exit_code = InterlockedCompareExchange(&shared->error, 0, 0);
|
||||
InterlockedExchange(&shared->active, 0);
|
||||
}
|
||||
UnmapViewOfFile(shared);
|
||||
for (HANDLE handle : handles) CloseHandle(handle);
|
||||
return exit_code;
|
||||
}
|
||||
|
||||
void CALLBACK RunBeforeBrokerEntryPoint(ULONG_PTR) {
|
||||
// The LoadLibraryW startup APC has returned, so the loader lock is no longer
|
||||
// held. Own the primary thread until privacy stops, including startup errors.
|
||||
// Never return into RuntimeBroker's COM server startup: an elevated launch
|
||||
// can fail there with CO_E_WRONG_SERVER_IDENTITY and kill healthy covers.
|
||||
ExitProcess(Run());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID) {
|
||||
if (reason == DLL_PROCESS_ATTACH) {
|
||||
module = instance;
|
||||
// Loaded by the startup APC on our dedicated, suspended broker's primary
|
||||
// thread. Queue the window loop after that APC instead of starting a worker
|
||||
// alongside RuntimeBroker's own entry point. Do not run it under loader lock.
|
||||
if (!QueueUserAPC(RunBeforeBrokerEntryPoint, GetCurrentThread(), 0))
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include "privacy_cover_renderer.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
constexpr size_t kInstructionLines = 2;
|
||||
constexpr size_t kBrandLine = kInstructionLines;
|
||||
|
||||
struct PaintResources {
|
||||
HDC dc;
|
||||
int saved;
|
||||
HICON logo = nullptr;
|
||||
std::array<HFONT, kInstructionLines + 1> fonts{};
|
||||
~PaintResources() {
|
||||
// Deselect every owned GDI object before releasing it.
|
||||
if (saved) RestoreDC(dc, saved);
|
||||
for (auto font : fonts)
|
||||
if (font) DeleteObject(font);
|
||||
if (logo) DestroyIcon(logo);
|
||||
}
|
||||
};
|
||||
|
||||
bool Select(HDC dc, HGDIOBJ object) {
|
||||
const auto previous = SelectObject(dc, object);
|
||||
return previous && previous != HGDI_ERROR;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool DrawPrivacyCover(HDC dc, const RECT& rect, UINT dpi, HINSTANCE module,
|
||||
const wchar_t* unlock_hint) {
|
||||
if (!FillRect(dc, &rect, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH))))
|
||||
return false;
|
||||
const int width = rect.right - rect.left;
|
||||
const int height = rect.bottom - rect.top;
|
||||
if (width <= 0 || height <= 0) return false;
|
||||
// Scale with the monitor DPI, shrinking the whole group on small displays.
|
||||
// All coordinates remain in the owning window's physical-pixel context.
|
||||
const double scale = (std::min)({dpi / 96.0, width / 640.0, height / 200.0});
|
||||
const auto px = [scale](int value) {
|
||||
return (std::max)(1, static_cast<int>(value * scale + 0.5));
|
||||
};
|
||||
const int margin = px(32);
|
||||
const int text_width = px(398);
|
||||
PaintResources resources{dc, SaveDC(dc)};
|
||||
if (!resources.saved || !SetBkMode(dc, TRANSPARENT)) return false;
|
||||
|
||||
struct Line {
|
||||
const wchar_t* text;
|
||||
int size;
|
||||
int weight;
|
||||
COLORREF color;
|
||||
RECT bounds{};
|
||||
};
|
||||
std::array<Line, kInstructionLines + 1> lines{{
|
||||
{unlock_hint, 16, FW_NORMAL, RGB(181, 190, 204)},
|
||||
{L"Ctrl + Alt + Shift + F12", 24, FW_SEMIBOLD, RGB(245, 247, 250)},
|
||||
{L"CrossDesk", 14, FW_SEMIBOLD, RGB(245, 247, 250)},
|
||||
}};
|
||||
constexpr UINT flags = DT_LEFT | DT_WORDBREAK | DT_NOPREFIX;
|
||||
for (size_t i = 0; i < lines.size(); ++i) {
|
||||
auto& line = lines[i];
|
||||
resources.fonts[i] =
|
||||
CreateFontW(-px(line.size), 0, 0, 0, line.weight, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
|
||||
ANTIALIASED_QUALITY, DEFAULT_PITCH, L"Microsoft YaHei UI");
|
||||
if (!resources.fonts[i] || !Select(dc, resources.fonts[i])) return false;
|
||||
line.bounds = {0, 0, text_width, 0};
|
||||
if (!DrawTextW(dc, line.text, -1, &line.bounds, flags | DT_CALCRECT) ||
|
||||
line.bounds.right > text_width)
|
||||
return false;
|
||||
}
|
||||
const int content_height =
|
||||
static_cast<int>(lines[0].bounds.bottom + lines[1].bounds.bottom) +
|
||||
px(12);
|
||||
// Match the icon width to the name; each side keeps its own height.
|
||||
const int brand_gap = px(6);
|
||||
const int brand_width = static_cast<int>(lines[kBrandLine].bounds.right);
|
||||
const int logo_size = brand_width;
|
||||
const int brand_height =
|
||||
logo_size + brand_gap + static_cast<int>(lines[kBrandLine].bounds.bottom);
|
||||
if (logo_size <= 0 ||
|
||||
(std::max)(brand_height, content_height) + 2 * margin > height ||
|
||||
brand_width + px(24) + text_width + 2 * margin > width)
|
||||
return false;
|
||||
resources.logo = static_cast<HICON>(LoadImageW(
|
||||
module, L"IDI_CROSSDESK_LOGO", IMAGE_ICON, logo_size, logo_size, 0));
|
||||
if (!resources.logo) return false;
|
||||
const int brand_left = rect.left + margin;
|
||||
const int left = brand_left + brand_width + px(24);
|
||||
const int brand_top = rect.bottom - margin - brand_height;
|
||||
int top = rect.bottom - margin - content_height;
|
||||
if (!DrawIconEx(dc, brand_left, brand_top, resources.logo, logo_size,
|
||||
logo_size, 0, nullptr, DI_NORMAL))
|
||||
return false;
|
||||
if (!Select(dc, resources.fonts[kBrandLine])) return false;
|
||||
RECT brand_bounds{brand_left, brand_top + logo_size + brand_gap,
|
||||
brand_left + brand_width, rect.bottom - margin};
|
||||
SetTextColor(dc, lines[kBrandLine].color);
|
||||
if (!DrawTextW(dc, lines[kBrandLine].text, -1, &brand_bounds,
|
||||
DT_CENTER | DT_SINGLELINE | DT_NOPREFIX))
|
||||
return false;
|
||||
for (size_t i = 0; i < kInstructionLines; ++i) {
|
||||
const auto& line = lines[i];
|
||||
if (!Select(dc, resources.fonts[i])) return false;
|
||||
RECT bounds{left, top, left + text_width, top + line.bounds.bottom};
|
||||
SetTextColor(dc, line.color);
|
||||
if (!DrawTextW(dc, line.text, -1, &bounds, flags)) return false;
|
||||
top += line.bounds.bottom + px(12);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_COVER_RENDERER_H_
|
||||
#define _PRIVACY_COVER_RENDERER_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Paints the local, opaque cover. The caller owns the HWND and its DPI context.
|
||||
bool DrawPrivacyCover(HDC dc, const RECT& rect, UINT dpi, HINSTANCE module,
|
||||
const wchar_t* unlock_hint);
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_COVER_RENDERER_H_
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cwchar>
|
||||
#include <limits>
|
||||
|
||||
#include "../privacy_cursor_api.h"
|
||||
|
||||
namespace {
|
||||
HANDLE ParseHandle(const wchar_t* text) {
|
||||
wchar_t* end = nullptr;
|
||||
errno = 0;
|
||||
const auto value = std::wcstoull(text, &end, 10);
|
||||
if (errno || !text[0] || *end || text[0] == L'-' || value == 0 ||
|
||||
value > (std::numeric_limits<uintptr_t>::max)())
|
||||
return nullptr;
|
||||
return reinterpret_cast<HANDLE>(static_cast<uintptr_t>(value));
|
||||
}
|
||||
DWORD FailureCode() {
|
||||
const DWORD code = GetLastError();
|
||||
return code ? code : ERROR_GEN_FAILURE;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int wmain(int argc, wchar_t** argv) {
|
||||
if (argc != 5) return ERROR_INVALID_PARAMETER;
|
||||
HANDLE parent = ParseHandle(argv[1]);
|
||||
HANDLE stop = ParseHandle(argv[2]);
|
||||
HANDLE ready = ParseHandle(argv[3]);
|
||||
HANDLE mapping = ParseHandle(argv[4]);
|
||||
// Observe the inherited process OBJECT, never a reused PID or a process name.
|
||||
if (!parent || !stop || !ready || !mapping ||
|
||||
WaitForSingleObject(parent, 0) != WAIT_TIMEOUT ||
|
||||
WaitForSingleObject(stop, 0) != WAIT_TIMEOUT)
|
||||
return ERROR_INVALID_HANDLE;
|
||||
auto shared = static_cast<crossdesk::PrivacyCursorReady*>(MapViewOfFile(
|
||||
mapping, FILE_MAP_WRITE, 0, 0, sizeof(crossdesk::PrivacyCursorReady)));
|
||||
if (!shared) return static_cast<int>(FailureCode());
|
||||
|
||||
crossdesk::PrivacyCursorApi cursor;
|
||||
DWORD error = ERROR_SUCCESS;
|
||||
if (!cursor.Initialize() || !cursor.Hide()) error = FailureCode();
|
||||
InterlockedExchange(&shared->error, static_cast<LONG>(error));
|
||||
if (!SetEvent(ready)) error = FailureCode();
|
||||
if (!error) {
|
||||
HANDLE watched[] = {parent, stop};
|
||||
for (;;) {
|
||||
const DWORD result =
|
||||
MsgWaitForMultipleObjects(2, watched, FALSE, 250, QS_ALLINPUT);
|
||||
if (result == WAIT_OBJECT_0 || result == WAIT_OBJECT_0 + 1) break;
|
||||
if (result == WAIT_OBJECT_0 + 2) {
|
||||
MSG message{};
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
} else if (result != WAIT_TIMEOUT) {
|
||||
error = FailureCode();
|
||||
break;
|
||||
}
|
||||
if (!cursor.Hide()) {
|
||||
error = FailureCode();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Also runs when the parent is force-terminated or crashes. The helper does
|
||||
// not own any input hooks or privacy HWNDs and never changes magnification.
|
||||
if (!cursor.RestoreAndClose()) error = FailureCode();
|
||||
UnmapViewOfFile(shared);
|
||||
CloseHandle(mapping);
|
||||
CloseHandle(ready);
|
||||
CloseHandle(stop);
|
||||
CloseHandle(parent);
|
||||
return static_cast<int>(error);
|
||||
}
|
||||
@@ -0,0 +1,573 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include <ShlObj.h>
|
||||
#include <Windows.h>
|
||||
#include <dwmapi.h>
|
||||
#include <winternl.h>
|
||||
#include <wtsapi32.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
|
||||
#include "../windows_thread_dpi.h"
|
||||
#include "privacy_backend.h"
|
||||
#include "privacy_band_guard.h"
|
||||
#include "privacy_cursor_guard.h"
|
||||
#include "privacy_input_guard.h"
|
||||
#include "privacy_window_visibility.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
#ifndef WDA_EXCLUDEFROMCAPTURE
|
||||
#define WDA_EXCLUDEFROMCAPTURE 0x00000011
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
constexpr wchar_t kClassName[] = L"CrossDesk.PrivacyWindow";
|
||||
constexpr UINT kEmergency = WM_APP + 71;
|
||||
constexpr int kHotkeyId = 0x4353;
|
||||
|
||||
std::string Error(const char* operation, DWORD code = GetLastError()) {
|
||||
const std::string result = std::string(operation) +
|
||||
" failed (Windows error " + std::to_string(code) +
|
||||
")";
|
||||
LOG_ERROR("Privacy: {}", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool DesktopName(HDESK desktop, wchar_t (&name)[256]) {
|
||||
DWORD needed = 0;
|
||||
return desktop && GetUserObjectInformationW(desktop, UOI_NAME, name,
|
||||
sizeof(name), &needed);
|
||||
}
|
||||
|
||||
bool SameRect(const RECT& a, const RECT& b) {
|
||||
return a.left == b.left && a.top == b.top && a.right == b.right &&
|
||||
a.bottom == b.bottom;
|
||||
}
|
||||
|
||||
struct MonitorEnumeration {
|
||||
std::vector<RECT> rects;
|
||||
bool ok = true;
|
||||
};
|
||||
|
||||
BOOL CALLBACK EnumMonitor(HMONITOR monitor, HDC, LPRECT, LPARAM data) {
|
||||
auto& result = *reinterpret_cast<MonitorEnumeration*>(data);
|
||||
MONITORINFO info{sizeof(info)};
|
||||
if (!GetMonitorInfoW(monitor, &info)) {
|
||||
Error("GetMonitorInfoW");
|
||||
result.ok = false;
|
||||
return FALSE;
|
||||
}
|
||||
result.rects.push_back(info.rcMonitor);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
class WindowsPrivacyBackend final : public PrivacyBackend {
|
||||
public:
|
||||
WindowsPrivacyBackend() {
|
||||
wake_event_ = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!wake_event_) wake_error_ = Error("CreateEventW privacy commands");
|
||||
}
|
||||
|
||||
~WindowsPrivacyBackend() override {
|
||||
Recover();
|
||||
if (sink_) DestroyWindow(sink_);
|
||||
if (registered_) UnregisterClassW(kClassName, GetModuleHandleW(nullptr));
|
||||
if (wake_event_) CloseHandle(wake_event_);
|
||||
}
|
||||
|
||||
PrivacyCapabilities Query() override {
|
||||
if (!wake_event_) return {false, false, wake_error_};
|
||||
using RtlGetVersionFn = LONG(WINAPI*)(PRTL_OSVERSIONINFOW);
|
||||
const auto rtl = reinterpret_cast<RtlGetVersionFn>(
|
||||
GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion"));
|
||||
RTL_OSVERSIONINFOW version{};
|
||||
version.dwOSVersionInfoSize = sizeof(version);
|
||||
if (!rtl || rtl(&version) != 0 || version.dwMajorVersion < 10 ||
|
||||
version.dwBuildNumber < 19041) {
|
||||
return {false, false, "Requires Windows 10 2004 (build 19041) or later"};
|
||||
}
|
||||
BOOL composed = FALSE;
|
||||
if (FAILED(DwmIsCompositionEnabled(&composed)) || !composed) {
|
||||
return {false, false, "Desktop composition is unavailable"};
|
||||
}
|
||||
if (GetSystemMetrics(SM_REMOTESESSION)) {
|
||||
return {false, false, "Privacy screen requires a local console session"};
|
||||
}
|
||||
if (!IsWindowsPrivacyDesktopAvailable()) {
|
||||
return {false, false,
|
||||
"Privacy screen requires the unlocked Default desktop"};
|
||||
}
|
||||
QUERY_USER_NOTIFICATION_STATE shell_state{};
|
||||
if (FAILED(SHQueryUserNotificationState(&shell_state)) ||
|
||||
shell_state == QUNS_RUNNING_D3D_FULL_SCREEN) {
|
||||
return {false, false,
|
||||
"Exclusive fullscreen or unknown display presentation cannot "
|
||||
"guarantee privacy coverage"};
|
||||
}
|
||||
std::string high_band_error;
|
||||
if (!PrivacyBandGuard::Available(high_band_error))
|
||||
return {false, false, high_band_error};
|
||||
return {true, true,
|
||||
"High-band privacy screen available"};
|
||||
}
|
||||
|
||||
bool Enable(bool block_input, const PrivacyScreenText& text,
|
||||
std::string& error) override {
|
||||
const auto caps = Query();
|
||||
if (!caps.overlay) {
|
||||
error = caps.reason;
|
||||
return false;
|
||||
}
|
||||
if (!Initialize(error)) return false;
|
||||
emergency_ = false;
|
||||
health_error_.clear();
|
||||
if (!RegisterHotKey(sink_, kHotkeyId,
|
||||
MOD_CONTROL | MOD_ALT | MOD_SHIFT | MOD_NOREPEAT,
|
||||
VK_F12)) {
|
||||
error = Error("RegisterHotKey Ctrl+Alt+Shift+F12");
|
||||
return false;
|
||||
}
|
||||
hotkey_ = true;
|
||||
if (!cursor_guard_.Start(error)) return false;
|
||||
block_input_ = block_input;
|
||||
if (block_input && !input_guard_.Start(sink_, kEmergency, error))
|
||||
return false;
|
||||
if (!band_guard_.Start(text, error)) return false;
|
||||
if (!ReconcileMonitors(error)) return false;
|
||||
event_owner_ = this;
|
||||
for (DWORD event : {EVENT_OBJECT_SHOW, EVENT_OBJECT_REORDER,
|
||||
EVENT_OBJECT_LOCATIONCHANGE}) {
|
||||
auto hook = SetWinEventHook(event, event, nullptr, WindowEvent, 0, 0,
|
||||
WINEVENT_OUTOFCONTEXT);
|
||||
if (!hook) {
|
||||
error = Error("Watch privacy window coverage changes");
|
||||
return false;
|
||||
}
|
||||
window_events_.push_back(hook);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Recover() override {
|
||||
for (auto& hook : window_events_) {
|
||||
if (UnhookWinEvent(hook))
|
||||
hook = nullptr;
|
||||
else
|
||||
Error("Unhook privacy window events");
|
||||
}
|
||||
window_events_.erase(
|
||||
std::remove(window_events_.begin(), window_events_.end(), nullptr),
|
||||
window_events_.end());
|
||||
if (window_events_.empty()) event_owner_ = nullptr;
|
||||
std::string band_error;
|
||||
band_guard_.Stop(band_error);
|
||||
if (band_guard_.stopped()) windows_.clear();
|
||||
input_guard_.Stop();
|
||||
block_input_ = false;
|
||||
if (hotkey_) {
|
||||
if (UnregisterHotKey(sink_, kHotkeyId) ||
|
||||
GetLastError() == ERROR_HOTKEY_NOT_REGISTERED)
|
||||
hotkey_ = false;
|
||||
else
|
||||
Error("UnregisterHotKey");
|
||||
}
|
||||
// The sink lives across sessions. Do not let an already-posted emergency
|
||||
// command from a closed session cancel a subsequent connection.
|
||||
if (sink_) {
|
||||
MSG discarded{};
|
||||
while (PeekMessageW(&discarded, sink_, WM_HOTKEY, WM_HOTKEY, PM_REMOVE)) {
|
||||
}
|
||||
while (
|
||||
PeekMessageW(&discarded, sink_, kEmergency, kEmergency, PM_REMOVE)) {
|
||||
}
|
||||
}
|
||||
last_check_ = 0;
|
||||
last_health_ = {};
|
||||
last_obstruction_ = nullptr;
|
||||
last_obstruction_log_ = 0;
|
||||
layout_changed_ = false;
|
||||
coverage_dirty_ = false;
|
||||
emergency_ = false;
|
||||
health_error_.clear();
|
||||
std::string cursor_error;
|
||||
cursor_guard_.Stop(cursor_error);
|
||||
}
|
||||
|
||||
bool IsRecovered() const override {
|
||||
return band_guard_.stopped() && windows_.empty() &&
|
||||
window_events_.empty() && input_guard_.stopped() && !hotkey_ &&
|
||||
cursor_guard_.stopped();
|
||||
}
|
||||
|
||||
void Wake() override {
|
||||
if (wake_event_) SetEvent(wake_event_);
|
||||
}
|
||||
|
||||
void WaitForEvents(unsigned timeout_ms) override {
|
||||
const DWORD result = MsgWaitForMultipleObjectsEx(
|
||||
wake_event_ ? 1 : 0, wake_event_ ? &wake_event_ : nullptr, timeout_ms,
|
||||
QS_ALLINPUT, MWMO_INPUTAVAILABLE);
|
||||
if (result == WAIT_FAILED)
|
||||
health_error_ = Error("MsgWaitForMultipleObjectsEx privacy thread");
|
||||
}
|
||||
|
||||
PrivacyHealth Poll() override {
|
||||
MSG message{};
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
if (message.message == WM_QUIT)
|
||||
health_error_ =
|
||||
"Privacy message thread is exiting";
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
if (emergency_) {
|
||||
emergency_ = false;
|
||||
return {{}, true};
|
||||
}
|
||||
if (block_input_) {
|
||||
std::string error;
|
||||
if (!input_guard_.Healthy(error)) return {error, false};
|
||||
}
|
||||
if (windows_.empty()) return {health_error_, false};
|
||||
// Input messages wake the thread immediately; expensive health queries
|
||||
// must retain their own cadence instead of running once per input event.
|
||||
if (!layout_changed_ &&
|
||||
GetTickCount64() - last_check_ < 100) {
|
||||
if (coverage_dirty_ && last_health_.failure.empty()) {
|
||||
coverage_dirty_ = false;
|
||||
last_health_ = CheckCoverage();
|
||||
}
|
||||
return last_health_;
|
||||
}
|
||||
coverage_dirty_ = false;
|
||||
last_check_ = GetTickCount64();
|
||||
last_health_ = CheckHealth();
|
||||
return last_health_;
|
||||
}
|
||||
|
||||
private:
|
||||
PrivacyHealth CheckHealth() {
|
||||
if (!health_error_.empty()) return {health_error_, false};
|
||||
if (!band_guard_.Healthy(health_error_)) return {health_error_, false};
|
||||
if (!IsWindowsPrivacyDesktopAvailable()) {
|
||||
std::string cursor_error;
|
||||
cursor_guard_.Stop(cursor_error);
|
||||
return {
|
||||
"Secure desktop, lock screen or unavailable input desktop; "
|
||||
"privacy screen will turn off",
|
||||
false};
|
||||
}
|
||||
std::string cursor_error;
|
||||
if (!cursor_guard_.Healthy(cursor_error)) return {cursor_error, false};
|
||||
QUERY_USER_NOTIFICATION_STATE shell_state{};
|
||||
if (FAILED(SHQueryUserNotificationState(&shell_state)) ||
|
||||
shell_state == QUNS_RUNNING_D3D_FULL_SCREEN) {
|
||||
return {
|
||||
"Exclusive fullscreen or unknown display presentation",
|
||||
false};
|
||||
}
|
||||
MonitorEnumeration monitors;
|
||||
if (!EnumDisplayMonitors(nullptr, nullptr, EnumMonitor,
|
||||
reinterpret_cast<LPARAM>(&monitors)) ||
|
||||
!monitors.ok) {
|
||||
return {Error("EnumDisplayMonitors"), false};
|
||||
}
|
||||
const bool changed =
|
||||
monitors.rects.size() != windows_.size() ||
|
||||
std::any_of(monitors.rects.begin(), monitors.rects.end(),
|
||||
[this](const RECT& rect) {
|
||||
return std::none_of(windows_.begin(), windows_.end(),
|
||||
[&](const auto& w) {
|
||||
return SameRect(w.rect, rect);
|
||||
});
|
||||
});
|
||||
if (changed || layout_changed_) {
|
||||
layout_changed_ = false;
|
||||
// Retain old covers until the monitor check completes, then release
|
||||
// privacy so capture can refresh its display mapping independently.
|
||||
std::string error;
|
||||
if (!ReconcileMonitors(error))
|
||||
health_error_ = error;
|
||||
else
|
||||
health_error_ =
|
||||
"Display layout/DPI changed; privacy screen will turn off";
|
||||
}
|
||||
if (!health_error_.empty()) return {health_error_, false};
|
||||
BOOL composed = FALSE;
|
||||
if (FAILED(DwmIsCompositionEnabled(&composed)) || !composed) {
|
||||
return {
|
||||
"Desktop composition stopped; privacy coverage cannot be guaranteed",
|
||||
false};
|
||||
}
|
||||
return CheckCoverage();
|
||||
}
|
||||
|
||||
PrivacyHealth CheckCoverage() {
|
||||
const auto get_band = reinterpret_cast<GetPrivacyWindowBand>(
|
||||
GetProcAddress(GetModuleHandleW(L"user32.dll"), "GetWindowBand"));
|
||||
if (!get_band) return {"High-band window API became unavailable", false};
|
||||
for (const auto& w : windows_) {
|
||||
DWORD band = 0;
|
||||
DWORD affinity = 0;
|
||||
BYTE alpha = 0;
|
||||
DWORD layered_flags = 0;
|
||||
RECT rect{};
|
||||
DWORD cloaked = 0;
|
||||
if (!get_band(w.cover, &band) || band != kPrivacyWindowBand ||
|
||||
!IsWindowVisible(w.cover) || !GetWindowRect(w.cover, &rect) ||
|
||||
!SameRect(rect, w.rect) ||
|
||||
!(GetWindowLongPtrW(w.cover, GWL_EXSTYLE) & WS_EX_TOPMOST) ||
|
||||
!GetLayeredWindowAttributes(w.cover, nullptr, &alpha,
|
||||
&layered_flags) ||
|
||||
alpha != 255 || layered_flags != LWA_ALPHA ||
|
||||
!GetWindowDisplayAffinity(w.cover, &affinity) ||
|
||||
affinity != WDA_EXCLUDEFROMCAPTURE ||
|
||||
FAILED(DwmGetWindowAttribute(w.cover, DWMWA_CLOAKED, &cloaked,
|
||||
sizeof(cloaked))) ||
|
||||
cloaked) {
|
||||
return {
|
||||
"Privacy window visibility, geometry or capture affinity was lost",
|
||||
false};
|
||||
}
|
||||
}
|
||||
for (const auto& w : windows_) {
|
||||
// Detect windows in special bands above the cover. A high-band window
|
||||
// still cannot cover another desktop or guarantee exclusive fullscreen.
|
||||
for (HWND above = GetWindow(w.cover, GW_HWNDPREV); above;
|
||||
above = GetWindow(above, GW_HWNDPREV)) {
|
||||
if (!IsWindowVisible(above) || IsIconic(above)) continue;
|
||||
DWORD above_band = 0;
|
||||
if (!get_band(above, &above_band))
|
||||
return {"Could not inspect a window above the high-band cover",
|
||||
false};
|
||||
// HWND list order alone does not express compositor band order.
|
||||
// Only skip the two known ordinary desktop bands, never unknown bands.
|
||||
if (above_band == 0 || above_band == 1) continue;
|
||||
if (std::any_of(windows_.begin(), windows_.end(),
|
||||
[above](const auto& own) {
|
||||
return above == own.cover;
|
||||
}))
|
||||
continue;
|
||||
RECT bounds{}, intersection{};
|
||||
DWORD hidden = 0;
|
||||
if (SUCCEEDED(DwmGetWindowAttribute(above, DWMWA_CLOAKED, &hidden,
|
||||
sizeof(hidden))) &&
|
||||
hidden)
|
||||
continue;
|
||||
if (GetWindowRect(above, &bounds) &&
|
||||
IntersectRect(&intersection, &bounds, &w.rect)) {
|
||||
if (IsNonObstructingPrivacyWindow(above, bounds)) continue;
|
||||
char window_class[128]{};
|
||||
DWORD process_id = 0;
|
||||
GetClassNameA(above, window_class, sizeof(window_class));
|
||||
GetWindowThreadProcessId(above, &process_id);
|
||||
const auto now = GetTickCount64();
|
||||
if (above != last_obstruction_ ||
|
||||
now - last_obstruction_log_ >= 1000) {
|
||||
LOG_WARN(
|
||||
"Potential privacy cover overlap: class={}, process={}, "
|
||||
"band={}, bounds=({}, {})-({}, {}), exstyle=0x{:x}",
|
||||
window_class, process_id, above_band, bounds.left, bounds.top,
|
||||
bounds.right, bounds.bottom,
|
||||
GetWindowLongPtrW(above, GWL_EXSTYLE));
|
||||
last_obstruction_ = above;
|
||||
last_obstruction_log_ = now;
|
||||
}
|
||||
// HWND order cannot prove compositor order, but this window may
|
||||
// display content. Report failure so optional privacy is released.
|
||||
return {
|
||||
"A visible window may overlap privacy coverage",
|
||||
false};
|
||||
}
|
||||
}
|
||||
}
|
||||
return {health_error_, false};
|
||||
}
|
||||
|
||||
struct Window {
|
||||
RECT rect{};
|
||||
HWND cover = nullptr;
|
||||
};
|
||||
|
||||
bool Initialize(std::string& error) {
|
||||
if (sink_) return true;
|
||||
// This dedicated thread owns no existing application windows. Never alter
|
||||
// process-wide or Slint/SDL DPI awareness.
|
||||
if (!dpi_scope_ || !dpi_scope_->active()) {
|
||||
dpi_scope_.reset();
|
||||
dpi_scope_ = std::make_unique<ScopedWindowsPhysicalCoordinates>();
|
||||
}
|
||||
if (!dpi_scope_->active()) {
|
||||
error = Error("SetThreadDpiAwarenessContext");
|
||||
return false;
|
||||
}
|
||||
WNDCLASSEXW cls{sizeof(cls)};
|
||||
cls.lpfnWndProc = WindowProc;
|
||||
cls.hInstance = GetModuleHandleW(nullptr);
|
||||
cls.lpszClassName = kClassName;
|
||||
cls.hCursor = nullptr;
|
||||
cls.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH));
|
||||
if (!registered_ && !RegisterClassExW(&cls)) {
|
||||
error = Error("RegisterClassExW");
|
||||
return false;
|
||||
}
|
||||
registered_ = true;
|
||||
sink_ = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, kClassName,
|
||||
L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr,
|
||||
cls.hInstance, this);
|
||||
if (!sink_) {
|
||||
error = Error("CreateWindowExW message sink");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ReconcileMonitors(std::string& error) {
|
||||
MonitorEnumeration monitors;
|
||||
if (!EnumDisplayMonitors(nullptr, nullptr, EnumMonitor,
|
||||
reinterpret_cast<LPARAM>(&monitors)) ||
|
||||
!monitors.ok || monitors.rects.empty()) {
|
||||
error = Error("EnumDisplayMonitors");
|
||||
return false;
|
||||
}
|
||||
std::vector<PrivacyBandWindow> covers;
|
||||
if (!band_guard_.Windows(covers, error)) return false;
|
||||
for (const RECT& rect : monitors.rects) {
|
||||
auto existing =
|
||||
std::find_if(windows_.begin(), windows_.end(),
|
||||
[&](const auto& w) { return SameRect(w.rect, rect); });
|
||||
if (existing != windows_.end()) continue;
|
||||
const auto cover = std::find_if(covers.begin(), covers.end(),
|
||||
[&](const auto& candidate) {
|
||||
return SameRect(candidate.rect, rect);
|
||||
});
|
||||
if (cover == covers.end()) {
|
||||
error = "High-band broker has not covered every physical monitor";
|
||||
return false;
|
||||
}
|
||||
windows_.push_back({rect, reinterpret_cast<HWND>(cover->hwnd)});
|
||||
LOG_INFO(
|
||||
"Privacy high-band cover ready: bounds=({}, {})-({}, {}), "
|
||||
"affinity=0x11, alpha=255",
|
||||
rect.left, rect.top, rect.right, rect.bottom);
|
||||
}
|
||||
// Cover windows are owned and released by the broker.
|
||||
windows_.erase(std::remove_if(windows_.begin(), windows_.end(),
|
||||
[&](const auto& window) {
|
||||
return std::none_of(monitors.rects.begin(), monitors.rects.end(),
|
||||
[&](const RECT& rect) { return SameRect(window.rect, rect); });
|
||||
}), windows_.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wp,
|
||||
LPARAM lp) {
|
||||
if (msg == WM_NCCREATE) {
|
||||
const auto create = reinterpret_cast<CREATESTRUCTW*>(lp);
|
||||
SetWindowLongPtrW(hwnd, GWLP_USERDATA,
|
||||
reinterpret_cast<LONG_PTR>(create->lpCreateParams));
|
||||
}
|
||||
auto self = reinterpret_cast<WindowsPrivacyBackend*>(
|
||||
GetWindowLongPtrW(hwnd, GWLP_USERDATA));
|
||||
if (msg == WM_HOTKEY || msg == kEmergency) {
|
||||
if (self && hwnd == self->sink_) self->emergency_ = true;
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_MOUSEACTIVATE) return MA_NOACTIVATE;
|
||||
if (msg == WM_SETCURSOR) {
|
||||
SetCursor(nullptr);
|
||||
return TRUE;
|
||||
}
|
||||
if (msg == WM_NCHITTEST) return HTTRANSPARENT;
|
||||
if (msg == WM_CLOSE) return 0;
|
||||
if ((msg == WM_DISPLAYCHANGE || msg == WM_DPICHANGED) && self) {
|
||||
self->layout_changed_ = true;
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProcW(hwnd, msg, wp, lp);
|
||||
}
|
||||
|
||||
static void CALLBACK WindowEvent(HWINEVENTHOOK, DWORD, HWND hwnd, LONG object,
|
||||
LONG child, DWORD, DWORD) {
|
||||
auto self = event_owner_;
|
||||
if (!self || !hwnd || object != OBJID_WINDOW || child != CHILDID_SELF ||
|
||||
hwnd == self->sink_ || GetAncestor(hwnd, GA_ROOT) != hwnd)
|
||||
return;
|
||||
for (const auto& w : self->windows_)
|
||||
if (hwnd == w.cover) return;
|
||||
// OUTOFCONTEXT delivers on this window thread. Only mark work here;
|
||||
// monitor/session queries and Z-order changes remain in the control loop.
|
||||
const auto get_band = reinterpret_cast<GetPrivacyWindowBand>(
|
||||
GetProcAddress(GetModuleHandleW(L"user32.dll"), "GetWindowBand"));
|
||||
DWORD band = 0;
|
||||
if (get_band && get_band(hwnd, &band) && (band == 0 || band == 1)) return;
|
||||
self->coverage_dirty_ = true;
|
||||
}
|
||||
|
||||
inline static thread_local WindowsPrivacyBackend* event_owner_ = nullptr;
|
||||
std::vector<HWINEVENTHOOK> window_events_;
|
||||
std::vector<Window> windows_;
|
||||
HWND sink_ = nullptr;
|
||||
HANDLE wake_event_ = nullptr;
|
||||
std::string wake_error_;
|
||||
PrivacyInputGuard input_guard_;
|
||||
bool block_input_ = false;
|
||||
PrivacyCursorGuard cursor_guard_;
|
||||
PrivacyBandGuard band_guard_;
|
||||
std::unique_ptr<ScopedWindowsPhysicalCoordinates> dpi_scope_;
|
||||
bool registered_ = false;
|
||||
bool hotkey_ = false;
|
||||
bool emergency_ = false;
|
||||
bool layout_changed_ = false;
|
||||
bool coverage_dirty_ = false;
|
||||
uint64_t last_check_ = 0;
|
||||
PrivacyHealth last_health_;
|
||||
HWND last_obstruction_ = nullptr;
|
||||
uint64_t last_obstruction_log_ = 0;
|
||||
std::string health_error_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool IsWindowsPrivacyDesktopAvailable() {
|
||||
// LockApp can display the lock screen while OpenInputDesktop still reports
|
||||
// Default. Desktop-name checks alone are NOT a session-unlocked check.
|
||||
DWORD session = 0;
|
||||
if (!ProcessIdToSessionId(GetCurrentProcessId(), &session) ||
|
||||
session != WTSGetActiveConsoleSessionId())
|
||||
return false;
|
||||
LPWSTR buffer = nullptr;
|
||||
DWORD bytes = 0;
|
||||
if (!WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session,
|
||||
WTSSessionInfoEx, &buffer, &bytes))
|
||||
return false;
|
||||
const auto info = reinterpret_cast<WTSINFOEXW*>(buffer);
|
||||
const bool unlocked =
|
||||
bytes >= sizeof(WTSINFOEXW) && info->Level == 1 &&
|
||||
info->Data.WTSInfoExLevel1.SessionFlags == WTS_SESSIONSTATE_UNLOCK;
|
||||
WTSFreeMemory(buffer);
|
||||
if (!unlocked) return false;
|
||||
HDESK input = OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS);
|
||||
if (!input) return false;
|
||||
wchar_t input_name[256]{}, thread_name[256]{};
|
||||
const bool ok =
|
||||
DesktopName(input, input_name) &&
|
||||
DesktopName(GetThreadDesktop(GetCurrentThreadId()), thread_name) &&
|
||||
_wcsicmp(input_name, L"Default") == 0 &&
|
||||
_wcsicmp(input_name, thread_name) == 0;
|
||||
CloseDesktop(input);
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::unique_ptr<PrivacyBackend> CreateWindowsPrivacyBackend() {
|
||||
return std::make_unique<WindowsPrivacyBackend>();
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,323 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include "privacy_band_guard.h"
|
||||
|
||||
#include <objbase.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
#include <new>
|
||||
|
||||
#include "privacy_backend.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
struct ScopedHandle {
|
||||
HANDLE value = nullptr;
|
||||
~ScopedHandle() {
|
||||
if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value);
|
||||
}
|
||||
};
|
||||
bool Failed(const char* operation, std::string& error,
|
||||
DWORD code = GetLastError()) {
|
||||
error =
|
||||
std::string(operation) + " (Windows error " + std::to_string(code) + ")";
|
||||
LOG_ERROR("Privacy high-band: {}", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::filesystem::path ModuleDirectory() {
|
||||
std::vector<wchar_t> path(32768);
|
||||
const DWORD length = GetModuleFileNameW(nullptr, path.data(), path.size());
|
||||
if (!length || length >= path.size()) return {};
|
||||
return std::filesystem::path(path.data()).parent_path();
|
||||
}
|
||||
|
||||
std::vector<wchar_t> ChildEnvironment(const std::wstring& bootstrap) {
|
||||
std::vector<std::wstring> entries;
|
||||
LPWCH environment = GetEnvironmentStringsW();
|
||||
if (!environment) return {};
|
||||
const std::wstring prefix = std::wstring(kPrivacyBandBootstrap) + L"=";
|
||||
for (const wchar_t* item = environment; *item; item += wcslen(item) + 1) {
|
||||
if (_wcsnicmp(item, prefix.c_str(), prefix.size()) != 0)
|
||||
entries.emplace_back(item);
|
||||
}
|
||||
FreeEnvironmentStringsW(environment);
|
||||
entries.push_back(prefix + bootstrap);
|
||||
std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) {
|
||||
return _wcsicmp(a.c_str(), b.c_str()) < 0;
|
||||
});
|
||||
std::vector<wchar_t> result;
|
||||
for (const auto& entry : entries) {
|
||||
result.insert(result.end(), entry.begin(), entry.end());
|
||||
result.push_back(0);
|
||||
}
|
||||
result.push_back(0);
|
||||
return result;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
PrivacyBandGuard::~PrivacyBandGuard() {
|
||||
std::string error;
|
||||
if (!Stop(error)) {
|
||||
// Last-resort teardown still targets only this object's dedicated job.
|
||||
if (job_) CloseHandle(job_);
|
||||
job_ = nullptr;
|
||||
Stop(error);
|
||||
}
|
||||
}
|
||||
|
||||
bool PrivacyBandGuard::Available(std::string& error) {
|
||||
#if !defined(_M_X64) && !defined(__x86_64__)
|
||||
error = "High-band privacy currently requires an x64 Windows process";
|
||||
return false;
|
||||
#else
|
||||
const HMODULE user = GetModuleHandleW(L"user32.dll");
|
||||
if (!GetProcAddress(user, "CreateWindowInBand") ||
|
||||
!GetProcAddress(user, "GetWindowBand")) {
|
||||
error = "Windows high-band window APIs are unavailable";
|
||||
return false;
|
||||
}
|
||||
const auto directory = ModuleDirectory();
|
||||
if (directory.empty())
|
||||
return Failed("Resolve privacy module directory", error);
|
||||
const auto dll = directory / kPrivacyBandDll;
|
||||
if (GetFileAttributesW(dll.c_str()) == INVALID_FILE_ATTRIBUTES)
|
||||
return Failed("Missing crossdesk_privacy_window.dll", error);
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool PrivacyBandGuard::Start(const PrivacyScreenText& text,
|
||||
std::string& error) {
|
||||
if (process_)
|
||||
return Failed("High-band broker is already running", error, ERROR_BUSY);
|
||||
if (!Available(error)) return false;
|
||||
const auto directory = ModuleDirectory();
|
||||
if (directory.empty())
|
||||
return Failed("Resolve privacy module directory", error);
|
||||
const auto dll = directory / kPrivacyBandDll;
|
||||
wchar_t system[MAX_PATH]{}, temporary[MAX_PATH]{}, guid_text[40]{};
|
||||
GUID guid{};
|
||||
if (!GetSystemDirectoryW(system, MAX_PATH) ||
|
||||
!GetTempPathW(MAX_PATH, temporary) || FAILED(CoCreateGuid(&guid)) ||
|
||||
!StringFromGUID2(guid, guid_text, 40))
|
||||
return Failed("Resolve high-band broker paths", error);
|
||||
broker_directory_ = std::filesystem::path(temporary) /
|
||||
(std::wstring(L"CrossDesk-privacy-") + guid_text);
|
||||
if (!CreateDirectoryW(broker_directory_.c_str(), nullptr))
|
||||
return Failed("Create private broker directory", error);
|
||||
broker_path_ = broker_directory_ / L"RuntimeBroker_crossdesk.exe";
|
||||
if (!CopyFileW((std::filesystem::path(system) / L"RuntimeBroker.exe").c_str(),
|
||||
broker_path_.c_str(), TRUE))
|
||||
return Failed("Copy system RuntimeBroker for this session", error);
|
||||
// Keep both images immutable throughout creation/injection and the session.
|
||||
image_lock_ = CreateFileW(broker_path_.c_str(), GENERIC_READ, FILE_SHARE_READ,
|
||||
nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
dll_lock_ = CreateFileW(dll.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
|
||||
OPEN_EXISTING, 0, nullptr);
|
||||
if (image_lock_ == INVALID_HANDLE_VALUE || dll_lock_ == INVALID_HANDLE_VALUE)
|
||||
return Failed("Lock privacy broker images", error);
|
||||
|
||||
SECURITY_ATTRIBUTES inherit{sizeof(inherit), nullptr, TRUE};
|
||||
ScopedHandle parent;
|
||||
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(),
|
||||
GetCurrentProcess(), &parent.value,
|
||||
SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, TRUE,
|
||||
0))
|
||||
return Failed("Duplicate privacy parent process handle", error);
|
||||
stop_ = CreateEventW(&inherit, TRUE, FALSE, nullptr);
|
||||
ready_ = CreateEventW(&inherit, TRUE, FALSE, nullptr);
|
||||
mapping_ = CreateFileMappingW(INVALID_HANDLE_VALUE, &inherit, PAGE_READWRITE,
|
||||
0, sizeof(PrivacyBandShared), nullptr);
|
||||
if (!stop_ || !ready_ || !mapping_) {
|
||||
const auto code = GetLastError();
|
||||
return Failed("Create high-band broker IPC", error, code);
|
||||
}
|
||||
shared_ = static_cast<PrivacyBandShared*>(MapViewOfFile(
|
||||
mapping_, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(PrivacyBandShared)));
|
||||
if (!shared_) {
|
||||
return Failed("Map high-band broker IPC", error);
|
||||
}
|
||||
new (shared_) PrivacyBandShared{};
|
||||
// Immutable after process startup; no cross-process string objects or
|
||||
// concurrent writes while the window thread paints.
|
||||
if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
|
||||
text.unlock_hint.c_str(), -1, shared_->unlock_hint,
|
||||
static_cast<int>(std::size(shared_->unlock_hint))))
|
||||
return Failed("Encode privacy screen text", error);
|
||||
shared_->parent_pid = GetCurrentProcessId();
|
||||
HANDLE handles[] = {parent.value, stop_, ready_, mapping_};
|
||||
std::wstring bootstrap;
|
||||
for (HANDLE handle : handles) {
|
||||
if (!bootstrap.empty()) bootstrap += L",";
|
||||
bootstrap += std::to_wstring(reinterpret_cast<uintptr_t>(handle));
|
||||
}
|
||||
auto environment = ChildEnvironment(bootstrap);
|
||||
if (environment.empty()) {
|
||||
return Failed("Build broker environment", error);
|
||||
}
|
||||
|
||||
job_ = CreateJobObjectW(nullptr, nullptr);
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if (!job_ || !SetInformationJobObject(job_, JobObjectExtendedLimitInformation,
|
||||
&limits, sizeof(limits))) {
|
||||
return Failed("Bind high-band broker lifetime", error);
|
||||
}
|
||||
SIZE_T bytes = 0;
|
||||
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
|
||||
std::vector<unsigned char> attributes(bytes);
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb = sizeof(startup);
|
||||
startup.lpAttributeList =
|
||||
reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(attributes.data());
|
||||
if (!InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0,
|
||||
&bytes)) {
|
||||
return Failed("Initialize broker handle list", error);
|
||||
}
|
||||
bool ok = UpdateProcThreadAttribute(
|
||||
startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
handles, sizeof(handles), nullptr, nullptr) != FALSE;
|
||||
PROCESS_INFORMATION child{};
|
||||
std::wstring command = L"\"" + broker_path_.wstring() + L"\"";
|
||||
if (ok) {
|
||||
ok = CreateProcessW(
|
||||
broker_path_.c_str(), command.data(), nullptr, nullptr, TRUE,
|
||||
CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT |
|
||||
EXTENDED_STARTUPINFO_PRESENT,
|
||||
environment.data(), broker_directory_.c_str(),
|
||||
&startup.StartupInfo, &child) != FALSE;
|
||||
}
|
||||
const DWORD create_error = GetLastError();
|
||||
DeleteProcThreadAttributeList(startup.lpAttributeList);
|
||||
if (!ok)
|
||||
return Failed("Create owned RuntimeBroker process", error, create_error);
|
||||
process_ = child.hProcess;
|
||||
shared_->broker_pid = child.dwProcessId;
|
||||
if (!AssignProcessToJobObject(job_, process_)) {
|
||||
const DWORD code = GetLastError();
|
||||
TerminateProcess(process_, code);
|
||||
CloseHandle(child.hThread);
|
||||
return Failed("Assign owned RuntimeBroker to privacy job", error, code);
|
||||
}
|
||||
const auto path = dll.wstring();
|
||||
const auto size = (path.size() + 1) * sizeof(wchar_t);
|
||||
void* remote_path = VirtualAllocEx(process_, nullptr, size,
|
||||
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
SIZE_T written = 0;
|
||||
const auto loader =
|
||||
GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");
|
||||
ok =
|
||||
remote_path && loader &&
|
||||
WriteProcessMemory(process_, remote_path, path.c_str(), size, &written) &&
|
||||
written == size &&
|
||||
QueueUserAPC(reinterpret_cast<PAPCFUNC>(loader), child.hThread,
|
||||
reinterpret_cast<ULONG_PTR>(remote_path));
|
||||
DWORD injection_error = GetLastError();
|
||||
if (ok && ResumeThread(child.hThread) == DWORD(-1)) {
|
||||
ok = false;
|
||||
injection_error = GetLastError();
|
||||
}
|
||||
CloseHandle(child.hThread);
|
||||
if (!ok)
|
||||
return Failed("Load high-band window module into owned broker", error,
|
||||
injection_error);
|
||||
HANDLE startup_events[] = {ready_, process_};
|
||||
const DWORD result = WaitForMultipleObjects(2, startup_events, FALSE, 5000);
|
||||
if (result != WAIT_OBJECT_0) {
|
||||
DWORD code = ERROR_TIMEOUT;
|
||||
if (result == WAIT_OBJECT_0 + 1) GetExitCodeProcess(process_, &code);
|
||||
return Failed("High-band broker did not become ready", error, code);
|
||||
}
|
||||
std::vector<PrivacyBandWindow> windows;
|
||||
if (!Windows(windows, error)) return false;
|
||||
LOG_INFO("Privacy high-band broker ready: process={}, band={}, monitors={}",
|
||||
process_id(), kPrivacyWindowBand, windows.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PrivacyBandGuard::Healthy(std::string& error) {
|
||||
if (!process_ || !shared_)
|
||||
return Failed("High-band broker is not initialized", error,
|
||||
ERROR_INVALID_HANDLE);
|
||||
const LONG code = InterlockedCompareExchange(&shared_->error, 0, 0);
|
||||
if (code != ERROR_SUCCESS) {
|
||||
char operation[256]{};
|
||||
WideCharToMultiByte(CP_UTF8, 0, shared_->operation, -1, operation,
|
||||
sizeof(operation), nullptr, nullptr);
|
||||
return Failed(operation[0] ? operation : "High-band window startup failed",
|
||||
error, code);
|
||||
}
|
||||
if (WaitForSingleObject(process_, 0) != WAIT_TIMEOUT) {
|
||||
DWORD exit_code = ERROR_PROCESS_ABORTED;
|
||||
GetExitCodeProcess(process_, &exit_code);
|
||||
return Failed("High-band window process exited", error, exit_code);
|
||||
}
|
||||
if (!InterlockedCompareExchange(&shared_->active, 0, 0) ||
|
||||
GetTickCount64() - static_cast<ULONGLONG>(InterlockedCompareExchange64(
|
||||
&shared_->heartbeat, 0, 0)) >
|
||||
1500)
|
||||
return Failed("High-band window thread stopped responding", error,
|
||||
ERROR_TIMEOUT);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PrivacyBandGuard::Windows(std::vector<PrivacyBandWindow>& windows,
|
||||
std::string& error) {
|
||||
if (!Healthy(error)) return false;
|
||||
for (int attempt = 0; attempt < 4; ++attempt) {
|
||||
const LONG before = InterlockedCompareExchange(&shared_->sequence, 0, 0);
|
||||
if (before & 1) continue;
|
||||
const auto count = shared_->count;
|
||||
if (count == 0 || count > kPrivacyMaxMonitors) break;
|
||||
windows.assign(shared_->windows, shared_->windows + count);
|
||||
if (before == InterlockedCompareExchange(&shared_->sequence, 0, 0)) {
|
||||
for (const auto& window : windows) {
|
||||
DWORD pid = 0;
|
||||
GetWindowThreadProcessId(reinterpret_cast<HWND>(window.hwnd), &pid);
|
||||
if (pid != process_id())
|
||||
return Failed("Invalid high-band window owner", error,
|
||||
ERROR_INVALID_HANDLE);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return Failed("High-band monitor snapshot is changing or invalid", error,
|
||||
ERROR_RETRY);
|
||||
}
|
||||
|
||||
bool PrivacyBandGuard::Stop(std::string& error) {
|
||||
bool ok = true;
|
||||
if (process_) {
|
||||
if (stop_) SetEvent(stop_);
|
||||
if (WaitForSingleObject(process_, 1500) != WAIT_OBJECT_0) {
|
||||
// This handle came only from our CreateProcessW call, never discovery.
|
||||
if (!TerminateProcess(process_, ERROR_CANCELLED) ||
|
||||
WaitForSingleObject(process_, 1500) != WAIT_OBJECT_0)
|
||||
ok = Failed("Stop owned high-band broker", error);
|
||||
}
|
||||
if (!ok) return false;
|
||||
CloseHandle(process_);
|
||||
process_ = nullptr;
|
||||
}
|
||||
if (job_) CloseHandle(job_);
|
||||
job_ = nullptr;
|
||||
if (shared_) UnmapViewOfFile(shared_);
|
||||
shared_ = nullptr;
|
||||
for (HANDLE handle : {stop_, ready_, mapping_, image_lock_, dll_lock_})
|
||||
if (handle && handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
|
||||
stop_ = ready_ = mapping_ = image_lock_ = dll_lock_ = nullptr;
|
||||
if (!broker_path_.empty()) DeleteFileW(broker_path_.c_str());
|
||||
if (!broker_directory_.empty()) RemoveDirectoryW(broker_directory_.c_str());
|
||||
broker_path_.clear();
|
||||
broker_directory_.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_BAND_GUARD_H_
|
||||
#define _PRIVACY_BAND_GUARD_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "privacy_band_ipc.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
struct PrivacyScreenText;
|
||||
|
||||
// Lifecycle and snapshots are owned by the privacy control thread. The broker
|
||||
// owns all high-band HWND operations. This class never injects an existing
|
||||
// process and never terminates a process found by name or PID.
|
||||
class PrivacyBandGuard {
|
||||
public:
|
||||
~PrivacyBandGuard();
|
||||
static bool Available(std::string& error);
|
||||
bool Start(const PrivacyScreenText& text, std::string& error);
|
||||
bool Stop(std::string& error);
|
||||
bool Healthy(std::string& error);
|
||||
bool Windows(std::vector<PrivacyBandWindow>& windows, std::string& error);
|
||||
bool stopped() const { return !process_; }
|
||||
DWORD process_id() const { return process_ ? GetProcessId(process_) : 0; }
|
||||
|
||||
private:
|
||||
HANDLE process_ = nullptr;
|
||||
HANDLE job_ = nullptr;
|
||||
HANDLE stop_ = nullptr;
|
||||
HANDLE ready_ = nullptr;
|
||||
HANDLE mapping_ = nullptr;
|
||||
HANDLE image_lock_ = nullptr;
|
||||
HANDLE dll_lock_ = nullptr;
|
||||
PrivacyBandShared* shared_ = nullptr;
|
||||
std::filesystem::path broker_path_;
|
||||
std::filesystem::path broker_directory_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_BAND_GUARD_H_
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_BAND_IPC_H_
|
||||
#define _PRIVACY_BAND_IPC_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
constexpr uint32_t kPrivacyBandMagic = 0x43534231;
|
||||
constexpr uint32_t kPrivacyBandVersion = 2;
|
||||
constexpr DWORD kPrivacyWindowBand = 18; // ZBID_ABOVELOCK_UX, current desktop.
|
||||
constexpr size_t kPrivacyMaxMonitors = 64;
|
||||
constexpr wchar_t kPrivacyBandBootstrap[] = L"CROSSDESK_PRIVACY_BAND_BOOTSTRAP";
|
||||
constexpr wchar_t kPrivacyBandDll[] = L"crossdesk_privacy_window.dll";
|
||||
|
||||
struct PrivacyBandWindow {
|
||||
uint64_t hwnd = 0;
|
||||
RECT rect{};
|
||||
};
|
||||
|
||||
// Unnamed mapping and synchronization/process handles are inherited only by
|
||||
// the newly created broker. No global window-name/PID discovery or named IPC.
|
||||
struct PrivacyBandShared {
|
||||
uint32_t magic = kPrivacyBandMagic;
|
||||
uint32_t version = kPrivacyBandVersion;
|
||||
uint32_t size = sizeof(PrivacyBandShared);
|
||||
DWORD parent_pid = 0;
|
||||
DWORD broker_pid = 0;
|
||||
volatile LONG sequence = 0;
|
||||
volatile LONG error = ERROR_IO_PENDING;
|
||||
volatile LONG active = 0;
|
||||
alignas(8) volatile LONG64 heartbeat = 0;
|
||||
wchar_t operation[128]{};
|
||||
wchar_t unlock_hint[128]{};
|
||||
uint32_t count = 0;
|
||||
PrivacyBandWindow windows[kPrivacyMaxMonitors]{};
|
||||
};
|
||||
|
||||
using CreatePrivacyWindowInBand = HWND(WINAPI*)(DWORD, ATOM, LPCWSTR, DWORD,
|
||||
int, int, int, int, HWND, HMENU,
|
||||
HINSTANCE, LPVOID, DWORD);
|
||||
using GetPrivacyWindowBand = BOOL(WINAPI*)(HWND, DWORD*);
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_BAND_IPC_H_
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_CURSOR_API_H_
|
||||
#define _PRIVACY_CURSOR_API_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// A separate cursor plane can remain visible above a capture-excluded HWND.
|
||||
// Magnification's documented cursor API hides that plane across input queues;
|
||||
// it does not change cursor schemes, shapes, positions, focus or DPI awareness.
|
||||
class PrivacyCursorApi {
|
||||
public:
|
||||
PrivacyCursorApi() = default;
|
||||
PrivacyCursorApi(const PrivacyCursorApi&) = delete;
|
||||
PrivacyCursorApi& operator=(const PrivacyCursorApi&) = delete;
|
||||
~PrivacyCursorApi() { RestoreAndClose(); }
|
||||
bool Initialize() {
|
||||
module_ = LoadLibraryExW(L"Magnification.dll", nullptr,
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if (!module_) return false;
|
||||
const auto initialize = reinterpret_cast<InitializeFn>(
|
||||
GetProcAddress(module_, "MagInitialize"));
|
||||
uninitialize_ = reinterpret_cast<InitializeFn>(
|
||||
GetProcAddress(module_, "MagUninitialize"));
|
||||
show_ = reinterpret_cast<ShowFn>(
|
||||
GetProcAddress(module_, "MagShowSystemCursor"));
|
||||
if (!initialize || !uninitialize_ || !show_) {
|
||||
SetLastError(ERROR_PROC_NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
initialized_ = initialize() != FALSE;
|
||||
return initialized_;
|
||||
}
|
||||
bool Hide() { return initialized_ && show_(FALSE); }
|
||||
bool RestoreAndClose() {
|
||||
bool ok = true;
|
||||
if (initialized_) {
|
||||
ok = show_(TRUE) != FALSE;
|
||||
ok = (uninitialize_() != FALSE) && ok;
|
||||
initialized_ = false;
|
||||
}
|
||||
if (module_) {
|
||||
FreeLibrary(module_);
|
||||
module_ = nullptr;
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
private:
|
||||
using InitializeFn = BOOL(WINAPI*)();
|
||||
using ShowFn = BOOL(WINAPI*)(BOOL);
|
||||
HMODULE module_ = nullptr;
|
||||
InitializeFn uninitialize_ = nullptr;
|
||||
ShowFn show_ = nullptr;
|
||||
bool initialized_ = false;
|
||||
};
|
||||
|
||||
struct PrivacyCursorReady {
|
||||
volatile LONG error;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_CURSOR_API_H_
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include "privacy_cursor_guard.h"
|
||||
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
|
||||
#include "../screen_capturer/dxgi_cursor_state.h"
|
||||
#include "privacy_cursor_api.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
struct Handle {
|
||||
HANDLE value = nullptr;
|
||||
~Handle() {
|
||||
if (value) CloseHandle(value);
|
||||
}
|
||||
};
|
||||
bool Failed(const char* operation, std::string& error,
|
||||
DWORD code = GetLastError()) {
|
||||
error = std::string(operation) + " failed (Windows error " +
|
||||
std::to_string(code) + ")";
|
||||
LOG_ERROR("Privacy cursor: {}", error);
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
PrivacyCursorGuard::~PrivacyCursorGuard() {
|
||||
std::string error;
|
||||
Stop(error);
|
||||
// The inherited parent handle still lets a slow helper restore on exit.
|
||||
if (process_) CloseHandle(process_);
|
||||
if (stop_event_) CloseHandle(stop_event_);
|
||||
}
|
||||
|
||||
bool PrivacyCursorGuard::Start(std::string& error) {
|
||||
if (process_ || restore_pending_)
|
||||
return Failed("Cursor guard already active", error, ERROR_BUSY);
|
||||
helper_failure_reported_ = false;
|
||||
std::vector<wchar_t> module(32768);
|
||||
const DWORD count = GetModuleFileNameW(nullptr, module.data(),
|
||||
static_cast<DWORD>(module.size()));
|
||||
if (!count || count >= module.size())
|
||||
return Failed("GetModuleFileNameW", error);
|
||||
const auto helper = std::filesystem::path(module.data()).parent_path() /
|
||||
L"crossdesk_privacy_cursor_helper.exe";
|
||||
SECURITY_ATTRIBUTES security{sizeof(security), nullptr, TRUE};
|
||||
Handle parent;
|
||||
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(),
|
||||
GetCurrentProcess(), &parent.value, SYNCHRONIZE, TRUE,
|
||||
0))
|
||||
return Failed("Duplicate parent process handle", error);
|
||||
Handle stop{CreateEventW(&security, TRUE, FALSE, nullptr)};
|
||||
Handle ready{CreateEventW(&security, TRUE, FALSE, nullptr)};
|
||||
Handle mapping{CreateFileMappingW(INVALID_HANDLE_VALUE, &security,
|
||||
PAGE_READWRITE, 0,
|
||||
sizeof(PrivacyCursorReady), nullptr)};
|
||||
if (!stop.value || !ready.value || !mapping.value)
|
||||
return Failed("Create cursor guard IPC", error);
|
||||
auto shared = static_cast<PrivacyCursorReady*>(MapViewOfFile(
|
||||
mapping.value, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(PrivacyCursorReady)));
|
||||
if (!shared) return Failed("Map cursor guard readiness", error);
|
||||
InterlockedExchange(&shared->error, ERROR_IO_PENDING);
|
||||
|
||||
SIZE_T bytes = 0;
|
||||
InitializeProcThreadAttributeList(nullptr, 1, 0, &bytes);
|
||||
std::vector<unsigned char> attributes(bytes);
|
||||
STARTUPINFOEXW startup{};
|
||||
startup.StartupInfo.cb = sizeof(startup);
|
||||
startup.lpAttributeList =
|
||||
reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(attributes.data());
|
||||
if (!InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0,
|
||||
&bytes)) {
|
||||
const DWORD code = GetLastError();
|
||||
UnmapViewOfFile(shared);
|
||||
return Failed("Initialize cursor guard handle list", error, code);
|
||||
}
|
||||
HANDLE inherited[] = {parent.value, stop.value, ready.value, mapping.value};
|
||||
bool ok = UpdateProcThreadAttribute(
|
||||
startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherited, sizeof(inherited), nullptr, nullptr) != FALSE;
|
||||
PROCESS_INFORMATION child{};
|
||||
if (ok) {
|
||||
std::wstring command = L"\"" + helper.wstring() + L"\"";
|
||||
for (HANDLE handle : inherited)
|
||||
command += L" " + std::to_wstring(reinterpret_cast<uintptr_t>(handle));
|
||||
ok =
|
||||
CreateProcessW(helper.c_str(), command.data(), nullptr, nullptr, TRUE,
|
||||
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT |
|
||||
CREATE_BREAKAWAY_FROM_JOB,
|
||||
nullptr, nullptr, &startup.StartupInfo, &child) != FALSE;
|
||||
}
|
||||
const DWORD start_error = GetLastError();
|
||||
DeleteProcThreadAttributeList(startup.lpAttributeList);
|
||||
if (!ok) {
|
||||
UnmapViewOfFile(shared);
|
||||
return Failed("Start crossdesk_privacy_cursor_helper.exe", error,
|
||||
start_error);
|
||||
}
|
||||
CloseHandle(child.hThread);
|
||||
process_ = child.hProcess;
|
||||
stop_event_ = stop.value;
|
||||
stop.value = nullptr;
|
||||
// The helper may hide the pointer before signaling readiness. Track its
|
||||
// entire lifetime, including startup failure and delayed restoration.
|
||||
SharedDxgiCursorState().SetPrivacyCursorHidden(true);
|
||||
HANDLE startup_events[] = {ready.value, process_};
|
||||
const DWORD result = WaitForMultipleObjects(2, startup_events, FALSE, 2000);
|
||||
const DWORD ready_error =
|
||||
static_cast<DWORD>(InterlockedCompareExchange(&shared->error, 0, 0));
|
||||
UnmapViewOfFile(shared);
|
||||
if (result != WAIT_OBJECT_0 || ready_error != ERROR_SUCCESS) {
|
||||
std::string cleanup;
|
||||
Stop(cleanup);
|
||||
return Failed(
|
||||
"Hide system cursor", error,
|
||||
ready_error == ERROR_IO_PENDING ? ERROR_TIMEOUT : ready_error);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PrivacyCursorGuard::RestoreAfterFailure(std::string& error) {
|
||||
PrivacyCursorApi cursor;
|
||||
if (!cursor.Initialize() || !cursor.RestoreAndClose()) {
|
||||
restore_pending_ = true;
|
||||
return Failed("Restore system cursor after helper failure", error);
|
||||
}
|
||||
restore_pending_ = false;
|
||||
SharedDxgiCursorState().SetPrivacyCursorHidden(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PrivacyCursorGuard::Healthy(std::string& error) {
|
||||
if (process_ && WaitForSingleObject(process_, 0) == WAIT_TIMEOUT) return true;
|
||||
if (restore_pending_ || (process_ && !helper_failure_reported_))
|
||||
RestoreAfterFailure(error);
|
||||
helper_failure_reported_ = true;
|
||||
error = "System cursor helper exited; privacy screen will turn off";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PrivacyCursorGuard::Stop(std::string& error) {
|
||||
if (!process_) return !restore_pending_ || RestoreAfterFailure(error);
|
||||
if (!SetEvent(stop_event_)) return Failed("Stop cursor helper", error);
|
||||
if (WaitForSingleObject(process_, 2000) != WAIT_OBJECT_0) {
|
||||
return Failed("Wait for cursor helper restoration", error, ERROR_TIMEOUT);
|
||||
}
|
||||
DWORD code = ERROR_GEN_FAILURE;
|
||||
GetExitCodeProcess(process_, &code);
|
||||
CloseHandle(process_);
|
||||
process_ = nullptr;
|
||||
CloseHandle(stop_event_);
|
||||
stop_event_ = nullptr;
|
||||
if (code != ERROR_SUCCESS) return RestoreAfterFailure(error);
|
||||
SharedDxgiCursorState().SetPrivacyCursorHidden(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_CURSOR_GUARD_H_
|
||||
#define _PRIVACY_CURSOR_GUARD_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Called only on the privacy message thread. The child owns cursor suppression
|
||||
// and restores it when either this guard stops it or its parent process exits.
|
||||
class PrivacyCursorGuard {
|
||||
public:
|
||||
PrivacyCursorGuard() = default;
|
||||
PrivacyCursorGuard(const PrivacyCursorGuard&) = delete;
|
||||
PrivacyCursorGuard& operator=(const PrivacyCursorGuard&) = delete;
|
||||
~PrivacyCursorGuard();
|
||||
bool Start(std::string& error);
|
||||
bool Healthy(std::string& error);
|
||||
bool Stop(std::string& error);
|
||||
bool stopped() const { return !process_ && !restore_pending_; }
|
||||
|
||||
private:
|
||||
bool RestoreAfterFailure(std::string& error);
|
||||
HANDLE process_ = nullptr;
|
||||
HANDLE stop_event_ = nullptr;
|
||||
bool restore_pending_ = false;
|
||||
bool helper_failure_reported_ = false;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_CURSOR_GUARD_H_
|
||||
@@ -0,0 +1,304 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include "privacy_input_guard.h"
|
||||
|
||||
#include "rd_log.h"
|
||||
#include "windows_input_marker.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
PrivacyInputGuard::~PrivacyInputGuard() { Stop(); }
|
||||
|
||||
void PrivacyInputGuard::Fault(const std::string& operation, DWORD code) {
|
||||
{
|
||||
std::lock_guard lock(error_mutex_);
|
||||
error_ = operation + " (Windows error " + std::to_string(code) + ")";
|
||||
LOG_ERROR("Privacy input: {}", error_);
|
||||
}
|
||||
healthy_.store(false);
|
||||
// Wake the owner's message loop; recovery is never performed in a hook.
|
||||
PostMessageW(owner_, WM_NULL, 0, 0);
|
||||
}
|
||||
|
||||
bool PrivacyInputGuard::Start(HWND owner, UINT exit_message,
|
||||
std::string& error) {
|
||||
if (thread_.joinable()) {
|
||||
error = "Privacy input thread is already running";
|
||||
return false;
|
||||
}
|
||||
owner_ = owner;
|
||||
exit_message_ = exit_message;
|
||||
healthy_.store(false);
|
||||
{
|
||||
std::lock_guard lock(error_mutex_);
|
||||
error_.clear();
|
||||
}
|
||||
stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
ready_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
if (!stop_ || !ready_) {
|
||||
Fault("Create privacy input events failed", GetLastError());
|
||||
Healthy(error);
|
||||
Stop();
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
thread_ = std::thread([this] { Run(); });
|
||||
} catch (const std::exception& e) {
|
||||
error = std::string("Start privacy input thread failed: ") + e.what();
|
||||
Stop();
|
||||
return false;
|
||||
}
|
||||
if (WaitForSingleObject(ready_, 2000) != WAIT_OBJECT_0) {
|
||||
error = "Privacy input thread startup timed out";
|
||||
Stop();
|
||||
return false;
|
||||
}
|
||||
if (!Healthy(error)) {
|
||||
Stop();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void PrivacyInputGuard::Stop() {
|
||||
if (stop_) SetEvent(stop_);
|
||||
if (thread_.joinable()) thread_.join();
|
||||
if (stop_) CloseHandle(stop_);
|
||||
if (ready_) CloseHandle(ready_);
|
||||
stop_ = ready_ = nullptr;
|
||||
owner_ = nullptr;
|
||||
}
|
||||
|
||||
bool PrivacyInputGuard::Healthy(std::string& error) const {
|
||||
if (healthy_.load() && running_.load() &&
|
||||
GetTickCount64() - last_pump_.load() < 1500)
|
||||
return true;
|
||||
std::lock_guard lock(error_mutex_);
|
||||
error = error_.empty() ? "Privacy input message thread stopped responding"
|
||||
: error_;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PrivacyInputGuard::Renew(HHOOK& hook, int kind, HOOKPROC procedure) {
|
||||
HHOOK replacement =
|
||||
SetWindowsHookExW(kind, procedure, GetModuleHandleW(nullptr), 0);
|
||||
if (!replacement) {
|
||||
Fault("Renew privacy input hook failed", GetLastError());
|
||||
return false;
|
||||
}
|
||||
HHOOK previous = hook;
|
||||
hook = replacement;
|
||||
if (UnhookWindowsHookEx(previous)) return true;
|
||||
const DWORD code = GetLastError();
|
||||
if (code != ERROR_INVALID_HOOK_HANDLE) retired_.push_back(previous);
|
||||
Fault("Privacy input hook was lost or could not be retired", code);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PrivacyInputGuard::PumpMessages() {
|
||||
MSG message{};
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
if (message.message == WM_QUIT) return false;
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
last_pump_.store(GetTickCount64());
|
||||
return WaitForSingleObject(stop_, 0) == WAIT_TIMEOUT;
|
||||
}
|
||||
|
||||
bool PrivacyInputGuard::ReleasePressedInputs() {
|
||||
// Both hooks must already be installed: otherwise a new local press can
|
||||
// slip between this snapshot and the transition to blocked input.
|
||||
std::array<bool, 256> pressed{};
|
||||
for (int key = 1; key < 256; ++key)
|
||||
pressed[key] = (GetAsyncKeyState(key) & 0x8000) != 0;
|
||||
// Keep held modifiers available to the physical emergency-exit chord.
|
||||
// Our injected releases intentionally do not clear this hook-side state.
|
||||
physical_keys_ = pressed;
|
||||
|
||||
std::vector<INPUT> releases;
|
||||
for (int key = 1; key < 256; ++key) {
|
||||
if (!pressed[key]) continue;
|
||||
// Generic modifier VKs alias their left/right variants. Release each
|
||||
// side once; use the generic VK only if Windows reports no specific side.
|
||||
if ((key == VK_SHIFT && (pressed[VK_LSHIFT] || pressed[VK_RSHIFT])) ||
|
||||
(key == VK_CONTROL && (pressed[VK_LCONTROL] || pressed[VK_RCONTROL])) ||
|
||||
(key == VK_MENU && (pressed[VK_LMENU] || pressed[VK_RMENU])))
|
||||
continue;
|
||||
INPUT input{};
|
||||
input.type = INPUT_MOUSE;
|
||||
input.mi.dwExtraInfo = kInjectedMouseInputMarker;
|
||||
switch (key) {
|
||||
// GetAsyncKeyState reports physical mouse buttons, as do these flags,
|
||||
// including when Windows swaps the primary and secondary buttons.
|
||||
case VK_LBUTTON:
|
||||
input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
|
||||
break;
|
||||
case VK_RBUTTON:
|
||||
input.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
|
||||
break;
|
||||
case VK_MBUTTON:
|
||||
input.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
|
||||
break;
|
||||
case VK_XBUTTON1:
|
||||
case VK_XBUTTON2:
|
||||
input.mi.dwFlags = MOUSEEVENTF_XUP;
|
||||
input.mi.mouseData = key == VK_XBUTTON1 ? XBUTTON1 : XBUTTON2;
|
||||
break;
|
||||
default: {
|
||||
input = {};
|
||||
input.type = INPUT_KEYBOARD;
|
||||
input.ki.wVk = static_cast<WORD>(key);
|
||||
const UINT scan = MapVirtualKeyW(key, MAPVK_VK_TO_VSC_EX);
|
||||
input.ki.wScan = static_cast<WORD>(scan & 0xff);
|
||||
input.ki.dwFlags = KEYEVENTF_KEYUP;
|
||||
if ((scan & 0xff00) == 0xe000)
|
||||
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
|
||||
input.ki.dwExtraInfo = kInjectedKeyboardInputMarker;
|
||||
break;
|
||||
}
|
||||
}
|
||||
LOG_INFO("Privacy input handoff: releasing held input vk=0x{:02X}", key);
|
||||
releases.push_back(input);
|
||||
}
|
||||
if (!releases.empty()) {
|
||||
const UINT count = static_cast<UINT>(releases.size());
|
||||
SetLastError(ERROR_SUCCESS);
|
||||
const UINT sent = SendInput(count, releases.data(), sizeof(INPUT));
|
||||
if (sent != count) {
|
||||
Fault("Release held privacy inputs failed (sent " + std::to_string(sent) +
|
||||
"/" + std::to_string(count) + ")",
|
||||
GetLastError());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// SendInput acknowledges insertion, not delivery. Pump this hook thread
|
||||
// until the tagged releases have passed through and Windows reports no
|
||||
// pressed inputs. The caller cannot publish input_blocked/ready earlier.
|
||||
const auto deadline = GetTickCount64() + 1000;
|
||||
for (;;) {
|
||||
if (!PumpMessages()) {
|
||||
Fault("Privacy input handoff cancelled", ERROR_CANCELLED);
|
||||
return false;
|
||||
}
|
||||
int held = 0;
|
||||
for (int key = 1; key < 256; ++key) {
|
||||
if (GetAsyncKeyState(key) & 0x8000) {
|
||||
held = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!held) {
|
||||
LOG_INFO("Privacy input handoff complete: released {} held inputs",
|
||||
releases.size());
|
||||
return true;
|
||||
}
|
||||
if (GetTickCount64() >= deadline) {
|
||||
Fault("Privacy input release timed out, still pressed vk=" +
|
||||
std::to_string(held),
|
||||
ERROR_TIMEOUT);
|
||||
return false;
|
||||
}
|
||||
if (MsgWaitForMultipleObjectsEx(1, &stop_, 10, QS_ALLINPUT,
|
||||
MWMO_INPUTAVAILABLE) == WAIT_FAILED) {
|
||||
Fault("Wait for privacy input releases failed", GetLastError());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PrivacyInputGuard::Run() {
|
||||
current_ = this;
|
||||
running_.store(true);
|
||||
try {
|
||||
keyboard_ = SetWindowsHookExW(WH_KEYBOARD_LL, KeyboardHook,
|
||||
GetModuleHandleW(nullptr), 0);
|
||||
if (!keyboard_)
|
||||
Fault("Install privacy keyboard hook failed", GetLastError());
|
||||
if (keyboard_) {
|
||||
mouse_ =
|
||||
SetWindowsHookExW(WH_MOUSE_LL, MouseHook, GetModuleHandleW(nullptr), 0);
|
||||
if (!mouse_) Fault("Install privacy mouse hook failed", GetLastError());
|
||||
}
|
||||
healthy_.store(keyboard_ && mouse_ && ReleasePressedInputs());
|
||||
last_pump_.store(GetTickCount64());
|
||||
SetEvent(ready_);
|
||||
auto last_refresh = GetTickCount64();
|
||||
LOG_INFO("Privacy input message thread started: thread={}",
|
||||
GetCurrentThreadId());
|
||||
while (keyboard_ && mouse_ &&
|
||||
WaitForSingleObject(stop_, 0) == WAIT_TIMEOUT) {
|
||||
if (!PumpMessages()) break;
|
||||
const auto now = GetTickCount64();
|
||||
if (healthy_.load() && now - last_refresh >= 1000) {
|
||||
last_refresh = now;
|
||||
// Install replacements before retiring old hooks, with no input gap.
|
||||
if (Renew(keyboard_, WH_KEYBOARD_LL, KeyboardHook))
|
||||
Renew(mouse_, WH_MOUSE_LL, MouseHook);
|
||||
}
|
||||
if (MsgWaitForMultipleObjectsEx(1, &stop_, 100, QS_ALLINPUT,
|
||||
MWMO_INPUTAVAILABLE) == WAIT_FAILED) {
|
||||
Fault("Wait for privacy input messages failed", GetLastError());
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Fault(std::string("Privacy input thread failed: ") + e.what(),
|
||||
ERROR_GEN_FAILURE);
|
||||
SetEvent(ready_);
|
||||
}
|
||||
healthy_.store(false);
|
||||
auto unhook = [this](HHOOK hook) {
|
||||
if (hook && !UnhookWindowsHookEx(hook) &&
|
||||
GetLastError() != ERROR_INVALID_HOOK_HANDLE)
|
||||
Fault("Release privacy input hook failed", GetLastError());
|
||||
};
|
||||
unhook(keyboard_);
|
||||
unhook(mouse_);
|
||||
for (auto hook : retired_) unhook(hook);
|
||||
keyboard_ = mouse_ = nullptr;
|
||||
retired_.clear();
|
||||
physical_keys_.fill(false);
|
||||
current_ = nullptr;
|
||||
running_.store(false);
|
||||
PostMessageW(owner_, WM_NULL, 0, 0);
|
||||
// Windows also removes hooks installed by a thread when that thread exits.
|
||||
LOG_INFO("Privacy input message thread stopped");
|
||||
}
|
||||
|
||||
LRESULT CALLBACK PrivacyInputGuard::KeyboardHook(int code, WPARAM wp,
|
||||
LPARAM lp) {
|
||||
auto self = current_;
|
||||
if (code < 0 || !self) return CallNextHookEx(nullptr, code, wp, lp);
|
||||
const auto& key = *reinterpret_cast<KBDLLHOOKSTRUCT*>(lp);
|
||||
if ((key.flags & LLKHF_INJECTED) &&
|
||||
key.dwExtraInfo == kInjectedKeyboardInputMarker)
|
||||
return CallNextHookEx(nullptr, code, wp, lp);
|
||||
if (!(key.flags & LLKHF_INJECTED) && key.vkCode < 256) {
|
||||
self->physical_keys_[key.vkCode] = !(key.flags & LLKHF_UP);
|
||||
const auto& keys = self->physical_keys_;
|
||||
if (key.vkCode == VK_F12 && !(key.flags & LLKHF_UP) &&
|
||||
(keys[VK_LCONTROL] || keys[VK_RCONTROL]) &&
|
||||
(keys[VK_LMENU] || keys[VK_RMENU]) &&
|
||||
(keys[VK_LSHIFT] || keys[VK_RSHIFT]))
|
||||
PostMessageW(self->owner_, self->exit_message_, 0, 0);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK PrivacyInputGuard::MouseHook(int code, WPARAM wp, LPARAM lp) {
|
||||
auto self = current_;
|
||||
if (code < 0 || !self) return CallNextHookEx(nullptr, code, wp, lp);
|
||||
const auto& mouse = *reinterpret_cast<MSLLHOOKSTRUCT*>(lp);
|
||||
if ((mouse.flags & LLMHF_INJECTED) &&
|
||||
mouse.dwExtraInfo == kInjectedMouseInputMarker)
|
||||
return CallNextHookEx(nullptr, code, wp, lp);
|
||||
return 1;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-10
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_INPUT_GUARD_H_
|
||||
#define _PRIVACY_INPUT_GUARD_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// The owner controls lifecycle; the dedicated message thread owns LL hooks.
|
||||
// Rendering and session queries never run on this thread.
|
||||
class PrivacyInputGuard {
|
||||
public:
|
||||
~PrivacyInputGuard();
|
||||
bool Start(HWND owner, UINT exit_message, std::string& error);
|
||||
void Stop();
|
||||
bool Healthy(std::string& error) const;
|
||||
bool stopped() const { return !thread_.joinable(); }
|
||||
|
||||
private:
|
||||
void Run();
|
||||
bool ReleasePressedInputs();
|
||||
bool PumpMessages();
|
||||
void Fault(const std::string& operation, DWORD code);
|
||||
bool Renew(HHOOK& hook, int kind, HOOKPROC procedure);
|
||||
static LRESULT CALLBACK KeyboardHook(int code, WPARAM wp, LPARAM lp);
|
||||
static LRESULT CALLBACK MouseHook(int code, WPARAM wp, LPARAM lp);
|
||||
|
||||
std::thread thread_;
|
||||
HANDLE stop_ = nullptr;
|
||||
HANDLE ready_ = nullptr;
|
||||
HWND owner_ = nullptr;
|
||||
UINT exit_message_ = 0;
|
||||
std::atomic<bool> healthy_{false};
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<ULONGLONG> last_pump_{0};
|
||||
mutable std::mutex error_mutex_;
|
||||
std::string error_;
|
||||
HHOOK keyboard_ = nullptr;
|
||||
HHOOK mouse_ = nullptr;
|
||||
std::vector<HHOOK> retired_;
|
||||
std::array<bool, 256> physical_keys_{};
|
||||
inline static thread_local PrivacyInputGuard* current_ = nullptr;
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_INPUT_GUARD_H_
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-11
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PRIVACY_WINDOW_VISIBILITY_H_
|
||||
#define _PRIVACY_WINDOW_VISIBILITY_H_
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Called for a visible foreign window whose full bounds intersect a cover.
|
||||
// Inspect it on every check: an OSD helper can grow into a content window.
|
||||
inline bool IsNonObstructingPrivacyWindow(HWND window, const RECT& bounds) {
|
||||
const auto styles = GetWindowLongPtrW(window, GWL_EXSTYLE);
|
||||
if (!(styles & WS_EX_LAYERED)) return false;
|
||||
|
||||
BYTE alpha = 0;
|
||||
DWORD flags = 0;
|
||||
// WS_EX_TRANSPARENT alone does not imply invisible pixels. Likewise,
|
||||
// UpdateLayeredWindow windows can reject this query; failure proves nothing.
|
||||
if (GetLayeredWindowAttributes(window, nullptr, &alpha, &flags) &&
|
||||
(flags & LWA_ALPHA) && alpha == 0)
|
||||
return true;
|
||||
|
||||
constexpr LONG_PTR helper_styles =
|
||||
WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_TRANSPARENT;
|
||||
const auto width = static_cast<int64_t>(bounds.right) - bounds.left;
|
||||
const auto height = static_cast<int64_t>(bounds.bottom) - bounds.top;
|
||||
// Single-pixel, nonactivating OSD placeholders cannot display meaningful
|
||||
// desktop content. Use the whole window, never its clipped intersection;
|
||||
// larger OSDs and windows with unknown opacity still require coverage checks.
|
||||
return (styles & helper_styles) == helper_styles && width == 1 && height == 1;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // _PRIVACY_WINDOW_VISIBILITY_H_
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-16
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CAPTURED_CURSOR_STATE_H_
|
||||
#define _CAPTURED_CURSOR_STATE_H_
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// Metadata belongs to the frame callback, not to the requested capture mode.
|
||||
// WGC's DLL adapter copies its frame metadata into this executable-local scope.
|
||||
inline thread_local bool current_frame_has_cursor = false;
|
||||
|
||||
class CapturedCursorFrameScope {
|
||||
public:
|
||||
explicit CapturedCursorFrameScope(bool embedded)
|
||||
: previous_(current_frame_has_cursor) {
|
||||
current_frame_has_cursor = embedded;
|
||||
}
|
||||
~CapturedCursorFrameScope() { current_frame_has_cursor = previous_; }
|
||||
CapturedCursorFrameScope(const CapturedCursorFrameScope&) = delete;
|
||||
CapturedCursorFrameScope& operator=(const CapturedCursorFrameScope&) = delete;
|
||||
|
||||
private:
|
||||
bool previous_;
|
||||
};
|
||||
|
||||
class CapturedCursorState {
|
||||
public:
|
||||
void Update(bool embedded, void* monitor) {
|
||||
embedded_monitor_.store(embedded ? monitor : nullptr,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
void Reset() { Update(false, nullptr); }
|
||||
bool IsEmbedded(void* monitor) const {
|
||||
return monitor && embedded_monitor_.load(std::memory_order_relaxed) == monitor;
|
||||
}
|
||||
|
||||
private:
|
||||
// This opaque handle is the entire state; no other data needs publishing.
|
||||
std::atomic<void*> embedded_monitor_{nullptr};
|
||||
};
|
||||
|
||||
inline CapturedCursorState& SharedCapturedCursorState() {
|
||||
static CapturedCursorState state;
|
||||
return state;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-16
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CURSOR_DRAW_H_
|
||||
#define _CURSOR_DRAW_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// ptScreenPos is the input hotspot; DrawIconEx expects the bitmap's top-left.
|
||||
// Return true only if a cursor intersects the captured rectangle and was drawn.
|
||||
inline bool DrawCursorInCapture(HDC dc, const CURSORINFO& cursor, int left,
|
||||
int top, int width, int height) {
|
||||
if (!(cursor.flags & CURSOR_SHOWING) || !cursor.hCursor) return false;
|
||||
struct CursorIconInfo : ICONINFO {
|
||||
CursorIconInfo() : ICONINFO{} {}
|
||||
~CursorIconInfo() {
|
||||
if (hbmColor) DeleteObject(hbmColor);
|
||||
if (hbmMask) DeleteObject(hbmMask);
|
||||
}
|
||||
} icon;
|
||||
if (!GetIconInfo(cursor.hCursor, &icon)) return false;
|
||||
BITMAP bitmap{};
|
||||
if (!GetObject(icon.hbmColor ? icon.hbmColor : icon.hbmMask, sizeof(bitmap),
|
||||
&bitmap))
|
||||
return false;
|
||||
const int cursor_width = bitmap.bmWidth;
|
||||
const int cursor_height =
|
||||
icon.hbmColor ? bitmap.bmHeight : bitmap.bmHeight / 2;
|
||||
const int64_t x =
|
||||
static_cast<int64_t>(cursor.ptScreenPos.x) - left - icon.xHotspot;
|
||||
const int64_t y =
|
||||
static_cast<int64_t>(cursor.ptScreenPos.y) - top - icon.yHotspot;
|
||||
if (x >= width || y >= height || x + cursor_width <= 0 ||
|
||||
y + cursor_height <= 0)
|
||||
return false;
|
||||
return DrawIconEx(dc, static_cast<int>(x), static_cast<int>(y),
|
||||
cursor.hCursor, 0, 0, 0, nullptr, DI_NORMAL) != FALSE;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,66 @@
|
||||
#ifndef CROSSDESK_DXGI_CURSOR_STATE_H_
|
||||
#define CROSSDESK_DXGI_CURSOR_STATE_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
// DXGI's Visible flag describes the separate hardware pointer, not the
|
||||
// system cursor. When it is false, a visible system cursor can already be
|
||||
// included in the desktop texture (for example, during window dragging).
|
||||
// Share that distinction with the GUI thread without changing cursor input
|
||||
// coordinates or the wire protocol.
|
||||
class DxgiCursorState {
|
||||
public:
|
||||
void Update(int64_t last_mouse_update_time, bool separate_pointer_visible,
|
||||
void* monitor) {
|
||||
// PointerPosition is undefined on desktop-only updates. Retain the last
|
||||
// pointer state until DXGI actually reports another pointer update.
|
||||
if (last_mouse_update_time == 0) return;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (privacy_cursor_hidden_) return;
|
||||
embedded_monitor_ = separate_pointer_visible ? nullptr : monitor;
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
embedded_monitor_ = nullptr;
|
||||
}
|
||||
|
||||
void SetPrivacyCursorHidden(bool hidden) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (privacy_cursor_hidden_ == hidden) return;
|
||||
privacy_cursor_hidden_ = hidden;
|
||||
// Pointer updates from before/during suppression cannot describe whether
|
||||
// the restored cursor is embedded. Wait for a fresh DXGI pointer update.
|
||||
embedded_monitor_ = nullptr;
|
||||
}
|
||||
|
||||
bool ShouldDrawCursor(bool system_cursor_visible, void* cursor_monitor) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// MagShowSystemCursor(FALSE) hides the local pointer plane without changing
|
||||
// CURSOR_SHOWING. DXGI Visible=false then means hidden, not embedded in the
|
||||
// captured frame. Keep sending the application's cursor to the controller.
|
||||
// CURSOR_SHOWING still takes precedence when the application hides it.
|
||||
if (privacy_cursor_hidden_) return system_cursor_visible;
|
||||
// A hidden cursor or a pointer on another monitor also makes DXGI report
|
||||
// Visible=false. Only suppress a visible cursor on the captured monitor.
|
||||
return system_cursor_visible &&
|
||||
(!cursor_monitor || embedded_monitor_ != cursor_monitor);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
void* embedded_monitor_ = nullptr;
|
||||
bool privacy_cursor_hidden_ = false;
|
||||
};
|
||||
|
||||
inline DxgiCursorState& SharedDxgiCursorState() {
|
||||
static DxgiCursorState state;
|
||||
return state;
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif // CROSSDESK_DXGI_CURSOR_STATE_H_
|
||||
@@ -1,11 +1,13 @@
|
||||
#include "screen_capturer_dxgi.h"
|
||||
|
||||
#include <display_stream_id.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include "dxgi_cursor_state.h"
|
||||
#include "libyuv.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
@@ -218,17 +220,20 @@ void ScreenCapturerDxgi::EnumerateDisplays() {
|
||||
mi.rcMonitor.left, mi.rcMonitor.top,
|
||||
mi.rcMonitor.right, mi.rcMonitor.bottom);
|
||||
// primary first
|
||||
if (is_primary)
|
||||
if (is_primary) {
|
||||
display_info_list_.insert(display_info_list_.begin(), info);
|
||||
else
|
||||
outputs_.insert(outputs_.begin(), output);
|
||||
} else {
|
||||
display_info_list_.push_back(info);
|
||||
outputs_.push_back(output);
|
||||
outputs_.push_back(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ScreenCapturerDxgi::CreateDuplicationForMonitor(int monitor_index) {
|
||||
SharedDxgiCursorState().Reset();
|
||||
if (monitor_index < 0 || monitor_index >= (int)outputs_.size()) return false;
|
||||
Microsoft::WRL::ComPtr<IDXGIOutput1> output1;
|
||||
HRESULT hr = outputs_[monitor_index]->QueryInterface(
|
||||
@@ -246,6 +251,11 @@ bool ScreenCapturerDxgi::CreateDuplicationForMonitor(int monitor_index) {
|
||||
}
|
||||
|
||||
staging_.Reset();
|
||||
DXGI_OUTDUPL_DESC desc{};
|
||||
duplication_->GetDesc(&desc);
|
||||
rotation_ = desc.Rotation;
|
||||
LOG_INFO("DXGI: duplication ready, monitor={}, rotation={}", monitor_index,
|
||||
static_cast<int>(rotation_));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -276,6 +286,8 @@ bool ScreenCapturerDxgi::RecreateDuplicationForCurrentMonitor() {
|
||||
}
|
||||
|
||||
void ScreenCapturerDxgi::ReleaseDuplication() {
|
||||
SharedDxgiCursorState().Reset();
|
||||
++duplication_generation_;
|
||||
staging_.Reset();
|
||||
if (duplication_) {
|
||||
duplication_->ReleaseFrame();
|
||||
@@ -284,16 +296,27 @@ void ScreenCapturerDxgi::ReleaseDuplication() {
|
||||
}
|
||||
|
||||
void ScreenCapturerDxgi::CaptureLoop() {
|
||||
const int timeout_ms = 33;
|
||||
const int timeout_ms = (std::max)(1, 1000 / (std::max)(1, fps_));
|
||||
bool cached_frame_valid = false;
|
||||
int cached_monitor = -1;
|
||||
uint64_t cached_generation = 0;
|
||||
std::vector<uint8_t> rotated_frame;
|
||||
auto last_duplication_retry =
|
||||
std::chrono::steady_clock::now() - std::chrono::milliseconds(1000);
|
||||
while (running_) {
|
||||
if (paused_) {
|
||||
cached_frame_valid = false;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Duplication/staging textures belong to one monitor. Do not release or
|
||||
// replace them in SwitchTo while AcquireNextFrame/Map is using them.
|
||||
std::unique_lock capture_lock(switch_mutex_);
|
||||
if (paused_ || !running_) continue;
|
||||
if (!duplication_) {
|
||||
cached_frame_valid = false;
|
||||
capture_lock.unlock();
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now - last_duplication_retry >= std::chrono::milliseconds(500)) {
|
||||
last_duplication_retry = now;
|
||||
@@ -303,19 +326,44 @@ void ScreenCapturerDxgi::CaptureLoop() {
|
||||
continue;
|
||||
}
|
||||
|
||||
const int frame_monitor = monitor_index_.load();
|
||||
DXGI_OUTDUPL_FRAME_INFO frame_info{};
|
||||
Microsoft::WRL::ComPtr<IDXGIResource> desktop_resource;
|
||||
HRESULT hr = duplication_->AcquireNextFrame(
|
||||
timeout_ms, &frame_info, desktop_resource.GetAddressOf());
|
||||
if (hr == DXGI_ERROR_WAIT_TIMEOUT) {
|
||||
// DXGI explicitly reports an unchanged desktop. Re-emit only a frame
|
||||
// successfully acquired for this monitor to keep delivering static frames.
|
||||
if (cached_frame_valid && cached_generation == duplication_generation_ &&
|
||||
cached_monitor == monitor_index_.load() && callback_ && nv12_frame_) {
|
||||
const auto stream_id = MakeDisplayStreamId(cached_monitor);
|
||||
capture_lock.unlock();
|
||||
callback_(nv12_frame_, nv12_width_ * nv12_height_ * 3 / 2, nv12_width_,
|
||||
nv12_height_, stream_id.c_str(), nullptr);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Never replay a cached image after an acquisition/conversion failure or
|
||||
// a backend rebuild. Normal error/reset handling releases optional privacy.
|
||||
cached_frame_valid = false;
|
||||
if (FAILED(hr)) {
|
||||
SharedDxgiCursorState().Reset();
|
||||
LOG_ERROR("DXGI: AcquireNextFrame failed, hr={}", (int)hr);
|
||||
capture_lock.unlock();
|
||||
if (callback_)
|
||||
callback_(nullptr, ScreenCapturer::kBackendReset, 0, 0, "", nullptr);
|
||||
RecreateDuplicationForCurrentMonitor();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (frame_monitor >= 0 &&
|
||||
frame_monitor < static_cast<int>(display_info_list_.size())) {
|
||||
SharedDxgiCursorState().Update(
|
||||
frame_info.LastMouseUpdateTime.QuadPart,
|
||||
frame_info.PointerPosition.Visible != FALSE,
|
||||
display_info_list_[frame_monitor].handle);
|
||||
}
|
||||
|
||||
Microsoft::WRL::ComPtr<ID3D11Texture2D> acquired_tex;
|
||||
if (desktop_resource) {
|
||||
hr = desktop_resource->QueryInterface(
|
||||
@@ -356,9 +404,42 @@ void ScreenCapturerDxgi::CaptureLoop() {
|
||||
continue;
|
||||
}
|
||||
|
||||
auto pixels = static_cast<const uint8_t*>(mapped.pData);
|
||||
int stride = static_cast<int>(mapped.RowPitch);
|
||||
int logical_width = static_cast<int>(src_desc.Width);
|
||||
int logical_height = static_cast<int>(src_desc.Height);
|
||||
libyuv::RotationMode rotation = libyuv::kRotate0;
|
||||
switch (rotation_) {
|
||||
case DXGI_MODE_ROTATION_ROTATE90:
|
||||
rotation = libyuv::kRotate90;
|
||||
break;
|
||||
case DXGI_MODE_ROTATION_ROTATE180:
|
||||
rotation = libyuv::kRotate180;
|
||||
break;
|
||||
case DXGI_MODE_ROTATION_ROTATE270:
|
||||
rotation = libyuv::kRotate270;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (rotation != libyuv::kRotate0) {
|
||||
const bool swap_axes = rotation != libyuv::kRotate180;
|
||||
const int rotated_width = swap_axes ? logical_height : logical_width;
|
||||
rotated_frame.resize(static_cast<size_t>(logical_width) * logical_height *
|
||||
4);
|
||||
if (libyuv::ARGBRotate(pixels, stride, rotated_frame.data(),
|
||||
rotated_width * 4, logical_width, logical_height,
|
||||
rotation) != 0) {
|
||||
d3d_context_->Unmap(staging_.Get(), 0);
|
||||
duplication_->ReleaseFrame();
|
||||
continue;
|
||||
}
|
||||
pixels = rotated_frame.data();
|
||||
stride = rotated_width * 4;
|
||||
if (swap_axes) std::swap(logical_width, logical_height);
|
||||
}
|
||||
int even_width = logical_width & ~1;
|
||||
int even_height = static_cast<int>(src_desc.Height) & ~1;
|
||||
int even_height = logical_height & ~1;
|
||||
if (even_width <= 0 || even_height <= 0) {
|
||||
d3d_context_->Unmap(staging_.Get(), 0);
|
||||
duplication_->ReleaseFrame();
|
||||
@@ -374,25 +455,29 @@ void ScreenCapturerDxgi::CaptureLoop() {
|
||||
nv12_height_ = even_height;
|
||||
}
|
||||
|
||||
libyuv::ARGBToNV12(static_cast<const uint8_t*>(mapped.pData),
|
||||
static_cast<int>(mapped.RowPitch), nv12_frame_,
|
||||
even_width, nv12_frame_ + even_width * even_height,
|
||||
even_width, even_width, even_height);
|
||||
const int converted =
|
||||
libyuv::ARGBToNV12(pixels, stride, nv12_frame_, even_width,
|
||||
nv12_frame_ + even_width * even_height, even_width,
|
||||
even_width, even_height);
|
||||
|
||||
if (callback_) {
|
||||
int idx = monitor_index_.load();
|
||||
cached_generation = duplication_generation_;
|
||||
d3d_context_->Unmap(staging_.Get(), 0);
|
||||
duplication_->ReleaseFrame();
|
||||
capture_lock.unlock();
|
||||
|
||||
if (converted == 0 && frame_monitor == monitor_index_.load() && callback_) {
|
||||
int idx = frame_monitor;
|
||||
if (idx >= 0 && idx < static_cast<int>(display_info_list_.size())) {
|
||||
const std::string stream_id = MakeDisplayStreamId(idx);
|
||||
callback_(nv12_frame_, nv12_size, even_width, even_height,
|
||||
stream_id.c_str(), nullptr);
|
||||
cached_monitor = idx;
|
||||
cached_frame_valid = true;
|
||||
} else {
|
||||
LOG_ERROR("DXGI: CaptureLoop invalid monitor_index {} (list size {})",
|
||||
idx, display_info_list_.size());
|
||||
}
|
||||
}
|
||||
|
||||
d3d_context_->Unmap(staging_.Get(), 0);
|
||||
duplication_->ReleaseFrame();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,8 @@ class ScreenCapturerDxgi : public ScreenCapturer {
|
||||
Microsoft::WRL::ComPtr<ID3D11DeviceContext> d3d_context_;
|
||||
Microsoft::WRL::ComPtr<IDXGIOutputDuplication> duplication_;
|
||||
Microsoft::WRL::ComPtr<ID3D11Texture2D> staging_;
|
||||
DXGI_MODE_ROTATION rotation_ = DXGI_MODE_ROTATION_IDENTITY;
|
||||
uint64_t duplication_generation_ = 0;
|
||||
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> paused_{false};
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
#include <vector>
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include "captured_cursor_state.h"
|
||||
#include "cursor_draw.h"
|
||||
#include "libyuv.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
@@ -184,18 +186,15 @@ void ScreenCapturerGdi::CaptureLoop() {
|
||||
BitBlt(mem_dc, 0, 0, width, height, screen_dc, left, top,
|
||||
SRCCOPY | CAPTUREBLT);
|
||||
|
||||
bool cursor_embedded = false;
|
||||
if (show_cursor_) {
|
||||
CURSORINFO ci{};
|
||||
ci.cbSize = sizeof(CURSORINFO);
|
||||
if (GetCursorInfo(&ci) && ci.flags == CURSOR_SHOWING && ci.hCursor) {
|
||||
POINT pt = ci.ptScreenPos;
|
||||
int cx = pt.x - left;
|
||||
int cy = pt.y - top;
|
||||
if (cx >= -64 && cy >= -64 && cx < width + 64 && cy < height + 64) {
|
||||
DrawIconEx(mem_dc, cx, cy, ci.hCursor, 0, 0, 0, nullptr, DI_NORMAL);
|
||||
}
|
||||
if (GetCursorInfo(&ci)) {
|
||||
cursor_embedded = DrawCursorInCapture(mem_dc, ci, left, top, width, height);
|
||||
}
|
||||
}
|
||||
GdiFlush();
|
||||
|
||||
int stride_argb = width * 4;
|
||||
int nv12_size = width * height * 3 / 2;
|
||||
@@ -211,6 +210,7 @@ void ScreenCapturerGdi::CaptureLoop() {
|
||||
width, height);
|
||||
|
||||
if (callback_) {
|
||||
CapturedCursorFrameScope cursor_scope(cursor_embedded);
|
||||
const std::string stream_id = MakeDisplayStreamId(idx);
|
||||
callback_(nv12_frame_, nv12_size, width, height, stream_id.c_str(),
|
||||
nullptr);
|
||||
|
||||
@@ -31,6 +31,9 @@ class ScreenCapturerGdi : public ScreenCapturer {
|
||||
int Destroy() override;
|
||||
int Start(bool show_cursor) override;
|
||||
int Stop() override;
|
||||
void SetCursorCapture(bool enabled) {
|
||||
show_cursor_.store(enabled, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int Pause(int monitor_index) override;
|
||||
int Resume(int monitor_index) override;
|
||||
@@ -65,4 +68,4 @@ class ScreenCapturerGdi : public ScreenCapturer {
|
||||
};
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <iostream>
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include "captured_cursor_state.h"
|
||||
#include "libyuv.h"
|
||||
#include "rd_log.h"
|
||||
|
||||
@@ -72,6 +73,16 @@ HMONITOR GetPrimaryMonitor() {
|
||||
|
||||
ScreenCapturerWgc::ScreenCapturerWgc() : monitor_(nullptr) {}
|
||||
|
||||
int ScreenCapturerWgc::SetCursorCapture(bool enabled) {
|
||||
int result = 0;
|
||||
for (auto& session : sessions_) {
|
||||
if (!session.inited_ || !session.running_) continue;
|
||||
const int ret = session.session_->Start(enabled);
|
||||
if (ret != 0) result = ret;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ScreenCapturerWgc::~ScreenCapturerWgc() {
|
||||
Stop();
|
||||
CleanUp();
|
||||
@@ -351,6 +362,10 @@ int ScreenCapturerWgc::ResetToInitialMonitor() {
|
||||
}
|
||||
void ScreenCapturerWgc::OnFrame(const WgcSession::wgc_session_frame& frame,
|
||||
int id) {
|
||||
if (!frame.data && frame.width == 0 && frame.height == 0) {
|
||||
if (on_data_) on_data_(nullptr, ScreenCapturer::kBackendReset, 0, 0, "", nullptr);
|
||||
return;
|
||||
}
|
||||
if (!running_ || !on_data_) {
|
||||
return;
|
||||
}
|
||||
@@ -405,6 +420,7 @@ void ScreenCapturerWgc::OnFrame(const WgcSession::wgc_session_frame& frame,
|
||||
even_width, even_width, even_height);
|
||||
|
||||
const std::string stream_id = MakeDisplayStreamId(id);
|
||||
CapturedCursorFrameScope cursor_scope(frame.cursor_captured);
|
||||
on_data_(nv12_frame_, nv12_size, even_width, even_height,
|
||||
stream_id.c_str(), nullptr);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ class ScreenCapturerWgc : public ScreenCapturer,
|
||||
int Destroy() override;
|
||||
int Start(bool show_cursor) override;
|
||||
int Stop() override;
|
||||
int SetCursorCapture(bool enabled);
|
||||
|
||||
int Pause(int monitor_index) override;
|
||||
int Resume(int monitor_index) override;
|
||||
|
||||
@@ -16,11 +16,14 @@
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include "captured_nv12_frame.h"
|
||||
#include "captured_cursor_state.h"
|
||||
#include "dxgi_cursor_state.h"
|
||||
#include "interactive_state.h"
|
||||
#include "named_pipe_deadline.h"
|
||||
#include "rd_log.h"
|
||||
#include "screen_capturer_dxgi.h"
|
||||
#include "screen_capturer_gdi.h"
|
||||
#include "secure_desktop_cursor_state.h"
|
||||
#include "secure_desktop_frame_schedule.h"
|
||||
#include "secure_desktop_status_poller.h"
|
||||
#include "service_host.h"
|
||||
@@ -33,6 +36,8 @@ namespace {
|
||||
|
||||
using Json = nlohmann::json;
|
||||
|
||||
thread_local bool current_frame_from_secure_desktop = false;
|
||||
|
||||
constexpr DWORD kSecureDesktopStatusIntervalMs = 250;
|
||||
constexpr DWORD kSecureDesktopStatusPipeTimeoutMs = 500;
|
||||
constexpr DWORD kSecureDesktopHelperPipeTimeoutMs = 120;
|
||||
@@ -48,6 +53,8 @@ class WgcPluginCapturer final : public ScreenCapturer {
|
||||
public:
|
||||
using CreateFn = ScreenCapturer* (*)();
|
||||
using DestroyFn = void (*)(ScreenCapturer*);
|
||||
using SetCursorFn = decltype(&CrossDeskSetWgcCursorCapture);
|
||||
using FrameCursorFn = decltype(&CrossDeskWgcFrameCapturesCursor);
|
||||
|
||||
static std::unique_ptr<ScreenCapturer> Create() {
|
||||
std::filesystem::path plugin_path;
|
||||
@@ -95,12 +102,38 @@ class WgcPluginCapturer final : public ScreenCapturer {
|
||||
}
|
||||
|
||||
int Init(const int fps, cb_desktop_data cb) override {
|
||||
return impl_ ? impl_->Init(fps, std::move(cb)) : -1;
|
||||
if (!impl_) return -1;
|
||||
return impl_->Init(fps, [this, cb = std::move(cb)](
|
||||
unsigned char* data, int size, int width, int height,
|
||||
const char* stream_id, const MiniRtcNativeVideoFrame* native_frame) {
|
||||
bool embedded = false;
|
||||
if (frame_cursor_fn_) {
|
||||
embedded = frame_cursor_fn_();
|
||||
} else if (legacy_capture_cursor_.load(std::memory_order_relaxed)) {
|
||||
CURSORINFO info{};
|
||||
info.cbSize = sizeof(info);
|
||||
embedded = GetCursorInfo(&info) && (info.flags & CURSOR_SHOWING) != 0;
|
||||
}
|
||||
// The plugin has its own globals. Bridge only this callback's metadata
|
||||
// into the executable before the wrapper accepts/publishes the frame.
|
||||
CapturedCursorFrameScope cursor_scope(embedded);
|
||||
cb(data, size, width, height, stream_id, native_frame);
|
||||
});
|
||||
}
|
||||
int Destroy() override { return impl_ ? impl_->Destroy() : 0; }
|
||||
int Start(bool show_cursor) override {
|
||||
if (!frame_cursor_fn_) {
|
||||
legacy_capture_cursor_.store(show_cursor, std::memory_order_relaxed);
|
||||
}
|
||||
return impl_ ? impl_->Start(show_cursor) : -1;
|
||||
}
|
||||
int SetCursorCapture(bool enabled) {
|
||||
if (!impl_) return -1;
|
||||
if (set_cursor_fn_) return set_cursor_fn_(impl_, enabled);
|
||||
// Older plugins only apply the cursor setting at startup.
|
||||
const int ret = impl_->Stop();
|
||||
return ret == 0 ? Start(enabled) : ret;
|
||||
}
|
||||
int Stop() override { return impl_ ? impl_->Stop() : 0; }
|
||||
int Pause(int monitor_index) override {
|
||||
return impl_ ? impl_->Pause(monitor_index) : -1;
|
||||
@@ -120,13 +153,30 @@ class WgcPluginCapturer final : public ScreenCapturer {
|
||||
|
||||
private:
|
||||
WgcPluginCapturer(HMODULE module, ScreenCapturer* impl, DestroyFn destroy_fn)
|
||||
: module_(module), impl_(impl), destroy_fn_(destroy_fn) {}
|
||||
: module_(module), impl_(impl), destroy_fn_(destroy_fn) {
|
||||
set_cursor_fn_ = reinterpret_cast<SetCursorFn>(
|
||||
GetProcAddress(module, "CrossDeskSetWgcCursorCapture"));
|
||||
frame_cursor_fn_ = reinterpret_cast<FrameCursorFn>(
|
||||
GetProcAddress(module, "CrossDeskWgcFrameCapturesCursor"));
|
||||
// Use the legacy restart path unless both parts of the extension exist.
|
||||
if (!frame_cursor_fn_) set_cursor_fn_ = nullptr;
|
||||
}
|
||||
|
||||
HMODULE module_ = nullptr;
|
||||
ScreenCapturer* impl_ = nullptr;
|
||||
DestroyFn destroy_fn_ = nullptr;
|
||||
SetCursorFn set_cursor_fn_ = nullptr;
|
||||
FrameCursorFn frame_cursor_fn_ = nullptr;
|
||||
std::atomic<bool> legacy_capture_cursor_{false};
|
||||
};
|
||||
|
||||
const char* CaptureBackendName(const ScreenCapturer* capturer) {
|
||||
if (dynamic_cast<const ScreenCapturerDxgi*>(capturer)) return "DXGI";
|
||||
if (dynamic_cast<const WgcPluginCapturer*>(capturer)) return "WGC";
|
||||
if (dynamic_cast<const ScreenCapturerGdi*>(capturer)) return "GDI";
|
||||
return "unavailable";
|
||||
}
|
||||
|
||||
std::string BuildSecureCaptureCommand(int left, int top, int width, int height,
|
||||
bool show_cursor,
|
||||
const std::string& stage,
|
||||
@@ -215,6 +265,7 @@ bool ParseSecureDesktopFrameResponse(const std::vector<uint8_t>& response,
|
||||
*width_out = static_cast<int>(header.width);
|
||||
*height_out = static_cast<int>(header.height);
|
||||
nv12_frame_out->assign(response.begin() + sizeof(header), response.end());
|
||||
SharedSecureDesktopCursorState().Update(header.cursor);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -330,7 +381,13 @@ bool QuerySecureDesktopHelperFrame(
|
||||
ScreenCapturerWin::ScreenCapturerWin() {}
|
||||
ScreenCapturerWin::~ScreenCapturerWin() { Destroy(); }
|
||||
|
||||
void ScreenCapturerWin::NotifyPrivacyCapture(bool running) {
|
||||
if (privacy_)
|
||||
privacy_->CaptureChanged(running);
|
||||
}
|
||||
|
||||
int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
|
||||
NotifyPrivacyCapture(false);
|
||||
fps_ = fps;
|
||||
cb_orig_ = cb;
|
||||
native_output_logged_.store(false, std::memory_order_relaxed);
|
||||
@@ -344,12 +401,20 @@ int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
|
||||
cb_ = [this](unsigned char* data, int size, int w, int h,
|
||||
const char* reported_stream_id,
|
||||
const MiniRtcNativeVideoFrame* native_frame) {
|
||||
if (size == ScreenCapturer::kBackendReset) {
|
||||
SharedCapturedCursorState().Reset();
|
||||
if (privacy_) privacy_->Fail("Capture restarted; privacy screen will turn off");
|
||||
return;
|
||||
}
|
||||
if (secure_desktop_capture_active_.load(std::memory_order_relaxed)) {
|
||||
SharedDxgiCursorState().Reset();
|
||||
SharedCapturedCursorState().Reset();
|
||||
return;
|
||||
}
|
||||
|
||||
const char* raw_stream_id = reported_stream_id ? reported_stream_id : "";
|
||||
std::string mapped_stream_id;
|
||||
void* frame_monitor = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(alias_mutex_);
|
||||
auto it = stream_id_alias_.find(raw_stream_id);
|
||||
@@ -363,6 +428,17 @@ int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
|
||||
mapped_stream_id = ResolveDisplayStreamId(
|
||||
mapped_stream_id.c_str(), canonical_displays_.size(),
|
||||
monitor_index_.load(std::memory_order_relaxed));
|
||||
if (current_frame_has_cursor) {
|
||||
for (size_t index = 0; index < canonical_displays_.size(); ++index) {
|
||||
if (mapped_stream_id == MakeDisplayStreamId(index)) {
|
||||
frame_monitor = canonical_displays_[index].handle;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (privacy_ && privacy_->Engaged() && !IsWindowsPrivacyDesktopAvailable()) {
|
||||
privacy_->Fail("Secure or unavailable desktop; privacy screen will turn off");
|
||||
}
|
||||
if (mapped_stream_id.empty()) {
|
||||
if (!invalid_stream_id_logged_.exchange(true,
|
||||
@@ -374,6 +450,7 @@ int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
|
||||
return;
|
||||
}
|
||||
invalid_stream_id_logged_.store(false, std::memory_order_relaxed);
|
||||
SharedCapturedCursorState().Update(current_frame_has_cursor, frame_monitor);
|
||||
if (post_secure_desktop_waiting_for_frame_.exchange(
|
||||
false, std::memory_order_relaxed)) {
|
||||
const ULONGLONG start_tick =
|
||||
@@ -393,50 +470,34 @@ int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
|
||||
native_frame);
|
||||
};
|
||||
|
||||
impl_.reset();
|
||||
int ret = -1;
|
||||
|
||||
impl_ = WgcPluginCapturer::Create();
|
||||
impl_is_wgc_plugin_ = (impl_ != nullptr);
|
||||
ret = impl_ ? impl_->Init(fps_, cb_) : -1;
|
||||
if (ret == 0) {
|
||||
LOG_INFO("Windows capturer: using WGC plugin");
|
||||
auto try_init = [&](std::unique_ptr<ScreenCapturer> candidate) {
|
||||
ret = candidate ? candidate->Init(fps_, cb_) : -1;
|
||||
if (ret != 0) {
|
||||
LOG_WARN("Windows capturer: {} init failed (ret={})",
|
||||
CaptureBackendName(candidate.get()), ret);
|
||||
return false;
|
||||
}
|
||||
impl_ = std::move(candidate);
|
||||
return true;
|
||||
};
|
||||
// Short-circuiting also keeps the unused WGC plugin unloaded.
|
||||
if ((IsBackendEnabled(ScreenCaptureMethod::Dxgi) &&
|
||||
try_init(std::make_unique<ScreenCapturerDxgi>())) ||
|
||||
(IsBackendEnabled(ScreenCaptureMethod::Wgc) &&
|
||||
try_init(WgcPluginCapturer::Create())) ||
|
||||
(IsBackendEnabled(ScreenCaptureMethod::Gdi) &&
|
||||
try_init(std::make_unique<ScreenCapturerGdi>()))) {
|
||||
LOG_INFO("Windows capturer: using {}", CaptureBackendName(impl_.get()));
|
||||
BuildCanonicalFromImpl();
|
||||
monitor_index_.store(0, std::memory_order_relaxed);
|
||||
initial_monitor_index_ = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
LOG_WARN("Windows capturer: WGC plugin init failed (ret={}), try DXGI", ret);
|
||||
impl_.reset();
|
||||
impl_is_wgc_plugin_ = false;
|
||||
|
||||
impl_ = std::make_unique<ScreenCapturerDxgi>();
|
||||
impl_is_wgc_plugin_ = false;
|
||||
ret = impl_->Init(fps_, cb_);
|
||||
if (ret == 0) {
|
||||
LOG_INFO("Windows capturer: using DXGI Desktop Duplication");
|
||||
BuildCanonicalFromImpl();
|
||||
monitor_index_.store(0, std::memory_order_relaxed);
|
||||
initial_monitor_index_ = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
LOG_WARN("Windows capturer: DXGI init failed (ret={}), fallback to GDI", ret);
|
||||
impl_.reset();
|
||||
|
||||
impl_ = std::make_unique<ScreenCapturerGdi>();
|
||||
impl_is_wgc_plugin_ = false;
|
||||
ret = impl_->Init(fps_, cb_);
|
||||
if (ret == 0) {
|
||||
LOG_INFO("Windows capturer: using GDI BitBlt");
|
||||
BuildCanonicalFromImpl();
|
||||
monitor_index_.store(0, std::memory_order_relaxed);
|
||||
initial_monitor_index_ = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
LOG_ERROR("Windows capturer: all implementations failed, ret={}", ret);
|
||||
impl_.reset();
|
||||
LOG_ERROR("Windows capturer: selected capture method {} failed, ret={}",
|
||||
static_cast<int>(capture_method_), ret);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -446,7 +507,6 @@ int ScreenCapturerWin::Destroy() {
|
||||
if (impl_) {
|
||||
impl_->Destroy();
|
||||
impl_.reset();
|
||||
impl_is_wgc_plugin_ = false;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(alias_mutex_);
|
||||
@@ -457,13 +517,37 @@ int ScreenCapturerWin::Destroy() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ScreenCapturerWin::CurrentFrameIsFromSecureDesktop() {
|
||||
return current_frame_from_secure_desktop;
|
||||
}
|
||||
|
||||
void ScreenCapturerWin::EmitCapturedFrame(
|
||||
unsigned char* data, int size, int width, int height,
|
||||
const char* stream_id, const MiniRtcNativeVideoFrame* native_frame) {
|
||||
const char* stream_id, const MiniRtcNativeVideoFrame* native_frame,
|
||||
bool from_secure_desktop) {
|
||||
// Helper frames do not use DXGI's pointer plane. Do not carry normal-desktop
|
||||
// cursor suppression into the lock screen or UAC desktop.
|
||||
if (from_secure_desktop) {
|
||||
SharedDxgiCursorState().Reset();
|
||||
SharedCapturedCursorState().Reset();
|
||||
}
|
||||
// Secure-desktop capture takes priority; remove privacy without dropping
|
||||
// the helper frame or delaying the remote session.
|
||||
if (from_secure_desktop && privacy_ && privacy_->Engaged()) {
|
||||
privacy_->Fail("Secure desktop helper frame arrived; privacy screen will turn off");
|
||||
}
|
||||
if (!cb_orig_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Normal and helper callbacks can originate on different threads during
|
||||
// desktop transitions. Keep diagnostics tied to this callback's source.
|
||||
struct RestoreFrameSource {
|
||||
bool previous;
|
||||
~RestoreFrameSource() { current_frame_from_secure_desktop = previous; }
|
||||
} restore_source{
|
||||
std::exchange(current_frame_from_secure_desktop, from_secure_desktop)};
|
||||
|
||||
if (native_frame) {
|
||||
if (!native_output_logged_.exchange(true, std::memory_order_relaxed)) {
|
||||
LOG_INFO("Windows capturer native frame output enabled (type={})",
|
||||
@@ -499,13 +583,49 @@ void ScreenCapturerWin::EmitCapturedFrame(
|
||||
owned_frame->Release();
|
||||
}
|
||||
|
||||
void ScreenCapturerWin::RestoreMonitor(int monitor_index) {
|
||||
RebuildAliasesFromImpl();
|
||||
if (monitor_index > 0 && impl_->SwitchTo(monitor_index) != 0) {
|
||||
monitor_index_.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
bool ScreenCapturerWin::TryStartBackend(
|
||||
std::unique_ptr<ScreenCapturer> candidate, int monitor_index) {
|
||||
if (!candidate) {
|
||||
LOG_WARN("Windows capturer: WGC plugin unavailable");
|
||||
return false;
|
||||
}
|
||||
const char* name = CaptureBackendName(candidate.get());
|
||||
const bool show_cursor = show_cursor_.load(std::memory_order_relaxed);
|
||||
int ret = candidate->Init(fps_, cb_);
|
||||
if (ret == 0)
|
||||
ret = candidate->Start(show_cursor);
|
||||
if (ret != 0) {
|
||||
LOG_WARN("Windows capturer: {} initialization/start failed (ret={})", name,
|
||||
ret);
|
||||
candidate->Destroy();
|
||||
return false;
|
||||
}
|
||||
// Commit only after the replacement is running. Failed candidates release
|
||||
// their resources without replacing the current backend.
|
||||
impl_ = std::move(candidate);
|
||||
applied_show_cursor_ = show_cursor;
|
||||
RestoreMonitor(monitor_index);
|
||||
LOG_INFO("Windows capturer: started {}", name);
|
||||
return true;
|
||||
}
|
||||
|
||||
int ScreenCapturerWin::Start(bool show_cursor) {
|
||||
if (!impl_) return -1;
|
||||
if (running_.load(std::memory_order_relaxed)) {
|
||||
return 0;
|
||||
}
|
||||
NotifyPrivacyCapture(false);
|
||||
|
||||
show_cursor_.store(show_cursor, std::memory_order_relaxed);
|
||||
applied_show_cursor_ = show_cursor;
|
||||
SharedCapturedCursorState().Reset();
|
||||
paused_.store(false, std::memory_order_relaxed);
|
||||
invalid_stream_id_logged_.store(false, std::memory_order_relaxed);
|
||||
|
||||
@@ -525,40 +645,23 @@ int ScreenCapturerWin::Start(bool show_cursor) {
|
||||
}
|
||||
}
|
||||
if (ret != 0) {
|
||||
if (capture_method_ != ScreenCaptureMethod::Auto) {
|
||||
LOG_ERROR("Windows capturer: selected backend {} failed to start (ret={})",
|
||||
CaptureBackendName(impl_.get()), ret);
|
||||
return ret;
|
||||
}
|
||||
LOG_WARN("Windows capturer: refresh/start failed (ret={}), trying fallback",
|
||||
ret);
|
||||
|
||||
auto try_init_start = [&](std::unique_ptr<ScreenCapturer> cand) -> bool {
|
||||
int r = cand->Init(fps_, cb_);
|
||||
if (r != 0) return false;
|
||||
int s = cand->Start(show_cursor);
|
||||
if (s == 0) {
|
||||
impl_ = std::move(cand);
|
||||
impl_is_wgc_plugin_ = false;
|
||||
RebuildAliasesFromImpl();
|
||||
if (requested_monitor > 0 &&
|
||||
impl_->SwitchTo(requested_monitor) != 0) {
|
||||
monitor_index_.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
bool fallback_started = false;
|
||||
if (impl_is_wgc_plugin_) {
|
||||
if (try_init_start(std::make_unique<ScreenCapturerDxgi>())) {
|
||||
LOG_INFO("Windows capturer: fallback to DXGI");
|
||||
fallback_started = true;
|
||||
} else if (try_init_start(std::make_unique<ScreenCapturerGdi>())) {
|
||||
LOG_INFO("Windows capturer: fallback to GDI");
|
||||
fallback_started = true;
|
||||
}
|
||||
} else if (dynamic_cast<ScreenCapturerDxgi*>(impl_.get())) {
|
||||
if (try_init_start(std::make_unique<ScreenCapturerGdi>())) {
|
||||
LOG_INFO("Windows capturer: fallback to GDI");
|
||||
fallback_started = true;
|
||||
}
|
||||
if (dynamic_cast<ScreenCapturerDxgi*>(impl_.get()) &&
|
||||
TryStartBackend(WgcPluginCapturer::Create(), requested_monitor)) {
|
||||
fallback_started = true;
|
||||
}
|
||||
if (!fallback_started && (dynamic_cast<WgcPluginCapturer*>(impl_.get()) ||
|
||||
dynamic_cast<ScreenCapturerDxgi*>(impl_.get()))) {
|
||||
fallback_started = TryStartBackend(std::make_unique<ScreenCapturerGdi>(),
|
||||
requested_monitor);
|
||||
}
|
||||
|
||||
if (!fallback_started) {
|
||||
@@ -568,6 +671,8 @@ int ScreenCapturerWin::Start(bool show_cursor) {
|
||||
}
|
||||
|
||||
running_.store(true, std::memory_order_relaxed);
|
||||
NotifyPrivacyCapture(true);
|
||||
SharedSecureDesktopCursorState().SetActive(false);
|
||||
secure_desktop_capture_active_.store(false, std::memory_order_relaxed);
|
||||
post_secure_desktop_waiting_for_frame_.store(false,
|
||||
std::memory_order_relaxed);
|
||||
@@ -581,6 +686,7 @@ int ScreenCapturerWin::Start(bool show_cursor) {
|
||||
}
|
||||
|
||||
int ScreenCapturerWin::Stop() {
|
||||
NotifyPrivacyCapture(false);
|
||||
running_.store(false, std::memory_order_relaxed);
|
||||
secure_desktop_capture_active_.store(false, std::memory_order_relaxed);
|
||||
post_secure_desktop_waiting_for_frame_.store(false,
|
||||
@@ -588,10 +694,13 @@ int ScreenCapturerWin::Stop() {
|
||||
post_secure_desktop_drop_logged_.store(false, std::memory_order_relaxed);
|
||||
post_secure_desktop_started_tick_.store(0, std::memory_order_relaxed);
|
||||
int ret = 0;
|
||||
// Drain management operations before stopping/replacing their backend.
|
||||
StopSecureCaptureThread();
|
||||
if (impl_) {
|
||||
ret = impl_->Stop();
|
||||
}
|
||||
StopSecureCaptureThread();
|
||||
SharedCapturedCursorState().Reset();
|
||||
SharedSecureDesktopCursorState().SetActive(false);
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
return ret;
|
||||
}
|
||||
@@ -613,6 +722,8 @@ int ScreenCapturerWin::SwitchTo(int monitor_index) {
|
||||
const int ret = impl_->SwitchTo(monitor_index);
|
||||
if (ret == 0) {
|
||||
monitor_index_.store(monitor_index, std::memory_order_relaxed);
|
||||
} else if (privacy_) {
|
||||
privacy_->Fail("Display switch failed; privacy screen will turn off");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -735,53 +846,20 @@ void ScreenCapturerWin::StopSecureCaptureThread() {
|
||||
}
|
||||
|
||||
bool ScreenCapturerWin::RestartCaptureBackendAfterSecureDesktop() {
|
||||
NotifyPrivacyCapture(false);
|
||||
if (!impl_ || !running_.load(std::memory_order_relaxed)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool show_cursor = show_cursor_.load(std::memory_order_relaxed);
|
||||
const int current_monitor = monitor_index_.load(std::memory_order_relaxed);
|
||||
auto restore_monitor = [&]() {
|
||||
RebuildAliasesFromImpl();
|
||||
if (current_monitor > 0 && impl_->SwitchTo(current_monitor) != 0) {
|
||||
monitor_index_.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
};
|
||||
auto try_started_backend = [&](std::unique_ptr<ScreenCapturer> cand,
|
||||
const char* name,
|
||||
bool is_wgc_plugin) -> bool {
|
||||
if (!cand) {
|
||||
return false;
|
||||
}
|
||||
const int init_ret = cand->Init(fps_, cb_);
|
||||
if (init_ret != 0) {
|
||||
LOG_WARN("Windows capturer: {} init after secure desktop failed (ret={})",
|
||||
name, init_ret);
|
||||
return false;
|
||||
}
|
||||
const int start_ret = cand->Start(show_cursor);
|
||||
if (start_ret != 0) {
|
||||
LOG_WARN(
|
||||
"Windows capturer: {} start after secure desktop failed (ret={})",
|
||||
name, start_ret);
|
||||
cand->Destroy();
|
||||
return false;
|
||||
}
|
||||
if (impl_) {
|
||||
impl_->Destroy();
|
||||
}
|
||||
impl_ = std::move(cand);
|
||||
impl_is_wgc_plugin_ = is_wgc_plugin;
|
||||
restore_monitor();
|
||||
LOG_INFO("Windows capturer: restarted {} after secure desktop", name);
|
||||
return true;
|
||||
};
|
||||
|
||||
LOG_INFO("Windows capturer: restarting capture backend after secure desktop");
|
||||
impl_->Stop();
|
||||
int ret = impl_->Start(show_cursor);
|
||||
if (ret == 0) {
|
||||
restore_monitor();
|
||||
applied_show_cursor_ = show_cursor;
|
||||
RestoreMonitor(current_monitor);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -795,20 +873,17 @@ bool ScreenCapturerWin::RestartCaptureBackendAfterSecureDesktop() {
|
||||
ret = impl_->Start(show_cursor);
|
||||
}
|
||||
if (ret == 0) {
|
||||
restore_monitor();
|
||||
applied_show_cursor_ = show_cursor;
|
||||
RestoreMonitor(current_monitor);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (impl_is_wgc_plugin_ &&
|
||||
try_started_backend(WgcPluginCapturer::Create(), "WGC plugin", true)) {
|
||||
return true;
|
||||
}
|
||||
if (try_started_backend(std::make_unique<ScreenCapturerDxgi>(), "DXGI",
|
||||
false)) {
|
||||
return true;
|
||||
}
|
||||
if (try_started_backend(std::make_unique<ScreenCapturerGdi>(), "GDI",
|
||||
false)) {
|
||||
if ((IsBackendEnabled(ScreenCaptureMethod::Dxgi) &&
|
||||
TryStartBackend(std::make_unique<ScreenCapturerDxgi>(), current_monitor)) ||
|
||||
(IsBackendEnabled(ScreenCaptureMethod::Wgc) &&
|
||||
TryStartBackend(WgcPluginCapturer::Create(), current_monitor)) ||
|
||||
(IsBackendEnabled(ScreenCaptureMethod::Gdi) &&
|
||||
TryStartBackend(std::make_unique<ScreenCapturerGdi>(), current_monitor))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -821,6 +896,24 @@ bool ScreenCapturerWin::RestartCaptureBackendAfterSecureDesktop() {
|
||||
return false;
|
||||
}
|
||||
|
||||
void ScreenCapturerWin::ApplyCursorCaptureSetting() {
|
||||
const bool requested = show_cursor_.load(std::memory_order_relaxed);
|
||||
if (!impl_ || requested == applied_show_cursor_) return;
|
||||
int ret = 0;
|
||||
if (auto* gdi = dynamic_cast<ScreenCapturerGdi*>(impl_.get())) {
|
||||
gdi->SetCursorCapture(requested);
|
||||
} else if (auto* wgc = dynamic_cast<WgcPluginCapturer*>(impl_.get())) {
|
||||
ret = wgc->SetCursorCapture(requested);
|
||||
}
|
||||
if (ret == 0) {
|
||||
applied_show_cursor_ = requested;
|
||||
LOG_INFO("Windows capturer cursor capture updated: backend={}, enabled={}",
|
||||
CaptureBackendName(impl_.get()), requested);
|
||||
} else {
|
||||
LOG_WARN("Windows capturer cursor update failed, ret={}; will retry", ret);
|
||||
}
|
||||
}
|
||||
|
||||
bool ScreenCapturerWin::GetCurrentCaptureRegion(int* left, int* top, int* width,
|
||||
int* height,
|
||||
std::string* display_name) {
|
||||
@@ -1009,6 +1102,9 @@ bool ScreenCapturerWin::ReadSecureDesktopSharedFrame(
|
||||
}
|
||||
|
||||
nv12_frame_out->resize(payload_size);
|
||||
const SecureDesktopCursorSnapshot cursor = header->cursor;
|
||||
const int captured_width = static_cast<int>(header->width);
|
||||
const int captured_height = static_cast<int>(header->height);
|
||||
std::memcpy(nv12_frame_out->data(), secure_frame_view_ + sizeof(*header),
|
||||
payload_size);
|
||||
MemoryBarrier();
|
||||
@@ -1019,8 +1115,9 @@ bool ScreenCapturerWin::ReadSecureDesktopSharedFrame(
|
||||
return false;
|
||||
}
|
||||
|
||||
*width_out = static_cast<int>(header->width);
|
||||
*height_out = static_cast<int>(header->height);
|
||||
*width_out = captured_width;
|
||||
*height_out = captured_height;
|
||||
SharedSecureDesktopCursorState().Update(cursor);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1096,6 +1193,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
bool post_secure_restart_pending = false;
|
||||
ULONGLONG post_secure_restart_deadline_tick = 0;
|
||||
ULONGLONG last_post_secure_restart_tick = 0;
|
||||
ULONGLONG next_cursor_update_tick = 0;
|
||||
SecureDesktopServiceStatus status;
|
||||
SecureDesktopStatusPoller status_poller(
|
||||
QuerySecureDesktopServiceStatus,
|
||||
@@ -1121,8 +1219,26 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
max_status_ms = 0;
|
||||
};
|
||||
std::vector<uint8_t> secure_frame;
|
||||
ULONGLONG last_shared_error_tick = 0;
|
||||
auto report_shared_error = [&](const char* operation,
|
||||
const std::string& error) {
|
||||
const ULONGLONG now = GetTickCount64();
|
||||
if (last_shared_error_tick == 0 || now - last_shared_error_tick >= 5000) {
|
||||
LOG_WARN(
|
||||
"Windows capturer secure shared capture {} failed; using pipe "
|
||||
"fallback, stage='{}', session_id={}, error={}",
|
||||
operation, status.interactive_stage, status.active_session_id, error);
|
||||
last_shared_error_tick = now;
|
||||
}
|
||||
};
|
||||
|
||||
while (running_.load(std::memory_order_relaxed)) {
|
||||
// Privacy covers belong to the ordinary desktop. Drop privacy on a
|
||||
// secure desktop, while continuing the normal helper capture path.
|
||||
if (privacy_ && privacy_->Engaged()) {
|
||||
if (!IsWindowsPrivacyDesktopAvailable())
|
||||
privacy_->Fail("Secure desktop or lock screen; privacy screen will turn off. Privacy cannot cover Windows security UI.");
|
||||
}
|
||||
if (paused_.load(std::memory_order_relaxed)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
continue;
|
||||
@@ -1157,6 +1273,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
|
||||
secure_desktop_capture_active_.store(status.capture_active,
|
||||
std::memory_order_relaxed);
|
||||
SharedSecureDesktopCursorState().SetActive(status.capture_active);
|
||||
if (status.capture_active != previous.capture_active ||
|
||||
status.interactive_stage != previous.interactive_stage ||
|
||||
status.active_session_id != previous.active_session_id ||
|
||||
@@ -1214,6 +1331,10 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
!RestartCaptureBackendAfterSecureDesktop();
|
||||
}
|
||||
}
|
||||
if (!post_secure_restart_pending && now >= next_cursor_update_tick) {
|
||||
next_cursor_update_tick = now + 500;
|
||||
ApplyCursorCaptureSetting();
|
||||
}
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds(status.service_available ? 50 : 200));
|
||||
continue;
|
||||
@@ -1261,6 +1382,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
status.interactive_stage, status.interactive_desktop, show_cursor,
|
||||
shared_fps, &error_message);
|
||||
if (!shared_ready) {
|
||||
report_shared_error("start", error_message);
|
||||
frame_schedule.OnStartFailure(GetTickCount64());
|
||||
} else if (!was_started) {
|
||||
frame_schedule.Reset(GetTickCount64());
|
||||
@@ -1280,6 +1402,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
IsPendingSecureDesktopFrame(error_message);
|
||||
if (frame_pending) ++shared_waits;
|
||||
if (shared_ready && !frame_delivered && !frame_pending) {
|
||||
report_shared_error("read", error_message);
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
frame_schedule.OnStartFailure(GetTickCount64());
|
||||
}
|
||||
@@ -1295,7 +1418,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
if (frame_delivered && !secure_frame.empty()) {
|
||||
EmitCapturedFrame(secure_frame.data(),
|
||||
static_cast<int>(secure_frame.size()), captured_width,
|
||||
captured_height, display_name.c_str());
|
||||
captured_height, display_name.c_str(), nullptr, true);
|
||||
}
|
||||
|
||||
if (!frame_delivered && !frame_pending) {
|
||||
@@ -1343,6 +1466,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
report_stats(true);
|
||||
StopSecureDesktopSharedCapture(secure_shared_session_id_);
|
||||
secure_desktop_capture_active_.store(false, std::memory_order_relaxed);
|
||||
SharedSecureDesktopCursorState().SetActive(false);
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
#include <vector>
|
||||
|
||||
#include "screen_capturer.h"
|
||||
#include "screen_capture_method.h"
|
||||
#include "privacy_controller.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -35,6 +37,10 @@ class ScreenCapturerWin : public ScreenCapturer {
|
||||
int Destroy() override;
|
||||
int Start(bool show_cursor) override;
|
||||
int Stop() override;
|
||||
// Applied on the capture-management thread, including secure-desktop capture.
|
||||
void SetCursorCapture(bool enabled) {
|
||||
show_cursor_.store(enabled, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int Pause(int monitor_index) override;
|
||||
int Resume(int monitor_index) override;
|
||||
@@ -43,10 +49,22 @@ class ScreenCapturerWin : public ScreenCapturer {
|
||||
int ResetToInitialMonitor() override;
|
||||
|
||||
std::vector<DisplayInfo> GetDisplayInfoList() override;
|
||||
void SetPrivacyController(PrivacyController* privacy) override { privacy_ = privacy; }
|
||||
// Set before Init(), while capture is stopped.
|
||||
void SetCaptureMethod(ScreenCaptureMethod method) { capture_method_ = method; }
|
||||
// Query synchronously inside the frame callback, on the delivering thread.
|
||||
// This describes the actual frame, independently of service status polling.
|
||||
static bool CurrentFrameIsFromSecureDesktop();
|
||||
|
||||
private:
|
||||
std::unique_ptr<ScreenCapturer> impl_;
|
||||
bool impl_is_wgc_plugin_ = false;
|
||||
ScreenCaptureMethod capture_method_ = ScreenCaptureMethod::Auto;
|
||||
bool IsBackendEnabled(ScreenCaptureMethod method) const {
|
||||
return capture_method_ == ScreenCaptureMethod::Auto ||
|
||||
capture_method_ == method;
|
||||
}
|
||||
PrivacyController* privacy_ = nullptr;
|
||||
void NotifyPrivacyCapture(bool running);
|
||||
int fps_ = 60;
|
||||
cb_desktop_data cb_;
|
||||
cb_desktop_data cb_orig_;
|
||||
@@ -61,6 +79,7 @@ class ScreenCapturerWin : public ScreenCapturer {
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> paused_{false};
|
||||
std::atomic<bool> show_cursor_{true};
|
||||
bool applied_show_cursor_ = true;
|
||||
std::atomic<int> monitor_index_{0};
|
||||
int initial_monitor_index_ = 0;
|
||||
std::atomic<bool> secure_desktop_capture_active_{false};
|
||||
@@ -86,11 +105,16 @@ class ScreenCapturerWin : public ScreenCapturer {
|
||||
|
||||
void BuildCanonicalFromImpl();
|
||||
void RebuildAliasesFromImpl();
|
||||
void RestoreMonitor(int monitor_index);
|
||||
bool TryStartBackend(std::unique_ptr<ScreenCapturer> candidate,
|
||||
int monitor_index);
|
||||
void EmitCapturedFrame(unsigned char* data, int size, int width, int height,
|
||||
const char* stream_id,
|
||||
const MiniRtcNativeVideoFrame* native_frame = nullptr);
|
||||
const MiniRtcNativeVideoFrame* native_frame = nullptr,
|
||||
bool from_secure_desktop = false);
|
||||
void StopSecureCaptureThread();
|
||||
bool RestartCaptureBackendAfterSecureDesktop();
|
||||
void ApplyCursorCaptureSetting();
|
||||
void SecureDesktopCaptureLoop();
|
||||
bool GetCurrentCaptureRegion(int* left, int* top, int* width, int* height,
|
||||
std::string* display_name);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user