Compare commits

...

9 Commits

26 changed files with 976 additions and 195 deletions
+5 -5
View File
@@ -8,6 +8,8 @@ APP_VERSION="$1"
ARCHITECTURE="amd64"
MAINTAINER="Junkun Di <junkun.di@hotmail.com>"
DESCRIPTION="A simple cross-platform remote desktop client."
ALSA_RUNTIME_DEP="libasound2 | libasound2t64"
PORTAL_RUNTIME_RECOMMENDS="xdg-desktop-portal, xdg-desktop-portal-gtk | xdg-desktop-portal-kde | xdg-desktop-portal-wlr"
# Remove 'v' prefix from version for Debian package (Debian version must start with digit)
DEB_VERSION="${APP_VERSION#v}"
@@ -41,11 +43,9 @@ Maintainer: $MAINTAINER
Description: $DESCRIPTION
Depends: libc6 (>= 2.29), libstdc++6 (>= 9), libx11-6, libxcb1,
libxcb-randr0, libxcb-xtest0, libxcb-xinerama0, libxcb-shape0,
libxcb-xkb1, libxcb-xfixes0, libxv1, libxtst6, libasound2,
libsndio7.0, libxcb-shm0, libpulse0, libdrm2, libdbus-1-3,
libpipewire-0.3-0, xdg-desktop-portal,
xdg-desktop-portal-gtk | xdg-desktop-portal-kde | xdg-desktop-portal-wlr
Recommends: nvidia-cuda-toolkit
libxcb-xkb1, libxcb-xfixes0, libxv1, libxtst6, $ALSA_RUNTIME_DEP,
libsndio7.0, libxcb-shm0, libpulse0, libdrm2, libdbus-1-3
Recommends: $PORTAL_RUNTIME_RECOMMENDS, nvidia-cuda-toolkit
Priority: optional
Section: utils
EOF
+5 -4
View File
@@ -8,6 +8,8 @@ APP_VERSION="$1"
ARCHITECTURE="arm64"
MAINTAINER="Junkun Di <junkun.di@hotmail.com>"
DESCRIPTION="A simple cross-platform remote desktop client."
ALSA_RUNTIME_DEP="libasound2 | libasound2t64"
PORTAL_RUNTIME_RECOMMENDS="xdg-desktop-portal, xdg-desktop-portal-gtk | xdg-desktop-portal-kde | xdg-desktop-portal-wlr"
# Remove 'v' prefix from version for Debian package (Debian version must start with digit)
DEB_VERSION="${APP_VERSION#v}"
@@ -41,10 +43,9 @@ Maintainer: $MAINTAINER
Description: $DESCRIPTION
Depends: libc6 (>= 2.29), libstdc++6 (>= 9), libx11-6, libxcb1,
libxcb-randr0, libxcb-xtest0, libxcb-xinerama0, libxcb-shape0,
libxcb-xkb1, libxcb-xfixes0, libxv1, libxtst6, libasound2,
libsndio7.0, libxcb-shm0, libpulse0, libdrm2, libdbus-1-3,
libpipewire-0.3-0, xdg-desktop-portal,
xdg-desktop-portal-gtk | xdg-desktop-portal-kde | xdg-desktop-portal-wlr
libxcb-xkb1, libxcb-xfixes0, libxv1, libxtst6, $ALSA_RUNTIME_DEP,
libsndio7.0, libxcb-shm0, libpulse0, libdrm2, libdbus-1-3
Recommends: $PORTAL_RUNTIME_RECOMMENDS
Priority: optional
Section: utils
EOF
+1 -8
View File
@@ -195,14 +195,7 @@ Function RegisterInstalledService
Abort
${EndIf}
DetailPrint "Starting CrossDesk service"
ExecWait '"$INSTDIR\CrossDesk.exe" --service-start' $0
${If} $0 != 0
ExecWait '"$INSTDIR\CrossDesk.exe" --service-uninstall' $1
ExecWait '"$SYSDIR\sc.exe" delete ${PRODUCT_SERVICE_NAME}' $1
MessageBox MB_ICONSTOP|MB_OK "The CrossDesk service was registered but could not be started. The installation will be aborted."
Abort
${EndIf}
DetailPrint "CrossDesk service registered for on-demand start"
Return
+21 -3
View File
@@ -14,6 +14,7 @@
#ifdef _WIN32
#include <cstdio>
#include "service_host.h"
#endif
@@ -53,7 +54,8 @@ void PrintServiceCliUsage() {
<< " --service-uninstall Remove the installed Windows service\n"
<< " --service-start Start the Windows service\n"
<< " --service-stop Stop the Windows service\n"
<< " --service-sas Ask the service to send Secure Attention Sequence\n"
<< " --service-sas Ask the service to send Secure Attention "
"Sequence\n"
<< " --service-ping Ping the service over named pipe IPC\n"
<< " --service-status Query service runtime status\n"
<< " --service-help Show this help\n";
@@ -93,6 +95,19 @@ bool IsServiceCliCommand(const char* arg) {
std::strcmp(arg, "--service-help") == 0;
}
void TryStartManagedWindowsService() {
std::filesystem::path service_path = GetSiblingServiceExecutablePath();
if (service_path.empty() || !std::filesystem::exists(service_path)) {
return;
}
if (!crossdesk::IsCrossDeskServiceInstalled()) {
return;
}
crossdesk::StartCrossDeskService();
}
int HandleServiceCliCommand(const std::string& command) {
EnsureConsoleForCli();
@@ -120,8 +135,7 @@ int HandleServiceCliCommand(const std::string& command) {
if (command == "--service-uninstall") {
bool success = crossdesk::UninstallCrossDeskService();
std::cout << (success ? "uninstall ok" : "uninstall failed")
<< std::endl;
std::cout << (success ? "uninstall ok" : "uninstall failed") << std::endl;
return success ? 0 : 1;
}
@@ -182,6 +196,10 @@ int main(int argc, char* argv[]) {
return 0;
}
#ifdef _WIN32
TryStartManagedWindowsService();
#endif
bool enable_daemon = false;
auto path_manager = std::make_unique<crossdesk::PathManager>("CrossDesk");
if (path_manager) {
+15 -8
View File
@@ -7,9 +7,10 @@
#ifndef _DEVICE_CONTROLLER_H_
#define _DEVICE_CONTROLLER_H_
#include <cstring>
#include <stdio.h>
#include <cstdint>
#include <cstring>
#include <nlohmann/json.hpp>
#include <string>
@@ -49,6 +50,8 @@ typedef struct {
typedef struct {
size_t key_value;
uint32_t scan_code;
bool extended;
KeyFlag flag;
} Key;
@@ -103,7 +106,10 @@ struct RemoteAction {
{"x", a.m.x}, {"y", a.m.y}, {"s", a.m.s}, {"flag", a.m.flag}};
break;
case ControlType::keyboard:
j["keyboard"] = {{"key_value", a.k.key_value}, {"flag", a.k.flag}};
j["keyboard"] = {{"key_value", a.k.key_value},
{"scan_code", a.k.scan_code},
{"extended", a.k.extended},
{"flag", a.k.flag}};
break;
case ControlType::audio_capture:
j["audio_capture"] = a.a;
@@ -113,8 +119,7 @@ struct RemoteAction {
break;
case ControlType::service_status:
j["service_status"] = {{"available", a.ss.available},
{"interactive_stage",
a.ss.interactive_stage}};
{"interactive_stage", a.ss.interactive_stage}};
break;
case ControlType::service_command:
j["service_command"] = {{"flag", a.c.flag}};
@@ -152,6 +157,9 @@ struct RemoteAction {
break;
case ControlType::keyboard:
out.k.key_value = j.at("keyboard").at("key_value").get<size_t>();
out.k.scan_code =
j.at("keyboard").value("scan_code", static_cast<uint32_t>(0));
out.k.extended = j.at("keyboard").value("extended", false);
out.k.flag = (KeyFlag)j.at("keyboard").at("flag").get<int>();
break;
case ControlType::audio_capture:
@@ -167,8 +175,7 @@ struct RemoteAction {
service_status_json.value("interactive_stage", std::string());
std::strncpy(out.ss.interactive_stage, interactive_stage.c_str(),
sizeof(out.ss.interactive_stage) - 1);
out.ss.interactive_stage[sizeof(out.ss.interactive_stage) - 1] =
'\0';
out.ss.interactive_stage[sizeof(out.ss.interactive_stage) - 1] = '\0';
break;
}
case ControlType::service_command:
@@ -212,8 +219,8 @@ struct RemoteAction {
}
};
// int key_code, bool is_down
typedef void (*OnKeyAction)(int, bool, void*);
// int key_code, bool is_down, uint32_t scan_code, bool extended
typedef void (*OnKeyAction)(int, bool, uint32_t, bool, void*);
class DeviceController {
public:
@@ -6,6 +6,7 @@
#include "keyboard_converter.h"
#include "platform.h"
#include "rd_log.h"
#include "windows_key_metadata.h"
namespace crossdesk {
@@ -35,9 +36,12 @@ static int KeyboardEventHandler(Display* display, XEvent* event) {
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, g_user_ptr);
g_on_key_action(key_code, is_key_down, scan_code, extended, g_user_ptr);
}
}
return 0;
@@ -146,7 +150,10 @@ int KeyboardCapturer::Unhook() {
return 0;
}
int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down) {
int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code, bool extended) {
(void)scan_code;
(void)extended;
if (IsWaylandSession()) {
if (!use_wayland_portal_ && !wayland_init_attempted_) {
wayland_init_attempted_ = true;
@@ -154,12 +161,14 @@ int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down) {
use_wayland_portal_ = true;
LOG_INFO("Keyboard controller initialized with Wayland portal backend");
} else {
LOG_WARN("Wayland keyboard control init failed, falling back to X11/XTest backend");
LOG_WARN(
"Wayland keyboard control init failed, falling back to X11/XTest "
"backend");
}
}
if (use_wayland_portal_) {
return SendWaylandKeyboardCommand(key_code, is_down);
return SendWaylandKeyboardCommand(key_code, is_down, scan_code, extended);
}
}
@@ -32,12 +32,15 @@ class KeyboardCapturer : public DeviceController {
public:
virtual int Hook(OnKeyAction on_key_action, void* user_ptr);
virtual int Unhook();
virtual int SendKeyboardCommand(int key_code, bool is_down);
virtual int SendKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code = 0,
bool extended = false);
private:
bool InitWaylandPortal();
void CleanupWaylandPortal();
int SendWaylandKeyboardCommand(int key_code, bool is_down);
int SendWaylandKeyboardCommand(int key_code, bool is_down, uint32_t scan_code,
bool extended);
bool NotifyWaylandKeyboardKeysym(int keysym, uint32_t state);
bool NotifyWaylandKeyboardKeycode(int keycode, uint32_t state);
bool SendWaylandPortalVoidCall(const char* method_name,
@@ -575,8 +575,12 @@ void KeyboardCapturer::CleanupWaylandPortal() {
wayland_session_handle_.clear();
}
int KeyboardCapturer::SendWaylandKeyboardCommand(int key_code, bool is_down) {
int KeyboardCapturer::SendWaylandKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code,
bool extended) {
#if defined(CROSSDESK_HAS_WAYLAND_CAPTURER) && CROSSDESK_HAS_WAYLAND_CAPTURER
(void)scan_code;
(void)extended;
if (!dbus_connection_ || wayland_session_handle_.empty()) {
return -1;
}
@@ -613,6 +617,8 @@ int KeyboardCapturer::SendWaylandKeyboardCommand(int key_code, bool is_down) {
#else
(void)key_code;
(void)is_down;
(void)scan_code;
(void)extended;
return -1;
#endif
}
@@ -119,7 +119,7 @@ CGEventRef eventCallback(CGEventTapProxy proxy, CGEventType type,
CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode));
int vk_code = ResolveVkCodeFromMacEvent(event, key_code, is_key_down);
if (vk_code >= 0) {
g_on_key_action(vk_code, is_key_down, g_user_ptr);
g_on_key_action(vk_code, is_key_down, 0, false, g_user_ptr);
}
} else if (type == kCGEventFlagsChanged) {
CGEventFlags current_flags = CGEventGetFlags(event);
@@ -135,35 +135,40 @@ CGEventRef eventCallback(CGEventTapProxy proxy, CGEventType type,
bool caps_lock_state = (current_flags & kCGEventFlagMaskAlphaShift) != 0;
if (caps_lock_state != keyboard_capturer->caps_lock_flag_) {
keyboard_capturer->caps_lock_flag_ = caps_lock_state;
g_on_key_action(vk_code, keyboard_capturer->caps_lock_flag_, g_user_ptr);
g_on_key_action(vk_code, keyboard_capturer->caps_lock_flag_, 0, false,
g_user_ptr);
}
// shift
bool shift_state = (current_flags & kCGEventFlagMaskShift) != 0;
if (shift_state != keyboard_capturer->shift_flag_) {
keyboard_capturer->shift_flag_ = shift_state;
g_on_key_action(vk_code, keyboard_capturer->shift_flag_, g_user_ptr);
g_on_key_action(vk_code, keyboard_capturer->shift_flag_, 0, false,
g_user_ptr);
}
// control
bool control_state = (current_flags & kCGEventFlagMaskControl) != 0;
if (control_state != keyboard_capturer->control_flag_) {
keyboard_capturer->control_flag_ = control_state;
g_on_key_action(vk_code, keyboard_capturer->control_flag_, g_user_ptr);
g_on_key_action(vk_code, keyboard_capturer->control_flag_, 0, false,
g_user_ptr);
}
// option
bool option_state = (current_flags & kCGEventFlagMaskAlternate) != 0;
if (option_state != keyboard_capturer->option_flag_) {
keyboard_capturer->option_flag_ = option_state;
g_on_key_action(vk_code, keyboard_capturer->option_flag_, g_user_ptr);
g_on_key_action(vk_code, keyboard_capturer->option_flag_, 0, false,
g_user_ptr);
}
// command
bool command_state = (current_flags & kCGEventFlagMaskCommand) != 0;
if (command_state != keyboard_capturer->command_flag_) {
keyboard_capturer->command_flag_ = command_state;
g_on_key_action(vk_code, keyboard_capturer->command_flag_, g_user_ptr);
g_on_key_action(vk_code, keyboard_capturer->command_flag_, 0, false,
g_user_ptr);
}
}
@@ -264,7 +269,10 @@ inline bool IsFunctionKey(int key_code) {
}
}
int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down) {
int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code, bool extended) {
(void)scan_code;
(void)extended;
if (vkCodeToCGKeyCode.find(key_code) != vkCodeToCGKeyCode.end()) {
CGKeyCode cg_key_code = vkCodeToCGKeyCode[key_code];
CGEventRef event = CGEventCreateKeyboardEvent(NULL, cg_key_code, is_down);
@@ -21,7 +21,9 @@ class KeyboardCapturer : public DeviceController {
public:
virtual int Hook(OnKeyAction on_key_action, void* user_ptr);
virtual int Unhook();
virtual int SendKeyboardCommand(int key_code, bool is_down);
virtual int SendKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code = 0,
bool extended = false);
private:
CFMachPortRef event_tap_ = nullptr;
@@ -7,14 +7,56 @@ namespace crossdesk {
static OnKeyAction g_on_key_action = nullptr;
static void* g_user_ptr = nullptr;
static int NormalizeModifierVkCode(const KBDLLHOOKSTRUCT* kb_data) {
if (kb_data == nullptr) {
return -1;
}
if (kb_data->vkCode != VK_SHIFT && kb_data->vkCode != VK_CONTROL &&
kb_data->vkCode != VK_MENU) {
return static_cast<int>(kb_data->vkCode);
}
UINT scan_code = static_cast<UINT>(kb_data->scanCode & 0xFF);
if ((kb_data->flags & LLKHF_EXTENDED) != 0) {
scan_code |= 0xE000;
}
const UINT normalized_vk = MapVirtualKeyW(scan_code, MAPVK_VSC_TO_VK_EX);
if (normalized_vk != 0) {
return static_cast<int>(normalized_vk);
}
return static_cast<int>(kb_data->vkCode);
}
static bool PreferSideSpecificVkInjection(int key_code) {
switch (key_code) {
case VK_LSHIFT:
case VK_RSHIFT:
case VK_LCONTROL:
case VK_RCONTROL:
case VK_LMENU:
case VK_RMENU:
case VK_LWIN:
case VK_RWIN:
return true;
default:
return false;
}
}
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HC_ACTION && g_on_key_action) {
KBDLLHOOKSTRUCT* kbData = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
const int key_code = NormalizeModifierVkCode(kbData);
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
g_on_key_action(kbData->vkCode, true, g_user_ptr);
g_on_key_action(key_code, true, kbData->scanCode,
(kbData->flags & LLKHF_EXTENDED) != 0, g_user_ptr);
} else if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) {
g_on_key_action(kbData->vkCode, false, g_user_ptr);
g_on_key_action(key_code, false, kbData->scanCode,
(kbData->flags & LLKHF_EXTENDED) != 0, g_user_ptr);
}
return 1;
}
@@ -49,20 +91,40 @@ int KeyboardCapturer::Unhook() {
}
// apply remote keyboard commands to the local machine
int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down) {
int KeyboardCapturer::SendKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code, bool extended) {
INPUT input = {0};
input.type = INPUT_KEYBOARD;
input.ki.wVk = (WORD)key_code;
const UINT scan_code =
MapVirtualKeyW(static_cast<UINT>(key_code), MAPVK_VK_TO_VSC_EX);
if (scan_code != 0) {
const bool prefer_vk = PreferSideSpecificVkInjection(key_code);
const UINT resolved_scan_code =
scan_code != 0
? static_cast<UINT>(scan_code & 0xFF) | (extended ? 0xE000u : 0u)
: MapVirtualKeyW(static_cast<UINT>(key_code), MAPVK_VK_TO_VSC_EX);
if (scan_code != 0 && !prefer_vk) {
input.ki.wVk = 0;
input.ki.wScan = static_cast<WORD>(scan_code & 0xFF);
input.ki.dwFlags |= KEYEVENTF_SCANCODE;
if ((scan_code & 0xFF00) != 0) {
if (extended) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
} else {
input.ki.wVk = (WORD)key_code;
if (prefer_vk && resolved_scan_code != 0) {
input.ki.wScan = static_cast<WORD>(resolved_scan_code & 0xFF);
if ((resolved_scan_code & 0xFF00) != 0) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
} else if (resolved_scan_code != 0) {
input.ki.wVk = 0;
input.ki.wScan = static_cast<WORD>(resolved_scan_code & 0xFF);
input.ki.dwFlags |= KEYEVENTF_SCANCODE;
if ((resolved_scan_code & 0xFF00) != 0) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
}
}
if (!is_down) {
@@ -21,7 +21,9 @@ class KeyboardCapturer : public DeviceController {
public:
virtual int Hook(OnKeyAction on_key_action, void* user_ptr);
virtual int Unhook();
virtual int SendKeyboardCommand(int key_code, bool is_down);
virtual int SendKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code = 0,
bool extended = false);
private:
HHOOK keyboard_hook_ = nullptr;
@@ -0,0 +1,89 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-05-07
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _WINDOWS_KEY_METADATA_H_
#define _WINDOWS_KEY_METADATA_H_
#include <cstdint>
namespace crossdesk {
inline bool LookupWindowsKeyMetadataFromVk(int key_code,
uint32_t* scan_code_out,
bool* extended_out) {
if (scan_code_out == nullptr || extended_out == nullptr) {
return false;
}
switch (key_code) {
case 0x21: // Page Up
*scan_code_out = 0x49;
*extended_out = true;
return true;
case 0x22: // Page Down
*scan_code_out = 0x51;
*extended_out = true;
return true;
case 0x23: // End
*scan_code_out = 0x4F;
*extended_out = true;
return true;
case 0x24: // Home
*scan_code_out = 0x47;
*extended_out = true;
return true;
case 0x25: // Left Arrow
*scan_code_out = 0x4B;
*extended_out = true;
return true;
case 0x26: // Up Arrow
*scan_code_out = 0x48;
*extended_out = true;
return true;
case 0x27: // Right Arrow
*scan_code_out = 0x4D;
*extended_out = true;
return true;
case 0x28: // Down Arrow
*scan_code_out = 0x50;
*extended_out = true;
return true;
case 0x2D: // Insert
*scan_code_out = 0x52;
*extended_out = true;
return true;
case 0x2E: // Delete
*scan_code_out = 0x53;
*extended_out = true;
return true;
case 0x6F: // Numpad /
*scan_code_out = 0x35;
*extended_out = true;
return true;
case 0xA3: // Right Ctrl
*scan_code_out = 0x1D;
*extended_out = true;
return true;
case 0xA5: // Right Alt
*scan_code_out = 0x38;
*extended_out = true;
return true;
case 0x5B: // Left Win
*scan_code_out = 0x5B;
*extended_out = true;
return true;
case 0x5C: // Right Win
*scan_code_out = 0x5C;
*extended_out = true;
return true;
default:
return false;
}
}
} // namespace crossdesk
#endif
+3 -2
View File
@@ -812,10 +812,11 @@ int Render::StartKeyboardCapturer() {
}
int keyboard_capturer_init_ret = keyboard_capturer_->Hook(
[](int key_code, bool is_down, void* user_ptr) {
[](int key_code, bool is_down, uint32_t scan_code, bool extended,
void* user_ptr) {
if (user_ptr) {
Render* render = (Render*)user_ptr;
render->SendKeyCommand(key_code, is_down);
render->SendKeyCommand(key_code, is_down, scan_code, extended);
}
},
this);
+3 -1
View File
@@ -62,6 +62,7 @@ class Render {
std::chrono::steady_clock::time_point file_send_last_update_time_;
uint64_t file_send_last_bytes_ = 0;
bool file_transfer_window_visible_ = false;
bool file_transfer_window_hovered_ = false;
std::atomic<uint32_t> current_file_id_{0};
struct QueuedFile {
@@ -338,7 +339,8 @@ class Render {
static void FreeRemoteAction(RemoteAction& action);
private:
int SendKeyCommand(int key_code, bool is_down);
int SendKeyCommand(int key_code, bool is_down, uint32_t scan_code = 0,
bool extended = false);
static bool IsModifierVkKey(int key_code);
void TrackPressedKeyState(int key_code, bool is_down);
void ForceReleasePressedKeys();
+105 -10
View File
@@ -17,6 +17,7 @@
#include "platform.h"
#include "rd_log.h"
#include "render.h"
#include "windows_key_metadata.h"
#if _WIN32
#include "interactive_state.h"
#include "service_host.h"
@@ -28,34 +29,66 @@ namespace crossdesk {
namespace {
int TranslateSdlKeypadScancodeToVk(SDL_Scancode scancode) {
switch (scancode) {
int TranslateSdlKeypadScancodeToVk(const SDL_KeyboardEvent& event) {
const bool numlock_enabled = (event.mod & SDL_KMOD_NUM) != 0;
switch (event.scancode) {
case SDL_SCANCODE_NUMLOCKCLEAR:
return 0x90;
case SDL_SCANCODE_KP_ENTER:
return 0x0D;
case SDL_SCANCODE_KP_0:
if (!numlock_enabled) {
return 0x2D;
}
return 0x60;
case SDL_SCANCODE_KP_1:
if (!numlock_enabled) {
return 0x23;
}
return 0x61;
case SDL_SCANCODE_KP_2:
if (!numlock_enabled) {
return 0x28;
}
return 0x62;
case SDL_SCANCODE_KP_3:
if (!numlock_enabled) {
return 0x22;
}
return 0x63;
case SDL_SCANCODE_KP_4:
if (!numlock_enabled) {
return 0x25;
}
return 0x64;
case SDL_SCANCODE_KP_5:
return 0x65;
case SDL_SCANCODE_KP_6:
if (!numlock_enabled) {
return 0x27;
}
return 0x66;
case SDL_SCANCODE_KP_7:
if (!numlock_enabled) {
return 0x24;
}
return 0x67;
case SDL_SCANCODE_KP_8:
if (!numlock_enabled) {
return 0x26;
}
return 0x68;
case SDL_SCANCODE_KP_9:
if (!numlock_enabled) {
return 0x21;
}
return 0x69;
case SDL_SCANCODE_KP_PERIOD:
case SDL_SCANCODE_KP_COMMA:
if (!numlock_enabled) {
return 0x2E;
}
return 0x6E;
case SDL_SCANCODE_KP_DIVIDE:
return 0x6F;
@@ -73,7 +106,7 @@ int TranslateSdlKeypadScancodeToVk(SDL_Scancode scancode) {
}
int TranslateSdlKeyboardEventToVk(const SDL_KeyboardEvent& event) {
const int keypad_key_code = TranslateSdlKeypadScancodeToVk(event.scancode);
const int keypad_key_code = TranslateSdlKeypadScancodeToVk(event);
if (keypad_key_code >= 0) {
return keypad_key_code;
}
@@ -200,6 +233,49 @@ int TranslateSdlKeyboardEventToVk(const SDL_KeyboardEvent& event) {
}
}
int NormalizeWindowsModifierVk(int key_code, uint32_t scan_code,
bool extended) {
#if _WIN32
if (key_code != 0x10 && key_code != 0x11 && key_code != 0x12) {
return key_code;
}
UINT scan_code_with_prefix = static_cast<UINT>(scan_code & 0xFF);
if (extended) {
scan_code_with_prefix |= 0xE000;
}
const UINT normalized_vk =
MapVirtualKeyW(scan_code_with_prefix, MAPVK_VSC_TO_VK_EX);
return normalized_vk != 0 ? static_cast<int>(normalized_vk) : key_code;
#else
(void)scan_code;
(void)extended;
return key_code;
#endif
}
void PopulateWindowsKeyMetadataFromVk(int key_code, uint32_t* scan_code_out,
bool* extended_out) {
if (scan_code_out == nullptr || extended_out == nullptr) {
return;
}
#if _WIN32
const UINT scan_code =
MapVirtualKeyW(static_cast<UINT>(key_code), MAPVK_VK_TO_VSC_EX);
if (scan_code == 0) {
LookupWindowsKeyMetadataFromVk(key_code, scan_code_out, extended_out);
return;
}
*scan_code_out = static_cast<uint32_t>(scan_code & 0xFF);
*extended_out = (scan_code & 0xFF00) != 0;
#else
LookupWindowsKeyMetadataFromVk(key_code, scan_code_out, extended_out);
#endif
}
#if _WIN32
constexpr uint32_t kSecureDesktopInputLogIntervalMs = 2000;
@@ -353,15 +429,26 @@ void Render::ForceReleasePressedKeys() {
}
}
int Render::SendKeyCommand(int key_code, bool is_down) {
RemoteAction remote_action;
int Render::SendKeyCommand(int key_code, bool is_down, uint32_t scan_code,
bool extended) {
RemoteAction remote_action{};
remote_action.type = ControlType::keyboard;
if (is_down) {
remote_action.k.flag = KeyFlag::key_down;
} else {
remote_action.k.flag = KeyFlag::key_up;
}
if (scan_code == 0) {
PopulateWindowsKeyMetadataFromVk(key_code, &scan_code, &extended);
}
#if _WIN32
key_code = NormalizeWindowsModifierVk(key_code, scan_code, extended);
#endif
remote_action.k.key_value = key_code;
remote_action.k.scan_code = scan_code;
remote_action.k.extended = extended;
std::string target_id = controlled_remote_id_.empty() ? focused_remote_id_
: controlled_remote_id_;
@@ -474,6 +561,12 @@ int Render::ProcessMouseEvent(const SDL_Event& event) {
continue;
}
const bool file_transfer_window_hovered =
props->file_transfer_.file_transfer_window_hovered_;
const bool overlay_hovered = props->control_bar_hovered_ ||
props->display_selectable_hovered_ ||
file_transfer_window_hovered;
const SDL_FRect render_rect = props->stream_render_rect_f_;
if (render_rect.w <= 1.0f || render_rect.h <= 1.0f) {
continue;
@@ -517,7 +610,7 @@ int Render::ProcessMouseEvent(const SDL_Event& event) {
remote_action.m.flag = MouseFlag::move;
}
if (props->control_bar_hovered_ || props->display_selectable_hovered_) {
if (overlay_hovered) {
break;
}
if (props->peer_) {
@@ -563,7 +656,7 @@ int Render::ProcessMouseEvent(const SDL_Event& event) {
remote_action.m.x = std::clamp(remote_action.m.x, 0.0f, 1.0f);
remote_action.m.y = std::clamp(remote_action.m.y, 0.0f, 1.0f);
if (props->control_bar_hovered_) {
if (overlay_hovered) {
continue;
}
if (props->peer_) {
@@ -1042,8 +1135,9 @@ void Render::OnReceiveDataBufferCb(const char* data, size_t size,
if (remote_action.type == ControlType::keyboard) {
const int key_code = static_cast<int>(remote_action.k.key_value);
const bool is_down = remote_action.k.flag == KeyFlag::key_down;
const std::string response =
SendCrossDeskSecureDesktopKeyInput(key_code, is_down, 1000);
const std::string response = SendCrossDeskSecureDesktopKeyInput(
key_code, is_down, remote_action.k.scan_code,
remote_action.k.extended, 1000);
auto json = nlohmann::json::parse(response, nullptr, false);
if (json.is_discarded() || !json.value("ok", false)) {
LogSecureDesktopInputBlocked(
@@ -1070,7 +1164,8 @@ void Render::OnReceiveDataBufferCb(const char* data, size_t size,
render->keyboard_capturer_) {
render->keyboard_capturer_->SendKeyboardCommand(
(int)remote_action.k.key_value,
remote_action.k.flag == KeyFlag::key_down);
remote_action.k.flag == KeyFlag::key_down, remote_action.k.scan_code,
remote_action.k.extended);
} else if (remote_action.type == ControlType::display_id &&
render->screen_capturer_) {
render->selected_display_ = remote_action.d;
+1 -1
View File
@@ -104,7 +104,7 @@ int Render::AboutWindow() {
ImGui::SetCursorPosX(about_window_width * 0.1f);
ImGui::Text("%s", text.c_str());
if (0) {
if (update_available_ && show_new_version_icon_in_menu_) {
std::string new_version_available =
localization::new_version_available[localization_language_index_] +
": ";
+26 -19
View File
@@ -31,6 +31,7 @@ int BitrateDisplay(int bitrate) {
int Render::FileTransferWindow(
std::shared_ptr<SubStreamWindowProperties>& props) {
FileTransferState* state = props ? &props->file_transfer_ : &file_transfer_;
state->file_transfer_window_hovered_ = false;
// Only show window if there are files in transfer list or currently
// transferring
@@ -72,8 +73,6 @@ int Render::FileTransferWindow(
return 0;
}
ImGuiIO& io = ImGui::GetIO();
// Position window at bottom-left of stream window
// Adjust window size based on number of files
float file_transfer_window_width = main_window_width_ * 0.6f;
@@ -82,15 +81,25 @@ int Render::FileTransferWindow(
float pos_x = file_transfer_window_width * 0.05f;
float pos_y = stream_window_height_ - file_transfer_window_height -
file_transfer_window_width * 0.05;
float same_line_width = file_transfer_window_width * 0.1f;
const ImVec2 mouse_pos = ImGui::GetMousePos();
const bool mouse_in_window_rect =
mouse_pos.x >= pos_x &&
mouse_pos.x <= pos_x + file_transfer_window_width &&
mouse_pos.y >= pos_y &&
mouse_pos.y <= pos_y + file_transfer_window_height;
ImGui::SetNextWindowPos(ImVec2(pos_x, pos_y), ImGuiCond_Always);
ImGui::SetNextWindowSize(
ImVec2(file_transfer_window_width, file_transfer_window_height),
ImGuiCond_Always);
if (mouse_in_window_rect) {
ImGui::SetNextWindowFocus();
}
// Set Chinese font for proper display
if (stream_windows_system_chinese_font_) {
const bool has_chinese_font = stream_windows_system_chinese_font_ != nullptr;
if (has_chinese_font) {
ImGui::PushFont(stream_windows_system_chinese_font_);
}
@@ -103,25 +112,28 @@ int Render::FileTransferWindow(
ImGui::SetWindowFontScale(0.5f);
bool window_opened = true;
if (ImGui::Begin(
const bool show_contents = ImGui::Begin(
localization::file_transfer_progress[localization_language_index_]
.c_str(),
&window_opened,
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoScrollbar)) {
ImGui::SetWindowFontScale(1.0f);
ImGui::SetWindowFontScale(0.5f);
ImGuiWindowFlags_NoScrollbar);
ImGui::PopStyleColor(4);
ImGui::PopStyleVar(2);
// Close button handling
state->file_transfer_window_hovered_ =
mouse_in_window_rect ||
ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
if (!window_opened) {
state->file_transfer_window_visible_ = false;
ImGui::End();
return 0;
}
if (show_contents && window_opened) {
ImGui::SetWindowFontScale(1.0f);
ImGui::SetWindowFontScale(0.5f);
// Display file list
if (file_list.empty()) {
ImGui::Text("No files in transfer queue");
@@ -225,21 +237,16 @@ int Render::FileTransferWindow(
}
ImGui::SetWindowFontScale(1.0f);
ImGui::SetWindowFontScale(0.5f);
}
ImGui::End();
ImGui::SetWindowFontScale(1.0f);
// Pop Chinese font if it was pushed
if (stream_windows_system_chinese_font_) {
if (has_chinese_font) {
ImGui::PopFont();
}
} else {
ImGui::PopStyleColor(4);
ImGui::PopStyleVar(2);
}
ImGui::SetWindowFontScale(1.0f);
return 0;
}
} // namespace crossdesk
@@ -92,7 +92,7 @@ int Render::UpdateNotificationWindow() {
ImGui::SetWindowFontScale(0.55f);
std::string title =
localization::new_version_available[localization_language_index_] +
": v" + latest_version_;
": " + latest_version_;
ImGui::Text("%s", title.c_str());
ImGui::SetWindowFontScale(0.1f);
@@ -57,6 +57,11 @@ int ScreenCapturerWayland::Init(const int fps, cb_desktop_data cb) {
return -1;
}
if (!EnsurePipeWireRuntimeAvailable()) {
LOG_ERROR("Wayland screen capturer requires PipeWire 0.3 runtime");
return -1;
}
fps_ = fps;
callback_ = cb;
pointer_granted_ = false;
@@ -52,6 +52,7 @@ class ScreenCapturerWayland : public ScreenCapturer {
bool SelectPortalDevices();
bool SelectPortalSource();
bool StartPortalSession();
bool EnsurePipeWireRuntimeAvailable() const;
bool OpenPipeWireRemote();
bool SetupPipeWireStream(bool relaxed_connect, PipeWireConnectMode mode);
@@ -3,6 +3,7 @@
#if CROSSDESK_WAYLAND_BUILD_ENABLED
#include <dlfcn.h>
#include <unistd.h>
#include <algorithm>
@@ -10,6 +11,7 @@
#include <cmath>
#include <cstdint>
#include <limits>
#include <mutex>
#include <thread>
#include <vector>
@@ -20,6 +22,143 @@ namespace crossdesk {
namespace {
struct PipeWireDynamicApi {
void* library = nullptr;
bool available = false;
decltype(&::pw_init) init = nullptr;
decltype(&::pw_deinit) deinit = nullptr;
decltype(&::pw_thread_loop_new) thread_loop_new = nullptr;
decltype(&::pw_thread_loop_destroy) thread_loop_destroy = nullptr;
decltype(&::pw_thread_loop_get_loop) thread_loop_get_loop = nullptr;
decltype(&::pw_thread_loop_start) thread_loop_start = nullptr;
decltype(&::pw_thread_loop_stop) thread_loop_stop = nullptr;
decltype(&::pw_thread_loop_lock) thread_loop_lock = nullptr;
decltype(&::pw_thread_loop_unlock) thread_loop_unlock = nullptr;
decltype(&::pw_thread_loop_wait) thread_loop_wait = nullptr;
decltype(&::pw_thread_loop_signal) thread_loop_signal = nullptr;
decltype(&::pw_context_new) context_new = nullptr;
decltype(&::pw_context_destroy) context_destroy = nullptr;
decltype(&::pw_context_connect_fd) context_connect_fd = nullptr;
decltype(&::pw_properties_new) properties_new = nullptr;
decltype(&::pw_properties_set) properties_set = nullptr;
decltype(&::pw_stream_new) stream_new = nullptr;
decltype(&::pw_stream_add_listener) stream_add_listener = nullptr;
decltype(&::pw_stream_state_as_string) stream_state_as_string = nullptr;
decltype(&::pw_stream_connect) stream_connect = nullptr;
decltype(&::pw_stream_update_params) stream_update_params = nullptr;
decltype(&::pw_stream_set_active) stream_set_active = nullptr;
decltype(&::pw_stream_disconnect) stream_disconnect = nullptr;
decltype(&::pw_stream_destroy) stream_destroy = nullptr;
decltype(&::pw_stream_dequeue_buffer) stream_dequeue_buffer = nullptr;
decltype(&::pw_stream_queue_buffer) stream_queue_buffer = nullptr;
decltype(&::pw_core_disconnect) core_disconnect = nullptr;
decltype(&::pw_proxy_destroy) proxy_destroy = nullptr;
};
template <typename T>
bool LoadPipeWireSymbol(void* library, T* function, const char* symbol_name) {
*function = reinterpret_cast<T>(dlsym(library, symbol_name));
if (*function != nullptr) {
return true;
}
LOG_ERROR("Unable to find PipeWire symbol {}", symbol_name);
return false;
}
void UnloadPipeWireApi(PipeWireDynamicApi* api) {
if (api->library != nullptr) {
dlclose(api->library);
}
*api = PipeWireDynamicApi{};
}
bool LoadPipeWireApi(PipeWireDynamicApi* api) {
static constexpr const char* kPipeWireLibraries[] = {
"libpipewire-0.3.so.0",
"libpipewire-0.3.so",
};
for (const char* library_name : kPipeWireLibraries) {
api->library = dlopen(library_name, RTLD_LAZY | RTLD_LOCAL);
if (api->library != nullptr) {
break;
}
}
if (api->library == nullptr) {
LOG_WARN("PipeWire 0.3 runtime library is unavailable");
return false;
}
if (!LoadPipeWireSymbol(api->library, &api->init, "pw_init") ||
!LoadPipeWireSymbol(api->library, &api->deinit, "pw_deinit") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_new,
"pw_thread_loop_new") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_destroy,
"pw_thread_loop_destroy") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_get_loop,
"pw_thread_loop_get_loop") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_start,
"pw_thread_loop_start") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_stop,
"pw_thread_loop_stop") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_lock,
"pw_thread_loop_lock") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_unlock,
"pw_thread_loop_unlock") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_wait,
"pw_thread_loop_wait") ||
!LoadPipeWireSymbol(api->library, &api->thread_loop_signal,
"pw_thread_loop_signal") ||
!LoadPipeWireSymbol(api->library, &api->context_new, "pw_context_new") ||
!LoadPipeWireSymbol(api->library, &api->context_destroy,
"pw_context_destroy") ||
!LoadPipeWireSymbol(api->library, &api->context_connect_fd,
"pw_context_connect_fd") ||
!LoadPipeWireSymbol(api->library, &api->properties_new,
"pw_properties_new") ||
!LoadPipeWireSymbol(api->library, &api->properties_set,
"pw_properties_set") ||
!LoadPipeWireSymbol(api->library, &api->stream_new, "pw_stream_new") ||
!LoadPipeWireSymbol(api->library, &api->stream_add_listener,
"pw_stream_add_listener") ||
!LoadPipeWireSymbol(api->library, &api->stream_state_as_string,
"pw_stream_state_as_string") ||
!LoadPipeWireSymbol(api->library, &api->stream_connect,
"pw_stream_connect") ||
!LoadPipeWireSymbol(api->library, &api->stream_update_params,
"pw_stream_update_params") ||
!LoadPipeWireSymbol(api->library, &api->stream_set_active,
"pw_stream_set_active") ||
!LoadPipeWireSymbol(api->library, &api->stream_disconnect,
"pw_stream_disconnect") ||
!LoadPipeWireSymbol(api->library, &api->stream_destroy,
"pw_stream_destroy") ||
!LoadPipeWireSymbol(api->library, &api->stream_dequeue_buffer,
"pw_stream_dequeue_buffer") ||
!LoadPipeWireSymbol(api->library, &api->stream_queue_buffer,
"pw_stream_queue_buffer") ||
!LoadPipeWireSymbol(api->library, &api->core_disconnect,
"pw_core_disconnect") ||
!LoadPipeWireSymbol(api->library, &api->proxy_destroy,
"pw_proxy_destroy")) {
UnloadPipeWireApi(api);
return false;
}
api->available = true;
return true;
}
const PipeWireDynamicApi* GetPipeWireApi() {
static PipeWireDynamicApi api;
static std::once_flag once;
std::call_once(once, []() { LoadPipeWireApi(&api); });
return api.available ? &api : nullptr;
}
const char* PipeWireFormatName(uint32_t spa_format) {
switch (spa_format) {
case SPA_VIDEO_FORMAT_BGRx:
@@ -76,6 +215,7 @@ double SnapLikelyFractionalScale(double observed_scale) {
}
struct PipeWireTargetLookupState {
const PipeWireDynamicApi* pipewire = nullptr;
pw_thread_loop* loop = nullptr;
uint32_t target_node_id = 0;
int sync_seq = -1;
@@ -87,11 +227,13 @@ struct PipeWireTargetLookupState {
std::string LookupPipeWireTargetObjectSerial(pw_core* core,
pw_thread_loop* loop,
uint32_t node_id) {
if (!core || !loop || node_id == 0) {
const PipeWireDynamicApi* pipewire = GetPipeWireApi();
if (!pipewire || !core || !loop || node_id == 0) {
return "";
}
PipeWireTargetLookupState state;
state.pipewire = pipewire;
state.loop = loop;
state.target_node_id = node_id;
@@ -138,7 +280,7 @@ std::string LookupPipeWireTargetObjectSerial(pw_core* core,
return;
}
state->done = true;
pw_thread_loop_signal(state->loop, false);
state->pipewire->thread_loop_signal(state->loop, false);
};
core_events.error = [](void* userdata, uint32_t id, int seq, int res,
const char* message) {
@@ -152,7 +294,7 @@ std::string LookupPipeWireTargetObjectSerial(pw_core* core,
LOG_WARN("PipeWire registry lookup error: {}",
message ? message : "unknown");
state->done = true;
pw_thread_loop_signal(state->loop, false);
state->pipewire->thread_loop_signal(state->loop, false);
};
pw_registry_add_listener(registry, &registry_listener, &registry_events,
@@ -161,12 +303,12 @@ std::string LookupPipeWireTargetObjectSerial(pw_core* core,
state.sync_seq = pw_core_sync(core, PW_ID_CORE, 0);
while (!state.done) {
pw_thread_loop_wait(loop);
pipewire->thread_loop_wait(loop);
}
spa_hook_remove(&registry_listener);
spa_hook_remove(&core_listener);
pw_proxy_destroy(reinterpret_cast<pw_proxy*>(registry));
pipewire->proxy_destroy(reinterpret_cast<pw_proxy*>(registry));
return state.found ? state.object_serial : "";
}
@@ -188,56 +330,68 @@ int BytesPerPixel(uint32_t spa_format) {
} // namespace
bool ScreenCapturerWayland::EnsurePipeWireRuntimeAvailable() const {
return GetPipeWireApi() != nullptr;
}
bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
PipeWireConnectMode mode) {
const PipeWireDynamicApi* pipewire = GetPipeWireApi();
if (!pipewire) {
LOG_ERROR("PipeWire 0.3 runtime library is unavailable");
return false;
}
if (pipewire_fd_ < 0 || pipewire_node_id_ == 0) {
return false;
}
if (!pipewire_initialized_) {
pw_init(nullptr, nullptr);
pipewire->init(nullptr, nullptr);
pipewire_initialized_ = true;
}
pw_thread_loop_ = pw_thread_loop_new("crossdesk-wayland-capture", nullptr);
pw_thread_loop_ =
pipewire->thread_loop_new("crossdesk-wayland-capture", nullptr);
if (!pw_thread_loop_) {
LOG_ERROR("Failed to create PipeWire thread loop");
return false;
}
if (pw_thread_loop_start(pw_thread_loop_) < 0) {
if (pipewire->thread_loop_start(pw_thread_loop_) < 0) {
LOG_ERROR("Failed to start PipeWire thread loop");
CleanupPipeWire();
return false;
}
pipewire_thread_loop_started_ = true;
pw_thread_loop_lock(pw_thread_loop_);
pipewire->thread_loop_lock(pw_thread_loop_);
pw_context_ =
pw_context_new(pw_thread_loop_get_loop(pw_thread_loop_), nullptr, 0);
pw_context_ = pipewire->context_new(
pipewire->thread_loop_get_loop(pw_thread_loop_), nullptr, 0);
if (!pw_context_) {
LOG_ERROR("Failed to create PipeWire context");
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
CleanupPipeWire();
return false;
}
pw_core_ = pw_context_connect_fd(pw_context_, pipewire_fd_, nullptr, 0);
pw_core_ =
pipewire->context_connect_fd(pw_context_, pipewire_fd_, nullptr, 0);
if (!pw_core_) {
LOG_ERROR("Failed to connect to PipeWire remote");
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
CleanupPipeWire();
return false;
}
pipewire_fd_ = -1;
pw_properties* stream_props =
pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY,
"Capture", PW_KEY_MEDIA_ROLE, "Screen", nullptr);
pw_properties* stream_props = pipewire->properties_new(
PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture",
PW_KEY_MEDIA_ROLE, "Screen", nullptr);
if (!stream_props) {
LOG_ERROR("Failed to allocate PipeWire stream properties");
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
CleanupPipeWire();
return false;
}
@@ -247,7 +401,7 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
target_object_serial = LookupPipeWireTargetObjectSerial(
pw_core_, pw_thread_loop_, pipewire_node_id_);
if (!target_object_serial.empty()) {
pw_properties_set(stream_props, PW_KEY_TARGET_OBJECT,
pipewire->properties_set(stream_props, PW_KEY_TARGET_OBJECT,
target_object_serial.c_str());
LOG_INFO("PipeWire target object serial for node {} is {}",
pipewire_node_id_, target_object_serial);
@@ -260,10 +414,10 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
}
pw_stream_ =
pw_stream_new(pw_core_, "CrossDesk Wayland Capture", stream_props);
pipewire->stream_new(pw_core_, "CrossDesk Wayland Capture", stream_props);
if (!pw_stream_) {
LOG_ERROR("Failed to create PipeWire stream");
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
CleanupPipeWire();
return false;
}
@@ -289,9 +443,11 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
return;
}
LOG_INFO("PipeWire stream state: {} -> {}",
pw_stream_state_as_string(old_state),
pw_stream_state_as_string(state));
const PipeWireDynamicApi* pipewire = GetPipeWireApi();
LOG_INFO(
"PipeWire stream state: {} -> {}",
pipewire ? pipewire->stream_state_as_string(old_state) : "unknown",
pipewire ? pipewire->stream_state_as_string(state) : "unknown");
};
events.param_changed = [](void* userdata, uint32_t id,
const struct spa_pod* param) {
@@ -369,7 +525,10 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
SPA_POD_Int(sizeof(struct spa_meta_header))));
if (self->pw_stream_) {
pw_stream_update_params(self->pw_stream_, params, param_count);
const PipeWireDynamicApi* pipewire = GetPipeWireApi();
if (pipewire) {
pipewire->stream_update_params(self->pw_stream_, params, param_count);
}
}
self->pipewire_format_ready_.store(true);
@@ -457,7 +616,7 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
return events;
}();
pw_stream_add_listener(pw_stream_, listener, &stream_events, this);
pipewire->stream_add_listener(pw_stream_, listener, &stream_events, this);
pipewire_format_ready_.store(false);
pipewire_stream_start_ms_.store(NowMs());
pipewire_last_frame_ms_.store(0);
@@ -501,7 +660,7 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
if (param_count == 0) {
LOG_ERROR("No valid PipeWire format params were built");
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
CleanupPipeWire();
return false;
}
@@ -522,12 +681,12 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
PipeWireConnectModeName(mode), pipewire_node_id_, target_id,
target_object_serial.empty() ? "none" : target_object_serial.c_str(),
relaxed_connect, param_count, fixed_size.width, fixed_size.height);
const int ret = pw_stream_connect(
const int ret = pipewire->stream_connect(
pw_stream_, PW_DIRECTION_INPUT, target_id,
static_cast<pw_stream_flags>(PW_STREAM_FLAG_AUTOCONNECT |
PW_STREAM_FLAG_MAP_BUFFERS),
param_count > 0 ? params : nullptr, static_cast<uint32_t>(param_count));
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
if (ret < 0) {
LOG_ERROR("pw_stream_connect failed: {}", spa_strerror(ret));
@@ -539,16 +698,17 @@ bool ScreenCapturerWayland::SetupPipeWireStream(bool relaxed_connect,
}
void ScreenCapturerWayland::CleanupPipeWire() {
const PipeWireDynamicApi* pipewire = GetPipeWireApi();
const bool need_lock =
pw_thread_loop_ &&
pipewire && pw_thread_loop_ &&
(pw_stream_ != nullptr || pw_core_ != nullptr || pw_context_ != nullptr);
if (need_lock) {
pw_thread_loop_lock(pw_thread_loop_);
pipewire->thread_loop_lock(pw_thread_loop_);
}
if (pw_stream_) {
pw_stream_set_active(pw_stream_, false);
pw_stream_disconnect(pw_stream_);
if (pw_stream_ && pipewire) {
pipewire->stream_set_active(pw_stream_, false);
pipewire->stream_disconnect(pw_stream_);
}
if (stream_listener_) {
@@ -557,33 +717,34 @@ void ScreenCapturerWayland::CleanupPipeWire() {
stream_listener_ = nullptr;
}
if (pw_stream_) {
pw_stream_destroy(pw_stream_);
if (pw_stream_ && pipewire) {
pipewire->stream_destroy(pw_stream_);
}
pw_stream_ = nullptr;
}
if (pw_core_) {
pw_core_disconnect(pw_core_);
if (pw_core_ && pipewire) {
pipewire->core_disconnect(pw_core_);
}
pw_core_ = nullptr;
}
if (pw_context_) {
pw_context_destroy(pw_context_);
pw_context_ = nullptr;
if (pw_context_ && pipewire) {
pipewire->context_destroy(pw_context_);
}
pw_context_ = nullptr;
if (need_lock) {
pw_thread_loop_unlock(pw_thread_loop_);
pipewire->thread_loop_unlock(pw_thread_loop_);
}
if (pw_thread_loop_) {
if (pw_thread_loop_ && pipewire) {
if (pipewire_thread_loop_started_) {
pw_thread_loop_stop(pw_thread_loop_);
pipewire->thread_loop_stop(pw_thread_loop_);
pipewire_thread_loop_started_ = false;
}
pw_thread_loop_destroy(pw_thread_loop_);
pw_thread_loop_ = nullptr;
pipewire->thread_loop_destroy(pw_thread_loop_);
}
pw_thread_loop_ = nullptr;
pipewire_thread_loop_started_ = false;
if (pipewire_fd_ >= 0) {
close(pipewire_fd_);
@@ -594,23 +755,24 @@ void ScreenCapturerWayland::CleanupPipeWire() {
pipewire_stream_start_ms_.store(0);
pipewire_last_frame_ms_.store(0);
if (pipewire_initialized_) {
pw_deinit();
pipewire_initialized_ = false;
if (pipewire_initialized_ && pipewire) {
pipewire->deinit();
}
pipewire_initialized_ = false;
}
void ScreenCapturerWayland::HandlePipeWireBuffer() {
if (!pw_stream_) {
const PipeWireDynamicApi* pipewire = GetPipeWireApi();
if (!pw_stream_ || !pipewire) {
return;
}
pw_buffer* buffer = pw_stream_dequeue_buffer(pw_stream_);
pw_buffer* buffer = pipewire->stream_dequeue_buffer(pw_stream_);
if (!buffer) {
return;
}
auto requeue = [&]() { pw_stream_queue_buffer(pw_stream_, buffer); };
auto requeue = [&]() { pipewire->stream_queue_buffer(pw_stream_, buffer); };
if (paused_) {
requeue();
+240 -21
View File
@@ -1,5 +1,6 @@
#include "service_host.h"
#include <Aclapi.h>
#include <TlHelp32.h>
#include <Userenv.h>
#include <WtsApi32.h>
@@ -27,6 +28,9 @@ using Json = nlohmann::json;
constexpr char kSecureDesktopKeyboardIpcCommandPrefix[] = "secure-input-key:";
constexpr char kSecureDesktopMouseIpcCommandPrefix[] = "secure-input-mouse:";
constexpr wchar_t kCrossDeskClientProcessName[] = L"crossdesk.exe";
constexpr DWORD kCrossDeskClientMonitorIntervalMs = 1000;
constexpr ULONGLONG kCrossDeskClientMonitorStartupGraceMs = 5000;
using SendSasFunction = VOID(WINAPI*)(BOOL);
@@ -157,6 +161,97 @@ std::string BuildErrorJson(const char* error, DWORD error_code = 0) {
return stream.str();
}
bool HasRunningCrossDeskClientProcess() {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
LOG_ERROR("CreateToolhelp32Snapshot failed, error={}", GetLastError());
return true;
}
PROCESSENTRY32W entry{};
entry.dwSize = sizeof(entry);
if (!Process32FirstW(snapshot, &entry)) {
DWORD error = GetLastError();
CloseHandle(snapshot);
if (error != ERROR_NO_MORE_FILES) {
LOG_ERROR("Process32FirstW failed, error={}", error);
return true;
}
return false;
}
do {
if (_wcsicmp(entry.szExeFile, kCrossDeskClientProcessName) == 0) {
CloseHandle(snapshot);
return true;
}
} while (Process32NextW(snapshot, &entry));
DWORD error = GetLastError();
CloseHandle(snapshot);
if (error != ERROR_NO_MORE_FILES) {
LOG_ERROR("Process32NextW failed, error={}", error);
return true;
}
return false;
}
bool GrantCrossDeskServiceStartAccessToAuthenticatedUsers(SC_HANDLE service) {
if (service == nullptr) {
return false;
}
PACL existing_dacl = nullptr;
PACL updated_dacl = nullptr;
PSECURITY_DESCRIPTOR security_descriptor = nullptr;
DWORD error =
GetSecurityInfo(service, SE_SERVICE, DACL_SECURITY_INFORMATION, nullptr,
nullptr, &existing_dacl, nullptr, &security_descriptor);
if (error != ERROR_SUCCESS) {
LOG_ERROR("GetSecurityInfo failed, error={}", error);
return false;
}
BYTE sid_buffer[SECURITY_MAX_SID_SIZE] = {0};
DWORD sid_size = sizeof(sid_buffer);
if (!CreateWellKnownSid(WinAuthenticatedUserSid, nullptr, sid_buffer,
&sid_size)) {
error = GetLastError();
LOG_ERROR("CreateWellKnownSid failed, error={}", error);
LocalFree(security_descriptor);
return false;
}
EXPLICIT_ACCESSW access{};
access.grfAccessPermissions = SERVICE_START | SERVICE_QUERY_STATUS;
access.grfAccessMode = SET_ACCESS;
access.grfInheritance = NO_INHERITANCE;
access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
access.Trustee.ptstrName = reinterpret_cast<LPWSTR>(sid_buffer);
error = SetEntriesInAclW(1, &access, existing_dacl, &updated_dacl);
if (error != ERROR_SUCCESS) {
LOG_ERROR("SetEntriesInAclW failed, error={}", error);
LocalFree(security_descriptor);
return false;
}
error = SetSecurityInfo(service, SE_SERVICE, DACL_SECURITY_INFORMATION,
nullptr, nullptr, updated_dacl, nullptr);
if (error != ERROR_SUCCESS) {
LOG_ERROR("SetSecurityInfo failed, error={}", error);
LocalFree(updated_dacl);
LocalFree(security_descriptor);
return false;
}
LocalFree(updated_dacl);
LocalFree(security_descriptor);
return true;
}
std::string QueryNamedPipeMessage(const std::wstring& pipe_name,
const std::string& command,
DWORD timeout_ms) {
@@ -218,10 +313,12 @@ std::string QueryNamedPipeMessage(const std::wstring& pipe_name,
return std::string(buffer, buffer + bytes_read);
}
std::string BuildSecureDesktopKeyboardIpcCommand(int key_code, bool is_down) {
std::string BuildSecureDesktopKeyboardIpcCommand(int key_code, bool is_down,
uint32_t scan_code,
bool extended) {
std::ostringstream stream;
stream << kSecureDesktopKeyboardIpcCommandPrefix << key_code << ":"
<< (is_down ? 1 : 0);
<< (is_down ? 1 : 0) << ":" << scan_code << ":" << (extended ? 1 : 0);
return stream.str();
}
@@ -233,20 +330,27 @@ std::string BuildSecureDesktopMouseIpcCommand(int x, int y, int wheel,
return stream.str();
}
std::string BuildSecureInputHelperKeyboardCommand(int key_code, bool is_down) {
std::string BuildSecureInputHelperKeyboardCommand(int key_code, bool is_down,
uint32_t scan_code,
bool extended) {
std::ostringstream stream;
stream << kCrossDeskSecureInputKeyboardCommandPrefix << key_code << ":"
<< (is_down ? 1 : 0);
<< (is_down ? 1 : 0) << ":" << scan_code << ":" << (extended ? 1 : 0);
return stream.str();
}
bool ParseSecureDesktopKeyboardIpcCommand(const std::string& command,
int* key_code_out,
bool* is_down_out) {
if (key_code_out == nullptr || is_down_out == nullptr) {
int* key_code_out, bool* is_down_out,
uint32_t* scan_code_out,
bool* extended_out) {
if (key_code_out == nullptr || is_down_out == nullptr ||
scan_code_out == nullptr || extended_out == nullptr) {
return false;
}
*scan_code_out = 0;
*extended_out = false;
if (command.rfind(kSecureDesktopKeyboardIpcCommandPrefix, 0) != 0) {
return false;
}
@@ -263,13 +367,46 @@ bool ParseSecureDesktopKeyboardIpcCommand(const std::string& command,
return false;
}
const std::string state = command.substr(separator + 1);
const size_t scan_separator = command.find(':', separator + 1);
const std::string state =
scan_separator == std::string::npos
? command.substr(separator + 1)
: command.substr(separator + 1, scan_separator - separator - 1);
if (state == "1" || state == "down") {
*is_down_out = true;
} else if (state == "0" || state == "up") {
*is_down_out = false;
} else {
return false;
}
if (scan_separator == std::string::npos) {
return true;
}
if (state == "0" || state == "up") {
*is_down_out = false;
const size_t extended_separator = command.find(':', scan_separator + 1);
const std::string scan_code_str =
extended_separator == std::string::npos
? command.substr(scan_separator + 1)
: command.substr(scan_separator + 1,
extended_separator - scan_separator - 1);
try {
*scan_code_out = static_cast<uint32_t>(std::stoul(scan_code_str));
} catch (...) {
return false;
}
if (extended_separator == std::string::npos) {
return true;
}
const std::string extended_str = command.substr(extended_separator + 1);
if (extended_str == "1" || extended_str == "true") {
*extended_out = true;
return true;
}
if (extended_str == "0" || extended_str == "false") {
*extended_out = false;
return true;
}
return false;
@@ -812,6 +949,10 @@ int CrossDeskServiceHost::InitializeRuntime() {
RefreshSessionState();
EnsureSessionHelper();
ipc_thread_ = std::thread(&CrossDeskServiceHost::IpcServerLoop, this);
if (!console_mode_) {
client_process_monitor_thread_ =
std::thread(&CrossDeskServiceHost::ClientProcessMonitorLoop, this);
}
LOG_INFO("CrossDesk service runtime initialized, session_id={}",
active_session_id_);
return 0;
@@ -825,6 +966,10 @@ void CrossDeskServiceHost::ShutdownRuntime() {
SetEvent(stop_event_);
}
if (client_process_monitor_thread_.joinable()) {
client_process_monitor_thread_.join();
}
if (ipc_thread_.joinable()) {
ipc_thread_.join();
}
@@ -841,6 +986,34 @@ void CrossDeskServiceHost::RequestStop() {
}
}
void CrossDeskServiceHost::ClientProcessMonitorLoop() {
const ULONGLONG monitor_started_at = GetTickCount64();
while (stop_event_ != nullptr) {
DWORD wait_result =
WaitForSingleObject(stop_event_, kCrossDeskClientMonitorIntervalMs);
if (wait_result == WAIT_OBJECT_0) {
return;
}
if (wait_result != WAIT_TIMEOUT) {
continue;
}
if (GetTickCount64() - monitor_started_at <
kCrossDeskClientMonitorStartupGraceMs) {
continue;
}
if (HasRunningCrossDeskClientProcess()) {
continue;
}
LOG_INFO("No crossdesk client process detected, stopping service");
RequestStop();
return;
}
}
void CrossDeskServiceHost::ReportServiceStatus(DWORD current_state,
DWORD win32_exit_code,
DWORD wait_hint) {
@@ -1581,8 +1754,12 @@ std::string CrossDeskServiceHost::HandleIpcCommand(const std::string& command) {
}
int key_code = 0;
bool is_down = false;
if (ParseSecureDesktopKeyboardIpcCommand(normalized, &key_code, &is_down)) {
return SendSecureDesktopKeyboardInput(key_code, is_down);
uint32_t scan_code = 0;
bool extended = false;
if (ParseSecureDesktopKeyboardIpcCommand(normalized, &key_code, &is_down,
&scan_code, &extended)) {
return SendSecureDesktopKeyboardInput(key_code, is_down, scan_code,
extended);
}
return BuildErrorJson("unknown_command");
}
@@ -1797,8 +1974,8 @@ std::string CrossDeskServiceHost::SendSecureAttentionSequence() {
return "{\"ok\":true,\"sent\":\"sas\"}";
}
std::string CrossDeskServiceHost::SendSecureDesktopKeyboardInput(int key_code,
bool is_down) {
std::string CrossDeskServiceHost::SendSecureDesktopKeyboardInput(
int key_code, bool is_down, uint32_t scan_code, bool extended) {
RefreshSessionState();
ReapSecureInputHelper();
EnsureSessionHelper();
@@ -1832,7 +2009,9 @@ std::string CrossDeskServiceHost::SendSecureDesktopKeyboardInput(int key_code,
return QueryNamedPipeMessage(
GetCrossDeskSecureInputHelperPipeName(target_session_id),
BuildSecureInputHelperKeyboardCommand(key_code, is_down), 1000);
BuildSecureInputHelperKeyboardCommand(key_code, is_down, scan_code,
extended),
1000);
}
bool InstallCrossDeskService(const std::wstring& binary_path) {
@@ -1845,7 +2024,7 @@ bool InstallCrossDeskService(const std::wstring& binary_path) {
std::wstring service_command = L"\"" + binary_path + L"\" --service";
SC_HANDLE service = CreateServiceW(
manager, kCrossDeskServiceName, kCrossDeskServiceDisplayName,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL, service_command.c_str(), nullptr, nullptr, nullptr,
nullptr, nullptr);
@@ -1858,14 +2037,15 @@ bool InstallCrossDeskService(const std::wstring& binary_path) {
}
service = OpenServiceW(manager, kCrossDeskServiceName,
SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS);
SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS |
READ_CONTROL | WRITE_DAC);
if (service == nullptr) {
LOG_ERROR("OpenServiceW failed, error={}", GetLastError());
CloseServiceHandle(manager);
return false;
}
if (!ChangeServiceConfigW(service, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
if (!ChangeServiceConfigW(service, SERVICE_NO_CHANGE, SERVICE_DEMAND_START,
SERVICE_NO_CHANGE, service_command.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr,
kCrossDeskServiceDisplayName)) {
@@ -1876,6 +2056,39 @@ bool InstallCrossDeskService(const std::wstring& binary_path) {
}
}
if (!GrantCrossDeskServiceStartAccessToAuthenticatedUsers(service)) {
CloseServiceHandle(service);
CloseServiceHandle(manager);
return false;
}
CloseServiceHandle(service);
CloseServiceHandle(manager);
return true;
}
bool IsCrossDeskServiceInstalled() {
SC_HANDLE manager = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
if (manager == nullptr) {
LOG_ERROR("OpenSCManagerW failed, error={}", GetLastError());
return false;
}
SC_HANDLE service =
OpenServiceW(manager, kCrossDeskServiceName, SERVICE_QUERY_STATUS);
if (service == nullptr) {
DWORD error = GetLastError();
CloseServiceHandle(manager);
if (error == ERROR_SERVICE_DOES_NOT_EXIST) {
return false;
}
if (error == ERROR_ACCESS_DENIED) {
return true;
}
LOG_ERROR("OpenServiceW failed, error={}", error);
return false;
}
CloseServiceHandle(service);
CloseServiceHandle(manager);
return true;
@@ -1891,7 +2104,10 @@ bool StartCrossDeskService() {
SC_HANDLE service =
OpenServiceW(manager, kCrossDeskServiceName, SERVICE_START);
if (service == nullptr) {
LOG_ERROR("OpenServiceW failed, error={}", GetLastError());
DWORD error = GetLastError();
if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
LOG_ERROR("OpenServiceW failed, error={}", error);
}
CloseServiceHandle(manager);
return false;
}
@@ -2008,9 +2224,12 @@ std::string QueryCrossDeskService(const std::string& command,
}
std::string SendCrossDeskSecureDesktopKeyInput(int key_code, bool is_down,
uint32_t scan_code,
bool extended,
DWORD timeout_ms) {
return QueryCrossDeskService(
BuildSecureDesktopKeyboardIpcCommand(key_code, is_down), timeout_ms);
return QueryCrossDeskService(BuildSecureDesktopKeyboardIpcCommand(
key_code, is_down, scan_code, extended),
timeout_ms);
}
std::string SendCrossDeskSecureDesktopMouseInput(int x, int y, int wheel,
+9 -1
View File
@@ -9,6 +9,7 @@
#include <Windows.h>
#include <cstdint>
#include <mutex>
#include <string>
#include <thread>
@@ -33,6 +34,7 @@ class CrossDeskServiceHost {
int InitializeRuntime();
void ShutdownRuntime();
void RequestStop();
void ClientProcessMonitorLoop();
void ReportServiceStatus(DWORD current_state, DWORD win32_exit_code,
DWORD wait_hint);
void IpcServerLoop();
@@ -59,7 +61,9 @@ class CrossDeskServiceHost {
std::string HandleIpcCommand(const std::string& command);
std::string BuildStatusResponse();
std::string SendSecureAttentionSequence();
std::string SendSecureDesktopKeyboardInput(int key_code, bool is_down);
std::string SendSecureDesktopKeyboardInput(int key_code, bool is_down,
uint32_t scan_code = 0,
bool extended = false);
static void WINAPI ServiceMain(DWORD argc, LPWSTR* argv);
static BOOL WINAPI ConsoleControlHandler(DWORD control_type);
@@ -71,6 +75,7 @@ class CrossDeskServiceHost {
SERVICE_STATUS service_status_{};
HANDLE stop_event_ = nullptr;
std::thread ipc_thread_;
std::thread client_process_monitor_thread_;
std::mutex state_mutex_;
DWORD active_session_id_ = 0xFFFFFFFF;
DWORD process_session_id_ = 0xFFFFFFFF;
@@ -128,6 +133,7 @@ class CrossDeskServiceHost {
static CrossDeskServiceHost* instance_;
};
bool IsCrossDeskServiceInstalled();
bool InstallCrossDeskService(const std::wstring& binary_path);
bool UninstallCrossDeskService();
bool StartCrossDeskService();
@@ -135,6 +141,8 @@ bool StopCrossDeskService(DWORD timeout_ms = 5000);
std::string QueryCrossDeskService(const std::string& command,
DWORD timeout_ms = 1000);
std::string SendCrossDeskSecureDesktopKeyInput(int key_code, bool is_down,
uint32_t scan_code = 0,
bool extended = false,
DWORD timeout_ms = 1000);
std::string SendCrossDeskSecureDesktopMouseInput(int x, int y, int wheel,
int flag,
+96 -15
View File
@@ -485,20 +485,56 @@ bool EnsureThreadDesktop(const wchar_t* desktop_name,
return true;
}
int InjectKeyboardInput(int key_code, bool is_down) {
bool PreferSideSpecificVkInjection(int key_code) {
switch (key_code) {
case VK_LSHIFT:
case VK_RSHIFT:
case VK_LCONTROL:
case VK_RCONTROL:
case VK_LMENU:
case VK_RMENU:
case VK_LWIN:
case VK_RWIN:
return true;
default:
return false;
}
}
int InjectKeyboardInput(int key_code, bool is_down, uint32_t scan_code,
bool extended) {
INPUT input = {0};
input.type = INPUT_KEYBOARD;
input.ki.wVk = static_cast<WORD>(key_code);
const UINT scan_code =
MapVirtualKeyW(static_cast<UINT>(key_code), MAPVK_VK_TO_VSC_EX);
if (scan_code != 0) {
const bool prefer_vk = PreferSideSpecificVkInjection(key_code);
const UINT resolved_scan_code =
scan_code != 0
? static_cast<UINT>(scan_code & 0xFF) | (extended ? 0xE000u : 0u)
: MapVirtualKeyW(static_cast<UINT>(key_code), MAPVK_VK_TO_VSC_EX);
if (scan_code != 0 && !prefer_vk) {
input.ki.wVk = 0;
input.ki.wScan = static_cast<WORD>(scan_code & 0xFF);
input.ki.dwFlags |= KEYEVENTF_SCANCODE;
if ((scan_code & 0xFF00) != 0) {
if (extended) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
} else {
input.ki.wVk = static_cast<WORD>(key_code);
if (prefer_vk && resolved_scan_code != 0) {
input.ki.wScan = static_cast<WORD>(resolved_scan_code & 0xFF);
if ((resolved_scan_code & 0xFF00) != 0) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
} else if (resolved_scan_code != 0) {
input.ki.wVk = 0;
input.ki.wScan = static_cast<WORD>(resolved_scan_code & 0xFF);
input.ki.dwFlags |= KEYEVENTF_SCANCODE;
if ((resolved_scan_code & 0xFF00) != 0) {
input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
}
}
}
if (!is_down) {
@@ -514,11 +550,17 @@ int InjectKeyboardInput(int key_code, bool is_down) {
}
bool ParseSecureInputKeyboardCommand(const std::string& command,
int* key_code_out, bool* is_down_out) {
if (key_code_out == nullptr || is_down_out == nullptr) {
int* key_code_out, bool* is_down_out,
uint32_t* scan_code_out,
bool* extended_out) {
if (key_code_out == nullptr || is_down_out == nullptr ||
scan_code_out == nullptr || extended_out == nullptr) {
return false;
}
*scan_code_out = 0;
*extended_out = false;
if (command.rfind(crossdesk::kCrossDeskSecureInputKeyboardCommandPrefix, 0) !=
0) {
return false;
@@ -537,13 +579,46 @@ bool ParseSecureInputKeyboardCommand(const std::string& command,
return false;
}
const std::string state = command.substr(separator + 1);
const size_t scan_separator = command.find(':', separator + 1);
const std::string state =
scan_separator == std::string::npos
? command.substr(separator + 1)
: command.substr(separator + 1, scan_separator - separator - 1);
if (state == "1" || state == "down") {
*is_down_out = true;
} else if (state == "0" || state == "up") {
*is_down_out = false;
} else {
return false;
}
if (scan_separator == std::string::npos) {
return true;
}
if (state == "0" || state == "up") {
*is_down_out = false;
const size_t extended_separator = command.find(':', scan_separator + 1);
const std::string scan_code_str =
extended_separator == std::string::npos
? command.substr(scan_separator + 1)
: command.substr(scan_separator + 1,
extended_separator - scan_separator - 1);
try {
*scan_code_out = static_cast<uint32_t>(std::stoul(scan_code_str));
} catch (...) {
return false;
}
if (extended_separator == std::string::npos) {
return true;
}
const std::string extended_str = command.substr(extended_separator + 1);
if (extended_str == "1" || extended_str == "true") {
*extended_out = true;
return true;
}
if (extended_str == "0" || extended_str == "false") {
*extended_out = false;
return true;
}
return false;
@@ -807,13 +882,17 @@ std::vector<uint8_t> HandleSecureInputHelperCommand(
int key_code = 0;
bool is_down = false;
if (ParseSecureInputKeyboardCommand(command, &key_code, &is_down)) {
const int inject_result = InjectKeyboardInput(key_code, is_down);
uint32_t scan_code = 0;
bool extended = false;
if (ParseSecureInputKeyboardCommand(command, &key_code, &is_down, &scan_code,
&extended)) {
const int inject_result =
InjectKeyboardInput(key_code, is_down, scan_code, extended);
if (inject_result != 0) {
LOG_WARN(
"Secure input helper SendInput failed for key_code={}, is_down={}, "
"err={}",
key_code, is_down, inject_result);
"scan_code={}, extended={}, err={}",
key_code, is_down, scan_code, extended, inject_result);
return BuildTextResponseBytes(BuildErrorJson(
"send_input_failed", static_cast<DWORD>(inject_result)));
}
@@ -823,6 +902,8 @@ std::vector<uint8_t> HandleSecureInputHelperCommand(
json["injected"] = "keyboard";
json["key_code"] = key_code;
json["is_down"] = is_down;
json["scan_code"] = scan_code;
json["extended"] = extended;
json["desktop"] = WideToUtf8(GetCurrentThreadDesktopNameW());
return BuildTextResponseBytes(json.dump());
}
+1 -1
View File
@@ -49,7 +49,7 @@ function setup_platform_settings()
end
if is_config("USE_WAYLAND", true) then
add_links("dbus-1", "pipewire-0.3")
add_links("dbus-1")
add_defines("CROSSDESK_HAS_WAYLAND_CAPTURER=1")
add_existing_include_dirs({
"/usr/include/dbus-1.0",