Compare commits

...
41 Commits
Author SHA1 Message Date
dijunkun 1b6248b05b [fix] position windows before showing to prevent flicker 2026-11-05 18:02:12 +08:00
dijunkun c0fa5e6474 [fix] improve file browser drag cursors and previews 2026-11-05 17:24:10 +08:00
dijunkun 5e34360d25 [fix] handle relative cache paths during device identity initialization 2026-11-05 16:25:05 +08:00
dijunkun 751cf04434 [feat] add dual-pane file transfers and directory browsing, refs #135 2026-11-05 15:27:53 +08:00
dijunkun 6f7c5a29ab [fix] fix OpenGL core rendering and video fallback, refs #138 2026-11-04 23:07:42 +08:00
dijunkun 4d8a650afc [fix] update MiniRTC for NVDEC runtime recovery 2026-11-04 19:41:10 +08:00
dijunkun dba7ac3203 Merge branch 'cli' into mcp 2026-11-04 15:08:35 +08:00
dijunkun 47e16622f8 [fix] expose retry and manual download after update failure 2026-11-04 13:59:06 +08:00
dijunkun 049cc0c8de [fix] avoid PRIME offload on NVIDIA primary displays, refs #137 2026-11-04 12:29:34 +08:00
dijunkun fc1529ee2b [fix] stabilize MCP sessions and extend input controls 2026-11-03 14:19:39 +08:00
dijunkun e1ae449d36 [feat] add MCP terminal views and agent cursor overlays 2026-11-03 03:00:57 +08:00
dijunkun f57b4cc4e3 [feat] add CrossDesk MCP with remote desktop panels 2026-11-03 02:44:55 +08:00
dijunkun 2fab61871e [build] bump CLI version to 0.1.6 2026-11-02 15:47:44 +08:00
dijunkun d776889562 [docs] remove DeskHub bold emphasis and clarify desktop CLI 2026-11-02 15:44:08 +08:00
dijunkun 30d409ff49 [feat] anchor CLI zoom to mouse and simplify view shortcuts 2026-11-02 15:32:16 +08:00
dijunkun 6de7165fb0 [fix] prioritize resolution in CLI previews 2026-11-02 15:18:53 +08:00
dijunkun 28398c0067 [build] bump CLI version to 0.1.5 2026-11-02 12:39:51 +08:00
dijunkun 0188f2e860 [fix] provide host pkg-config for Xcode Cloud dependencies 2026-11-02 12:35:23 +08:00
dijunkun 597c4971cf [feat] add Sixel rendering to CLI 2026-11-02 11:41:25 +08:00
dijunkun b1a0dcdb92 [fix] correct certificate errors and restore automatic reconnection 2026-11-02 11:07:19 +08:00
dijunkun 3382792bfd [fix] prebuild iOS native dependencies before Xcode Cloud archives 2026-11-02 10:34:34 +08:00
dijunkun bfa743fd1b [fix] correct mobile viewport safe areas and zoom reset 2026-11-02 03:17:17 +08:00
dijunkun d051dbb278 [fix] avoid X11 None macro collision in credential recovery 2026-11-02 03:03:53 +08:00
dijunkun 425698e22e [feat] authenticate controller sessions with device keys 2026-11-02 03:00:18 +08:00
dijunkun adcb0f17dd [ui] improve scrollbar spacing in the trusted devices dialog 2026-11-02 02:20:31 +08:00
dijunkun 49717f0f68 [feat] use device keys for server login 2026-11-02 01:15:11 +08:00
dijunkun bb48551d59 [docs] document trusted device setup in READMEs 2026-11-01 23:32:58 +08:00
dijunkun ea4db45dbf [ui] remove redundant IP connection hints 2026-11-01 23:27:17 +08:00
dijunkun 489491008a [feat] add trusted device pairing and management UI 2026-11-01 23:27:17 +08:00
dijunkun e15e2c33bd [feat] add application-layer trusted device authentication 2026-11-01 23:26:48 +08:00
dijunkun b999a01e66 [refactor] share private file storage helpers 2026-11-01 23:25:53 +08:00
dijunkun 53a3df6133 [chore] remove merged MiniRTC credential log patch 2026-11-01 03:26:26 +08:00
dijunkun 3597fd4b3e [fix] include OpenSSL resource symbols in iOS archives 2026-11-01 03:11:18 +08:00
dijunkun c2bfce03f2 [fix] update MiniRTC to correct inbound data bitrate 2026-11-01 02:57:42 +08:00
dijunkun 86d3a8cf72 [fix] adapt iOS keyboard switch widths to localized text 2026-11-01 02:49:59 +08:00
dijunkun 4e2e5b74dd [build] migrate CLI macOS runner and release 0.1.4 2026-10-31 05:34:29 +08:00
dijunkun 7bcda7a6fa [build] bump CLI version to 0.1.3 2026-10-31 05:27:31 +08:00
dijunkun baf48120bb [perf] optimize CLI ANSI output and refresh previews 2026-10-31 05:21:10 +08:00
dijunkun 1b716f3682 [docs] clarify platform and client badges in READMEs 2026-10-31 05:09:41 +08:00
dijunkun b361533d70 [docs] refresh CLI previews and clarify FPS capture 2026-10-31 04:58:15 +08:00
dijunkun af60fb2541 [docs] expand CLI guide with npm setup and previews 2026-10-31 04:49:13 +08:00
137 changed files with 13545 additions and 704 deletions
+2 -2
View File
@@ -17,7 +17,7 @@ jobs:
fail-fast: false
matrix:
include:
- runner: macos-14
- runner: macos-15
target: darwin-arm64
arch: arm64
- runner: macos-15-intel
@@ -97,7 +97,7 @@ jobs:
uses: actions/cache/restore@v5
with:
path: ${{ env.XMAKE_PKG_INSTALLDIR }}
key: cli-deps-v1-${{ matrix.runner }}-${{ matrix.target }}-image${{ steps.runner-image.outputs.version }}-xmake${{ env.XMAKE_VERSION }}-${{ hashFiles('xmake.lua', 'apps/cli/xmake.lua', 'apps/desktop/xmake/options.lua', 'deps/thirdparty/openssl/**', 'deps/submodules/minirtc/xmake.lua', 'deps/submodules/minirtc/thirdparty/**', 'deps/patches/**', '.github/workflows/build-cli.yml') }}
key: cli-deps-v1-${{ matrix.runner }}-${{ matrix.target }}-image${{ steps.runner-image.outputs.version }}-xmake${{ env.XMAKE_VERSION }}-${{ hashFiles('xmake.lua', 'apps/cli/xmake.lua', 'apps/desktop/xmake/options.lua', 'deps/thirdparty/openssl/**', 'deps/submodules/minirtc/xmake.lua', 'deps/submodules/minirtc/thirdparty/**', '.github/workflows/build-cli.yml') }}
- name: Configure macOS
if: runner.os == 'macOS'
run: xmake f -y -p macosx -a ${{ matrix.arch }} -m release --target_minver=13.0 --CROSSDESK_BUILD_DESKTOP=n --CROSSDESK_BUILD_CLI=y --USE_CUDA=n
+5 -4
View File
@@ -276,7 +276,8 @@ jobs:
if [[ "${CROSSDESK_RELEASE_BUILD:-NO}" == "YES" ]]; then
VERIFY_FLAGS+=(--require-release)
fi
python3 apps/ios/scripts/verify_app_bundle.py "${APP_PATH}" "${VERIFY_FLAGS[@]}"
python3 apps/ios/scripts/verify_app_bundle.py "${APP_PATH}" \
--dsym-dir "${DERIVED_DATA}/Build/Products/Release-iphoneos" "${VERIFY_FLAGS[@]}"
xcrun lipo -info "${EXECUTABLE_PATH}"
echo "Minimum iOS version: ${MINIMUM_OS}"
@@ -293,10 +294,10 @@ jobs:
cp apps/ios/licenses/OPEN_SOURCE_NOTICE.txt "${PACKAGE_DIR}/OPEN_SOURCE_NOTICE.txt"
cp "${APP_PATH}/SourceMetadata.json" "${PACKAGE_DIR}/SourceMetadata.json"
DSYM_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/CrossDeskMobile.app.dSYM"
if [[ -d "${DSYM_PATH}" ]]; then
for DSYM_NAME in CrossDeskMobile.app.dSYM OpenSSL.framework.dSYM; do
DSYM_PATH="${DERIVED_DATA}/Build/Products/Release-iphoneos/${DSYM_NAME}"
cp -R "${DSYM_PATH}" "${PACKAGE_DIR}/"
fi
done
ditto -c -k --sequesterRsrc --keepParent "${PACKAGE_DIR}" "${PACKAGE_FILE}"
echo "PACKAGE_FILE=${PACKAGE_FILE}" >> "${GITHUB_ENV}"
+34
View File
@@ -0,0 +1,34 @@
name: MCP package
on:
push:
paths: ['apps/mcp/**', 'apps/cli/package.json', 'apps/cli/npm/platforms.json', '.github/workflows/build-mcp.yml']
pull_request:
paths: ['apps/mcp/**', 'apps/cli/package.json', 'apps/cli/npm/platforms.json', '.github/workflows/build-mcp.yml']
workflow_dispatch:
permissions:
contents: read
jobs:
package:
runs-on: ubuntu-22.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
cache-dependency-path: apps/mcp/package-lock.json
- run: npm ci
working-directory: apps/mcp
- run: npm run build
working-directory: apps/mcp
- run: npm run pack:npm
working-directory: apps/mcp
- uses: actions/upload-artifact@v6
with:
name: mcp-package
path: build/npm-mcp/*.tgz
if-no-files-found: error
+99 -13
View File
@@ -8,7 +8,10 @@
[![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux%20%7C%20iOS%20%7C%20Android%20%7C%20HarmonyOS-blue?style=flat)](#download)
[![Clients](https://img.shields.io/badge/client-Desktop%20%7C%20Mobile%20%7C%20Web%20%7C%20CLI-2ea44f?style=flat)](#download)
[![Release](https://img.shields.io/github/v/release/kunkundi/crossdesk?style=flat)](https://github.com/kunkundi/crossdesk/releases)
[![npm](https://img.shields.io/npm/v/%40chunkdash%2Fcrossdesk-cli?style=flat)](https://www.npmjs.com/package/@chunkdash/crossdesk-cli)
[![Build](https://img.shields.io/github/actions/workflow/status/kunkundi/crossdesk/build.yml?style=flat&label=build)](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml)
[![License: GPL v3](https://img.shields.io/badge/license-GPL--3.0-blue?style=flat)](LICENSE)
[![Stars](https://img.shields.io/github/stars/kunkundi/crossdesk?style=flat&label=stars)](https://github.com/kunkundi/crossdesk/stargazers)
@@ -19,9 +22,9 @@
</div>
CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也能通过 **桌面墙(DeskHub)** 集中查看与操控多台设备。项目基于 [MiniRTC](https://github.com/kunkundi/minirtc),支持自托管。
CrossDesk 让你从电脑、浏览器、手机或终端(桌面 CLI)连接远端电脑,也能通过桌面墙(DeskHub)集中查看与操控多台设备。项目基于 [MiniRTC](https://github.com/kunkundi/minirtc),支持自托管。
[主要功能](#features) · [下载与平台支持](#download) · [快速连接](#quick-start) · [终端 CLI](#cli) · [IP 直连](#lan-direct) · [界面预览](#preview) · [使用指南](docs/USER_GUIDE.md) · [自托管](#self-hosting) · [构建与反馈](#development) · [赞助](#sponsor)
[主要功能](#features) · [下载与平台支持](#download) · [快速连接](#quick-start) · [终端 CLI](#cli) · [IP 直连](#lan-direct) · [可信设备](#trusted-devices) · [界面预览](#preview) · [使用指南](docs/USER_GUIDE.md) · [自托管](#self-hosting) · [构建与反馈](#development) · [赞助](#sponsor)
<a id="features"></a>
@@ -29,10 +32,11 @@ CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也
- **跨平台远控:** Windows、macOS、Linux 桌面互控,浏览器及原生 iOS / Android 客户端访问电脑;鸿蒙 PC 与移动端处于开发阶段。
- **局域网 IP 直连:** 桌面客户端通过 IP、端口和六位密码连接,无需云端信令服务;支持独立端口、记住密码及按模式显示近期设备。
- **终端主控:** 在终端中通过设备 ID 观看和操控远程桌面,支持 ANSI / Kitty 画面、局部缩放与平移、持续本地命令模式及 Pi 扩展,可单独构建。
- **桌面墙:** 多设备实时预览、分组、放大操控、群控和批量文件分发。
- **终端主控:** 在终端中通过设备 ID 观看和操控远程桌面,支持 ANSI / Kitty / Sixel 画面、局部缩放与平移、持续本地命令模式及 Pi 扩展,可单独构建。
- 桌面墙:多设备实时预览、分组、放大操控、群控和批量文件分发。
- **画面与声音:** H.264 / AV1、硬件编解码、远端音频,以及会话内画质和帧率调整;可用能力随平台与设备而异。
- **日常协作:** 多显示器切换、键鼠与组合键、文本剪贴板、文件传输。
- **可信设备:** 桌面端可选开启可信设备限制,在连接密码之外校验设备身份;支持复制、粘贴配对信息,提前添加允许访问本机的设备。
- **部署与运维:** P2P 直连、TURN 中继、SRTP 媒体加密、自托管,以及 Windows 登录前远控和 Linux 无头运行。
<a id="download"></a>
@@ -51,7 +55,7 @@ CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也
| 鸿蒙 PC(开发版) | **控制 / 被控**;API 26,arm64;使用 DevEco 构建并签名 HAP,仍在进行真机验收 |
| 鸿蒙手机 / 平板(开发版) | **仅控制**;API 20+,arm64;使用 DevEco 构建并签名 HAP,仍在进行真机验收 |
| Web | **仅控制**;支持 WebRTC 的浏览器;无需在控制端安装客户端 |
| 终端 CLI(开发版) | **仅控制**;构建目标为 macOS / Linux(x64、arm64)和 Windows(x64);从源码构建,平台验收范围见 [CLI 说明](apps/cli/README.md) |
| 终端 CLI(开发版) | **仅控制**;分发目标为 macOS / Linux(x64、arm64)和 Windows(x64);通过 [npm 安装](#cli-npm) 或从源码构建,平台验收范围见 [CLI 说明](apps/cli/README.md) |
系统要求按当前源码与构建配置整理,具体安装包以对应 Release 说明为准。各客户端的功能范围见 [终端 CLI](#cli) 与 [移动端与鸿蒙](#mobile)。
@@ -69,7 +73,7 @@ CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也
2. **发起连接。** 在另一台电脑的 CrossDesk 中输入被控电脑的 9 位 ID,点击“连接”;也可使用原生移动端或 [Web 客户端](https://web.crossdesk.cn/)。
3. **验证密码。** 输入被控电脑当前的连接密码,等待远程画面出现。桌面端可勾选“记住密码”,后续从“近期连接”重连。
使用自建服务器时,两端需要接入同一服务。更多连接、密码及浏览器操作见 [使用指南](docs/USER_GUIDE.md#quick-start);连接失败、黑屏或无法操作键鼠时先查阅 [常见问题](docs/FAQ.md)。
使用自建服务器时,两端需要接入同一服务。新版桌面端使用设备密钥登录服务器,请先升级服务端:新 ID 注册时绑定公钥,旧 ID 首次升级时验证原密码后绑定;绑定后,针对该 ID 的错误密码尝试不会阻塞正常签名登录。远程控制仍需输入连接密码;新版控制端也验证设备签名,密码失败按控制端及“控制端 → 目标”计数,不再累计被控端的总失败次数,避免他人的错误尝试锁住目标。身份备份与兼容要求见 [设备登录说明](docs/connection-architecture.md#41-id-模式)。更多连接、密码及浏览器操作见 [使用指南](docs/USER_GUIDE.md#quick-start);连接失败、黑屏或无法操作键鼠时先查阅 [常见问题](docs/FAQ.md)。
<a id="lan-direct"></a>
@@ -81,6 +85,24 @@ CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也
两台电脑需要在局域网内可互相访问;网络可以有外网,也可以没有外网,直连会话不依赖云端信令服务。主窗口可直接切换本机 IP、修改端口和密码,默认开启所有 IP 接口监听,支持 IPv4 和 IPv6,支持通过 VPN 等接口连接,可在设置的“网络连接”中调整;关闭设置中的“启用 IP 直连”会停止监听、断开 IP 直连会话并隐藏模式按钮。详见 [IP 直连使用指南](docs/USER_GUIDE.md#lan-direct)。
<a id="trusted-devices"></a>
### 仅允许可信设备连接(可选)
桌面端的可信设备限制**默认关闭**,适用于 ID 连接和 IP 直连。开启后,控制端仍需通过原有密码验证,并持有可信名单中设备的配对私钥;仅知道 ID 和密码不能通过这项限制。
1. **在控制端复制配对信息。** 打开 **设置 → 常规 → 隐私保护 → 管理可信设备**,在 **本机配对信息** 中点击 **复制配对信息**。
2. **在被控端添加控制端。** 打开同一管理界面,将收到的信息粘贴到 **添加可信设备** 输入框,点击 **添加** 即可加入,无需再次确认,也无需先建立远程连接。
3. **在被控端开启限制。** 返回设置,勾选 **仅允许可信设备控制** 并保存。之后照常通过 ID 或 IP 发起连接、验证密码。
配对信息只包含公钥、设备名称和 ID,不含私钥或密码,应通过可信渠道传递。添加后可点击 **查看指纹** 与控制端核对;也允许添加本机,同一公钥不会重复加入。信任是单向的,如需互相控制,应在双方分别添加对方。
添加和移除会立即保存;开启限制时,**移除信任** 会断开对应设备的会话,名单为空则拒绝所有控制端。也可以从管理界面的已连接设备中添加完成身份验证的控制端。
**兼容范围:** 两端均需使用支持可信设备认证的客户端。不支持该协议的旧版客户端无法连接开启限制的被控端;当前 CLI、iOS、Android 和鸿蒙移动端尚未实现该认证。关闭限制时沿用原有连接方式。
设备登录与配对共用缓存目录 `identity.json` 中的私钥,可信名单保存在配置目录的 `trusted-devices/devices.json`。迁移本机身份时应同时备份 ID/密码缓存与 `identity.json`;已绑定的 ID 无法仅凭密码恢复登录。清空整个缓存目录后需重新登记 ID,并让其他设备重新信任本机。备份、迁移及认证机制见 [可信设备技术说明](docs/connection-architecture.md#43-可选可信设备认证)。
<a id="preview"></a>
## 界面预览
@@ -118,7 +140,7 @@ CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也
## 会话操作与设置
远程会话支持显示器切换、画质与帧率调整、声音、文本剪贴板同步和文件传输。工具栏还可查看网络状态、控制隐私屏;桌面设置中可配置 IP 直连开关、编码、中继、自托管与桌面墙画面预算。
远程会话支持显示器切换、画质与帧率调整、声音、文本剪贴板同步和文件传输。工具栏还可查看网络状态、控制隐私屏;桌面设置中可配置 IP 直连开关、可信设备限制、编码、中继、自托管与桌面墙画面预算。
- [会话操作](docs/USER_GUIDE.md#session):工具栏、文本剪贴板、文件保存和隐私屏。
- [客户端设置与更新](docs/USER_GUIDE.md#settings):常规设置、桌面墙传输及版本检查。
@@ -128,7 +150,39 @@ CrossDesk 让你从电脑、浏览器、手机或终端连接远端电脑,也
## 终端客户端 CLI
`crossdesk-cli` 在终端中通过 9 位设备 ID 连接被控电脑,默认只读、静音。普通终端使用 ANSI 字符画面,支持 Kitty 图形协议的终端可显示像素画面;可切换显示器、调整画质、放大细节和平移,也可明确开启键鼠控制。CLI 可以独立于桌面 GUI 构建,被控电脑仍需运行 CrossDesk 并提供可捕获的图形会话,信令服务需支持 `cli` 临时身份注册。
`crossdesk-cli` 在终端中通过 9 位设备 ID 连接被控电脑,默认只读、静音。普通终端使用 ANSI 字符画面,支持 Kitty 或 Sixel 图形协议的终端可显示像素画面;可切换显示器、调整画质、放大细节和平移,也可明确开启键鼠控制。CLI 可以独立于桌面 GUI 构建,被控电脑仍需运行 CrossDesk 并提供可捕获的图形会话,信令服务需支持 `cli` 临时身份注册。
### 画面预览
| ANSI 字符画面 | Kitty 协议像素画面 |
| --- | --- |
| <img src="docs/images/cli-ansi-overview.png" width="480" alt="CrossDesk CLI 的 ANSI 四象限全景:顶部显示只读模式和连接状态,底部显示操作快捷键" /> | <img src="docs/images/cli-kitty-overview.png" width="480" alt="CrossDesk CLI 的 Kitty 协议全景:同一远程桌面以像素画面显示,保留状态栏和操作快捷键" /> |
| 用彩色字符显示桌面轮廓,适合普通终端;查看局部可用 `+/-` 或滚轮以鼠标位置缩放。 | 直接显示像素画面,适合支持 Kitty 图形协议的终端,如 Ghostty。 |
两图采集于 **2026-10-31**,来自同一授权设备的实际只读连接,以 128 × 40 字符视口还原 CLI 的 ANSI / Kitty 协议输出。图中 FPS 是采集时的实际输出计数,静止画面下 ANSI 无变化可显示 `FPS 0`。图示为输出渲染,终端实窗效果受字体、窗口大小及协议支持影响;采集方法见 [图示来源](docs/images/README.md#cli-captures)。
<a id="cli-npm"></a>
### 通过 npm 安装并连接
准备 **Node.js 22 或以上**及 npm,从 [@chunkdash/crossdesk-cli](https://www.npmjs.com/package/@chunkdash/crossdesk-cli) 安装。npm 会按操作系统与 CPU 架构选择原生程序,无需安装 Xmake 或 C++ 编译工具链。
```sh
npm install -g @chunkdash/crossdesk-cli@latest
crossdesk-cli doctor --json
crossdesk-cli 123456789
```
将 `123456789` 换成被控电脑的 9 位设备 ID,连接时按提示隐藏输入密码。默认只读、静音;`doctor` 仅检查本机环境,不发起连接。更新到最新版时,重新执行上面的 `npm install -g @chunkdash/crossdesk-cli@latest`。
无需全局安装时,也可使用 `npx`,首次运行会下载对应平台包:
```sh
npx @chunkdash/crossdesk-cli@latest doctor --json
npx @chunkdash/crossdesk-cli@latest 123456789
```
请安装统一入口 `@chunkdash/crossdesk-cli`,并保留 npm 的可选依赖,不要添加 `--omit=optional`;仅安装平台包不会注册 `crossdesk-cli` 命令。平台运行要求、旧包迁移及故障排查见 [npm 分发说明](apps/cli/docs/npm-distribution.md)。
### 从源码构建并连接
@@ -146,7 +200,34 @@ xmake run crossdesk-cli 123456789
已有仓库时从仓库根目录执行依赖准备及后续命令。将 `123456789` 换成被控电脑的 ID,密码在连接时隐藏输入。`doctor` 只检查本机环境,不发起连接。仓库默认构建桌面端;以上配置只构建 CLI,需要同时构建桌面端时将 `CROSSDESK_BUILD_DESKTOP` 设为 `y`。产物位于 `build/<platform>/<arch>/release/`。
ANSI 全景受终端字符网格限制。阅读小字可添加 `--quality high --zoom native`,或进入画面后按 `d` 查看细节;`--renderer kitty` 需要终端支持对应协议。显示、鼠标报告、SSH 和终端兼容性见 [使用说明](apps/cli/docs/terminal-client.md)。
### 选择画面与连接参数
默认 `--renderer auto` 按 Kitty → Sixel → ANSI 的顺序选择。macOS「终端」等普通终端可显式选择 `ansi`;支持对应图形协议的终端可选择 `kitty` 或 `sixel`。显式像素模式探测失败时会报错,此时改用 `ansi`。Xshell 是否能显示像素图片取决于终端自身的协议支持,CLI 无法单方面补齐。
以下示例使用 npm 全局安装后的命令;从源码构建时,可在仓库根目录将 `crossdesk-cli` 替换为 `xmake run crossdesk-cli`。
```sh
# 普通终端:以细节模式查看局部
crossdesk-cli 123456789 --renderer ansi --zoom native
# 支持 Kitty 图形协议的终端:显示像素画面
crossdesk-cli 123456789 --renderer kitty
# 降低远端画质与刷新请求
crossdesk-cli 123456789 --quality balanced --fps 8
```
| 参数 | 用途 |
| --- | --- |
| `--renderer auto\|ansi\|kitty\|sixel` | 自动选择、字符画面或像素画面;默认 `auto` |
| `--zoom native` | 从原始细节模式开始;`--zoom 2` 表示相对全景放大 2 倍 |
| `--quality low\|balanced\|high\|ultra` | 请求最高 360p / 720p / 1080p / 2160p;默认 `high`,实际画质由被控端决定 |
| `--fps 8` | 固定本地输出目标和相应远端预览请求;允许 1–30,默认本地目标为 30,未指定时远端供帧会自适应 |
| `--display 1` | 选择第二个显示器,索引从 `0` 开始 |
| `--control` | 连接后直接启用键鼠控制;省略时默认只读 |
| `--server your-server.example --port 9099` | 使用自建信令服务,两端需接入同一服务 |
ANSI 全景受字符网格限制,提高画质不能让整屏小字变得清晰;可扩大终端、缩小字体,再用 `+/-` 或滚轮查看局部,按 `f` 回到全景并重置平移。顶部状态栏显示模式、连接进度、渲染器、缩放、实时输出 FPS 和网络信息,窄窗口会省略部分字段。通过 SSH 使用时分配 PTY(`ssh -t`);tmux / screen 使用 ANSI。更多显示、鼠标报告和兼容性说明见 [终端使用指南](apps/cli/docs/terminal-client.md)。
### 控制、查看与退出
@@ -156,11 +237,16 @@ ANSI 全景受终端字符网格限制。阅读小字可添加 `--quality high -
| 控制模式 | 键鼠输入传给远端;`Ctrl+]` 进入本地命令模式并暂停远端输入 |
| 本地命令模式 | 执行命令后持续保持;`c` 选择手动返回后是否启用控制,`q` 退出 CLI |
| `Esc` / `Ctrl+C` | 在本地命令模式中手动返回所选的控制或只读模式 |
| `+` / `=` / `-` | 在只读或本地命令模式中放大 / 缩小 |
| `d` / `f` | 在只读或本地命令模式中切换原始细节 / 完整桌面;只读时也可点击目标进入细节 |
| `+` / `=` / `-` | 在只读或本地命令模式中以鼠标位置放大 / 缩小 |
| 滚轮 / 点击 | 只读模式中,滚轮以鼠标位置缩放;点击目标进入原始细节 |
| `f` | 在只读或本地命令模式中恢复完整桌面,同时重置倍率、平移和细节模式 |
| 方向键 / `i j k l` | 在只读或本地命令模式中平移;`i` 上、`j` 左、`k` 下、`l` 右 |
`Ctrl+]` 模式不会因为缩放、平移或按 `c` 自动结束。状态栏中的 `CONTROL PAUSED` / `READ ONLY` 表示返回后是否启用控制。控制模式中的普通 `c`、`q` 和 `Ctrl+C` 会发送到远端,需要先按 `Ctrl+]` 执行本地操作;再次按 `Ctrl+]` 也可返回,若返回控制模式则向远端发送一次该组合键。
鼠标下的画面内容在缩放时尽量保持原位,到达桌面边缘时限制裁剪范围;没有有效鼠标位置时沿用当前中心。本地命令模式中鼠标仅更新缩放锚点,点击和滚轮不执行视图操作。
**控制模式下退出:先按 `Ctrl+]`,再按 `q`。** 普通 `c`、`q` 和 `Ctrl+C` 在控制模式中会发送到远端。
`Ctrl+]` 模式不会因为缩放、平移或按 `c` 自动结束。状态栏中的 `CONTROL PAUSED` / `READ ONLY` 表示返回后是否启用控制;按 `Esc` / `Ctrl+C` 手动返回。再次按 `Ctrl+]` 也可返回,若返回控制模式则向远端发送一次该组合键。
### Pi 扩展与功能范围
@@ -173,7 +259,7 @@ pi -e ./apps/cli/plugins/pi/index.ts
其他平台将 `CROSSDESK_CLI` 改为原生可执行文件的绝对路径。在 Pi 中输入 `/crossdesk` 或 `/crossdesk 123456789`,按提示输入密码。安装要求与验证范围见 [Pi 扩展说明](apps/cli/docs/terminal-client.md#pi-扩展)。
CLI 当前仅提供 ID 连接与远程观看 / 输入,不提供 IP 直连、音频播放、文件传输或剪贴板同步。macOS arm64 已完成本地构建和连接验证;Linux / Windows 完整运行、SSH / Kitty 实机显示及真实 Pi TUI 的验收范围见 [验证记录](apps/cli/docs/validation.md)。平台构建配置与 npm 打包流程不代表全部平台已验收或包已发布。
CLI 当前仅提供 ID 连接与远程观看 / 输入,不提供 IP 直连、音频播放、文件传输或剪贴板同步,也暂不支持连接开启[可信设备限制](#trusted-devices)的被控端。macOS arm64 已完成本地构建和连接验证;Linux / Windows 完整运行、SSH / Kitty / Sixel 实机显示及真实 Pi TUI 的验收范围见 [验证记录](apps/cli/docs/validation.md)。平台构建与 npm 发布不代表全部平台已完成实机验收。
[CLI 文档入口](apps/cli/README.md) · [终端使用与故障排查](apps/cli/docs/terminal-client.md) · [桥接协议](apps/cli/docs/bridge-protocol.md) · [npm 打包与分发](apps/cli/docs/npm-distribution.md)
+99 -13
View File
@@ -8,7 +8,10 @@
[![Platforms](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux%20%7C%20iOS%20%7C%20Android%20%7C%20HarmonyOS-blue?style=flat)](#download)
[![Clients](https://img.shields.io/badge/client-Desktop%20%7C%20Mobile%20%7C%20Web%20%7C%20CLI-2ea44f?style=flat)](#download)
[![Release](https://img.shields.io/github/v/release/kunkundi/crossdesk?style=flat)](https://github.com/kunkundi/crossdesk/releases)
[![npm](https://img.shields.io/npm/v/%40chunkdash%2Fcrossdesk-cli?style=flat)](https://www.npmjs.com/package/@chunkdash/crossdesk-cli)
[![Build](https://img.shields.io/github/actions/workflow/status/kunkundi/crossdesk/build.yml?style=flat&label=build)](https://github.com/kunkundi/crossdesk/actions/workflows/build.yml)
[![License: GPL v3](https://img.shields.io/badge/license-GPL--3.0-blue?style=flat)](LICENSE)
[![Stars](https://img.shields.io/github/stars/kunkundi/crossdesk?style=flat&label=stars)](https://github.com/kunkundi/crossdesk/stargazers)
@@ -19,9 +22,9 @@
</div>
CrossDesk connects your computers from desktop, browser, mobile, and terminal clients, with **DeskHub** for viewing and controlling multiple devices together. It is built on [MiniRTC](https://github.com/kunkundi/minirtc) and supports self-hosting.
CrossDesk connects your computers from desktop, browser, mobile, and terminal clients, with DeskHub for viewing and controlling multiple devices together. It is built on [MiniRTC](https://github.com/kunkundi/minirtc) and supports self-hosting.
[Features](#features) · [Download and platforms](#download) · [Quick start](#quick-start) · [Terminal CLI](#cli) · [Direct IP](#lan-direct) · [Preview](#preview) · [User guide](docs/USER_GUIDE_EN.md) · [Self-hosting](#self-hosting) · [Build and feedback](#development) · [Sponsor](#sponsor)
[Features](#features) · [Download and platforms](#download) · [Quick start](#quick-start) · [Terminal CLI](#cli) · [Direct IP](#lan-direct) · [Trusted devices](#trusted-devices) · [Preview](#preview) · [User guide](docs/USER_GUIDE_EN.md) · [Self-hosting](#self-hosting) · [Build and feedback](#development) · [Sponsor](#sponsor)
<a id="features"></a>
@@ -29,10 +32,11 @@ CrossDesk connects your computers from desktop, browser, mobile, and terminal cl
- **Cross-platform access:** control Windows, macOS, and Linux desktops from computers, browsers, or native iOS / Android clients. HarmonyOS PC and mobile clients are in development.
- **Direct IP over LAN:** connect desktop clients using an IP address, port, and six-character password without a cloud signaling service. Each local IP has its own port; passwords can be remembered and recent devices are separated by mode.
- **Terminal controller:** view and control remote desktops by device ID, with ANSI / Kitty rendering, zoom and pan, persistent local command mode, a Pi extension, and a build independent of the desktop GUI.
- **DeskHub:** live multi-device previews, groups, enlarged control, group input, and batch file distribution.
- **Terminal controller:** view and control remote desktops by device ID, with ANSI / Kitty / Sixel rendering, zoom and pan, persistent local command mode, a Pi extension, and a build independent of the desktop GUI.
- DeskHub: live multi-device previews, groups, enlarged control, group input, and batch file distribution.
- **Video and audio:** H.264 / AV1, hardware codecs, remote audio, and in-session quality and frame-rate controls. Capabilities depend on the platform and device.
- **Everyday controls:** monitor switching, keyboard and mouse input, shortcuts, text clipboard, and file transfer.
- **Trusted devices:** optionally restrict desktop access to trusted device identities in addition to the connection password. Copy and paste pairing information to approve devices before they connect.
- **Deployment:** direct P2P connections, TURN relay, SRTP media encryption, self-hosting, Windows access before sign-in, and Linux headless operation.
<a id="download"></a>
@@ -51,7 +55,7 @@ Get a package matching your OS and CPU architecture from the [website](https://w
| HarmonyOS PC (development) | **Control + host**. API 26, arm64; build and sign a HAP with DevEco; physical-device validation is ongoing |
| HarmonyOS phones / tablets (development) | **Control only**. API 20+, arm64; build and sign a HAP with DevEco; physical-device validation is ongoing |
| Web | **Control only**. A WebRTC-capable browser; no client installation on the controlling device |
| Terminal CLI (development) | **Control only**. Build targets: macOS / Linux (x64, arm64) and Windows (x64). Build from source; see the [CLI guide](apps/cli/README.md) (Chinese) for platform validation status |
| Terminal CLI (development) | **Control only**. Distribution targets: macOS / Linux (x64, arm64) and Windows (x64). [Install from npm](#cli-npm) or build from source; see the [CLI guide](apps/cli/README.md) (Chinese) for platform validation status |
Requirements follow the current source and build configuration. Check the release notes for the downloaded package. Client capabilities are summarized under [Terminal CLI](#cli) and [Mobile and HarmonyOS](#mobile).
@@ -69,7 +73,7 @@ Requirements follow the current source and build configuration. Check the releas
2. **Connect.** On another computer, enter the host's 9-digit ID and click **Connect**. Native mobile clients and the [Web Client](https://web.crossdesk.cn/) can also connect.
3. **Verify the password.** Enter the host's current connection password and wait for the desktop to appear. On desktop, select **Remember password** to reconnect later from **Recent Connections**.
For self-hosting, both ends must use the same service. See the [user guide](docs/USER_GUIDE_EN.md#quick-start) for connection, password, and browser controls, or the [FAQ](docs/FAQ.md#english) for failed connections, blank video, and input problems.
For self-hosting, both ends must use the same service. Upgrade the server before using the new desktop client: device login uses a private key, with its public key bound at registration or after a one-time password check for an existing ID. Once bound, wrong-password attempts against that ID cannot block valid signature login. Remote control still requires the connection password. Signed controllers have separate per-controller and controller-to-destination failure budgets; failures from one controller no longer lock the destination for others. See the [device login guide](docs/connection-architecture.md#41-id-模式) (Chinese) for identity backups and compatibility, the [user guide](docs/USER_GUIDE_EN.md#quick-start) for controls, or the [FAQ](docs/FAQ.md#english) for connection problems.
<a id="lan-direct"></a>
@@ -81,6 +85,24 @@ For self-hosting, both ends must use the same service. See the [user guide](docs
Both computers must be reachable over the LAN. Internet access may be available or absent; direct sessions do not depend on a cloud signaling service. The main window lets you select the local IP, edit its port, and change the password. **Listen on all IP interfaces** is enabled by default for IPv4, IPv6, VPN, and other local interfaces on a shared port; change it under **Settings → General → Network**. Disabling **Enable direct IP** stops listeners, disconnects direct IP sessions, and hides the mode button. See the [direct IP guide](docs/USER_GUIDE_EN.md#lan-direct).
<a id="trusted-devices"></a>
### Allow only trusted devices (optional)
The desktop trusted-device restriction is **off by default** and applies to both ID and direct IP connections. When enabled, the controller must pass the existing password verification and prove possession of a pairing private key recognized by the host. Knowing the ID and password alone does not satisfy this restriction.
1. **Copy pairing information on the controller.** Open **Settings → General → Privacy → Manage trusted devices**. Under **This device’s pairing info**, click **Copy pairing info**.
2. **Add the controller on the host.** Open the same management dialog, paste the information into **Add a trusted device**, and click **Add**. It is saved immediately, with no second confirmation or prior remote connection required.
3. **Enable the restriction on the host.** Return to settings, select **Only allow trusted devices**, and save. Connect by ID or IP and verify the password as usual.
Pairing information contains only the public key, device name, and ID, with no private key or password. Exchange it through a trusted channel. After adding a device, use **View fingerprint** to compare it with the controller. You can also add the local device; the same public key is not added twice. Trust is one-way: to control each other, add the other device on both computers.
Adding or removing a device takes effect immediately. With the restriction enabled, **Remove trust** disconnects that device’s sessions, and an empty list rejects all controllers. The dialog also lets you add connected controllers that have completed identity verification.
**Compatibility:** both clients must support trusted-device authentication. Older clients without the protocol cannot connect to a restricted host. The CLI, iOS, Android, and HarmonyOS mobile clients do not currently implement it. With the restriction disabled, the existing connection behavior applies.
Device login and pairing share the private key in the cache directory's `identity.json`; the trusted list is stored in `trusted-devices/devices.json` in the configuration directory. Back up the ID/password cache and `identity.json` together when migrating a device: a bound ID cannot be recovered with its password alone. Clearing the entire cache requires a new ID and renewed trust from other devices. See the [trusted-device technical guide](docs/connection-architecture.md#43-可选可信设备认证) (Chinese) for details.
<a id="preview"></a>
## Preview
@@ -118,7 +140,7 @@ Group control sends input to all connected devices; closing DeskHub disconnects
## Session controls and settings
Remote sessions support monitor switching, video quality and frame-rate controls, audio, text clipboard synchronization, and file transfer. The toolbar also provides network statistics and privacy screen controls. Desktop settings configure direct IP availability, codecs, relay, self-hosting, and the DeskHub video budget.
Remote sessions support monitor switching, video quality and frame-rate controls, audio, text clipboard synchronization, and file transfer. The toolbar also provides network statistics and privacy screen controls. Desktop settings configure direct IP availability, trusted-device restrictions, codecs, relay, self-hosting, and the DeskHub video budget.
- [Session controls](docs/USER_GUIDE_EN.md#session): toolbar, text clipboard, received files, and privacy screens.
- [Client settings and updates](docs/USER_GUIDE_EN.md#settings): general options, DeskHub video settings, and version checks.
@@ -128,7 +150,39 @@ Remote sessions support monitor switching, video quality and frame-rate controls
## Terminal client CLI
`crossdesk-cli` connects to a host by its 9-digit device ID and starts in read-only, silent mode. Standard terminals use ANSI character rendering; terminals supporting the Kitty graphics protocol can display pixel graphics. The CLI supports monitor selection, quality settings, detail zoom, panning, and optional keyboard/mouse control. It builds independently of the desktop GUI. The host still needs CrossDesk and a capturable graphical session, and the signaling service must support temporary `cli` identities.
`crossdesk-cli` connects to a host by its 9-digit device ID and starts in read-only, silent mode. Standard terminals use ANSI character rendering; terminals supporting the Kitty or Sixel graphics protocol can display pixel graphics. The CLI supports monitor selection, quality settings, detail zoom, panning, and optional keyboard/mouse control. It builds independently of the desktop GUI. The host still needs CrossDesk and a capturable graphical session, and the signaling service must support temporary `cli` identities.
### Display preview
| ANSI character rendering | Kitty pixel graphics |
| --- | --- |
| <img src="docs/images/cli-ansi-overview.png" width="480" alt="CrossDesk CLI ANSI quadrant overview, with read-only mode and connection status at the top and shortcuts at the bottom" /> | <img src="docs/images/cli-kitty-overview.png" width="480" alt="CrossDesk CLI Kitty protocol overview of the same remote desktop, rendered as pixels with the status bar and shortcuts" /> |
| Colored characters show the desktop in standard terminals; use `+/-` or the wheel to zoom at the mouse position. | Pixel graphics display the desktop in terminals supporting the Kitty graphics protocol, such as Ghostty. |
Both images were captured on **2026-10-31** from real read-only connections to the same authorized host. They render the CLI's ANSI / Kitty protocol output in a 128 × 40 character viewport. FPS counts actual output during capture; an unchanged ANSI view can show `FPS 0`. Actual terminal appearance depends on the font, window size, and protocol support. See [capture notes](docs/images/README.md#cli-captures) for the method.
<a id="cli-npm"></a>
### Install from npm and connect
Install **Node.js 22 or later** and npm, then get [@chunkdash/crossdesk-cli](https://www.npmjs.com/package/@chunkdash/crossdesk-cli). npm selects the native executable for your OS and CPU architecture; Xmake and a C++ toolchain are not required.
```sh
npm install -g @chunkdash/crossdesk-cli@latest
crossdesk-cli doctor --json
crossdesk-cli 123456789
```
Replace `123456789` with the host's 9-digit device ID and enter its password at the hidden prompt. Connections start in read-only, silent mode; `doctor` checks the local environment without connecting. To update, run `npm install -g @chunkdash/crossdesk-cli@latest` again.
You can also use `npx` without a global installation. The first run downloads the matching platform package:
```sh
npx @chunkdash/crossdesk-cli@latest doctor --json
npx @chunkdash/crossdesk-cli@latest 123456789
```
Install the main `@chunkdash/crossdesk-cli` package with npm optional dependencies enabled; do not add `--omit=optional`. Installing a platform package alone does not register the `crossdesk-cli` command. See the [npm distribution guide](apps/cli/docs/npm-distribution.md) (Chinese) for platform requirements, migration from older packages, and troubleshooting.
### Build and connect
@@ -146,7 +200,34 @@ xmake run crossdesk-cli 123456789
For an existing checkout, run the dependency preparation and subsequent commands from the repository root. Replace `123456789` with the host's ID; the password prompt hides your input. `doctor` reports the local environment without connecting. The repository builds the desktop client by default; this configuration builds only the CLI. Set `CROSSDESK_BUILD_DESKTOP=y` to also build the desktop client. Binaries are placed in `build/<platform>/<arch>/release/`.
An ANSI overview is limited by the terminal's character grid. Add `--quality high --zoom native`, or press `d` in the viewer, to inspect small text. `--renderer kitty` requires a terminal supporting that protocol. See the [terminal guide](apps/cli/docs/terminal-client.md) (Chinese) for rendering, mouse reporting, SSH, and terminal compatibility.
### Rendering and connection options
The default `--renderer auto` selects Kitty, then Sixel, then ANSI according to terminal capability replies. Use `ansi` in standard terminals such as macOS Terminal, or `kitty` / `sixel` in terminals supporting the corresponding protocol. Explicit pixel modes report an error if the probe fails; use `ansi` in that case. Sixel output alone does not guarantee Xshell compatibility: the terminal itself must support the protocol.
These examples use the command installed globally by npm. For a source build, replace `crossdesk-cli` with `xmake run crossdesk-cli` and run it from the repository root.
```sh
# Standard terminal: start with a detail view
crossdesk-cli 123456789 --renderer ansi --zoom native
# Terminal supporting the Kitty graphics protocol: display pixel graphics
crossdesk-cli 123456789 --renderer kitty
# Request lower video quality and refresh rate
crossdesk-cli 123456789 --quality balanced --fps 8
```
| Option | Purpose |
| --- | --- |
| `--renderer auto\|ansi\|kitty\|sixel` | Automatic selection, character rendering, or pixel graphics; default: `auto` |
| `--zoom native` | Start in native detail mode; `--zoom 2` zooms to twice the full-desktop scale |
| `--quality low\|balanced\|high\|ultra` | Request up to 360p / 720p / 1080p / 2160p; default: `high`. The host determines actual quality |
| `--fps 8` | Fix the local output target and corresponding remote preview request; accepts 1–30. The default local target is 30, with adaptive remote requests when omitted |
| `--display 1` | Select the second monitor; indexes start at `0` |
| `--control` | Enable keyboard/mouse control immediately after connecting; omitted by default for read-only viewing |
| `--server your-server.example --port 9099` | Use a self-hosted signaling service; both ends must use the same service |
ANSI overviews are limited by the character grid: higher video quality alone cannot make full-desktop text legible. Enlarge the terminal or reduce its font size, use `+/-` or the wheel for detail, and `f` to restore the full desktop and reset panning. The top bar shows input mode, connection progress, renderer, zoom, live output FPS, and network information; narrow windows omit some fields. Allocate a PTY over SSH (`ssh -t`), and use ANSI inside tmux / screen. See the [terminal guide](apps/cli/docs/terminal-client.md) (Chinese) for rendering, mouse reporting, and compatibility details.
### Control, navigation, and exit
@@ -156,11 +237,16 @@ An ANSI overview is limited by the terminal's character grid. Add `--quality hig
| Control mode | Keyboard/mouse input goes to the host; `Ctrl+]` enters local command mode and pauses remote input |
| Local command mode | Stays active after commands; `c` selects whether control resumes when you leave; `q` exits the CLI |
| `Esc` / `Ctrl+C` | Manually leave local command mode and return to the selected control or read-only mode |
| `+` / `=` / `-` | Zoom in / out in read-only or local command mode |
| `d` / `f` | Switch to native detail / full-desktop view in read-only or local command mode; clicking in read-only mode also opens detail at that point |
| `+` / `=` / `-` | Zoom in / out at the mouse position in read-only or local command mode |
| Wheel / click | In read-only mode, zoom at the mouse position with the wheel; click a point to open native detail |
| `f` | Restore the full desktop and reset zoom, pan, and native detail mode in read-only or local command mode |
| Arrow keys / `i j k l` | Pan in read-only or local command mode: `i` up, `j` left, `k` down, `l` right |
Zooming, panning, or pressing `c` does not end `Ctrl+]` mode. The status bar shows `CONTROL PAUSED` / `READ ONLY` to indicate whether control will resume. In control mode, ordinary `c`, `q`, and `Ctrl+C` go to the host, so enter local command mode first for local actions. Pressing `Ctrl+]` again also leaves local mode and forwards that shortcut if control resumes.
Zoom keeps the content under the pointer in place where possible, clamping the crop at desktop edges. Without a valid mouse position, zoom uses the current center. In local command mode, mouse reports only update the zoom anchor; clicks and the wheel do not change the view.
**To quit while controlling the host, press `Ctrl+]`, then `q`.** Ordinary `c`, `q`, and `Ctrl+C` go to the host in control mode.
Zooming, panning, or pressing `c` does not end `Ctrl+]` mode. The status bar shows `CONTROL PAUSED` / `READ ONLY` to indicate whether control will resume; press `Esc` / `Ctrl+C` to return manually. Pressing `Ctrl+]` again also leaves local mode and forwards that shortcut if control resumes.
### Pi extension and feature scope
@@ -173,7 +259,7 @@ pi -e ./apps/cli/plugins/pi/index.ts
On other platforms, set `CROSSDESK_CLI` to the absolute path of the native executable. Enter `/crossdesk` or `/crossdesk 123456789` in Pi and follow the password prompt. See the [Pi extension guide](apps/cli/docs/terminal-client.md#pi-扩展) (Chinese) for requirements and validation scope.
The CLI currently provides ID-based viewing and input, without direct IP connections, audio playback, file transfer, or clipboard synchronization. Local builds and remote connections have been validated on macOS arm64. See the [validation record](apps/cli/docs/validation.md) (Chinese) for the remaining Linux / Windows, SSH / Kitty terminal, and actual Pi TUI checks. Platform build configurations and npm packaging do not establish that every platform is validated or that packages have been published.
The CLI currently provides ID-based viewing and input, without direct IP connections, audio playback, file transfer, or clipboard synchronization. It also cannot yet connect to hosts with [trusted-device restrictions](#trusted-devices) enabled. Local builds and remote connections have been validated on macOS arm64. See the [validation record](apps/cli/docs/validation.md) (Chinese) for the remaining Linux / Windows, SSH / Kitty / Sixel terminal, and actual Pi TUI checks. Platform builds and npm publication do not establish that every platform has been validated on real devices.
[CLI documentation](apps/cli/README.md) · [Terminal usage and troubleshooting](apps/cli/docs/terminal-client.md) · [Bridge protocol](apps/cli/docs/bridge-protocol.md) · [npm packaging and distribution](apps/cli/docs/npm-distribution.md) (detailed guides in Chinese)
@@ -34,7 +34,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
private View settingsUpdateDot, aboutUpdateDot, settingsUpdateButton, aboutUpdateRow;
private TextView aboutUpdateLabel;
private boolean navigatingBack;
private FrameLayout canvas;
private FrameLayout canvas, safeArea;
private LinearLayout root;
private EditText remote;
private TextView status, signalBadge, identitySummary;
@@ -133,10 +133,11 @@ public final class MainActivity extends Activity implements NativeSession.Listen
settingsUpdateDot=null;aboutUpdateDot=null;settingsUpdateButton=null;aboutUpdateRow=null;aboutUpdateLabel=null;
previewSwitch=null;clearPreviewsButton=null;previewCleanupError=null;previewCards.clear();recentGrid=null;
canvas=new FrameLayout(this);canvas.setBackgroundColor(dark?Color.BLACK:BACKGROUND);
FrameLayout safeArea=new FrameLayout(this);canvas.addView(safeArea,new FrameLayout.LayoutParams(-1,-1));
safeArea=new FrameLayout(this);canvas.addView(safeArea,new FrameLayout.LayoutParams(-1,-1));
root=ui.pageColumn(dark?0:nextPage.equals("home")?1200:720);
safeArea.addView(root,new FrameLayout.LayoutParams(-1,-1,Gravity.TOP|Gravity.CENTER_HORIZONTAL));
safeArea.setOnApplyWindowInsetsListener((view,insets)->{
if(dark&&(pictureInPictureUi||isInPictureInPictureMode())){view.setPadding(0,0,0,0);return insets;}
if(dark&&android.os.Build.VERSION.SDK_INT>=30){
android.graphics.Insets bars=insets.getInsets(WindowInsets.Type.systemBars()|WindowInsets.Type.displayCutout());
view.setPadding(bars.left,bars.top,bars.right,bars.bottom);
@@ -328,7 +329,10 @@ public final class MainActivity extends Activity implements NativeSession.Listen
dialog.setContentView(card);dialog.setCanceledOnTouchOutside(false);dialog.setOnCancelListener(d->end(""));Window w=dialog.getWindow();if(w!=null){w.setBackgroundDrawableResource(android.R.color.transparent);w.setDimAmount(.08f);}dialog.show();if(w!=null)w.setLayout(dp(292),-2);
}
private void sessionScreen(boolean autoLandscape){
installRoot("session",true);remoteOrientation.begin(autoLandscape,!isTablet()&&!isInMultiWindowMode());video=new RemoteVideoView(this,session);video.setRelative(preferences.getBoolean("relativeMouse",true));canvas.addView(video,0,new FrameLayout.LayoutParams(-1,-1));
installRoot("session",true);remoteOrientation.begin(autoLandscape,!isTablet()&&!isInMultiWindowMode());video=new RemoteVideoView(this,session);video.setRelative(preferences.getBoolean("relativeMouse",true));
// Video, cursor and touch input must share the area inside system bars
// and display cutouts; fitting to the outer canvas hides image edges.
safeArea.addView(video,0,new FrameLayout.LayoutParams(-1,-1));
controls=new SessionControls(this,ui,new SessionControls.Actions(){
public void disconnect(){confirmDisconnect();}public void display(){selectDisplay();}public void clipboard(){MainActivity.this.clipboard();}
public void sendFile(){chooseFile();}public void saveFile(){saveReceivedFile();}public void secureAttention(){MainActivity.this.secureAttention();}
@@ -803,6 +807,7 @@ public final class MainActivity extends Activity implements NativeSession.Listen
if(value){releaseKeys();hideKeyboard();pageHost.finish();if(disconnectDialog!=null)disconnectDialog.dismiss();if(remoteUpdateDialog!=null)remoteUpdateDialog.dismiss();}
if(controls!=null)controls.setPictureInPicture(value);
if(video!=null)video.setPictureInPicture(value);
if(safeArea!=null)safeArea.requestApplyInsets();
}
@Override protected void onUserLeaveHint(){
super.onUserLeaveHint();
@@ -42,6 +42,9 @@ final class RemoteViewport {
void zoomBy(float factor, float focusX, float focusY) {
if (baseWidth == 0 || baseHeight == 0 || !Float.isFinite(factor) || factor <= 0) return;
float nextScale = clamp(scale * factor, 1, MAXIMUM_SCALE);
// Returning to fit must clear cursor-edge panning too, including a
// pinch that starts at 1x with an already shifted image.
if (nextScale == 1) { reset(); return; }
float ratio = nextScale / scale;
float focusFromCenterX = focusX - (baseLeft + baseWidth / 2f);
float focusFromCenterY = focusY - (baseTop + baseHeight / 2f);
@@ -75,10 +78,9 @@ final class RemoteViewport {
}
void finishGesture() {
if (!isZoomed()) {
scale = 1;
constrainOffset();
}
// Ordinary pointer gestures at 1x retain edge panning. Only a zoom
// snapping back to its minimum restores the complete centered image.
if (scale > 1 && !isZoomed()) reset();
}
void reset() { scale = 1; offsetX = offsetY = 0; edgePanned = false; }
+64 -5
View File
@@ -1,15 +1,39 @@
# CrossDesk CLI
CrossDesk 的终端主控客户端,源码位于本仓库的 `apps/cli`。通过真实 MiniRTC ID 会话观看远程桌面;默认只读、静音。包含 ANSI 象限字符画面、局部放大和平移、Kitty 图形后端,以及 Pi 自定义 TUI 扩展。
CrossDesk 的终端主控客户端,源码位于本仓库的 `apps/cli`。通过真实 MiniRTC ID 会话观看远程桌面;默认只读、静音。包含 ANSI 象限字符画面、局部放大和平移、Kitty / Sixel 图形后端,以及 Pi 自定义 TUI 扩展。
分发目标为 macOS / Linux(x64、arm64)和 Windows(x64)的原生终端客户端。npm 包发布后可统一使用:
## 画面预览
| ANSI 字符画面 | Kitty 协议像素画面 |
| --- | --- |
| <img src="../../docs/images/cli-ansi-overview.png" width="480" alt="CrossDesk CLI 的 ANSI 全景输出,包含只读状态栏与快捷键提示" /> | <img src="../../docs/images/cli-kitty-overview.png" width="480" alt="CrossDesk CLI 的 Kitty 像素全景输出,显示同一远程桌面" /> |
图示来自 **2026-10-31** 的实际只读连接,通过伪终端采集并渲染协议输出;来源与边界见 [图示说明](../../docs/images/README.md#cli-captures)。默认 `auto` 依次选择 Kitty、Sixel、ANSI;普通终端可指定 `--renderer ansi`,支持对应协议的终端可指定 `--renderer kitty` 或 `--renderer sixel`。显式像素模式需要通过能力探测;增加 Sixel 输出不代表所有 Xshell 版本均可显示图片,终端本身也必须支持该协议。ANSI 全景适合查看桌面轮廓,阅读小字需进入细节模式。
## 安装与连接
### 通过 npm 安装
需要 **Node.js 22 或以上**和 npm。统一入口为 [@chunkdash/crossdesk-cli](https://www.npmjs.com/package/@chunkdash/crossdesk-cli),分发目标为 macOS / Linux(x64、arm64)和 Windows(x64)。安装时自动选择对应的原生程序,无需 Xmake 或 C++ 编译工具链:
```sh
npm install -g @chunkdash/crossdesk-cli@latest
crossdesk-cli doctor --json
crossdesk-cli 123456789
```
将示例 ID 替换为被控电脑的 9 位 ID,按提示隐藏输入密码。`doctor` 仅检查本机环境,不发起连接。更新到最新版时重新执行上述安装命令。
无需全局安装时,使用 `npx`,首次运行会下载对应平台包:
```sh
npx @chunkdash/crossdesk-cli@latest doctor --json
npx @chunkdash/crossdesk-cli@latest 123456789
```
统一入口包为 `@chunkdash/crossdesk-cli`,安装后命令仍为 `crossdesk-cli`。五个平台依赖使用 `@chunkdash/crossdesk-cli-*`,由启动器自动选择。旧的无 scope 平台包不属于这套依赖;仅安装平台包不会注册命令。是否可安装以 npm 上完整版本的发布结果为准,三端实机验收尚未全部完成。运行要求、打包、本地安装与发布步骤见 [npm 分发](docs/npm-distribution.md)。
安装后命令为 `crossdesk-cli`。五个平台依赖使用 `@chunkdash/crossdesk-cli-*`,由启动器自动选择;请保留 npm 的可选依赖,不要使用 `--omit=optional`。旧的无 scope 平台包不属于这套依赖,仅安装平台包不会注册命令。三端实机验收尚未全部完成;运行要求、旧包迁移、打包与发布步骤见 [npm 分发](docs/npm-distribution.md)。
### 从源码构建
在 CrossDesk 仓库根目录执行以下命令构建 CLI:
@@ -21,8 +45,43 @@ xmake run crossdesk-cli doctor --json
xmake run crossdesk-cli 123456789 --quality high --zoom native
```
`crossdesk-cli <设备ID> [选项]` 为默认连接方式,`view <设备ID>` 保留为兼容别名。最后一个设备 ID 是格式示例,使用时替换为你有权访问的设备。密码通过隐藏提示输入。只读时 `c` 开启控制、`q` 或 `Ctrl+C` 退出;点击目标或按 `d` 进入原始细节模式,`+/-` 或滚轮缩放,方向键或 `i` 上、`j` 左、`k` 下、`l` 右平移,`f` 回到完整桌面。任何模式下先按 `Ctrl+]` 进入持续本地命令模式,再按 `c` 选择返回后的控制状态、`q` 退出或视图按键连续调整画面,`Esc` / `Ctrl+C` 手动返回。控制模式中的 `Ctrl+T`、`Ctrl+C` 和普通按键均传给远端。ANSI 全屏缩略图仍受字符网格限制,默认请求 high 画质,阅读小字建议使用细节模式;支持 Kitty 协议的终端可使用 `--renderer kitty` 获得像素画面。
构建后可直接运行 `build/<platform>/<arch>/release/crossdesk-cli`,也可将对应目录加入 PATH;Windows 的文件名为 `crossdesk-cli.exe`。
### 常用连接命令
以下示例适用于 npm 全局安装,或已将原生程序加入 PATH 的环境。`crossdesk-cli <设备ID> [选项]` 为默认连接方式,`view <设备ID>` 保留为兼容别名。设备 ID 是格式示例,使用时替换为你有权访问的设备,密码通过隐藏提示输入:
```sh
crossdesk-cli 123456789 --renderer kitty
crossdesk-cli 123456789 --renderer sixel --fps 8
crossdesk-cli 123456789 --renderer ansi --zoom native
crossdesk-cli 123456789 --quality balanced --fps 8
crossdesk-cli 123456789 --display 1
```
默认请求 `high` 画质(最高 1920 × 1080)和清晰度优先策略,`--display` 的索引从 `0` 开始。交互 CLI 默认本地输出目标为 30 FPS,远端供帧会随输出耗时自适应;显式 `--fps` 固定目标和相应预览请求,各帧率下均优先保持分辨率,实际画质与帧率仍取决于设备、终端与链路。更多参数见 [主 README](../../README.md#cli) 和 [终端使用指南](docs/terminal-client.md)。
## 查看、控制与退出
| 操作 | 按键 |
| --- | --- |
| 开启远端控制 | 只读模式下按 `c` |
| 缩放 | 只读或本地命令模式下用 `+` / `=` / `-` 以鼠标位置缩放;只读时也可用滚轮 |
| 回到全景 | 只读或本地命令模式下按 `f`,同时重置倍率、平移和细节模式 |
| 平移 | 只读或本地命令模式下用方向键或 `i` 上、`j` 左、`k` 下、`l` 右 |
| 原始细节 | 只读时点击目标位置,或以 `--zoom native` 启动 |
| 暂停远端输入并进入本地命令模式 | `Ctrl+]` |
| 选择返回后的控制状态 | 本地命令模式下按 `c`,再按 `Esc` / `Ctrl+C` 返回 |
| 退出连接 | 只读模式下按 `q` / `Ctrl+C`;控制模式下先按 `Ctrl+]`,再按 `q` |
缩放尽量保持鼠标下的画面内容原位;没有有效鼠标位置时沿用当前中心。底部提示随模式和窗口宽度调整,`Zoom at mouse` 表示鼠标锚点缩放,`Full view` / `Full` 表示恢复全景。
本地命令模式在缩放、平移和按 `c` 后持续保持,直到手动返回。此模式中鼠标仅更新缩放锚点,点击和滚轮不执行视图操作。控制模式中的 `Ctrl+T`、`Ctrl+C` 和普通按键均传给远端。再次按 `Ctrl+]` 也可离开本地命令模式,若返回控制模式则同时向远端发送该组合键。
## 更多文档与功能范围
- [MCP 服务与实时面板](../mcp/README.md):Agent 截图和结构化远程操作,不要求控制端安装桌面客户端。
- [原生自动化协议](docs/automation-protocol.md):独立 `agent --stdio` 模式。
- [构建、使用、Pi 安装和故障排查](docs/terminal-client.md)
- [私有桥接协议](docs/bridge-protocol.md)
- [实际验证记录](docs/validation.md)
@@ -30,4 +89,4 @@ xmake run crossdesk-cli 123456789 --quality high --zoom native
CLI 仅作为控制端,每次连接通过服务端获得新的 `cli-xxxxxxxxx` 临时 ID。使用前须部署支持 `cli` 注册的 crossdesk-server;旧服务端不会回退为普通设备身份。
终端 I/O 包含 POSIX(Linux/macOS)和 Windows Console / ConPTY 实现。macOS arm64 已完整构建,之前已连接真实被控端验证 ANSI 观看与预览协商。Linux / Windows 全量构建和真实连接、SSH/Kitty 实机显示及真实 Pi TUI 仍需验收;交叉编译检查不等于完整运行验证。此项目不创建被控端虚拟桌面,不提供音频播放、文件传输、剪贴板同步或 MCP 服务。
终端 I/O 包含 POSIX(Linux/macOS)和 Windows Console / ConPTY 实现。macOS arm64 已完整构建,之前已连接真实被控端验证 ANSI 观看与预览协商。Linux / Windows 全量构建和真实连接、SSH/Kitty/Sixel 实机显示及真实 Pi TUI 仍需验收;交叉编译检查不等于完整运行验证。CLI 不创建被控端虚拟桌面,不提供音频播放、文件传输或剪贴板同步;MCP 服务由独立的 `apps/mcp` 包提供。
+835
View File
@@ -0,0 +1,835 @@
#include "agent.h"
#include "automation_protocol.h"
#include "terminal_io.h"
#include "video_server.h"
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <deque>
#include <frame_image.h>
#include <future>
#include <memory>
#include <stdexcept>
#include <terminal_renderer.h>
namespace crossdesk::cli {
namespace {
using nlohmann::json;
using namespace automation;
using Clock = std::chrono::steady_clock;
using Ms = std::chrono::milliseconds;
constexpr size_t kMaxResponse = 4 * 1024 * 1024;
int64_t Age(Clock::time_point queued) {
return std::chrono::duration_cast<Ms>(Clock::now() - queued).count();
}
class Responses {
public:
explicit Responses(int fd) : fd_(fd), mode_(fd, true) {}
void Put(json j) {
auto line = j.dump(-1, ' ', false, json::error_handler_t::replace) + '\n';
if (line.size() > kMaxResponse || queue_.size() >= 64 ||
bytes_ + line.size() > 8 * 1024 * 1024)
throw std::runtime_error("OUTPUT_BACKPRESSURE");
if (queue_.empty())
progressed_ = Clock::now();
bytes_ += line.size();
queue_.push_back(std::move(line));
}
bool Empty() const { return queue_.empty(); }
void Pump() {
if (Empty())
return;
const auto &s = queue_.front();
auto n = Write(fd_, s.data() + offset_,
std::min(size_t(16384), s.size() - offset_));
if (n > 0) {
offset_ += n;
bytes_ -= n;
progressed_ = Clock::now();
if (offset_ == s.size()) {
queue_.pop_front();
offset_ = 0;
}
} else if (n < 0 && errno != EAGAIN && errno != EINTR)
throw std::runtime_error("OUTPUT_CLOSED");
if (Clock::now() - progressed_ > std::chrono::seconds(10))
throw std::runtime_error("OUTPUT_TIMEOUT");
}
private:
int fd_;
NonBlocking mode_;
std::deque<std::string> queue_;
size_t offset_ = 0, bytes_ = 0;
Clock::time_point progressed_ = Clock::now();
};
struct Observation {
std::string id;
uint64_t generation, epoch;
int width, height, source_width, source_height;
ImageRegion region;
Clock::time_point created;
};
struct Capture {
json id, request;
bool preview = false;
Clock::time_point deadline;
};
struct Encoding {
Capture capture;
std::shared_ptr<const DecodedFrame> frame;
uint64_t epoch;
bool cancelled = false;
std::future<FrameImage> result;
};
struct TerminalEncoding {
json id;
uint64_t generation, epoch;
Clock::time_point queued;
bool cancelled = false;
std::future<terminal::Grid> result;
};
struct RunningAction {
json id;
std::string operation;
uint64_t generation = 0, epoch = 0;
std::vector<Step> steps;
size_t next = 0;
bool submitted = false;
Clock::time_point started;
};
struct Record {
std::string operation, arguments;
json result;
Clock::time_point created;
};
class Automation {
public:
Automation(int output, SessionOptions options, int password, bool video)
: output_(output), options_(std::move(options)), password_fd_(password),
video_(video ? std::make_unique<VideoServer>() : nullptr) {}
~Automation() { session_.Disconnect(); }
int Run() {
NonBlocking input(0);
std::string buffer;
bool eof = false, quit = false;
auto until = Clock::time_point::max();
while (!interrupted) {
Tick();
output_.Pump();
PumpVideo();
if (!quit) {
char bytes[8192];
const auto n = Read(0, bytes, sizeof(bytes));
if (n > 0)
buffer.append(bytes, size_t(n));
else if (!n)
eof = true;
else if (errno != EAGAIN && errno != EINTR)
eof = true;
for (int count = 0; count < 16 && !quit; ++count) {
const auto end = buffer.find('\n');
if ((end == std::string::npos && buffer.size() > 65536) ||
(end != std::string::npos && end > 65536)) {
Error(nullptr, "MESSAGE_TOO_LARGE");
quit = true;
break;
}
if (end == std::string::npos)
break;
auto request = ParseBoundedJson(buffer.substr(0, end));
buffer.erase(0, end + 1);
quit = Handle(request);
}
if (!quit && buffer.size() > 128 * 1024) {
Error(nullptr, "INPUT_BACKPRESSURE");
quit = true;
}
if (eof && buffer.find('\n') == std::string::npos) {
if (!buffer.empty())
Error(nullptr, "INCOMPLETE_MESSAGE");
quit = true;
}
}
if (quit && until == Clock::time_point::max()) {
Stop("CANCELLED");
session_.Disconnect();
PumpVideo();
until = Clock::now() + std::chrono::seconds(2);
}
if (quit && (output_.Empty() || Clock::now() >= until))
break;
WaitIo(quit ? -1 : 0, output_.Empty() ? -1 : output_fd(), 5);
}
return interrupted ? 130 : 0;
}
void SetOutputFd(int fd) { output_fd_ = fd; }
private:
int output_fd() const { return output_fd_; }
json Status() const {
auto result = session_.Status();
result["video"] = {{"decode_path", decode_path_}, {"decoder", decoder_}};
result["video_output"]["enabled"] = video_ && video_->Enabled();
result["video_output"]["protocol"] =
decode_path_ == "minirtc" ? "nv12/1" : "h264-annexb/1";
if (video_) result["video_output"].update(video_->Status());
if (decode_path_ == "minirtc") {
result["video_output"]["received"] = frame_ ? frame_->frame_id : 0;
result["video_output"]["waiting_keyframe"] = false;
result["video_output"].erase("has_sps");
result["video_output"].erase("has_pps");
}
result["transport_state"] = result["state"];
result["geometry_epoch"] = epoch_;
result["cursor"] = Cursor();
result["human_paused"] = paused_;
result["control_allowed"] = allowed_;
result["frame_age_ms"] = frame_ ? json(Age(frame_->queued)) : json(nullptr);
result["source_size"] =
frame_ ? json{{"width", frame_->width}, {"height", frame_->height}}
: json(nullptr);
if (session_.Connected())
result["state"] = frame_ && frame_->generation == session_.Generation()
? "ready"
: "waiting_frame";
return result;
}
json Cursor() const {
const bool visible = cursor_visible_ && frame_ && session_.Connected() &&
frame_->generation == session_.Generation() && allowed_ && !paused_ &&
session_.ControlEnabled();
return {{"type", "cursor"}, {"visible", visible},
{"x", cursor_x_}, {"y", cursor_y_},
{"generation", session_.Generation()}, {"geometry_epoch", epoch_},
{"width", frame_ ? frame_->width : 0},
{"height", frame_ ? frame_->height : 0}};
}
void PumpVideo() {
if (!video_) return;
const auto generation = session_.Generation();
const bool connected = session_.Connected();
const bool decoded = decode_path_ == "minirtc";
if (generation != video_generation_ || connected != video_connected_) {
video_->Bind(generation, decoded, connected);
video_generation_ = generation;
video_connected_ = connected;
last_video_frame_ = 0;
}
const auto cursor = Cursor();
if (cursor != video_cursor_) {
video_->Cursor(cursor);
video_cursor_ = cursor;
}
const bool enabled = video_->Enabled();
const bool key = video_->TakeKeyframeRequest();
if (enabled != video_enabled_ || key) {
session_.SetVideoOutput(enabled && !decoded, key && !decoded);
video_enabled_ = enabled;
last_video_frame_ = 0;
}
if (!enabled) return;
if (decoded) {
if (frame_ && frame_->generation == generation && Age(frame_->queued) <= 2000 &&
frame_->frame_id != last_video_frame_) {
video_->Submit(frame_);
last_video_frame_ = frame_->frame_id;
}
} else {
for (int count = 0; count < 8; ++count) {
auto frame = session_.TakeEncodedVideo();
if (!frame) break;
video_->Submit(std::move(*frame));
}
}
}
void Reply(const json &id, json value) {
output_.Put({{"id", id}, {"ok", true}, {"result", std::move(value)}});
}
void Error(const json &id, const std::string &code,
bool side_effect = false) {
output_.Put({{"id", id},
{"ok", false},
{"error",
{{"code", code},
{"retryable", !side_effect && (code == "FRAME_TIMEOUT" ||
code == "BUSY")},
{"side_effect_possible", side_effect}}}});
}
void FinishAction(const char *error = nullptr) {
if (!action_)
return;
session_.ReleaseInput();
json result = {
{"status", error ? (action_->submitted ? "outcome_unknown"
: "failed_before_submit")
: "submitted"},
{"operation_id", action_->operation},
{"generation", action_->generation},
{"after_frame_id", frame_ ? frame_->frame_id : 0},
{"side_effect_possible", action_->submitted},
{"retryable", false}};
if (error)
result["error"] = error;
for (auto &record : records_)
if (record.operation == action_->operation) {
record.result = result;
break;
}
Reply(action_->id, result);
action_.reset();
}
void Stop(const char *code) {
FinishAction(code);
for (const auto &capture : captures_)
Error(capture.id, code);
captures_.clear();
if (encoding_ && !encoding_->cancelled) {
Error(encoding_->capture.id, code);
encoding_->cancelled = true;
}
if (terminal_encoding_ && !terminal_encoding_->cancelled) {
Error(terminal_encoding_->id, code);
terminal_encoding_->cancelled = true;
}
observations_.clear();
preview_ = json();
}
void Tick() {
session_.Tick();
// Recycle only uniquely owned frames; an encoder/video worker may still be
// reading the old pixels. Save geometry before Take can swap its storage.
if (auto f = session_.TakeFrame(frame_ && frame_.use_count() == 1 ? frame_.get() : nullptr)) {
if (!frame_ || f->generation != frame_->generation ||
f->width != frame_->width || f->height != frame_->height) {
++epoch_;
cursor_visible_ = false;
observations_.clear();
preview_ = json();
}
frame_ = std::make_shared<DecodedFrame>(std::move(*f));
}
if (frame_ && frame_->generation != session_.Generation()) {
frame_.reset();
++epoch_;
cursor_visible_ = false;
observations_.clear();
preview_ = json();
}
if (action_) {
if (!session_.Connected() || !frame_ || paused_ || !allowed_ ||
action_->generation != session_.Generation() ||
action_->epoch != epoch_)
FinishAction("SESSION_CHANGED");
while (action_ && action_->next < action_->steps.size() &&
Age(action_->started) >= action_->steps[action_->next].delay) {
const auto &step = action_->steps[action_->next++];
action_->submitted =
true; // A failed send may still have reached the peer.
const bool sent =
step.kind == StepKind::Pointer
? session_.Pointer(step.x, step.y, step.flag, step.wheel)
: step.kind == StepKind::Key ? session_.Key(step.key, step.down)
: session_.Text(step.text);
if (!sent) {
FinishAction("ACTION_OUTCOME_UNKNOWN");
break;
}
if (step.kind == StepKind::Pointer) {
cursor_x_ = step.x;
cursor_y_ = step.y;
cursor_visible_ = true;
}
action_->submitted = true;
}
if (action_ && action_->next == action_->steps.size())
FinishAction();
}
if (terminal_encoding_ &&
terminal_encoding_->result.wait_for(Ms(0)) == std::future_status::ready) {
auto job = std::move(terminal_encoding_);
try {
auto grid = job->result.get();
if (job->cancelled) {
// Consume the worker result without replying twice.
} else if (!session_.Connected() || job->generation != session_.Generation() ||
job->epoch != epoch_)
Error(job->id, "STALE_OBSERVATION");
else if (Age(job->queued) > 2000)
Error(job->id, "FRAME_TIMEOUT");
else {
json cursor = nullptr;
if (Cursor()["visible"].get<bool>()) {
const int x = grid.content.x + std::clamp(
int(cursor_x_ * grid.content.width), 0, grid.content.width - 1);
const int y = grid.content.y + std::clamp(
int(cursor_y_ * grid.content.height), 0, grid.content.height - 1);
cursor = {{"column", x / grid.samples_x}, {"row", y / grid.samples_y}};
}
Reply(job->id, {{"columns", grid.viewport.columns}, {"rows", grid.viewport.rows},
{"lines", terminal::Lines(grid)}, {"cursor", cursor},
{"generation", job->generation}, {"geometry_epoch", job->epoch}});
}
} catch (...) { if (!job->cancelled) Error(job->id, "FRAME_RENDER_FAILED"); }
}
if (encoding_ &&
encoding_->result.wait_for(Ms(0)) == std::future_status::ready) {
auto job = std::move(encoding_);
try {
auto image = job->result.get();
if (!job->cancelled) {
if (!frame_ || job->epoch != epoch_ ||
job->frame->generation != session_.Generation())
Error(job->capture.id, "STALE_OBSERVATION");
else if (Age(job->frame->queued) > 2000)
Error(job->capture.id, "FRAME_TIMEOUT");
else {
const auto &f = *job->frame;
json meta = {
{"generation", f.generation},
{"geometry_epoch", job->epoch},
{"frame_id", f.frame_id},
{"display_index", session_.Status()["display"]},
{"source_size", {{"width", f.width}, {"height", f.height}}},
{"source_rect",
{{"x", image.region.x},
{"y", image.region.y},
{"width", image.region.width},
{"height", image.region.height}}},
{"image_size",
{{"width", image.width}, {"height", image.height}}},
{"frame_age_ms", Age(f.queued)}};
json result = {{"mime_type", "image/png"},
{"data", ImageBase64(image.png)},
{"metadata", meta}};
if (job->capture.preview) {
preview_ = result;
preview_time_ = f.queued;
preview_edge_ =
Number(job->capture.request, "max_edge", 64, 960, 960);
} else {
const auto id = "obs_" + std::to_string(f.generation) + "_" +
std::to_string(++observation_sequence_);
result["metadata"]["observation_id"] = id;
if (observations_.size() >= 32)
observations_.pop_front();
observations_.push_back(
{id, f.generation, job->epoch, image.width, image.height,
int(f.width), int(f.height), image.region, Clock::now()});
}
Reply(job->capture.id, std::move(result));
}
}
} catch (...) {
if (!job->cancelled)
Error(job->capture.id, "IMAGE_ENCODING_FAILED");
}
}
for (auto it = captures_.begin(); it != captures_.end();) {
if (it->request.contains("generation") &&
Sequence(it->request, "generation") != session_.Generation()) {
Error(it->id, "STALE_OBSERVATION");
it = captures_.erase(it);
} else if (Clock::now() > it->deadline || session_.Finished()) {
Error(it->id, session_.Finished() ? "NOT_READY" : "FRAME_TIMEOUT");
it = captures_.erase(it);
} else
++it;
}
if (!encoding_ && !captures_.empty() && frame_ && session_.Connected() &&
Age(frame_->queued) <= 2000) {
auto it = std::find_if(
captures_.begin(), captures_.end(), [&](const Capture &c) {
return !c.request.contains("after_frame_id") ||
frame_->frame_id > Sequence(c.request, "after_frame_id");
});
if (it != captures_.end()) {
auto capture = *it;
const auto capture_id = capture.id;
captures_.erase(it);
try {
Encode(std::move(capture));
} catch (...) {
Error(capture_id, "INVALID_REGION");
}
}
}
}
void Encode(Capture capture) {
ImageRegion region;
if (capture.request.contains("region")) {
const auto &r = capture.request["region"];
Fields(r, {"x", "y", "width", "height"});
region = {Number(r, "x", 0, int(frame_->width) - 1, -1),
Number(r, "y", 0, int(frame_->height) - 1, -1),
Number(r, "width", 1, frame_->width, -1),
Number(r, "height", 1, frame_->height, -1)};
if (region.x < 0 || region.y < 0 || region.width < 1 ||
region.height < 1 || region.x > int(frame_->width) - region.width ||
region.y > int(frame_->height) - region.height)
throw std::invalid_argument("INVALID_REGION");
}
const int edge =
Number(capture.request, "max_edge", 64, capture.preview ? 960 : 2048,
capture.preview ? 960 : 1280);
auto job = std::make_unique<Encoding>();
job->capture = capture;
job->frame = frame_;
job->epoch = epoch_;
job->result = std::async(std::launch::async, [frame = frame_, region, edge,
preview = capture.preview] {
return EncodeFrameImage(*frame, region, edge,
preview ? 256 * 1024 : 2 * 1024 * 1024);
});
encoding_ = std::move(job);
}
void CaptureFrame(const json &j, const json &id, bool preview) {
Fields(j, {"id", "method", "region", "max_edge", "after_frame_id",
"generation", "timeout_ms"});
if (!session_.Connected())
throw std::invalid_argument("NOT_READY");
Number(j, "max_edge", 64, preview ? 960 : 2048, preview ? 960 : 1280);
if (preview && j.contains("region"))
throw std::invalid_argument("INVALID_REQUEST");
if (j.contains("after_frame_id") && !j.contains("generation"))
throw std::invalid_argument("GENERATION_REQUIRED");
Sequence(j, "after_frame_id");
if (j.contains("generation") &&
Sequence(j, "generation") != session_.Generation())
throw std::invalid_argument("STALE_OBSERVATION");
if (preview && frame_ && j.contains("after_frame_id") &&
Sequence(j, "after_frame_id") >= frame_->frame_id) {
Reply(id, {{"unchanged", true},
{"generation", frame_->generation},
{"frame_id", frame_->frame_id},
{"frame_age_ms", Age(frame_->queued)},
{"stale", Age(frame_->queued) > 2000}});
return;
}
if (preview && frame_ && !preview_.is_null() &&
Age(preview_time_) <= 2000 &&
preview_edge_ == Number(j, "max_edge", 64, 960, 960) &&
preview_["metadata"]["generation"] == frame_->generation &&
preview_["metadata"]["frame_id"] == frame_->frame_id) {
auto cached = preview_;
cached["metadata"]["frame_age_ms"] = Age(preview_time_);
Reply(id, cached);
return;
}
if (captures_.size() >= 16)
throw std::invalid_argument("BUSY");
const int timeout = Number(j, "timeout_ms", 0, 5000, 2000);
Capture c{id, j, preview, Clock::now() + Ms(timeout)};
// timeout_ms bounds waiting for a suitable frame, not PNG encoding.
// A zero timeout can capture an already available frame immediately.
const bool available = frame_ && frame_->generation == session_.Generation() &&
Age(frame_->queued) <= 2000 &&
(!j.contains("after_frame_id") || frame_->frame_id > Sequence(j, "after_frame_id"));
if (!encoding_ && captures_.empty() && available) {
Encode(std::move(c));
return;
}
if (timeout == 0)
throw std::invalid_argument(encoding_ || !captures_.empty() ? "BUSY" : "FRAME_TIMEOUT");
if (preview)
captures_.push_back(c);
else
captures_.insert(std::find_if(captures_.begin(), captures_.end(),
[](const Capture &queued) { return queued.preview; }), c);
}
const Observation &Observe(const json &j) {
auto name = String(j, "observation_id");
auto it = std::find_if(observations_.begin(), observations_.end(),
[&](const Observation &o) { return o.id == name; });
if (it == observations_.end() || it->generation != session_.Generation() ||
it->epoch != epoch_ || Age(it->created) > 30000)
throw std::invalid_argument("STALE_OBSERVATION");
return *it;
}
void StartAction(const json &j, const json &id) {
Fields(j, {"id", "method", "operation_id", "observation_id", "action"});
const auto operation = String(j, "operation_id");
const auto arguments = json{
{"observation_id", j.at("observation_id")},
{"action",
j.at("action")}}.dump();
for (const auto &r : records_)
if (r.operation == operation) {
if (r.arguments != arguments)
throw std::invalid_argument("OPERATION_ID_CONFLICT");
Reply(id, r.result);
return;
}
if (!allowed_ || paused_ || !session_.ControlEnabled())
throw std::invalid_argument("CONTROL_DENIED");
if (!session_.Connected() || !frame_ || Age(frame_->queued) > 2000)
throw std::invalid_argument("NOT_READY");
if (action_)
throw std::invalid_argument("BUSY");
const auto &o = Observe(j);
const auto &a = j.at("action");
const auto type = String(a, "type", 32);
auto running = std::make_unique<RunningAction>();
running->id = id;
running->operation = operation;
running->generation = o.generation;
running->epoch = o.epoch;
if (type == "type_text" && !session_.Status()["text_input"].get<bool>())
throw std::invalid_argument("TEXT_INPUT_UNSUPPORTED");
running->steps = automation::BuildInputSteps(a,
{o.width, o.height, o.source_width, o.source_height, o.region});
while (records_.size() >= 128 ||
(!records_.empty() && Age(records_.front().created) > 300000))
records_.pop_front();
records_.push_back(
{operation,
arguments,
{{"status", "in_progress"}, {"operation_id", operation}},
Clock::now()});
running->started = Clock::now();
action_ = std::move(running);
}
std::string Password() {
if (password_fd_ < 3 || password_fd_ > 1024)
throw std::invalid_argument("CREDENTIAL_CHANNEL_INVALID");
std::string secret;
const auto deadline = Clock::now() + std::chrono::seconds(5);
while (!interrupted && Clock::now() < deadline) {
if (!WaitReadable(password_fd_, 10))
continue;
char c;
const auto n = Read(password_fd_, &c, 1);
if (!n || (n == 1 && c == '\n'))
return secret;
if (n < 0) {
if (errno == EINTR || errno == EAGAIN)
continue;
throw std::invalid_argument("CREDENTIAL_CHANNEL_FAILED");
}
if (!c || secret.size() >= 256)
throw std::invalid_argument("INVALID_CREDENTIAL");
secret += c;
}
std::fill(secret.begin(), secret.end(), '\0');
throw std::invalid_argument("CREDENTIAL_TIMEOUT");
}
bool Handle(const json &j) {
json id = nullptr;
try {
if (!j.is_object() || !j.contains("id") || !j["id"].is_number_integer() ||
j["id"].get<int64_t>() < 0)
throw std::invalid_argument("INVALID_REQUEST");
id = j["id"];
const auto method = String(j, "method", 32);
if (method == "hello") {
Fields(j, {"id", "method", "protocol"});
if (String(j, "protocol") != "crossdesk-automation/1")
throw std::invalid_argument("VERSION_MISMATCH");
hello_ = true;
Reply(id, {{"protocol", "crossdesk-automation/1"},
{"image_formats", {"image/png"}},
{"video_protocols", {"h264-annexb/1", "nv12/1"}},
{"video_decoders", {"auto", "software"}},
{"video_transport", "loopback-websocket/1"},
{"terminal_protocol", "ansi/1"},
{"action_completion", "submitted"},
{"max_request_bytes", 65536},
{"max_response_bytes", kMaxResponse},
{"operation_cache_entries", 128},
{"operation_cache_ms", 300000},
{"human_pause", true}});
return false;
}
if (!hello_)
throw std::invalid_argument("HELLO_REQUIRED");
if (method == "connect") {
Fields(j, {"id", "method", "device", "display", "mode",
"decode_path", "decoder"});
if (connected_once_)
throw std::invalid_argument("NEW_PROCESS_REQUIRED");
const auto device = String(j, "device", 9);
if (device.size() != 9 ||
device.find_first_not_of("0123456789") != std::string::npos)
throw std::invalid_argument("INVALID_DEVICE");
const auto mode = j.contains("mode") ? String(j, "mode", 8) : "observe";
if (mode != "observe" && mode != "control")
throw std::invalid_argument("INVALID_MODE");
options_.display = Number(j, "display", 0, 63, 0);
const auto path = j.contains("decode_path")
? String(j, "decode_path", 16) : "browser";
const auto decoder = j.contains("decoder")
? String(j, "decoder", 16) : "auto";
if ((path != "browser" && path != "minirtc") ||
(decoder != "auto" && decoder != "software"))
throw std::invalid_argument("INVALID_VIDEO_CONFIG");
decode_path_ = path;
decoder_ = decoder;
options_.hardware_acceleration = decoder != "software";
auto password = Password();
connected_once_ = true;
paused_ = false;
allowed_ = mode == "control";
session_.Connect(options_, device, std::move(password));
session_.SetControl(allowed_);
} else if (method == "screenshot" || method == "preview") {
CaptureFrame(j, id, method == "preview");
return false;
} else if (method == "action") {
StartAction(j, id);
return false;
} else if (method == "terminal_frame") {
Fields(j, {"id", "method", "columns", "rows", "colors", "cell_aspect"});
if (terminal_encoding_) throw std::invalid_argument("BUSY");
if (!session_.Connected() || !frame_ ||
frame_->generation != session_.Generation() || Age(frame_->queued) > 2000)
throw std::invalid_argument("NOT_READY");
terminal::Viewport viewport;
viewport.columns = Number(j, "columns", 1, 160, 80);
viewport.rows = Number(j, "rows", 1, 60, 22);
viewport.colors = Number(j, "colors", 8, 256, 24);
if (viewport.colors != 8 && viewport.colors != 24 && viewport.colors != 256)
throw std::invalid_argument("INVALID_REQUEST");
viewport.cell_aspect = j.value("cell_aspect", .5);
if (!std::isfinite(viewport.cell_aspect) || viewport.cell_aspect < .2 || viewport.cell_aspect > 2)
throw std::invalid_argument("INVALID_REQUEST");
viewport.detail = terminal::AnsiDetail::Quadrant;
auto job = std::make_unique<TerminalEncoding>();
job->id = id;
job->generation = frame_->generation;
job->epoch = epoch_;
job->queued = frame_->queued;
job->result = std::async(std::launch::async, [frame = frame_, viewport] {
return terminal::Convert(*frame, viewport);
});
terminal_encoding_ = std::move(job);
return false;
} else if (method == "control") {
Fields(j, {"id", "method", "enabled"});
const bool enable = Flag(j, "enabled");
if (enable && (!allowed_ || paused_))
throw std::invalid_argument("CONTROL_DENIED");
if (!enable)
FinishAction("CONTROL_DISABLED");
session_.SetControl(enable);
} else if (method == "viewer_control") {
Fields(j, {"id", "method", "operation"});
const auto operation = String(j, "operation", 16);
if (operation == "pause") {
paused_ = true;
FinishAction("USER_PAUSED");
session_.SetControl(false);
} else if (operation == "resume") {
if (!allowed_)
throw std::invalid_argument("CONTROL_DENIED");
paused_ = false;
session_.SetControl(true);
} else if (operation == "disconnect") {
Stop("CANCELLED");
session_.Disconnect();
} else
throw std::invalid_argument("INVALID_REQUEST");
} else if (method == "display") {
Fields(j, {"id", "method", "index"});
const int index = Number(j, "index", 0, 63, -1);
if (!session_.Connected() || index < 0 ||
size_t(index) >= session_.Status()["displays"].size())
throw std::invalid_argument("DISPLAY_UNAVAILABLE");
Stop("SESSION_CHANGED");
if (!session_.SelectDisplay(index))
throw std::invalid_argument("DISPLAY_UNAVAILABLE");
frame_.reset();
++epoch_;
cursor_visible_ = false;
} else if (method == "cancel") {
Fields(j, {"id", "method", "request_id"});
if (!j.contains("request_id") || !j["request_id"].is_number_integer())
throw std::invalid_argument("INVALID_REQUEST");
const auto target = j["request_id"];
if (action_ && action_->id == target)
FinishAction("CANCELLED");
if (encoding_ && !encoding_->cancelled &&
encoding_->capture.id == target) {
encoding_->cancelled = true;
Error(target, "CANCELLED");
}
if (terminal_encoding_ && !terminal_encoding_->cancelled && terminal_encoding_->id == target) {
terminal_encoding_->cancelled = true;
Error(target, "CANCELLED");
}
for (auto it = captures_.begin(); it != captures_.end();) {
if (it->id == target) {
Error(target, "CANCELLED");
it = captures_.erase(it);
} else
++it;
}
} else if (method == "disconnect" || method == "exit") {
Fields(j, {"id", "method"});
Stop("CANCELLED");
session_.Disconnect();
frame_.reset();
} else if (method == "video_open") {
Fields(j, {"id", "method", "ticket", "view", "view_generation",
"session", "origin", "apps"});
if (!video_) throw std::invalid_argument("VIDEO_CHANNEL_UNAVAILABLE");
if (!session_.Connected()) throw std::invalid_argument("NOT_READY");
PumpVideo();
video_->Grant({String(j, "ticket", 32), String(j, "view", 32),
String(j, "session", 32), String(j, "origin", 256),
Sequence(j, "view_generation"), Flag(j, "apps")});
Reply(id, {{"url", video_->Url()}, {"transport", "loopback-websocket/1"},
{"protocol", decode_path_ == "minirtc" ? "nv12/1" : "h264-annexb/1"},
{"decoder", decoder_}, {"expires_in_ms", 15000}});
return false;
} else if (method == "video_revoke") {
Fields(j, {"id", "method", "view"});
if (video_) video_->Revoke(j.contains("view") ? String(j, "view", 32) : "");
} else if (method == "status")
Fields(j, {"id", "method"});
else
throw std::invalid_argument("UNSUPPORTED_METHOD");
PumpVideo();
Reply(id, Status());
return method == "exit";
} catch (const std::invalid_argument &e) {
Error(id, e.what());
} catch (const json::exception &) {
Error(id, "INVALID_REQUEST");
} catch (...) {
Error(id, "OPERATION_FAILED");
}
return false;
}
ControllerSession session_;
Responses output_;
SessionOptions options_;
std::string decode_path_ = "browser", decoder_ = "auto";
int password_fd_, output_fd_ = -1;
bool hello_ = false, connected_once_ = false, allowed_ = false,
paused_ = false;
uint64_t epoch_ = 0, observation_sequence_ = 0;
std::shared_ptr<DecodedFrame> frame_;
std::deque<Observation> observations_;
std::deque<Capture> captures_;
std::unique_ptr<Encoding> encoding_;
std::unique_ptr<TerminalEncoding> terminal_encoding_;
std::unique_ptr<RunningAction> action_;
std::deque<Record> records_;
json preview_;
int preview_edge_ = 960;
Clock::time_point preview_time_;
std::unique_ptr<VideoServer> video_;
uint64_t video_generation_ = 0, last_video_frame_ = 0;
bool video_connected_ = false, video_enabled_ = false;
bool cursor_visible_ = false;
float cursor_x_ = 0, cursor_y_ = 0;
json video_cursor_;
};
} // namespace
int Agent(int output_fd, SessionOptions options, int password_fd,
bool video_websocket) {
Automation automation(output_fd, std::move(options), password_fd, video_websocket);
automation.SetOutputFd(output_fd);
return automation.Run();
}
} // namespace crossdesk::cli
+17
View File
@@ -0,0 +1,17 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-02
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _AGENT_H_
#define _AGENT_H_
#include <controller_session.h>
namespace crossdesk::cli {
int Agent(int output_fd, SessionOptions options, int password_fd,
bool video_websocket = false);
}
#endif
+262
View File
@@ -0,0 +1,262 @@
#include "automation_protocol.h"
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stdexcept>
namespace crossdesk::cli::automation {
void Fields(const json &j, std::initializer_list<const char *> names) {
if (!j.is_object())
throw std::invalid_argument("INVALID_REQUEST");
for (auto it = j.begin(); it != j.end(); ++it)
if (std::none_of(names.begin(), names.end(),
[&](const char *s) { return it.key() == s; }))
throw std::invalid_argument("UNKNOWN_FIELD");
}
int Number(const json &j, const char *key, int low, int high, int fallback) {
if (!j.contains(key))
return fallback;
if (!j[key].is_number_integer())
throw std::invalid_argument("INVALID_REQUEST");
const auto n = j[key].get<int64_t>();
if (n < low || n > high)
throw std::invalid_argument("INVALID_REQUEST");
return int(n);
}
uint64_t Sequence(const json &j, const char *key, uint64_t fallback) {
if (!j.contains(key))
return fallback;
if (!j[key].is_number_unsigned())
throw std::invalid_argument("INVALID_REQUEST");
return j[key].get<uint64_t>();
}
bool Flag(const json &j, const char *key, bool fallback) {
if (!j.contains(key))
return fallback;
if (!j[key].is_boolean())
throw std::invalid_argument("INVALID_REQUEST");
return j[key].get<bool>();
}
std::string String(const json &j, const char *key, size_t limit) {
if (!j.contains(key) || !j[key].is_string())
throw std::invalid_argument("INVALID_REQUEST");
auto s = j[key].get<std::string>();
if (s.empty() || s.size() > limit || s.find('\0') != std::string::npos)
throw std::invalid_argument("INVALID_REQUEST");
return s;
}
namespace {
int KeyCode(const std::string &key) {
if (key.size() == 1 &&
((key[0] >= 'A' && key[0] <= 'Z') || (key[0] >= '0' && key[0] <= '9')))
return key[0];
static const std::map<std::string, int> keys = {{"BACKSPACE", 8},
{"TAB", 9},
{"ENTER", 13},
{"SHIFT", 16},
{"CTRL", 17},
{"ALT", 18},
{"PAUSE", 19},
{"CAPS_LOCK", 20},
{"ESC", 27},
{"SPACE", 32},
{"PAGE_UP", 33},
{"PAGE_DOWN", 34},
{"END", 35},
{"HOME", 36},
{"LEFT", 37},
{"UP", 38},
{"RIGHT", 39},
{"DOWN", 40},
{"INSERT", 45},
{"DELETE", 46},
{"META", 91},
{"F1", 112},
{"F2", 113},
{"F3", 114},
{"F4", 115},
{"F5", 116},
{"F6", 117},
{"F7", 118},
{"F8", 119},
{"F9", 120},
{"F10", 121},
{"F11", 122},
{"F12", 123},
{"SEMICOLON", 186},
{"EQUAL", 187},
{"COMMA", 188},
{"MINUS", 189},
{"PERIOD", 190},
{"SLASH", 191},
{"BACKQUOTE", 192},
{"BRACKET_LEFT", 219},
{"BACKSLASH", 220},
{"BRACKET_RIGHT", 221},
{"QUOTE", 222}};
auto it = keys.find(key);
if (it == keys.end())
throw std::invalid_argument("INVALID_KEY");
return it->second;
}
} // namespace
std::vector<Step> BuildInputSteps(const json &a, const InputGeometry &o) {
const auto type = String(a, "type", 32);
std::vector<Step> steps;
auto point = [&](const json &p, int delay, int flag = 0, int wheel = 0) {
auto coordinate = [&](const char *key, int size, int offset, int span,
int source) {
if (!p.contains(key) || !p[key].is_number())
throw std::invalid_argument("INVALID_COORDINATE");
const auto value = p[key].get<double>();
if (!std::isfinite(value) || value < 0 || value >= size)
throw std::invalid_argument("INVALID_COORDINATE");
const auto center = std::min(value + .5, double(size) - .5);
return float(std::clamp((offset + center * span / size) / source, 0.0, 1.0));
};
Step step;
step.delay = delay;
step.flag = flag;
step.wheel = wheel;
step.x =
coordinate("x", o.width, o.region.x, o.region.width, o.source_width);
step.y =
coordinate("y", o.height, o.region.y, o.region.height, o.source_height);
steps.push_back(std::move(step));
};
auto key = [&](int code, bool down, int delay) {
Step step;
step.kind = StepKind::Key;
step.key = code;
step.down = down;
step.delay = delay;
steps.push_back(std::move(step));
};
if (type == "move" || type == "click" || type == "double_click") {
Fields(a, type == "move"
? std::initializer_list<const char *>{"type", "x", "y",
"modifiers"}
: std::initializer_list<const char *>{"type", "x", "y",
"button", "modifiers"});
point(a, 0);
if (type != "move") {
const auto button =
a.contains("button") ? String(a, "button", 8) : "left";
const int flag = button == "left" ? 1
: button == "right" ? 3
: button == "middle" ? 5
: -1;
if (flag < 0)
throw std::invalid_argument("INVALID_BUTTON");
point(a, 10, flag);
point(a, 40, flag + 1);
if (type == "double_click") {
point(a, 110, flag);
point(a, 140, flag + 1);
}
}
} else if (type == "scroll") {
Fields(a, {"type", "x", "y", "direction", "ticks", "modifiers"});
const auto direction = String(a, "direction", 8);
if (direction != "up" && direction != "down" && direction != "left" &&
direction != "right")
throw std::invalid_argument("INVALID_DIRECTION");
const int ticks = Number(a, "ticks", 1, 10, 1);
point(a, 0);
point(a, 10, direction == "left" || direction == "right" ? 8 : 7,
(direction == "up" || direction == "right" ? 120 : -120) * ticks);
} else if (type == "drag") {
Fields(a, {"type", "path", "duration_ms", "button", "modifiers"});
const auto button = a.contains("button") ? String(a, "button", 8) : "left";
const int flag = button == "left" ? 1
: button == "right" ? 3
: button == "middle" ? 5
: -1;
if (flag < 0)
throw std::invalid_argument("INVALID_BUTTON");
const auto &path = a.at("path");
if (!path.is_array() || path.size() < 2 || path.size() > 128)
throw std::invalid_argument("INVALID_PATH");
const int duration = Number(a, "duration_ms", 100, 2000, 500);
for (const auto &p : path)
Fields(p, {"x", "y"});
point(path.front(), 0);
point(path.front(), 10, flag);
for (size_t i = 1; i < path.size(); ++i)
point(path[i], 10 + int(i * duration / (path.size() - 1)));
point(path.back(), duration + 30, flag + 1);
} else if (type == "key_press") {
Fields(a, {"type", "key", "modifiers"});
const auto code = KeyCode(String(a, "key", 16));
key(code, true, 0);
key(code, false, 40);
} else if (type == "hotkey") {
Fields(a, {"type", "keys"});
const auto &keys = a.at("keys");
if (!keys.is_array() || keys.size() < 2 || keys.size() > 6)
throw std::invalid_argument("INVALID_KEYS");
std::set<int> seen;
std::vector<int> codes;
for (const auto &item : keys) {
if (!item.is_string())
throw std::invalid_argument("INVALID_KEY");
int code = KeyCode(item.get<std::string>());
if (!seen.insert(code).second)
throw std::invalid_argument("DUPLICATE_KEY");
codes.push_back(code);
}
int delay = 0;
for (int code : codes) {
key(code, true, delay);
delay += 15;
}
delay += 30;
for (auto it = codes.rbegin(); it != codes.rend(); ++it) {
key(*it, false, delay);
delay += 15;
}
} else if (type == "type_text") {
Fields(a, {"type", "text"});
Step step;
step.kind = StepKind::Text;
step.text = String(a, "text", 16384);
steps.push_back(std::move(step));
} else
throw std::invalid_argument("UNSUPPORTED_ACTION");
if (a.contains("modifiers")) {
const auto &modifiers = a["modifiers"];
if (!modifiers.is_array() || modifiers.size() > 4)
throw std::invalid_argument("INVALID_KEYS");
std::set<int> seen;
std::vector<Step> prefix;
for (const auto &item : modifiers) {
if (!item.is_string())
throw std::invalid_argument("INVALID_KEY");
const auto name = item.get<std::string>();
if (name != "CTRL" && name != "ALT" && name != "SHIFT" && name != "META")
throw std::invalid_argument("INVALID_KEY");
const int code = KeyCode(name);
if (!seen.insert(code).second ||
(type == "key_press" && String(a, "key", 16) == name))
throw std::invalid_argument("DUPLICATE_KEY");
Step step;
step.kind = StepKind::Key;
step.key = code;
step.down = true;
step.delay = int(prefix.size()) * 15;
prefix.push_back(step);
}
const int offset = int(prefix.size()) * 15;
for (auto &step : steps)
step.delay += offset;
steps.insert(steps.begin(), prefix.begin(), prefix.end());
int delay = steps.back().delay + 15;
for (auto it = prefix.rbegin(); it != prefix.rend(); ++it, delay += 15)
key(it->key, false, delay);
}
return steps;
}
} // namespace crossdesk::cli::automation
+41
View File
@@ -0,0 +1,41 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-03
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _AUTOMATION_PROTOCOL_H_
#define _AUTOMATION_PROTOCOL_H_
#include <frame_image.h>
#include <initializer_list>
#include <string>
#include <vector>
namespace crossdesk::cli::automation {
using nlohmann::json;
void Fields(const json &, std::initializer_list<const char *> names);
int Number(const json &, const char *key, int low, int high, int fallback);
uint64_t Sequence(const json &, const char *key, uint64_t fallback = 0);
bool Flag(const json &, const char *key, bool fallback = false);
std::string String(const json &, const char *key, size_t limit = 128);
struct InputGeometry {
int width, height, source_width, source_height;
ImageRegion region;
};
enum class StepKind { Pointer, Key, Text };
struct Step {
StepKind kind = StepKind::Pointer;
int delay = 0, key = 0, flag = 0, wheel = 0;
float x = 0, y = 0;
bool down = false;
std::string text;
};
// Pure validation and translation: no session access or input side effects.
std::vector<Step> BuildInputSteps(const json &action,
const InputGeometry &geometry);
} // namespace crossdesk::cli::automation
#endif
+123
View File
@@ -0,0 +1,123 @@
# Native automation protocol
`crossdesk-cli agent --stdio --password-fd 3 --video-ws` is the private native adapter used by CrossDesk MCP. It is separate from the existing terminal-oriented `bridge` protocol. This is **not MCP on stdin**: the TypeScript service owns the public MCP transport and tool schemas.
Optional native arguments are `--server HOST`, `--port PORT`, `--quality PRESET` and `--log-dir DIRECTORY`. The caller creates the log directory. Diagnostic stdout is redirected to stderr; only protocol responses use the preserved output descriptor. Passwords travel over descriptor 3, terminated by newline or EOF, and never appear in JSON requests. `--video-ws` starts an authenticated, native loopback WebSocket listener on an ephemeral port. There is no video file descriptor. Agent mode selects the high-frame-rate preview tier at up to 1920 × 1080 by default; negotiated remote capabilities and network conditions determine the delivered rate. Each process accepts one connection attempt; retry authentication with a new process and credential pipe.
## Envelope
One UTF-8 JSON object per line, maximum request 64 KiB and nesting depth 32. Use nonnegative integer request IDs. Responses may complete out of order; correlate by ID.
```json
{"id":1,"method":"hello","protocol":"crossdesk-automation/1"}
{"id":1,"ok":true,"result":{"protocol":"crossdesk-automation/1","image_formats":["image/png"],"action_completion":"submitted","human_pause":true,"max_request_bytes":65536,"max_response_bytes":4194304,"operation_cache_entries":128,"operation_cache_ms":300000}}
```
Unknown fields and malformed arguments are rejected. Error responses contain a stable code, retryability and whether input may already have been submitted:
```json
{"id":2,"ok":false,"error":{"code":"CONTROL_DENIED","retryable":false,"side_effect_possible":false}}
```
The output queue is bounded to 64 messages and 8 MiB; a blocked output pipe terminates after 10 seconds without progress. EOF, signals and `exit` disconnect and release held input. A caller that needs responses must keep stdin open until they arrive.
## Methods
| Method | Parameters in addition to `id`/`method` |
| --- | --- |
| `hello` | `protocol: "crossdesk-automation/1"` |
| `connect` | `device` (9 digits), `mode: "observe" | "control"`, `display` (0–63), optional `decode_path: "browser" / "minirtc"`, `decoder: "auto" / "software"` |
| `status` | none |
| `screenshot` | optional `region: {x,y,width,height}`, `max_edge` (64–2048), `after_frame_id`, `generation`, `timeout_ms` (0–5000) |
| `video_open` | `ticket`, `view`, `view_generation`, `session`, `origin`, `apps`; requires `--video-ws` and a connected session |
| `video_revoke` | optional `view`; omit to revoke all video grants and sockets |
| `preview` | optional `max_edge` (64–960), `after_frame_id`, `generation`, `timeout_ms` (0–5000); no region |
| `action` | `operation_id`, `observation_id`, `action` |
| `control` | `enabled` boolean; cannot override observe-only permission or human pause |
| `viewer_control` | `operation: "pause" | "resume" | "disconnect"`; restricted to trusted UI by the MCP adapter |
| `terminal_frame` | `columns` (1–160), `rows` (1–60), `colors` (8/24/256), `cell_aspect` (0.2–2); private terminal viewer only |
| `display` | `index` (0–63) |
| `cancel` | `request_id`; cancels queued/in-flight captures or input sequences |
| `disconnect`, `exit` | none; `exit` also ends the process |
`connect` returns immediately after initiating transport. Poll `status` until `state == "ready"`; this requires a frame from the current display generation. Status includes `transport_state`, `geometry_epoch`, `frame_age_ms`, `source_size`, `control_allowed`, `human_paused`, host platform, displays and transport diagnostics.
## Live video
`doctor --json` advertises `automation_video_transport: "loopback-websocket/1"`, `automation_video_protocols: ["h264-annexb/1", "nv12/1"]`, and `automation_video_decoders: ["auto", "software"]`. `hello` repeats these without the `automation_` prefix. The MCP adapter requires the transport capability, so an old pipe-only CLI is rejected. Node spawns only stdin, stdout, stderr, and the credential pipe; live video never enters Node.
The terminal viewer additionally requires `automation_terminal_protocol: "ansi/1"` in `doctor` and `terminal_protocol: "ansi/1"` in `hello`. `terminal_frame` asynchronously converts the current decoded frame using the existing ANSI quadrant renderer and returns `columns`, `rows`, `lines`, `generation`, `geometry_epoch`, and a nullable `cursor` with zero-based terminal `column`/`row`. Only one render may be in flight; obsolete geometry or frames older than two seconds are rejected. These rendered text rows travel through the private authenticated terminal IPC, never through public MCP tools or model content. The viewer requests at most 8 FPS and waits for terminal writes before requesting another frame. It shares the automation connection; no second media session is opened.
Status includes `cursor` with normalized full-frame `x`/`y`, `visible`, `generation`, `geometry_epoch`, `width`, and `height`. The native layer updates it after each successfully sent pointer step, including drag steps, using the same ROI-to-source mapping as remote input. It hides on pause/control disable and clears on geometry changes. It is an Agent position indicator, not remote cursor telemetry or execution confirmation; observation PNGs and source video remain unchanged.
Authenticated video sockets also receive small JSON text messages with `type: "cursor"` and these fields, independently of binary video frames. Pointer updates are coalesced to at most 30 Hz, retained for newly authorized viewers, and deferred under socket backpressure; they require no video ACK. Browser/Apps render a separate transparent overlay with the same aspect-ratio fitting as the video, including when no new video frame arrives.
`connect.decode_path` defaults to `browser` (compressed H.264), or selects `minirtc` (decoded NV12). `connect.decoder` defaults to `auto` (hardware preferred, software when unavailable); `software` selects the native software decoder. Both paths maintain native screenshot frames with the selected decoder. These choices are fixed for the connection. Status exposes `video` and the reported `native_video_decoder` backend name. PNG encoding runs only when requested. The legacy `preview` image method remains available to private protocol callers but is not used by MCP panels.
### Authorization and transport
The trusted adapter generates 24 random bytes as a 32-character base64url `ticket` and sends `video_open` over private JSON-RPC. `view` and `session` are also 32-character base64url IDs; `view_generation` is positive. `origin` is the Node panel's exact `http://127.0.0.1:PORT` origin. `apps` permits an opaque (`null`) or HTTPS MCP Apps origin, but still requires the same one-time ticket. No password is included.
The response contains `{url, transport, protocol, decoder, expires_in_ms:15000}`. Node supplies the ticket to the authorized UI. The browser opens the returned `ws://127.0.0.1:PORT/api/video` directly and sends `{"ticket":"..."}` as its first text message within 3 seconds. Tickets expire after 15 seconds, are consumed once, and are bound to a view/session plus the native display generation. The native service checks the exact Host and path, RFC 6455 version, and authorized Origin. It does not serve HTTP content or accept remote input commands. Logs are disabled for this listener; tickets never go in URLs or model-visible results.
The listener uses its own I/O thread, at most 16 WebSocket candidates and 8 authorized viewers. Client messages are limited to 1024 bytes. Revocation, disconnect, native generation changes, or shutdown cancel sockets and invalidate tickets, including partially sent frames. Pause only disables Agent control; viewing continues. The adapter explicitly revokes a removed or replaced view, and terminates the native session if revocation cannot be confirmed. Native processes own ephemeral ports, so panel CSP allows `ws://127.0.0.1:*`, restricted to the literal loopback address; the control HTTP origin remains exact.
### Binary messages and flow control
Each binary WebSocket message contains one complete frame, **without the old pipe length prefix**. Integers are big-endian. For `h264-annexb/1`:
| Offset | Type | Value |
| --- | --- | --- |
| 0 | u32 | `0x43445631` (`CDV1`) |
| 4 | u32 | Display/connection generation |
| 8 | u32 | Receive sequence; gaps require a new keyframe |
| 12 | u64 | Local monotonic receive timestamp in microseconds |
| 20 | u32 | Flags: 1 = IDR keyframe, 0 = delta |
| 24 | bytes | Annex B H.264; keyframes include SPS and PPS |
Access units are capped at 4 MiB. Both the receive tap and the I/O handoff are bounded to 60 frames / 8 MiB. Overflow discards dependent frames until an IDR. After receiving each message the browser sends `{"type":"ack","generation":N,"sequence":N}` directly to the native socket, in order. This acknowledges receipt, not decode, presentation, or remote execution. Per-viewer unacknowledged output is capped at 8 frames; at 1 MiB outstanding, further frames are skipped until space is available (a single keyframe may exceed that threshold). Dropping a dependent picture requires a new keyframe; `{"type":"keyframe"}` requests recovery, rate-limited to once per second.
For `nv12/1`, magic is `0x43444e31` (`CDN1`). Offsets 4, 8, 12 and 20 remain generation, decoded sequence, local monotonic decoded-frame queue time in microseconds, and flags (always 1). Offsets 24 and 28 are u32 width and height; offset 32 starts tightly packed Y followed by interleaved UV. Dimensions must be even, at most 8192 per axis / 16777216 pixels. Message size must equal `32 + width * height * 3 / 2` (at most 25165856 bytes). Color is limited-range BT.601, matching the existing PNG conversion. Sequence gaps are allowed.
NV12 retains one latest picture in the I/O handoff and at most one unacknowledged picture per viewer. New pictures are skipped for a slow viewer without blocking others. Each prepared WebSocket message is immutable and shared between recipients, avoiding per-viewer payload copies. There is still a native copy into the WebSocket payload and raw pixel transfer to the browser; this is not GPU zero-copy. A viewer whose oldest outstanding frame remains unacknowledged for 10 seconds is disconnected. Hidden/unloaded pages close their native socket. The browser replaces pending raw pictures and does not decode H.264 in this mode.
`status.video_output` includes `transport`, `viewers`, I/O handoff `queued` / `queued_bytes`, aggregate `unacknowledged_bytes`, and `dropped` (handoff replacements plus per-viewer congestion skips). These diagnostics contain no video payload. The original receive-tap SPS/PPS and keyframe state remain available for H.264.
The MiniRTC `Params` structure appends `on_receive_encoded_video`, changing its ABI size. Rebuild consumers and MiniRTC together; zero-initialize `Params`. The callback borrows frame bytes on the receive/decode queue and must not retain the pointer. Returning nonzero requests a remote keyframe. No remote wire-protocol change is required.
## Images and observations
Images return `{mime_type:"image/png",data:"<base64>",metadata:{...}}`. Metadata includes `generation`, `geometry_epoch`, `frame_id`, `display_index`, `source_size`, `source_rect`, `image_size` and `frame_age_ms`; only screenshots create `observation_id`. Preview images cannot authorize model input.
NV12 frames must be tightly packed, even dimensions, at most 8192 per axis and 16 million pixels. Conversion/PNG encoding runs on one worker with no `ControllerSession` calls. The owner loop continues processing cancellation and input release. Screenshots have priority over queued previews. An encoding from an obsolete generation or geometry epoch is discarded. Frames older than two seconds are not used for a new image. PNG limits are 2 MiB for observations and 256 KiB for previews; the encoder reduces dimensions when necessary.
`after_frame_id` requires `generation`. A screenshot waits up to `timeout_ms` for a newer frame; a preview can return `{unchanged:true, frame_age_ms, stale, generation, frame_id}`. Neither path treats an image as an input acknowledgement.
`timeout_ms` bounds frame/worker availability, not the subsequent PNG encoding. With `timeout_ms: 0`, a fresh eligible frame is encoded immediately if the worker and queue are idle; otherwise return `FRAME_TIMEOUT` or `BUSY`. Captures of the same priority retain arrival order. Encoding still rejects obsolete geometry and frames that become older than two seconds. Terminal rendering also honors cancellation without sending a second result when the worker finishes.
## Actions
All coordinates refer to the immutable returned observation image. The native layer maps them through its source rectangle to normalized remote coordinates, without terminal layout padding. Coordinates must satisfy `0 <= x < image_width` and `0 <= y < image_height`. Observations expire after 30 seconds, retain at most 32 entries, and are invalidated by geometry/display generation changes.
```json
{"id":10,"method":"action","operation_id":"click-1","observation_id":"obs_2_1","action":{"type":"click","x":120,"y":80,"button":"left"}}
```
Supported payloads:
- `move`: `x`, `y`.
- `click`, `double_click`: `x`, `y`, optional `button` (`left`, `right`, `middle`).
- `scroll`: `x`, `y`, `direction` (`up`, `down`, `left`, `right`), optional `ticks` (1–10).
- `drag`: `path` of 2–128 `{x,y}` points, optional `duration_ms` (100–2000), optional `button` (`left`, `right`, `middle`; default `left`).
- `key_press`: `key`; `hotkey`: 2–6 unique `keys`.
- `type_text`: `text`, at most 16 KiB UTF-8; requires negotiated remote text-input capability.
All pointer actions and `key_press` accept optional `modifiers`, an array of at most four unique names from `CTRL`, `ALT`, `SHIFT`, `META`. They are pressed before the action and released afterwards in reverse order; a `key_press` cannot also list its own key as a modifier. `hotkey` already describes the complete chord and does not accept `modifiers`. Punctuation VK names are `SEMICOLON`, `EQUAL`, `COMMA`, `MINUS`, `PERIOD`, `SLASH`, `BACKQUOTE`, `BRACKET_LEFT`, `BACKSLASH`, `BRACKET_RIGHT`, `QUOTE`; these name keys, not layout-independent text.
Only one input sequence runs at once. Timed steps are advanced by the owner loop; cancellation, disconnect, display changes and pause release held buttons/keys. A failed send is conservatively considered potentially submitted.
New actions require a current frame no older than two seconds as well as a valid observation. Cached operation lookups remain available with a stalled feed or paused control. Failed key/button releases remain tracked for subsequent cleanup, including after control is disabled; a successful local send still does not prove remote execution. Invalid display indices leave existing observations and input sequences intact.
Results use `status: submitted | in_progress | failed_before_submit | outcome_unknown`, with `operation_id`, `retryable`, `side_effect_possible` and, for completed actions, `generation`/`after_frame_id`. The same operation ID and arguments retrieve the cached result; different arguments conflict. Retention is bounded to 128 entries, with entries older than five minutes eligible for removal on a new action. Never retry an uncertain effect with a new ID. `submitted` does not claim remote execution.
The native process trusts its parent. The parent must authenticate panel-only `viewer_control` calls and protect descriptor 3; this private pipe does not isolate arbitrary programs running as the same OS user.
+1 -1
View File
@@ -12,7 +12,7 @@
| connect | device:9位数字字符串, display:0..63(默认0) | 从专用 password fd 读取至换行/EOF(最多256字节、等待5秒),开始异步注册/连接;ok不是远端已连接 |
| status | 无 | 返回当前状态 |
| control | enabled:boolean | 显式启停控制;关闭时释放输入 |
| input | data:string,最多16KiB | 终端原始按键/UTF-8/bracketed paste/SGR鼠标;只读时 c 开启控制、q/Ctrl+C 退出,d/鼠标点击进入细节,+/-/滚轮缩放,方向键或 i 上、j 左、k 下、l 右平移,f 全景;Ctrl+] 打开本地命令,随后 c 选择返回后的控制状态、q 退出或视图键连续调整画面,Esc/Ctrl+C 手动返回;控制模式中 Ctrl+T/Ctrl+C 传给远端,本地模式中再按 Ctrl+] 手动返回,并在返回控制模式时传递远端 Ctrl+] |
| input | data:string,最多16KiB | 终端原始按键/UTF-8/bracketed paste/SGR鼠标;只读时 c 开启控制、q/Ctrl+C 退出,鼠标点击进入细节,+/-/滚轮以鼠标位置缩放,方向键或 i 上、j 左、k 下、l 右平移,f 恢复全景并重置倍率与平移;Ctrl+] 打开本地命令,随后 c 选择返回后的控制状态、q 退出或视图键连续调整画面,Esc/Ctrl+C 手动返回;控制模式中 Ctrl+T/Ctrl+C 传给远端,本地模式中再按 Ctrl+] 手动返回,并在返回控制模式时传递远端 Ctrl+] |
| display | index:0..63 | 选择已广告的零起始显示器,提升 generation |
| ack | frame_id、generation:非负整数 | 确认宿主消费帧;匹配当前等待帧才开放下一帧 |
| disconnect | 无 | 释放输入、结束当前媒体会话 |
+15 -7
View File
@@ -2,16 +2,24 @@
## 使用方式
完整版本发布后的统一入口如下。构建产物或部分平台包上传成功,不代表入口包和全部平台依赖已经可用;发布者须完成本文的注册表检查。
从 [@chunkdash/crossdesk-cli](https://www.npmjs.com/package/@chunkdash/crossdesk-cli) 安装统一入口,npm 会选择对应系统和架构的原生平台包。需要 Node.js 22 或以上和 npm,无需本机编译工具链。
```sh
npm install -g @chunkdash/crossdesk-cli@latest
crossdesk-cli doctor --json
crossdesk-cli 123456789
```
更新时重新执行同一条 `npm install -g @chunkdash/crossdesk-cli@latest`。将示例 ID 替换为被控电脑的 9 位 ID,密码在连接时隐藏输入;`doctor` 只检查本机环境,不建立远程连接。
无需全局安装时使用 `npx`,首次运行会下载对应平台包:
```sh
npx @chunkdash/crossdesk-cli@latest doctor --json
npx @chunkdash/crossdesk-cli@latest 123456789
npm install -g @chunkdash/crossdesk-cli
crossdesk-cli 123456789
```
需要 Node.js 22 或以上和 npm。启动器根据 Node 的 `process.platform` / `process.arch` 选择同版本的 `@chunkdash` 平台包,直接启动原生 C++ 程序,继承终端、工作目录、环境变量和命令参数。安装过程不下载外部可执行文件、不执行 postinstall、不在用户机器编译。不要使用 `--omit=optional`,否则对应平台包不会安装。
启动器根据 Node 的 `process.platform` / `process.arch` 选择同版本的 `@chunkdash` 平台包,直接启动原生 C++ 程序,继承终端、工作目录、环境变量和命令参数。原生可执行文件随 npm 平台包下载,安装过程不执行 postinstall,也不在本机编译。不要使用 `--omit=optional`,否则对应平台包不会安装。
入口包名为 `@chunkdash/crossdesk-cli`,`bin` 声明的终端命令仍为 `crossdesk-cli`。如已全局安装旧的无 scope 入口,先执行 `npm uninstall -g crossdesk-cli`,再安装 scoped 入口,避免两个包争用同一个命令。原来的 `crossdesk-cli@0.1.0` 是独立的旧包,改名不会更新它或自动迁移已有安装。
@@ -31,7 +39,7 @@ crossdesk-cli 123456789
这些是构建与分发目标,不代表均已实机通过。当前完整构建与 npm 运行验证只覆盖 macOS arm64;CLI 主程序与平台 I/O 已通过 Windows x64 与 Linux x64、arm64 的交叉编译检查。其他平台的完整 MiniRTC 链接、实际视频连接、键鼠、终端恢复仍需对应机器验收。
普通终端使用 ANSI 渲染,按能力选择 TrueColor / 256 色 / 基础色;Kitty 图形协议是可选增强。macOS Terminal、iTerm2、Linux 常用终端、Windows Terminal 和 VS Code 集成终端属于目标场景。SSH 应分配 PTY(`ssh -t`);tmux / screen 使用 ANSI。不支持 `TERM=dumb` 或把交互观看输出重定向到文件;非交互宿主使用 `bridge --stdio`。Alpine / musl 当前没有预编译包。Windows 独立 mintty 窗口可能不提供 Console / ConPTY,应使用 Windows Terminal 承载 Git Bash。
普通终端使用 ANSI 渲染,按能力选择 TrueColor / 256 色 / 基础色;Kitty / Sixel 图形协议是可选增强,需终端自身支持并通过能力探测。macOS Terminal、iTerm2、Linux 常用终端、Windows Terminal 和 VS Code 集成终端属于目标场景。SSH 应分配 PTY(`ssh -t`);tmux / screen 使用 ANSI。不支持 `TERM=dumb` 或把交互观看输出重定向到文件;非交互宿主使用 `bridge --stdio`。Alpine / musl 当前没有预编译包。Windows 独立 mintty 窗口可能不提供 Console / ConPTY,应使用 Windows Terminal 承载 Git Bash。
CI 的 macOS 构建配置指定 `--target_minver=13.0`,但最终必须检查实际产物及依赖。当前开发机的本地二进制最低要求为 **macOS 27.0**,不应将这个本地产物宣称为旧 macOS 通用版。
@@ -49,7 +57,7 @@ codesign --force --sign - build/macosx/arm64/release/crossdesk-cli
npm --prefix apps/cli run pack:npm
```
脚本读取 `apps/cli/package.json` 与 `apps/cli/xmake.lua` 的版本,检查二者一致;确认源码中的 MiniRTC 日志脱敏补丁已应用,再检查当前平台二进制格式、CPU、动态链接依赖,并运行离线 `doctor --json`。macOS 只接受系统动态库,Linux 只接受列明的基础系统运行库,Windows 拒绝未随产品处理的 DLL 和动态 MSVC 运行库。Windows 在含 `dumpbin.exe` 的 Visual Studio 开发者环境中运行打包。脚本预先检查两个输出文件是否存在,并在临时目录中完成两个包后再写入输出目录;写入失败时清理本次已写入的包,已有同名产物不会被覆盖。
脚本读取 `apps/cli/package.json` 与 `apps/cli/xmake.lua` 的版本,检查二者一致;检查当前平台二进制格式、CPU、动态链接依赖,并运行离线 `doctor --json`。macOS 只接受系统动态库,Linux 只接受列明的基础系统运行库,Windows 拒绝未随产品处理的 DLL 和动态 MSVC 运行库。Windows 在含 `dumpbin.exe` 的 Visual Studio 开发者环境中运行打包。脚本预先检查两个输出文件是否存在,并在临时目录中完成两个包后再写入输出目录;写入失败时清理本次已写入的包,已有同名产物不会被覆盖。
默认从 `build/<platform>/<arch>/release/` 读取原生程序,将两个 `.tgz` 写入 `build/npm/`。可指定路径:
@@ -59,7 +67,7 @@ npm --prefix apps/cli run pack:npm -- --binary /absolute/path/crossdesk-cli --ou
每台构建机生成当前平台的原生包与相同版本的通用启动包。以 macOS arm64、版本 0.1.0 为例,文件名为 `chunkdash-crossdesk-cli-darwin-arm64-0.1.0.tgz` 和 `chunkdash-crossdesk-cli-0.1.0.tgz`;npm 将 `@scope/name` 的 tarball 文件名写作 `scope-name-version.tgz`。五个 CI artifact 各含一份入口包,最终需要五个平台包和一份入口包,共六个 tarball。
`apps/cli/npm/platforms.json` 集中定义五个平台;脚本校验平台包名合法且不重复,启动包通过精确版本的 `optionalDependencies` 让 npm 仅安装匹配系统和 CPU 的原生包。生成的六个包都包含作者、源码仓库、主页、问题反馈地址,以及面向 npm 官方注册表的公开发布配置。原生包包含二进制、运行要求、SHA-256,以及当前控制端和已应用修补的 MiniRTC 源码快照。外部 Xmake 依赖的许可证、对应源码和重链接材料需要随正式版本一并提供,参见 [源码来源](source-provenance.md)。源码快照已含 MiniRTC,解包后无需运行 `prepare-deps.sh`;在 `source/` 目录按上述构建说明显式关闭桌面、开启 CLI,再构建 `crossdesk-cli`。源码包仅包含 CLI 及其依赖,不包含桌面或移动应用。
`apps/cli/npm/platforms.json` 集中定义五个平台;脚本校验平台包名合法且不重复,启动包通过精确版本的 `optionalDependencies` 让 npm 仅安装匹配系统和 CPU 的原生包。生成的六个包都包含作者、源码仓库、主页、问题反馈地址,以及面向 npm 官方注册表的公开发布配置。原生包包含二进制、运行要求、SHA-256,以及当前控制端和 MiniRTC 源码快照。外部 Xmake 依赖的许可证、对应源码和重链接材料需要随正式版本一并提供,参见 [源码来源](source-provenance.md)。源码快照已含 MiniRTC,解包后无需运行 `prepare-deps.sh`;在 `source/` 目录按上述构建说明显式关闭桌面、开启 CLI,再构建 `crossdesk-cli`。源码包仅包含 CLI 及其依赖,不包含桌面或移动应用。
`apps/cli/package.json` 的 `private: true` 表示源码目录不是发布产物。只发布打包脚本生成的 tarball;生成的包不带 private 标记。
+4 -2
View File
@@ -7,9 +7,11 @@ CLI 从独立开发目录整合到 CrossDesk,入口、打包脚本、npm 启
- `ControllerSession` 的流名称、HostInformation 和输入参考 Android `rtc_bridge.cpp`;身份使用单 Peer 的 `cli` 临时注册协议;终端适配不依赖 JNI、Surface 或 GuiRuntime。
- 帧缓存遵守 `MiniRtcVideoFrame` 回调借用契约,直接复制到有界 CPU 存储,不跨回调保留 native 指针。
- PreviewSubscription 复用 wire 实现与对端 capability 字段,不新增被控端协议。
- MCP 实时面板新增 MiniRTC 的 `on_receive_encoded_video` 回调,转发解码前的完整 H.264 Annex B 帧;回调及关键帧请求由当前子模块源码提供。`Params` 新增字段改变 ABI 大小,CLI 与 MiniRTC 必须一起重建;发布时同步记录包含该改动的子模块提交。
- 自动化图像编码复用 MiniRTC 已有的 libyuv 2025.8.14,并通过 Xmake 固定静态 libpng v1.6.59;libpng 的压缩依赖沿用平台 zlib。新增依赖的许可证和对应源码也应纳入正式发行的依赖材料。
`deps/patches/minirtc-credential-logs.patch` 是 CLI 所需的 MiniRTC 修补:Join、排队 Join、取消 Join、Leave 四个日志点只记录 `@` 前的 ID,不记录密码。`apps/cli/scripts/prepare-deps.sh` 按主仓库记录初始化子模块并幂等应用补丁,不另行校验提交哈希;更新 MiniRTC 时无需修改脚本中的版本。CLI 构建检查补丁已存在。共享子模块中的脱敏同样适用于桌面程序;补丁没有改变鉴权、TLS、TURN 或媒体协议。
MiniRTC 已在提交 `b9ee1fa7fe038fdf771f5dec1b1d561d78273f15` 中合入凭据日志脱敏:Join、排队 Join、取消 Join、Leave 四个日志点只记录 `@` 前的 ID,不记录密码。`apps/cli/scripts/prepare-deps.sh` 仅按主仓库记录初始化子模块,不再应用独立补丁;更新 MiniRTC 时只需更新子模块提交。共享子模块中的脱敏同样适用于桌面程序;该修改没有改变鉴权、TLS、TURN 或媒体协议。
npm 原生包携带 CLI、共享库、构建配置和已修补 MiniRTC 的源码快照,不复制桌面、移动端、测试或本机构建缓存。源码包保留仓库目录结构,在 `source/` 中配置 `--CROSSDESK_BUILD_DESKTOP=n --CROSSDESK_BUILD_CLI=y` 后构建。
npm 原生包携带 CLI、共享库、构建配置和 MiniRTC 的源码快照,不复制桌面、移动端、测试或本机构建缓存。源码包保留仓库目录结构,在 `source/` 中配置 `--CROSSDESK_BUILD_DESKTOP=n --CROSSDESK_BUILD_CLI=y` 后构建。
LICENSE 沿用 CrossDesk GPL-3.0;MiniRTC 子模块保留其 LGPL-3.0 和第三方声明。外部 Xmake 依赖的许可证、对应源码及重链接材料仍需随正式版本提供。
+25 -14
View File
@@ -11,7 +11,7 @@ xmake build crossdesk-cli
xmake run crossdesk-cli doctor --json
```
`prepare-deps.sh` 按主仓库记录的提交初始化 MiniRTC 子模块,并应用凭据日志脱敏补丁,可重复执行。脚本不另行校验提交哈希,升级 MiniRTC 时只需更新子模块提交;如果补丁与新版源码不兼容,准备步骤仍会失败,需要同步调整补丁。构建会检查补丁,缺失时失败。仓库默认开启桌面构建、关闭 CLI。上述参数只构建 CLI;需要同时构建桌面和 CLI 时,将 `CROSSDESK_BUILD_DESKTOP` 设为 `y`。恢复默认桌面配置使用 `xmake f -y --CROSSDESK_BUILD_DESKTOP=y --CROSSDESK_BUILD_CLI=n`。所有命令均从仓库根目录执行。
`prepare-deps.sh` 按主仓库记录的提交初始化 MiniRTC 子模块,可重复执行。凭据日志脱敏已合入 MiniRTC,无需额外应用补丁;升级 MiniRTC 时只需更新子模块提交。仓库默认开启桌面构建、关闭 CLI。上述参数只构建 CLI;需要同时构建桌面和 CLI 时,将 `CROSSDESK_BUILD_DESKTOP` 设为 `y`。恢复默认桌面配置使用 `xmake f -y --CROSSDESK_BUILD_DESKTOP=y --CROSSDESK_BUILD_CLI=n`。所有命令均从仓库根目录执行。
构建产物在 `build/<platform>/<arch>/<mode>/crossdesk-cli`。可把对应目录加入 PATH 或复制可执行文件到自己的 bin 目录。Pi 需要直接启动该可执行文件,不能使用会输出构建日志的 `xmake run` 作为桥接程序。
@@ -41,7 +41,7 @@ crossdesk-cli 123456789 --server your-server.example --port 9099
保留 MiniRTC WSS 证书链与主机名验证、TURN 临时凭据下发及 SRTP 协商。未提供跳过证书检查的参数。SRTP 是否实际协商成功通过状态统计呈现;沿用现有 MiniRTC 对旧端的兼容性,不宣称所有旧端必然启用 SRTP。自建证书问题应修复证书/系统信任链。
## ANSI、Kitty 与 SSH
## ANSI、Kitty、Sixel 与 SSH
ANSI 默认使用四象限字符:每个字符从 2×2 样本选择误差最小的两个颜色和象限形状,比原先上下半方块多一倍水平采样点;每个字符仍只有前景/背景两色。使用 `--ansi-detail half` 可回到上下半方块以兼容字体。缩小时采用面积加权滤波,避免最近邻采样漏掉细线。支持 TrueColor、256 色和基础 8 色,256 色选择实际颜色立方体或灰阶条中更接近的颜色。环境的 COLORTERM/TERM 决定颜色模式;非 UTF-8 locale 使用背景色空格。TERM=dumb、非 TTY 输出明确拒绝交互连接,不输出全屏转义序列。
@@ -57,13 +57,13 @@ Windows 的可见传统控制台优先读取当前字体尺寸;Windows Termina
缩放在完整输出边界清理旧画面。上限 240 列、100 画面行;默认顶部预留一行状态栏、底部预留两行快捷键,另预留一列避免自动换行。顶部状态栏用反色区分,左侧为控制模式和连接进度,右侧为画面参数及网络信息;底部两行分别为会话和视图快捷键。视频和等待提示从顶部状态栏下方开始,鼠标坐标按视频区域映射,点击状态栏不会传给远端。按键分组使用统一列宽和左右留白,窄窗口自动减少列数、合并按键组并省略次要参数,累计帧数和输出字节数保留在日志中。控制模式下仅提示本地命令入口及后续操作,进入本地命令模式后才显示平移和缩放按键;终端高度不足时优先收起底部提示行。
快捷键行使用 `KEYS |`、`VIEW |` 等固定宽度标题,标题和按键组之间用竖线分隔;键名用 `<c>`、`<+/->` 等标签标识。宽窗口中的分组分隔线按列对齐,窄窗口保留标题和完整按键标签,按可用宽度合并或减少分组。
快捷键行使用 `KEYS |`、`VIEW |` 等固定宽度标题,标题和按键组之间用竖线分隔;键名用 `<c>`、`<+/->` 等标签标识。`Zoom at mouse` 表示鼠标锚点缩放,`Full view` / `Full` 表示恢复全景,`Pan` 表示平移。只读模式提示滚轮缩放,宽窗口还显示点击进入细节;本地命令模式提示返回、控制切换及键盘视图操作,宽窗口显示鼠标选择锚点和 `=` 放大。宽窗口中的分组分隔线按列对齐,窄窗口保留完整按键标签,优先保留缩放和全景,按可用宽度合并或减少分组。
顶部状态栏以整数显示实时帧率(例如 `FPS 30`),约每秒按最近统计区间内完整输出到终端的帧数计算;没有新画面输出时更新为 `FPS 0`。该数值是实际提交速率,不是 `--fps` 目标值或终端 GPU 呈现频率;窄窗口优先省略画面参数和网络信息,保留帧率。
ANSI 在完整桌面缩略图中仍无法保留普通字号的文字。先增加终端列数(缩小终端字体或扩大窗口),阅读局部时用 `--zoom native`。只读全景中点击目标位置可直接进入该区域的细节模式;按 `d` 则以当前中心进入。细节模式依据视口和字符宽高比选择源区域,避免为了完整装入桌面而把文字缩小;ANSI 视野较小,借助方向键平移阅读。`--zoom 1..32` 是相对整桌面的倍率;在细节模式中 `+/-` 是相对原始细节尺寸的倍率。画面缩放完全在本地进行,控制鼠标坐标映射回原始桌面的正确区域。
ANSI 在完整桌面缩略图中仍无法保留普通字号的文字。先增加终端列数(缩小终端字体或扩大窗口),阅读局部时用 `--zoom native`。只读时可用 `+/-` 或滚轮以鼠标位置缩放,也可点击目标位置直接进入该区域的细节模式。细节模式依据视口和字符宽高比选择源区域,避免为了完整装入桌面而把文字缩小;ANSI 视野较小,借助方向键平移阅读。`--zoom 1..32` 是相对整桌面的倍率;在细节模式中 `+/-` 是相对原始细节尺寸的倍率。画面缩放完全在本地进行,控制鼠标坐标映射回原始桌面的正确区域。
auto 模式发送 Kitty 查询与设备属性查询,等待最多 250ms;没有有效 Kitty 回应就用 ANSI。显式 kitty 模式探测失败时报错。tmux/screen 中 auto 使用 ANSI,显式 kitty 报不支持;不修改用户终端配置。
auto 模式发送 Kitty 查询与主设备属性查询(DA1),等待最多 250ms;优先选择 Kitty,否则在 DA1 的能力参数中找到 `4` 时选择 Sixel,再回退为 ANSI。显式 `kitty` 或 `sixel` 模式探测失败时报错,不强制向未知终端输出图像。tmux/screen 中 auto 使用 ANSI,显式像素模式报不支持;不修改用户终端配置。
本地 macOS/Linux 的 Kitty 模式会另用一个 1×1 像素的共享内存对象探测 `t=s`,最多等待 250ms;探测成功后,将未压缩 RGB 写入权限为 0600 的 POSIX 共享内存,仅通过终端字节流发送名字和显示命令。每次使用唯一名字,最多保留一个待确认的共享缓冲区(1920×1080×3 字节)。收到上传成功确认后才显示新图并释放缓冲区;上传报错、确认超过 500ms 或本地分配失败时,本次会话退回内联传输,继续保留旧画面。终端和 CLI 都会清理共享对象,退出时也会释放未确认的对象。SSH 中不尝试共享内存;Windows 暂用内联传输。
@@ -71,16 +71,26 @@ auto 模式发送 Kitty 查询与设备属性查询,等待最多 250ms;没
依据终端报告的像素尺寸生成画面(未知时按 10×20 像素字符估算),上限 1920×1080。保留面积滤波、黑边、宽高比和裁剪坐标;原始细节模式按像素视口裁取源区域。共享内存路径使用可复用水平行计算的整数面积权重,避免逐像素重复浮点运算,也不再因 Base64 字节预算额外降采样。没有可靠终端像素尺寸时使用估算值,因此不承诺显示设备的物理像素一一对应。内联压缩结果超出单次输出预算时仍逐级降低尺寸;高熵视频的实际帧率可能低于目标。RGB 传输和压缩不丢失像素,不代表面积采样或上游视频编码无损。
Sixel 使用终端字节流传图,无需额外图像库或临时图片文件:每六行像素按颜色平面编码,使用重复压缩。每帧最多 248 色(RGB 色立方体加灰阶),复杂画面超过约 1.9MB 时逐级降低到 43 色、16 色,必要时降到 4 级灰阶,以保留原有 2MiB 单消息上限。Sixel 有调色板量化损失;它没有 Kitty 的图像缩放 placement,因此依据字符像素尺寸限制画面行列,使图像保持在 1920×1080 内,缩放、细节模式和鼠标映射使用相同视口。每帧覆盖整个图像区域(包括黑边),最后不足六行的部分不会绘制到状态栏;通过保存/恢复 DECSDM 模式使图像从视频区光标位置开始,退出时恢复。未收到像素尺寸时按 10×20 字符估算,实际对齐仍取决于终端尺寸报告。高熵画面或慢速 SSH 建议先用 `--fps 8`。
```sh
crossdesk-cli 123456789 --renderer sixel --fps 8
```
CLI 支持 Sixel 不等于 Xshell 必然支持。查阅的 [Xshell 官方完整功能列表](https://www.netsarang.com/en/xshell-all-features/) 与 [更新记录](https://www.netsarang.com/en/xshell-update-history/) 尚未提供 Sixel 支持说明;以终端实际能力回应及显示测试为准,不能仅修改 `TERM` 就获得像素图像支持。无能力回应时可继续使用 `--renderer ansi --zoom native`。Sixel 协议与 DA1 能力位依据 [XTerm 控制序列文档](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Sixel-Graphics)。
```sh
ssh -t your-server
crossdesk-cli 123456789 --renderer ansi --fps 8
```
用户本地终端负责显示 SSH 字节流。ANSI、Kitty over SSH 和 SSH+tmux 的实机互通尚未验证。无 GUI 指主控客户端;被控端仍需要可捕获的图形会话。
用户本地终端负责显示 SSH 字节流。ANSI、Kitty / Sixel over SSH 和 SSH+tmux 的实机互通尚未验证。无 GUI 指主控客户端;被控端仍需要可捕获的图形会话。
## 预览与背压
`--fps 1..30` 是本地输出目标。交互 CLI 的 ANSI、内联 Kitty 和共享内存 Kitty 默认均为 30 FPS;共享内存失败回退时保持该目标。bridge 仍按宿主协议默认使用 8 FPS。
`--fps 1..30` 是本地输出目标。交互 CLI 的 ANSI、Sixel、内联 Kitty 和共享内存 Kitty 默认均为 30 FPS;共享内存失败回退时保持该目标。bridge 仍按宿主协议默认使用 8 FPS。
独立 CLI 与 bridge 的远端预览统一请求清晰度优先(保持分辨率),包括默认 30 FPS、显式 `--fps` 和自动切换预览帧率。提高帧率不会将编码策略切回帧率优先;实际分辨率仍受画质上限、源画面尺寸、被控端支持及编码/传输条件限制。
未显式指定 `--fps` 时,远端预览从 30 FPS 开始,根据完整一帧从转换开始到输出完成的耗时自动选择 8/15/30 FPS 请求;共享内存的上传确认等待也计入,等待源帧的空闲时间不计入。使用平滑估计、不同升降档阈值和至少 8 个新帧样本,持续变慢 2 秒才降档、持续恢复 4 秒才升档,保留供帧余量。15 FPS 仅在对端声明支持时使用;预览未获接受时不追加自动调节。视口变化、显示器切换和共享内存回退会重置耗时估计。显式 `--fps` 固定本地目标和对应的远端预览请求,关闭自动调节;例如 `--fps 30` 可用于与自动策略对比。
@@ -99,7 +109,7 @@ crossdesk-cli 123456789 --renderer ansi --fps 8
媒体回调仅同步复制借用的 NV12 数据,校验尺寸、容量、native 描述符与 stride;不保留借用指针。上限单帧 16,777,216 像素、每边 8192、偶数尺寸。最多一个待转换帧,替换前先完成校验与复制,无效帧不会挤掉已有画面;播放器另保留最近转换的一帧用于静止桌面的本地放大/重绘,并在接收新帧时回收上一帧缓冲区供后续复制使用。只丢弃解码后图像。显示器切换/关闭提升 generation,旧帧失效。
转换与输出在拥有会话的事件循环,媒体回调独立。输出至多一个完整消息(2MiB),按令牌预算分块非阻塞写入,突发额度上限仍为 1MiB。本地 Kitty 使用 8MiB/s;存在 `SSH_CONNECTION`、`SSH_CLIENT` 或 `SSH_TTY` 时,Kitty 保持 1MiB/s,ANSI 和 Pi 桥接也保持 1MiB/s。不能开始新画面时保留最新解码帧。ANSI 差分基准只在整帧输出完成后提交。Pi 桥接另要求消费帧 ACK,最多一帧等待 ACK,输入映射只在对应 ACK 后切换到新网格。状态栏优先在完整画面输出之间更新,避免大图持续刷新时状态饥饿;可写事件唤醒短写重试,仍遵守字节预算。控制事件至多 64 条,协议输入 64KiB/嵌套 32 层,输入粘贴缓冲 32KiB,文本单次最多 16KiB。
转换与输出在拥有会话的事件循环,媒体回调独立。输出至多一个完整消息(2MiB),按令牌预算分块非阻塞写入,突发额度上限仍为 1MiB。本地交互 ANSI、Kitty 和 Sixel 使用 8MiB/s;存在 `SSH_CONNECTION`、`SSH_CLIENT` 或 `SSH_TTY` 时,三者保持 1MiB/s,Pi 桥接始终保持 1MiB/s。不能开始新画面时保留最新解码帧。ANSI 差分按终端实际使用的颜色与字形比较,忽略量化后相同的颜色和空格不可见的前景色;同一行可输出多个变化片段,并按光标定位、颜色切换和字符的实际字节成本合并短间隔。差分基准只在整帧输出完成后提交。Pi 桥接另要求消费帧 ACK,最多一帧等待 ACK,输入映射只在对应 ACK 后切换到新网格。状态栏优先在完整画面输出之间更新,避免大图持续刷新时状态饥饿;可写事件唤醒短写重试,仍遵守字节预算。控制事件至多 64 条,协议输入 64KiB/嵌套 32 层,输入粘贴缓冲 32KiB,文本单次最多 16KiB。
测量像素渲染帧率时使用 release 构建;debug 的 `-O0` 面积采样开销明显更高。共享内存中的像素不经过终端字节预算,但仍受转换和终端消费速度限制;8MiB/s 是内联路径的输出上限,不是帧率保证。解码、像素转换、压缩、终端消费速度和帧大小都会影响结果。退出时,未完成画面最多继续写入 2s;取消图像传输及恢复屏幕的短写最多另重试 500ms。POSIX 立即恢复 termios 并清理输入,不等待输出排空;如果终端始终不消费输出,屏幕清理只能尽力发送。
@@ -117,12 +127,13 @@ macOS 自带 Terminal 还需要在当前窗口勾选“显示 → 允许鼠标
| 退出 CLI | `q` 或 `Ctrl+C` | `Ctrl+]`,再按 `q` |
| 进入本地命令模式 | `?` 或 `Ctrl+]` | `Ctrl+]` |
| 放大/缩小 | `+` / `=` / `-` | `Ctrl+]`,再按对应键 |
| 原始细节/完整画面 | `d`(detail)/ `f`(fit),相邻字母键 | `Ctrl+]`,再按对应键 |
| 恢复完整画面 | `f`,重置倍率、平移和细节模式 | `Ctrl+]`,再按 `f` |
| 鼠标查看 | 滚轮以鼠标位置缩放;点击进入原始细节 | 进入本地命令模式后仅更新缩放锚点,使用缩放键调整 |
| 平移 | 方向键或 `i` 上、`j` 左、`k` 下、`l` 右 | `Ctrl+]`,再按对应键 |
进入本地命令模式时暂停远端输入,并释放已记录按键/鼠标。执行缩放、平移、`c` 或未知命令后均保持此模式;`c` 切换手动返回后是否启用远端控制,状态栏显示 `CONTROL PAUSED` 或 `READ ONLY`。`Esc` 或 `Ctrl+C` 手动返回所选模式;`q` 退出 CLI。再次按 `Ctrl+]` 也会返回,并在所选模式为控制时向远端发送一次 `Ctrl+]`。命令模式中的鼠标事件被忽略,bracketed paste 内容被丢弃,均不会退出模式或触发快捷键。窗口失焦或输入缓冲区溢出时继续保持本地命令模式,但将返回模式设为只读。控制模式下普通 `c/q/?`、`Ctrl+T`、`Ctrl+C` 和单独 `Esc` 均传给远端。目前不支持重绑定。
进入本地命令模式时暂停远端输入,并释放已记录按键/鼠标。执行缩放、平移、`c` 或未知命令后均保持此模式;`c` 切换手动返回后是否启用远端控制,状态栏显示 `CONTROL PAUSED` 或 `READ ONLY`。`Esc` 或 `Ctrl+C` 手动返回所选模式;`q` 退出 CLI。再次按 `Ctrl+]` 也会返回,并在所选模式为控制时向远端发送一次 `Ctrl+]`。命令模式中的鼠标事件仅更新本地缩放锚点,不执行点击、拖动或滚轮操作;bracketed paste 内容被丢弃,均不会退出模式或触发快捷键。窗口失焦或输入缓冲区溢出时继续保持本地命令模式,但将返回模式设为只读。控制模式下普通 `c/q/?`、`Ctrl+T`、`Ctrl+C` 和单独 `Esc` 均传给远端。目前不支持重绑定。
只读时,`d` 或在画面中单击进入该位置的原始细节模式;`+` / `=` 放大、`-` 缩小(1~32倍),滚轮以鼠标指向为中心调整倍率。方向键或 `i/j/k/l` 分别向上/左/下/右平移,`f` 恢复完整画面。黑边点击被忽略。这些按键和鼠标在控制模式下仍传给远端;进入本地命令模式后可连续调整视图,直至手动返回。放大、平移和只读鼠标定位不会向远端发送操作,也适用于静止画面。
只读时,在画面中单击进入该位置的原始细节模式;`+` / `=` 放大、`-` 缩小(1~32倍)。缩放键与滚轮均以鼠标位置为锚点,尽量保持鼠标下的画面内容在原位置;到达桌面边缘时限制裁剪范围。没有收到鼠标位置,或鼠标位于黑边、状态栏时,缩放键沿用当前中心;窗口失焦会清除鼠标位置。方向键或 `i/j/k/l` 分别向上/左/下/右平移,`f` 恢复完整画面并重置倍率、平移和细节模式。黑边点击被忽略。这些按键和鼠标在控制模式下仍传给远端;进入本地命令模式后可移动鼠标选择锚点并连续按缩放键调整视图,直至手动返回。放大、平移和只读鼠标定位不会向远端发送操作,也适用于静止画面。
支持 SGR 和传统 `CSI M` 鼠标报告,包括移动、左右中键、拖动和滚轮;完整缓冲跨读取分片的传统报告,坐标字节不会作为按键执行。启动时依次启用普通、拖动和全移动报告,兼容只支持部分跟踪模式的终端;退出时关闭这些模式。传统报告的坐标上限为 223,较大窗口应使用支持 SGR 的终端。协议格式依据 [XTerm 鼠标协议](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking)。
@@ -145,7 +156,7 @@ export CROSSDESK_CLI="$PWD/build/macosx/arm64/release/crossdesk-cli"
pi -e ./apps/cli/plugins/pi/index.ts
```
在 Pi 输入 `/crossdesk` 或 `/crossdesk 123456789`。先输入 ID,再在自定义遮蔽组件输入密码。扩展使用独立 fd 3 写密码,随后关闭;不写配置、聊天、工具结果或模型上下文。查看组件与独立 CLI 使用相同的 `Ctrl+]` 命令前缀和上述模式按键,由 bridge 统一解析。插件默认请求 high 预览并显示 ANSI 象限字符行,支持同样的只读细节/放大/平移键,颜色深度依据终端环境回退,由 Pi 自身布局和刷新;不直接占用 TTY,不发送 Kitty 图形或自行打开鼠标报告。
在 Pi 输入 `/crossdesk` 或 `/crossdesk 123456789`。先输入 ID,再在自定义遮蔽组件输入密码。扩展使用独立 fd 3 写密码,随后关闭;不写配置、聊天、工具结果或模型上下文。查看组件与独立 CLI 使用相同的 `Ctrl+]` 命令前缀和上述模式按键,由 bridge 统一解析。插件默认请求 high 预览并显示 ANSI 象限字符行,支持同样的缩放、全景和平移键,颜色深度依据终端环境回退,由 Pi 自身布局和刷新;不直接占用 TTY,不发送 Kitty 图形或自行打开鼠标报告。
Pi 扩展读取宿主的字符尺寸,并通过宿主终端写入/输入监听接口查询字符尺寸或完整文本区尺寸,每两秒及窗口变化时刷新;尺寸回复不会传给远端。得到的宽高比通过 bridge 的 `viewport.cell_aspect` 传入,比例变化时重绘静止画面,并丢弃仍在途的旧比例帧。自动检测不可用或不准确时,可在启动 Pi 前设置环境变量 `CROSSDESK_CELL_ASPECT=0.45`(宽/高,允许 0.2~2;`auto` 恢复自动检测)。视图关闭或 bridge 停止时移除查询定时器和输入监听。
@@ -169,9 +180,9 @@ Pi 扩展读取宿主的字符尺寸,并通过宿主终端写入/输入监
- 日志在进程创建的私有临时目录(POSIX `/tmp/crossdesk-cli-*`、Windows `%TEMP%\crossdesk-cli-*`)。交互连接的摘要在 client.log,包含收到的终端鼠标报告数 `mouse_reports`、其中的传统报告数 `mouse_legacy_reports`、成功交给传输层的鼠标事件数 `mouse_forwarded`、发送失败数 `mouse_send_failures`。一次点击报告可能生成定位和按键两条事件,所以发送数可能大于报告数;发送成功不表示被控端已执行。transport.log 只记录白名单中的 ICE/DTLS 状态及本地控制开关,不记录密码、SDP 或原始信令。使用完可删除。错误退出信息在恢复终端后显示,并给出本次日志目录。
- `connection_failed` 表示连接建立失败;`connection_lost` 表示连接成功后传输失效。xmake 随后的 `execv ... failed(1)` 表示程序以错误码 1 退出,本身不代表进程崩溃。遇到控制失效时,对照 transport.log 中的控制开关和连接状态;`mouse_reports` 为 0 表示终端没有向 CLI 提供可识别的鼠标事件。报告数增长但 `mouse_forwarded` 为 0 时,检查是否仍为只读/本地命令模式、是否已有画面,以及点击是否落在视频区域;`mouse_send_failures` 增长时检查连接状态。
- 如果整个 macOS Terminal 窗口退出且 CLI 记录 `output closed`,还应检查系统 DiagnosticReports 中的 Terminal 报告。已观察到 Terminal 2.15 在创建标签页并调整窗口尺寸时发生 `TTLogicalScreen expandUnicharOffsetCacheToLine:` 行缓存越界;这与 CLI 的 `connection_failed` 不同。临时可在独立窗口运行,避开该标签页操作,不能据此认为 Terminal 缺陷已修复。
- `doctor --json` 是环境报告,不会联网登录、主动探测 Kitty 或证明远端可连接。 `input_shortcuts=local_commands_v2` 表示支持本文的持续本地命令模式;启动日志同时记录实际执行路径,以便区分不同工程的构建产物。
- `doctor --json` 是环境报告,不会联网登录、主动探测 Kitty / Sixel 或证明远端可连接。 `input_shortcuts=local_commands_v2` 表示支持本文的持续本地命令模式;启动日志同时记录实际执行路径,以便区分不同工程的构建产物。
- 画面比例异常时查看 `client.log` 摘要的 `terminal_geometry`:`cell_aspect` 为实际采用的字符宽高比,`reported` 表示收到有效的终端尺寸报告,`manual_aspect` 表示使用了手动覆盖。`doctor` 中的比例和像素尺寸只反映系统 TTY 信息,不主动查询终端,可能与交互连接自动检测后的值不同。
第一轮无音频播放或音频订阅 API,SSH 服务器上的声音不会传回本地。无后台守护进程、共享媒体 Broker、IP 直连、MCP 或自动截图。其他宿主可以使用 [私有桥接](bridge-protocol.md),没有可靠自定义 UI 时打开独立终端或给出播放器命令。
终端模式无音频播放或音频订阅 API,SSH 服务器上的声音不会传回本地。无后台守护进程、共享媒体 Broker 或 IP 直连。终端宿主可以使用 [私有桥接](bridge-protocol.md),没有可靠自定义 UI 时打开独立终端。Agent 的 PNG 截图和结构化操作由独立的 [自动化模式](automation-protocol.md) 和 [MCP 服务](../../mcp/README.md) 提供。
每个播放器/桥接进程只拥有自己的一个媒体会话,不向模型消息发送视频。
+29 -4
View File
@@ -18,16 +18,23 @@
- Release 构建、实际二进制 bridge/PTY 回归通过。ASan/UBSan 检查覆盖原有会话和渲染行为,以及无效帧保留、NV12 缓冲复用、预览参数去重、ACK 状态、重复断开和重连网络统计复位。
- 生产 bridge 配合工程外假传输验证静止画面重绘、细节模式、质量切换、窗口变化、无效配置原子性和帧 ACK 背压,通过。
- ANSI 渲染前后对比覆盖 8/24/256 色、UTF-8/ASCII、half/quadrant、全景/细节模式,输出校验值一致。在本机 240×100 网格连续执行 200 次差分生成,静止网格约 447.4 ms → 3.6 ms,单行变化约 422.8 ms → 9.5 ms。该结果只衡量差分文本生成,不包含视频解码、图像缩放和终端显示时间。
- npm 真实打包、离线安装及源码包重建通过;工程外故障注入确认已有产物保留、第二个包生成失败时无半套输出、缺失脱敏补丁时拒绝打包。
- npm 真实打包、离线安装及源码包重建通过;工程外故障注入确认已有产物保留、第二个包生成失败时无半套输出。
新增回归代码、基准、假传输和验证产物均位于工程外临时目录,未向工程或子模块添加测试。此次完整构建与运行验证覆盖 macOS arm64,未重新进行 Linux/Windows 实机验证。
## 控制按键调整(2026-10-30)
## 鼠标锚点缩放与快捷键提示(2026-11-02)
- 移除 `d` 本地快捷键,保留鼠标点击进入细节及 `--zoom native`。`f` 恢复完整桌面并重置倍率、平移和细节模式;`+/-`、`=` 和只读滚轮使用鼠标锚点缩放。
- 工程外 ASan/UBSan 检查通过 900 次缩放几何检查,覆盖 ASCII、ANSI half/quadrant、Kitty/Sixel 视口、全景/细节、连续输入、边缘限制、SGR/传统鼠标报告、失焦与模式切换;确认 `d` 不再改变本地视图,控制模式仍转发普通字母。
- 四种控制/本地模式组合、1~240 列共 960 组状态栏布局检查通过,覆盖完整按键标签、缩放/全景提示及模式可用操作。Pi 提示通过 Node.js 语法检查;没有进行真实 Pi TUI 或远端设备连接验证。
- 新增验证代码及产物均保存在工程外临时目录。
## 控制按键调整(2026-10-30,历史记录)
- 当前桌面与 CLI 同时启用的 debug 配置下,`xmake build crossdesk-cli`、`xmake run crossdesk-cli doctor --json` 和命令帮助检查通过。
- 工程外 ASan/UBSan 检查覆盖本地命令前缀、只读快捷键、远端 Ctrl+T/Ctrl+C/Ctrl+]、鼠标释放、取消命令、粘贴隔离、UTF-8/CSI 分片、失焦与退出;原有会话/渲染检查通过。
- 平移字母键采用 `i` 上、`j` 左、`k` 下、`l` 右;工程外 ASan/UBSan 检查确认四个方向与普通/应用模式方向键一致,控制模式中普通字母仍传给远端。
- 细节/全景采用相邻的 `d`/`f`;工程外 ASan/UBSan 检查确认细节保留中心、全景复位缩放与中心、前缀命令和鼠标点击行为正确,控制模式中普通字母仍传给远端。
- 当时细节/全景采用相邻的 `d`/`f`(`d` 已于 2026-11-02 移除);工程外 ASan/UBSan 检查确认细节保留中心、全景复位缩放与中心、前缀命令和鼠标点击行为正确,控制模式中普通字母仍传给远端。
- 实际二进制 bridge 验证命令状态、错误恢复和退出响应;生产 view 配合假传输的 PTY 检查验证快捷键、模式提示、隐藏密码和终端恢复。实际二进制的 bridge 与 PTY 回归同样通过。
- Pi 1.4.0 SDK 严格类型检查和模拟组件运行通过,覆盖控制按键转发、命令提示、取消、缩放、退出与 bridge 启动失败后的关闭操作。
@@ -122,8 +129,26 @@
- SSH 环境保持原有 1MiB/s 字节预算且不探测共享内存;慢速输出降远端请求但保留本地目标。ANSI 默认 30/显式 15 和 bridge 默认 8/帧 ACK 通过。所有 Kitty 场景继续验证不显示未确认帧、最多两个终端图像、共享对象释放及退出后终端模式恢复。
- 以上数字是合成源和伪终端的完整输出接收率,不包含真实视频解码、网络或 Ghostty GPU 呈现。全部额外测试代码、数据、构建脚本和产物位于工程外系统临时目录;本次未新增工程内测试,尚未对新版进行 Ghostty 实窗验收。
## ANSI 多片段差分与本地吞吐(2026-10-31)
- 本地交互 ANSI 的持续输出预算由 1MiB/s 提高到 8MiB/s;SSH 与 bridge 仍为 1MiB/s。保留 2MiB 单消息、1MiB 突发、非阻塞短写、最新帧替换和完整输出后提交差分基准的约束。
- 同一行的分散修改按多个片段输出,短间隔按实际编码字节成本合并,比较包含下一单元的颜色设置。差分忽略色板量化后相同的颜色、空格前景色以及 ASCII 模式不显示的字形/背景字段;未修改采样、象限拟合及 Kitty 传输。
- macOS arm64 CLI debug/release 构建及两种产物的 `doctor --json` 通过,完成后工程配置恢复为桌面与 CLI 同时启用的 debug。工程外 ASan/UBSan 检查通过:全部四象限字形、8/24/256 色、ASCII、首尾单元、长短间隔、色板等价、多种尺寸及偏移变化、600 帧连续随机更新与整帧重绘的屏幕一致性;140 组转换逐格一致,bridge 行输出及 Kitty 数据保持一致。
- `-O2`、240×100 合成网格:10 行各两处分散修改由 90,058 降到 931 字节;隔列修改由 919,260 降到 562,601 字节;量化后颜色相同的整屏变化由 72,716 降到 0 字节。高色彩变化整帧仍为 922,929 字节,2×3 光标修改仍为 262 字节。多片段选择会增加部分交错修改场景的编码计算,以减少终端输出量。
- 使用生产 CLI/渲染器的 `-O3` 构建、1920×1080 连续变化合成 NV12、240×100 字符视口、固定目标 30 FPS 的本地 PTY 对比:跳过启动阶段后的完整帧接收速率约 1.64 → 6.42 FPS,约 3.9 倍;平均每帧约 640 KB。分别设置 `SSH_TTY`、`SSH_CONNECTION`、`SSH_CLIENT` 时预算均保持 1MiB/s;设置 `TMUX` 的本地 ANSI 路径使用 8MiB/s。
- 暂停 PTY 读取 1.3s,并在暂停期间发送退出命令,恢复读取后完整帧计数与提交计数一致,约 1.17s 内退出,备用屏幕、termios 和非阻塞标志恢复。没有连接真实远端,也未验证真实终端的 GPU 绘制、SSH 或 tmux 实际显示;上述帧率为合成源的完整输出接收率。
- 额外检查源码、脚本、数据和产物均位于工程外系统临时目录,未新增或修改工程内测试文件/用例。
## Sixel 图形输出(2026-11-02)
- 新增 `--renderer sixel`;auto 按 Kitty → Sixel → ANSI 选择,Sixel 通过 DA1 能力参数 `4` 探测。显式像素模式没有有效回应或处于 tmux/screen 时拒绝启动;`doctor --json` 增加 `sixel=probe_on_view`,不主动探测。
- macOS arm64 CLI debug 构建、帮助信息和 `doctor --json` 通过。工程外 ASan/UBSan 检查覆盖能力回复解析、20,000 组随机尺寸的视口限制及重复计算一致性、7 组合成 NV12 图像(纯黑、纯白、渐变、彩色、部分六行、裁剪缩放和大视口)。
- 工程外独立 Sixel 解码器验证完整像素覆盖、颜色量化误差、图像边界和光标保存/恢复;1920×1080 高熵样本触发 4 级灰阶回退,输出约 1.30MB,保持原尺寸且低于单消息上限。
- 生产 CLI/终端 I/O 配合工程外假会话的 11 组 POSIX PTY 检查通过:Kitty 优先、Sixel 自动及显式选择、分片 DA1 回应、错误/无回应回退、显式模式失败、tmux/screen 限制、窗口变化和细节缩放;SSH 字节预算保持 1MiB/s,退出后 termios 与备用屏幕恢复,Sixel 路径发送 DECSDM 恢复命令。
- 未连接真实远端,未进行 Xshell、其他 Sixel 终端或真实 SSH 显示验收,不保证任何 Xshell 版本支持该协议。额外测试源码、脚本、数据及产物均保存在工程外系统临时目录,未新增或修改工程内测试文件/用例。
## 实测边界
本地检查不涵盖 Linux / Windows 完整构建、跨平台远程控制、Kitty/SSH 实际终端显示、真实 Pi TUI 或长时间资源占用。五个平台 CI 配置与 npm 包名均不代表已发布或已验收。
本地检查不涵盖 Linux / Windows 完整构建、跨平台远程控制、Kitty/Sixel/SSH 实际终端显示、真实 Pi TUI 或长时间资源占用。五个平台 CI 配置与 npm 包名均不代表已发布或已验收。
CLI 需要支持 `cli` 临时注册的服务端。`doctor --json` 仅报告本机环境,不会联网登录或证明远端可连接。
+65 -24
View File
@@ -1,4 +1,5 @@
#include "terminal_io.h"
#include "agent.h"
#include <algorithm>
#include <cerrno>
#include <clocale>
@@ -143,6 +144,7 @@ private:
};
struct Tty {
int out;
bool sixel = false;
RawTerminal terminal;
Tty(int input, int output) : out(output), terminal(input, output) {
// Fall back to button/drag reporting if all-motion tracking is unsupported.
@@ -153,6 +155,7 @@ struct Tty {
~Tty() {
// Cancel any incomplete string/control sequence before restoration.
std::string end = "\030\033\\" + std::string(kKittyDelete) +
(sixel ? "\033[?80r" : "") +
"\033[0m\033[?1003l\033[?1002l\033[?1000l"
"\033[?1006l\033[?1004l\033[?2004l\033["
"?7h\033[?25h\033[?1049l";
@@ -332,9 +335,9 @@ int View(SessionOptions options, const std::string &device,
return 130;
Tty tty(0, fd);
Output output(fd);
bool kitty = false;
bool kitty = false, sixel = false;
if (renderer != "ansi" && Env("TMUX").empty() && Env("STY").empty()) {
output.Put(std::string(kKittyQuery) + "\033[c");
output.Put((renderer == "sixel" ? std::string{} : kKittyQuery) + "\033[c");
std::string reply;
auto until = Clock::now() + std::chrono::milliseconds(250);
while (Clock::now() < until && !interrupted) {
@@ -345,17 +348,28 @@ int View(SessionOptions options, const std::string &device,
if (n > 0 && reply.size() < 8192)
reply.append(b, n);
}
kitty = KittyReply(reply);
kitty = renderer != "sixel" && KittyReply(reply);
sixel = renderer != "kitty" && !kitty && SixelReply(reply);
}
if (renderer == "kitty" && !kitty)
throw std::runtime_error(
"Kitty probe failed or multiplexer active; use --renderer ansi");
// Local pixel frames need more throughput than character output. Keep the
// conservative budget for SSH and the existing one-message/burst limits.
if (renderer == "sixel" && !sixel)
throw std::runtime_error(
"Sixel probe failed or multiplexer active; use --renderer ansi");
if (sixel) {
// DECSDM reset places graphics at the cursor. Save the user's setting
// and restore it on exit, including interrupted image writes.
output.Put("\033[?80s\033[?80l");
tty.sixel = true;
}
// Both pixel frames and large true-colour character grids need local
// throughput. Keep SSH conservative and retain the one-message/burst limits
// and nonblocking writes so slow terminals still apply backpressure.
const bool local_terminal = Env("SSH_CONNECTION").empty() &&
Env("SSH_CLIENT").empty() &&
Env("SSH_TTY").empty();
if (kitty && local_terminal)
if (local_terminal)
output.SetByteRate(8 * 1024 * 1024);
SharedImage shared_image;
bool shared_enabled = false;
@@ -519,10 +533,12 @@ int View(SessionOptions options, const std::string &device,
auto v = Size(&status_rows, &input.terminal_metrics, cell_aspect);
v.detail = detail;
v.native = input.native;
v.pixel_mode = kitty;
v.pixel_mode = kitty || sixel;
v.zoom = input.zoom;
v.center_x = input.center_x;
v.center_y = input.center_y;
if (sixel)
v = SixelViewport(v);
if (input.view_revision != view_revision) {
view_revision = input.view_revision;
redraw = true;
@@ -590,9 +606,10 @@ int View(SessionOptions options, const std::string &device,
bar.command_mode = input.command_mode;
bar.fps = "FPS " + std::to_string(output_fps);
bar.view = std::string(kitty ? "KITTY"
: sixel ? "SIXEL"
: detail == AnsiDetail::Quadrant ? "QUAD"
: "HALF") +
(input.native ? " | Detail x" : " | Fit x") +
(input.native ? " | Detail x" : " | Zoom x") +
std::to_string(int(input.zoom)) +
(last_frame ? " | " + std::to_string(last_frame->width) + "x" +
std::to_string(last_frame->height)
@@ -650,15 +667,15 @@ int View(SessionOptions options, const std::string &device,
now - last_frame->queued)
.count();
}
pending = kitty ? Layout(*last_frame, v) : Convert(*last_frame, v);
// Clear waiting text and Kitty margins without erasing the status bars.
pending = v.pixel_mode ? Layout(*last_frame, v) : Convert(*last_frame, v);
// Clear waiting text and image margins without erasing the status bars.
std::string clear;
if (waiting_visible)
for (int row = 0; row < v.rows; ++row)
clear += "\033[" + std::to_string(v.row_offset + row + 1) +
";1H\033[0m\033[2K";
if (shared_enabled) {
const auto pixels = KittyPixels(*last_frame, v);
const auto pixels = ImagePixels(*last_frame, v);
if (shared_image.Assign(pixels.rgb.data(), pixels.rgb.size())) {
output.Put(KittySharedUpload(shared_image.Name(), pixels.width,
pixels.height, submitted % 2 != 0));
@@ -672,7 +689,8 @@ int View(SessionOptions options, const std::string &device,
if (fresh && !frame_started)
frame_started = Clock::now();
output.Put(clear + (kitty ? Kitty(*last_frame, v, submitted % 2 != 0)
: Difference(*pending, displayed)));
: sixel ? Sixel(*last_frame, v)
: Difference(*pending, displayed)));
waiting_visible = false;
pending_frame = true;
}
@@ -728,7 +746,7 @@ int View(SessionOptions options, const std::string &device,
{"reported", input.terminal_metrics.Known()},
{"manual_aspect", cell_aspect > 0}}},
{"submitted", submitted},
{"renderer", kitty ? "kitty" : "ansi"},
{"renderer", kitty ? "kitty" : sixel ? "sixel" : "ansi"},
{"kitty_transport", !kitty ? "none"
: shared_enabled ? "shared_memory"
: "inline"},
@@ -1010,27 +1028,34 @@ int Bridge(int fd, SessionOptions options, int password_fd) {
s.Disconnect();
return interrupted ? 130 : 0;
}
const char *help = R"(crossdesk-cli <9-digit-device-id> [--renderer auto|ansi|kitty] [--fps 1..30]
const char *help = R"(crossdesk-cli <9-digit-device-id> [--renderer auto|ansi|kitty|sixel] [--fps 1..30]
[--display 0..63] [--control] [--server host] [--port 9099]
[--quality low|balanced|high|ultra] [--ansi-detail quadrant|half] [--zoom 1..32|native]
[--cell-aspect auto|0.2..2]
crossdesk-cli view <9-digit-device-id> [options] (compatibility alias)
crossdesk-cli doctor [--json]
crossdesk-cli bridge --stdio [--password-fd 3] [--server host] [--port 9099]
crossdesk-cli agent --stdio [--password-fd 3] [--video-ws] [--server host] [--port 9099]
Connect by device ID: read-only and silent by default; hidden password prompt on the local terminal.
Read-only: c enables control; q or Ctrl+C quits; ? shows local commands.
Ctrl+] enters persistent local mode: c selects control on return; q quits; Esc/Ctrl+C returns.
View keys: click/d native detail, wheel/+/- zoom, arrows/ijkl pan (i up, j left, k down, l right), f fit.
View keys (read-only/local): +/- zoom at mouse (= also zooms in); f restores the full desktop and resets pan.
Pan: arrows or i up, j left, k down, l right. Read-only mouse: wheel zooms at pointer; click opens native detail.
Local mode: move the mouse to choose the zoom anchor; clicks and wheel do not change the view.
Zoom uses the current center when no mouse position is available or the pointer is outside the picture.
Local mode stays active after commands, paste or focus loss; remote input remains paused.
Ctrl+T and Ctrl+C pass through in control mode; another Ctrl+] leaves local mode and forwards Ctrl+] if control is enabled.
Default ANSI detail: quadrant. Default quality: high (1920x1080); ultra requests up to 3840x2160.
Remote previews prioritize resolution at every frame rate.
Cell aspect is character width/height: auto detects terminal geometry; use --cell-aspect to calibrate.
Display index is zero-based. ANSI cannot reproduce full desktop text at fit scale.
Auto rendering prefers Kitty, then Sixel, then ANSI. Explicit pixel renderers require a successful probe.
--fps controls local output (default 30). Without it, remote preview adapts to measured output speed.
Explicit --fps keeps a fixed preview request. Kitty transport fallback keeps the local target unchanged.
Preview requests above 15 use the negotiated interactive 30 FPS stream; lower requests use 1/8/15 FPS.
bridge: private NDJSON v1, default 8 FPS, credentials on a separate inherited descriptor.
agent: crossdesk-automation/1, structured actions and PNG screenshots; no terminal required.
No IP direct connection, audio playback, clipboard or file transfer support.
)";
} // namespace
@@ -1063,13 +1088,20 @@ int main(int argc, char **argv) {
{"multiplexer", !Env("TMUX").empty() || !Env("STY").empty()},
{"software_decode", true},
{"kitty", "probe_on_view"},
{"sixel", "probe_on_view"},
{"audio_playback", false},
{"bridge_version", 1}};
{"bridge_version", 1},
{"automation_terminal_protocol", "ansi/1"},
{"automation_protocol", "crossdesk-automation/1"},
{"automation_video", "h264-annexb/1"},
{"automation_video_transport", "loopback-websocket/1"},
{"automation_video_protocols", {"h264-annexb/1", "nv12/1"}},
{"automation_video_decoders", {"auto", "software"}}};
std::cout << d.dump(argc == 3 ? -1 : 2) << "\n";
return 0;
}
int i = 2;
if (command != "view" && command != "bridge") {
if (command != "view" && command != "bridge" && command != "agent") {
if (command.find_first_not_of("0123456789") != std::string::npos)
throw std::invalid_argument(
"expected a 9-digit device ID or a command; use --help");
@@ -1082,6 +1114,8 @@ int main(int argc, char **argv) {
double zoom = 1, cell_aspect = 0;
bool control = false, stdio = false, native = false, fps_explicit = false;
int secret_fd = 3;
bool video_websocket = false;
if (command == "agent") options.fps = 30;
if (command == "view") {
if (i >= argc)
throw std::invalid_argument("device ID required");
@@ -1101,8 +1135,10 @@ int main(int argc, char **argv) {
std::string a = argv[i];
if (a == "--control" && command == "view")
control = true;
else if (a == "--stdio" && command == "bridge")
else if (a == "--stdio" && command != "view")
stdio = true;
else if (a == "--video-ws" && command == "agent")
video_websocket = true;
else {
if (i + 1 >= argc)
throw std::invalid_argument("option value missing");
@@ -1111,6 +1147,8 @@ int main(int argc, char **argv) {
options.host = value;
else if (a == "--port")
options.port = number(value, 1, 65535);
else if (a == "--log-dir" && command == "agent")
options.log_directory = value;
else if (a == "--fps" && command == "view") {
options.fps = number(value, 1, 30);
fps_explicit = true;
@@ -1135,22 +1173,23 @@ int main(int argc, char **argv) {
} else if (a == "--zoom" && command == "view") {
native = value == "native";
zoom = native ? 1 : number(value, 1, 32);
} else if (a == "--password-fd" && command == "bridge")
} else if (a == "--password-fd" && command != "view")
secret_fd = number(value, 3, 1024);
else
throw std::invalid_argument("unsupported option");
}
}
if (renderer != "auto" && renderer != "ansi" && renderer != "kitty")
if (renderer != "auto" && renderer != "ansi" && renderer != "kitty" &&
renderer != "sixel")
throw std::invalid_argument("unknown renderer");
if (command == "bridge" && !stdio)
throw std::invalid_argument("bridge requires --stdio");
if (command != "view" && !stdio)
throw std::invalid_argument("automation and bridge require --stdio");
Descriptor output(Duplicate(1));
if (output.value < 0)
throw std::runtime_error("cannot preserve output channel");
// All library stdout writes go to diagnostics. Only Output uses the saved
// fd.
options.log_directory = Logs();
if (options.log_directory.empty()) options.log_directory = Logs();
if (command == "view") {
Descriptor logs(OpenLog(options.log_directory + "/client.log"));
if (logs.value < 0 || Redirect(logs.value, 2) < 0)
@@ -1169,7 +1208,9 @@ int main(int argc, char **argv) {
return command == "view" ? View(options, device, renderer, control,
output.value, detail, zoom, native,
cell_aspect, fps_explicit)
: Bridge(output.value, options, secret_fd);
: command == "agent"
? Agent(output.value, options, secret_fd, video_websocket)
: Bridge(output.value, options, secret_fd);
} catch (const std::exception &e) {
if (command == "view") {
std::string msg = "crossdesk-cli: " + SafeText(e.what()) + "\r\n";
+13 -11
View File
@@ -36,17 +36,19 @@ function main() {
return;
}
const stdio = ['inherit', 'inherit', 'inherit'];
if (args[0] === 'bridge') {
const index = args.lastIndexOf('--password-fd');
const fd = index === -1 ? 3 : Number(args[index + 1]);
if (Number.isInteger(fd) && fd >= 3 && fd <= 1024) {
try {
const stat = fs.fstatSync(fd);
if (stat.isFIFO() || stat.isSocket() || stat.isFile()) {
while (stdio.length <= fd) stdio.push('ignore');
stdio[fd] = fd;
}
} catch { /* The native bridge reports a missing credential descriptor. */ }
if (args[0] === 'bridge' || args[0] === 'agent') {
for (const [option, fallback] of [['--password-fd', 3]]) {
const index = args.lastIndexOf(option);
const fd = index === -1 ? fallback : Number(args[index + 1]);
if (Number.isInteger(fd) && fd >= 3 && fd <= 1024) {
try {
const stat = fs.fstatSync(fd);
if (stat.isFIFO() || stat.isSocket() || stat.isFile()) {
while (stdio.length <= fd) stdio.push('ignore');
stdio[fd] = fd;
}
} catch { /* Native code reports unavailable descriptors. */ }
}
}
}
const child = spawn(binary, args, { stdio, shell: false });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@chunkdash/crossdesk-cli",
"version": "0.1.2",
"version": "0.2.0",
"private": true,
"description": "CrossDesk remote desktop controller for the terminal",
"license": "GPL-3.0-only",
+3 -3
View File
@@ -227,10 +227,10 @@ export default function crossdesk(pi: ExtensionAPI) {
const ack = frame; frame = undefined;
if (ack) queueMicrotask(() => send("ack", ack)); // Host consumed the frame; not a physical display timestamp.
const hint = bridgeStopped ? "q / Esc / Ctrl+C close"
: commandMode ? "Esc/Ctrl+C return | c toggle q quit | arrows/ijkl pan +/- zoom f fit d detail"
: commandMode ? "Esc/Ctrl+C return | c toggle | q quit | +/- zoom | f full | arrows/ijkl pan"
: control ? "Keys -> remote | Ctrl+] then c release, q quit"
: "c control q quit ? help | i up j left k down l right | +/- zoom f fit d detail";
return [truncateToWidth(`CrossDesk ${device} | ${status} ${native ? "detail" : "fit"} x${zoom} | Ctrl+] commands`, width),
: "c control | q quit | +/- zoom | f full | arrows/ijkl pan | ? commands";
return [truncateToWidth(`CrossDesk ${device} | ${status} ${native ? "detail" : "zoom"} x${zoom} | Ctrl+] commands`, width),
...lines.slice(0, h).map(line => truncateToWidth(line, width)),
truncateToWidth(`${hint}${error ? " | " + error : lines.length ? "" : " | Waiting for remote video…"}`, width)];
},
+5 -5
View File
@@ -84,6 +84,8 @@ function inspect(binary, target) {
}
const doctor = JSON.parse(run(binary, ['doctor', '--json'], { timeout: 15000 }));
if (doctor.bridge_version !== 1) throw new Error('Native binary does not report the expected bridge version.');
if (doctor.automation_protocol !== 'crossdesk-automation/1')
throw new Error('Native binary does not report the expected automation protocol.');
return info;
}
function pack(directory, output) {
@@ -132,8 +134,6 @@ try {
const filename = tarballName(name, version);
if (fs.existsSync(path.join(output, filename))) throw new Error(`Output already exists: ${filename}`);
}
run('git', ['-C', path.join(root, 'deps/submodules/minirtc'), 'apply', '--reverse', '--check',
path.join(root, 'deps/patches/minirtc-credential-logs.patch')]);
const executable = process.platform === 'win32' ? 'crossdesk-cli.exe' : 'crossdesk-cli';
binary ||= path.join(root, 'build', platform.xmakePlatform, platform.xmakeArch, 'release', executable);
const info = inspect(binary, target);
@@ -144,7 +144,7 @@ try {
fs.copyFileSync(binary, path.join(native, 'bin', executable));
fs.chmodSync(path.join(native, 'bin', executable), 0o755);
copy('LICENSE', path.join(native, 'LICENSE'));
// Include the controller and patched MiniRTC sources used by this checkout.
// Include the controller and MiniRTC sources used by this checkout.
// External Xmake dependency source/licenses still belong to the release's
// dependency bundle; see source/apps/cli/docs/source-provenance.md.
// Keep desktop build definitions for Xmake's initial option discovery;
@@ -153,11 +153,11 @@ try {
'libs/controller/include',
'libs/controller/src', 'libs/terminal', 'libs/wire/include',
'libs/wire/src', 'deps/submodules/minirtc',
'deps/submodules/xmake.lua', 'deps/thirdparty', 'deps/patches', 'xmake.lua',
'deps/submodules/xmake.lua', 'deps/thirdparty', 'xmake.lua',
'LICENSE', '.gitmodules'])
copy(entry, path.join(native, 'source', entry));
json(path.join(native, 'build-info.json'), { version, ...info });
fs.writeFileSync(path.join(native, 'README.md'), `# ${platform.packageName}\n\nNative ${target} dependency for [${project.name}](https://www.npmjs.com/package/${project.name}) ${version}, published under the ${platform.packageName.split('/')[0]} scope.\n\nInstall the cross-platform entry package with \`npm install -g ${project.name}\` or run \`npx ${project.name} doctor --json\`. This platform package contains the native binary and does not register a shell command.\n\nSource repository: [CrossDesk](${project.repository.url.replace(/^git\+/, '').replace(/\.git$/, '')}). Report problems at ${project.bugs.url}.\n\nRuntime requirements and linked libraries: [build-info.json](build-info.json).\n\nController and patched MiniRTC sources are included in source/. From source/, configure with xmake f -y --CROSSDESK_BUILD_DESKTOP=n --CROSSDESK_BUILD_CLI=y --USE_CUDA=n -m release, then run xmake build crossdesk-cli. External dependency notices and corresponding sources must accompany the product release; see source/apps/cli/docs/source-provenance.md.\n`);
fs.writeFileSync(path.join(native, 'README.md'), `# ${platform.packageName}\n\nNative ${target} dependency for [${project.name}](https://www.npmjs.com/package/${project.name}) ${version}, published under the ${platform.packageName.split('/')[0]} scope.\n\nInstall the cross-platform entry package with \`npm install -g ${project.name}\` or run \`npx ${project.name} doctor --json\`. This platform package contains the native binary and does not register a shell command.\n\nSource repository: [CrossDesk](${project.repository.url.replace(/^git\+/, '').replace(/\.git$/, '')}). Report problems at ${project.bugs.url}.\n\nRuntime requirements and linked libraries: [build-info.json](build-info.json).\n\nController and MiniRTC sources are included in source/. From source/, configure with xmake f -y --CROSSDESK_BUILD_DESKTOP=n --CROSSDESK_BUILD_CLI=y --USE_CUDA=n -m release, then run xmake build crossdesk-cli. External dependency notices and corresponding sources must accompany the product release; see source/apps/cli/docs/source-provenance.md.\n`);
const metadata = {
license: project.license, author: project.author, repository: project.repository,
homepage: project.homepage, bugs: project.bugs,
-6
View File
@@ -2,9 +2,3 @@
set -eu
cd "$(dirname "$0")/../../.."
git submodule update --init --recursive
patch_file="$(pwd)/deps/patches/minirtc-credential-logs.patch"
if git -C deps/submodules/minirtc apply --reverse --check "$patch_file" 2>/dev/null; then
exit 0
fi
git -C deps/submodules/minirtc apply --check "$patch_file"
git -C deps/submodules/minirtc apply "$patch_file"
+507
View File
@@ -0,0 +1,507 @@
#include "video_server.h"
#include <atomic>
#include <deque>
#include <future>
#include <map>
#include <mutex>
#include <thread>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
namespace crossdesk::cli {
namespace {
using Clock = std::chrono::steady_clock;
using namespace std::chrono_literals;
using json = nlohmann::json;
using Handle = websocketpp::connection_hdl;
using Server = websocketpp::server<websocketpp::config::asio>;
constexpr size_t kMaxEncoded = 4 * 1024 * 1024;
constexpr size_t kMaxQueued = 8 * 1024 * 1024;
bool Token(const std::string &s) {
return s.size() == 32 &&
s.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw"
"xyz0123456789-_") == std::string::npos;
}
bool AppOrigin(const std::string &s) {
return s == "null" ||
(s.size() > 8 && s.size() <= 256 && s.compare(0, 8, "https://") == 0 &&
s.find_first_of("/?#@\\ \t\r\n", 8) == std::string::npos);
}
bool BrowserOrigin(const std::string &s) {
const std::string prefix = "http://127.0.0.1:";
if (s.compare(0, prefix.size(), prefix) || s.size() > prefix.size() + 5 ||
s.size() == prefix.size() ||
s.find_first_not_of("0123456789", prefix.size()) != std::string::npos)
return false;
const auto port = std::stoul(s.substr(prefix.size()));
return port > 0 && port <= 65535;
}
void Number(std::string &out, uint64_t value, int bytes) {
for (int n = bytes - 1; n >= 0; --n)
out.push_back(char(value >> (n * 8)));
}
} // namespace
struct VideoServer::State {
struct Ticket {
VideoGrant grant;
Clock::time_point expires;
};
struct Receipt {
uint32_t generation, sequence;
size_t bytes;
Clock::time_point sent;
};
struct Client {
std::string origin, view, session;
uint64_t view_generation = 0;
uint64_t cursor_revision = 0;
bool authorized = false, waiting_key = true;
size_t bytes = 0;
Clock::time_point opened = Clock::now(), pinged = Clock::now();
std::deque<Receipt> receipts;
};
struct Packet {
std::shared_ptr<const DecodedFrame> raw;
EncodedVideoFrame encoded;
size_t Size() const {
return raw ? 32 + raw->nv12.size() : 24 + encoded.data.size();
}
uint64_t Generation() const {
return raw ? raw->generation : encoded.generation;
}
uint64_t Sequence() const { return raw ? raw->frame_id : encoded.sequence; }
bool Key() const { return raw || encoded.key; }
};
Server server;
Server::timer_ptr timer;
std::thread thread;
std::string authority;
std::map<Handle, Client, std::owner_less<Handle>> clients;
std::map<std::string, Ticket> tickets;
std::atomic<size_t> viewers{0}, outstanding{0}, dropped{0};
std::atomic<bool> key_requested{false};
uint64_t generation = 0;
bool connected = false, decoded = false;
Clock::time_point last_key_request{};
// One posted drain, not one posted handler per picture. Raw frames replace
// each other; the compressed handoff is bounded and recovers at an IDR.
mutable std::mutex mutex;
std::deque<Packet> queue;
size_t queued_bytes = 0;
bool scheduled = false, wait_key = true;
json cursor;
uint64_t cursor_revision = 0;
State() {
server.clear_access_channels(websocketpp::log::alevel::all);
server.clear_error_channels(websocketpp::log::elevel::all);
server.init_asio();
server.set_open_handshake_timeout(3000);
server.set_close_handshake_timeout(1000);
server.set_pong_timeout(10000);
server.set_max_message_size(1024);
server.set_max_http_body_size(0);
server.set_socket_init_handler([](Handle, asio::ip::tcp::socket &socket) {
asio::error_code ec;
socket.set_option(asio::ip::tcp::no_delay(true), ec);
socket.set_option(asio::socket_base::send_buffer_size(256 * 1024), ec);
});
server.set_validate_handler([this](Handle h) {
auto c = server.get_con_from_hdl(h);
if (clients.size() >= 16 || c->get_resource() != "/api/video" ||
c->get_request_header("Host") != authority ||
c->get_request_header("Sec-WebSocket-Version") != "13" ||
c->get_origin().empty() || c->get_origin().size() > 256) {
c->set_status(websocketpp::http::status_code::forbidden);
return false;
}
Client client;
client.origin = c->get_origin();
clients.emplace(h, std::move(client));
return true;
});
server.set_message_handler([this](Handle h, Server::message_ptr message) {
try {
Message(h, message);
} catch (...) {
Drop(h);
}
});
server.set_close_handler([this](Handle h) { Remove(h); });
server.set_fail_handler([this](Handle h) { Remove(h); });
server.set_pong_timeout_handler(
[this](Handle h, const std::string &) { Drop(h); });
server.listen(asio::ip::tcp::endpoint(asio::ip::address_v4::loopback(), 0));
asio::error_code ec;
authority =
"127.0.0.1:" + std::to_string(server.get_local_endpoint(ec).port());
if (ec)
throw std::runtime_error("VIDEO_CHANNEL_UNAVAILABLE");
server.start_accept();
Maintain();
thread = std::thread([this] { server.run(); });
}
~State() {
Call([this] {
websocketpp::lib::error_code ec;
server.stop_listening(ec);
if (timer)
timer->cancel();
Revoke("");
});
server.stop();
thread.join();
}
template <class F> void Call(F f) {
auto task = std::make_shared<std::packaged_task<void()>>(std::move(f));
auto result = task->get_future();
server.get_io_service().post([task] { (*task)(); });
result.get();
}
void Remove(Handle h) {
auto it = clients.find(h);
if (it == clients.end())
return;
if (it->second.authorized)
--viewers;
outstanding -= it->second.bytes;
clients.erase(it);
}
void Drop(Handle h) {
// Cancel even a partially sent raw picture on revocation. Waiting for a
// WebSocket close frame behind megabytes of video would keep it alive.
Remove(h);
websocketpp::lib::error_code ec;
auto c = server.get_con_from_hdl(h, ec);
if (!ec) {
asio::error_code ignored;
c->get_raw_socket().cancel(ignored);
c->get_raw_socket().close(ignored);
}
}
void Revoke(const std::string &view) {
for (auto it = tickets.begin(); it != tickets.end();) {
if (view.empty() || it->second.grant.view == view)
it = tickets.erase(it);
else
++it;
}
std::vector<Handle> close;
for (const auto &[h, c] : clients)
if (view.empty() || c.view == view)
close.push_back(h);
for (auto h : close)
Drop(h);
}
void RequestKey() {
const auto now = Clock::now();
if (now - last_key_request < 1s)
return;
last_key_request = now;
key_requested = true;
}
void Message(Handle h, const Server::message_ptr &message) {
auto it = clients.find(h);
if (it == clients.end())
return;
auto &c = it->second;
auto j = json::parse(message->get_payload(), nullptr, false);
if (message->get_opcode() != websocketpp::frame::opcode::TEXT ||
!j.is_object())
return Drop(h);
if (!c.authorized) {
if (j.size() != 1 || !j.contains("ticket") || !j["ticket"].is_string())
return Drop(h);
auto ticket = tickets.find(j["ticket"].get<std::string>());
if (ticket == tickets.end())
return Drop(h);
const auto grant = std::move(ticket->second);
tickets.erase(ticket);
if (!connected || grant.expires <= Clock::now() || viewers >= 8 ||
(c.origin != grant.grant.origin &&
!(grant.grant.apps && AppOrigin(c.origin))))
return Drop(h);
c.authorized = true;
c.view = grant.grant.view;
c.view_generation = grant.grant.view_generation;
c.session = grant.grant.session;
++viewers;
// Also prompts a raw viewer to receive the current fresh picture.
key_requested = true;
return;
}
if (j.value("type", "") == "keyframe" && j.size() == 1 && !decoded) {
c.waiting_key = true;
RequestKey();
return;
}
if (j.value("type", "") != "ack" || j.size() != 3 ||
!j.contains("generation") || !j["generation"].is_number_unsigned() ||
!j.contains("sequence") || !j["sequence"].is_number_unsigned() ||
c.receipts.empty() ||
j["generation"] != c.receipts.front().generation ||
j["sequence"] != c.receipts.front().sequence)
return Drop(h);
c.bytes -= c.receipts.front().bytes;
outstanding -= c.receipts.front().bytes;
c.receipts.pop_front();
}
void Maintain() {
timer = server.set_timer(
33, [this](const websocketpp::lib::error_code &error) {
if (error)
return;
const auto now = Clock::now();
std::string pointer;
uint64_t revision;
{
std::lock_guard lock(mutex);
revision = cursor_revision;
if (!cursor.is_null()) pointer = cursor.dump();
}
for (auto it = tickets.begin(); it != tickets.end();)
if (it->second.expires <= now)
it = tickets.erase(it);
else
++it;
std::vector<Handle> close;
for (auto &[h, c] : clients) {
if (c.authorized && c.cursor_revision != revision && !pointer.empty()) {
websocketpp::lib::error_code ec;
auto connection = server.get_con_from_hdl(h, ec);
// Coalesce pointer changes while a viewer is backpressured.
if (!ec && connection->get_buffered_amount() < 256 * 1024) {
server.send(h, pointer, websocketpp::frame::opcode::TEXT, ec);
if (!ec) c.cursor_revision = revision;
}
if (ec) close.push_back(h);
}
if ((!c.authorized && now - c.opened >= 3s) ||
(!c.receipts.empty() && now - c.receipts.front().sent >= 10s)) {
close.push_back(h);
} else if (c.authorized && now - c.pinged >= 10s) {
c.pinged = now;
websocketpp::lib::error_code ec;
server.ping(h, "", ec);
if (ec)
close.push_back(h);
}
}
for (auto h : close)
Drop(h);
Maintain();
});
}
void Enqueue(Packet p) {
std::lock_guard lock(mutex);
if (p.raw) {
dropped += queue.size();
queue.clear();
queued_bytes = 0;
} else {
if (queue.size() >= 60 || queued_bytes + p.Size() > kMaxQueued) {
dropped += queue.size();
queue.clear();
queued_bytes = 0;
wait_key = true;
key_requested = true;
}
if (wait_key && !p.Key()) {
++dropped;
return;
}
wait_key = false;
}
queued_bytes += p.Size();
queue.push_back(std::move(p));
if (!scheduled) {
scheduled = true;
server.get_io_service().post([this] { Drain(); });
}
}
void Drain() {
Packet p;
{
std::lock_guard lock(mutex);
if (queue.empty()) {
scheduled = false;
return;
}
p = std::move(queue.front());
queued_bytes -= p.Size();
queue.pop_front();
}
if (connected && p.Generation() == generation && bool(p.raw) == decoded)
Publish(p);
// Let authorization, reads, and timers run between large pictures.
server.get_io_service().post([this] { Drain(); });
}
void Publish(const Packet &p) {
std::vector<Handle> ready;
for (auto &[h, c] : clients) {
if (!c.authorized)
continue;
// ACKs are flow-control hints, not proof that a client read the socket.
// Also bound the actual send queue against forged early receipts.
const auto buffered = server.get_con_from_hdl(h)->get_buffered_amount();
if ((decoded && (!c.receipts.empty() || buffered > 0)) ||
(!decoded && (c.receipts.size() >= 8 || c.bytes >= 1024 * 1024 ||
buffered >= 1024 * 1024))) {
++dropped;
c.waiting_key = true;
if (!decoded)
RequestKey();
continue;
}
if (!decoded && c.waiting_key && !p.Key()) {
RequestKey();
continue;
}
ready.push_back(h);
}
if (ready.empty())
return;
// Prepare once and share the immutable WebSocket message across viewers.
// No length-prefixed pipe, Node Buffer, or per-viewer payload copy.
auto message =
server.get_con_from_hdl(ready.front())
->get_message(websocketpp::frame::opcode::BINARY, p.Size());
auto &bytes = message->get_raw_payload();
Number(bytes, decoded ? 0x43444e31 : 0x43445631, 4);
Number(bytes, p.Generation(), 4);
Number(bytes, p.Sequence(), 4);
const auto time =
p.raw ? std::chrono::duration_cast<std::chrono::microseconds>(
p.raw->queued.time_since_epoch())
.count()
: p.encoded.timestamp_us;
Number(bytes, time, 8);
Number(bytes, p.Key() ? 1 : 0, 4);
if (p.raw) {
Number(bytes, p.raw->width, 4);
Number(bytes, p.raw->height, 4);
message->append_payload(p.raw->nv12.data(), p.raw->nv12.size());
} else
message->append_payload(p.encoded.data.data(), p.encoded.data.size());
message->set_header(websocketpp::frame::prepare_header(
websocketpp::frame::basic_header(websocketpp::frame::opcode::BINARY,
bytes.size(), true, false),
websocketpp::frame::extended_header(bytes.size())));
message->set_prepared(true);
for (auto h : ready) {
auto &c = clients.at(h);
websocketpp::lib::error_code ec;
server.send(h, message, ec);
if (ec) {
Drop(h);
continue;
}
c.waiting_key = false;
c.bytes += bytes.size();
outstanding += bytes.size();
c.receipts.push_back({uint32_t(p.Generation()), uint32_t(p.Sequence()),
bytes.size(), Clock::now()});
}
}
};
VideoServer::VideoServer() : state_(std::make_unique<State>()) {}
VideoServer::~VideoServer() = default;
std::string VideoServer::Url() const {
return "ws://" + state_->authority + "/api/video";
}
void VideoServer::Bind(uint64_t generation, bool decoded, bool connected) {
auto &s = *state_;
// Only the automation owner calls Bind; the I/O thread reads these values.
s.Call([&s, generation, decoded, connected] {
if (s.generation == generation && s.decoded == decoded &&
s.connected == connected)
return;
s.Revoke("");
s.generation = generation;
s.decoded = decoded;
s.connected = connected;
s.key_requested = false;
std::lock_guard lock(s.mutex);
s.queue.clear();
s.queued_bytes = 0;
s.wait_key = true;
});
}
void VideoServer::Grant(VideoGrant grant) {
if (!Token(grant.ticket) || !Token(grant.view) || !Token(grant.session) ||
!grant.view_generation || !BrowserOrigin(grant.origin))
throw std::invalid_argument("INVALID_VIDEO_GRANT");
auto &s = *state_;
s.Call([&s, grant = std::move(grant)] {
if (!s.connected)
throw std::invalid_argument("NOT_READY");
for (auto it = s.tickets.begin(); it != s.tickets.end();)
if (it->second.expires <= Clock::now())
it = s.tickets.erase(it);
else
++it;
if (s.tickets.size() >= 32)
throw std::invalid_argument("VIDEO_LIMIT");
// A replaced view cannot retain a socket or consume an old grant.
bool changed = false;
for (const auto &[h, c] : s.clients)
changed |=
c.view == grant.view && (c.view_generation != grant.view_generation ||
c.session != grant.session);
for (const auto &[ticket, t] : s.tickets)
changed |= t.grant.view == grant.view &&
(t.grant.view_generation != grant.view_generation ||
t.grant.session != grant.session);
if (changed)
s.Revoke(grant.view);
if (!s.tickets
.emplace(grant.ticket, State::Ticket{grant, Clock::now() + 15s})
.second)
throw std::invalid_argument("INVALID_VIDEO_GRANT");
});
}
void VideoServer::Revoke(const std::string &view) {
state_->Call([&] { state_->Revoke(view); });
}
bool VideoServer::Enabled() const { return state_->viewers.load() > 0; }
bool VideoServer::TakeKeyframeRequest() {
return state_->key_requested.exchange(false);
}
void VideoServer::Submit(std::shared_ptr<const DecodedFrame> frame) {
if (!frame || !frame->width || !frame->height || (frame->width & 1) ||
(frame->height & 1) || frame->width > 8192 || frame->height > 8192 ||
uint64_t(frame->width) * frame->height > 16777216 ||
frame->nv12.size() != size_t(frame->width) * frame->height * 3 / 2)
throw std::invalid_argument("INVALID_VIDEO_FRAME");
if (Enabled())
state_->Enqueue({std::move(frame), {}});
}
void VideoServer::Submit(EncodedVideoFrame frame) {
if (frame.data.empty() || frame.data.size() > kMaxEncoded)
throw std::invalid_argument("INVALID_VIDEO_FRAME");
if (Enabled())
state_->Enqueue({{}, std::move(frame)});
}
void VideoServer::Cursor(json cursor) {
auto &s = *state_;
std::lock_guard lock(s.mutex);
s.cursor = std::move(cursor);
++s.cursor_revision;
}
json VideoServer::Status() const {
const auto &s = *state_;
std::lock_guard lock(s.mutex);
return {{"transport", "loopback-websocket/1"},
{"viewers", s.viewers.load()},
{"queued", s.queue.size()},
{"queued_bytes", s.queued_bytes},
{"unacknowledged_bytes", s.outstanding.load()},
{"dropped", s.dropped.load()}};
}
} // namespace crossdesk::cli
+49
View File
@@ -0,0 +1,49 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-03
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _VIDEO_SERVER_H_
#define _VIDEO_SERVER_H_
#include <controller_session.h>
#include <memory>
#include <string>
namespace crossdesk::cli {
struct VideoGrant {
std::string ticket, view, session, origin;
uint64_t view_generation = 0;
bool apps = false;
};
// Owns the loopback listener and its I/O thread. JSON-RPC carries only grants
// and diagnostics; encoded and decoded pictures stay in the native process.
class VideoServer {
public:
VideoServer();
~VideoServer();
VideoServer(const VideoServer &) = delete;
VideoServer &operator=(const VideoServer &) = delete;
std::string Url() const;
void Bind(uint64_t generation, bool decoded, bool connected);
void Grant(VideoGrant grant);
void Revoke(const std::string &view = "");
bool Enabled() const;
bool TakeKeyframeRequest();
void Submit(std::shared_ptr<const DecodedFrame> frame);
void Submit(EncodedVideoFrame frame);
void Cursor(nlohmann::json cursor);
nlohmann::json Status() const;
private:
struct State;
std::unique_ptr<State> state_;
};
} // namespace crossdesk::cli
#endif
+7 -8
View File
@@ -2,9 +2,10 @@ local source_dir = path.absolute("../..", os.scriptdir())
local controller_dir = path.join(source_dir, "libs/controller")
local terminal_dir = path.join(source_dir, "libs/terminal")
local minirtc_dir = path.join(source_dir, "deps/submodules/minirtc")
local credential_patch = path.join(source_dir, "deps/patches/minirtc-credential-logs.patch")
add_requires("spdlog 1.14.1", {system = false})
add_requires("asio 1.32.0", "websocketpp 0.8.2", {system = false})
add_requires("libpng v1.6.59", {system = false, configs = {shared = false}})
if is_plat("windows") then
add_requires("zlib 1.3.1", {system = false, configs = {shared = false}})
end
@@ -12,15 +13,11 @@ end
target("crossdesk_controller")
set_kind("static")
add_deps("minirtc", "crossdesk_wire")
add_packages("spdlog")
add_packages("spdlog", "libpng", "libyuv")
add_includedirs(path.join(controller_dir, "include"),
path.join(minirtc_dir, "src/api"), {public = true})
add_includedirs(path.join(minirtc_dir, "src/log"))
add_files(path.join(controller_dir, "src/*.cpp"))
before_build(function ()
-- Require the same credential redaction in checkouts and source bundles.
os.vrunv("git", {"-C", minirtc_dir, "apply", "--reverse", "--check", credential_patch})
end)
target_end()
target("crossdesk_terminal")
@@ -37,12 +34,14 @@ target_end()
target("crossdesk-cli")
set_kind("binary")
set_version("0.1.2")
set_version("0.2.0")
add_deps("crossdesk_terminal")
add_files("main.cpp")
add_files("agent.cpp", "automation_protocol.cpp", "video_server.cpp")
add_packages("asio", "websocketpp")
add_files(is_plat("windows") and "terminal_io_windows.cpp" or "terminal_io_posix.cpp")
if is_plat("windows") then
add_syslinks("advapi32", "user32")
add_syslinks("advapi32", "user32", "ws2_32")
add_defines("NOMINMAX", "WIN32_LEAN_AND_MEAN")
elseif is_plat("linux") then
add_syslinks("rt")
+247
View File
@@ -0,0 +1,247 @@
#include "private_file.h"
#include <openssl/rand.h>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#include <Aclapi.h>
#include <sddl.h>
#else
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace crossdesk::private_file {
namespace {
void Require(bool ok, const char* error) {
if (!ok) throw std::runtime_error(error);
}
std::string RandomSuffix() {
unsigned char bytes[16];
Require(RAND_bytes(bytes, sizeof(bytes)) == 1, "Secure random source unavailable");
constexpr char hex[] = "0123456789abcdef";
std::string value;
for (auto byte : bytes) { value += hex[byte >> 4]; value += hex[byte & 15]; }
return value;
}
#ifdef _WIN32
std::vector<unsigned char> CurrentUser() {
HANDLE token = nullptr;
Require(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token),
"Cannot open user token");
DWORD size = 0;
GetTokenInformation(token, TokenUser, nullptr, 0, &size);
std::vector<unsigned char> data(size);
bool ok = GetTokenInformation(token, TokenUser, data.data(), size, &size);
CloseHandle(token);
Require(ok, "Cannot read user token");
return data;
}
PSECURITY_DESCRIPTOR PrivateSecurityDescriptor(bool directory) {
auto user = CurrentUser();
LPWSTR sid = nullptr;
Require(ConvertSidToStringSidW(
reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid, &sid),
"Cannot read user SID");
// An elevated token can default to Administrators as the owner even when
// its DACL grants access only to TokenUser. Always set both explicitly.
const auto acl = L"O:" + std::wstring(sid) + L"D:P(A;" +
(directory ? L"OICI" : L"") + L";FA;;;" + sid + L")";
LocalFree(sid);
PSECURITY_DESCRIPTOR descriptor = nullptr;
Require(ConvertStringSecurityDescriptorToSecurityDescriptorW(
acl.c_str(), SDDL_REVISION_1, &descriptor, nullptr),
"Cannot protect private file");
return descriptor;
}
#endif
} // namespace
void Write(const std::filesystem::path& path, const std::string& text) {
const auto temporary = path.parent_path() / (".write-" + RandomSuffix());
#ifdef _WIN32
auto descriptor = PrivateSecurityDescriptor(false);
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
HANDLE file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, &security,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
LocalFree(descriptor);
Require(file != INVALID_HANDLE_VALUE, "Cannot create private file");
DWORD written = 0;
bool ok = WriteFile(file, text.data(), static_cast<DWORD>(text.size()),
&written, nullptr) &&
written == text.size() && FlushFileBuffers(file);
CloseHandle(file);
if (!ok || !MoveFileExW(temporary.c_str(), path.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
DeleteFileW(temporary.c_str());
throw std::runtime_error("Cannot persist private file");
}
#else
int fd =
open(temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
Require(fd >= 0, "Cannot create private file");
size_t offset = 0;
while (offset < text.size()) {
const auto count = write(fd, text.data() + offset, text.size() - offset);
if (count <= 0) break;
offset += static_cast<size_t>(count);
}
bool ok = offset == text.size() && fsync(fd) == 0;
close(fd);
if (!ok || rename(temporary.c_str(), path.c_str()) != 0) {
unlink(temporary.c_str());
throw std::runtime_error("Cannot persist private file");
}
const int directory = open(path.parent_path().c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
const bool durable = directory >= 0 && fsync(directory) == 0;
if (directory >= 0) close(directory);
Require(durable, "Cannot persist private directory entry");
#endif
}
namespace {
#ifdef _WIN32
using FileHandle = std::unique_ptr<void, decltype(&CloseHandle)>;
FileHandle OpenPrivatePath(const std::filesystem::path& path, DWORD access) {
// Keep the object open without FILE_SHARE_DELETE so validation and legacy
// owner repair cannot operate on a replacement at the same path.
HANDLE file = CreateFileW(
path.c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
Require(file != INVALID_HANDLE_VALUE, "Cannot open private path");
return {file, CloseHandle};
}
void CheckPrivateWindowsPath(const std::filesystem::path& path) {
auto file = OpenPrivatePath(path, READ_CONTROL);
BY_HANDLE_FILE_INFORMATION info{};
Require(GetFileInformationByHandle(file.get(), &info) &&
!(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT),
"private path cannot be a reparse point");
auto user = CurrentUser();
auto sid = reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid;
PSID owner = nullptr;
PACL acl = nullptr;
PSECURITY_DESCRIPTOR descriptor = nullptr;
Require(GetSecurityInfo(
file.get(), SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &owner,
nullptr, &acl, nullptr, &descriptor) == ERROR_SUCCESS,
"Cannot read private file permissions");
std::unique_ptr<void, decltype(&LocalFree)> security(descriptor, LocalFree);
bool ok = acl && acl->AceCount > 0;
// Only the exact protected, full-access DACL written by older versions is
// eligible for owner repair. Never adopt a shared or foreign-user profile.
SECURITY_DESCRIPTOR_CONTROL control{};
DWORD revision = 0;
bool legacy = owner && IsWellKnownSid(owner, WinBuiltinAdministratorsSid) &&
GetSecurityDescriptorControl(descriptor, &control, &revision) &&
(control & SE_DACL_PROTECTED) && acl && acl->AceCount == 1;
for (DWORD i = 0; ok && i < acl->AceCount; ++i) {
void* raw = nullptr;
if (!GetAce(acl, i, &raw)) {
ok = false;
break;
}
const auto* ace = static_cast<ACCESS_ALLOWED_ACE*>(raw);
ok = ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE &&
EqualSid(const_cast<DWORD*>(&ace->SidStart), sid);
const BYTE flags = (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
? OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
: 0;
legacy =
legacy && ace->Mask == FILE_ALL_ACCESS && ace->Header.AceFlags == flags;
}
Require(ok && owner && (EqualSid(owner, sid) || legacy),
"private files must be accessible only by the current user");
if (legacy) {
auto writable = OpenPrivatePath(path, WRITE_OWNER);
BY_HANDLE_FILE_INFORMATION current{};
Require(GetFileInformationByHandle(writable.get(), &current) &&
current.dwVolumeSerialNumber == info.dwVolumeSerialNumber &&
current.nFileIndexHigh == info.nFileIndexHigh &&
current.nFileIndexLow == info.nFileIndexLow &&
SetSecurityInfo(writable.get(), SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION, sid, nullptr,
nullptr, nullptr) == ERROR_SUCCESS,
"Cannot repair private file owner");
}
}
void CreatePrivateDirectory(const std::filesystem::path& path, bool protect_existing) {
if (!std::filesystem::exists(path)) {
auto descriptor = PrivateSecurityDescriptor(true);
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
bool ok = CreateDirectoryW(path.c_str(), &security);
LocalFree(descriptor);
Require(ok, "Cannot create private directory");
}
if (protect_existing) {
// The cache may predate identity storage and inherit a normal profile ACL.
// Elevated older builds may have used Administrators as the owner. The
// private-path check below repairs that owner after applying the user ACL.
auto file = OpenPrivatePath(path, READ_CONTROL | WRITE_DAC);
BY_HANDLE_FILE_INFORMATION info{};
Require(GetFileInformationByHandle(file.get(), &info) &&
(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
!(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT),
"Invalid cache directory");
PSID owner = nullptr;
PSECURITY_DESCRIPTOR original = nullptr;
Require(GetSecurityInfo(file.get(), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION,
&owner, nullptr, nullptr, nullptr, &original) == ERROR_SUCCESS,
"Cannot read cache directory owner");
std::unique_ptr<void, decltype(&LocalFree)> original_guard(original, LocalFree);
auto user = CurrentUser();
Require(owner && (EqualSid(owner, reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid) ||
IsWellKnownSid(owner, WinBuiltinAdministratorsSid)),
"Cache directory belongs to another user");
auto descriptor = PrivateSecurityDescriptor(true);
std::unique_ptr<void, decltype(&LocalFree)> descriptor_guard(descriptor, LocalFree);
BOOL present = FALSE, defaulted = FALSE;
PACL acl = nullptr;
Require(GetSecurityDescriptorDacl(descriptor, &present, &acl, &defaulted) && present &&
SetSecurityInfo(file.get(), SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
nullptr, nullptr, acl, nullptr) == ERROR_SUCCESS,
"Cannot protect cache directory");
}
CheckPrivateWindowsPath(path);
}
#endif
} // namespace
std::string Read(const std::filesystem::path& path) {
#ifdef _WIN32
CheckPrivateWindowsPath(path);
#else
struct stat status{};
Require(lstat(path.c_str(), &status) == 0 && S_ISREG(status.st_mode) &&
status.st_uid == getuid() && (status.st_mode & 0077) == 0,
"private file must be owned by this user with mode 0600");
#endif
Require(std::filesystem::file_size(path) <= 64 * 1024, "private file too large");
std::ifstream input(path, std::ios::binary);
Require(input.good(), "Cannot read private file");
return {std::istreambuf_iterator<char>(input), {}};
}
void EnsureDirectory(const std::filesystem::path& directory, bool protect_existing) {
const auto parent = directory.parent_path();
if (!parent.empty()) {
std::filesystem::create_directories(parent);
}
#ifdef _WIN32
CreatePrivateDirectory(directory, protect_existing);
#else
std::filesystem::create_directories(directory);
struct stat status{};
Require(lstat(directory.c_str(), &status) == 0 && S_ISDIR(status.st_mode) &&
status.st_uid == getuid(), "Invalid private directory owner or type");
Require(chmod(directory.c_str(), 0700) == 0, "Cannot protect private directory");
#endif
}
} // namespace crossdesk::private_file
+21
View File
@@ -0,0 +1,21 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-01
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _PRIVATE_FILE_H_
#define _PRIVATE_FILE_H_
#include <filesystem>
#include <string>
namespace crossdesk::private_file {
// User-only files, atomic replacement, and rejection of shared/linked stores.
void EnsureDirectory(const std::filesystem::path& directory,
bool protect_existing = false);
std::string Read(const std::filesystem::path& path);
void Write(const std::filesystem::path& path, const std::string& text);
}
#endif
@@ -36,6 +36,14 @@ ConfigCenter::~ConfigCenter() {}
int ConfigCenter::Load() {
SI_Error rc = ini_->LoadFile(config_path_.c_str());
if (rc < 0) {
std::error_code error;
if (std::filesystem::exists(config_path_, error) || error) {
// An unreadable existing configuration must not silently disable access
// restrictions or overwrite the user's settings with default values.
trusted_devices_only_.store(true);
LOG_ERROR("Cannot read existing configuration; restricting incoming connections");
return -1;
}
Save();
return -1;
}
@@ -141,6 +149,9 @@ int ConfigCenter::Load() {
ini_->GetBoolValue(section_, "privacy_local_unlock_allowed", true));
lock_on_disconnect_.store(
ini_->GetBoolValue(section_, "lock_on_disconnect", true));
trusted_devices_only_.store(
ini_->GetValue(section_, "trusted_devices_only", nullptr) != nullptr &&
ini_->GetBoolValue(section_, "trusted_devices_only", true));
save_remote_previews_.store(
ini_->GetBoolValue(section_, "save_remote_previews", true));
portable_service_prompt_suppressed_ =
@@ -239,6 +250,7 @@ int ConfigCenter::Save() {
ini_->SetBoolValue(section_, "privacy_local_unlock_allowed",
privacy_local_unlock_allowed_.load());
ini_->SetBoolValue(section_, "lock_on_disconnect", lock_on_disconnect_.load());
ini_->SetBoolValue(section_, "trusted_devices_only", trusted_devices_only_.load());
ini_->SetBoolValue(section_, "save_remote_previews",
save_remote_previews_.load());
ini_->SetBoolValue(section_, "portable_service_prompt_suppressed",
@@ -425,6 +437,13 @@ bool ConfigCenter::IsPrivacyLocalUnlockAllowed() const {
return privacy_local_unlock_allowed_.load();
}
int ConfigCenter::SetTrustedDevicesOnly(bool enabled) {
if (StoreValues({{"trusted_devices_only", enabled ? "true" : "false"}}) != 0) return -1;
trusted_devices_only_.store(enabled);
return 0;
}
bool ConfigCenter::IsTrustedDevicesOnly() const { return trusted_devices_only_.load(); }
int ConfigCenter::SetLockOnDisconnect(bool enabled) {
if (StoreValues({{"lock_on_disconnect", enabled ? "true" : "false"}}) != 0)
return -1;
@@ -55,6 +55,7 @@ class ConfigCenter {
int SetPrivacyScreen(bool enable_privacy_screen);
int SetPrivacyLocalUnlock(bool allowed);
int SetLockOnDisconnect(bool enabled);
int SetTrustedDevicesOnly(bool enabled);
int SetSaveRemotePreviews(bool enabled);
int SetPortableServicePromptSuppressed(bool suppressed);
int SetSponsorshipPromptDismissedVersion(const std::string& version);
@@ -80,6 +81,7 @@ class ConfigCenter {
bool IsEnablePrivacyScreen() const;
bool IsPrivacyLocalUnlockAllowed() const;
bool IsLockOnDisconnect() const;
bool IsTrustedDevicesOnly() const;
bool IsSaveRemotePreviews() const;
bool IsPortableServicePromptSuppressed() const;
std::string GetSponsorshipPromptDismissedVersion() const;
@@ -113,6 +115,7 @@ class ConfigCenter {
std::atomic<bool> enable_privacy_screen_{true};
std::atomic<bool> privacy_local_unlock_allowed_{true};
std::atomic<bool> lock_on_disconnect_{true};
std::atomic<bool> trusted_devices_only_{false};
std::atomic<bool> save_remote_previews_{true};
bool portable_service_prompt_suppressed_ = false;
std::string sponsorship_prompt_dismissed_version_;
@@ -38,6 +38,8 @@
#include "fa_solid_900.h"
#include "features/about/about_catalog.h"
#include "features/file_transfer/transfer_notification_layout.h"
#include "features/file_transfer/transfer_notification_state.h"
#include "features/file_transfer/file_browser_window.h"
#include "features/gallery/gallery_fullscreen_transition.h"
#include "features/gallery/gallery_window_state.h"
#include "features/gallery/gallery_workspace.h"
@@ -95,6 +97,7 @@
#include "updater/update_controller.h"
#endif
#include "window_geometry.h"
#include "window_presentation.h"
namespace crossdesk {
namespace {
@@ -366,6 +369,19 @@ slint::SharedString UiText(std::string_view value) {
return slint::SharedString(value);
}
slint::SharedString TrustFingerprint(std::string fingerprint) {
for (size_t i = 8; i < fingerprint.size(); i += 9) fingerprint.insert(i, " ");
return UiText(fingerprint);
}
ui::TrustedDeviceEntry TrustRow(const TrustedDevices::Device& device,
const std::string& remote = {}) {
auto id = device.device_id;
if (id.rfind("C-", 0) == 0) id.erase(0, 2);
return {UiText(remote), UiText(device.public_key),
UiText(device.name.empty() ? id : device.name), UiText(id), {}};
}
void RegisterFontAwesome(slint::Window& window) {
if (const auto error = window.window_handle().register_font_from_data(
fa_solid_900_ttf, fa_solid_900_ttf_len)) {
@@ -1051,9 +1067,10 @@ struct GuiApplication::SlintUi {
struct TransferNotification {
std::optional<slint::ComponentHandle<ui::FileTransferNotification>> window;
RemoteSession::FileTransferInfo info;
bool dismissed = false;
transfer_notification::Presentation presentation;
};
std::map<uint32_t, TransferNotification> transfer_notifications;
std::map<std::string, std::unique_ptr<FileBrowserWindow>> file_browsers;
SDL_DisplayID transfer_display = 0;
std::shared_ptr<slint::VectorModel<ui::NetworkStatsRow>> stats_model =
std::make_shared<slint::VectorModel<ui::NetworkStatsRow>>();
@@ -1065,6 +1082,11 @@ struct GuiApplication::SlintUi {
std::string tab_model_signature;
std::vector<std::string> controller_ids;
std::string controller_model_signature;
std::string trusted_device_signature;
std::shared_ptr<slint::VectorModel<ui::TrustedDeviceEntry>> trusted_device_model =
std::make_shared<slint::VectorModel<ui::TrustedDeviceEntry>>();
std::shared_ptr<slint::VectorModel<ui::TrustedDeviceEntry>> trust_candidate_model =
std::make_shared<slint::VectorModel<ui::TrustedDeviceEntry>>();
std::string connection_dialog_remote_id;
bool connection_password_initialized = false;
bool connection_dialog_gallery = false;
@@ -1095,9 +1117,6 @@ struct GuiApplication::SlintUi {
bool server_file_dialog_open = false;
bool server_suspended_for_dialog = false;
server_window_state::EdgeLayout server_layout{};
#if _WIN32
int server_native_window_attempts = 0;
#endif
int localized_language = -1;
std::chrono::steady_clock::time_point last_clipboard_poll{};
slint::Timer video_timer;
@@ -1153,6 +1172,7 @@ int GuiApplication::Run() {
announcements_.SetStorageDirectory(path_manager_->GetCachePath() /
"announcement_reads");
config_center_ = std::make_unique<ConfigCenter>(cache_path_ + "/config.ini");
InitializeTrustedDevices(path_manager_->GetConfigPath() / "trusted-devices");
LOG_INFO("CrossDesk version: {} (Slint UI)", CROSSDESK_VERSION);
@@ -1559,6 +1579,7 @@ void GuiApplication::ResetSettingsUi(bool gallery_window) {
config_center_->IsEnablePrivacyScreen());
main->set_privacy_local_unlock_allowed(config_center_->IsPrivacyLocalUnlockAllowed());
main->set_lock_on_disconnect_enabled(config_center_->IsLockOnDisconnect());
main->set_trusted_devices_only(config_center_->IsTrustedDevicesOnly());
#ifdef _WIN32
main->set_capture_method_visible(true);
main->set_capture_method_index(
@@ -1932,6 +1953,7 @@ void GuiApplication::BindMainCallbacks(bool gallery_window) {
main->set_file_save_path(folder);
}
});
BindTrustedDeviceCallbacks(gallery_window);
main->on_save_settings([this, main] {
return SaveSettingsFromUi(main->get_gallery_mode());
});
@@ -1959,9 +1981,14 @@ void GuiApplication::BindMainCallbacks(bool gallery_window) {
if (updater_ && updater_->busy()) updater_->Cancel();
#endif
});
main->on_open_download([this, main] {
main->on_open_manual_download([this] {
const auto& latest = update_checker_->latest();
OpenUrl(latest && !latest->download_url.empty() ? latest->download_url
: "https://crossdesk.cn");
});
main->on_open_download([this, main] {
#if CROSSDESK_HAS_UPDATER
const auto& latest = update_checker_->latest();
if (updater_ && updater_->busy()) return;
if (updater_ && latest && updater_->Available(latest->update_envelope)) {
main->set_about_open(false);
@@ -1970,8 +1997,7 @@ void GuiApplication::BindMainCallbacks(bool gallery_window) {
return;
}
#endif
OpenUrl(latest && !latest->download_url.empty() ? latest->download_url
: "https://crossdesk.cn");
main->invoke_open_manual_download();
});
main->on_confirm_update([this, main] {
if (!main->get_update_confirm_open()) return;
@@ -1983,8 +2009,12 @@ void GuiApplication::BindMainCallbacks(bool gallery_window) {
!updater_->Available(latest->update_envelope)) return;
updater_->Start(latest->update_envelope);
// Disable both windows immediately, before the next polling tick.
for (const auto& window : {ui_->main, ui_->wall})
for (const auto& window : {ui_->main, ui_->wall}) {
window->set_update_install_busy(updater_->busy());
window->set_update_install_failed(
updater_->state() == updater::Controller::State::Failed);
window->set_update_install_status("");
}
#endif
});
about::Populate(ui_->Window(gallery_window));
@@ -2298,16 +2328,7 @@ void GuiApplication::BindStreamCallbacks() {
SyncAudioPlayback();
});
stream->on_select_file([this] {
auto props = SelectedSession();
if (!props) {
return;
}
OpenFileDialog(localization::select_file[localization_language_index_],
[this, props](std::string path) {
if (!path.empty() && !props->closing_ &&
props->connection_status_ == ConnectionStatus::Connected)
transfers_.ProcessSelectedFile(path, props, props->file_label_);
});
if (auto props = SelectedSession()) OpenFileManager(props->remote_id_);
});
stream->on_can_drop_file(
[](const slint::DataTransfer& data) { return data.has_plain_text(); });
@@ -2420,40 +2441,7 @@ void GuiApplication::BindServerCallbacks() {
selected_server_remote_id_ = ui_->controller_ids[index];
});
server->on_select_file([this] {
if (selected_server_remote_id_.empty() || ui_->server_file_dialog_open) {
return;
}
// Keep the recipient stable if another controller connects or leaves while
// the asynchronous native picker is open.
const std::string recipient = selected_server_remote_id_;
ui_->server_file_dialog_open = true;
(*ui_->server)->window().request_redraw();
const auto select_file = [this, recipient] {
const auto connected = [this, recipient] {
std::shared_lock lock(connection_status_mutex_);
const auto found = connection_status_.find(recipient);
return found != connection_status_.end() &&
found->second == ConnectionStatus::Connected;
};
if (!connected()) {
ui_->server_file_dialog_open = false;
return;
}
OpenFileDialog(localization::select_file[localization_language_index_],
[this, recipient, connected](std::string path) {
ui_->server_file_dialog_open = false;
if (connected() && !path.empty())
transfers_.ProcessSelectedFile(path, nullptr, file_label_, recipient);
});
};
#if defined(__APPLE__)
// The native picker is already dispatched outside the clicked callback.
select_file();
#else
// Let TouchArea release and repaint before the blocking native picker.
ui_->server_file_dialog_timer.start(
slint::TimerMode::SingleShot, std::chrono::milliseconds(32), select_file);
#endif
if (!selected_server_remote_id_.empty()) OpenFileManager(selected_server_remote_id_);
});
server->on_disconnect_controller([this](slint::SharedString id) {
CloseServerController(std::string(id));
@@ -2472,6 +2460,7 @@ void GuiApplication::Tick() {
return;
}
TickLan();
TickControllerTrust();
if (LanAvailable()) {
const auto address = lan_->identity().settings().value("address", "");
ui_->main->set_lan_listen_all(lan_->identity().listen_all());
@@ -2702,6 +2691,15 @@ void GuiApplication::Tick() {
}
SyncStreamWindow();
SyncServerWindow();
SyncTrustedDevices();
for (auto it = ui_->file_browsers.begin(); it != ui_->file_browsers.end();) {
if (!it->second->Tick()) it = ui_->file_browsers.erase(it);
else {
if (it->second->Visible())
it->second->SetPeerName(FileManagerPeerName(it->first));
++it;
}
}
SyncFileTransferNotifications();
}
@@ -2720,18 +2718,22 @@ void GuiApplication::PollUpdateCheck() {
}
const auto& latest = update_checker_->latest();
const bool can_install = latest && updater_->Available(latest->update_envelope);
const bool failed = updater_->state() == updater::Controller::State::Failed;
const int language = localization::detail::ClampLanguageIndex(localization_language_index_);
std::string status;
if (updater_->busy()) {
status = localization::update_preparing[language];
if (updater_->state() == updater::Controller::State::Downloading)
status += " " + std::to_string(updater_->progress()) + "%";
} else if (updater_->state() == updater::Controller::State::Failed) {
status = localization::update_install_failed[language] + "\n" + updater_->error();
} else if (failed) {
status = (can_install ? localization::update_install_failed[language]
: localization::update_install_failed_manual[language]) +
"\n" + updater_->error();
}
for (const auto& main : {ui_->main, ui_->wall}) {
main->set_update_install_available(can_install);
main->set_update_install_busy(updater_->busy());
main->set_update_install_failed(failed);
main->set_update_install_status(UiText(status));
}
}
@@ -2960,6 +2962,7 @@ bool GuiApplication::RequestPasswordChange(const std::string &password) {
password_change_result_ready_ = false;
password_change_succeeded_ = false;
password_change_result_uncertain_ = false;
password_change_recovery_ = false;
password_change_requested_at_ = std::chrono::steady_clock::now();
pending_password_change_request_id_ = request_id;
pending_local_password_ = password;
@@ -3039,6 +3042,7 @@ void GuiApplication::HandlePasswordChangeResult() {
password_change_result_ready_ = false;
password_change_succeeded_ = false;
password_change_result_uncertain_ = false;
password_change_recovery_ = false;
pending_password_change_request_id_.clear();
pending_local_password_.clear();
password_change_error_.clear();
@@ -3085,23 +3089,53 @@ void GuiApplication::HandlePasswordChangeResult() {
}
void GuiApplication::HandleCredentialRecovery() {
bool retry_active = false;
bool promote_pending = false;
bool clear_pending = false;
CredentialRecoveryAction action;
{
std::lock_guard<std::mutex> lock(password_change_mutex_);
retry_active = credential_recovery_retry_active_;
promote_pending = credential_recovery_promote_pending_;
clear_pending = credential_recovery_clear_pending_;
credential_recovery_retry_active_ = false;
credential_recovery_promote_pending_ = false;
credential_recovery_clear_pending_ = false;
if (retry_active) {
action = std::exchange(credential_recovery_action_, CredentialRecoveryAction::Idle);
if (action == CredentialRecoveryAction::RetryActive) {
credential_recovery_attempt_pending_ = false;
}
}
if (retry_active) {
if (action == CredentialRecoveryAction::ResumePending) {
// Key authentication proves device ownership, not which password committed.
// Replay the durable request and promote only its successful server reply.
const bool self_hosted = config_center_->IsSelfHosted();
std::string request_id;
const auto identity = settings_.PendingPasswordChangeIdentity(self_hosted,
self_hosted ? config_center_->GetSignalServerHost() : config_center_->GetDefaultServerHost(),
self_hosted ? config_center_->GetSignalServerPort() : config_center_->GetDefaultSignalServerPort(),
&request_id);
const auto at = identity.find('@');
if (!peer_ || !signal_connected_ || at == std::string::npos || request_id.empty() ||
identity.substr(0, at) != client_id_) return;
const auto password = identity.substr(at + 1);
{
std::lock_guard lock(password_change_mutex_);
if (password_change_pending_) return;
password_change_pending_ = true;
password_change_result_ready_ = false;
password_change_succeeded_ = false;
password_change_result_uncertain_ = false;
password_change_recovery_ = true;
password_change_requested_at_ = std::chrono::steady_clock::now();
pending_password_change_request_id_ = request_id;
pending_local_password_ = password;
password_change_error_.clear();
}
const auto message = nlohmann::json{{"type", "change_password"},
{"request_id", request_id}, {"new_password", password}}.dump();
if (SendSignalMessage(peer_, message.data(), message.size()) != 0) {
std::lock_guard lock(password_change_mutex_);
password_change_result_ready_ = true;
password_change_result_uncertain_ = true;
password_change_error_ = "Password recovery connection unavailable";
}
return;
}
if (action == CredentialRecoveryAction::RetryActive) {
LOG_INFO("Pending credential was not accepted; retrying active credential");
if (peer_) {
CloseConnectionPeer();
@@ -3109,7 +3143,7 @@ void GuiApplication::HandleCredentialRecovery() {
return;
}
if (promote_pending) {
if (action == CredentialRecoveryAction::PromotePending) {
#if defined(__linux__) && !defined(__OHOS__)
HeadlessConsole::Instance().NotifyKey("console_password_recovered");
#endif
@@ -3118,7 +3152,7 @@ void GuiApplication::HandleCredentialRecovery() {
} else {
LOG_INFO("Recovered password change with pending credential");
}
} else if (clear_pending) {
} else if (action == CredentialRecoveryAction::ClearPending) {
#if defined(__linux__) && !defined(__OHOS__)
HeadlessConsole::Instance().NotifyKey("console_password_retained");
#endif
@@ -3155,6 +3189,8 @@ void GuiApplication::UpdateLocalization() {
if (ui_->stream) {
ui_localization::ApplyStreamWindowStrings(*ui_->stream, language);
}
for (auto& [_, browser] : ui_->file_browsers)
browser->UpdateActionLabels(language);
ui_->localized_language = language;
}
@@ -3726,9 +3762,10 @@ void GuiApplication::SyncStreamWindow() {
(*ui_->stream)->set_displays(ui_->display_model);
(*ui_->stream)->set_stats_rows(ui_->stats_model);
BindStreamCallbacks();
(*ui_->stream)->show();
// Repeat after the next layout pass because the backend resolves the
// initial DPI and preferred size asynchronously on some platforms.
(*ui_->stream)->window().set_size(slint::LogicalSize({
kStreamWindowLogicalWidth,
StreamWindowLogicalHeight((*ui_->stream)->get_custom_titlebar())}));
// Resolve placement and any display-DPI change while still hidden.
ui_->stream_initial_position_attempts = 2;
#if defined(__APPLE__)
ui_->stream_live_resize_configuration_attempts = 30;
@@ -3743,8 +3780,10 @@ void GuiApplication::SyncStreamWindow() {
// A wall takeover hides an existing stream window without destroying it.
// Opening a recent device must also restore that existing window.
if (need_to_create_stream_window_) {
(*ui_->stream)->window().set_minimized(false);
(*ui_->stream)->show();
if (ui_->stream_initial_position_attempts == 0) {
(*ui_->stream)->window().set_minimized(false);
(*ui_->stream)->show();
}
need_to_create_stream_window_ = false;
}
#if _WIN32
@@ -3764,7 +3803,8 @@ void GuiApplication::SyncStreamWindow() {
if (ui_->video_presenter && ui_->video_presenter->EnsureAttached()) {
video_frame_dirty_.store(true, std::memory_order_release);
}
if (ui_->stream_initial_position_attempts > 0) {
if (has_sessions && ui_->stream_initial_position_attempts > 0 &&
NativeWindowReady((*ui_->stream)->window())) {
if (PositionWindowAtCenter(
(*ui_->stream)->window(), ui_->main->window(),
kStreamWindowLogicalWidth,
@@ -3773,6 +3813,7 @@ void GuiApplication::SyncStreamWindow() {
} else {
ui_->stream_initial_position_attempts = 0;
}
if (ui_->stream_initial_position_attempts == 0) (*ui_->stream)->show();
}
if (!has_sessions) {
SetStreamKeyboardFocus(false);
@@ -4173,11 +4214,7 @@ void GuiApplication::SetServerPanelExpanded(bool expanded) {
server_window_collapsed_ = !expanded;
(*ui_->server_bar)->set_expanded(expanded);
if (expanded) {
PositionServerWindows();
(*ui_->server)->show();
#if _WIN32
ConfigureWindowsServerWindow((*ui_->server)->window());
#endif
// SyncServerWindow shows the panel after native creation and placement.
PositionServerWindows();
} else {
(*ui_->server)->set_confirming_disconnect(false);
@@ -4258,6 +4295,113 @@ void GuiApplication::PositionServerWindows() {
}
}
void GuiApplication::BindTrustedDeviceCallbacks(bool gallery_window) {
const auto main = ui_->Window(gallery_window);
main->on_trust_action([this, main](
slint::SharedString action, slint::SharedString id, slint::SharedString key) {
const auto message = [this](const char* text) {
return UiText(localization::Literal(text, localization_language_index_));
};
const bool copying = action == "copy";
const auto set_error = [&](const char* text) {
if (copying) main->set_trust_copy_error(message(text));
else main->set_trusted_devices_error(message(text));
};
if (copying || action == "open" || action == "close") {
main->set_trust_copy_error("");
main->set_trust_copy_notice("");
}
if (!copying) {
main->set_trusted_devices_error("");
main->set_trusted_devices_notice("");
}
if (action == "open" || action == "close") {
main->set_trust_pairing_input("");
SyncTrustedDevices();
return;
}
if (!trusted_devices_) {
set_error("无法读取设备身份或可信列表,请修复后再启用。");
return;
}
if (action == "edit") return;
try {
if (copying) {
const auto text = trusted_devices_->PairingInfo(client_id_, GetHostName());
if (SDL_SetClipboardText(text.c_str()))
main->set_trust_copy_notice(message("配对信息已复制。"));
else set_error("无法访问剪贴板,请重试。");
} else if (action == "import") {
const auto input = std::string(main->get_trust_pairing_input());
if (input.empty()) return;
const auto device = TrustedDevices::ParsePairingInfo(input);
if (!device) {
set_error("配对信息无效,请从控制端重新复制。");
return;
}
// The Add action approves the current input. Import only updates the
// list; a live connection must still complete its own authentication.
if (trusted_devices_->Contains(device->public_key)) {
main->set_trusted_devices_notice(message("已在可信列表中"));
} else {
trusted_devices_->Add(*device);
main->set_trusted_devices_notice(message("已加入可信设备。"));
}
main->set_trust_pairing_input("");
} else if ((action == "add" && !TrustController(std::string(id), std::string(key))) ||
(action == "remove" && !RemoveTrustedDevice(std::string(key)))) {
set_error("无法更新可信设备,请检查列表容量和存储权限后重试。");
}
} catch (const std::exception&) {
set_error(copying ? "无法复制配对信息,请重试。"
: "无法更新可信设备,请检查列表容量和存储权限后重试。");
}
SyncTrustedDevices();
});
}
void GuiApplication::SyncTrustedDevices() {
if (!ui_->main->get_trusted_devices_open() && !ui_->wall->get_trusted_devices_open()) return;
std::vector<ui::TrustedDeviceEntry> saved, candidates;
if (trusted_devices_) {
for (const auto& device : trusted_devices_->List()) saved.push_back(TrustRow(device));
for (const auto& id : ConnectedControllers())
if (const auto device = VerifiedController(id);
device && !trusted_devices_->Contains(device->public_key))
candidates.push_back(TrustRow(*device, id));
}
std::sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) {
return std::string(a.remote_id) < std::string(b.remote_id);
});
std::string signature = trusted_devices_ ? "ready" : "unavailable";
for (const auto* rows : {&saved, &candidates}) {
signature += "|";
for (const auto& device : *rows)
signature += std::string(device.remote_id) + '\0' + std::string(device.public_key) + '\0' +
std::string(device.display_name) + '\0' + std::string(device.device_id) + '\0';
}
if (signature != ui_->trusted_device_signature) {
// Tick runs frequently. Hash keys and update Slint only when the rows change.
for (auto* rows : {&saved, &candidates})
for (auto& device : *rows)
device.fingerprint = TrustFingerprint(TrustedDevices::Fingerprint(std::string(device.public_key)));
ui_->trusted_device_model->set_vector(std::move(saved));
ui_->trust_candidate_model->set_vector(std::move(candidates));
ui_->trusted_device_signature = std::move(signature);
const auto fingerprint = TrustFingerprint(trusted_devices_ ? trusted_devices_->Fingerprint() : "");
for (auto& window : {ui_->main, ui_->wall}) {
window->set_trusted_devices(ui_->trusted_device_model);
window->set_trust_candidates(ui_->trust_candidate_model);
window->set_device_fingerprint(fingerprint);
}
}
if (!trusted_devices_) {
for (auto& window : {ui_->main, ui_->wall})
window->set_trusted_devices_error(UiText(localization::Literal(
"无法读取设备身份或可信列表,请修复后再启用。", localization_language_index_)));
}
}
void GuiApplication::SyncServerWindow() {
// The connection map is authoritative. Lifecycle flags record callback
// intent, but callbacks for different controllers can cross each other, so
@@ -4302,10 +4446,6 @@ void GuiApplication::SyncServerWindow() {
BindServerCallbacks();
ui_localization::ApplyServerStrings(*ui_->server, localization_language_index_);
ui_localization::ApplyServerStrings(*ui_->server_bar, localization_language_index_);
(*ui_->server_bar)->show();
#if _WIN32
ui_->server_native_window_attempts = 30;
#endif
server_window_created_ = true;
server_window_inited_ = true;
}
@@ -4325,13 +4465,9 @@ void GuiApplication::SyncServerWindow() {
ui_->server_drag.active = false;
server_window_created_ = false;
server_window_inited_ = false;
#if _WIN32
ui_->server_native_window_attempts = 0;
#endif
}
if (!ui_->server) return;
if (ui_->server_suspended_for_dialog) {
(*ui_->server_bar)->show();
ui_->server_suspended_for_dialog = false;
}
@@ -4372,16 +4508,17 @@ void GuiApplication::SyncServerWindow() {
(*ui_->server_bar)->set_controller_count(static_cast<int>(ui_->controller_ids.size()));
ui_localization::ApplyServerStrings(*ui_->server, localization_language_index_);
ui_localization::ApplyServerStrings(*ui_->server_bar, localization_language_index_);
#if _WIN32
if (ui_->server_native_window_attempts > 0) {
if (ConfigureWindowsServerWindow((*ui_->server_bar)->window()))
ui_->server_native_window_attempts = 0;
else
--ui_->server_native_window_attempts;
}
#endif
(*ui_->server)->set_sending_file(transfers_.global_state().file_sending_.load());
PositionServerWindows();
const auto show_prepared = [](slint::Window& window) {
if (window.is_visible() || !NativeWindowReady(window)) return;
#if _WIN32
if (!ConfigureWindowsServerWindow(window)) return;
#endif
window.show();
};
show_prepared((*ui_->server_bar)->window());
if (!server_window_collapsed_) show_prepared((*ui_->server)->window());
}
void GuiApplication::CancelFileTransfer(uint32_t file_id) {
@@ -4407,16 +4544,72 @@ void GuiApplication::CancelFileTransfer(uint32_t file_id) {
}
}
std::string GuiApplication::FileManagerPeerName(const std::string& remote) {
Thumbnail::RecentConnection device{};
device.remote_id = remote;
if (const auto props = FindRemoteSession(remote)) {
if (const auto direct = props->lan_session_) {
device.remote_id = Thumbnail::LanRecordId(direct->target.device_id);
}
std::lock_guard lock(props->remote_version_mutex_);
device.remote_host_name = props->remote_host_name_;
} else {
std::shared_lock lock(connection_status_mutex_);
if (const auto host = connection_host_names_.find(remote);
host != connection_host_names_.end())
device.remote_host_name = host->second;
}
if (device.remote_host_name.empty() || device.remote_host_name == "unknown") {
for (const auto& [_, recent] : recent_connections_) {
if (recent.remote_id == device.remote_id) {
device.remote_host_name = recent.remote_host_name;
break;
}
}
}
const auto name = settings_.RecentConnectionDisplayName(device);
// Keep transport IDs out of the header while peer information is arriving.
return name == device.remote_id ? std::string{} : name;
}
void GuiApplication::OpenFileManager(const std::string& remote) {
if (!transfers_.OpenBrowser(remote)) return;
if (!transfers_.BrowserSupported(remote)) {
// Host information from older clients omits the capability. Use their
// existing file protocol and picker directly, without a directory RPC.
const auto generation = transfers_.browser().Generation(remote);
OpenFileDialog(std::string(localization::select_file[localization_language_index_]),
[this, remote, generation](std::string path) {
if (path.empty() || !transfers_.BrowserConnected(remote) ||
transfers_.browser().Generation(remote) != generation) return;
const auto props = FindRemoteSession(remote);
transfers_.ProcessSelectedFile(path, props,
props ? props->file_label_ : file_label_, remote);
});
return;
}
auto& browser = ui_->file_browsers[remote];
if (browser && !browser->Tick()) browser.reset();
if (!browser) {
const bool controller = static_cast<bool>(FindRemoteSession(remote));
browser = std::make_unique<FileBrowserWindow>(transfers_, remote, controller,
localization_language_index_);
}
browser->SetPeerName(FileManagerPeerName(remote));
browser->Show();
SyncFileTransferNotifications();
}
void GuiApplication::SyncFileTransferNotifications() {
using Status = RemoteSession::FileTransferStatus;
using namespace transfer_notification;
std::map<uint32_t, RemoteSession::FileTransferInfo> files;
const auto collect = [&](FileTransferState& state) {
std::lock_guard lock(state.file_transfer_list_mutex_);
for (const auto& info : state.file_transfer_list_) files.emplace(info.file_id, info);
for (const auto& info : state.file_transfer_list_)
if (!info.receiving) files.emplace(info.file_id, info);
};
collect(transfers_.global_state());
collect(transfers_.received_state());
{
std::shared_lock lock(remote_sessions_mutex_);
for (const auto& [_, props] : remote_sessions_) {
@@ -4431,11 +4624,17 @@ void GuiApplication::SyncFileTransferNotifications() {
operation.state != SlintUi::BatchOperation::State::Finished)
pending_files.insert(operation.file_id);
// Retain the last progress independently of session lifetime. Results stay
// visible until dismissed, including after the connection is closed.
// visible until dismissed or presented in the browser, even after disconnect.
for (const auto& [id, info] : files)
ui_->transfer_notifications[id].info = info;
std::erase_if(ui_->transfer_notifications, [&](auto& item) {
if (!item.second.dismissed || files.count(item.first) ||
// Progress belongs to the sender. Remove any cached receive popup as well,
// regardless of window visibility, peer version or final transfer status.
if (item.second.info.receiving) {
if (item.second.window) (*item.second.window)->hide();
return true;
}
if ((!item.second.presentation.dismissed && !item.second.presentation.result_seen) || files.count(item.first) ||
pending_files.count(item.first)) return false;
if (item.second.window) (*item.second.window)->hide();
return true;
@@ -4475,7 +4674,11 @@ void GuiApplication::SyncFileTransferNotifications() {
}
const bool completed = info.status == Status::Completed;
const bool failed = info.status == Status::Failed;
if (notification.dismissed || slot >= layout.capacity()) {
const auto browser = ui_->file_browsers.find(info.remote_id);
const bool in_browser = browser != ui_->file_browsers.end() && browser->second->PresentsTransfers();
const bool result_presented = in_browser && browser->second->PresentsResult(id, info.status);
if (!notification.presentation.ShowNotification(in_browser, result_presented) ||
slot >= layout.capacity()) {
if (notification.window) {
(*notification.window)->hide();
notification.window.reset();
@@ -4489,7 +4692,7 @@ void GuiApplication::SyncFileTransferNotifications() {
const auto dismiss = [this, id] {
const auto found = ui_->transfer_notifications.find(id);
if (found == ui_->transfer_notifications.end()) return;
found->second.dismissed = true;
found->second.presentation.dismissed = true;
if (found->second.window) (*found->second.window)->hide();
};
(*notification.window)->on_dismissed(dismiss);
@@ -4519,15 +4722,12 @@ void GuiApplication::SyncFileTransferNotifications() {
auto display_id = info.remote_id;
std::erase_if(display_id, [](unsigned char c) { return c < '0' || c > '9'; });
component->set_remote_id(UiText(display_id));
component->set_heading(UiText(info.receiving
? localization::file_receiving_progress[localization_language_index_]
: localization::file_sending_progress[localization_language_index_]));
component->set_transferring(info.status == Status::Sending || info.status == Status::Receiving);
component->set_heading(UiText(localization::file_sending_progress[localization_language_index_]));
component->set_transferring(info.status == Status::Sending);
component->set_completed(completed);
component->set_failed(failed);
component->set_cancelled(info.status == Status::Cancelled || info.status == Status::Cancelling);
component->set_can_cancel(!info.receiving &&
(info.status == Status::Queued || info.status == Status::Sending));
component->set_can_cancel(info.status == Status::Queued || info.status == Status::Sending);
component->set_cancel_text(UiText(localization::cancel[localization_language_index_]));
auto& window = component->window();
const auto size = window.size();
@@ -4551,13 +4751,8 @@ void GuiApplication::SyncFileTransferNotifications() {
#endif
}
if (!window.is_visible()) {
#if defined(__APPLE__)
// Winit creates native windows on the next event-loop turn. Wait until
// it exists so show() and focus restoration happen synchronously.
if (!window.appkit_view()) continue;
#elif _WIN32
if (!window.win32_hwnd()) continue;
#endif
// Wait until native placement and focus restoration can be synchronous.
if (!NativeWindowReady(window)) continue;
#if _WIN32
// Tool windows stay out of Alt-Tab and must not interrupt remote input.
const auto configure = [&] {
@@ -4610,6 +4805,11 @@ bool GuiApplication::SaveSettingsFromUi(bool gallery_window) {
const auto previous_connection_mode = config_center_->GetConnectionMode();
auto& main = ui_->Window(gallery_window);
main->set_settings_save_error("");
if (main->get_trusted_devices_only() && !trusted_devices_) {
main->set_settings_save_error(UiText(localization::Literal(
"无法读取设备身份或可信列表,请修复后再启用。", localization_language_index_)));
return false;
}
const bool has_endpoint = main->get_self_hosted_enabled() ||
!std::string(main->get_server_host()).empty() ||
!std::string(main->get_server_port()).empty();
@@ -4769,6 +4969,12 @@ bool GuiApplication::SaveSettingsFromUi(bool gallery_window) {
props->preview_needs_sync_ = true;
ui_->gallery_synced = {};
}
if (config_center_->SetTrustedDevicesOnly(main->get_trusted_devices_only()) != 0) {
main->set_settings_save_error(UiText(localization::Literal(
"无法保存可信设备设置,请重试。", localization_language_index_)));
return false;
}
TickControllerTrust();
ApplySettingsFromConfig(previous_server !=
GetSignalServerSettings(*config_center_));
ResetSettingsUi(gallery_window);
@@ -54,6 +54,7 @@ private:
void ShowMainWindow(const std::string& activation_token = {});
bool MinimizeMainWindowToTray();
void BindMainCallbacks(bool gallery_window = false);
void BindTrustedDeviceCallbacks(bool gallery_window = false);
void BindStreamCallbacks();
void BindServerCallbacks();
void Tick();
@@ -92,7 +93,10 @@ private:
void SyncStreamKeyboardFocus();
void SetStreamKeyboardFocus(bool focused);
void SyncServerWindow();
void SyncTrustedDevices();
void SyncFileTransferNotifications();
void OpenFileManager(const std::string& remote);
std::string FileManagerPeerName(const std::string& remote);
void CancelFileTransfer(uint32_t file_id);
void SetServerPanelExpanded(bool expanded);
void PositionServerWindows();
@@ -0,0 +1,21 @@
#pragma once
#include <slint.h>
namespace crossdesk {
// Winit creates hidden native windows on a later event-loop turn. Wait for
// that window before applying geometry that depends on its frame or DPI.
inline bool NativeWindowReady([[maybe_unused]] const slint::Window& window) {
#if defined(_WIN32)
return window.win32_hwnd() != nullptr;
#elif defined(__APPLE__)
return window.appkit_view() != nullptr;
#else
// Other backends accept initial geometry before show(); Wayland placement
// is controlled by the compositor and must not wait for a mapped surface.
return true;
#endif
}
} // namespace crossdesk
@@ -386,7 +386,7 @@ inline constexpr TranslationRow kTranslationRows[] = {
{"设置(修改后立即保存)", {"设置(修改后立即保存)", "Settings (each change is saved immediately)", "Настройки (изменения сохраняются сразу)", "設定(修改後立即儲存)", "設定 (各変更はすぐに保存されます)", "설정(각 변경 사항은 즉시 저장됩니다)", "Einstellungen (jede Änderung wird sofort gespeichert)", "Paramètres (chaque modification est enregistrée immédiatement)", "Configuración (cada cambio se guarda inmediatamente)", "Configurações (cada alteração é salva imediatamente)"}},
{"访问官网: ", {"访问官网: ", "Access Website: ", "Официальный сайт: ", "訪問官網: ", "ウェブサイトにアクセス: ", "웹사이트 접속: ", "Zugriff auf die Website: ", "Accéder au site Web : ", "Acceder al sitio web: ", "Acesse o site: "}},
{"访问密码必须为 6 位英文字母或数字,区分大小写。", {"访问密码必须为 6 位英文字母或数字,区分大小写。", "Use exactly 6 letters (A–Z, a–z) or digits (0–9). Case-sensitive.", "Пароль: ровно 6 латинских букв или цифр. Регистр учитывается.", "訪問密碼必須為 6 位英文字母或數字,區分大小寫。", "正確に 6 つの文字 (A ~ Z、a ~ z) または数字 (0 ~ 9) を使用してください。大文字と小文字を区別。", "정확히 6개의 문자(A–Z, a–z) 또는 숫자(0–9)를 사용하세요. 대소문자를 구분합니다.", "Verwenden Sie genau 6 Buchstaben (A–Z, a–z) oder Ziffern (0–9). Groß- und Kleinschreibung beachten.", "Utilisez exactement 6 lettres (A–Z, a–z) ou chiffres (0–9). Sensible aux majuscules et minuscules.", "Utilice exactamente 6 letras (A–Z, a–z) o dígitos (0–9). Distingue mayúsculas y minúsculas.", "Use exatamente 6 letras (A–Z, a–z) ou dígitos (0–9). Maiúsculas e minúsculas."}},
{"证书验证失败,请重新安装自托管根证书", {"证书验证失败,请重新安装自托管根证书", "Certificate verification failed. Reinstall the self-hosted root certificate.", "Ошибка проверки сертификата. Переустановите корневой сертификат собственного сервера.", "證書驗證失敗,請重新安裝自託管根證書", "証明書の検証に失敗しました。セルフホスト型ルート証明書を再インストールします。", "인증서 확인에 실패했습니다. 자체 호스팅 루트 인증서를 다시 설치합니다.", "Die Zertifikatsüberprüfung ist fehlgeschlagen. Installieren Sie das selbstgehostete Stammzertifikat neu.", "La vérification du certificat a échoué. Réinstallez le certificat racine auto-hébergé.", "Falló la verificación del certificado. Reinstale el certificado raíz autohospedado.", "Falha na verificação do certificado. Reinstale o certificado raiz auto-hospedado."}},
{"服务器证书无效或已过期,正在自动重试", {"服务器证书无效或已过期,正在自动重试", "Server certificate invalid or expired. Retrying automatically.", "Сертификат сервера недействителен или просрочен. Повторяем подключение автоматически.", "伺服器憑證無效或已過期,正在自動重試", "サーバー証明書が無効か期限切れです。自動的に再試行します。", "서버 인증서가 유효하지 않거나 만료되었습니다. 자동으로 재시도합니다.", "Serverzertifikat ungültig oder abgelaufen. Automatischer Neuversuch.", "Certificat du serveur invalide ou expiré. Nouvelle tentative automatique.", "Certificado del servidor no válido o caducado. Reintentando automáticamente.", "Certificado do servidor inválido ou expirado. Tentando novamente automaticamente."}},
{"该分组暂无近期连接", {"该分组暂无近期连接", "No recent connections in this group", "В этой группе нет недавних подключений", "該分組暫無近期連線", "このグループには最近の接続がありません", "이 그룹에는 최근 연결이 없습니다.", "Keine aktuellen Verbindungen in dieser Gruppe", "Aucune connexion récente dans ce groupe", "No hay conexiones recientes en este grupo.", "Nenhuma conexão recente neste grupo"}},
{"该应用需要授权以下权限:", {"该应用需要授权以下权限:", "The application requires the following permissions:", "Для работы приложения требуются следующие разрешения:", "該應用需要授權以下許可權:", "アプリケーションには次の権限が必要です。", "애플리케이션에는 다음 권한이 필요합니다.", "Die Anwendung erfordert die folgenden Berechtigungen:", "L'application nécessite les autorisations suivantes :", "La aplicación requiere los siguientes permisos:", "O aplicativo requer as seguintes permissões:"}},
{"该设备正在连接,请稍候", {"该设备正在连接,请稍候", "This device is already connecting", "Устройство уже подключается", "該裝置正在連線,請稍候", "このデバイスはすでに接続されています", "이 장치는 이미 연결되어 있습니다", "Dieses Gerät stellt bereits eine Verbindung her", "Cet appareil est déjà connecté", "Este dispositivo ya se está conectando", "Este dispositivo já está conectado"}},
@@ -494,6 +494,37 @@ inline constexpr TranslationRow kTranslationRows[] = {
{":同步键鼠到所有已连接设备", {":同步键鼠到所有已连接设备", ": mirror input to all connected devices", ": ввод на всех подключённых устройствах", ":同步鍵鼠到所有已連線裝置", ": 接続されているすべてのデバイスへのミラー入力", ": 연결된 모든 장치에 대한 미러 입력", ": Eingang auf alle angeschlossenen Geräte spiegeln", ": entrée miroir sur tous les appareils connectés", ": entrada espejo para todos los dispositivos conectados", ": entrada espelhada para todos os dispositivos conectados"}},
{"监听所有 IP 接口", {"监听所有 IP 接口", "Listen on all IP interfaces", "Все IP-интерфейсы", "監聽所有 IP 介面", "すべての IP で待ち受け", "모든 IP 인터페이스 수신", "Alle IP-Schnittstellen", "Toutes les interfaces IP", "Todas las interfaces IP", "Todas as interfaces IP"}},
{"所有接口共用一个端口,包括 VPN。分享时请选择实际 IP;关闭后恢复各 IP 的独立端口。", {"所有接口共用一个端口,包括 VPN。分享时请选择实际 IP;关闭后恢复各 IP 的独立端口。", "Use one port on all interfaces, including VPNs. Select an actual IP to share. Turn off to restore separate ports per IP.", "Один порт для всех интерфейсов, включая VPN. Для подключения выберите реальный IP. Отключение вернёт отдельные порты для каждого IP.", "所有介面共用一個連接埠,包括 VPN。分享時請選擇實際 IP;關閉後恢復各 IP 的獨立連接埠。", "VPN を含む全インターフェースで同じポートを使います。共有には実際の IP を選択してください。オフにすると IP ごとのポートに戻ります。", "VPN을 포함한 모든 인터페이스가 하나의 포트를 사용합니다. 공유할 실제 IP를 선택하세요. 끄면 IP별 포트가 복원됩니다.", "Ein Port für alle Schnittstellen, einschließlich VPN. Zum Teilen eine tatsächliche IP wählen. Ausschalten stellt die Ports pro IP wieder her.", "Un port commun à toutes les interfaces, VPN inclus. Choisissez une IP réelle à partager. Désactivez pour rétablir les ports propres à chaque IP.", "Un puerto para todas las interfaces, incluidas las VPN. Seleccione una IP real para compartir. Desactive para restaurar los puertos de cada IP.", "Uma porta para todas as interfaces, incluindo VPNs. Selecione um IP real para compartilhar. Desative para restaurar as portas de cada IP."}},
{"可信设备", {"可信设备", "Trusted devices", "Доверенные устройства", "可信裝置", "信頼済みデバイス", "신뢰하는 기기", "Vertrauenswürdige Geräte", "Appareils de confiance", "Dispositivos de confianza", "Dispositivos confiáveis"}},
{"仅允许可信设备控制", {"仅允许可信设备控制", "Only allow trusted devices", "Разрешать только доверенные устройства", "僅允許可信裝置控制", "信頼済みデバイスのみ許可", "신뢰하는 기기만 제어 허용", "Nur vertrauenswürdige Geräte zulassen", "Autoriser uniquement les appareils de confiance", "Permitir solo dispositivos de confianza", "Permitir apenas dispositivos confiáveis"}},
{"管理可信设备", {"管理可信设备", "Manage trusted devices", "Управление доверенными устройствами", "管理可信裝置", "信頼済みデバイスを管理", "신뢰하는 기기 관리", "Vertrauenswürdige Geräte verwalten", "Gérer les appareils de confiance", "Administrar dispositivos de confianza", "Gerenciar dispositivos confiáveis"}},
{"可添加的已连接设备", {"可添加的已连接设备", "Connected devices available to trust", "Подключённые устройства для добавления", "可新增的已連線裝置", "追加可能な接続中のデバイス", "추가 가능한 연결된 기기", "Verbundene Geräte zum Hinzufügen", "Appareils connectés à ajouter", "Dispositivos conectados que puedes añadir", "Dispositivos conectados disponíveis"}},
{"信任此设备", {"信任此设备", "Trust this device", "Доверять устройству", "信任此裝置", "このデバイスを信頼", "이 기기 신뢰", "Diesem Gerät vertrauen", "Faire confiance à cet appareil", "Confiar en este dispositivo", "Confiar neste dispositivo"}},
{"移除信任", {"移除信任", "Remove trust", "Отозвать доверие", "移除信任", "信頼を解除", "신뢰 해제", "Vertrauen entfernen", "Retirer la confiance", "Retirar confianza", "Remover confiança"}},
{"无法读取设备身份或可信列表,请修复后再启用。", {"无法读取设备身份或可信列表,请修复后再启用。", "Could not load the device identity or trusted list. Repair the local data before enabling this restriction.", "Не удалось загрузить идентификатор устройства или список доверия. Восстановите локальные данные перед включением ограничения.", "無法讀取裝置身分或可信清單,請修復後再啟用。", "デバイス情報または信頼リストを読み込めません。ローカルデータを修復してから制限を有効にしてください。", "기기 ID 또는 신뢰 목록을 불러올 수 없습니다. 로컬 데이터를 복구한 후 제한을 켜세요.", "Geräteidentität oder Vertrauensliste konnte nicht geladen werden. Lokale Daten vor dem Aktivieren reparieren.", "Impossible de charger l’identité ou la liste de confiance. Réparez les données locales avant d’activer la restriction.", "No se pudo cargar la identidad o la lista de confianza. Repara los datos locales antes de activar la restricción.", "Não foi possível carregar a identidade ou a lista confiável. Repare os dados locais antes de ativar a restrição."}},
{"无法保存可信设备设置,请重试。", {"无法保存可信设备设置,请重试。", "Could not save trusted device settings. Try again.", "Не удалось сохранить настройки доверенных устройств. Повторите попытку.", "無法儲存可信裝置設定,請重試。", "信頼済みデバイスの設定を保存できません。再試行してください。", "신뢰하는 기기 설정을 저장할 수 없습니다. 다시 시도하세요.", "Einstellungen für vertrauenswürdige Geräte konnten nicht gespeichert werden. Erneut versuchen.", "Impossible d’enregistrer les paramètres de confiance. Réessayez.", "No se pudo guardar la configuración de confianza. Inténtalo de nuevo.", "Não foi possível salvar as configurações de confiança. Tente novamente."}},
{"粘贴", {"粘贴", "Paste", "Вставить", "貼上", "貼り付け", "붙여넣기", "Einfügen", "Coller", "Pegar", "Colar"}},
{"粘贴控制端的配对信息", {"粘贴控制端的配对信息", "Paste the controller’s pairing information", "Вставьте данные сопряжения управляющего устройства", "貼上控制端的配對資訊", "操作側のペアリング情報を貼り付け", "제어 장치의 페어링 정보 붙여넣기", "Kopplungsdaten des steuernden Geräts einfügen", "Collez les informations d’association de l’appareil de contrôle", "Pegue la información de emparejamiento del dispositivo de control", "Cole as informações de pareamento do dispositivo controlador"}},
{"已在可信列表中", {"已在可信列表中", "Already trusted", "Уже доверенное", "已在可信清單中", "信頼済み", "이미 신뢰하는 장치", "Bereits vertrauenswürdig", "Déjà approuvé", "Ya es de confianza", "Já é confiável"}},
{"无法访问剪贴板,请重试。", {"无法访问剪贴板,请重试。", "Cannot access the clipboard. Please try again.", "Не удалось получить доступ к буферу обмена. Повторите попытку.", "無法存取剪貼簿,請重試。", "クリップボードにアクセスできません。もう一度お試しください。", "클립보드에 접근할 수 없습니다. 다시 시도하세요.", "Kein Zugriff auf die Zwischenablage. Bitte erneut versuchen.", "Impossible d’accéder au presse-papiers. Réessayez.", "No se puede acceder al portapapeles. Inténtelo de nuevo.", "Não foi possível acessar a área de transferência. Tente novamente."}},
{"配对信息无效,请从控制端重新复制。", {"配对信息无效,请从控制端重新复制。", "Invalid pairing information. Copy it again from the controller.", "Недопустимые данные сопряжения. Скопируйте их заново с управляющего устройства.", "配對資訊無效,請從控制端重新複製。", "ペアリング情報が無効です。操作側からコピーし直してください。", "유효하지 않은 페어링 정보입니다. 제어 장치에서 다시 복사하세요.", "Ungültige Kopplungsdaten. Kopieren Sie sie erneut vom steuernden Gerät.", "Informations d’association invalides. Copiez-les à nouveau depuis l’appareil de contrôle.", "Información de emparejamiento no válida. Cópiela de nuevo del dispositivo de control.", "Informações de pareamento inválidas. Copie-as novamente do dispositivo controlador."}},
{"已加入可信设备。", {"已加入可信设备。", "Device added to the trusted list.", "Устройство добавлено в список доверенных.", "已加入可信裝置。", "信頼済みデバイスに追加しました。", "신뢰 장치 목록에 추가했습니다.", "Gerät zur Vertrauensliste hinzugefügt.", "Appareil ajouté à la liste de confiance.", "Dispositivo añadido a la lista de confianza.", "Dispositivo adicionado à lista de confiança."}},
{"无法更新可信设备,请检查列表容量和存储权限后重试。", {"无法更新可信设备,请检查列表容量和存储权限后重试。", "Cannot update trusted devices. Check the list capacity and storage permissions, then try again.", "Не удалось обновить список доверенных устройств. Проверьте его размер и права доступа к хранилищу.", "無法更新可信裝置,請檢查清單容量和儲存權限後重試。", "信頼済みデバイスを更新できません。リストの上限と保存先の権限を確認してください。", "신뢰 장치를 업데이트할 수 없습니다. 목록 용량과 저장 권한을 확인한 후 다시 시도하세요.", "Vertrauensliste konnte nicht aktualisiert werden. Prüfen Sie die Listenbegrenzung und Speicherberechtigungen.", "Impossible de mettre à jour les appareils de confiance. Vérifiez la capacité de la liste et les autorisations de stockage.", "No se pueden actualizar los dispositivos de confianza. Compruebe la capacidad de la lista y los permisos de almacenamiento.", "Não foi possível atualizar os dispositivos confiáveis. Verifique a capacidade da lista e as permissões de armazenamento."}},
{"复制配对信息", {"复制配对信息", "Copy pairing info", "Копировать данные", "複製配對資訊", "ペアリング情報をコピー", "페어링 정보 복사", "Kopplungsdaten kopieren", "Copier les informations", "Copiar información", "Copiar informações"}},
{"添加可信设备", {"添加可信设备", "Add a trusted device", "Добавить доверенное устройство", "新增可信裝置", "信頼するデバイスを追加", "신뢰 장치 추가", "Vertrauenswürdiges Gerät hinzufügen", "Ajouter un appareil de confiance", "Añadir dispositivo de confianza", "Adicionar dispositivo confiável"}},
{"已信任的设备", {"已信任的设备", "Trusted devices", "Доверенные устройства", "已信任的裝置", "信頼済みデバイス", "신뢰하는 장치", "Vertrauenswürdige Geräte", "Appareils de confiance", "Dispositivos de confianza", "Dispositivos confiáveis"}},
{"本机配对信息", {"本机配对信息", "This device’s pairing info", "Данные этого устройства", "本機配對資訊", "このデバイスのペアリング情報", "이 장치의 페어링 정보", "Kopplungsdaten dieses Geräts", "Informations de cet appareil", "Información de este dispositivo", "Informações deste dispositivo"}},
{"查看指纹", {"查看指纹", "View fingerprint", "Показать отпечаток", "查看指紋", "フィンガープリントを表示", "지문 보기", "Fingerabdruck anzeigen", "Afficher l’empreinte", "Ver huella", "Ver impressão digital"}},
{"收起指纹", {"收起指纹", "Hide fingerprint", "Скрыть отпечаток", "收起指紋", "フィンガープリントを隠す", "지문 숨기기", "Fingerabdruck ausblenden", "Masquer l’empreinte", "Ocultar huella", "Ocultar impressão digital"}},
{"暂无可信设备", {"暂无可信设备", "No trusted devices", "Нет доверенных устройств", "暫無可信裝置", "信頼済みデバイスはありません", "신뢰하는 장치 없음", "Keine vertrauenswürdigen Geräte", "Aucun appareil de confiance", "No hay dispositivos de confianza", "Nenhum dispositivo confiável"}},
{"请核对控制端指纹。", {"请核对控制端指纹。", "Check the fingerprint on the controller.", "Сверьте отпечаток с управляющим устройством.", "請核對控制端指紋。", "操作側のフィンガープリントと照合してください。", "제어 장치의 지문과 대조하세요.", "Mit dem Fingerabdruck des steuernden Geräts vergleichen.", "Vérifiez l’empreinte sur l’appareil de contrôle.", "Verifique la huella en el dispositivo de control.", "Confira a impressão digital no dispositivo controlador."}},
{"配对信息已复制。", {"配对信息已复制。", "Pairing information copied.", "Данные сопряжения скопированы.", "配對資訊已複製。", "ペアリング情報をコピーしました。", "페어링 정보를 복사했습니다.", "Kopplungsdaten kopiert.", "Informations d’association copiées.", "Información de emparejamiento copiada.", "Informações de pareamento copiadas."}},
{"无法复制配对信息,请重试。", {"无法复制配对信息,请重试。", "Unable to copy pairing information. Please try again.", "Не удалось скопировать данные сопряжения. Повторите попытку.", "無法複製配對資訊,請重試。", "ペアリング情報をコピーできません。もう一度お試しください。", "페어링 정보를 복사할 수 없습니다. 다시 시도하세요.", "Kopplungsdaten konnten nicht kopiert werden. Bitte erneut versuchen.", "Impossible de copier les informations d’association. Réessayez.", "No se pudo copiar la información de emparejamiento. Inténtelo de nuevo.", "Não foi possível copiar as informações de pareamento. Tente novamente."}},
{"重试更新", {"重试更新", "Retry update", "Повторить", "重試更新", "再試行", "다시 시도", "Erneut versuchen", "Réessayer", "Reintentar", "Tentar novamente"}},
{"更新未完成,请手动下载安装。", {"更新未完成,请手动下载安装。", "Update did not complete. Download and install manually.", "Обновление не завершено. Скачайте и установите вручную.", "更新未完成,請手動下載安裝。", "アップデートが完了しませんでした。手動でダウンロードしてインストールしてください。", "업데이트가 완료되지 않았습니다. 수동으로 다운로드하여 설치하세요.", "Das Update wurde nicht abgeschlossen. Laden Sie es herunter und installieren Sie es manuell.", "La mise à jour n'a pas été effectuée. Téléchargez-la et installez-la manuellement.", "La actualización no se completó. Descárguela e instálela manualmente.", "A atualização não foi concluída. Baixe e instale manualmente."}},
{"发送到远端", {"发送到远端", "Send to remote", "Отправить на удалённый ПК", "傳送到遠端", "リモートへ送信", "원격으로 보내기", "An Remote-PC senden", "Envoyer au PC distant", "Enviar al equipo remoto", "Enviar ao computador remoto"}},
{"发送到本机", {"发送到本机", "Send to local", "Отправить на этот ПК", "傳送到本機", "この端末へ送信", "이 기기로 보내기", "An diesen PC senden", "Envoyer à ce PC", "Enviar a este equipo", "Enviar a este computador"}},
{"清除已完成", {"清除已完成", "Clear completed", "Убрать завершённые", "清除已完成", "完了済みをクリア", "완료 항목 지우기", "Abgeschlossene entfernen", "Effacer les tâches terminées", "Limpiar completadas", "Limpar concluídas"}},
{"打开目录", {"打开目录", "Open folder", "Открыть папку", "開啟目錄", "フォルダーを開く", "폴더 열기", "Ordner öffnen", "Ouvrir le dossier", "Abrir carpeta", "Abrir pasta"}},
};
struct NamedTranslation { const char* name; const char* literal; };
@@ -676,7 +707,7 @@ inline constexpr NamedTranslation kNamedTranslations[] = {
{"signal_disconnected", "未连接服务器"},
{"signal_reconnect", "重新连接"},
{"signal_reconnecting", "正在重新连接..."},
{"signal_tls_cert_error", "证书验证失败,请重新安装自托管根证书"},
{"signal_tls_cert_error", "服务器证书无效或已过期,正在自动重试"},
{"p2p_connected", "对等连接已建立"},
{"p2p_disconnected", "对等连接已断开"},
{"p2p_connecting", "正在建立对等连接..."},
@@ -708,10 +739,12 @@ inline constexpr NamedTranslation kNamedTranslations[] = {
{"access_website", "访问官网: "},
{"update", "更新"},
{"install_update", "安装更新"},
{"retry_update", "重试更新"},
{"manual_download", "手动下载"},
{"install_update_confirm", "下载完成后将关闭 CrossDesk 并安装更新,当前连接和文件传输会中断。安装需要系统授权,完成后重新启动。是否继续?"},
{"update_preparing", "正在准备更新…"},
{"update_install_failed", "更新未完成,可重试或手动安装。"},
{"update_install_failed_manual", "更新未完成,请手动下载安装。"},
{"connection_alias", "修改名称"},
{"delete_connection", "删除连接"},
{"connect_to_this_connection", "发起连接"},
@@ -1204,10 +1237,12 @@ inline constexpr const char* kSlintLiterals[] = {
X(access_website) \
X(update) \
X(install_update) \
X(retry_update) \
X(manual_download) \
X(install_update_confirm) \
X(update_preparing) \
X(update_install_failed) \
X(update_install_failed_manual) \
X(connection_alias) \
X(delete_connection) \
X(connect_to_this_connection) \
@@ -0,0 +1,566 @@
#include "features/file_transfer/file_browser.h"
#include <file_transfer_core.h>
#include <algorithm>
#include <cctype>
#include <charconv>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
#include <stdexcept>
#include "filesystem_utf8.h"
namespace crossdesk {
namespace {
using Json = FileBrowser::Json;
namespace fs = std::filesystem;
constexpr size_t kPageEntries = 512;
constexpr size_t kPageBytes = 45000;
std::string Utf8(const fs::path& path) {
const auto value = path.u8string();
return {value.begin(), value.end()};
}
fs::path Home() {
#ifdef _WIN32
const auto* home = std::getenv("USERPROFILE");
#else
const auto* home = std::getenv("HOME");
#endif
return home ? PathFromUtf8(home) : fs::current_path();
}
Json Failure(const std::string& reason) { return {{"ok", false}, {"error", reason}}; }
template <typename FileTime>
auto SystemTime(FileTime time, FileTime file_now, std::chrono::system_clock::time_point system_now) {
using Clock = typename FileTime::clock;
if constexpr (requires { Clock::to_sys(time); })
return std::chrono::time_point_cast<std::chrono::system_clock::duration>(Clock::to_sys(time));
else
return std::chrono::time_point_cast<std::chrono::system_clock::duration>(time - file_now + system_now);
}
std::pair<std::string, size_t> ParseCursor(const std::string& cursor) {
const auto split = cursor.find(':');
if (cursor.size() > 64 || split == std::string::npos || !split)
throw std::runtime_error("invalid_listing");
size_t offset = 0;
const auto end = cursor.data() + cursor.size();
const auto parsed = std::from_chars(cursor.data() + split + 1, end, offset);
if (parsed.ec != std::errc{} || parsed.ptr != end)
throw std::runtime_error("invalid_listing");
return {cursor.substr(0, split), offset};
}
Json Page(const Json& listing, size_t offset, const std::string& snapshot) {
const auto& entries = listing.at("entries");
if (offset > entries.size()) throw std::runtime_error("invalid_listing");
Json page{{"ok", true}, {"path", listing.at("path")}, {"parent", listing.at("parent")},
{"entries", Json::array()}, {"offset", offset}, {"total", entries.size()}};
size_t next = offset, bytes = 0;
while (next < entries.size() && next - offset < kPageEntries) {
const auto entry_bytes = entries[next].dump(-1, ' ', false, Json::error_handler_t::replace).size() + 1;
if (entry_bytes > kPageBytes) throw std::runtime_error("invalid_listing");
if (bytes + entry_bytes > kPageBytes) break;
page["entries"].push_back(entries[next++]);
bytes += entry_bytes;
}
page["truncated"] = next < entries.size();
page["next"] = next < entries.size() && !snapshot.empty()
? snapshot + ":" + std::to_string(next) : "";
return page;
}
std::string Text(const Json& value, const char* key) {
const auto& field = value.at(key);
if (!field.is_string()) throw std::runtime_error("invalid_request");
auto text = field.get<std::string>();
if (text.size() > 4096 || text.find('\0') != std::string::npos)
throw std::runtime_error("invalid_path");
return text;
}
fs::path ExistingDirectory(const std::string& path) {
if (path.empty()) throw std::runtime_error("invalid_path");
auto input = PathFromUtf8(path);
if (!input.is_absolute()) throw std::runtime_error("invalid_path");
std::error_code ec;
auto result = fs::canonical(input, ec);
if (ec || !fs::is_directory(result, ec)) throw std::runtime_error("directory_unavailable");
return result;
}
fs::path Destination(const fs::path& root, const std::string& relative) {
auto path = PathFromUtf8(relative);
if (path.is_absolute() || path.has_root_name()) throw std::runtime_error("invalid_path");
auto result = root;
for (const auto& component : path) {
if (component == "." || component == "..") throw std::runtime_error("invalid_path");
result /= component;
std::error_code ec;
// Do not follow links within a transferred folder hierarchy.
if (fs::is_symlink(fs::symlink_status(result, ec))) throw std::runtime_error("symbolic_link");
ec.clear();
fs::create_directory(result, ec);
if (ec && ec != std::errc::file_exists) throw std::runtime_error("directory_not_writable");
if (!fs::is_directory(result)) throw std::runtime_error("directory_not_writable");
}
return result;
}
}
FileBrowser::FileBrowser(Send send, Enqueue enqueue, Reserve reserve, Cancel cancel)
: send_(std::move(send)), enqueue_(std::move(enqueue)), reserve_(std::move(reserve)), cancel_(std::move(cancel)),
worker_([this] { Run(); }) {}
FileBrowser::~FileBrowser() { Stop(); }
void FileBrowser::Stop() {
{ std::lock_guard lock(mutex_); stopping_ = true; jobs_.clear();
for (const auto& [_, listing] : listings_) listing->cancelled = true;
listings_.clear();
}
wake_.notify_all();
if (worker_.joinable()) worker_.join();
}
void FileBrowser::Post(const std::string& peer, std::function<void()> work) {
std::lock_guard lock(mutex_);
if (stopping_ || jobs_.size() >= 512) return;
const auto generation = generations_[peer];
jobs_.push_back([this, peer, generation, work = std::move(work)] {
{ std::lock_guard lock(mutex_);
if (stopping_ || generations_[peer] != generation) return;
}
active_peer_ = peer; active_generation_ = generation;
work();
});
wake_.notify_one();
}
void FileBrowser::Run() {
for (;;) {
std::function<void()> work;
{
std::unique_lock lock(mutex_);
wake_.wait_for(lock, std::chrono::milliseconds(250), [this] { return stopping_ || !jobs_.empty(); });
if (stopping_) return;
if (!jobs_.empty()) { work = std::move(jobs_.front()); jobs_.pop_front(); }
}
try { if (work) work(); } catch (...) { /* Invalid peer data cannot kill the worker. */ }
std::erase_if(directory_snapshots_, [](const auto& entry) {
return Clock::now() >= entry.second.expires;
});
for (auto it = pending_.begin(); it != pending_.end();) {
if (Clock::now() < it->second.deadline) { ++it; continue; }
auto pending = std::move(it->second); it = pending_.erase(it);
if (Current(pending.peer, pending.generation)) {
active_peer_ = pending.peer; active_generation_ = pending.generation;
pending.complete(Failure("timeout"));
}
}
}
}
bool FileBrowser::Current(const std::string& peer, uint64_t generation) {
std::lock_guard lock(mutex_);
return !stopping_ && generations_[peer] == generation;
}
void FileBrowser::Report(const std::string& peer, Json result, bool notify_peer) {
if (!Current(peer, active_generation_)) return;
Publish(peer, 0, result);
if (notify_peer) {
result["op"] = "notice"; result["id"] = next_id_++;
SendMessage(peer, std::move(result));
}
}
bool FileBrowser::SendMessage(const std::string& peer, Json message) {
{ std::lock_guard lock(mutex_);
if (stopping_ || (peer == active_peer_ && generations_[peer] != active_generation_)) return false;
}
message["type"] = "file_browser"; message["version"] = 1;
return send_(peer, message);
}
void FileBrowser::Publish(const std::string& peer, uint32_t id, Json result) {
std::lock_guard lock(mutex_);
auto& events = events_[peer];
if (id) {
for (auto& event : events) {
if (event.id == id && event.result.value("loading", false)) {
event.result = std::move(result);
return;
}
}
}
if (events.size() < 512) events.push_back({id, std::move(result)});
}
std::vector<FileBrowser::Event> FileBrowser::TakeEvents(const std::string& peer) {
std::lock_guard lock(mutex_);
std::vector<Event> result; result.swap(events_[peer]); return result;
}
uint64_t FileBrowser::Generation(const std::string& peer) {
std::lock_guard lock(mutex_);
const auto found = generations_.find(peer);
return found == generations_.end() ? 0 : found->second;
}
void FileBrowser::Disconnect(const std::string& peer) {
{
std::lock_guard lock(mutex_);
++generations_[peer]; events_.erase(peer);
std::erase_if(listings_, [&](auto& entry) {
if (entry.second->peer != peer) return false;
entry.second->cancelled = true;
return true;
});
}
Post(peer, [this, peer] {
std::erase_if(pending_, [&](const auto& entry) { return entry.second.peer == peer; });
std::erase_if(directory_snapshots_, [&](const auto& entry) { return entry.first.first == peer; });
Publish(peer, 0, Failure("disconnected"));
});
}
void FileBrowser::Request(const std::string& peer, Json message,
std::function<void(const Json&)> complete) {
if (pending_.size() >= 256) { complete(Failure("busy")); return; }
const auto id = next_id_++;
message["id"] = id;
pending_.emplace(id, Pending{peer, active_generation_, Clock::now() + std::chrono::seconds(12), std::move(complete)});
if (!SendMessage(peer, std::move(message))) {
auto done = std::move(pending_.at(id).complete); pending_.erase(id);
done(Failure("disconnected"));
}
}
uint32_t FileBrowser::List(const std::string& peer, const std::string& path, bool local) {
const auto id = next_id_++;
auto listing = std::make_shared<Listing>();
listing->id = id; listing->peer = peer; listing->path = path;
{
std::lock_guard lock(mutex_);
listing->generation = generations_[peer];
listings_[id] = listing;
}
Post(peer, [this, listing, local] {
if (listing->cancelled) return;
if (local) FinishList(listing, Directory(listing->path, [listing] { return listing->cancelled.load(); }));
else ListPage(listing);
});
return id;
}
void FileBrowser::CancelList(const std::string& peer, uint32_t id) {
std::lock_guard lock(mutex_);
const auto found = listings_.find(id);
if (found != listings_.end() && found->second->peer == peer) {
found->second->cancelled = true;
listings_.erase(found);
}
if (const auto events = events_.find(peer); events != events_.end())
std::erase_if(events->second, [id](const auto& event) { return event.id == id; });
}
void FileBrowser::FinishList(const std::shared_ptr<Listing>& listing, Json result) {
std::lock_guard lock(mutex_);
if (listing->cancelled || stopping_ || generations_[listing->peer] != listing->generation) return;
listings_.erase(listing->id);
auto& events = events_[listing->peer];
std::erase_if(events, [&](const auto& event) { return event.id == listing->id; });
if (events.size() < 512) events.push_back({listing->id, std::move(result)});
}
void FileBrowser::ReleaseList(const std::string& peer, const std::string& cursor) {
if (!cursor.empty()) Request(peer, {{"op", "list_cancel"}, {"cursor", cursor}}, [](const Json&) {});
}
void FileBrowser::ListPage(const std::shared_ptr<Listing>& listing) {
if (listing->cancelled) { ReleaseList(listing->peer, listing->cursor); return; }
Json request{{"op", "list"}, {"path", listing->path}, {"pagination", 1}};
if (!listing->cursor.empty()) request["cursor"] = listing->cursor;
Request(listing->peer, std::move(request), [this, listing](const Json& page) {
std::string next;
try {
next = page.value("next", std::string{});
if (listing->cancelled) { ReleaseList(listing->peer, next.empty() ? listing->cursor : next); return; }
if (!page.value("ok", false)) {
ReleaseList(listing->peer, listing->cursor);
FinishList(listing, page); return;
}
const auto& entries = page.at("entries");
if (!entries.is_array() || entries.size() > 2000 || next.size() > 64)
throw std::runtime_error("invalid_listing");
if ((page.contains("offset") && !page["offset"].is_number_unsigned()) ||
(page.contains("total") && !page["total"].is_number_unsigned()) ||
(!next.empty() && !page.value("truncated", false)))
throw std::runtime_error("invalid_listing");
if (page.value("truncated", false) && next.empty())
throw std::runtime_error("pagination_unsupported");
const bool first = listing->result.is_null();
const size_t offset = first ? 0 : listing->result.at("entries").size();
if (page.value("offset", offset) != offset ||
(!first && (page.at("path") != listing->result.at("path") ||
page.at("parent") != listing->result.at("parent") ||
page.at("total") != listing->result.at("total"))))
throw std::runtime_error("invalid_listing");
const size_t total = page.value("total", entries.size());
if (total < offset || entries.size() > total - offset ||
(next.empty() ? offset + entries.size() != total : entries.empty() || offset + entries.size() >= total))
throw std::runtime_error("invalid_listing");
if (!next.empty() && ParseCursor(next).second != offset + entries.size())
throw std::runtime_error("invalid_listing");
if (first) {
listing->result = {{"ok", true}, {"path", page.at("path")}, {"parent", page.at("parent")},
{"entries", Json::array()}, {"total", total}, {"truncated", false}};
}
auto& all = listing->result["entries"].get_ref<Json::array_t&>();
all.insert(all.end(), entries.begin(), entries.end());
if (next.empty()) { FinishList(listing, std::move(listing->result)); return; }
listing->cursor = next;
Publish(listing->peer, listing->id, {{"ok", true}, {"loading", true},
{"loaded", all.size()}, {"total", total}});
// Yield between pages so newer navigation and transfer work can run.
Post(listing->peer, [this, listing] { ListPage(listing); });
} catch (const std::exception& error) {
ReleaseList(listing->peer, next.empty() ? listing->cursor : next);
FinishList(listing, Failure(std::string(error.what()) == "pagination_unsupported"
? "pagination_unsupported" : "invalid_listing"));
}
});
}
void FileBrowser::Copy(const std::string& peer, const std::vector<std::string>& paths,
const std::string& destination, bool download) {
Post(peer, [this, peer, paths, destination, download] {
if (download) Request(peer, {{"op", "copy"}, {"paths", paths}, {"destination", destination}},
[this, peer](const Json& result) { Publish(peer, 0, result); });
else Upload(peer, paths, destination);
});
}
void FileBrowser::CancelTransfer(const std::string& peer, uint32_t id) {
Post(peer, [this, peer, id] {
Request(peer, {{"op", "cancel"}, {"file_id", id}}, [this, peer](const Json& result) {
Publish(peer, 0, result);
});
});
}
void FileBrowser::Handle(const std::string& peer, Json message) {
Post(peer, [this, peer, message = std::move(message)] {
try {
if (message.at("version") != 1 || !message.at("id").is_number_unsigned()) return;
const auto wide_id = message.at("id").get<uint64_t>();
if (!wide_id || wide_id > UINT32_MAX) return;
const auto id = static_cast<uint32_t>(wide_id);
if (message.value("op", "") == "notice") {
if (message.at("ok").is_boolean()) Publish(peer, 0, message);
return;
}
if (message.value("op", "") == "reply") {
const auto it = pending_.find(id);
if (it == pending_.end() || it->second.peer != peer || !message.at("ok").is_boolean()) return;
const auto generation = it->second.generation;
auto done = std::move(it->second.complete); pending_.erase(it);
if (!Current(peer, generation)) return;
active_generation_ = generation;
done(message);
} else Serve(peer, message);
} catch (...) { }
});
}
FileBrowser::Json FileBrowser::Directory(const std::string& value, const std::function<bool()>& cancelled) {
try {
Json entries = Json::array();
if (value == "@roots") {
#ifdef _WIN32
for (char drive = 'A'; drive <= 'Z'; ++drive) {
const std::string root = std::string(1, drive) + ":\\";
std::error_code ec;
if (fs::is_directory(PathFromUtf8(root), ec))
entries.push_back({{"name", root}, {"path", root}, {"directory", true}, {"size", 0}, {"modified", ""}, {"link", false}});
}
#else
entries.push_back({{"name", "/"}, {"path", "/"}, {"directory", true}, {"size", 0}, {"modified", ""}, {"link", false}});
#endif
return {{"ok", true}, {"path", value}, {"parent", ""}, {"entries", entries}, {"truncated", false}};
}
auto path = ExistingDirectory(value.empty() ? Utf8(Home()) : value);
std::error_code ec;
fs::directory_iterator it(path, ec), end;
if (ec) return Failure("directory_unavailable");
// Reuse one clock offset for every entry so equal timestamps stay equal.
const auto file_now = fs::file_time_type::clock::now();
const auto system_now = std::chrono::system_clock::now();
for (; it != end; it.increment(ec)) {
if (cancelled && cancelled()) return Failure("cancelled");
if (ec) return Failure("directory_unavailable");
const auto name = Utf8(it->path().filename());
if (name.rfind(".crossdesk-", 0) == 0) continue;
std::error_code error;
const auto status = it->symlink_status(error);
if (error) continue;
const bool link = fs::is_symlink(status);
const bool directory = it->is_directory(error);
if (!directory && !link && !fs::is_regular_file(status)) continue;
uint64_t size = 0;
if (!directory && !link) { size = it->file_size(error); if (error) size = 0; }
std::string modified;
Json modified_ms = nullptr;
const auto time = it->last_write_time(error);
if (!error) {
const auto system_time = SystemTime(time, file_now, system_now);
modified_ms = std::chrono::duration_cast<std::chrono::milliseconds>(system_time.time_since_epoch()).count();
const auto stamp = std::chrono::system_clock::to_time_t(system_time);
std::tm tm{};
#ifdef _WIN32
localtime_s(&tm, &stamp);
#else
localtime_r(&stamp, &tm);
#endif
char buffer[32]; std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm);
modified = buffer;
}
Json entry{{"name", name}, {"directory", directory}, {"size", size}, {"modified", modified},
{"modified_ms", modified_ms}, {"link", link}};
entries.push_back(std::move(entry));
}
if (ec) return Failure("directory_unavailable");
std::sort(entries.begin(), entries.end(), [](const auto& a, const auto& b) {
if (a["directory"] != b["directory"]) return a["directory"] == true;
auto first = a["name"].template get<std::string>(), second = b["name"].template get<std::string>();
const auto lower = [](unsigned char c) { return std::tolower(c); };
auto folded_first = first, folded_second = second;
std::transform(folded_first.begin(), folded_first.end(), folded_first.begin(), lower);
std::transform(folded_second.begin(), folded_second.end(), folded_second.begin(), lower);
return folded_first == folded_second ? first < second : folded_first < folded_second;
});
return {{"ok", true}, {"path", Utf8(path)}, {"parent", Utf8(path.parent_path())},
{"entries", std::move(entries)}, {"truncated", false}};
} catch (...) { return Failure("directory_unavailable"); }
}
FileBrowser::Json FileBrowser::DirectoryPage(const std::string& peer, const Json& message) {
const auto now = Clock::now();
const auto cursor = message.value("cursor", std::string{});
if (!cursor.empty()) {
const auto [token, offset] = ParseCursor(cursor);
const auto found = directory_snapshots_.find({peer, token});
if (found == directory_snapshots_.end() || found->second.generation != active_generation_ ||
now >= found->second.expires) return Failure("listing_expired");
auto page = Page(found->second.listing, offset, token);
if (page.at("next") == "") directory_snapshots_.erase(found);
else found->second.expires = now + std::chrono::seconds(30);
return page;
}
const auto generation = active_generation_;
auto listing = Directory(Text(message, "path"), [this, &peer, generation] { return !Current(peer, generation); });
if (!listing.value("ok", false)) return listing;
const bool paginated = message.value("pagination", Json{}) == 1;
const auto token = paginated ? std::to_string(next_snapshot_++) : "";
auto page = Page(listing, 0, token);
if (paginated && page.at("next") != "") {
const auto snapshots = std::count_if(directory_snapshots_.begin(), directory_snapshots_.end(),
[&](const auto& entry) { return entry.first.first == peer; });
if (snapshots >= 16) return Failure("busy");
directory_snapshots_.emplace(std::make_pair(peer, token),
DirectorySnapshot{std::move(listing), active_generation_, Clock::now() + std::chrono::seconds(30)});
}
return page;
}
void FileBrowser::Serve(const std::string& peer, const Json& message) {
Json result;
try {
const auto op = Text(message, "op");
if (op == "list") result = DirectoryPage(peer, message);
else if (op == "list_cancel") {
const auto [token, _] = ParseCursor(Text(message, "cursor"));
directory_snapshots_.erase({peer, token});
result = {{"ok", true}};
}
else if (op == "prepare") {
auto root = ExistingDirectory(Text(message, "destination"));
const auto& items = message.at("items");
if (!items.is_array() || items.empty() || items.size() > 64) throw std::runtime_error("invalid_request");
for (const auto& item : items) {
if (!Current(peer, active_generation_)) return;
if (!item.at("file_id").is_number_unsigned()) throw std::runtime_error("invalid_request");
const auto id = item.at("file_id").get<uint64_t>();
if (id > UINT32_MAX) throw std::runtime_error("invalid_request");
auto dir = Destination(root, Text(item, "directory"));
if (id && !reserve_(peer, static_cast<uint32_t>(id), dir)) throw std::runtime_error("directory_not_writable");
}
result = {{"ok", true}};
} else if (op == "cancel") {
const auto& id = message.at("file_id");
if (!id.is_number_unsigned() || id.get<uint64_t>() > UINT32_MAX || !id.get<uint32_t>())
throw std::runtime_error("invalid_request");
if (!cancel_ || !cancel_(peer, id.get<uint32_t>())) throw std::runtime_error("already_finished");
result = {{"ok", true}, {"message", "cancelling"}};
} else if (op == "copy") {
const auto& paths = message.at("paths");
if (!paths.is_array() || paths.empty() || paths.size() > 256) throw std::runtime_error("invalid_request");
std::vector<std::string> sources;
for (const auto& path : paths) sources.push_back(Text(Json{{"path", path}}, "path"));
Upload(peer, sources, Text(message, "destination"), true);
result = {{"ok", true}, {"message", "queued"}};
} else throw std::runtime_error("unsupported");
} catch (const std::exception& error) { result = Failure(error.what()); }
result["op"] = "reply"; result["id"] = message.at("id");
SendMessage(peer, std::move(result));
}
void FileBrowser::Upload(const std::string& peer, const std::vector<std::string>& paths,
const std::string& destination, bool notify_peer) {
std::vector<UploadItem> files;
try {
if (paths.empty() || paths.size() > 256 || destination.empty()) throw std::runtime_error("invalid_request");
std::set<fs::path> visited;
const auto add = [&](const fs::path& path, const fs::path& relative) {
if (!visited.insert(path).second) return;
if (files.size() >= 4096) throw std::runtime_error("too_many_files");
const auto status = fs::symlink_status(path);
if (fs::is_symlink(status)) throw std::runtime_error("symbolic_link");
if (fs::is_directory(status)) files.push_back({0, "", Utf8(relative)});
else if (fs::is_regular_file(status)) {
std::ifstream input(path, std::ios::binary);
if (!input) throw std::runtime_error("file_unreadable");
files.push_back({file_transfer::Session::NextFileId(), Utf8(path), Utf8(relative.parent_path())});
} else throw std::runtime_error("unsupported_file");
};
// Validate the entire selection before creating remote folders or sending.
for (const auto& source : paths) {
auto path = PathFromUtf8(source);
if (!path.is_absolute() || path.filename().empty()) throw std::runtime_error("invalid_path");
add(path, path.filename());
if (fs::is_directory(fs::symlink_status(path))) {
for (const auto& entry : fs::recursive_directory_iterator(path)) {
{ std::lock_guard lock(mutex_); if (stopping_ || generations_[peer] != active_generation_) return; }
add(entry.path(), entry.path().lexically_relative(path.parent_path()));
}
}
}
auto job = std::make_shared<UploadJob>();
job->files = std::move(files); job->destination = destination; job->notify_peer = notify_peer;
UploadNext(peer, job);
} catch (const std::exception& error) {
Publish(peer, 0, Failure(error.what()));
throw;
}
}
void FileBrowser::UploadNext(const std::string& peer, const std::shared_ptr<UploadJob>& job) {
if (!Current(peer, active_generation_)) return;
if (job->next == job->files.size()) {
Report(peer, {{"ok", true}, {"message", "queued"}}, job->notify_peer);
return;
}
const auto start = job->next;
Json items = Json::array();
size_t bytes = job->destination.size();
while (job->next < job->files.size() && items.size() < 32) {
const auto& file = job->files[job->next];
Json item{{"file_id", file.id}, {"directory", file.directory}};
const auto size = item.dump().size();
if (!items.empty() && bytes + size > 44000) break;
bytes += size; items.push_back(std::move(item)); ++job->next;
}
const auto end = job->next;
// Only one preparation batch per operation is in flight. Large folder
// copies do not exhaust pending requests or reserve thousands of paths.
Request(peer, {{"op", "prepare"}, {"destination", job->destination}, {"items", items}},
[this, peer, job, start, end](const Json& reply) {
if (!reply.value("ok", false)) { Report(peer, reply, job->notify_peer); return; }
for (auto index = start; index < end; ++index) {
if (!Current(peer, active_generation_)) return;
const auto& file = job->files[index];
if (file.id && !enqueue_(peer, file.path, file.id)) {
Report(peer, Failure("file_unreadable"), job->notify_peer); return;
}
}
UploadNext(peer, job);
});
}
} // namespace crossdesk
@@ -0,0 +1,116 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-04
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _FILE_BROWSER_H_
#define _FILE_BROWSER_H_
#include <nlohmann/json.hpp>
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
namespace crossdesk {
// Filesystem work is serialized off the UI and RTC threads. The adapter owns
// connection authorization and the existing reliable file transfer engine.
class FileBrowser {
public:
using Json = nlohmann::json;
using Send = std::function<bool(const std::string&, const Json&)>;
using Enqueue = std::function<bool(const std::string&, const std::string&, uint32_t)>;
using Reserve = std::function<bool(const std::string&, uint32_t, const std::filesystem::path&)>;
using Cancel = std::function<bool(const std::string&, uint32_t)>;
struct Event { uint32_t id; Json result; };
FileBrowser(Send send, Enqueue enqueue, Reserve reserve, Cancel cancel = {});
~FileBrowser();
uint32_t List(const std::string& peer, const std::string& path, bool local);
void CancelList(const std::string& peer, uint32_t id);
void Copy(const std::string& peer, const std::vector<std::string>& paths,
const std::string& destination, bool download);
void CancelTransfer(const std::string& peer, uint32_t id);
void Handle(const std::string& peer, Json message);
void Disconnect(const std::string& peer);
uint64_t Generation(const std::string& peer);
std::vector<Event> TakeEvents(const std::string& peer);
void Stop();
static Json Directory(const std::string& path, const std::function<bool()>& cancelled = {});
private:
using Clock = std::chrono::steady_clock;
struct Pending {
std::string peer;
uint64_t generation;
Clock::time_point deadline;
std::function<void(const Json&)> complete;
};
struct Listing {
uint32_t id;
uint64_t generation;
std::string peer, path, cursor;
Json result;
std::atomic<bool> cancelled{false};
};
struct DirectorySnapshot {
Json listing;
uint64_t generation;
Clock::time_point expires;
};
struct UploadItem { uint32_t id; std::string path, directory; };
struct UploadJob {
std::vector<UploadItem> files;
size_t next = 0;
std::string destination;
bool notify_peer = false;
};
void Post(const std::string& peer, std::function<void()> work);
void Run();
void Request(const std::string& peer, Json message,
std::function<void(const Json&)> complete);
void Publish(const std::string& peer, uint32_t id, Json result);
void Serve(const std::string& peer, const Json& message);
void ListPage(const std::shared_ptr<Listing>& listing);
void FinishList(const std::shared_ptr<Listing>& listing, Json result);
void ReleaseList(const std::string& peer, const std::string& cursor);
Json DirectoryPage(const std::string& peer, const Json& message);
void Upload(const std::string& peer, const std::vector<std::string>& paths,
const std::string& destination, bool notify_peer = false);
void UploadNext(const std::string& peer, const std::shared_ptr<UploadJob>& job);
bool Current(const std::string& peer, uint64_t generation);
void Report(const std::string& peer, Json result, bool notify_peer);
bool SendMessage(const std::string& peer, Json message);
Send send_;
Enqueue enqueue_;
Reserve reserve_;
Cancel cancel_;
std::mutex mutex_;
std::condition_variable wake_;
bool stopping_ = false;
std::deque<std::function<void()>> jobs_;
std::map<std::string, uint64_t> generations_;
std::map<std::string, std::vector<Event>> events_;
std::map<uint32_t, std::shared_ptr<Listing>> listings_;
// Worker-thread state only.
std::map<uint32_t, Pending> pending_;
std::map<std::pair<std::string, std::string>, DirectorySnapshot> directory_snapshots_;
uint64_t next_snapshot_ = 1;
std::string active_peer_;
uint64_t active_generation_ = 0;
std::atomic<uint32_t> next_id_{1};
std::thread worker_;
};
} // namespace crossdesk
#endif
@@ -0,0 +1,637 @@
#include "features/file_transfer/file_browser_window.h"
#include <algorithm>
#include <any>
#include <cctype>
#include <climits>
#include <cstdio>
extern unsigned char fa_solid_900_ttf[];
extern unsigned int fa_solid_900_ttf_len;
#include "ui/model_update.h"
#include "localization.h"
#include "application/window_geometry.h"
#include "application/window_presentation.h"
#if defined(__APPLE__)
#include "platform/window_drag.h"
#elif defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <SDL3/SDL.h>
#endif
namespace crossdesk {
namespace {
slint::SharedString S(std::string_view value) { return slint::SharedString(value); }
std::string Size(uint64_t bytes) {
const char* units[] = {"B", "KB", "MB", "GB", "TB"};
double value = bytes; int unit = 0;
while (value >= 1024 && unit < 4) { value /= 1024; ++unit; }
char text[64]; std::snprintf(text, sizeof(text), unit ? "%.1f %s" : "%.0f %s", value, units[unit]);
return text;
}
std::string Join(const std::string& parent, const std::string& name) {
const bool windows = (parent.size() > 1 && parent[1] == ':') || parent.rfind("\\\\", 0) == 0;
return parent + (parent.empty() || parent.back() == '/' || parent.back() == '\\'
? "" : windows ? "\\" : "/") + name;
}
std::string Name(const std::string& path) {
const auto slash = path.find_last_of("/\\");
return slash == std::string::npos || slash == path.size() - 1 ? path : path.substr(slash + 1);
}
bool Matches(const std::string& text, const std::string& filter) {
return std::search(text.begin(), text.end(), filter.begin(), filter.end(),
[](unsigned char a, unsigned char b) { return std::tolower(a) == std::tolower(b); }) != text.end();
}
}
std::string FileBrowserWindow::Tr(const char* chinese, const char* english) const { return chinese_ ? chinese : english; }
FileBrowserWindow::FileBrowserWindow(FileTransferManager& transfers, std::string remote,
bool controller, int language)
: transfers_(transfers), remote_(std::move(remote)),
connection_generation_(transfers_.browser().Generation(remote_)),
chinese_(language == 0 || language == 3) {
transfers_.browser().TakeEvents(remote_);
window_->window().window_handle().register_font_from_data(
fa_solid_900_ttf, fa_solid_900_ttf_len);
// Resolve the native frame at its final size while it is still hidden.
// Otherwise show() applies the preferred size after we have centered it.
window_->window().set_size(slint::LogicalSize({900, 620}));
window_->set_chinese(chinese_);
UpdateActionLabels(language);
SetPeerName("");
window_->set_local_role(S(controller ? Tr("控制端", "Controller") : Tr("被控端", "Host")));
window_->set_remote_role(S(controller ? Tr("被控端", "Host") : Tr("控制端", "Controller")));
window_->set_local_entries(panes_[0].rows); window_->set_local_tree(panes_[0].tree);
window_->set_remote_entries(panes_[1].rows); window_->set_remote_tree(panes_[1].tree);
window_->set_tasks(tasks_);
window_->on_navigate([this](bool remote, slint::SharedString path) { Navigate(remote, std::string(path)); });
window_->on_refresh([this](bool remote) { Navigate(remote, panes_[remote].path); });
window_->on_up([this](bool remote) { Navigate(remote, panes_[remote].parent); });
window_->on_filter([this](bool remote, slint::SharedString filter) {
auto& pane = panes_[remote]; pane.filter = std::string(filter); pane.selected.clear(); UpdatePane(remote);
});
window_->on_sort([this](bool remote, int column) {
auto& pane = panes_[remote];
if (column < 0 || column > 2 || pane.busy || !pane.loaded ||
!pane.error.empty() || window_->get_drag_active()) return;
const auto sort_column = static_cast<SortColumn>(column);
pane.sort_descending = pane.sort_column == sort_column ? !pane.sort_descending
: sort_column != SortColumn::Name;
pane.sort_column = sort_column;
SortEntries(pane);
UpdatePane(remote);
});
window_->on_toggle_hidden([this](bool remote) {
auto& pane = panes_[remote]; pane.show_hidden = !pane.show_hidden;
pane.selected.clear(); UpdatePane(remote); UpdateTree(remote);
});
window_->on_select_entry([this](bool remote, int index) {
auto& pane = panes_[remote];
if (index < 0 || index >= static_cast<int>(pane.rows->row_count())) return;
auto row = *pane.rows->row_data(index);
if (row.link) return;
SelectSource(remote);
const std::string path(row.path);
if (!pane.selected.erase(path)) pane.selected.insert(path);
UpdatePane(remote);
});
window_->on_select_all([this](bool remote) {
SelectSource(remote);
auto& pane = panes_[remote];
bool all = true;
for (size_t i = 0; i < pane.rows->row_count(); ++i) {
const auto row = *pane.rows->row_data(i);
if (!row.link && !pane.selected.count(std::string(row.path))) all = false;
}
for (size_t i = 0; i < pane.rows->row_count(); ++i) {
const auto row = *pane.rows->row_data(i);
if (all) pane.selected.erase(std::string(row.path));
else if (!row.link) pane.selected.insert(std::string(row.path));
}
UpdatePane(remote);
});
window_->on_clear_selection([this] {
if (window_->get_drag_active()) return;
for (int side = 0; side < 2; ++side) {
panes_[side].selected.clear();
UpdatePane(side);
}
});
window_->on_open_entry([this](bool remote, int index) {
auto& pane = panes_[remote];
if (index < 0 || index >= static_cast<int>(pane.rows->row_count())) return;
const auto row = *pane.rows->row_data(index);
if (row.directory) OpenDirectory(remote, std::string(row.path));
});
window_->on_open_directory([this](bool remote, slint::SharedString path) {
OpenDirectory(remote, std::string(path));
});
window_->on_tree_open([this](bool remote, int index) {
const auto& pane = panes_[remote];
if (index >= 0 && index < static_cast<int>(pane.tree->row_count()))
Navigate(remote, std::string(pane.tree->row_data(index)->path));
});
window_->on_tree_toggle([this](bool remote, int index) {
auto& pane = panes_[remote];
if (index < 0 || index >= static_cast<int>(pane.tree->row_count())) return;
const std::string path(pane.tree->row_data(index)->path);
if (!pane.expanded.erase(path)) {
pane.expanded.insert(path);
if (!pane.directories.count(path)) Navigate(remote, path, true);
}
UpdateTree(remote);
});
window_->on_drag_data([this](bool remote, slint::SharedString path, int) {
return MakeDragData(remote, std::string(path));
});
window_->on_drag_state([this](const slint::DataTransfer& data, bool active) {
if (!active) { CancelDrag(); return; }
const auto value = data.user_data();
const auto stored = std::any_cast<std::shared_ptr<DragPayload>>(&value);
if (!stored || !*stored) return;
const auto payload = DropPayload(!(*stored)->remote, data);
if (!payload) return;
window_->set_drag_active(true);
window_->set_drag_count(static_cast<int>(payload->paths->size()));
SelectSource(payload->remote);
panes_[payload->remote].selected = {payload->paths->begin(), payload->paths->end()};
UpdatePane(payload->remote);
});
window_->on_can_drop([this](bool remote, const slint::DataTransfer& data) {
return static_cast<bool>(DropPayload(remote, data));
});
window_->on_dropped([this](bool remote, const slint::DataTransfer& data) {
const auto payload = DropPayload(remote, data);
if (!payload) return false;
// The drag owns a snapshot of both directories and its selected paths.
// Consume before queueing so repeated release events cannot send twice.
payload->consumed = true;
return QueueTransfer(payload->remote, *payload->paths, payload->target_directory);
});
window_->on_cancel_drag([this] { CancelDrag(); });
window_->on_transfer([this](bool download) { Transfer(download); });
window_->on_cancel_task([this](int id) { transfers_.CancelBrowserTransfer(remote_, static_cast<uint32_t>(id)); });
window_->on_clear_finished([this] {
using Status = FileTransferManager::FileTransferState::FileTransferStatus;
for (const auto& [id, task] : history_)
if (task.status == Status::Completed || task.status == Status::Failed || task.status == Status::Cancelled)
dismissed_.insert(id);
next_sync_ = {};
});
window_->window().on_close_requested([this] {
show_pending_ = false;
CancelDrag();
window_->hide(); return slint::CloseRequestResponse::KeepWindowShown;
});
Navigate(false, ""); Navigate(true, "");
}
void FileBrowserWindow::SetPeerName(const std::string& name) {
const auto text = S(name.empty() ? Tr("远端设备", "Remote device") : name);
if (window_->get_peer_name() != text) window_->set_peer_name(text);
}
void FileBrowserWindow::UpdateActionLabels(int language) {
window_->set_send_local_text(S(localization::Literal("发送到本机", language)));
window_->set_send_remote_text(S(localization::Literal("发送到远端", language)));
window_->set_clear_completed_text(S(localization::Literal("清除已完成", language)));
window_->set_open_directory_text(S(localization::Literal("打开目录", language)));
}
bool FileBrowserWindow::PresentsResult(uint32_t id,
FileTransferManager::FileTransferState::FileTransferStatus status) const {
using Status = FileTransferManager::FileTransferState::FileTransferStatus;
if (!PresentsTransfers() ||
(status != Status::Completed && status != Status::Failed && status != Status::Cancelled))
return false;
const auto task = history_.find(id);
return task != history_.end() && !task->second.receiving && task->second.status == status &&
(window_->get_tasks_expanded() || dismissed_.count(id));
}
bool FileBrowserWindow::CenterOnScreen() {
auto& window = window_->window();
if (window.is_fullscreen() || window.is_maximized()) return true;
#if defined(__APPLE__)
return CenterNativeWindowOnScreen(window.appkit_view());
#elif defined(_WIN32)
const HWND hwnd = window.win32_hwnd();
if (!hwnd) return false;
MONITORINFO monitor{sizeof(MONITORINFO)};
RECT frame{};
if (!GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &monitor) ||
!GetWindowRect(hwnd, &frame)) return false;
const auto& bounds = monitor.rcWork;
const auto target = window_geometry::CenteredPosition(
{static_cast<int>(bounds.left), static_cast<int>(bounds.top),
static_cast<int>(bounds.right - bounds.left),
static_cast<int>(bounds.bottom - bounds.top)},
{static_cast<int>(frame.right - frame.left),
static_cast<int>(frame.bottom - frame.top)});
return SetWindowPos(hwnd, nullptr, target.x, target.y, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE) != 0;
#else
#if defined(__linux__) && !defined(__OHOS__)
// Native Wayland placement belongs to the compositor.
if (window.wayland_surface()) return true;
#endif
const auto position = window.position();
const auto size = window.size();
if (!size.width || !size.height) return false;
const SDL_Point center{position.x + static_cast<int>(size.width / 2),
position.y + static_cast<int>(size.height / 2)};
SDL_DisplayID display = SDL_GetDisplayForPoint(&center);
if (!display) display = SDL_GetPrimaryDisplay();
SDL_Rect bounds{};
if (!display || !SDL_GetDisplayUsableBounds(display, &bounds)) return false;
const auto target = window_geometry::CenteredPosition(
{bounds.x, bounds.y, bounds.w, bounds.h},
{static_cast<int>(size.width), static_cast<int>(size.height)});
window.set_position(slint::PhysicalPosition({target.x, target.y}));
return true;
#endif
}
void FileBrowserWindow::Show() {
if (!Tick()) return;
if (Visible()) {
window_->window().set_minimized(false);
} else {
show_pending_ = true;
ShowWhenReady();
}
if (!panes_[1].busy && !panes_[1].error.empty()) Navigate(true, panes_[1].path);
}
void FileBrowserWindow::ShowWhenReady() {
if (!show_pending_ || !NativeWindowReady(window_->window())) return;
#if defined(__APPLE__)
if (!ConfigureWhiteWindowChrome(window_->window().appkit_view())) return;
#endif
if (!CenterOnScreen()) return;
show_pending_ = false;
window_->show();
}
void FileBrowserWindow::OpenDirectory(bool remote, const std::string& path) {
const auto& pane = panes_[remote];
if (!SessionConnected() || !pane.loaded || pane.busy || !pane.error.empty() ||
window_->get_drag_active()) return;
// Resolve the menu target by path, never by a row index that can change.
const auto entry = std::find_if(pane.entries.begin(), pane.entries.end(), [&](const auto& item) {
return item.row.directory && std::string_view(item.row.path) == path;
});
if (entry != pane.entries.end()) Navigate(remote, path);
}
void FileBrowserWindow::Navigate(bool remote, const std::string& path, bool tree) {
if (window_->get_drag_active()) CancelDrag();
if (remote && !transfers_.BrowserConnected(remote_)) { Notice(Error("disconnected"), true); return; }
auto& pane = panes_[remote];
for (auto it = requests_.begin(); it != requests_.end();) {
if (it->second.remote == remote && it->second.tree == tree &&
(!tree || it->second.path == path)) {
transfers_.browser().CancelList(remote_, it->first);
it = requests_.erase(it);
} else ++it;
}
const auto id = transfers_.browser().List(remote_, path, !remote);
requests_[id] = {remote, tree, path};
if (!tree) {
pane.request = id; pane.busy = true; pane.error.clear(); pane.loading.clear();
pane.selected.clear(); UpdatePane(remote);
}
}
void FileBrowserWindow::SortEntries(Pane& pane) {
std::sort(pane.entries.begin(), pane.entries.end(), [&](const Entry& a, const Entry& b) {
// Folder grouping and unknown dates stay consistent in either direction.
if (a.row.directory != b.row.directory) return a.row.directory;
int order = 0;
if (pane.sort_column == SortColumn::Modified) {
const bool a_known = a.modified_ms.has_value() || !a.modified.empty();
const bool b_known = b.modified_ms.has_value() || !b.modified.empty();
if (a_known != b_known) return a_known;
if (a.modified_ms && b.modified_ms)
order = *a.modified_ms < *b.modified_ms ? -1 : *a.modified_ms > *b.modified_ms ? 1 : 0;
else order = a.modified.compare(b.modified);
} else if (pane.sort_column == SortColumn::Size && !a.row.directory) {
order = a.bytes < b.bytes ? -1 : a.bytes > b.bytes ? 1 : 0;
}
if (!order) order = a.name_key.compare(b.name_key);
if (!order) order = std::string_view(a.row.name).compare(std::string_view(b.row.name));
if (!order) order = std::string_view(a.row.path).compare(std::string_view(b.row.path));
return pane.sort_descending ? order > 0 : order < 0;
});
}
void FileBrowserWindow::UpdatePane(bool remote) {
auto& pane = panes_[remote];
std::vector<ui::BrowserEntry> rows;
size_t selectable = 0;
rows.reserve(pane.entries.size());
for (const auto& item : pane.entries) {
auto entry = item.row;
if (!pane.show_hidden && std::string(entry.name).starts_with('.')) continue;
if (!Matches(std::string(entry.name), pane.filter)) continue;
entry.selected = pane.selected.count(std::string(entry.path));
if (!entry.link) ++selectable;
rows.push_back(std::move(entry));
}
ui::UpdateModelRows(*pane.rows, std::move(rows));
const auto summary = pane.busy
? pane.loading.empty() ? Tr("正在读取目录…", "Loading folder…") : pane.loading
: std::to_string(pane.rows->row_count()) + Tr(" 项", " items");
const bool up = pane.loaded && !pane.parent.empty() && pane.path != pane.parent;
const bool all = selectable > 0 && pane.selected.size() == selectable;
if (remote) {
window_->set_remote_sort_column(static_cast<int>(pane.sort_column));
window_->set_remote_sort_descending(pane.sort_descending);
window_->set_remote_current_path(S(pane.path));
window_->set_remote_filter(S(pane.filter));
window_->set_remote_hidden(pane.show_hidden);
window_->set_remote_busy(pane.busy); window_->set_remote_status(S(summary));
window_->set_remote_error(S(pane.error)); window_->set_remote_up(up);
window_->set_remote_selected(static_cast<int>(pane.selected.size())); window_->set_remote_all(all);
} else {
window_->set_local_sort_column(static_cast<int>(pane.sort_column));
window_->set_local_sort_descending(pane.sort_descending);
window_->set_local_current_path(S(pane.path));
window_->set_local_filter(S(pane.filter));
window_->set_local_hidden(pane.show_hidden);
window_->set_local_busy(pane.busy); window_->set_local_status(S(summary));
window_->set_local_error(S(pane.error)); window_->set_local_up(up);
window_->set_local_selected(static_cast<int>(pane.selected.size())); window_->set_local_all(all);
}
UpdateAvailability();
}
void FileBrowserWindow::UpdateTree(bool remote) {
auto& pane = panes_[remote];
std::vector<ui::BrowserTreeEntry> rows;
const auto append = [&](auto&& self, const std::string& path, const std::string& name, int depth) -> void {
if (depth > 24) return;
const bool expanded = pane.expanded.count(path);
rows.push_back({S(name), S(path), depth, expanded, pane.path == path});
if (expanded) {
const auto it = pane.directories.find(path);
if (it != pane.directories.end())
for (const auto& entry : it->second)
if (entry.directory && !entry.link && (pane.show_hidden || !std::string(entry.name).starts_with('.')))
self(self, std::string(entry.path), std::string(entry.name), depth + 1);
}
};
if (!pane.home.empty()) append(append, pane.home, Tr("主目录", "Home"), 0);
append(append, "@roots", Tr("磁盘", "Drives"), 0);
if (pane.loaded && pane.path != "@roots" && pane.path != pane.home &&
std::none_of(rows.begin(), rows.end(), [&](const auto& row) { return std::string(row.path) == pane.path; }))
append(append, pane.path, Name(pane.path), 0);
ui::UpdateModelRows(*pane.tree, std::move(rows));
}
bool FileBrowserWindow::TransferReady() const {
return window_->get_connected() && panes_[0].loaded && panes_[1].loaded &&
!panes_[0].busy && !panes_[1].busy && panes_[0].error.empty() && panes_[1].error.empty() &&
panes_[0].path != "@roots" && panes_[1].path != "@roots" &&
std::string(window_->get_local_path()) == panes_[0].path &&
std::string(window_->get_remote_path()) == panes_[1].path;
}
bool FileBrowserWindow::SessionConnected() const {
// A peer can reconnect with the same ID between UI ticks. Its old window
// must still close, even if the new connection is already usable.
return !disconnected_ && transfers_.BrowserConnected(remote_) &&
connection_generation_ == transfers_.browser().Generation(remote_);
}
void FileBrowserWindow::UpdateAvailability() {
const bool ready = TransferReady();
window_->set_transfer_ready(ready);
window_->set_can_upload(ready && !panes_[0].selected.empty());
window_->set_can_download(ready && !panes_[1].selected.empty());
// All selected rows share one immutable list, so selecting a large folder
// doesn't allocate a copy of the entire selection for every draggable row.
for (int side = 0; side < 2; ++side)
drag_selection_[side] = std::make_shared<const std::vector<std::string>>(
panes_[side].selected.begin(), panes_[side].selected.end());
// Callback bindings don't track C++ container mutations. Refresh the drag
// payload only when its selection/directory state changes, never every tick.
const int revision = window_->get_selection_revision();
window_->set_selection_revision(revision == INT_MAX ? 0 : revision + 1);
}
void FileBrowserWindow::SelectSource(bool remote) {
window_->set_source_remote(remote);
if (!panes_[!remote].selected.empty()) {
panes_[!remote].selected.clear(); UpdatePane(!remote);
}
}
slint::DataTransfer FileBrowserWindow::MakeDragData(bool remote, const std::string& path) const {
slint::DataTransfer result;
if (!TransferReady()) return result;
const auto& source = panes_[remote]; const auto& target = panes_[!remote];
const auto found = std::find_if(source.entries.begin(), source.entries.end(),
[&](const auto& entry) { return !entry.row.link && std::string(entry.row.path) == path; });
if (found == source.entries.end()) return result;
auto payload = std::make_shared<DragPayload>();
payload->owner = drag_owner_; payload->epoch = drag_epoch_; payload->remote = remote;
payload->source_request = source.request; payload->target_request = target.request;
payload->source_directory = source.path; payload->target_directory = target.path;
if (source.selected.count(path)) payload->paths = drag_selection_[remote];
else payload->paths = std::make_shared<const std::vector<std::string>>(std::initializer_list<std::string>{path});
// Opaque application data: a remote path must never masquerade as a local
// file URL when the pointer leaves this window or enters another session.
result.set_user_data(std::move(payload));
return result;
}
std::shared_ptr<FileBrowserWindow::DragPayload> FileBrowserWindow::DropPayload(
bool remote, const slint::DataTransfer& data) const {
const auto value = data.user_data();
const auto stored = std::any_cast<std::shared_ptr<DragPayload>>(&value);
if (!stored || !*stored) return {};
const auto& payload = *stored;
if (payload->owner.lock() != drag_owner_ || payload->epoch != drag_epoch_ ||
payload->consumed || payload->remote == remote || !payload->paths || payload->paths->empty() ||
!TransferReady() || !SessionConnected()) return {};
const auto& source = panes_[payload->remote]; const auto& target = panes_[remote];
if (source.request != payload->source_request || target.request != payload->target_request ||
source.path != payload->source_directory || target.path != payload->target_directory) return {};
return payload;
}
void FileBrowserWindow::CancelDrag() {
++drag_epoch_;
window_->set_drag_active(false); window_->set_drag_count(0);
UpdateAvailability();
}
bool FileBrowserWindow::QueueTransfer(bool download, const std::vector<std::string>& paths,
const std::string& destination) {
if (paths.empty() || !TransferReady() || !SessionConnected()) return false;
transfers_.browser().Copy(remote_, paths, destination, download);
Notice(Tr("正在准备传输 → ", "Preparing transfer → ") + destination, false);
panes_[download].selected.clear(); UpdatePane(download);
return true;
}
void FileBrowserWindow::Transfer(bool download) {
if (!TransferReady()) return;
auto& source = panes_[download];
const std::vector<std::string> paths(source.selected.begin(), source.selected.end());
QueueTransfer(download, paths, panes_[!download].path);
}
void FileBrowserWindow::Notice(const std::string& message, bool error) {
window_->set_notice(S(message)); window_->set_notice_error(error);
}
std::string FileBrowserWindow::Error(const std::string& code) const {
if (code == "timeout") return Tr("远端未响应,请确认两端已更新至支持文件浏览的版本后重试。", "Peer did not respond. Update both ends to a version that supports file browsing, then retry.");
if (code == "disconnected") return Tr("连接已断开,请重新连接后打开文件管理器。", "Disconnected. Reconnect and reopen the file manager.");
if (code == "browser_not_open") return Tr("请先在控制端打开本连接的文件管理器,再浏览控制端目录。", "Open this connection's file manager on the controller to enable browsing its folders.");
if (code == "directory_unavailable") return Tr("无法打开目录,请检查路径和访问权限后刷新。", "Cannot open folder. Check the path and access permissions, then refresh.");
if (code == "pagination_unsupported") return Tr("远端版本无法完整读取此目录,请更新远端后重试。", "Update the remote app to load every item in this folder.");
if (code == "invalid_listing" || code == "listing_expired") return Tr("目录列表未能完整加载,请刷新重试。", "The folder listing could not be fully loaded. Refresh to retry.");
if (code == "directory_not_writable") return Tr("目标目录不可写,请选择其他目录。", "Cannot write to the destination. Choose another folder.");
if (code == "symbolic_link") return Tr("所选内容包含符号链接,请选择实际文件或目录。", "Selection contains a symbolic link. Select the original files or folders.");
if (code == "too_many_files") return Tr("单次最多传输 4096 个文件与目录,请分批选择。", "Select at most 4096 files and folders per transfer.");
if (code == "file_unreadable") return Tr("文件无法读取,可能已移动或无访问权限。", "Cannot read a file. It may have moved or access was denied.");
if (code == "busy") return Tr("请求较多,请稍后重试。", "Too many pending requests. Try again shortly.");
if (code == "already_finished") return Tr("任务已结束,无需取消。", "This transfer has already finished.");
return Tr("操作失败,请检查所选路径与文件权限后重试。", "Operation failed. Check the paths and file permissions, then retry.");
}
bool FileBrowserWindow::Tick() {
using Status = FileTransferManager::FileTransferState::FileTransferStatus;
// Connection lifetime is checked every UI tick, outside the throttled
// directory/progress refresh. All native window operations stay on this thread.
if (!SessionConnected()) {
disconnected_ = true;
show_pending_ = false;
window_->set_connected(false);
CancelDrag();
requests_.clear();
window_->hide();
return false;
}
ShowWhenReady();
const auto now = std::chrono::steady_clock::now();
if (now < next_sync_) return true;
next_sync_ = now + std::chrono::milliseconds(150);
for (auto& event : transfers_.browser().TakeEvents(remote_)) {
if (!event.id) {
const bool ok = event.result.value("ok", false);
if (!ok || !window_->get_notice_error())
Notice(ok ? event.result.value("message", "") == "cancelling"
? Tr("正在取消传输…", "Cancelling transfer…")
: Tr("已加入传输队列", "Added to transfer queue")
: Error(event.result.value("error", "unknown")), !ok);
if (ok) refresh_at_ = now + std::chrono::seconds(1);
continue;
}
const auto found = requests_.find(event.id);
if (found == requests_.end()) continue;
const auto request = found->second;
auto& pane = panes_[request.remote];
if (!request.tree && pane.request != event.id) continue;
if (event.result.value("loading", false)) {
if (!request.tree) {
pane.loading = Tr("正在加载 ", "Loading ") + std::to_string(event.result.value("loaded", size_t{})) +
" / " + std::to_string(event.result.value("total", size_t{})) + Tr(" 项…", " items…");
if (request.remote) window_->set_remote_status(S(pane.loading));
else window_->set_local_status(S(pane.loading));
}
continue;
}
requests_.erase(found);
if (!request.tree) pane.busy = false;
if (!event.result.value("ok", false)) {
pane.error = Error(event.result.value("error", "unknown"));
if (request.tree) pane.expanded.erase(request.path);
} else {
try {
const auto path = event.result.at("path").get<std::string>();
const auto& entries = event.result.at("entries");
if (!entries.is_array()) throw std::runtime_error("invalid");
std::vector<ui::BrowserEntry> rows;
rows.reserve(entries.size());
std::vector<Entry> sortable;
if (!request.tree) sortable.reserve(entries.size());
for (const auto& entry : entries) {
ui::BrowserEntry row{};
const auto name = entry.at("name").get<std::string>();
if (name.empty() || name == "." || name == "..") continue;
// Paths from a different operating system are opaque to this UI.
row.name = S(name); row.path = S(path == "@roots" ? entry.at("path").get<std::string>() : Join(path, name));
row.directory = entry.at("directory").get<bool>(); row.link = entry.value("link", false);
const auto bytes = entry.at("size").get<uint64_t>();
const auto timestamp = entry.at("modified").get<std::string>();
row.size = S(Size(bytes));
auto modified = timestamp.substr(0, 10);
std::replace(modified.begin(), modified.end(), '-', '/');
row.modified = S(modified);
if (!request.tree) {
Entry item{row, name, timestamp, bytes, std::nullopt};
std::transform(item.name_key.begin(), item.name_key.end(), item.name_key.begin(),
[](unsigned char c) { return std::tolower(c); });
if (entry.contains("modified_ms") && entry["modified_ms"].is_number_integer())
item.modified_ms = entry["modified_ms"].get<int64_t>();
sortable.push_back(std::move(item));
}
rows.push_back(std::move(row));
}
pane.directories[path] = rows;
if (!request.tree) {
// A name filter belongs to the open folder. Preserve it on refresh,
// but don't silently hide entries after navigating somewhere else.
if (pane.path != path) pane.filter.clear();
pane.path = path; pane.parent = event.result.at("parent").get<std::string>();
if (request.path.empty()) pane.home = path;
pane.entries = std::move(sortable); pane.error.clear(); pane.loaded = true;
SortEntries(pane);
pane.expanded.insert(path);
}
} catch (...) { pane.error = Error("unknown"); }
}
if (!request.tree) {
if (request.remote) window_->set_remote_path(S(pane.path)); else window_->set_local_path(S(pane.path));
}
UpdatePane(request.remote); UpdateTree(request.remote);
}
bool new_tasks = false;
for (const auto& task : transfers_.BrowserTransfers(remote_)) {
new_tasks = new_tasks || (!task.receiving && !history_.count(task.file_id));
history_[task.file_id] = task;
}
if (new_tasks) window_->set_tasks_expanded(true);
std::vector<ui::BrowserTask> rows;
for (auto it = history_.rbegin(); it != history_.rend(); ++it) {
const auto& [id, task] = *it;
if (task.status == Status::Completed && completed_.insert(id).second)
refresh_at_ = now + std::chrono::milliseconds(500);
// Received files still trigger directory refresh, but only this computer's
// outgoing transfers appear in the task list and progress notifications.
if (task.receiving || dismissed_.count(id)) continue;
ui::BrowserTask row{};
row.id = static_cast<int>(id); row.name = S(task.file_name); row.receiving = task.receiving;
row.size = S(Size(task.file_size));
row.active = task.status == Status::Queued || task.status == Status::Sending || task.status == Status::Receiving || task.status == Status::Cancelling;
row.failed = task.status == Status::Failed;
row.can_cancel = task.status == Status::Queued || task.status == Status::Sending || task.status == Status::Receiving;
row.progress = task.status == Status::Completed ? 1.f : task.file_size ? std::clamp(float(task.sent_bytes) / task.file_size, 0.f, 1.f) : 0.f;
const auto detail = Tr("已传输 ", "Transferred ") + Size(task.sent_bytes) +
(task.rate_bps ? " · " + Size(task.rate_bps / 8) + "/s" : "");
row.detail = S(detail);
switch (task.status) {
case Status::Queued: row.status = S(Tr("排队中", "Queued")); break;
case Status::Sending: row.status = S(Tr("发送中 ", "Sending ") + std::to_string(int(row.progress * 100)) + "%"); break;
case Status::Receiving: row.status = S(Tr("接收中 ", "Receiving ") + std::to_string(int(row.progress * 100)) + "%"); break;
case Status::Completed: row.status = S(Tr("已完成", "Completed")); break;
case Status::Failed: row.status = S(Tr("失败 · 请重试", "Failed · Retry")); break;
case Status::Cancelling: row.status = S(Tr("正在取消", "Cancelling")); break;
case Status::Cancelled: row.status = S(Tr("已取消", "Cancelled")); break;
}
rows.push_back(row);
}
const auto active = std::count_if(rows.begin(), rows.end(), [](const auto& task) { return task.active; });
const auto failed = std::count_if(rows.begin(), rows.end(), [](const auto& task) { return task.failed; });
const auto summary = std::to_string(rows.size()) + Tr(" 项", " items") +
(active ? " · " + std::to_string(active) + Tr(" 项进行中", " active") : "") +
(failed ? " · " + std::to_string(failed) + Tr(" 项失败", " failed") : "");
window_->set_task_summary(S(summary));
ui::UpdateModelRows(*tasks_, std::move(rows));
if (!window_->get_drag_active() && refresh_at_ != std::chrono::steady_clock::time_point{} && now >= refresh_at_) {
refresh_at_ = {};
for (int side = 0; side < 2; ++side)
if (panes_[side].loaded && !panes_[side].busy && panes_[side].selected.empty() &&
std::string(side ? window_->get_remote_path() : window_->get_local_path()) == panes_[side].path)
Navigate(side, panes_[side].path);
}
const bool ready = TransferReady();
if (window_->get_transfer_ready() != ready) UpdateAvailability();
return true;
}
} // namespace crossdesk
@@ -0,0 +1,102 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-04
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _FILE_BROWSER_WINDOW_H_
#define _FILE_BROWSER_WINDOW_H_
#include "crossdesk_ui.h"
#include "features/file_transfer/file_transfer_manager.h"
#include <optional>
#include <set>
namespace crossdesk {
class FileBrowserWindow {
public:
FileBrowserWindow(FileTransferManager& transfers, std::string remote,
bool controller, int language);
void Show();
void SetPeerName(const std::string& name);
void UpdateActionLabels(int language);
// False means this connection ended; the UI owner should discard the window.
bool Tick();
bool Visible() const { return window_->window().is_visible(); }
bool PresentsTransfers() const { return Visible() && !window_->window().is_minimized(); }
bool PresentsResult(uint32_t id, FileTransferManager::FileTransferState::FileTransferStatus status) const;
private:
enum class SortColumn { Name, Modified, Size };
struct Entry {
ui::BrowserEntry row;
std::string name_key, modified;
uint64_t bytes = 0;
std::optional<int64_t> modified_ms;
};
struct Pane {
std::string path, parent, home, filter, error, loading;
bool loaded = false, busy = false, show_hidden = false;
uint32_t request = 0;
SortColumn sort_column = SortColumn::Name;
bool sort_descending = false;
std::vector<Entry> entries;
std::set<std::string> selected, expanded;
std::map<std::string, std::vector<ui::BrowserEntry>> directories;
std::shared_ptr<slint::VectorModel<ui::BrowserEntry>> rows =
std::make_shared<slint::VectorModel<ui::BrowserEntry>>();
std::shared_ptr<slint::VectorModel<ui::BrowserTreeEntry>> tree =
std::make_shared<slint::VectorModel<ui::BrowserTreeEntry>>();
};
struct Request { bool remote, tree; std::string path; };
struct DragPayload {
std::weak_ptr<int> owner;
uint64_t epoch = 0;
bool remote = false, consumed = false;
uint32_t source_request = 0, target_request = 0;
std::string source_directory, target_directory;
std::shared_ptr<const std::vector<std::string>> paths;
};
void Navigate(bool remote, const std::string& path, bool tree = false);
void OpenDirectory(bool remote, const std::string& path);
bool CenterOnScreen();
void ShowWhenReady();
void UpdatePane(bool remote);
void SortEntries(Pane& pane);
void UpdateTree(bool remote);
bool TransferReady() const;
bool SessionConnected() const;
void UpdateAvailability();
void SelectSource(bool remote);
slint::DataTransfer MakeDragData(bool remote, const std::string& path) const;
std::shared_ptr<DragPayload> DropPayload(bool remote, const slint::DataTransfer& data) const;
void CancelDrag();
bool QueueTransfer(bool download, const std::vector<std::string>& paths,
const std::string& destination);
void Transfer(bool download);
void Notice(const std::string& message, bool error);
std::string Error(const std::string& code) const;
std::string Tr(const char* chinese, const char* english) const;
FileTransferManager& transfers_;
std::string remote_;
uint64_t connection_generation_;
bool chinese_;
bool disconnected_ = false;
bool show_pending_ = false;
slint::ComponentHandle<ui::FileBrowserWindow> window_ = ui::FileBrowserWindow::create();
Pane panes_[2];
std::shared_ptr<int> drag_owner_ = std::make_shared<int>(0);
std::shared_ptr<const std::vector<std::string>> drag_selection_[2];
uint64_t drag_epoch_ = 0;
std::map<uint32_t, Request> requests_;
std::set<uint32_t> dismissed_, completed_;
std::map<uint32_t, FileTransferManager::FileTransferState::FileTransferInfo> history_;
std::shared_ptr<slint::VectorModel<ui::BrowserTask>> tasks_ =
std::make_shared<slint::VectorModel<ui::BrowserTask>>();
std::chrono::steady_clock::time_point next_sync_{}, refresh_at_{};
};
} // namespace crossdesk
#endif
@@ -10,10 +10,31 @@
namespace crossdesk {
FileTransferManager::FileTransferManager(GuiRuntime& owner) : owner_(owner) {}
FileTransferManager::FileTransferManager(GuiRuntime& owner)
: owner_(owner), browser_(
[this](const auto& remote, const auto& message) { return SendBrowser(remote, message); },
[this](const auto& remote, const auto& path, uint32_t id) {
if (!BrowserConnected(remote)) return false;
auto props = owner_.FindRemoteSession(remote);
return ProcessSelectedFile(path, props, owner_.file_label_, remote, id);
},
[this](const auto& remote, uint32_t id, const auto& directory) {
if (!BrowserConnected(remote)) return false;
std::shared_ptr<PeerEventHandler> events;
{ std::lock_guard lock(browser_mutex_); events = browser_peers_[remote]; }
const auto receiver = ReceiverFor(events.get(), remote);
return receiver && receiver->ReserveDirectory(id, directory);
},
[this](const auto& remote, uint32_t id) {
if (!BrowserConnected(remote)) return false;
for (const auto& info : BrowserTransfers(remote))
if (!info.receiving && info.file_id == id) return CancelSend(id);
return false;
}) {}
FileTransferManager::~FileTransferManager() { Shutdown(); }
void FileTransferManager::Shutdown() {
browser_.Stop();
std::vector<std::future<void>> workers;
{
std::lock_guard lock(workers_mutex_);
@@ -99,8 +120,9 @@ void FileTransferManager::ProcessQueue(std::shared_ptr<RemoteSession> props) {
peer = events ? events->DirectPeer() : nullptr;
}
auto session = std::make_shared<file_transfer::Session>(
[peer, events, file, props](const char*, const char* data, size_t size) {
if (!peer || !events || (props && props->closing_)) return -1;
[this, peer, events, file, props](const char*, const char* data, size_t size) {
if (!peer || !events || (props && props->closing_) ||
(!props && !owner_.IsAuthorizedController(file.remote_id))) return -1;
auto callback = events->EnterCallback();
if (!callback || !events->DataAllowed()) return -1;
const auto wire_id = events->WireId(file.remote_id);
@@ -146,6 +168,18 @@ void FileTransferManager::ProcessQueue(std::shared_ptr<RemoteSession> props) {
uint64_t previous = UINT64_MAX;
auto progress = file_transfer::SendState{id, 0, 0,
cancelled ? file_transfer::Status::Cancelled : file_transfer::Status::Failed};
if (cancelled && peer && events && (!props || !props->closing_) &&
(props || owner_.IsAuthorizedController(file.remote_id))) {
auto callback = events->EnterCallback();
if (callback && events->DataAllowed()) {
// A queued browser file already reserved a destination on the peer.
// Release that reservation even though no data chunk was ever sent.
const auto packet = EncodeFileCancel(id, 0);
const auto wire_id = events->WireId(file.remote_id);
SendReliableDataFrameToPeer(peer, packet.data(), packet.size(),
file.file_label.c_str(), wire_id.data(), wire_id.size());
}
}
if (started) {
do {
{
@@ -287,6 +321,7 @@ void FileTransferManager::UpdateReceiveProgress(
info.file_id = file_transfer::Session::NextFileId();
info.remote_id = remote_id;
info.receiving = true;
info.wire_file_id = progress.id;
receive_rate_samples_.emplace(info.file_id,
ReceiveRateSample{std::chrono::steady_clock::now(), 0});
found = notifications.emplace(progress.id, files.size()).first;
@@ -309,7 +344,7 @@ void FileTransferManager::UpdateReceiveProgress(
}
}
void FileTransferManager::Receive(const char* data, size_t size,
std::shared_ptr<FileReceiver> FileTransferManager::ReceiverFor(
PeerEventHandler* handler, const std::string& remote) {
const auto props = owner_.FindRemoteSession(remote);
PeerPtr* peer;
@@ -323,14 +358,14 @@ void FileTransferManager::Receive(const char* data, size_t size,
events = owner_.ControllerEvents(remote);
peer = events ? events->DirectPeer() : nullptr;
}
if (!peer || !events || events.get() != handler || (props && props->closing_)) return;
if (!peer || !events || events.get() != handler || (props && props->closing_)) return {};
std::shared_ptr<FileReceiver> receiver;
std::filesystem::path default_directory;
{
std::lock_guard lock(sessions_mutex_);
const auto closed = disconnected_.find(handler);
if (stopping_ || (closed != disconnected_.end() &&
(closed->second.count("") || closed->second.count(remote)))) return;
(closed->second.count("") || closed->second.count(remote)))) return {};
auto& entry = receivers_[handler][remote];
if (!entry.session) {
entry.session = std::make_shared<FileReceiver>(); entry.handler = events;
@@ -341,7 +376,8 @@ void FileTransferManager::Receive(const char* data, size_t size,
(const file_transfer::ReceiveState& progress) mutable {
UpdateReceiveProgress(progress, notifications, remote);
});
entry.session->SetOnSendAck([peer, events, remote](const FileTransferAck& ack) {
entry.session->SetOnSendAck([this, peer, events, remote, props](const FileTransferAck& ack) {
if (!props && !owner_.IsAuthorizedController(remote)) return -1;
auto callback = events->EnterCallback();
if (!callback || !events->DataAllowed()) return -1;
const auto bytes = EncodeFileTransferAck(ack);
@@ -356,7 +392,12 @@ void FileTransferManager::Receive(const char* data, size_t size,
}
const auto configured = owner_.config_center_->GetFileTransferSavePath();
receiver->SetOutputDir(configured.empty() ? default_directory : PathFromUtf8(configured));
receiver->OnData(data, size);
return receiver;
}
void FileTransferManager::Receive(const char* data, size_t size,
PeerEventHandler* handler, const std::string& remote) {
if (auto receiver = ReceiverFor(handler, remote)) receiver->OnData(data, size);
}
void FileTransferManager::Connected(PeerEventHandler* handler, const std::string& remote) {
@@ -369,6 +410,17 @@ void FileTransferManager::Connected(PeerEventHandler* handler, const std::string
}
void FileTransferManager::Cancel(PeerEventHandler* handler, const std::string& remote) {
{
std::lock_guard lock(browser_mutex_);
for (auto it = browser_peers_.begin(); it != browser_peers_.end();) {
if (it->second.get() == handler && (remote.empty() || it->first == remote)) {
browser_.Disconnect(it->first);
browser_opened_.erase(it->first);
browser_supported_.erase(it->first);
it = browser_peers_.erase(it);
} else ++it;
}
}
std::lock_guard lock(sessions_mutex_);
disconnected_[handler].insert(remote);
for (auto& [id, sender] : senders_)
@@ -409,4 +461,129 @@ void FileTransferManager::Poll() {
}
}
void FileTransferManager::SetBrowserSupport(PeerEventHandler* handler,
const std::string& remote, bool supported) {
const auto props = owner_.FindRemoteSession(remote);
const auto events = props ? props->peer_events_ : owner_.ControllerEvents(remote);
if (!events || events.get() != handler || !events->DataAllowed()) return;
std::lock_guard lock(browser_mutex_);
if (const auto previous = browser_peers_.find(remote);
previous != browser_peers_.end() && previous->second != events) {
browser_.Disconnect(remote);
browser_opened_.erase(remote);
}
browser_peers_[remote] = events;
if (supported) browser_supported_.insert(remote);
else browser_supported_.erase(remote);
}
bool FileTransferManager::BrowserSupported(const std::string& remote) {
std::lock_guard lock(browser_mutex_);
return browser_supported_.count(remote) != 0;
}
bool FileTransferManager::OpenBrowser(const std::string& remote) {
auto props = owner_.FindRemoteSession(remote);
auto events = props ? props->peer_events_ : owner_.ControllerEvents(remote);
if (!events || !events->DataAllowed() || owner_.unattended_host_ ||
(props ? props->closing_ || !props->connection_established_
: !owner_.IsAuthorizedController(remote))) return false;
std::lock_guard lock(browser_mutex_);
if (const auto previous = browser_peers_.find(remote);
previous != browser_peers_.end() && previous->second != events) {
browser_.Disconnect(remote);
browser_opened_.erase(remote);
browser_supported_.erase(remote);
}
browser_peers_[remote] = events;
// Opening the legacy file picker authorizes a send, not disk browsing.
if (browser_supported_.count(remote)) browser_opened_.insert(remote);
return true;
}
void FileTransferManager::CancelBrowserTransfer(const std::string& remote, uint32_t file_id) {
for (const auto& info : BrowserTransfers(remote)) {
if (info.file_id != file_id) continue;
if (info.receiving) browser_.CancelTransfer(remote, info.wire_file_id);
else CancelSend(file_id);
return;
}
}
bool FileTransferManager::BrowserConnected(const std::string& remote) {
auto props = owner_.FindRemoteSession(remote);
auto events = props ? props->peer_events_ : owner_.ControllerEvents(remote);
if (!events || !events->DataAllowed() || owner_.unattended_host_ ||
(props ? props->closing_ || !props->connection_established_
: !owner_.IsAuthorizedController(remote))) return false;
std::lock_guard lock(browser_mutex_);
const auto it = browser_peers_.find(remote);
return it != browser_peers_.end() && it->second == events;
}
bool FileTransferManager::SendBrowser(const std::string& remote, const FileBrowser::Json& message) {
if (!BrowserConnected(remote)) return false;
auto props = owner_.FindRemoteSession(remote);
std::shared_ptr<PeerEventHandler> events;
{ std::lock_guard lock(browser_mutex_); events = browser_peers_[remote]; }
if (!events) return false;
auto callback = events->EnterCallback();
if (!callback || !events->DataAllowed()) return false;
PeerPtr* peer = events->IsDirect() ? events->DirectPeer() : props ? props->peer_ : owner_.peer_;
const auto data = message.dump(-1, ' ', false, FileBrowser::Json::error_handler_t::replace);
if (!peer || data.size() > 60000) return false;
const auto wire_id = events->WireId(remote);
return SendReliableDataFrameToPeer(peer, data.data(), data.size(),
owner_.control_data_label_.c_str(), wire_id.data(), wire_id.size()) == 0;
}
bool FileTransferManager::HandleBrowser(const char* data, size_t size,
PeerEventHandler* handler, const std::string& remote) {
if (!data || size > 60000 || std::string_view(data, size).find("file_browser") == std::string_view::npos)
return false;
auto message = FileBrowser::Json::parse(data, data + size, nullptr, false);
if (!message.is_object() || message.value("type", FileBrowser::Json{}) != "file_browser") return false;
auto props = owner_.FindRemoteSession(remote);
auto events = props ? props->peer_events_ : owner_.ControllerEvents(remote);
if (owner_.unattended_host_ || !events || events.get() != handler || !events->DataAllowed() ||
(props ? props->closing_ || !props->connection_established_
: !owner_.IsAuthorizedController(remote))) return true;
bool opened;
{
std::lock_guard lock(browser_mutex_);
browser_peers_[remote] = events;
if (message.value("op", FileBrowser::Json{}) == "presentation") {
// Older browser builds synchronized window visibility. Ignore that
// optional event: progress now belongs exclusively to the local sender.
return true;
}
opened = browser_opened_.count(remote);
}
// A controlled computer cannot browse the controller's disk until that
// controller explicitly opens this peer's file manager in this connection.
const auto op = message.value("op", FileBrowser::Json{});
if (props && !opened && op != "reply") {
if (message.contains("id")) SendBrowser(remote,
{{"op", "reply"}, {"id", message["id"]}, {"type", "file_browser"},
{"version", 1}, {"ok", false}, {"error", "browser_not_open"}});
return true;
}
browser_.Handle(remote, std::move(message));
return true;
}
std::vector<FileTransferManager::FileTransferState::FileTransferInfo>
FileTransferManager::BrowserTransfers(const std::string& remote) {
std::vector<FileTransferState::FileTransferInfo> result;
const auto collect = [&](auto& state) {
std::lock_guard lock(state.file_transfer_list_mutex_);
for (const auto& info : state.file_transfer_list_)
if (info.remote_id == remote) result.push_back(info);
};
collect(global_state_); collect(received_state_);
if (auto props = owner_.FindRemoteSession(remote)) collect(props->file_transfer_);
std::sort(result.begin(), result.end(), [](const auto& a, const auto& b) { return a.file_id > b.file_id; });
return result;
}
} // namespace crossdesk
@@ -13,6 +13,7 @@
#include <vector>
#include "file_transfer.h"
#include "features/file_transfer/file_browser.h"
#include "runtime/remote_session.h"
namespace crossdesk {
@@ -40,6 +41,15 @@ class FileTransferManager {
bool CancelSend(uint32_t file_id);
void Poll();
void Shutdown();
FileBrowser& browser() { return browser_; }
bool OpenBrowser(const std::string& remote);
void SetBrowserSupport(PeerEventHandler* handler, const std::string& remote, bool supported);
bool BrowserSupported(const std::string& remote);
bool BrowserConnected(const std::string& remote);
bool HandleBrowser(const char* data, size_t size, PeerEventHandler* handler,
const std::string& remote);
std::vector<FileTransferState::FileTransferInfo> BrowserTransfers(const std::string& remote);
void CancelBrowserTransfer(const std::string& remote, uint32_t file_id);
private:
struct Sender {
@@ -53,6 +63,8 @@ class FileTransferManager {
std::filesystem::path default_directory;
};
void ProcessQueue(std::shared_ptr<RemoteSession> props);
std::shared_ptr<FileReceiver> ReceiverFor(PeerEventHandler* handler, const std::string& remote);
bool SendBrowser(const std::string& remote, const FileBrowser::Json& message);
void UpdateProgress(FileTransferState& state,
const file_transfer::SendState& progress,
std::chrono::steady_clock::time_point now);
@@ -76,6 +88,11 @@ class FileTransferManager {
FileTransferState received_state_;
// Guarded by received_state_.file_transfer_list_mutex_.
std::unordered_map<uint32_t, ReceiveRateSample> receive_rate_samples_;
std::mutex browser_mutex_;
std::map<std::string, std::shared_ptr<PeerEventHandler>> browser_peers_;
std::set<std::string> browser_opened_;
std::set<std::string> browser_supported_;
FileBrowser browser_;
};
} // namespace crossdesk
@@ -0,0 +1,26 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-05
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _TRANSFER_NOTIFICATION_STATE_H_
#define _TRANSFER_NOTIFICATION_STATE_H_
namespace crossdesk::transfer_notification {
struct Presentation {
bool dismissed = false;
bool result_seen = false;
bool ShowNotification(bool browser_visible, bool result_presented) {
// Hiding an active transfer is temporary. A result already presented in
// the browser must not pop up again when that window closes.
result_seen = result_seen || result_presented;
return !dismissed && !result_seen && !browser_visible;
}
};
} // namespace crossdesk::transfer_notification
#endif
@@ -593,14 +593,17 @@ bool SettingsManager::StagePendingPasswordChange(
}
std::string SettingsManager::PendingPasswordChangeIdentity(
bool self_hosted, const std::string &server_host, int server_port) const {
bool self_hosted, const std::string &server_host, int server_port,
std::string* request_id) const {
std::lock_guard<std::mutex> lock(cache_mutex_);
if (request_id) request_id->clear();
if (cache_v3_.pending_identity[0] == '\0' ||
cache_v3_.pending_self_hosted != self_hosted ||
cache_v3_.pending_server_port != server_port ||
server_host != cache_v3_.pending_server_host) {
return {};
}
if (request_id) *request_id = cache_v3_.pending_request_id;
return cache_v3_.pending_identity;
}
@@ -51,7 +51,7 @@ public:
const std::string &request_id);
std::string PendingPasswordChangeIdentity(
bool self_hosted, const std::string &server_host,
int server_port) const;
int server_port, std::string* request_id = nullptr) const;
bool PromotePendingPasswordChange();
bool ClearPendingPasswordChange();
@@ -88,6 +88,11 @@ struct SlintVideoPresenter::Impl {
VideoRenderSize gl_pending_size;
bool gl_pending_dirty = false;
VideoLatencyFrame gl_pending_timing;
bool gl_use_pixel_buffers = false;
VideoRenderer::RenderOutcome gl_last_outcome;
std::string gl_rendered_stream;
std::string gl_requested_stream;
uint64_t gl_requested_sequence = 0;
#endif
SurfaceState CurrentState() const {
@@ -125,6 +130,13 @@ struct SlintVideoPresenter::Impl {
auto* opengl_renderer =
dynamic_cast<OpenGlVideoRenderer*>(&renderer);
if (state == slint::RenderingState::RenderingSetup) {
gl_use_pixel_buffers = false;
gl_last_outcome = {};
gl_rendered_stream.clear();
gl_requested_stream.clear();
gl_requested_sequence = 0;
displayed_frame_sequence.clear();
seeded_frame_sequence.clear();
GLuint texture = 0;
glGenTextures(1, &texture);
if (texture == 0) {
@@ -165,9 +177,28 @@ struct SlintVideoPresenter::Impl {
rounded_window ? static_cast<int>(std::lround(
kStreamWindowCornerRadius * scale_factor))
: 0;
opengl_renderer->RenderLatest(
const auto outcome = opengl_renderer->RenderLatest(
surface.selected_stream, static_cast<int>(window_size.width),
static_cast<int>(window_size.height), top_inset, corner_radius);
if (outcome.result == VideoRenderer::RenderResult::idle) {
return;
}
if (outcome.result == VideoRenderer::RenderResult::failed) {
// RenderLatest stops native submissions. Apply the UI fallback
// on the next UI tick, outside Slint's rendering callback.
gl_use_pixel_buffers = true;
LOG_WARN("Switching Slint video presentation to pixel buffers");
}
const bool changed = gl_rendered_stream != surface.selected_stream ||
gl_last_outcome.result != outcome.result ||
gl_last_outcome.sequence != outcome.sequence ||
gl_last_outcome.width != outcome.width ||
gl_last_outcome.height != outcome.height;
gl_last_outcome = outcome;
gl_rendered_stream = surface.selected_stream;
if (changed) {
MarkDirty();
}
return;
}
@@ -211,6 +242,8 @@ struct SlintVideoPresenter::Impl {
gl_pending_size = {};
gl_pending_dirty = false;
gl_pending_frame.clear();
gl_last_outcome = {};
gl_rendered_stream.clear();
}
});
@@ -239,6 +272,7 @@ void SlintVideoPresenter::PrepareWindow(
impl_->attachment_attempts = kMetalAttachmentAttemptLimit;
impl_->skip_attachment_once = true;
#elif !defined(__OHOS__)
stream->set_native_video_enabled(false);
impl_->ConfigureOpenGlNotifier();
#endif
}
@@ -313,7 +347,12 @@ bool SlintVideoPresenter::SelectStream(std::string remote_id) {
}
SlintVideoPresenter::PresentResult SlintVideoPresenter::Present(
const Frame& frame) {
const Frame& incoming_frame) {
#if !defined(__APPLE__) && !defined(__OHOS__)
Frame frame = incoming_frame;
#else
const Frame& frame = incoming_frame;
#endif
PresentResult result;
if (!impl_->stream || frame.remote_id.empty()) {
return result;
@@ -355,25 +394,54 @@ SlintVideoPresenter::PresentResult SlintVideoPresenter::Present(
auto* opengl_renderer =
dynamic_cast<OpenGlVideoRenderer*>(&impl_->renderer);
if (opengl_renderer && opengl_renderer->IsReady()) {
opengl_renderer->SetSelectedStream(frame.remote_id);
bool needs_redraw = opengl_renderer->SetSelectedStream(frame.remote_id);
if (!(*impl_->stream)->get_native_video_enabled()) {
(*impl_->stream)->set_native_video_enabled(true);
needs_redraw = true;
}
VideoRenderer::RenderOutcome outcome;
{
std::lock_guard lock(impl_->gl_mutex);
if (impl_->gl_rendered_stream == frame.remote_id) {
outcome = impl_->gl_last_outcome;
}
}
const bool has_frame =
frame.width > 0 && frame.height > 0 && frame.sequence > 0;
outcome.result == VideoRenderer::RenderResult::rendered;
(*impl_->stream)->set_has_frame(has_frame);
if (has_frame) {
(*impl_->stream)->set_receiving_text("");
result.width = frame.width;
result.height = frame.height;
result.new_frame = impl_->MarkPresented(frame.remote_id, frame.sequence);
result.width = outcome.width;
result.height = outcome.height;
result.new_frame = impl_->MarkPresented(frame.remote_id, outcome.sequence);
}
// A rendering acknowledgement also schedules Present(). Do not draw the
// same video again solely to acknowledge it, especially for low-FPS peers.
if (needs_redraw || impl_->gl_requested_stream != frame.remote_id ||
impl_->gl_requested_sequence != frame.sequence) {
impl_->gl_requested_stream = frame.remote_id;
impl_->gl_requested_sequence = frame.sequence;
(*impl_->stream)->window().request_redraw();
}
(*impl_->stream)->window().request_redraw();
return result;
}
if ((*impl_->stream)->get_native_video_enabled()) {
(*impl_->stream)->set_native_video_enabled(false);
(*impl_->stream)->set_has_frame(false);
(*impl_->stream)->set_frame(slint::Image{});
impl_->displayed_frame_sequence.clear();
impl_->seeded_frame_sequence.clear();
}
if (!frame.nv12 && impl_->gl_use_pixel_buffers) {
// Native submissions intentionally release the session's CPU buffers.
// Recover the retained frame so even a static remote desktop can switch
// immediately; subsequent decode callbacks will supply CPU frames.
auto pixels = std::make_shared<std::vector<unsigned char>>();
if (impl_->renderer.CopyLatestNv12(frame.remote_id, pixels.get(),
&frame.width, &frame.height)) {
frame.nv12 = std::move(pixels);
}
}
#endif
@@ -423,7 +491,7 @@ SlintVideoPresenter::PresentResult SlintVideoPresenter::Present(
uint32_t texture_id = 0;
{
std::lock_guard lock(impl_->gl_mutex);
texture_id = impl_->gl_texture;
texture_id = impl_->gl_use_pixel_buffers ? 0 : impl_->gl_texture;
}
if (texture_id != 0) {
impl_->gl_conversion_frame.resize(static_cast<size_t>(output_width) *
@@ -443,6 +443,12 @@ void GuiRuntime::CloseConnectionPeer() {
announcements_.Reset();
return;
}
{
std::lock_guard lock(controller_trust_mutex_);
std::erase_if(controller_trust_, [this](const auto& item) {
return item.second.events == peer_events_.get();
});
}
peer_events_->StopAccepting();
transfers_.Cancel(peer_events_.get());
announcements_.Reset();
@@ -0,0 +1,97 @@
#include "runtime/device_identity_store.h"
#include <openssl/crypto.h>
#include <stdexcept>
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "private_file.h"
namespace crossdesk::device_identity_store {
namespace {
void Require(bool ok) {
if (!ok) throw std::runtime_error("Device identity store unavailable or invalid");
}
// Keep the lock file's inode stable; it contains no credentials.
class StoreLock {
public:
explicit StoreLock(const std::filesystem::path& path) {
#ifdef _WIN32
handle_ = CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr,
OPEN_ALWAYS, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
BY_HANDLE_FILE_INFORMATION info{};
if (handle_ == INVALID_HANDLE_VALUE || !GetFileInformationByHandle(handle_, &info) ||
(info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) {
if (handle_ != INVALID_HANDLE_VALUE) CloseHandle(handle_);
throw std::runtime_error("Device identity store unavailable");
}
#else
handle_ = open(path.c_str(), O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, 0600);
struct stat info{};
if (handle_ < 0 || fstat(handle_, &info) != 0 || !S_ISREG(info.st_mode) ||
info.st_uid != getuid() || (info.st_mode & 0077) != 0 ||
flock(handle_, LOCK_EX | LOCK_NB) != 0) {
if (handle_ >= 0) close(handle_);
throw std::runtime_error("Device identity store unavailable");
}
#endif
}
~StoreLock() {
#ifdef _WIN32
CloseHandle(handle_);
#else
close(handle_);
#endif
}
StoreLock(const StoreLock&) = delete;
StoreLock& operator=(const StoreLock&) = delete;
private:
#ifdef _WIN32
HANDLE handle_ = INVALID_HANDLE_VALUE;
#else
int handle_ = -1;
#endif
};
struct PrivateText {
std::string value;
~PrivateText() { OPENSSL_cleanse(value.data(), value.size()); }
};
void Validate(const nlohmann::json& document) {
Require(document.is_object() && document.at("version") == 1);
}
} // namespace
void Update(const std::filesystem::path& cache,
const std::function<void(nlohmann::json&)>& update) {
private_file::EnsureDirectory(cache, true);
StoreLock lock(cache / "identity.json.lock");
const auto path = cache / "identity.json";
const bool exists = std::filesystem::symlink_status(path).type() !=
std::filesystem::file_type::not_found;
nlohmann::json saved = {{"version", 1}};
if (exists) {
PrivateText text{private_file::Read(path)};
saved = nlohmann::json::parse(text.value, nullptr, false);
Require(!saved.is_discarded());
}
Validate(saved);
PrivateText before{saved.dump()};
update(saved);
Validate(saved);
PrivateText after{saved.dump()};
Require(after.value.size() <= 64 * 1024);
if (!exists || before.value != after.value) private_file::Write(path, after.value);
}
} // namespace crossdesk::device_identity_store
@@ -0,0 +1,24 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-01
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _DEVICE_IDENTITY_STORE_H_
#define _DEVICE_IDENTITY_STORE_H_
#include <filesystem>
#include <functional>
#include <nlohmann/json.hpp>
namespace crossdesk::device_identity_store {
// The shared device signing key lives in cache/identity.json. Read the latest
// document under a process lock, apply an update, then atomically persist it.
// Throw on corruption, unsafe permissions, lock contention or persistence error.
void Update(const std::filesystem::path& cache,
const std::function<void(nlohmann::json&)>& update);
} // namespace crossdesk::device_identity_store
#endif
@@ -0,0 +1,70 @@
#include "runtime/device_login.h"
#include <algorithm>
#include <cstring>
#include "runtime/trusted_devices.h"
namespace crossdesk {
int DeviceLogin::Exchange(SignalExchangeStage stage, const nlohmann::json& message,
const TrustedDevices* identity, char* response, size_t capacity) {
auto output = [&](const nlohmann::json& reply) {
const auto text = reply.dump();
if (text.empty() || text.size() > capacity) return -1;
std::memcpy(response, text.data(), text.size());
return static_cast<int>(text.size());
};
if (stage == SignalExchangeStage::PrepareLogin) {
phase_ = Phase::Idle;
used_password_ = false;
password_.clear();
request_ = message;
const auto login = message.at("user_id").get<std::string>();
if (!identity) return -1; // Never fall back when local key storage fails.
const auto at = login.find('@');
request_["user_id"] = login.substr(0, at);
if (at != std::string::npos) password_ = login.substr(at + 1);
request_["device_key"] = {{"version", 1}, {"public_key", identity->PublicKey()}};
request_.erase("reconnect_token");
request_.erase("reconnect_version");
phase_ = Phase::AwaitingChallenge;
return output(request_);
}
if (!Pending()) return 0;
const auto type = message.value("type", "");
if (type == "login_challenge") {
if (!identity || phase_ != Phase::AwaitingChallenge || message.at("device_key_version") != 1 ||
message.at("user_id") != request_.at("user_id")) return -1;
const auto nonce = message.at("nonce").get<std::string>();
if (nonce.size() != 64 || !std::all_of(nonce.begin(), nonce.end(),
[](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }))
return -1;
const auto id = request_.at("user_id").get<std::string>();
auto reply = request_;
used_password_ = message.at("password_required").get<bool>();
if (used_password_) {
if (id.empty() || id.rfind("C-", 0) == 0 || password_.empty()) return -1;
reply["user_id"] = id + "@" + password_;
}
const auto transcript = nlohmann::json::array(
{"crossdesk.device-login.v1", id, identity->PublicKey(), nonce}).dump();
reply["device_key"]["nonce"] = nonce;
reply["device_key"]["signature"] = identity->Sign(transcript);
phase_ = Phase::AwaitingResult;
password_.clear();
return output(reply);
}
if (type == "login") {
if (message.at("status") == "success") {
if (phase_ != Phase::AwaitingResult || message.value("device_key_version", 0) != 1) return -1;
const auto assigned = message.at("user_id").get<std::string>();
const auto expected = request_.at("user_id").get<std::string>();
if (assigned.empty() || (!expected.empty() && assigned != expected)) return -1;
}
password_.clear();
request_.clear();
phase_ = Phase::Idle;
}
return 0;
}
} // namespace crossdesk
@@ -0,0 +1,35 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-02
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _DEVICE_LOGIN_H_
#define _DEVICE_LOGIN_H_
#include <nlohmann/json.hpp>
#include <string>
#include "minirtc.h"
namespace crossdesk {
class TrustedDevices;
// One signaling connection's application authentication, owned by its callbacks.
class DeviceLogin {
public:
int Exchange(SignalExchangeStage stage, const nlohmann::json& message,
const TrustedDevices* identity, char* response, size_t capacity);
bool Pending() const { return phase_ != Phase::Idle; }
bool UsedPassword() const { return used_password_; }
private:
enum class Phase { Idle, AwaitingChallenge, AwaitingResult };
nlohmann::json request_;
std::string password_;
Phase phase_ = Phase::Idle;
bool used_password_ = false;
};
} // namespace crossdesk
#endif
@@ -0,0 +1,192 @@
#include "runtime/gui_runtime.h"
#include "platform.h"
#include "rd_log.h"
namespace crossdesk {
void GuiRuntime::InitializeTrustedDevices(const std::filesystem::path& directory) {
try {
trusted_devices_ = std::make_unique<TrustedDevices>(directory, cache_path_);
} catch (const std::exception& error) {
LOG_ERROR("Cannot load trusted devices: {}", error.what());
// The independent persisted switch stays enabled on identity/store failure.
}
}
bool GuiRuntime::TrustedControllerAllowed(const std::string& id) {
if (!config_center_ || !config_center_->IsTrustedDevicesOnly()) return true;
std::lock_guard lock(controller_trust_mutex_);
const auto it = controller_trust_.find(id);
return it != controller_trust_.end() && it->second.IsTrusted(trusted_devices_.get());
}
bool GuiRuntime::BeginControllerTrust(const std::string& id, PeerEventHandler* events) {
const bool required = config_center_->IsTrustedDevicesOnly();
std::lock_guard lock(controller_trust_mutex_);
const auto previous = controller_trust_.find(id);
// Non-connected statuses clear this state. Duplicate Connected notifications
// in the same application session must not restart the challenge or timeout.
if (previous != controller_trust_.end() && previous->second.events == events) {
auto& state = previous->second;
const bool allowed = !required || state.IsTrusted(trusted_devices_.get());
state.pending = !allowed;
return allowed;
}
ControllerTrust state;
state.events = events;
state.pending = required;
state.deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10);
try {
if (!trusted_devices_) state.invalid = true;
else state.nonce = TrustedDevices::Nonce();
} catch (...) { state.invalid = true; }
controller_trust_[id] = std::move(state);
return !required;
}
void GuiRuntime::ForgetControllerTrust(const std::string& id, PeerEventHandler* events) {
std::lock_guard lock(controller_trust_mutex_);
const auto it = controller_trust_.find(id);
if (it != controller_trust_.end() && it->second.events == events)
controller_trust_.erase(it);
}
int GuiRuntime::SendTrustMessage(const std::string& id, const nlohmann::json& message) {
const auto text = message.dump();
return WithController(id, [&](PeerPtr* peer, const std::string& wire) {
return SendReliableDataFrameToPeer(peer, text.data(), text.size(),
control_data_label_.c_str(), wire.data(), wire.size());
}, false);
}
bool GuiRuntime::HandleDeviceTrustMessage(const std::string& id, PeerEventHandler* events,
const char* data, size_t size) {
if (!data || size > 4096) return false;
const auto message = nlohmann::json::parse(data, data + size, nullptr, false);
if (!message.is_object()) return false;
const auto type_it = message.find("type");
if (type_it == message.end()) return false;
if (*type_it == static_cast<int>(ControlType::host_infomation)) {
// Advertise through an existing message so disabled restrictions send no
// unfamiliar protocol messages to legacy clients. Retain only bounded,
// inert metadata until the connection's proof has been accepted.
std::lock_guard lock(controller_trust_mutex_);
const auto it = controller_trust_.find(id);
if (it != controller_trust_.end() && it->second.events == events) {
const auto capability = message.find("device_trust_version");
if (capability != message.end() && *capability == 1) it->second.capable = true;
if (it->second.pending) {
it->second.early_host_info.assign(data, size);
return true;
}
}
return false;
}
if (!type_it->is_string()) return false;
const auto type = type_it->get<std::string>();
if (type.rfind("device_trust_", 0) != 0) return false;
if (!trusted_devices_) return true;
try {
if (type == "device_trust_challenge") {
const auto props = FindRemoteSession(id);
if (!props || props->closing_ || props->peer_events_.get() != events ||
message.at("version") != 1) return true;
const auto wire = events->WireId(id);
const auto proof = trusted_devices_->Prove(message.at("nonce"),
props->local_id_, GetHostName()).dump();
SendReliableDataFrameToPeer(props->peer_, proof.data(), proof.size(),
control_data_label_.c_str(), wire.data(), wire.size());
} else if (type == "device_trust_proof") {
std::lock_guard lock(controller_trust_mutex_);
const auto it = controller_trust_.find(id);
if (it == controller_trust_.end() || it->second.events != events) return true;
auto& state = it->second;
if (state.invalid || state.verified || std::chrono::steady_clock::now() >= state.deadline)
return true;
// Accept once per fresh challenge; malformed/replayed proofs grant nothing.
state.verified = TrustedDevices::Verify(message, state.nonce);
if (!state.verified) state.invalid = true;
}
} catch (const std::exception&) {
// Untrusted protocol input never escapes the transport callback.
}
return true;
}
void GuiRuntime::TickControllerTrust() {
struct Action {
std::string id;
PeerEventHandler* events;
std::string nonce;
int kind;
std::string host_info;
};
std::vector<Action> actions;
const auto now = std::chrono::steady_clock::now();
const bool required = config_center_->IsTrustedDevicesOnly();
{
std::lock_guard lock(controller_trust_mutex_);
for (auto& [id, state] : controller_trust_) {
if (state.closing) continue;
const bool trusted = state.IsTrusted(trusted_devices_.get());
if (required && (state.invalid || (state.verified && !trusted) ||
(!state.verified && now >= state.deadline))) {
state.invalid = true;
state.closing = true;
actions.push_back({id, state.events, {}, -1});
} else if (state.pending && (!required || trusted)) {
state.pending = false;
actions.push_back({id, state.events, {}, 1, std::exchange(state.early_host_info, {})});
}
if ((required || state.capable) && !state.invalid && !state.verified &&
now < state.deadline && now >= state.next_challenge) {
state.next_challenge = now + std::chrono::seconds(1);
actions.push_back({id, state.events, state.nonce, 0});
}
}
}
for (const auto& action : actions) {
const auto events = ControllerEvents(action.id);
if (!events || events.get() != action.events) continue;
auto callback = events->EnterCallback();
if (!callback) continue;
if (action.kind < 0) {
LOG_WARN("Reject controller [{}]: trusted device verification required", action.id);
transfers_.Cancel(events.get(), action.id);
remote_input_.Disconnect(action.id);
CloseServerController(action.id);
} else if (action.kind > 0) {
events->ApplyConnectionStatus(ConnectionStatus::Connected, action.id);
if (!action.host_info.empty()) {
const auto wire = events->WireId(action.id);
PeerEventHandler::OnReceiveDataBuffer(action.host_info.data(), action.host_info.size(),
wire.data(), wire.size(), control_data_label_.data(), control_data_label_.size(), events.get());
}
} else {
SendTrustMessage(action.id, {{"type", "device_trust_challenge"},
{"version", 1}, {"nonce", action.nonce}});
}
}
}
std::optional<TrustedDevices::Device> GuiRuntime::VerifiedController(const std::string& id) {
std::lock_guard lock(controller_trust_mutex_);
const auto it = controller_trust_.find(id);
return it == controller_trust_.end() || it->second.invalid
? std::nullopt : it->second.verified;
}
bool GuiRuntime::TrustController(const std::string& id, const std::string& expected_key) {
if (!trusted_devices_ || !IsAuthorizedController(id)) return false;
const auto device = VerifiedController(id);
if (!device || device->public_key != expected_key) return false;
try { trusted_devices_->Add(*device); return true; }
catch (const std::exception& error) { LOG_ERROR("Cannot trust device: {}", error.what()); return false; }
}
bool GuiRuntime::RemoveTrustedDevice(const std::string& public_key) {
if (!trusted_devices_) return false;
try { trusted_devices_->Remove(public_key); }
catch (const std::exception& error) { LOG_ERROR("Cannot remove trusted device: {}", error.what()); return false; }
TickControllerTrust();
return true;
}
} // namespace crossdesk
+2 -3
View File
@@ -190,9 +190,7 @@ int GuiRuntime::CreateConnectionPeer() {
if (pending_identity.empty()) {
credential_recovery_in_progress_ = false;
credential_recovery_attempt_pending_ = false;
credential_recovery_retry_active_ = false;
credential_recovery_promote_pending_ = false;
credential_recovery_clear_pending_ = false;
credential_recovery_action_ = CredentialRecoveryAction::Idle;
} else if (!credential_recovery_in_progress_) {
credential_recovery_in_progress_ = true;
credential_recovery_attempt_pending_ = true;
@@ -270,6 +268,7 @@ int GuiRuntime::CreateConnectionPeer() {
params_.on_signal_status = PeerEventHandler::OnSignalStatus;
params_.on_signal_message = PeerEventHandler::OnSignalMessage;
params_.on_signal_exchange = PeerEventHandler::OnSignalExchange;
params_.on_connection_status = PeerEventHandler::OnConnectionStatus;
params_.on_net_status_report = PeerEventHandler::OnNetStatusReport;
+29 -1
View File
@@ -26,6 +26,7 @@
#include "runtime/announcement_inbox.h"
#include "runtime/peer_event_handler.h"
#include "runtime/privacy_session_policy.h"
#include "runtime/trusted_devices.h"
namespace crossdesk {
@@ -63,7 +64,8 @@ class GuiRuntime : protected gui_detail::GuiState {
std::string password, bool remember_password = false);
int WithController(
const std::string& id,
const std::function<int(PeerPtr*, const std::string&)>& operation);
const std::function<int(PeerPtr*, const std::string&)>& operation,
bool require_trusted = true);
int SendControllerData(const std::string& id, const char* data, size_t size,
const char* label);
std::shared_ptr<PeerEventHandler> ControllerEvents(const std::string& id);
@@ -105,6 +107,32 @@ class GuiRuntime : protected gui_detail::GuiState {
void HandlePrivacy();
void HandleScreenLock();
bool IsAuthorizedController(const std::string& remote_id);
void InitializeTrustedDevices(const std::filesystem::path& directory);
bool TrustedControllerAllowed(const std::string& remote_id);
bool BeginControllerTrust(const std::string& remote_id, PeerEventHandler* events);
void ForgetControllerTrust(const std::string& remote_id, PeerEventHandler* events);
bool HandleDeviceTrustMessage(const std::string& remote_id, PeerEventHandler* events,
const char* data, size_t size);
void TickControllerTrust();
std::optional<TrustedDevices::Device> VerifiedController(const std::string& remote_id);
bool TrustController(const std::string& remote_id, const std::string& expected_key);
bool RemoveTrustedDevice(const std::string& public_key);
int SendTrustMessage(const std::string& remote_id, const nlohmann::json& message);
std::unique_ptr<TrustedDevices> trusted_devices_;
struct ControllerTrust {
PeerEventHandler* events = nullptr;
std::string nonce;
std::optional<TrustedDevices::Device> verified;
std::string early_host_info;
std::chrono::steady_clock::time_point deadline{}, next_challenge{};
bool pending = false, invalid = false, closing = false, capable = false;
bool IsTrusted(const TrustedDevices* devices) const {
return devices && !invalid && !closing && verified &&
devices->Contains(verified->public_key);
}
};
std::mutex controller_trust_mutex_;
std::map<std::string, ControllerTrust> controller_trust_;
void SetControllerPrivacySupport(const std::string& remote_id, bool supported);
// Caller holds connection_status_mutex_ exclusively. Turns privacy off when
// any connected controller lacks support, or on for the first automatic one.
+3 -1
View File
@@ -180,7 +180,9 @@ std::shared_ptr<PeerEventHandler> GuiRuntime::ControllerEvents(
}
int GuiRuntime::WithController(
const std::string& id,
const std::function<int(PeerPtr*, const std::string&)>& operation) {
const std::function<int(PeerPtr*, const std::string&)>& operation,
bool require_trusted) {
if (require_trusted && !TrustedControllerAllowed(id)) return -1;
std::shared_lock lock(remote_sessions_mutex_);
auto it = lan_controllers_.find(id);
auto events = it == lan_controllers_.end() ? peer_events_ : it->second.events;
@@ -133,6 +133,12 @@ void PeerEventHandler::OnReceiveDataBuffer(
GuiRuntime* runtime = &handler->owner_;
std::string source_id = std::string(src_id, src_id_size);
const auto remote_id = handler->ConnectionKey(user_id, user_id_size);
if (source_id == runtime->control_data_label_ &&
runtime->HandleDeviceTrustMessage(remote_id, handler, data, size)) return;
const auto viewer = runtime->FindRemoteSession(remote_id);
if (viewer && viewer->peer_events_.get() != handler) return;
if (!viewer && !runtime->TrustedControllerAllowed(remote_id)) return;
// The service-owned host runs as SYSTEM. Do not expose filesystem or
// clipboard operations in that security context.
if (runtime->unattended_host_ &&
@@ -141,36 +147,34 @@ void PeerEventHandler::OnReceiveDataBuffer(
source_id == runtime->clipboard_label_ ||
source_id == web_clipboard::kStream))
return;
if (source_id == runtime->control_data_label_ &&
runtime->transfers_.HandleBrowser(data, size, handler, remote_id)) return;
if (source_id == web_clipboard::kStream) {
runtime->clipboard_.ReceiveWeb(
data, size, handler->ConnectionKey(user_id, user_id_size), handler);
data, size, remote_id, handler);
return;
}
if (source_id == runtime->file_label_) {
runtime->transfers_.Receive(data, size, handler,
handler->ConnectionKey(user_id, user_id_size));
runtime->transfers_.Receive(data, size, handler, remote_id);
return;
} else if (source_id == runtime->clipboard_label_) {
if (size > 0) {
std::string remote_user_id =
handler->ConnectionKey(user_id, user_id_size);
auto props =
runtime->FindRemoteSession(remote_user_id);
if (props && !props->clipboard_allowed_.load()) {
if (viewer && !viewer->clipboard_allowed_.load()) {
return;
}
runtime->clipboard_.QueueRemoteText(
data, size, props ? remote_user_id : std::string{});
data, size, viewer ? remote_id : std::string{}, {},
viewer ? std::function<bool()>{} : [runtime, remote_id] {
return runtime->IsAuthorizedController(remote_id);
});
}
return;
} else if (source_id == runtime->file_feedback_label_) {
runtime->transfers_.HandleAck(
data, size, handler, handler->ConnectionKey(user_id, user_id_size));
runtime->transfers_.HandleAck(data, size, handler, remote_id);
return;
}
const std::string remote_id = handler->ConnectionKey(user_id, user_id_size);
const std::string wire_id = handler->WireId(remote_id);
PeerPtr* bound_peer =
handler->IsDirect() ? handler->DirectPeer() : runtime->peer_;
@@ -422,6 +426,10 @@ void PeerEventHandler::OnReceiveDataBuffer(
}
if (remote_action.type == ControlType::host_infomation) {
if (source_id == runtime->control_data_label_) {
runtime->transfers_.SetBrowserSupport(handler, remote_id,
remote_action.i.supports_file_browser);
}
bool is_client_mode = false;
std::shared_ptr<GuiRuntime::RemoteSession> props;
{
@@ -84,6 +84,24 @@ PeerEventHandler::PeerEventHandler(GuiRuntime& owner) : owner_(owner) {
owner_.transfers_.Connected(this, "");
}
int PeerEventHandler::OnSignalExchange(SignalExchangeStage stage, const char* message,
size_t size, char* response, size_t capacity, void* user_data) {
auto* handler = static_cast<PeerEventHandler*>(user_data);
if (!handler || !message) return -1;
auto callback = handler->EnterCallback();
if (!callback) return -1;
if (stage == SignalExchangeStage::IncomingMessage &&
!handler->device_login_.Pending()) return 0;
try {
return handler->device_login_.Exchange(stage,
nlohmann::json::parse(message, message + size),
handler->owner_.trusted_devices_.get(), response, capacity);
} catch (const std::exception&) {
LOG_ERROR("Device login protocol or identity unavailable");
return -1;
}
}
void PeerEventHandler::OnSignalMessage(const char* message, size_t size,
void* user_data) {
auto* handler = static_cast<PeerEventHandler*>(user_data);
@@ -184,13 +202,16 @@ void PeerEventHandler::OnSignalMessage(const char* message, size_t size,
j.contains("reason") && j["reason"].is_string()
? j["reason"].get<std::string>()
: "Password change failed";
runtime->password_change_result_uncertain_ = false;
// A rejected replay cannot tell us whether the original request committed.
runtime->password_change_result_uncertain_ = runtime->password_change_recovery_ &&
!runtime->password_change_succeeded_;
runtime->password_change_result_ready_ = true;
}
}
void PeerEventHandler::OnSignalStatus(SignalStatus status, const char* user_id,
size_t user_id_size, void* user_data) {
using RecoveryAction = GuiRuntime::CredentialRecoveryAction;
auto* handler = static_cast<PeerEventHandler*>(user_data);
if (!handler) return;
auto callback = handler->EnterCallback();
@@ -212,10 +233,12 @@ void PeerEventHandler::OnSignalStatus(SignalStatus status, const char* user_id,
SendClientInfo(runtime->peer_, client_id);
std::lock_guard<std::mutex> lock(runtime->password_change_mutex_);
if (runtime->credential_recovery_in_progress_) {
if (runtime->credential_recovery_attempt_pending_) {
runtime->credential_recovery_promote_pending_ = true;
if (!handler->device_login_.UsedPassword()) {
runtime->credential_recovery_action_ = RecoveryAction::ResumePending;
} else if (runtime->credential_recovery_attempt_pending_) {
runtime->credential_recovery_action_ = RecoveryAction::PromotePending;
} else {
runtime->credential_recovery_clear_pending_ = true;
runtime->credential_recovery_action_ = RecoveryAction::ClearPending;
}
}
} else if (SignalStatus::SignalFailed == status) {
@@ -223,7 +246,7 @@ void PeerEventHandler::OnSignalStatus(SignalStatus status, const char* user_id,
std::lock_guard<std::mutex> lock(runtime->password_change_mutex_);
if (runtime->credential_recovery_in_progress_ &&
runtime->credential_recovery_attempt_pending_) {
runtime->credential_recovery_retry_active_ = true;
runtime->credential_recovery_action_ = RecoveryAction::RetryActive;
}
} else if (SignalStatus::SignalClosed == status) {
runtime->signal_connected_ = false;
@@ -300,6 +323,14 @@ void PeerEventHandler::DispatchConnectionStatus(ConnectionStatus status,
}
}
if (!props) {
if (status == ConnectionStatus::Connected) {
if (!runtime->BeginControllerTrust(remote_id, handler)) return;
} else {
runtime->ForgetControllerTrust(remote_id, handler);
}
}
if (props) {
runtime->is_client_mode_ = true;
if (!props->wall_managed_) runtime->show_connection_status_window_ = true;
@@ -328,11 +359,14 @@ void PeerEventHandler::DispatchConnectionStatus(ConnectionStatus status,
remote_action.i.supports_deskhub_resolution = true;
remote_action.i.supports_deskhub_fps15 = true;
remote_action.i.supports_deskhub_bandwidth = true;
remote_action.i.supports_file_browser = !runtime->unattended_host_;
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
LOG_INFO("Local display [{}:{}]", i + 1,
remote_action.i.display_list[i]);
}
std::string msg = remote_action.to_json();
auto information = nlohmann::json::parse(remote_action.to_json());
information["device_trust_version"] = 1;
std::string msg = information.dump();
const int ret =
SendReliableDataFrame(props->peer_, msg.data(), msg.size(),
runtime->control_data_label_.c_str());
@@ -495,6 +529,7 @@ void PeerEventHandler::DispatchConnectionStatus(ConnectionStatus status,
remote_action.i.supports_deskhub_resolution = true;
remote_action.i.supports_deskhub_fps15 = true;
remote_action.i.supports_deskhub_bandwidth = true;
remote_action.i.supports_file_browser = !runtime->unattended_host_;
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
LOG_INFO("Local display [{}:{}]", i + 1,
remote_action.i.display_list[i]);
@@ -15,6 +15,7 @@
#include "minirtc.h"
#include "runtime/session_lifecycle.h"
#include "runtime/device_login.h"
namespace crossdesk {
@@ -63,6 +64,9 @@ public:
size_t user_id_size, void *user_data);
static void OnSignalMessage(const char *message, size_t size,
void *user_data);
static int OnSignalExchange(SignalExchangeStage stage, const char* message,
size_t size, char* response, size_t capacity,
void* user_data);
static void OnConnectionStatus(ConnectionStatus status, const char *user_id,
size_t user_id_size, void *user_data);
static void OnNetStatusReport(const char *client_id, size_t client_id_size,
@@ -85,6 +89,7 @@ private:
size_t early_data_bytes_ = 0;
GuiRuntime& owner_;
DeviceLogin device_login_;
gui_detail::SessionCallbackGate callbacks_;
};
@@ -183,9 +183,11 @@ void PeerEventHandler::OnReceiveVideoBuffer(
return;
}
if (submit_result == VideoRenderer::SubmitResult::dropped ||
submit_result == VideoRenderer::SubmitResult::failed) {
(submit_result == VideoRenderer::SubmitResult::failed &&
native_renderer->IsActive())) {
// Keep presenting the last native frame. A later decoded frame can
// reuse the renderer without changing ownership mid-window.
// reuse an active renderer. If rendering disabled it concurrently,
// continue below to materialize this frame for the CPU fallback.
props->streaming_ = true;
return;
}
@@ -16,6 +16,7 @@
namespace crossdesk {
bool GuiRuntime::IsAuthorizedController(const std::string& remote_id) {
if (!TrustedControllerAllowed(remote_id)) return false;
if (remote_id.rfind("lan/", 0) == 0) {
const auto events = ControllerEvents(remote_id);
if (!events || !events->DataAllowed()) return false;
@@ -59,6 +60,7 @@ void GuiRuntime::ApplyPrivacyAdmission(bool automatic_enable) {
void GuiRuntime::QueuePrivacyCommand(const std::string& remote_id,
const PrivacyCommand& command) {
if (!TrustedControllerAllowed(remote_id)) return;
std::shared_lock session_lock(connection_status_mutex_);
const auto found = connection_status_.find(remote_id);
if (found == connection_status_.end() ||
@@ -86,6 +88,7 @@ void GuiRuntime::HandlePrivacy() {
commands.swap(privacy_commands_);
}
for (const auto& [remote_id, command] : commands) {
if (!TrustedControllerAllowed(remote_id)) continue;
// 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_);
@@ -73,6 +73,7 @@ struct FileTransferState {
uint32_t file_id = 0;
uint32_t rate_bps = 0;
bool receiving = false;
uint32_t wire_file_id = 0;
};
std::vector<FileTransferInfo> file_transfer_list_;
std::mutex file_transfer_list_mutex_;
+5 -3
View File
@@ -167,21 +167,23 @@ struct UserSettingsState {
};
struct PasswordChangeState {
enum class CredentialRecoveryAction {
Idle, RetryActive, PromotePending, ClearPending, ResumePending
};
std::mutex password_change_mutex_;
uint64_t next_password_change_request_id_ = 0;
bool password_change_pending_ = false;
bool password_change_result_ready_ = false;
bool password_change_succeeded_ = false;
bool password_change_result_uncertain_ = false;
bool password_change_recovery_ = false;
std::chrono::steady_clock::time_point password_change_requested_at_;
std::string pending_password_change_request_id_;
std::string pending_local_password_;
std::string password_change_error_;
bool credential_recovery_in_progress_ = false;
bool credential_recovery_attempt_pending_ = false;
bool credential_recovery_retry_active_ = false;
bool credential_recovery_promote_pending_ = false;
bool credential_recovery_clear_pending_ = false;
CredentialRecoveryAction credential_recovery_action_ = CredentialRecoveryAction::Idle;
};
struct ConnectionState {
@@ -0,0 +1,233 @@
#include "runtime/trusted_devices.h"
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <algorithm>
#include <array>
#include <stdexcept>
#include "private_file.h"
#include "runtime/device_identity_store.h"
namespace crossdesk {
namespace {
constexpr size_t kMaxTrustedDevices = 128;
void Require(bool ok) {
if (!ok) throw std::runtime_error("Invalid or unavailable trusted device identity");
}
std::string Hex(const uint8_t* data, size_t size) {
constexpr char digits[] = "0123456789abcdef";
std::string result;
result.reserve(size * 2);
for (size_t i = 0; i < size; ++i) {
result += digits[data[i] >> 4]; result += digits[data[i] & 15];
}
return result;
}
bool IsHex(const std::string& value, size_t bytes) {
return value.size() == bytes * 2 && std::all_of(value.begin(), value.end(),
[](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); });
}
std::vector<uint8_t> Unhex(const std::string& text, size_t bytes) {
Require(IsHex(text, bytes));
auto digit = [](char c) { return c <= '9' ? c - '0' : c - 'a' + 10; };
std::vector<uint8_t> result(bytes);
for (size_t i = 0; i < bytes; ++i)
result[i] = (digit(text[2 * i]) << 4) | digit(text[2 * i + 1]);
return result;
}
bool Label(const std::string& value) {
return value.size() <= 128 && std::none_of(value.begin(), value.end(),
[](unsigned char c) { return c < 32 || c == 127; });
}
std::string Transcript(const std::string& nonce, const TrustedDevices::Device& device) {
// Canonical encoding and a domain tag prevent ambiguous or cross-protocol use.
return nlohmann::json::array({"crossdesk.device-trust.v1", nonce, device.public_key,
device.device_id, device.name}).dump();
}
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
struct PrivateText {
std::string value;
~PrivateText() { OPENSSL_cleanse(value.data(), value.size()); }
};
}
TrustedDevices::TrustedDevices(const std::filesystem::path& directory,
const std::filesystem::path& cache)
: path_(directory / "devices.json") {
private_file::EnsureDirectory(directory);
const bool exists = std::filesystem::symlink_status(path_).type() !=
std::filesystem::file_type::not_found;
PrivateText legacy_key;
if (exists) {
PrivateText text{private_file::Read(path_)};
auto saved = nlohmann::json::parse(text.value, nullptr, false);
Require(!saved.is_discarded());
const bool legacy = saved.at("version") == 1;
Require((legacy || saved.at("version") == 2) && saved.at("devices").is_array() &&
saved.at("devices").size() <= kMaxTrustedDevices);
if (legacy) {
legacy_key.value = saved.at("private_key").get<std::string>();
auto& encoded = saved["private_key"].get_ref<std::string&>();
OPENSSL_cleanse(encoded.data(), encoded.size());
Require(IsHex(legacy_key.value, 32));
} else Require(!saved.contains("private_key"));
for (const auto& row : saved.at("devices")) {
Device device{row.at("public_key"), row.at("name"), row.at("device_id")};
Require(IsHex(device.public_key, 32) && Label(device.name) && Label(device.device_id));
Require(devices_.emplace(device.public_key, device).second);
}
}
device_identity_store::Update(cache, [&](nlohmann::json& identity) {
if (!identity.contains("trust_private_key") && !legacy_key.value.empty())
identity["trust_private_key"] = legacy_key.value;
if (identity.contains("trust_private_key")) {
const auto& encoded = identity.at("trust_private_key").get_ref<const std::string&>();
// Interrupted migration may leave both copies. Never replace either key
// on a mismatch: that would silently invalidate existing pairings.
Require(legacy_key.value.empty() || encoded == legacy_key.value);
auto secret = Unhex(encoded, 32);
key_.reset(EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr,
secret.data(), secret.size()));
OPENSSL_cleanse(secret.data(), secret.size());
} else {
key_.reset(EVP_PKEY_Q_keygen(nullptr, nullptr, "ED25519"));
Require(bool(key_));
std::array<uint8_t, 32> secret{};
size_t size = secret.size();
Require(EVP_PKEY_get_raw_private_key(key_.get(), secret.data(), &size) == 1 && size == 32);
identity["trust_private_key"] = Hex(secret.data(), secret.size());
OPENSSL_cleanse(secret.data(), secret.size());
}
Require(bool(key_));
});
std::array<uint8_t, 32> public_key{};
size_t size = public_key.size();
Require(EVP_PKEY_get_raw_public_key(key_.get(), public_key.data(), &size) == 1 && size == 32);
public_key_ = Hex(public_key.data(), public_key.size());
// The identity update is durable before removing the legacy secret. If this
// write fails, reopening can safely retry with the same key and device list.
if (!exists || !legacy_key.value.empty()) Save(devices_);
}
std::string TrustedDevices::Fingerprint(const std::string& public_key) {
const auto bytes = Unhex(public_key, 32);
std::array<uint8_t, SHA256_DIGEST_LENGTH> hash{};
SHA256(bytes.data(), bytes.size(), hash.data());
return Hex(hash.data(), hash.size());
}
std::string TrustedDevices::Fingerprint() const { return Fingerprint(public_key_); }
std::string TrustedDevices::PairingInfo(const std::string& device_id,
const std::string& name) const {
Require(Label(device_id) && Label(name));
// Export public information only. Connection admission still requires a fresh
// proof of private-key possession; importing this document grants no bypass.
return nlohmann::json{{"type", "crossdesk-pairing"}, {"version", 1},
{"public_key", public_key_}, {"device_id", device_id}, {"name", name}}.dump();
}
std::optional<TrustedDevices::Device> TrustedDevices::ParsePairingInfo(std::string_view text) {
if (text.empty() || text.size() > kMaxPairingInfoSize) return std::nullopt;
try {
const auto info = nlohmann::json::parse(text.begin(), text.end(), nullptr, false);
if (!info.is_object() || info.size() != 5 || info.at("type") != "crossdesk-pairing" ||
!info.at("version").is_number_integer() || info.at("version") != 1)
return std::nullopt;
Device device{info.at("public_key"), info.at("name"), info.at("device_id")};
if (IsHex(device.public_key, 32) && Label(device.name) && Label(device.device_id))
return device;
} catch (const std::exception&) {}
return std::nullopt;
}
std::string TrustedDevices::Nonce() {
std::array<uint8_t, 32> bytes{};
Require(RAND_bytes(bytes.data(), bytes.size()) == 1);
return Hex(bytes.data(), bytes.size());
}
nlohmann::json TrustedDevices::Prove(const std::string& nonce,
const std::string& device_id, const std::string& name) const {
Require(IsHex(nonce, 32) && Label(device_id) && Label(name));
const Device device{public_key_, name, device_id};
const auto text = Transcript(nonce, device);
return {{"type", "device_trust_proof"}, {"version", 1}, {"nonce", nonce},
{"public_key", public_key_}, {"device_id", device_id}, {"name", name},
{"signature", Sign(text)}};
}
std::string TrustedDevices::Sign(std::string_view text) const {
Context context(EVP_MD_CTX_new(), EVP_MD_CTX_free);
std::array<uint8_t, 64> signature{};
size_t size = signature.size();
Require(context && EVP_DigestSignInit(context.get(), nullptr, nullptr, nullptr, key_.get()) == 1 &&
EVP_DigestSign(context.get(), signature.data(), &size,
reinterpret_cast<const uint8_t*>(text.data()), text.size()) == 1 && size == 64);
return Hex(signature.data(), signature.size());
}
std::optional<TrustedDevices::Device> TrustedDevices::Verify(
const nlohmann::json& proof, const std::string& nonce) {
try {
if (proof.at("version") != 1 || proof.at("nonce") != nonce || !IsHex(nonce, 32))
return std::nullopt;
Device device{proof.at("public_key"), proof.at("name"), proof.at("device_id")};
if (!Label(device.name) || !Label(device.device_id)) return std::nullopt;
const auto public_key = Unhex(device.public_key, 32);
const auto signature = Unhex(proof.at("signature"), 64);
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(
EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key.data(), public_key.size()),
EVP_PKEY_free);
Context context(EVP_MD_CTX_new(), EVP_MD_CTX_free);
const auto text = Transcript(nonce, device);
if (key && context && EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr, key.get()) == 1 &&
EVP_DigestVerify(context.get(), signature.data(), signature.size(),
reinterpret_cast<const uint8_t*>(text.data()), text.size()) == 1)
return device;
} catch (const std::exception&) {}
return std::nullopt;
}
bool TrustedDevices::Contains(const std::string& public_key) const {
std::lock_guard lock(mutex_);
return devices_.count(public_key) != 0;
}
std::vector<TrustedDevices::Device> TrustedDevices::List() const {
std::lock_guard lock(mutex_);
std::vector<Device> result;
for (const auto& [key, device] : devices_) result.push_back(device);
return result;
}
void TrustedDevices::Save(const std::map<std::string, Device>& devices) const {
nlohmann::json saved{{"version", 2}, {"devices", nlohmann::json::array()}};
for (const auto& [key, device] : devices)
saved["devices"].push_back({{"public_key", key}, {"name", device.name}, {"device_id", device.device_id}});
const auto text = saved.dump(2);
Require(text.size() <= 64 * 1024);
private_file::Write(path_, text);
}
void TrustedDevices::Add(const Device& device) {
Require(IsHex(device.public_key, 32) && Label(device.name) && Label(device.device_id));
std::lock_guard lock(mutex_);
const auto existing = devices_.find(device.public_key);
if (existing != devices_.end() && existing->second == device) return;
Require(existing != devices_.end() || devices_.size() < kMaxTrustedDevices);
auto next = devices_;
next[device.public_key] = device;
Save(next);
devices_.swap(next);
}
void TrustedDevices::Remove(const std::string& public_key) {
std::lock_guard lock(mutex_);
if (!devices_.contains(public_key)) return;
auto next = devices_;
next.erase(public_key);
Save(next);
devices_.swap(next);
}
} // namespace crossdesk
@@ -0,0 +1,63 @@
/*
* @Author: DI JUNKUN
* @Date: 2026-11-01
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
*/
#ifndef _TRUSTED_DEVICES_H_
#define _TRUSTED_DEVICES_H_
#include <openssl/evp.h>
#include <filesystem>
#include <map>
#include <memory>
#include <mutex>
#include <nlohmann/json.hpp>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace crossdesk {
class TrustedDevices {
public:
struct Device {
std::string public_key, name, device_id;
bool operator==(const Device&) const = default;
};
TrustedDevices(const std::filesystem::path& directory,
const std::filesystem::path& cache);
std::string Fingerprint() const;
const std::string& PublicKey() const { return public_key_; }
// Callers supply a canonical, purpose-specific transcript.
std::string Sign(std::string_view transcript) const;
static std::string Fingerprint(const std::string& public_key);
static std::string Nonce();
nlohmann::json Prove(const std::string& nonce,
const std::string& device_id, const std::string& name) const;
static std::optional<Device> Verify(const nlohmann::json& proof,
const std::string& nonce);
static constexpr size_t kMaxPairingInfoSize = 2048;
std::string PairingInfo(const std::string& device_id, const std::string& name) const;
static std::optional<Device> ParsePairingInfo(std::string_view text);
bool Contains(const std::string& public_key) const;
std::vector<Device> List() const;
// Call only after a local add action for a verified peer or valid pairing info.
void Add(const Device& device);
void Remove(const std::string& public_key);
private:
void Save(const std::map<std::string, Device>& devices) const;
std::filesystem::path path_;
std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key_{nullptr, EVP_PKEY_free};
std::string public_key_;
mutable std::mutex mutex_;
std::map<std::string, Device> devices_;
};
} // namespace crossdesk
#endif
+1
View File
@@ -89,6 +89,7 @@ export global FontAwesomeIcons {
out property <string> angle-right: "\u{f105}";
out property <string> angle-up: "\u{f106}";
out property <string> arrow-right-long: "\u{f178}";
out property <string> arrow-up: "\u{f062}";
out property <string> arrow-up-right-from-square: "\u{f35d}";
out property <string> bars: "\u{f0c9}";
out property <string> check: "\u{f00c}";
@@ -12,3 +12,7 @@ export { GalleryStrings } from "device_strings.slint";
export { LanStrings } from "lan_strings.slint";
export { GalleryNetworkDevice } from "gallery_network_dialog.slint";
export { DeviceGroupOption } from "device_group_dialog.slint";
export { TrustedDeviceEntry, TrustStrings } from "trusted_devices.slint";
export { FileBrowserWindow, BrowserEntry, BrowserTreeEntry, BrowserTask } from "file_browser.slint";
+836
View File
@@ -0,0 +1,836 @@
import { ScrollView, ListView, Spinner } from "std-widgets.slint";
import { WorkbenchStyle, WorkbenchButton, WorkbenchCard } from "workbench_controls.slint";
import { FlatSurface, UiSurface, SurfaceSeparator } from "ui_surface.slint";
import { UiRadius } from "ui_radius.slint";
import { RoundedLineEdit } from "rounded_line_edit.slint";
import { FontAwesomeIcons, ControlStyle, ImGuiFontStyle } from "common.slint";
export struct BrowserEntry {
name: string, path: string, directory: bool, selected: bool,
size: string, modified: string, link: bool,
}
export struct BrowserTreeEntry {
name: string, path: string, depth: int, expanded: bool, selected: bool,
}
export struct BrowserTask {
id: int, name: string, size: string, detail: string, status: string,
progress: float, active: bool, failed: bool, can-cancel: bool, receiving: bool,
}
component BrowserButton inherits WorkbenchButton {
mouse-cursor: default;
}
component BrowserScrollView inherits Rectangle {
// Fluent overlays a 14px scrollbar on its viewport. Keep a 4px gap between
// that track and row content, including while the scrollbar expands on hover.
out property <length> content-gutter: 18px;
horizontal-stretch: 1;
vertical-stretch: 1;
clip: true;
ScrollView {
x: 0px; y: 0px; width: root.width; height: root.height;
viewport-width: self.visible-width;
horizontal-scrollbar-policy: always-off;
@children
}
}
// Keep the visual compact while retaining a generous pointer target.
// Selection stays model-owned so refreshing rows cannot toggle it accidentally.
component BrowserCheckBox inherits Rectangle {
in property <bool> checked;
in property <bool> indeterminate;
in property <bool> enabled: true;
in property <string> label;
in property <bool> show-label: false;
private property <bool> keyboard-focus: false;
callback toggled;
width: 24px; height: 24px;
forward-focus: focus;
accessible-role: checkbox;
accessible-label: root.label;
accessible-checked: root.checked;
accessible-enabled: root.enabled;
accessible-action-default => { if root.enabled { root.toggled(); } }
box := FlatSurface {
x: 4px; y: (parent.height - self.height) / 2; width: 16px; height: 16px;
border-radius: 4px;
background: !root.enabled ? #f4f6f9
: touch.pressed ? #dce7fb
: root.checked || root.indeterminate ? (touch.has-hover ? #dfe9fc : #edf2fc)
: touch.has-hover ? #f5f8fe : white;
outline-color: !root.enabled ? #dce2eb
: touch.has-hover || touch.pressed ? #7d9edb
: root.checked || root.indeterminate ? #a6bce6 : #b7c3d4;
animate background, outline-color { duration: 100ms; }
if root.checked && !root.indeterminate: Path {
width: parent.width; height: parent.height;
viewbox-width: 16; viewbox-height: 16;
commands: "M 4 8 L 6.75 10.75 L 12 5.5";
stroke: root.enabled ? WorkbenchStyle.accent : #aab5c6;
stroke-width: 1.7px; stroke-line-cap: round; stroke-line-join: round;
}
if root.indeterminate: Rectangle {
x: 4px; y: 7px; width: 8px; height: 2px; border-radius: 1px;
background: root.enabled ? WorkbenchStyle.accent : #aab5c6;
}
}
if root.show-label: Text {
x: 30px; width: parent.width - self.x; height: parent.height;
text: root.label; color: WorkbenchStyle.text; font-size: ImGuiFontStyle.base;
vertical-alignment: center; overflow: elide; accessible-role: none;
}
if root.keyboard-focus && focus.has-focus: FlatSurface {
x: 1px; y: box.y - 3px; width: 22px; height: 22px;
border-radius: 6px; outline-color: UiSurface.focus;
}
focus := FocusScope {
enabled: root.enabled;
focus-gained(reason) => { root.keyboard-focus = reason == FocusReason.tab-navigation; }
focus-lost => { root.keyboard-focus = false; }
key-pressed(event) => {
if event.text == " " || event.text == Key.Return {
root.keyboard-focus = true; root.toggled(); return accept;
}
reject
}
touch := TouchArea {
enabled: root.enabled; mouse-cursor: default;
pointer-event(event) => {
if event.kind == PointerEventKind.down { root.keyboard-focus = false; }
}
clicked => { focus.focus(); root.keyboard-focus = false; root.toggled(); }
}
}
}
component BrowserSortHeader inherits FlatSurface {
in property <string> text;
in property <bool> chinese;
in property <bool> active;
in property <bool> descending;
in property <bool> default-descending;
in property <bool> right-aligned;
in property <bool> enabled: true;
private property <bool> keyboard-focus: false;
private property <bool> next-descending: root.active ? !root.descending : root.default-descending;
callback clicked;
height: 28px;
border-radius: UiRadius.control;
outline-enabled: focus.has-focus && root.keyboard-focus;
outline-color: UiSurface.focus;
background: touch.pressed ? ControlStyle.pressed.with-alpha(0.3)
: touch.has-hover && root.enabled ? ControlStyle.hover.with-alpha(0.2) : transparent;
forward-focus: focus;
accessible-role: button;
accessible-enabled: root.enabled;
accessible-label: root.text + (root.active ? (root.descending ? (root.chinese ? ",降序" : ", descending") : (root.chinese ? ",升序" : ", ascending")) : "")
+ (root.next-descending ? (root.chinese ? ",点击按降序排列" : ", sort descending") : (root.chinese ? ",点击按升序排列" : ", sort ascending"));
accessible-action-default => { if root.enabled { root.clicked(); } }
label := Text {
x: root.right-aligned ? parent.width - self.width - (root.active ? 14px : 0px) : 0px;
width: min(self.preferred-width, parent.width - (root.active ? 14px : 0px));
height: parent.height;
text: root.text; font-size: ImGuiFontStyle.body; font-weight: root.active ? 600 : 400;
color: root.active ? WorkbenchStyle.text : WorkbenchStyle.muted;
vertical-alignment: center; overflow: elide; accessible-role: none;
}
if root.active: Text {
x: label.x + label.width + 4px; width: 10px; height: parent.height;
text: root.descending ? FontAwesomeIcons.angle-down : FontAwesomeIcons.angle-up;
font-family: "Font Awesome 6 Free"; font-weight: 900; font-size: 10px;
color: WorkbenchStyle.muted; vertical-alignment: center; accessible-role: none;
}
focus := FocusScope {
enabled: root.enabled;
focus-gained(reason) => { root.keyboard-focus = reason == FocusReason.tab-navigation; }
focus-lost => { root.keyboard-focus = false; }
key-pressed(event) => {
if event.text == " " || event.text == Key.Return {
root.keyboard-focus = true; root.clicked(); return accept;
}
reject
}
touch := TouchArea {
enabled: root.enabled; mouse-cursor: default;
pointer-event(event) => { if event.kind == PointerEventKind.down { root.keyboard-focus = false; } }
clicked => { focus.focus(); root.keyboard-focus = false; root.clicked(); }
}
}
}
component BrowserPane inherits WorkbenchCard {
in property <bool> chinese;
in property <string> open-directory-text;
in property <string> heading;
in property <string> subtitle;
in-out property <string> path;
in property <string> current-path;
in-out property <string> filter-text;
in property <string> status;
in property <string> error;
in property <bool> busy;
in property <bool> enabled: true;
in property <bool> can-up;
in property <bool> all-selected;
in property <bool> show-hidden;
in property <int> selected-count;
in property <bool> destination;
in property <bool> transfer-ready;
in property <int> selection-revision;
in property <int> drag-count;
in property <bool> dragging;
in property <bool> drop-hover;
in property <[BrowserEntry]> entries;
in property <[BrowserTreeEntry]> tree;
in property <int> sort-column;
in property <bool> sort-descending;
private property <length> modified-column-width: 72px;
private property <length> size-column-width: 56px;
outline-color: root.destination ? UiSurface.hover : UiSurface.edge;
callback navigate(string);
callback up;
callback select-entry(int);
callback open-entry(int);
callback open-directory(string);
callback select-all;
callback tree-open(int);
callback tree-toggle(int);
callback filter(string);
callback toggle-hidden;
callback sort(int);
pure callback drag-data(string, int) -> data-transfer;
callback drag-start(data-transfer, BrowserEntry);
callback drag-move(length, length);
callback drag-end;
callback drag-cancel;
public pure function contains-drop(x: length, y: length) -> bool {
return root.enabled && root.transfer-ready
&& x >= body.absolute-position.x && x < body.absolute-position.x + body.width
&& y >= body.absolute-position.y && y < body.absolute-position.y + body.height;
}
changed enabled => { if !root.enabled { directory-popup.close(); } }
changed dragging => { if root.dragging { directory-popup.close(); } }
changed current-path => { file-list.reset-scroll(); }
changed filter-text => { file-list.reset-scroll(); }
changed sort-column => { file-list.reset-scroll(); }
changed sort-descending => { file-list.reset-scroll(); }
VerticalLayout {
padding-left: 14px; padding-right: 14px;
padding-top: 12px; padding-bottom: 12px; spacing: 6px;
HorizontalLayout {
height: 24px; spacing: 8px;
Text { text: root.heading; color: WorkbenchStyle.text; font-size: ImGuiFontStyle.prominent; font-weight: 600; vertical-alignment: center; }
Text {
horizontal-stretch: 1;
text: root.destination ? (root.chinese ? "接收目录" : "Destination")
: root.selected-count > 0 ? (root.chinese ? "已选 " + root.selected-count + " 项" : root.selected-count + " selected") : root.subtitle;
color: root.destination ? WorkbenchStyle.accent : WorkbenchStyle.muted;
font-size: ImGuiFontStyle.body; horizontal-alignment: right; vertical-alignment: center; overflow: elide;
}
RoundedLineEdit {
width: min(164px, root.width * 0.4); height: 24px;
text <=> root.filter-text; tint-opacity: 0.15;
placeholder-text: root.chinese ? "筛选名称…" : "Filter by name…";
enabled: root.enabled && !root.busy && !root.dragging;
edited => { root.filter(self.text); }
accepted => { self.clear-focus(); }
}
}
HorizontalLayout {
height: 32px; spacing: 6px;
BrowserButton {
width: 32px; height: 32px; quiet: true; icon: FontAwesomeIcons.arrow-up;
tooltip: root.chinese ? "打开上一级目录" : "Open parent folder";
tooltip-above: true; tooltip-align-left: true;
accessible-label: self.tooltip;
enabled: root.can-up && !root.busy && root.enabled && !root.dragging;
clicked => { root.up(); }
}
path-focus := FocusScope {
horizontal-stretch: 1; height: 32px;
forward-focus: path-editor;
key-pressed(event) => {
if event.text == Key.Escape {
root.path = root.current-path;
path-editor.clear-focus();
return accept;
}
reject
}
path-editor := RoundedLineEdit {
width: parent.width; height: parent.height; text <=> root.path;
tint-opacity: 0.2;
enabled: root.enabled && !root.dragging;
placeholder-text: root.chinese ? "输入路径,按回车打开" : "Enter a folder path";
accepted => { root.navigate(self.text); self.clear-focus(); }
}
}
tree-trigger := BrowserButton {
width: 28px; height: 32px; quiet: true; icon: FontAwesomeIcons.folder-open;
enabled: root.enabled && !root.dragging;
accessible-label: root.chinese ? "浏览目录树" : "Browse folder tree";
clicked => { if directory-popup.is-open { directory-popup.close(); } else { directory-popup.show(); } }
}
}
body := Rectangle {
vertical-stretch: 1;
Rectangle {
width: parent.width; height: parent.height;
VerticalLayout {
spacing: 0px;
Rectangle {
height: 28px; background: WorkbenchStyle.field-surface; border-radius: UiRadius.control;
HorizontalLayout {
padding-left: 6px; padding-right: 8px + file-list.content-gutter; spacing: 8px;
BrowserCheckBox {
width: 24px; height: 28px; checked: root.all-selected;
indeterminate: root.selected-count > 0 && !root.all-selected;
label: (root.chinese ? "选择全部" : "Select all")
+ (self.indeterminate ? (root.chinese ? ",部分已选" : ", partially selected") : "");
enabled: root.enabled && root.entries.length > 0 && !root.busy && root.error == "" && !root.dragging;
toggled => { root.select-all(); }
}
BrowserSortHeader {
horizontal-stretch: 1; text: root.chinese ? "名称" : "Name"; chinese: root.chinese;
active: root.sort-column == 0; descending: root.sort-descending;
enabled: root.enabled && !root.busy && root.error == "" && !root.dragging;
clicked => { root.sort(0); }
}
BrowserSortHeader {
width: root.modified-column-width; text: root.chinese ? "修改日期" : "Modified"; chinese: root.chinese;
active: root.sort-column == 1; descending: root.sort-descending; default-descending: true; right-aligned: true;
enabled: root.enabled && !root.busy && root.error == "" && !root.dragging;
clicked => { root.sort(1); }
}
BrowserSortHeader {
width: root.size-column-width; text: root.chinese ? "大小" : "Size"; chinese: root.chinese;
active: root.sort-column == 2; descending: root.sort-descending; default-descending: true; right-aligned: true;
enabled: root.enabled && !root.busy && root.error == "" && !root.dragging;
clicked => { root.sort(2); }
}
}
}
file-list := Rectangle {
out property <length> content-gutter: 18px;
public function reset-scroll() { visible-files.viewport-y = 0px; }
vertical-stretch: 1;
clip: true;
visible-files := ListView {
width: parent.width; height: parent.height;
viewport-width: self.visible-width;
horizontal-scrollbar-policy: always-off;
for entry[index] in root.entries: Rectangle {
x: 0px; width: file-list.width - file-list.content-gutter;
height: 28px;
border-radius: UiRadius.control;
background: entry.selected
? (row-touch.pressed ? ControlStyle.selected-pressed.with-alpha(0.4) : row-touch.has-hover ? ControlStyle.selected-hover.with-alpha(0.35) : ControlStyle.selected.with-alpha(0.3))
: row-touch.pressed ? ControlStyle.pressed.with-alpha(0.3) : row-touch.has-hover ? ControlStyle.hover.with-alpha(0.2) : transparent;
opacity: root.dragging && row-touch.drag-started ? 0.55 : 1;
folder-menu := ContextMenuArea {
enabled: entry.directory && root.enabled && !root.busy && root.error == "" && !root.dragging;
Menu {
MenuItem {
title: root.open-directory-text;
activated => { root.open-directory(entry.path); }
}
}
HorizontalLayout {
padding-left: 6px; padding-right: 8px; spacing: 8px;
Rectangle { width: 24px; }
Text { width: 17px; text: entry.directory ? FontAwesomeIcons.folder-open : FontAwesomeIcons.file-lines; font-family: "Font Awesome 6 Free"; font-weight: 900; font-size: 14px; color: entry.directory ? WorkbenchStyle.accent : ControlStyle.icon; vertical-alignment: center; }
Text { text: entry.name; color: entry.link ? WorkbenchStyle.muted : entry.selected ? ControlStyle.selected-text : WorkbenchStyle.text; font-size: ImGuiFontStyle.base; vertical-alignment: center; horizontal-stretch: 1; overflow: elide; }
Text { width: root.modified-column-width; text: entry.modified != "" ? entry.modified : "—"; color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; horizontal-alignment: right; }
Text { width: root.size-column-width; text: entry.directory ? "—" : entry.size; color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.body; vertical-alignment: center; horizontal-alignment: right; }
}
row-touch := TouchArea {
// Only the row body starts drags; checkboxes remain selection controls.
x: 34px; width: parent.width - 34px; height: parent.height;
enabled: root.enabled && !root.busy && root.error == "";
private property <bool> drag-armed;
out property <bool> drag-started;
// Keep pointer capture throughout the in-window drag, so the cursor
// remains a closed hand instead of DragArea's copy/no-drop cursor.
mouse-cursor: self.drag-started && root.dragging ? MouseCursor.grabbing : MouseCursor.default;
function update-drag-position() {
root.drag-move(self.absolute-position.x + self.mouse-x,
self.absolute-position.y + self.mouse-y);
}
pointer-event(event) => {
if event.button == PointerEventButton.left && event.kind == PointerEventKind.down {
self.drag-armed = root.transfer-ready && !entry.link;
self.drag-started = false;
} else if event.kind == PointerEventKind.cancel {
self.drag-armed = false;
if self.drag-started && root.dragging { root.drag-cancel(); }
} else if event.button == PointerEventButton.left && event.kind == PointerEventKind.up {
self.drag-armed = false;
if self.drag-started && root.dragging {
self.update-drag-position();
root.drag-end();
}
} else if event.button == PointerEventButton.right && event.kind == PointerEventKind.up && folder-menu.enabled {
folder-menu.show({ x: self.mouse-x + 34px, y: self.mouse-y });
}
}
moved => {
if self.drag-armed && !self.drag-started && root.transfer-ready
&& (abs(self.mouse-x - self.pressed-x) >= 5px || abs(self.mouse-y - self.pressed-y) >= 5px) {
self.drag-started = true;
root.drag-start(root.drag-data(entry.path, root.selection-revision), entry);
}
if self.drag-started && root.dragging { self.update-drag-position(); }
}
clicked => { if !self.drag-started { root.select-entry(index); } }
double-clicked => { if !self.drag-started { root.open-entry(index); } }
}
BrowserCheckBox { x: 6px; y: (parent.height - self.height) / 2; width: 24px; checked: entry.selected; label: (root.chinese ? "选择 " : "Select ") + entry.name; enabled: !entry.link && root.enabled && !root.busy && root.error == "" && !root.dragging; toggled => { root.select-entry(index); } }
}
}
}
}
}
}
if root.entries.length == 0 && !root.busy && root.error == "": VerticalLayout {
x: 12px; y: 34px; width: parent.width - 24px; height: parent.height - 40px;
alignment: center; spacing: 10px;
Text {
text: root.filter-text != "" ? (root.chinese ? "没有匹配的项目" : "No matching items")
: (root.chinese ? "此目录为空" : "This folder is empty");
color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.base; horizontal-alignment: center;
}
if root.filter-text != "": HorizontalLayout {
alignment: center;
BrowserButton { width: 112px; height: 28px; text-size: ImGuiFontStyle.base; text: root.chinese ? "清空筛选" : "Clear filter"; clicked => { root.filter-text = ""; root.filter(""); } }
}
}
if root.error != "" && !root.busy: Rectangle {
width: parent.width; height: parent.height; background: WorkbenchStyle.surface;
TouchArea {}
VerticalLayout {
padding: 16px; spacing: 10px; alignment: center;
Text { text: root.chinese ? "无法读取目录" : "Unable to open folder"; color: WorkbenchStyle.text; font-size: ImGuiFontStyle.base; font-weight: 600; horizontal-alignment: center; }
Text { text: root.error; color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.body; wrap: word-wrap; horizontal-alignment: center; }
HorizontalLayout {
alignment: center;
BrowserButton { width: 128px; height: 28px; text-size: ImGuiFontStyle.base; text: root.chinese ? "打开主目录" : "Open home folder"; clicked => { root.navigate(""); } }
}
}
}
if root.busy: Rectangle {
width: parent.width; height: parent.height; background: WorkbenchStyle.surface.with-alpha(0.9);
VerticalLayout { alignment: center; spacing: 12px; Spinner { width: 24px; height: 24px; } Text { text: root.status; horizontal-alignment: center; color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.base; } }
}
if root.drop-hover: FlatSurface {
width: parent.width; height: parent.height;
background: ControlStyle.selected.with-alpha(0.3); outline-color: UiSurface.focus; border-radius: UiRadius.control;
Rectangle {
x: 8px; y: max(6px, parent.height - 68px); width: parent.width - 16px; height: 60px;
background: ControlStyle.surface; border-radius: UiRadius.control;
VerticalLayout {
padding: 9px; spacing: 4px;
Text { text: root.chinese ? "松手复制 " + root.drag-count + " 项到此目录" : "Release to copy " + root.drag-count + " items here"; color: WorkbenchStyle.accent; font-size: ImGuiFontStyle.base; font-weight: 600; horizontal-alignment: center; }
Text { text: root.path; color: WorkbenchStyle.text; font-size: ImGuiFontStyle.body; overflow: elide; horizontal-alignment: center; }
}
}
}
}
Text {
height: 16px;
text: root.busy ? root.status
: root.path != root.current-path ? (root.chinese ? "Enter 打开路径 · Esc 还原" : "Enter to open · Esc to restore")
: root.error != "" ? (root.chinese ? "目录不可用" : "Folder unavailable")
: root.filter-text != "" ? (root.chinese ? "筛选结果 · " : "Filtered · ") + root.status : root.status;
color: root.path != root.current-path ? WorkbenchStyle.accent : WorkbenchStyle.muted;
font-size: ImGuiFontStyle.body; overflow: elide;
}
}
directory-popup := PopupWindow {
x: 14px; y: 78px; width: root.width - 28px; height: min(330px, max(180px, root.height - 90px));
close-policy: close-on-click-outside;
FlatSurface {
width: parent.width; height: parent.height; background: WorkbenchStyle.surface; outline-color: UiSurface.edge; border-radius: UiRadius.menu;
VerticalLayout {
padding: 12px; spacing: 10px;
HorizontalLayout {
height: 28px; spacing: 8px;
BrowserButton { text: root.chinese ? "主目录" : "Home"; quiet: true; height: 28px; clicked => { root.navigate(""); directory-popup.close(); } }
BrowserButton { text: root.chinese ? "磁盘" : "Drives"; quiet: true; height: 28px; clicked => { root.navigate("@roots"); directory-popup.close(); } }
}
tree-list := Rectangle {
out property <length> content-gutter: 18px;
vertical-stretch: 1;
clip: true;
ListView {
width: parent.width; height: parent.height;
viewport-width: self.visible-width;
horizontal-scrollbar-policy: always-off;
for node[index] in root.tree: Rectangle {
x: 0px; width: tree-list.width - tree-list.content-gutter;
height: 29px; border-radius: UiRadius.control;
background: node.selected ? ControlStyle.selected.with-alpha(0.3) : tree-touch.has-hover ? ControlStyle.hover.with-alpha(0.2) : transparent;
Text { x: 24px + min(node.depth, 8) * 12px; width: parent.width - self.x - 4px; height: parent.height; text: node.name; color: node.selected ? WorkbenchStyle.accent : WorkbenchStyle.text; font-size: ImGuiFontStyle.base; vertical-alignment: center; overflow: elide; }
tree-touch := TouchArea { clicked => { root.tree-open(index); directory-popup.close(); } }
BrowserButton { x: min(node.depth, 8) * 12px; width: 22px; height: 28px; quiet: true; icon: node.expanded ? FontAwesomeIcons.angle-down : FontAwesomeIcons.angle-right; clicked => { root.tree-toggle(index); } }
}
}
}
BrowserCheckBox { width: parent.width; show-label: true; label: root.chinese ? "显示隐藏项" : "Show hidden files"; checked: root.show-hidden; toggled => { root.toggle-hidden(); } }
}
}
}
}
export component FileBrowserWindow inherits Window {
title: root.chinese ? "文件传输" : "File transfer";
icon: @image-url("../../../resources/linux/crossdesk_256x256.png");
preferred-width: 900px; preferred-height: 620px;
min-width: 760px; min-height: 500px;
background: WorkbenchStyle.canvas;
default-font-size: ImGuiFontStyle.base;
in property <bool> chinese: true;
in property <string> send-local-text: root.chinese ? "发送到本机" : "Send to local";
in property <string> send-remote-text: root.chinese ? "发送到远端" : "Send to remote";
in property <string> clear-completed-text: root.chinese ? "清除已完成" : "Clear completed";
in property <string> open-directory-text: root.chinese ? "打开目录" : "Open folder";
in property <bool> connected: true;
in property <string> peer-name;
in property <string> local-role;
in property <string> remote-role;
in-out property <string> local-path;
in-out property <string> remote-path;
in property <string> local-current-path;
in property <string> remote-current-path;
in-out property <string> local-filter;
in-out property <string> remote-filter;
in property <string> local-status;
in property <string> remote-status;
in property <string> local-error;
in property <string> remote-error;
in property <bool> local-busy;
in property <bool> remote-busy;
in property <bool> local-up;
in property <bool> remote-up;
in property <bool> local-all;
in property <bool> remote-all;
in property <bool> local-hidden;
in property <bool> remote-hidden;
in property <int> local-sort-column;
in property <int> remote-sort-column;
in property <bool> local-sort-descending;
in property <bool> remote-sort-descending;
in property <int> local-selected;
in property <int> remote-selected;
in property <[BrowserEntry]> local-entries;
in property <[BrowserEntry]> remote-entries;
in property <[BrowserTreeEntry]> local-tree;
in property <[BrowserTreeEntry]> remote-tree;
in property <[BrowserTask]> tasks;
in property <string> task-summary;
in property <string> notice;
in property <bool> notice-error;
in property <bool> can-upload;
in property <bool> can-download;
in property <bool> source-remote;
in property <bool> transfer-ready;
in property <int> selection-revision;
in property <bool> drag-active;
in property <int> drag-count;
private property <data-transfer> drag-payload;
private property <BrowserEntry> drag-entry;
private property <length> drag-x;
private property <length> drag-y;
private property <int> drop-target: -1;
changed drag-active => { if !root.drag-active { root.drop-target = -1; } }
in-out property <bool> tasks-expanded: false;
private property <length> task-list-max-height: min(144px, max(72px, root.height - 440px));
private property <int> selected-count: root.local-selected + root.remote-selected;
private property <bool> path-pending: root.local-path != root.local-current-path || root.remote-path != root.remote-current-path;
private property <bool> notice-visible: false;
changed notice => { root.notice-visible = root.notice != ""; }
Timer {
interval: 3500ms;
running: root.notice-visible && !root.notice-error;
triggered => { root.notice-visible = false; }
}
callback navigate(bool, string);
callback refresh(bool);
callback up(bool);
callback select-entry(bool, int);
callback open-entry(bool, int);
callback open-directory(bool, string);
callback select-all(bool);
callback clear-selection;
callback tree-open(bool, int);
callback tree-toggle(bool, int);
callback filter(bool, string);
callback toggle-hidden(bool);
callback sort(bool, int);
callback transfer(bool);
callback cancel-task(int);
callback clear-finished;
pure callback drag-data(bool, string, int) -> data-transfer;
callback drag-state(data-transfer, bool);
callback can-drop(bool, data-transfer) -> bool;
callback dropped(bool, data-transfer) -> bool;
callback cancel-drag;
function start-drag(data: data-transfer, entry: BrowserEntry) {
root.drag-payload = data;
root.drag-entry = entry;
root.drop-target = -1;
root.drag-state(data, true);
}
function move-drag(x: length, y: length) {
if !root.drag-active { return; }
root.drag-x = x;
root.drag-y = y;
root.drop-target = local-pane.contains-drop(x, y) && root.can-drop(false, root.drag-payload) ? 0
: remote-pane.contains-drop(x, y) && root.can-drop(true, root.drag-payload) ? 1 : -1;
}
function finish-drag() {
if !root.drag-active { return; }
// The payload stays fixed from press-and-drag through release; C++ validates
// its source, destination, session and generation again before copying.
let data = root.drag-payload;
if root.drop-target >= 0 { root.dropped(root.drop-target == 1, data); }
root.drag-state(data, false);
}
forward-focus: focus;
SurfaceSeparator { x: 0px; y: 0px; width: parent.width; }
focus := FocusScope {
focus-on-click: true;
key-pressed(event) => {
if event.text == Key.Escape { root.cancel-drag(); return accept; }
reject
}
focus-lost => { if root.drag-active { root.cancel-drag(); } }
VerticalLayout {
spacing: 12px; padding: 16px;
HorizontalLayout {
height: 32px; spacing: 12px;
Text { text: root.chinese ? "文件传输" : "File transfer"; font-size: ImGuiFontStyle.section-title; font-weight: 600; color: WorkbenchStyle.text; vertical-alignment: center; horizontal-stretch: 1; }
Text { text: root.peer-name; color: WorkbenchStyle.muted; vertical-alignment: center; font-size: ImGuiFontStyle.base; overflow: elide; }
Rectangle {
width: root.chinese ? 104px : 144px;
BrowserButton {
y: (parent.height - self.height) / 2;
width: parent.width; height: 28px; icon: FontAwesomeIcons.rotate;
text: root.chinese ? "刷新目录" : "Refresh folders";
text-size: ImGuiFontStyle.base;
accessible-label: root.chinese ? "刷新双方目录" : "Refresh both folders";
enabled: root.connected && !root.drag-active && !root.local-busy && !root.remote-busy;
clicked => { root.refresh(false); root.refresh(true); }
}
}
}
HorizontalLayout {
vertical-stretch: 1; spacing: 12px;
local-pane := BrowserPane {
width: (parent.width - 12px) / 2;
horizontal-stretch: 1; chinese: root.chinese; heading: root.chinese ? "本机" : "Local"; subtitle: root.local-role;
path <=> root.local-path; status: root.local-status; error: root.local-error; busy: root.local-busy;
open-directory-text: root.open-directory-text;
open-directory(path) => { root.open-directory(false, path); }
current-path: root.local-current-path; filter-text <=> root.local-filter;
can-up: root.local-up; all-selected: root.local-all; entries: root.local-entries; tree: root.local-tree;
show-hidden: root.local-hidden; toggle-hidden => { root.toggle-hidden(false); }
sort-column: root.local-sort-column; sort-descending: root.local-sort-descending;
sort(column) => { root.sort(false, column); }
selected-count: root.local-selected; destination: root.remote-selected > 0;
transfer-ready: root.transfer-ready; selection-revision: root.selection-revision; dragging: root.drag-active; drag-count: root.drag-count;
drop-hover: root.drag-active && root.drop-target == 0;
navigate(path) => { root.navigate(false, path); } up => { root.up(false); }
select-entry(index) => { root.select-entry(false, index); } open-entry(index) => { root.open-entry(false, index); }
select-all => { root.select-all(false); } tree-open(index) => { root.tree-open(false, index); } tree-toggle(index) => { root.tree-toggle(false, index); }
filter(text) => { root.filter(false, text); }
drag-data(path, revision) => { return root.drag-data(false, path, revision); }
drag-start(data, entry) => { root.start-drag(data, entry); }
drag-move(x, y) => { root.move-drag(x, y); }
drag-end => { root.finish-drag(); }
drag-cancel => { root.cancel-drag(); }
}
remote-pane := BrowserPane {
width: (parent.width - 12px) / 2;
horizontal-stretch: 1; chinese: root.chinese; heading: root.chinese ? "远端" : "Remote"; subtitle: root.remote-role; enabled: root.connected;
path <=> root.remote-path; status: root.remote-status; error: root.remote-error; busy: root.remote-busy;
open-directory-text: root.open-directory-text;
open-directory(path) => { root.open-directory(true, path); }
current-path: root.remote-current-path; filter-text <=> root.remote-filter;
can-up: root.remote-up; all-selected: root.remote-all; entries: root.remote-entries; tree: root.remote-tree;
show-hidden: root.remote-hidden; toggle-hidden => { root.toggle-hidden(true); }
sort-column: root.remote-sort-column; sort-descending: root.remote-sort-descending;
sort(column) => { root.sort(true, column); }
selected-count: root.remote-selected; destination: root.local-selected > 0;
transfer-ready: root.transfer-ready; selection-revision: root.selection-revision; dragging: root.drag-active; drag-count: root.drag-count;
drop-hover: root.drag-active && root.drop-target == 1;
navigate(path) => { root.navigate(true, path); } up => { root.up(true); }
select-entry(index) => { root.select-entry(true, index); } open-entry(index) => { root.open-entry(true, index); }
select-all => { root.select-all(true); } tree-open(index) => { root.tree-open(true, index); } tree-toggle(index) => { root.tree-toggle(true, index); }
filter(text) => { root.filter(true, text); }
drag-data(path, revision) => { return root.drag-data(true, path, revision); }
drag-start(data, entry) => { root.start-drag(data, entry); }
drag-move(x, y) => { root.move-drag(x, y); }
drag-end => { root.finish-drag(); }
drag-cancel => { root.cancel-drag(); }
}
}
WorkbenchCard {
height: 83px + task-content.height;
VerticalLayout {
spacing: 0px; padding: 1px;
HorizontalLayout {
height: 48px; padding-left: 12px; padding-right: 12px; spacing: 12px;
VerticalLayout {
alignment: center; spacing: 3px; horizontal-stretch: 1;
Text {
text: root.path-pending ? (root.chinese ? "按 Enter 打开路径" : "Press Enter to open the path")
: root.drag-active ? (root.chinese ? "松手复制 · Esc 取消" : "Release to copy · Esc to cancel")
: root.notice-error ? root.notice
: root.selected-count > 0 ? (root.chinese ? "已选 " + root.selected-count + " 项 · " + (root.source-remote ? "远端 → 本机" : "本机 → 远端")
: (root.source-remote ? "Remote → Local" : "Local → Remote") + " · " + root.selected-count + " selected")
: root.notice-visible ? root.notice
: (root.chinese ? "选择文件,或拖到另一侧" : "Select files or drag to the other side");
color: root.notice-error && !root.drag-active && !root.path-pending ? UiSurface.error
: root.selected-count > 0 ? WorkbenchStyle.text : WorkbenchStyle.muted;
font-size: ImGuiFontStyle.base; font-weight: 400; overflow: elide;
}
if root.selected-count > 0 && !root.path-pending && !root.drag-active && !root.notice-error: Text {
text: (root.chinese ? "目标:" : "To: ") + (root.source-remote ? root.local-current-path : root.remote-current-path);
color: WorkbenchStyle.muted;
font-size: ImGuiFontStyle.body; overflow: elide;
}
}
if root.selected-count > 0: Rectangle {
width: root.chinese ? 76px : 100px;
BrowserButton {
y: (parent.height - self.height) / 2; width: parent.width; height: 28px; quiet: true;
text-size: ImGuiFontStyle.base; text: root.chinese ? "取消选择" : "Clear selection";
enabled: !root.drag-active; clicked => { root.clear-selection(); }
}
}
Rectangle {
width: max(root.chinese ? 148px : 160px, send-label-measure.preferred-width + 32px);
send-label-measure := Text {
visible: false;
text: root.source-remote ? root.send-local-text : root.send-remote-text;
font-size: ImGuiFontStyle.base; font-weight: 600;
}
BrowserButton {
y: (parent.height - self.height) / 2; width: parent.width; height: 32px; primary: true;
text-size: ImGuiFontStyle.base;
enabled: !root.drag-active && (root.source-remote ? root.can-download : root.can-upload);
text: send-label-measure.text;
clicked => { root.transfer(root.source-remote); }
}
}
}
Rectangle { height: 1px; SurfaceSeparator { x: 12px; y: 0px; width: parent.width - 24px; } }
Rectangle {
height: 32px;
HorizontalLayout {
padding-left: 10px; padding-right: 10px; spacing: 8px;
Rectangle {
horizontal-stretch: 1;
BrowserButton { x: 0px; width: min(parent.width, task-label.preferred-width + 46px); height: 32px; quiet: true; accessible-label: task-label.text; clicked => { root.tasks-expanded = !root.tasks-expanded; } }
Text { x: 8px; width: 14px; height: parent.height; font-family: "Font Awesome 6 Free"; font-weight: 900; font-size: ImGuiFontStyle.base; color: ControlStyle.icon; vertical-alignment: center; text: root.tasks-expanded ? FontAwesomeIcons.angle-down : FontAwesomeIcons.angle-right; }
task-label := Text { x: 30px; width: parent.width - 40px; height: parent.height; font-size: ImGuiFontStyle.base; color: WorkbenchStyle.muted; vertical-alignment: center; overflow: elide; text: (root.chinese ? "传输任务" : "Transfers") + " · " + (root.tasks.length == 0 ? (root.chinese ? "暂无任务" : "No tasks") : root.task-summary != "" ? root.task-summary : root.tasks.length); }
}
if root.tasks-expanded: Rectangle {
width: max(100px, clear-label-measure.preferred-width + 24px);
clear-label-measure := Text {
visible: false; text: root.clear-completed-text;
font-size: ImGuiFontStyle.body; font-weight: 500;
}
BrowserButton { y: (parent.height - self.height) / 2; width: parent.width; height: 28px; quiet: true; text-size: ImGuiFontStyle.body; text: root.clear-completed-text; clicked => { root.clear-finished(); } }
}
}
}
task-content := Rectangle {
height: root.tasks-expanded ? min(root.task-list-max-height, root.tasks.length == 0 ? 40px : task-rows.preferred-height) : 0px;
visible: root.tasks-expanded;
clip: true;
SurfaceSeparator { x: 12px; y: 0px; width: parent.width - 24px; }
if root.tasks.length == 0: Text { text: root.chinese ? "暂无传输任务" : "No transfers yet"; color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.base; horizontal-alignment: center; vertical-alignment: center; }
task-list := BrowserScrollView {
x: 16px; width: parent.width - 32px; height: parent.height;
visible: root.tasks.length > 0;
task-rows := VerticalLayout {
spacing: 2px; padding-top: 4px; padding-bottom: 4px; padding-right: task-list.content-gutter;
for task in root.tasks: Rectangle {
height: task.active ? 46px : 32px;
HorizontalLayout {
spacing: 12px;
Text { width: 18px; text: task.receiving ? "↓" : "↑"; color: WorkbenchStyle.accent; font-size: 16px; vertical-alignment: center; }
VerticalLayout {
padding-top: 5px; padding-bottom: 5px; spacing: 3px; alignment: center; horizontal-stretch: 1;
Rectangle {
height: 16px;
task-name := Text {
x: 0px;
width: min(self.preferred-width, max(0px, parent.width - task-size.preferred-width - 8px));
height: parent.height; text: task.name; color: WorkbenchStyle.text;
font-size: ImGuiFontStyle.base; overflow: elide; vertical-alignment: center;
}
task-size := Text {
x: task-name.width + 8px; width: self.preferred-width; height: parent.height;
text: task.size; color: WorkbenchStyle.muted;
font-size: ImGuiFontStyle.body; vertical-alignment: center;
}
}
if task.active: Text { text: task.detail; color: WorkbenchStyle.muted; font-size: ImGuiFontStyle.body; overflow: elide; }
}
Rectangle { width: root.width < 820px ? 80px : 110px; Rectangle { x: 0px; y: (parent.height - 4px) / 2; width: parent.width; height: 4px; background: WorkbenchStyle.separator; border-radius: 2px; Rectangle { x: 0px; y: 0px; width: parent.width * task.progress; height: 4px; border-radius: 2px; background: task.failed ? UiSurface.error : WorkbenchStyle.accent; } } }
Text { width: root.width < 820px ? 92px : 110px; text: task.status; color: task.failed ? UiSurface.error : WorkbenchStyle.muted; font-size: ImGuiFontStyle.body; vertical-alignment: center; horizontal-alignment: right; }
Rectangle { width: 56px; if task.can-cancel: BrowserButton { y: (parent.height - self.height) / 2; width: 56px; height: 26px; text: root.chinese ? "取消" : "Cancel"; text-size: ImGuiFontStyle.body; quiet: true; clicked => { root.cancel-task(task.id); } } }
}
}
}
}
}
}
}
}
}
// Visual only: pointer capture and drop validation stay with the source row.
if root.drag-active: FlatSurface {
private property <bool> label-on-left: root.drag-x - 12px + self.width > root.width - 8px;
z: 100;
width: min(300px, max(112px, drag-label.preferred-width + 54px + drag-badge.width));
height: 40px;
// Keep the icon's top-left corner at the pointer when the label flips at the right edge.
x: root.drag-x - drag-icon.x;
y: root.drag-y - drag-icon.y;
border-radius: UiRadius.control;
background: WorkbenchStyle.surface;
outline-color: root.drop-target >= 0 ? WorkbenchStyle.accent : UiSurface.hover;
opacity: 0.94;
drag-icon := Text {
x: parent.label-on-left ? parent.width - 30px : 12px;
y: (parent.height - self.height) / 2; width: 18px; height: 18px;
text: root.drag-entry.directory ? FontAwesomeIcons.folder-open : FontAwesomeIcons.file-lines;
font-family: "Font Awesome 6 Free"; font-weight: 900; font-size: 17px;
color: root.drag-entry.directory ? WorkbenchStyle.accent : ControlStyle.icon;
horizontal-alignment: left; vertical-alignment: top;
}
drag-label := Text {
x: parent.label-on-left ? 12px : 40px;
width: parent.width - 54px - drag-badge.width; height: parent.height;
text: root.drag-entry.name; color: WorkbenchStyle.text;
font-size: ImGuiFontStyle.base; font-weight: 500;
vertical-alignment: center; overflow: elide;
}
drag-badge := Rectangle {
visible: root.drag-count > 1;
x: parent.width - self.width - (parent.label-on-left ? 38px : 10px); y: 10px;
width: root.drag-count > 1 ? max(24px, count-label.preferred-width + 12px) : 0px;
height: 20px; border-radius: 10px; background: WorkbenchStyle.accent;
count-label := Text {
width: parent.width; height: parent.height; text: root.drag-count;
color: white; font-size: ImGuiFontStyle.body; font-weight: 600;
horizontal-alignment: center; vertical-alignment: center;
}
}
}
}
+54 -10
View File
@@ -1,4 +1,5 @@
import { SurfaceSeparator, FlatSurface, UiSurface } from "ui_surface.slint";
import { TrustedDevicesDialog, TrustedDeviceEntry, TrustStrings } from "trusted_devices.slint";
import { LanStrings } from "lan_strings.slint";
import { AboutPanel, AboutPage, AboutComponent, AboutStrings, AboutNavigationRow, AboutNavigationGroup, AboutRowSeparator } from "about_panel.slint";
import { UiRadius } from "ui_radius.slint";
@@ -93,7 +94,7 @@ export global UiStrings {
in-out property <string> license: "Licensed under GNU GPL v3.";
in-out property <string> signal-connected: "Signal server connected";
in-out property <string> signal-disconnected: "Signal server disconnected";
in-out property <string> tls-error: "Signal server TLS certificate error";
in-out property <string> tls-error: "Server certificate invalid or expired. Retrying automatically.";
in-out property <string> signal-reconnect: "Reconnect";
in-out property <string> signal-reconnecting: "Reconnecting...";
in-out property <string> update-available: "A new version is available";
@@ -107,6 +108,7 @@ export global UiStrings {
in-out property <string> later: "Later";
in-out property <string> download: "Download";
in-out property <string> install-update: "Install update";
in-out property <string> retry-update: "Retry update";
in-out property <string> install-update-confirm;
in-out property <string> input-password: "Input password";
in-out property <string> reinput-password: "Incorrect password, please try again";
@@ -592,6 +594,7 @@ export component MainWindow inherits Window {
in property <bool> update-available: false;
in property <bool> update-install-available: false;
in property <bool> update-install-busy: false;
in property <bool> update-install-failed: false;
changed update-install-available => {
if !root.update-install-available { root.update-confirm-open = false; }
}
@@ -599,7 +602,8 @@ export component MainWindow inherits Window {
if root.update-install-busy { root.update-confirm-open = false; }
}
in property <string> update-install-status: "";
private property <string> update-action-text: root.update-install-available ? UiStrings.install-update : UiStrings.download;
private property <string> update-action-text: !root.update-install-available ? UiStrings.download
: root.update-install-failed && !root.update-install-busy ? UiStrings.retry-update : UiStrings.install-update;
in property <UpdateCheckStatus> update-check-status: idle;
private property <string> update-status-text:
root.update-check-status == UpdateCheckStatus.checking ? UiStrings.checking-for-updates :
@@ -660,6 +664,17 @@ export component MainWindow inherits Window {
in-out property <bool> privacy-local-unlock-allowed: true;
in property <bool> lock-on-disconnect-available: false;
in-out property <bool> lock-on-disconnect-enabled: true;
in-out property <bool> trusted-devices-only: false;
in-out property <bool> trusted-devices-open: false;
in property <[TrustedDeviceEntry]> trusted-devices;
in property <[TrustedDeviceEntry]> trust-candidates;
in property <string> device-fingerprint;
in property <string> trusted-devices-error;
in property <string> trusted-devices-notice;
in property <string> trust-copy-error;
in property <string> trust-copy-notice;
in-out property <string> trust-pairing-input;
callback trust-action(string, string, string);
in-out property <string> file-save-path: "";
in-out property <string> server-host: "";
in-out property <string> server-port: "";
@@ -683,6 +698,7 @@ export component MainWindow inherits Window {
callback cancel-self-hosted-settings;
callback browse-save-path;
callback open-download;
callback open-manual-download;
callback confirm-update;
callback cancel-update;
callback open-website;
@@ -1087,7 +1103,7 @@ export component MainWindow inherits Window {
if event.text == Key.Escape { root.messages-open = false; }
return accept;
}
if root.settings-open && !root.self-host-settings-open {
if root.settings-open && !root.self-host-settings-open && !root.trusted-devices-open {
if event.text == Key.Escape { root.cancel-settings(); root.settings-open = false; }
return accept;
}
@@ -1923,7 +1939,7 @@ export component MainWindow inherits Window {
text: root.current-version;
font-size: 11px; color: WorkbenchStyle.muted; vertical-alignment: center;
}
if !root.lan-mode && !root.signal-connected && !root.signal-tls-error: WorkbenchButton {
if !root.lan-mode && !root.signal-connected: WorkbenchButton {
x: parent.width - self.width - 20px;
y: (parent.height - self.height) / 2;
width: max(64px, reconnect-label-metrics.preferred-width + 22px);
@@ -2753,15 +2769,21 @@ export component MainWindow inherits Window {
}
}
}
Text {
text: GalleryStrings.texts[119] + "\n" + GalleryStrings.texts[207];
font-size: 11px; color: WorkbenchStyle.muted; wrap: word-wrap;
}
SettingsGroup {
title: GalleryStrings.texts[120]; rows: 3;
title: GalleryStrings.texts[120]; rows: 5;
SettingsToggleRow { label: UiStrings.privacy-on-connect; checked <=> root.privacy-on-connect-enabled; enabled: root.privacy-setting-available; }
SettingsToggleRow { label: UiStrings.privacy-local-unlock; checked <=> root.privacy-local-unlock-allowed; enabled: root.privacy-setting-available; }
SettingsToggleRow { label: UiStrings.lock-on-disconnect; checked <=> root.lock-on-disconnect-enabled; enabled: root.lock-on-disconnect-available; divider: false; }
SettingsToggleRow { label: UiStrings.lock-on-disconnect; checked <=> root.lock-on-disconnect-enabled; enabled: root.lock-on-disconnect-available; }
SettingsToggleRow { label: TrustStrings.only; checked <=> root.trusted-devices-only; }
SettingsRow {
label: TrustStrings.title; divider: false;
SettingsButton {
x: parent.width - self.width - 12px; y: 4px;
width: max(104px, self.label-width); height: 28px;
text: TrustStrings.manage;
clicked => { root.trusted-devices-open = true; root.trust-action("open", "", ""); }
}
}
}
Text {
text: GalleryStrings.texts[121];
@@ -2871,6 +2893,20 @@ export component MainWindow inherits Window {
}
}
if root.trusted-devices-open: TrustedDevicesDialog {
z: 51;
devices: root.trusted-devices;
candidates: root.trust-candidates;
local-fingerprint: root.device-fingerprint;
error: root.trusted-devices-error;
notice: root.trusted-devices-notice;
copy-error: root.trust-copy-error;
copy-notice: root.trust-copy-notice;
pairing-input <=> root.trust-pairing-input;
close => { root.trust-action("close", "", ""); root.trusted-devices-open = false; }
action(action, id, key) => { root.trust-action(action, id, key); }
}
if root.self-host-settings-open: Rectangle {
background: #15223835;
z: 49;
@@ -3268,6 +3304,14 @@ export component MainWindow inherits Window {
text: UiStrings.later;
clicked => { root.cancel-update(); root.update-open = false; }
}
if root.update-install-failed && root.update-install-available: WorkbenchButton {
width: max(110px, manual-download-metrics.preferred-width + 24px);
height: 34px;
enabled: !root.update-install-busy;
text: UiStrings.download;
clicked => { root.open-manual-download(); }
manual-download-metrics := Text { visible: false; text: UiStrings.download; font-size: 12px; }
}
WorkbenchButton {
width: max(110px, update-action-metrics.preferred-width + 24px);
height: 34px;
@@ -12,6 +12,7 @@ export component RoundedLineEdit inherits Rectangle {
in property <bool> enabled: true;
in property <length> font-size: 12px;
in property <color> normal-outline-color: UiSurface.edge;
in property <float> tint-opacity: 1;
in property <brush> surrounding-background: white;
callback accepted();
callback edited();
@@ -36,6 +37,7 @@ export component RoundedLineEdit inherits Rectangle {
// A visual-only tint preserves the standard editor and its built-in actions.
Rectangle {
width: parent.width; height: parent.height;
opacity: root.tint-opacity;
background: !root.enabled ? transparent
: editor.has-focus ? ControlStyle.input-focus-tint : ControlStyle.input-tint;
}
@@ -6,11 +6,13 @@ import { WorkbenchStyle } from "workbench_controls.slint";
// Shared visual treatment for the global settings pages.
export component SettingsButton inherits FlatSurface {
in property <string> text;
in property <length> text-size: 12px;
in property <image> icon;
in property <bool> primary: false;
in property <bool> quiet: false;
in property <bool> align-left: false;
in property <bool> enabled: true;
in property <bool> destructive: false;
out property <length> label-width: button-label.preferred-width + 2 * root.content-padding + (root.has-icon ? 24px : 0px);
private property <bool> has-icon: root.icon.width > 0;
private property <length> content-padding: root.has-icon ? 8px : 12px;
@@ -18,7 +20,8 @@ export component SettingsButton inherits FlatSurface {
width: 88px; height: 32px; border-radius: UiRadius.control;
background: !root.enabled ? ControlStyle.disabled
: root.primary ? (touch.pressed ? #1e4fa3 : touch.has-hover ? #2866c9 : #3275dc)
: touch.pressed ? ButtonStyle.pressed : touch.has-hover ? ButtonStyle.hover
: touch.pressed ? (root.destructive ? #f6babb : ButtonStyle.pressed)
: touch.has-hover ? (root.destructive ? #fbe0e0 : ButtonStyle.hover)
: root.quiet ? transparent : ButtonStyle.surface;
outline-enabled: !root.quiet && !root.primary;
outline-color: !root.enabled ? ButtonStyle.disabled-border
@@ -44,8 +47,9 @@ export component SettingsButton inherits FlatSurface {
button-label := Text {
x: root.has-icon ? 24px : 0px;
width: parent.width - self.x; height: parent.height;
text: root.text; font-size: 12px; font-weight: root.primary ? 600 : 400;
color: !root.enabled ? #98a2b3 : root.primary ? white : root.quiet ? #65758b : #3c4d63;
text: root.text; font-size: root.text-size; font-weight: root.primary ? 600 : 400;
color: !root.enabled ? #98a2b3 : root.primary ? white
: root.destructive ? #c43c43 : root.quiet ? #65758b : #3c4d63;
horizontal-alignment: root.align-left ? left : center; vertical-alignment: center; overflow: elide;
}
}
@@ -0,0 +1,264 @@
import { SettingsDialog, SettingsButton } from "settings_controls.slint";
import { WorkbenchStyle } from "workbench_controls.slint";
import { ScrollView } from "std-widgets.slint";
import { FlatSurface, UiSurface } from "ui_surface.slint";
import { UiRadius } from "ui_radius.slint";
import { RoundedLineEdit } from "rounded_line_edit.slint";
export struct TrustedDeviceEntry {
remote-id: string,
public-key: string,
display-name: string,
device-id: string,
fingerprint: string,
}
export global TrustStrings {
in property <string> title: "Trusted devices";
in property <string> only: "Only allow trusted devices";
in property <string> manage: "Manage";
in property <string> copy: "Copy pairing info";
in property <string> import-title: "Add a trusted device";
in property <string> add: "Add";
in property <string> placeholder: "Paste the controller's pairing information";
in property <string> confirm: "Check the fingerprint on the controller.";
in property <string> empty: "No trusted devices";
in property <string> candidates: "Connected devices available to trust";
in property <string> trust: "Trust";
in property <string> remove: "Remove";
in property <string> saved: "Trusted devices";
in property <string> sharing: "This device’s pairing info";
in property <string> show-fingerprint: "View fingerprint";
in property <string> hide-fingerprint: "Hide fingerprint";
in property <string> close: "Close";
}
component FingerprintBlock inherits Rectangle {
in property <string> fingerprint;
background: #f0f4fa; border-radius: UiRadius.control;
height: content.preferred-height;
content := VerticalLayout {
width: parent.width; height: self.preferred-height;
padding: 10px;
Text { text: root.fingerprint; color: #465a76; font-size: 11px; wrap: word-wrap; }
}
}
component DeviceRow inherits FlatSurface {
in property <TrustedDeviceEntry> device;
in property <string> action-text;
in property <bool> confirming: false;
private property <bool> fingerprint-open: false;
callback action;
height: content.preferred-height;
background: white; outline-color: UiSurface.edge;
border-radius: UiRadius.control;
content := VerticalLayout {
width: parent.width; height: self.preferred-height;
padding: 12px; spacing: 8px;
padding-top: root.confirming ? 12px : 8px;
padding-bottom: root.confirming ? 12px : 8px;
HorizontalLayout {
spacing: 6px;
VerticalLayout {
spacing: 2px; horizontal-stretch: 1; min-width: 0px;
Text {
text: root.device.display-name;
font-size: root.confirming ? 13px : 12px; font-weight: root.confirming ? 600 : 500;
color: WorkbenchStyle.text; overflow: elide;
}
Text {
text: "ID: " + (root.device.device-id == "" ? "—" : root.device.device-id);
font-size: 11px; color: WorkbenchStyle.muted; overflow: elide;
}
}
if !root.confirming: SettingsButton {
width: min(144px, self.label-width); height: 28px; quiet: true;
text-size: 11px;
text: root.fingerprint-open ? TrustStrings.hide-fingerprint : TrustStrings.show-fingerprint;
clicked => { root.fingerprint-open = !root.fingerprint-open; }
}
if !root.confirming: SettingsButton {
width: min(128px, max(64px, self.label-width)); height: 28px;
text-size: 11px;
quiet: true; text: root.action-text;
destructive: true;
clicked => { root.action(); }
}
}
if root.confirming || root.fingerprint-open: FingerprintBlock {
fingerprint: root.device.fingerprint;
}
if root.confirming: HorizontalLayout {
spacing: 12px;
Text {
text: TrustStrings.confirm; font-size: 11px;
color: WorkbenchStyle.muted; wrap: word-wrap;
horizontal-stretch: 1; min-width: 0px; vertical-alignment: center;
}
SettingsButton {
width: min(parent.width * 0.6, max(112px, self.label-width)); height: 30px;
primary: true; text: root.action-text;
clicked => { root.action(); }
}
}
}
}
export component TrustedDevicesDialog inherits Rectangle {
in property <[TrustedDeviceEntry]> devices;
in property <[TrustedDeviceEntry]> candidates;
in property <string> local-fingerprint;
in property <string> error;
in property <string> notice;
in property <string> copy-error;
in property <string> copy-notice;
in-out property <string> pairing-input;
private property <bool> local-fingerprint-open: false;
callback close;
callback action(string, string, string);
background: #15223835;
TouchArea { }
forward-focus: focus;
focus := FocusScope {
key-pressed(event) => {
if event.text == Key.Escape { root.close(); return accept; }
return reject;
}
}
dialog := SettingsDialog {
// Reserve the full 14px Fluent scrollbar plus an 8px content gap.
private property <length> scrollbar-gutter: 22px;
x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2;
width: min(540px, parent.width - 32px);
height: min(400px, parent.height - 32px);
min-width: 0px; max-width: parent.width - 32px;
min-height: 0px; max-height: parent.height - 32px;
title: TrustStrings.title; close-label: TrustStrings.close;
close => { root.close(); }
ScrollView {
x: 24px; y: 64px;
// Extend into the right margin to preserve the existing card width.
width: parent.width - 56px + dialog.scrollbar-gutter;
height: parent.height - 84px;
min-width: 0px; min-height: 0px;
horizontal-scrollbar-policy: always-off;
vertical-scrollbar-policy: as-needed;
viewport-width: self.visible-width;
viewport-height: content.preferred-height;
content := VerticalLayout {
x: 0px; y: 0px;
width: max(0px, parent.visible-width - dialog.scrollbar-gutter); height: self.preferred-height;
spacing: 16px; padding: 0px; alignment: start;
FlatSurface {
background: #f1f6ff; outline-color: #d7e3f7; border-radius: UiRadius.surface;
height: add-content.preferred-height;
add-content := VerticalLayout {
width: parent.width; height: self.preferred-height; padding: 14px; spacing: 10px;
Text {
text: TrustStrings.import-title; font-size: 14px; font-weight: 600;
color: WorkbenchStyle.text; min-width: 0px; wrap: word-wrap;
}
HorizontalLayout {
spacing: 8px;
RoundedLineEdit {
horizontal-stretch: 1; height: 32px; text <=> root.pairing-input;
placeholder-text: TrustStrings.placeholder; surrounding-background: #f1f6ff;
edited => { root.action("edit", "", ""); }
accepted => { root.action("import", "", ""); }
}
SettingsButton {
width: max(64px, self.label-width); height: 32px; primary: true;
text: TrustStrings.add; enabled: root.pairing-input != "" && root.local-fingerprint != "";
clicked => { root.action("import", "", ""); }
}
}
if root.error != "": Text {
text: root.error; color: #b33c39; font-size: 11px; wrap: word-wrap;
}
if root.notice != "": Text {
text: root.notice; color: #28734a; font-size: 11px; wrap: word-wrap;
}
}
}
VerticalLayout {
spacing: 6px;
Rectangle {
// Align mixed font sizes by their baselines rather than their top edges.
private property <length> baseline: max(saved-title.font-metrics.ascent, saved-count.font-metrics.ascent);
height: max(saved-title.y + saved-title.preferred-height, saved-count.y + saved-count.preferred-height);
saved-title := Text {
x: 0px; width: self.preferred-width; height: self.preferred-height;
y: parent.baseline - self.font-metrics.ascent;
text: TrustStrings.saved; font-size: 13px; font-weight: 600; color: WorkbenchStyle.text;
}
saved-count := Text {
x: saved-title.preferred-width + 6px;
width: self.preferred-width; height: self.preferred-height;
y: parent.baseline - self.font-metrics.ascent;
text: "" + root.devices.length; font-size: 12px; color: WorkbenchStyle.muted;
}
}
if root.devices.length == 0: FlatSurface {
height: 48px; background: white;
outline-color: UiSurface.edge; border-radius: UiRadius.control;
Text {
x: 14px; width: parent.width - 28px; height: parent.height;
text: TrustStrings.empty; font-size: 12px; color: WorkbenchStyle.muted;
horizontal-alignment: center; vertical-alignment: center; wrap: word-wrap;
}
}
for device in root.devices: DeviceRow {
device: device; action-text: TrustStrings.remove;
action => { root.action("remove", device.remote-id, device.public-key); }
}
}
if root.candidates.length > 0: VerticalLayout {
spacing: 8px;
Text { text: TrustStrings.candidates; font-size: 13px; font-weight: 600; color: WorkbenchStyle.text; wrap: word-wrap; }
for device in root.candidates: DeviceRow {
device: device; confirming: true; action-text: TrustStrings.trust;
action => { root.action("add", device.remote-id, device.public-key); }
}
}
FlatSurface {
height: sharing-content.preferred-height; background: white;
outline-color: UiSurface.edge; border-radius: UiRadius.control;
sharing-content := VerticalLayout {
width: parent.width; height: self.preferred-height; padding: 14px; spacing: 8px;
HorizontalLayout {
spacing: 12px;
Text {
horizontal-stretch: 1; min-width: 0px;
text: TrustStrings.sharing; font-size: 13px; font-weight: 600;
color: WorkbenchStyle.text; wrap: word-wrap; vertical-alignment: center;
}
SettingsButton {
width: min(160px, self.label-width); height: 30px; text: TrustStrings.copy;
enabled: root.local-fingerprint != ""; clicked => { root.action("copy", "", ""); }
}
}
HorizontalLayout {
spacing: 8px;
SettingsButton {
width: self.label-width; height: 22px; quiet: true; align-left: true;
text: root.local-fingerprint-open ? TrustStrings.hide-fingerprint : TrustStrings.show-fingerprint;
enabled: root.local-fingerprint != "";
clicked => { root.local-fingerprint-open = !root.local-fingerprint-open; }
}
Text {
text: root.copy-error != "" ? root.copy-error : root.copy-notice;
color: root.copy-error != "" ? #b33c39 : #28734a; font-size: 11px;
horizontal-stretch: 1; min-width: 0px; wrap: word-wrap;
horizontal-alignment: right; vertical-alignment: center;
}
}
if root.local-fingerprint-open: FingerprintBlock {
fingerprint: root.local-fingerprint;
}
}
}
}
}
}
}
+19
View File
@@ -55,6 +55,24 @@ inline int ApplyMainWindowStrings(
languages.push_back(Text(option.display_name));
languages.push_back(Text(localization::Literal("跟随系统", language)));
window->set_language_options(std::make_shared<slint::VectorModel<slint::SharedString>>(languages));
auto& trust = window->global<ui::TrustStrings>();
trust.set_title(Text(localization::Literal("可信设备", language)));
trust.set_only(Text(localization::Literal("仅允许可信设备控制", language)));
trust.set_manage(Text(localization::Literal("管理可信设备", language)));
trust.set_copy(Text(localization::Literal("复制配对信息", language)));
trust.set_import_title(Text(localization::Literal("添加可信设备", language)));
trust.set_add(Text(localization::Literal("添加", language)));
trust.set_placeholder(Text(localization::Literal("粘贴控制端的配对信息", language)));
trust.set_confirm(Text(localization::Literal("请核对控制端指纹。", language)));
trust.set_saved(Text(localization::Literal("已信任的设备", language)));
trust.set_sharing(Text(localization::Literal("本机配对信息", language)));
trust.set_show_fingerprint(Text(localization::Literal("查看指纹", language)));
trust.set_hide_fingerprint(Text(localization::Literal("收起指纹", language)));
trust.set_empty(Text(localization::Literal("暂无可信设备", language)));
trust.set_candidates(Text(localization::Literal("可添加的已连接设备", language)));
trust.set_trust(Text(localization::Literal("信任此设备", language)));
trust.set_remove(Text(localization::Literal("移除信任", language)));
trust.set_close(Text(localization::message_close[language]));
auto& strings = window->global<ui::UiStrings>();
strings.set_window_minimize(Text(localization::window_minimize[language]));
strings.set_window_close(Text(localization::window_close[language]));
@@ -151,6 +169,7 @@ inline int ApplyMainWindowStrings(
strings.set_view_release_notes(Text(localization::view_release_notes[language]));
strings.set_download(Text(localization::manual_download[language]));
strings.set_install_update(Text(localization::install_update[language]));
strings.set_retry_update(Text(localization::retry_update[language]));
strings.set_install_update_confirm(
Text(localization::install_update_confirm[language]));
strings.set_input_password(Text(localization::input_password[language]));
@@ -24,6 +24,7 @@ export component WorkbenchButton inherits FlatSurface {
in property <string> icon;
in property <string> tooltip;
in property <bool> tooltip-above: false;
in property <bool> tooltip-align-left: false;
in property <bool> tooltip-suppressed: false;
in property <color> icon-color: root.destructive ? white : root.primary
? (root.soft && !touch.has-hover && !root.show-focus ? WorkbenchStyle.accent : white)
@@ -33,6 +34,7 @@ export component WorkbenchButton inherits FlatSurface {
in property <bool> soft: false;
in property <bool> quiet: false;
in property <bool> enabled: true;
in property <MouseCursor> mouse-cursor: pointer;
out property <bool> has-focus: button-focus.has-focus;
private property <bool> keyboard-focus: false;
private property <bool> show-focus: button-focus.has-focus && root.keyboard-focus;
@@ -99,15 +101,12 @@ export component WorkbenchButton inherits FlatSurface {
button-focus := FocusScope {
enabled: root.enabled;
focus-gained(reason) => {
if reason == FocusReason.tab-navigation {
root.keyboard-focus = true;
} else if reason == FocusReason.pointer-click {
root.keyboard-focus = false;
}
root.keyboard-focus = reason == FocusReason.tab-navigation;
}
focus-lost => { root.keyboard-focus = false; }
key-pressed(event) => {
root.keyboard-focus = true;
if event.text == Key.Return || event.text == " " {
root.keyboard-focus = true;
root.clicked();
return accept;
}
@@ -115,7 +114,7 @@ export component WorkbenchButton inherits FlatSurface {
}
touch := TouchArea {
enabled: root.enabled;
mouse-cursor: pointer;
mouse-cursor: root.mouse-cursor;
pointer-event(event) => {
if event.kind == PointerEventKind.down {
root.keyboard-focus = false;
@@ -123,7 +122,7 @@ export component WorkbenchButton inherits FlatSurface {
}
// Keep focus for subsequent keyboard activation without leaving a
// keyboard focus ring behind after a pointer click.
clicked => { root.keyboard-focus = false; button-focus.focus(); root.clicked(); }
clicked => { button-focus.focus(); root.keyboard-focus = false; root.clicked(); }
}
}
tooltip-timer := Timer {
@@ -132,7 +131,7 @@ export component WorkbenchButton inherits FlatSurface {
triggered => { root.tooltip-visible = true; }
}
if root.tooltip-active && root.tooltip-visible: Rectangle {
x: min(0px, root.width - self.width);
x: root.tooltip-align-left ? 0px : min(0px, root.width - self.width);
y: root.tooltip-above ? -self.height - 6px : root.height + 6px;
width: min(260px, tip.preferred-width + 20px);
height: max(28px, tip.preferred-height + 12px);
+9 -183
View File
@@ -1,4 +1,5 @@
#include "lan_identity.h"
#include "private_file.h"
#include <openssl/crypto.h>
#include <openssl/pem.h>
@@ -8,7 +9,6 @@
#include <algorithm>
#include <array>
#include <charconv>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <string_view>
@@ -16,23 +16,18 @@
#include "direct_address.h"
#include "lan_password.h"
#ifdef _WIN32
// Winsock must precede windows.h; the networking/ACL headers need its types.
// Winsock must precede windows.h; the networking headers need its types.
// clang-format off
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <Aclapi.h>
#include <iphlpapi.h>
#include <netioapi.h>
#include <sddl.h>
// clang-format on
#else
#include <arpa/inet.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef __APPLE__
#include <net/if_dl.h>
#include <net/if_types.h>
@@ -59,166 +54,8 @@ bool IsHex(const std::string& text, size_t size) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
});
}
#ifdef _WIN32
std::vector<unsigned char> CurrentUser() {
HANDLE token = nullptr;
Require(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token),
"Cannot open user token");
DWORD size = 0;
GetTokenInformation(token, TokenUser, nullptr, 0, &size);
std::vector<unsigned char> data(size);
bool ok = GetTokenInformation(token, TokenUser, data.data(), size, &size);
CloseHandle(token);
Require(ok, "Cannot read user token");
return data;
}
PSECURITY_DESCRIPTOR PrivateSecurityDescriptor(bool directory) {
auto user = CurrentUser();
LPWSTR sid = nullptr;
Require(ConvertSidToStringSidW(
reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid, &sid),
"Cannot read user SID");
// An elevated token can default to Administrators as the owner even when
// its DACL grants access only to TokenUser. Always set both explicitly.
const auto acl = L"O:" + std::wstring(sid) + L"D:P(A;" +
(directory ? L"OICI" : L"") + L";FA;;;" + sid + L")";
LocalFree(sid);
PSECURITY_DESCRIPTOR descriptor = nullptr;
Require(ConvertStringSecurityDescriptorToSecurityDescriptorW(
acl.c_str(), SDDL_REVISION_1, &descriptor, nullptr),
"Cannot protect LAN file");
return descriptor;
}
#endif
void PrivateWrite(const std::filesystem::path& path, const std::string& text) {
const auto temporary = path.parent_path() / (".write-" + RandomHex(16));
#ifdef _WIN32
auto descriptor = PrivateSecurityDescriptor(false);
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
HANDLE file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, &security,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
LocalFree(descriptor);
Require(file != INVALID_HANDLE_VALUE, "Cannot create LAN file");
DWORD written = 0;
bool ok = WriteFile(file, text.data(), static_cast<DWORD>(text.size()),
&written, nullptr) &&
written == text.size() && FlushFileBuffers(file);
CloseHandle(file);
if (!ok || !MoveFileExW(temporary.c_str(), path.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
DeleteFileW(temporary.c_str());
throw std::runtime_error("Cannot persist LAN file");
}
#else
int fd =
open(temporary.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600);
Require(fd >= 0, "Cannot create private LAN file");
size_t offset = 0;
while (offset < text.size()) {
const auto count = write(fd, text.data() + offset, text.size() - offset);
if (count <= 0) break;
offset += static_cast<size_t>(count);
}
bool ok = offset == text.size() && fsync(fd) == 0;
close(fd);
if (!ok || rename(temporary.c_str(), path.c_str()) != 0) {
unlink(temporary.c_str());
throw std::runtime_error("Cannot persist LAN file");
}
#endif
}
#ifdef _WIN32
using FileHandle = std::unique_ptr<void, decltype(&CloseHandle)>;
FileHandle OpenLanPath(const std::filesystem::path& path, DWORD access) {
// Keep the object open without FILE_SHARE_DELETE so validation and legacy
// owner repair cannot operate on a replacement at the same path.
HANDLE file = CreateFileW(
path.c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
Require(file != INVALID_HANDLE_VALUE, "Cannot open LAN path");
return {file, CloseHandle};
}
void CheckPrivateWindowsPath(const std::filesystem::path& path) {
auto file = OpenLanPath(path, READ_CONTROL);
BY_HANDLE_FILE_INFORMATION info{};
Require(GetFileInformationByHandle(file.get(), &info) &&
!(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT),
"LAN path cannot be a reparse point");
auto user = CurrentUser();
auto sid = reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid;
PSID owner = nullptr;
PACL acl = nullptr;
PSECURITY_DESCRIPTOR descriptor = nullptr;
Require(GetSecurityInfo(
file.get(), SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &owner,
nullptr, &acl, nullptr, &descriptor) == ERROR_SUCCESS,
"Cannot read LAN file permissions");
std::unique_ptr<void, decltype(&LocalFree)> security(descriptor, LocalFree);
bool ok = acl && acl->AceCount > 0;
// Only the exact protected, full-access DACL written by older versions is
// eligible for owner repair. Never adopt a shared or foreign-user profile.
SECURITY_DESCRIPTOR_CONTROL control{};
DWORD revision = 0;
bool legacy = owner && IsWellKnownSid(owner, WinBuiltinAdministratorsSid) &&
GetSecurityDescriptorControl(descriptor, &control, &revision) &&
(control & SE_DACL_PROTECTED) && acl && acl->AceCount == 1;
for (DWORD i = 0; ok && i < acl->AceCount; ++i) {
void* raw = nullptr;
if (!GetAce(acl, i, &raw)) {
ok = false;
break;
}
const auto* ace = static_cast<ACCESS_ALLOWED_ACE*>(raw);
ok = ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE &&
EqualSid(const_cast<DWORD*>(&ace->SidStart), sid);
const BYTE flags = (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
? OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
: 0;
legacy =
legacy && ace->Mask == FILE_ALL_ACCESS && ace->Header.AceFlags == flags;
}
Require(ok && owner && (EqualSid(owner, sid) || legacy),
"LAN files must be accessible only by the current user");
if (legacy) {
auto writable = OpenLanPath(path, WRITE_OWNER);
BY_HANDLE_FILE_INFORMATION current{};
Require(GetFileInformationByHandle(writable.get(), &current) &&
current.dwVolumeSerialNumber == info.dwVolumeSerialNumber &&
current.nFileIndexHigh == info.nFileIndexHigh &&
current.nFileIndexLow == info.nFileIndexLow &&
SetSecurityInfo(writable.get(), SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION, sid, nullptr,
nullptr, nullptr) == ERROR_SUCCESS,
"Cannot repair LAN file owner");
}
}
void CreatePrivateDirectory(const std::filesystem::path& path) {
if (!std::filesystem::exists(path)) {
auto descriptor = PrivateSecurityDescriptor(true);
SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
bool ok = CreateDirectoryW(path.c_str(), &security);
LocalFree(descriptor);
Require(ok, "Cannot create LAN directory");
}
CheckPrivateWindowsPath(path);
}
#endif
std::string Read(const std::filesystem::path& path) {
#ifdef _WIN32
CheckPrivateWindowsPath(path);
#else
struct stat status{};
Require(lstat(path.c_str(), &status) == 0 && S_ISREG(status.st_mode) &&
status.st_uid == getuid() && (status.st_mode & 0077) == 0,
"LAN file must be owned by this user with mode 0600");
#endif
Require(std::filesystem::file_size(path) <= 64 * 1024, "LAN file too large");
std::ifstream input(path, std::ios::binary);
Require(input.good(), "Cannot read LAN file");
return {std::istreambuf_iterator<char>(input), {}};
}
using private_file::Read;
using private_file::Write;
std::string BioText(BIO* bio) {
char* data = nullptr;
long size = BIO_get_mem_data(bio, &data);
@@ -245,7 +82,7 @@ std::string PasswordKey(const std::filesystem::path& directory, bool create) {
Require(
RAND_bytes(reinterpret_cast<unsigned char*>(key.value.data()), 32) == 1,
"Cannot generate LAN password storage key");
PrivateWrite(path, key.value);
Write(path, key.value);
}
auto key = Read(path);
Require(key.size() == 32, "Invalid LAN password storage key");
@@ -358,11 +195,11 @@ void CreateCertificate(const std::filesystem::path& key_path,
Require(PEM_write_bio_PrivateKey(bio.get(), key.get(), nullptr, nullptr, 0,
nullptr, nullptr) == 1,
"Cannot encode private key");
PrivateWrite(key_path, BioText(bio.get()));
Write(key_path, BioText(bio.get()));
(void)BIO_reset(bio.get());
Require(PEM_write_bio_X509(bio.get(), cert.get()) == 1,
"Cannot encode certificate");
PrivateWrite(cert_path, BioText(bio.get()));
Write(cert_path, BioText(bio.get()));
}
} // namespace
unsigned ParsePort(const std::string& value) {
@@ -539,18 +376,7 @@ Identity::Identity(std::filesystem::path directory)
: directory_(std::move(directory)) {}
void Identity::Load() {
DevicePassword::CheckSupport();
std::filesystem::create_directories(directory_.parent_path());
#ifdef _WIN32
CreatePrivateDirectory(directory_);
#else
std::filesystem::create_directories(directory_);
struct stat directory_status{};
Require(lstat(directory_.c_str(), &directory_status) == 0 &&
S_ISDIR(directory_status.st_mode) &&
directory_status.st_uid == getuid(),
"Invalid LAN directory owner or type");
Require(chmod(directory_.c_str(), 0700) == 0, "Cannot protect LAN directory");
#endif
private_file::EnsureDirectory(directory_);
const auto store = directory_ / "identity.json";
if (!std::filesystem::exists(store)) {
Require(!std::filesystem::exists(private_key()) &&
@@ -642,7 +468,7 @@ void Identity::Load() {
state_.erase("password_attempts");
}
void Identity::Save(const nlohmann::json& state) {
PrivateWrite(directory_ / "identity.json", state.dump(2));
Write(directory_ / "identity.json", state.dump(2));
}
std::pair<std::string, nlohmann::json> Identity::GeneratePassword() {
constexpr std::string_view alphabet =
@@ -123,6 +123,9 @@ struct OpenGlFunctions {
PFNGLUNIFORM4FPROC uniform_4f = nullptr;
PFNGLUSEPROGRAMPROC use_program = nullptr;
PFNGLVERTEXATTRIBPOINTERPROC vertex_attrib_pointer = nullptr;
PFNGLGENVERTEXARRAYSPROC gen_vertex_arrays = nullptr;
PFNGLDELETEVERTEXARRAYSPROC delete_vertex_arrays = nullptr;
PFNGLBINDVERTEXARRAYPROC bind_vertex_array = nullptr;
PFNGLGENFRAMEBUFFERSPROC gen_framebuffers = nullptr;
PFNGLDELETEFRAMEBUFFERSPROC delete_framebuffers = nullptr;
PFNGLBINDFRAMEBUFFERPROC bind_framebuffer = nullptr;
@@ -178,6 +181,12 @@ struct OpenGlFunctions {
"glCheckFramebufferStatus");
}
bool LoadVertexArrayFunctions() {
return LoadOpenGlFunction(&gen_vertex_arrays, "glGenVertexArrays") &&
LoadOpenGlFunction(&delete_vertex_arrays, "glDeleteVertexArrays") &&
LoadOpenGlFunction(&bind_vertex_array, "glBindVertexArray");
}
#if CROSSDESK_OPENGL_CUDA_INTEROP
bool LoadSyncFunctions() {
return LoadOpenGlFunction(&fence_sync, "glFenceSync") &&
@@ -292,6 +301,8 @@ struct OpenGlVideoRenderer::Impl {
std::atomic<bool> ready{false};
GLuint program = 0;
GLuint vertex_buffer = 0;
GLuint vertex_array = 0;
bool modern_gl = false;
GLuint y_texture = 0;
GLuint uv_texture = 0;
GLint position_location = -1;
@@ -644,6 +655,8 @@ struct OpenGlVideoRenderer::Impl {
void ResetGlHandles() {
program = 0;
vertex_buffer = 0;
vertex_array = 0;
modern_gl = false;
y_texture = 0;
uv_texture = 0;
position_location = -1;
@@ -698,6 +711,13 @@ bool OpenGlVideoRenderer::Setup() {
std::sscanf(is_gles ? version + std::strlen("OpenGL ES ") : version,
"%d.%d", &major, &minor);
}
// Slint may fall back from GLES to a desktop core context. In that context
// VAO 0, legacy luminance textures and legacy shader inputs are not usable.
impl_->modern_gl = major >= 3;
if (impl_->modern_gl && !impl_->gl.LoadVertexArrayFunctions()) {
LOG_WARN("OpenGL NV12 underlay unavailable: vertex array functions missing");
return false;
}
const auto *extensions = major < 3
? reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)) : nullptr;
impl_->pixel_unpack_buffer_available = major >= 3 ||
@@ -727,22 +747,30 @@ bool OpenGlVideoRenderer::Setup() {
}
#endif
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;
const std::string shader_version = is_gles
? (impl_->modern_gl ? "#version 300 es\n" : "#version 100\n")
: (major > 3 || (major == 3 && minor >= 2) ? "#version 150\n"
: impl_->modern_gl ? "#version 130\n" : "#version 110\n");
const std::string vertex_source = shader_version +
(impl_->modern_gl ? "#define INPUT in\n#define OUTPUT out\n"
: "#define INPUT attribute\n#define OUTPUT varying\n") + R"glsl(
INPUT vec2 position;
INPUT vec2 texcoord;
OUTPUT vec2 video_texcoord;
void main() {
video_texcoord = texcoord;
gl_Position = vec4(position, 0.0, 1.0);
}
)glsl";
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(
const std::string fragment_source = shader_version +
(is_gles ? "#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
"precision highp float;\n"
"#else\nprecision mediump float;\n#endif\n" : "") +
(impl_->modern_gl
? "#define INPUT in\n#define SAMPLE texture\n"
"#define UV_CHANNELS rg\nout vec4 fragment_color;\n"
: "#define INPUT varying\n#define SAMPLE texture2D\n"
"#define UV_CHANNELS ra\n#define fragment_color gl_FragColor\n") + R"glsl(
uniform sampler2D y_texture;
uniform sampler2D uv_texture;
uniform vec2 target_size;
@@ -752,7 +780,7 @@ uniform float packed_video;
uniform vec4 video_rect;
uniform float corner_radius;
uniform float video_enabled;
varying vec2 video_texcoord;
INPUT 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) {
@@ -766,7 +794,7 @@ 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);
return SAMPLE(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;
@@ -776,7 +804,7 @@ vec4 sample_plane(sampler2D plane, vec2 size, vec2 coord) {
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);
sum += weight * SAMPLE(plane, coord + filter_direction * offset / size);
weight_sum += weight;
}
return sum / weight_sum;
@@ -785,7 +813,7 @@ 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);
sample_plane(uv_texture, source_size * 0.5, coord).UV_CHANNELS);
}
void main() {
vec2 surface_point = video_texcoord * target_size;
@@ -800,7 +828,7 @@ void main() {
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);
fragment_color = vec4(yuv, 1.0);
return;
}
float y = 1.16438356 * (yuv.x - 16.0 / 255.0);
@@ -820,7 +848,7 @@ void main() {
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);
fragment_color = vec4(rgb * coverage, coverage);
}
)glsl";
@@ -903,6 +931,11 @@ void main() {
};
GLint previous_array_buffer = 0;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &previous_array_buffer);
while (glGetError() != GL_NO_ERROR) {
}
if (impl_->modern_gl) {
impl_->gl.gen_vertex_arrays(1, &impl_->vertex_array);
}
impl_->gl.gen_buffers(1, &impl_->vertex_buffer);
impl_->gl.bind_buffer(GL_ARRAY_BUFFER, impl_->vertex_buffer);
impl_->gl.buffer_data(GL_ARRAY_BUFFER, sizeof(kVertices), kVertices,
@@ -918,8 +951,6 @@ void main() {
impl_->gl.active_texture(GL_TEXTURE1);
GLint previous_texture_1 = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous_texture_1);
while (glGetError() != GL_NO_ERROR) {
}
glGenTextures(1, &impl_->y_texture);
glGenTextures(1, &impl_->uv_texture);
for (const auto [unit, texture] :
@@ -940,6 +971,7 @@ void main() {
const GLenum setup_error = glGetError();
if (impl_->program == 0 || impl_->vertex_buffer == 0 ||
(impl_->modern_gl && impl_->vertex_array == 0) ||
impl_->y_texture == 0 || impl_->uv_texture == 0 ||
setup_error != GL_NO_ERROR) {
LOG_ERROR("OpenGL NV12 resource setup failed, error={}", setup_error);
@@ -950,9 +982,16 @@ void main() {
impl_->ready.store(true, std::memory_order_release);
const auto *vendor = reinterpret_cast<const char *>(glGetString(GL_VENDOR));
const auto *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
LOG_INFO("OpenGL NV12 underlay initialized ({}), vendor={}, renderer={}",
GLint profile = 0;
if (!is_gles && (major > 3 || (major == 3 && minor >= 2))) {
glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &profile);
}
LOG_INFO("OpenGL NV12 underlay initialized ({}), vendor={}, renderer={}, "
"profile={}, textures={}, vao={}",
version ? version : "unknown OpenGL version",
vendor ? vendor : "unknown", renderer ? renderer : "unknown");
vendor ? vendor : "unknown", renderer ? renderer : "unknown",
profile, impl_->modern_gl ? "R/RG" : "luminance",
impl_->vertex_array);
return true;
}
@@ -973,6 +1012,9 @@ void OpenGlVideoRenderer::Teardown() {
if (impl_->vertex_buffer != 0 && impl_->gl.delete_buffers) {
impl_->gl.delete_buffers(1, &impl_->vertex_buffer);
}
if (impl_->vertex_array != 0 && impl_->gl.delete_vertex_arrays) {
impl_->gl.delete_vertex_arrays(1, &impl_->vertex_array);
}
if (impl_->program != 0 && impl_->gl.delete_program) {
impl_->gl.delete_program(impl_->program);
}
@@ -1056,6 +1098,9 @@ OpenGlVideoRenderer::SubmitResult OpenGlVideoRenderer::SubmitNv12Internal(
auto &frames = *impl_->frames;
std::lock_guard lock(frames.mutex);
if (!IsReady()) {
return SubmitResult::failed;
}
if (frames.selected_stream != remote_id) {
return SubmitResult::not_selected;
}
@@ -1194,9 +1239,12 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
int target_width, int target_height,
int top_inset_pixels,
int corner_radius_pixels) {
if (!IsReady() || target_width <= 0 || target_height <= 0) {
if (!IsReady()) {
return {RenderResult::failed};
}
if (target_width <= 0 || target_height <= 0) {
return {RenderResult::idle};
}
size_t slot_index = kFrameSlotCount;
uint64_t sequence = 0;
@@ -1286,10 +1334,18 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
GLint previous_texture_1 = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous_texture_1);
const auto position_state = CaptureVertexAttrib(
impl_->gl, static_cast<GLuint>(impl_->position_location));
const auto texcoord_state = CaptureVertexAttrib(
impl_->gl, static_cast<GLuint>(impl_->texcoord_location));
GLint previous_vertex_array = 0;
VertexAttribState position_state;
VertexAttribState texcoord_state;
if (impl_->vertex_array != 0) {
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &previous_vertex_array);
impl_->gl.bind_vertex_array(impl_->vertex_array);
} else {
position_state = CaptureVertexAttrib(
impl_->gl, static_cast<GLuint>(impl_->position_location));
texcoord_state = CaptureVertexAttrib(
impl_->gl, static_cast<GLuint>(impl_->texcoord_location));
}
glDisable(GL_BLEND);
glDisable(GL_CULL_FACE);
@@ -1401,20 +1457,26 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
if (uploaded_texture_width != source_width ||
uploaded_texture_height != source_height) {
impl_->gl.active_texture(GL_TEXTURE0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, source_width,
source_height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE,
glTexImage2D(GL_TEXTURE_2D, 0,
impl_->modern_gl ? GL_R8 : GL_LUMINANCE, source_width,
source_height, 0,
impl_->modern_gl ? GL_RED : GL_LUMINANCE, GL_UNSIGNED_BYTE,
y_pixels);
impl_->gl.active_texture(GL_TEXTURE1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, source_width / 2,
source_height / 2, 0, GL_LUMINANCE_ALPHA,
glTexImage2D(GL_TEXTURE_2D, 0,
impl_->modern_gl ? GL_RG8 : GL_LUMINANCE_ALPHA,
source_width / 2, source_height / 2, 0,
impl_->modern_gl ? GL_RG : GL_LUMINANCE_ALPHA,
GL_UNSIGNED_BYTE, uv_pixels);
} else {
impl_->gl.active_texture(GL_TEXTURE0);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, source_width, source_height,
GL_LUMINANCE, GL_UNSIGNED_BYTE, y_pixels);
impl_->modern_gl ? GL_RED : GL_LUMINANCE,
GL_UNSIGNED_BYTE, y_pixels);
impl_->gl.active_texture(GL_TEXTURE1);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, source_width / 2,
source_height / 2, GL_LUMINANCE_ALPHA,
source_height / 2,
impl_->modern_gl ? GL_RG : GL_LUMINANCE_ALPHA,
GL_UNSIGNED_BYTE, uv_pixels);
}
const GLenum upload_error = glGetError();
@@ -1562,10 +1624,23 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
has_video ? source_width : 0, has_video ? source_height : 0,
has_video ? sequence : 0};
RestoreVertexAttrib(impl_->gl, static_cast<GLuint>(impl_->position_location),
position_state);
RestoreVertexAttrib(impl_->gl, static_cast<GLuint>(impl_->texcoord_location),
texcoord_state);
if (outcome.result == RenderResult::failed) {
LOG_WARN("OpenGL NV12 presentation failed: upload={}, draw_error={}, "
"vao={}; disabling native video until the context is recreated",
upload_succeeded, draw_error, impl_->vertex_array);
// Do not expose the desktop during the UI tick that switches to pixels.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
if (impl_->vertex_array != 0) {
impl_->gl.bind_vertex_array(static_cast<GLuint>(previous_vertex_array));
} else {
RestoreVertexAttrib(impl_->gl, static_cast<GLuint>(impl_->position_location),
position_state);
RestoreVertexAttrib(impl_->gl, static_cast<GLuint>(impl_->texcoord_location),
texcoord_state);
}
impl_->gl.bind_buffer(GL_ARRAY_BUFFER,
static_cast<GLuint>(previous_array_buffer));
if (impl_->pixel_unpack_buffer_available) {
@@ -1600,9 +1675,13 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
const GLenum restore_error = glGetError();
if (restore_error != GL_NO_ERROR) {
LOG_WARN("OpenGL NV12 state restoration failed, error={}", restore_error);
if (outcome.result == RenderResult::rendered) {
outcome.result = RenderResult::failed;
}
outcome.result = RenderResult::failed;
}
if (outcome.result == RenderResult::failed) {
// Keep the last decoded frame available for a CPU snapshot. GL resources
// are released by RenderingTeardown while the owning context is current.
std::lock_guard lock(impl_->frames->mutex);
impl_->ready.store(false, std::memory_order_release);
}
return outcome;
}
@@ -2,12 +2,62 @@
#include <cstdlib>
#include <initializer_list>
#include <memory>
#include <string_view>
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#include "rd_log.h"
#include "platform/common/gui/cuda_opengl_interop.h"
namespace crossdesk {
namespace {
#if USE_CUDA && (defined(__x86_64__) || defined(__amd64__))
bool HasNvidiaOffloadProvider() {
// CUDA availability says nothing about the X server's PRIME topology.
// In particular, NVIDIA-0 is a normal display provider, not an offload
// GPU screen. Forcing offload in that configuration can render into a GL
// buffer successfully while leaving the actual window blank.
const char* display_name = std::getenv("DISPLAY");
if (!display_name || display_name[0] == '\0') return false;
std::unique_ptr<Display, decltype(&XCloseDisplay)> display(
XOpenDisplay(display_name), XCloseDisplay);
if (!display) return false;
int major = 0, minor = 0;
if (!XRRQueryVersion(display.get(), &major, &minor) || major < 1 ||
(major == 1 && minor < 4)) return false;
const auto root = XDefaultRootWindow(display.get());
std::unique_ptr<XRRScreenResources, decltype(&XRRFreeScreenResources)> screen(
XRRGetScreenResourcesCurrent(display.get(), root), XRRFreeScreenResources);
std::unique_ptr<XRRProviderResources, decltype(&XRRFreeProviderResources)>
providers(XRRGetProviderResources(display.get(), root),
XRRFreeProviderResources);
if (!screen || !providers) return false;
for (int i = 0; i < providers->nproviders; ++i) {
std::unique_ptr<XRRProviderInfo, decltype(&XRRFreeProviderInfo)> provider(
XRRGetProviderInfo(display.get(), screen.get(), providers->providers[i]),
XRRFreeProviderInfo);
if (!provider || !provider->name || provider->nameLen <= 0) continue;
const std::string_view name(provider->name, provider->nameLen);
// NVIDIA documents offload GPU screens as NVIDIA-G0, NVIDIA-G1, etc.
// Their RandR capability mask can be zero, so SourceOffload is not a
// reliable test for the proprietary driver's offload support.
constexpr std::string_view prefix = "NVIDIA-G";
if (name.size() > prefix.size() && name.substr(0, prefix.size()) == prefix &&
name.find_first_not_of("0123456789", prefix.size()) ==
std::string_view::npos) return true;
}
return false;
}
#endif
} // namespace
void ConfigureLinuxCudaGraphics() {
#if USE_CUDA && (defined(__x86_64__) || defined(__amd64__))
@@ -28,6 +78,11 @@ void ConfigureLinuxCudaGraphics() {
}
}
if (!HasNvidiaOffloadProvider()) {
LOG_INFO("Keeping default Linux graphics selection: no NVIDIA PRIME "
"offload GPU screen");
return;
}
if (!IsCudaDeviceAvailable()) {
return;
}
@@ -9,8 +9,10 @@
namespace crossdesk {
// Call before SDL or Slint initializes EGL/GLX. Hybrid laptops otherwise
// create the GUI context on the integrated GPU while NVDEC uses NVIDIA.
// Call before SDL or Slint initializes EGL/GLX. Select NVIDIA on hybrid
// systems with a PRIME offload GPU screen so GL can share NVDEC buffers.
// Keep the default driver when NVIDIA already owns the display or the
// display server does not advertise offload support.
void ConfigureLinuxCudaGraphics();
} // namespace crossdesk
@@ -126,6 +126,42 @@ float MainWindowInitialPositionYOffset() {
}
}
bool CenterNativeWindowOnScreen(void *opaque_slint_view) {
@autoreleasepool {
NSView *slint_view = (__bridge NSView *)opaque_slint_view;
NSWindow *window = slint_view.window;
NSScreen *screen = window.screen ?: NSScreen.mainScreen;
if (!window || !screen) return false;
CenterWindowOnScreen(window, screen);
return true;
}
}
bool ConfigureWhiteWindowChrome(void *opaque_slint_view) {
@autoreleasepool {
NSView *slint_view = (__bridge NSView *)opaque_slint_view;
NSWindow *window = slint_view.window;
if (window == nil ||
(window.styleMask & NSWindowStyleMaskTitled) == 0) {
return false;
}
// Winit creates a transparent AppKit backing even when Slint paints an
// opaque client area. macOS 27 can expose that backing in the titlebar.
// Use a fixed white backing instead of AppKit's theme-dependent titlebar
// material. Aqua keeps the native title and controls readable on white.
window.styleMask &= ~NSWindowStyleMaskFullSizeContentView;
window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
window.titlebarAppearsTransparent = YES;
window.opaque = YES;
window.backgroundColor = NSColor.whiteColor;
NSView *frame_view = window.contentView.superview;
frame_view.needsLayout = YES;
[frame_view layoutSubtreeIfNeeded];
return true;
}
}
bool ConfigureMainWindowChrome(void *opaque_slint_view, bool gallery) {
@autoreleasepool {
NSView *slint_view = (__bridge NSView *)opaque_slint_view;
@@ -150,21 +186,8 @@ bool ConfigureMainWindowChrome(void *opaque_slint_view, bool gallery) {
NSWindowCollectionBehaviorFullScreenAllowsTiling)) |
NSWindowCollectionBehaviorFullScreenNone;
// Winit creates a transparent AppKit backing even when Slint paints an
// opaque client area. macOS 27 can expose that backing in the titlebar.
// Use a fixed white backing instead of AppKit's theme-dependent titlebar
// material. Aqua keeps the native title and controls readable on white.
window.styleMask &= ~NSWindowStyleMaskFullSizeContentView;
window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
window.titlebarAppearsTransparent = YES;
window.opaque = YES;
window.backgroundColor = NSColor.whiteColor;
HideMainWindowZoomButton(window);
NSView *frame_view = window.contentView.superview;
frame_view.needsLayout = YES;
[frame_view layoutSubtreeIfNeeded];
return true;
return ConfigureWhiteWindowChrome(opaque_slint_view);
}
}
+7
View File
@@ -9,6 +9,13 @@ namespace crossdesk {
// left-mouse-down event. Returns false when no suitable native event exists.
bool StartNativeWindowDrag();
// Gives a titled AppKit window an opaque white backing, preserving its resize
// and fullscreen behavior. Returns false until its native window is ready.
bool ConfigureWhiteWindowChrome(void* slint_view);
// Centers the complete AppKit window frame in its screen's usable area.
// Returns false until its native window and screen are ready.
bool CenterNativeWindowOnScreen(void* slint_view);
// Configures the connection or DeskHub window with a white native titlebar.
// Only DeskHub is resizable. |slint_view| is its AppKit NSView*.
// Returns false while the native window or its titlebar controls are not ready.
@@ -24,6 +24,7 @@ int GuiApplication::RunUnattended(void* stop_event) {
dll_log_path_ = exec_log_path_;
InitializeLogger();
config_center_ = std::make_unique<ConfigCenter>(cache_path_ + "/config.ini");
InitializeTrustedDevices(root / "trusted-devices");
if (config_center_->SetPrivacyScreen(false) != 0 ||
config_center_->SetSaveRemotePreviews(false) != 0)
return 1;
@@ -44,6 +45,7 @@ int GuiApplication::RunUnattended(void* stop_event) {
next_peer_attempt = now + 3000;
if (CreateConnectionPeer() != 0) CloseConnectionPeer();
}
TickControllerTrust();
HandleConnectionStatusChange();
HandleScreenLock();
HandleWindowsServiceIntegration();
+3
View File
@@ -24,6 +24,9 @@ class FileReceiver {
bool OnData(const char* data, size_t size) { return session_.Receive(data, size); }
void Poll() { session_.Pump(); }
void Cancel() { session_.Cancel(); }
bool ReserveDirectory(uint32_t id, const std::filesystem::path& directory) {
return session_.ReserveDirectory(id, directory);
}
// Set once, before the receiver is published to transport callbacks.
void SetOnSendAck(OnSendAck cb) { on_send_ack_ = std::move(cb); }
void SetOnReceiveProgress(OnReceiveProgress cb) { on_receive_progress_ = std::move(cb); }
@@ -0,0 +1,148 @@
#include "platform/linux/gui/cuda_graphics.h"
#include "rd_log.h"
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
namespace {
// Exercise the actual startup policy without requiring a particular GPU or
// X server. NVIDIA offload providers deliberately have a zero capability mask.
std::vector<std::string> provider_names;
std::vector<RRProvider> provider_ids;
bool display_available = true, cuda_available = true, randr_available = true;
bool resources_available = true, info_available = true;
int randr_minor = 4, display_opens = 0, display_closes = 0;
constexpr const char* selection_variables[] = {
"__NV_PRIME_RENDER_OFFLOAD", "__NV_PRIME_RENDER_OFFLOAD_PROVIDER",
"__GLX_VENDOR_LIBRARY_NAME", "__EGL_VENDOR_LIBRARY_FILENAMES",
"__EGL_VENDOR_LIBRARY_DIRS", "DRI_PRIME", "LIBGL_ALWAYS_SOFTWARE",
"MESA_LOADER_DRIVER_OVERRIDE"};
void Reset(std::vector<std::string> names) {
for (const auto* name : selection_variables) unsetenv(name);
setenv("DISPLAY", ":test", 1);
provider_names = std::move(names);
provider_ids.resize(provider_names.size());
for (size_t i = 0; i < provider_ids.size(); ++i) provider_ids[i] = i;
display_available = cuda_available = randr_available = true;
resources_available = info_available = true;
randr_minor = 4;
display_opens = display_closes = 0;
}
bool CheckSelection(bool offload, const char* scenario) {
crossdesk::ConfigureLinuxCudaGraphics();
const char* prime = std::getenv("__NV_PRIME_RENDER_OFFLOAD");
const char* vendor = std::getenv("__GLX_VENDOR_LIBRARY_NAME");
const bool matches = offload
? prime && std::string(prime) == "1" && vendor && std::string(vendor) == "nvidia"
: !prime && !vendor;
if (!matches || display_opens != display_closes) {
std::cerr << "Incorrect graphics selection or leaked X display: " << scenario << '\n';
return false;
}
return true;
}
} // namespace
// Link-time substitutes for the external XRandR/CUDA queries, not for the
// selection logic under test. No real display or CUDA context is initialized.
extern "C" {
Display* XOpenDisplay(const char*) {
if (!display_available) return nullptr;
++display_opens;
return reinterpret_cast<Display*>(&display_opens);
}
int XCloseDisplay(Display*) { ++display_closes; return 0; }
Window XDefaultRootWindow(Display*) { return 1; }
Status XRRQueryVersion(Display*, int* major, int* minor) {
*major = 1;
*minor = randr_minor;
return randr_available;
}
XRRScreenResources* XRRGetScreenResourcesCurrent(Display*, Window) {
return resources_available ? new XRRScreenResources{} : nullptr;
}
void XRRFreeScreenResources(XRRScreenResources* value) { delete value; }
XRRProviderResources* XRRGetProviderResources(Display*, Window) {
if (!resources_available) return nullptr;
auto* result = new XRRProviderResources{};
result->nproviders = static_cast<int>(provider_ids.size());
result->providers = provider_ids.data();
return result;
}
void XRRFreeProviderResources(XRRProviderResources* value) { delete value; }
XRRProviderInfo* XRRGetProviderInfo(Display*, XRRScreenResources*, RRProvider id) {
if (!info_available) return nullptr;
auto* result = new XRRProviderInfo{};
result->name = provider_names.at(id).data();
result->nameLen = static_cast<int>(provider_names.at(id).size());
return result;
}
void XRRFreeProviderInfo(XRRProviderInfo* value) { delete value; }
}
namespace crossdesk {
bool IsCudaDeviceAvailable() { return cuda_available; }
std::shared_ptr<spdlog::logger> get_logger() { return spdlog::default_logger(); }
} // namespace crossdesk
int main() {
bool ok = true;
Reset({"NVIDIA-0", "AMD Radeon Graphics @ pci:0000:05:00.0"});
ok &= CheckSelection(false, "NVIDIA primary with an AMD display sink");
Reset({"NVIDIA-0"});
ok &= CheckSelection(false, "NVIDIA-only desktop");
Reset({"modesetting", "NVIDIA-G0"});
ok &= CheckSelection(true, "integrated primary with NVIDIA offload");
Reset({"modesetting", "NVIDIA-G12"});
ok &= CheckSelection(true, "numbered offload GPU screen");
Reset({"modesetting", "NVIDIA-G", "NVIDIA-G0-extra", ""});
ok &= CheckSelection(false, "no recognized NVIDIA GPU screen");
Reset({});
ok &= CheckSelection(false, "no providers");
Reset({"NVIDIA-G0"});
cuda_available = false;
ok &= CheckSelection(false, "CUDA unavailable");
Reset({"NVIDIA-G0"});
unsetenv("DISPLAY");
ok &= CheckSelection(false, "no X display");
Reset({"NVIDIA-G0"});
display_available = false;
ok &= CheckSelection(false, "X display inaccessible");
Reset({"NVIDIA-G0"});
randr_available = false;
ok &= CheckSelection(false, "RandR unavailable");
Reset({"NVIDIA-G0"});
randr_minor = 3;
ok &= CheckSelection(false, "RandR predates provider queries");
Reset({"NVIDIA-G0"});
resources_available = false;
ok &= CheckSelection(false, "RandR resources unavailable");
Reset({"NVIDIA-G0"});
info_available = false;
ok &= CheckSelection(false, "provider info unavailable");
// Any explicit graphics selection must win, including PRIME=0.
for (const auto* name : selection_variables) {
Reset({"modesetting", "NVIDIA-G0"});
setenv(name, "0", 1);
crossdesk::ConfigureLinuxCudaGraphics();
for (const auto* other : selection_variables) {
const char* value = std::getenv(other);
const bool preserved = std::string(name) == other
? value && std::string(value) == "0" : !value;
if (!preserved) { std::cerr << "Changed explicit selection: " << name << '\n'; ok = false; }
}
if (display_opens) { std::cerr << "Probed explicitly selected graphics\n"; ok = false; }
}
return ok ? 0 : 1;
}
@@ -3,6 +3,7 @@
#include "ui/model_update.h"
#include "ui/ui_localization.h"
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdlib>
@@ -330,6 +331,60 @@ bool VerifyGalleryPopups(RenderTestPlatform& platform) {
return Check(!wall->get_gallery_adding(), "Add dialog Cancel must respond immediately");
}
bool VerifyUpdateRecovery(RenderTestPlatform& platform) {
auto main = CreateMainWindow();
auto& screen = *platform.adapter;
const float width = main->get_minimum_window_width();
const float height = main->get_minimum_window_height();
main->window().set_size(slint::LogicalSize({width, height}));
main->set_update_available(true);
main->set_update_install_available(true);
main->set_latest_version("v2.0.0");
int install_requests = 0, manual_downloads = 0;
main->on_open_download([&] { ++install_requests; main->set_update_confirm_open(true); });
main->on_open_manual_download([&] { ++manual_downloads; });
main->show();
screen.Settle();
const float button_y = height / 2 + std::min(488.f, height - 32) / 2 - 41;
const float action_x = width / 2 + 161;
const float manual_x = action_x - 118;
const auto action_pixels = [&] {
return screen.Region(int(action_x - 40), int(button_y - 12), 80, 24);
};
const auto install_label = action_pixels();
main->set_update_install_failed(true);
main->set_update_install_status(crossdesk::ui_localization::Text(
crossdesk::localization::update_install_failed[0] + "\nDownload failed"));
screen.Settle();
if (!Check(action_pixels() != install_label,
"A failed update must visibly replace Install update with Retry update")) return false;
screen.Click(manual_x, button_y);
if (!Check(manual_downloads == 1 && install_requests == 0 && !main->get_update_confirm_open(),
"Manual download must remain reachable after failure without starting automatic installation")) return false;
screen.Click(action_x, button_y);
if (!Check(install_requests == 1 && main->get_update_confirm_open(),
"Retry must open the installation confirmation")) return false;
screen.Key(slint::platform::key_codes::Escape);
if (!Check(!main->get_update_confirm_open(), "Retry confirmation must remain cancellable")) return false;
main->set_update_install_busy(true);
screen.Settle();
screen.Click(action_x, button_y);
screen.Click(manual_x, button_y);
if (!Check(install_requests == 1 && manual_downloads == 1,
"Recovery buttons must reject repeated clicks while an update is running")) return false;
main->set_update_install_busy(false);
main->set_update_install_available(false);
main->set_update_install_status(crossdesk::ui_localization::Text(
crossdesk::localization::update_install_failed_manual[0]));
// The application's primary action falls back to manual download when the
// current installation or signed manifest no longer supports automatic updates.
main->on_open_download([&] { ++manual_downloads; });
screen.Settle();
screen.Click(action_x, button_y);
return Check(manual_downloads == 2 && !main->get_update_confirm_open(),
"An unavailable automatic retry must retain the primary manual download action");
}
bool VerifyServerPanel(RenderTestPlatform& platform) {
auto panel = crossdesk::ui::ServerWindow::create();
auto& screen = *platform.adapter;
@@ -377,5 +432,6 @@ int main() {
if (!VerifyGalleryPopups(*backend)) return 3;
if (!VerifyServerPanel(*backend)) return 4;
if (!VerifyAutostartSettings(*backend)) return 5;
if (!VerifyUpdateRecovery(*backend)) return 6;
std::cout << "Slint popup rendering and local input passed.\n";
}
+13 -1
View File
@@ -82,12 +82,13 @@ function setup_targets()
target("desktop_common")
set_kind("object")
add_deps("rd_log", "crossdesk_wire")
add_packages("libyuv")
add_packages("libyuv", "openssl3")
add_packages("concurrentqueue")
add_files("apps/desktop/src/common/*.cpp")
if is_os("windows") then
add_files("apps/desktop/src/platform/windows/system_info.cpp",
"apps/desktop/src/platform/windows/screen_lock.cpp")
add_syslinks("Advapi32", {public = true})
elseif is_os("macosx") then
add_files("apps/desktop/src/platform/macos/system_info.cpp",
"apps/desktop/src/platform/macos/screen_lock.cpp")
@@ -232,6 +233,17 @@ function setup_targets()
add_files("apps/desktop/tests/slint_ui_smoke_test.cpp")
add_rules("crossdesk.slint_runtime")
if is_os("linux") and is_arch("x86_64") and is_config("USE_CUDA", true) then
target("linux_cuda_graphics_test")
set_kind("binary")
set_default(false)
add_packages("spdlog")
add_includedirs("apps/desktop/src", "apps/desktop/src/log",
"deps/submodules/minirtc/src/api")
add_files("apps/desktop/tests/linux_cuda_graphics_test.cpp",
"apps/desktop/src/platform/linux/gui/cuda_graphics.cpp")
end
target("slint_stream_render_test")
set_kind("binary")
set_languages("c++20")
@@ -222,6 +222,7 @@
300000000000000000000001 /* Frameworks */,
600000000000000000000002 /* Resources */,
300000000000000000000002 /* Embed Frameworks */,
700000000000000000000002 /* Generate OpenSSL symbols */,
);
buildRules = (
);
@@ -318,6 +319,24 @@
shellPath = /bin/zsh;
shellScript = "set -e\npython3 \"${PROJECT_DIR}/scripts/prepare_source_metadata.py\" --output \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/SourceMetadata.json\"\n\"${PROJECT_DIR}/scripts/build_minirtc_ios.sh\"\npython3 \"${PROJECT_DIR}/scripts/verify_native_build.py\" --inputs \"${PROJECT_DIR}/Vendor/${PLATFORM_NAME}/${CONFIGURATION}/libCrossDeskMiniRTC.a.inputs.sha256\" --xmake-version \"${PROJECT_DIR}/Vendor/${PLATFORM_NAME}/${CONFIGURATION}/xmake-version.txt\"\npython3 \"${PROJECT_DIR}/scripts/package_openssl_ios.py\" --inputs \"${PROJECT_DIR}/Vendor/${PLATFORM_NAME}/${CONFIGURATION}/libCrossDeskMiniRTC.a.inputs.sha256\" --output \"${BUILT_PRODUCTS_DIR}/OpenSSL.framework\" --platform \"${PLATFORM_NAME}\"\n";
};
700000000000000000000002 /* Generate OpenSSL symbols */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(TARGET_BUILD_DIR)/$(FRAMEWORKS_FOLDER_PATH)/OpenSSL.framework/OpenSSL",
"$(PROJECT_DIR)/scripts/generate_openssl_symbols.py",
);
name = "Generate OpenSSL symbols";
outputPaths = (
"$(DWARF_DSYM_FOLDER_PATH)/OpenSSL.framework.dSYM/Contents/Resources/DWARF/OpenSSL",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/zsh;
shellScript = "set -e\nif [[ \"${DEBUG_INFORMATION_FORMAT}\" == \"dwarf-with-dsym\" ]]; then\n python3 -B \"${PROJECT_DIR}/scripts/generate_openssl_symbols.py\" --binary \"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework/OpenSSL\" --output \"${DWARF_DSYM_FOLDER_PATH}/OpenSSL.framework.dSYM\"\nfi\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -496,7 +515,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 4;
ENABLE_BITCODE = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -548,7 +567,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 4;
ENABLE_BITCODE = NO;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -323,6 +323,7 @@ final class RemoteKeyboardInputBar: UIView {
let computerButton = UIButton(type: .system)
computerButton.setTitle(NSLocalizedString("电脑键盘", comment: ""), for: .normal)
computerButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
computerButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
computerButton.accessibilityLabel = NSLocalizedString("切换到电脑键盘", comment: "")
computerButton.addTarget(self, action: #selector(switchToComputer), for: .touchUpInside)
@@ -337,7 +338,8 @@ final class RemoteKeyboardInputBar: UIView {
row.translatesAutoresizingMaskIntoConstraints = false
addSubview(row)
NSLayoutConstraint.activate([
computerButton.widthAnchor.constraint(equalToConstant: 80),
// Keep the minimum touch width while allowing longer translations.
computerButton.widthAnchor.constraint(greaterThanOrEqualToConstant: 80),
dismissButton.widthAnchor.constraint(equalToConstant: RemoteKeyboardDismissButton.sideLength),
row.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 4),
row.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -4),
@@ -384,6 +384,15 @@ final class RemoteTouchSurface: UIView, UIGestureRecognizerDelegate {
let newScale = min(max(oldScale * recognizer.scale, 1),
maximumViewportScale)
recognizer.scale = 1
if newScale == 1 {
// Pinching back to fit also ends any cursor-edge pan, even
// when the gesture starts at 1x with an off-center image.
viewportScale = 1
viewportOffset = .zero
edgePanned = false
publishViewport()
return
}
guard abs(newScale - oldScale) > 0.0001 else { return }
let center = CGPoint(x: bounds.midX, y: bounds.midY)
@@ -402,7 +411,8 @@ final class RemoteTouchSurface: UIView, UIGestureRecognizerDelegate {
pinchActive = false
if viewportScale <= 1.001 {
viewportScale = 1
viewportOffset = constrainedViewportOffset(viewportOffset, scale: 1)
viewportOffset = .zero
edgePanned = false
publishViewport()
}
default:
@@ -140,8 +140,11 @@ struct RemoteSessionView: View {
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipped()
}
.ignoresSafeArea()
// Fit video and input to the same unobscured area. Only the black
// background extends beneath the home indicator and display cutout.
.ignoresSafeArea(.keyboard)
.transaction { transaction in
transaction.animation = nil
transaction.disablesAnimations = true
@@ -855,7 +858,8 @@ private struct RemoteComputerKeyboard: View {
switchKeyboard()
}
.font(.system(size: 15, weight: .medium))
.frame(width: 80, height: 44)
.fixedSize(horizontal: true, vertical: false)
.frame(minWidth: 80, minHeight: 44)
.accessibilityLabel(NSLocalizedString("切换到系统键盘", comment: ""))
if verticalSizeClass == .compact {
pageTabs
@@ -1 +1 @@
"NSLocalNetworkUsageDescription" = "CrossDesk 需要访问本地网络,以连接同一局域网内的电脑,进行远程控制和文件传输。";
"NSLocalNetworkUsageDescription" = "CrossDesk 使用局域网发现并建立原生 P2P 远程控制连接。";
+31 -4
View File
@@ -150,11 +150,28 @@ Commit and push the intended signing settings and shared scheme to the branch
selected by the workflow before starting a build.
Xcode Cloud automatically runs `ci_scripts/ci_post_clone.sh` next to the Xcode
project. It installs Xmake, CMake, and Python 3.13 with Homebrew, prepares an
project. It installs Xmake, CMake, pkgconf, and Python 3.13 with Homebrew, prepares an
isolated host Python environment with pip/setuptools/wheel, verifies the minimum
Xmake version, and initializes the pinned MiniRTC submodules. The native build
phase selects these tools again and preserves Cloud's proxy settings for package
downloads. No manual workflow PATH setting or `sudo` command is required.
Xmake version and host `pkg-config`, and initializes the pinned MiniRTC submodules.
It exposes both `pkgconf` and `pkg-config` from the Homebrew formula in the host
tool directory, allowing GLib's Meson build to resolve Xmake's iOS PCRE2 and
libffi packages instead of compiling bundled fallback versions. The native build
phase checks and selects these tools again and preserves Cloud's proxy settings
for package downloads. No manual workflow PATH setting or `sudo` command is required.
For **Archive - iOS**, `ci_scripts/ci_pre_xcodebuild.sh` builds the native
dependencies before `xcodebuild`, using `Release / iphoneos / arm64` to match the
shared scheme. It streams verbose build output and prints a heartbeat with
process status every minute, avoiding the archive's 30-minute inactivity timeout
while Xcode buffers Run Script output. The archive's native build phase reuses
the same dependency cache and libraries, retaining its input and toolchain
validation. Other actions keep their existing native build behavior.
The prebuild records its output under `.xmake/xcode-cloud-logs` and copies package
installation and Meson logs there on failure. These files are temporary, so the
script also prints the complete GLib install log and the last 200 lines of other
failed package logs and GLib's Meson log into the retained Cloud step output.
Inspect **Run ci_pre_xcodebuild.sh script** when diagnosing native build failures.
The first archive compiles native dependencies from source and may take longer
than later builds. After changing the setup script, start a build from the new
@@ -586,6 +603,16 @@ Xcode removes the static archive from the embedded framework (it may insert a
small resource-framework stub) and preserves `PrivacyInfo.xcprivacy`, source
metadata and license texts. The application does not load a dynamic OpenSSL copy.
For builds using `DWARF with dSYM File`, the **Generate OpenSSL symbols** phase
runs after embedding. It verifies that Xcode's placeholder has no executable
code, generates `OpenSSL.framework.dSYM` from that exact binary, and checks its
UUIDs. This companion describes the empty resource stub, not the statically
linked OpenSSL implementation. Xcode includes it alongside the app's dSYM in
the archive so Organizer can upload symbols for every embedded Mach-O binary.
`verify_app_bundle.py` checks both UUID matches when given an archived app;
for an ordinary Release build, pass `--dsym-dir /path/to/Release-iphoneos`.
The CI ZIP includes both dSYM bundles.
The iOS-specific OpenSSL recipe disables POSIX metadata calls, automatic
`openssl.cnf` loading, and the unused file-URI store provider. It selects the
upstream `getrandom` entropy backend, which uses Darwin's `getentropy` on the
+10 -1
View File
@@ -13,8 +13,9 @@ if ! command -v brew >/dev/null 2>&1; then
fi
echo "Installing Xcode Cloud native build tools"
brew install xmake cmake python@3.13
brew install xmake cmake pkgconf python@3.13
BREW_PREFIX="$(brew --prefix)"
PKGCONF_PREFIX="$(brew --prefix pkgconf)"
PYTHON_PREFIX="$(brew --prefix python@3.13)"
# Match GitHub Actions' host Python dependencies without modifying Homebrew's
@@ -25,6 +26,14 @@ PYTHON_PREFIX="$(brew --prefix python@3.13)"
for tool in xmake xrepo cmake ctest cpack; do
ln -sf "${BREW_PREFIX}/bin/${tool}" "${HOST_TOOLS_DIR}/bin/${tool}"
done
# Meson needs the host pkg-config executable to find Xmake's iOS packages.
# Without it, GLib falls back to bundled PCRE2/libffi sources. Use the formula's
# prefix so an older pkg-config elsewhere on PATH cannot shadow this tool.
for tool in pkgconf pkg-config; do
ln -sf "${PKGCONF_PREFIX}/bin/${tool}" "${HOST_TOOLS_DIR}/bin/${tool}"
done
echo "Verifying Xcode Cloud host pkg-config"
"${HOST_TOOLS_DIR}/bin/pkg-config" --version
"${HOST_TOOLS_DIR}/bin/xmake" --version > "${HOST_TOOLS_DIR}/xmake-version.txt"
"${HOST_TOOLS_DIR}/bin/python3" -B "${IOS_DIR}/scripts/verify_native_build.py" \
+85
View File
@@ -0,0 +1,85 @@
#!/bin/bash
set -euo pipefail
# The shared CrossDeskMobile scheme archives Release for physical iOS devices.
# Leave other actions to their existing Xcode build phase and SDK selection.
if [[ "${CI_XCODEBUILD_ACTION:-}" != "archive" || "${CI_PRODUCT_PLATFORM:-}" != "iOS" ]]; then
echo "Skipping native prebuild for ${CI_XCODEBUILD_ACTION:-unknown} (${CI_PRODUCT_PLATFORM:-unknown})"
exit 0
fi
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
IOS_DIR="$(dirname "$SCRIPT_DIR")"
LOG_DIR="${IOS_DIR}/.xmake/xcode-cloud-logs"
mkdir -p "$LOG_DIR"
collect_dependency_logs() {
local log_root="$1"
local label="$2"
local log_file relative_path destination
[[ -d "$log_root" ]] || return 0
while IFS= read -r -d '' log_file; do
relative_path="${log_file#"${log_root}/"}"
destination="${LOG_DIR}/dependencies/${label}/${relative_path}"
mkdir -p "$(dirname "$destination")"
cp "$log_file" "$destination"
# Cloud does not publish arbitrary files as downloadable artifacts.
# Include GLib's complete install log in the retained step output, plus
# the tail of Meson and other failed package logs for context.
if [[ "$log_file" == */glib/*/logs/install.txt ]]; then
echo "GLib install log: ${log_file}"
cat "$log_file"
elif [[ "$log_file" == */installdir.failed/logs/* || \
"$log_file" == */glib/*/meson-logs/meson-log.txt ]]; then
echo "Last 200 lines: ${log_file}"
tail -n 200 "$log_file"
fi
done < <(find "$log_root" -type f \( \
-path '*/logs/*.txt' -o -path '*/meson-logs/meson-log.txt' \) -print0)
}
MONITOR_PID=""
finish() {
local build_exit_code=$?
trap - EXIT
set +e
if [[ -n "$MONITOR_PID" ]]; then
kill "$MONITOR_PID" 2>/dev/null
wait "$MONITOR_PID" 2>/dev/null
fi
if [[ "$build_exit_code" -ne 0 ]]; then
echo "iOS native prebuild failed with exit code ${build_exit_code}"
collect_dependency_logs "${XMAKE_GLOBALDIR:-${HOME}}/.xmake/cache/packages" cache
collect_dependency_logs "${IOS_DIR}/.xmake/packages" installed
echo "Native build diagnostics: ${LOG_DIR}"
fi
exit "$build_exit_code"
}
trap finish EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# Run outside xcodebuild so downloads and compiler output are streamed instead
# of buffered by a Run Script phase. Keep the step active during quiet commands.
(
SLEEP_PID=""
trap 'kill "${SLEEP_PID}" 2>/dev/null || true; wait "${SLEEP_PID}" 2>/dev/null || true; exit 0' TERM INT
while true; do
sleep 60 &
SLEEP_PID=$!
wait "$SLEEP_PID" || exit 0
echo "iOS native prebuild still running at $(date -u +%FT%TZ)"
ps -axo pid,ppid,state,etime,pcpu,comm | \
awk 'NR == 1 || /xmake|clang|cmake|ninja|meson|python|git|curl|make|zsh/' || true
done
) &
MONITOR_PID=$!
echo "Prebuilding iOS native dependencies for Release / iphoneos / arm64"
CONFIGURATION=Release PLATFORM_NAME=iphoneos CURRENT_ARCH=arm64 \
CROSSDESK_NATIVE_VERBOSE=1 \
"${IOS_DIR}/scripts/build_minirtc_ios.sh" 2>&1 | tee "${LOG_DIR}/ios-native-build.log"
echo "iOS native prebuild finished; Archive will reuse the native build products"
+6 -4
View File
@@ -50,10 +50,12 @@ fi
# tools again here instead of relying on exported PATH changes surviving.
if [[ "${CI_XCODE_CLOUD:-}" == "TRUE" ]]; then
CLOUD_HOST_BIN="${IOS_DIR}/.xmake/xcode-cloud-host/bin"
if [[ ! -x "${CLOUD_HOST_BIN}/xmake" || ! -x "${CLOUD_HOST_BIN}/python3" ]]; then
print -u2 "Xcode Cloud build tools are missing. Run ci_scripts/ci_post_clone.sh before building."
exit 69
fi
for host_tool in xmake python3 pkg-config; do
if [[ ! -x "${CLOUD_HOST_BIN}/${host_tool}" ]]; then
print -u2 "Xcode Cloud host tool ${host_tool} is missing. Run ci_scripts/ci_post_clone.sh before building."
exit 69
fi
done
export PATH="${CLOUD_HOST_BIN}:${PATH}"
fi
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Generate matching symbols for Xcode's embedded, codeless OpenSSL framework."""
import argparse
from pathlib import Path
import re
import subprocess
import sys
def uuids(path):
output = subprocess.check_output(["xcrun", "dwarfdump", "--uuid", str(path)], text=True)
result = dict((arch, uuid.upper()) for uuid, arch in
re.findall(r"UUID: ([0-9A-Fa-f-]{36}) \(([^)]+)\)", output))
if not result:
raise ValueError(f"No Mach-O UUIDs found: {path}")
return result
def verify_symbols(binary, dsym):
dwarf = dsym / "Contents/Resources/DWARF" / binary.name
if not dwarf.is_file():
raise ValueError(f"Missing dSYM DWARF file: {dwarf}")
if uuids(binary) != uuids(dwarf):
raise ValueError(f"dSYM UUIDs do not match {binary}: {dwarf}")
def generate(binary, output):
# This is only for Xcode's resource placeholder. Real OpenSSL code remains
# statically linked into the app and must not receive an empty dSYM here.
commands = subprocess.check_output(["xcrun", "otool", "-l", str(binary)], text=True)
text_sizes = re.findall(
r"sectname __text\s+segname __TEXT\s+addr \S+\s+size (0x[0-9a-fA-F]+)", commands)
if not text_sizes or any(int(size, 16) for size in text_sizes):
raise ValueError(f"Expected a codeless OpenSSL resource stub: {binary}")
output.parent.mkdir(parents=True, exist_ok=True)
# No function-level debug info exists in this empty stub. dsymutil still
# emits a valid UUID-matched DWARF companion; quiet suppresses that expected
# warning only after verifying that there is no executable code to lose.
subprocess.run(["xcrun", "dsymutil", "--quiet", str(binary), "-o", str(output)], check=True)
verify_symbols(binary, output)
subprocess.run(["xcrun", "dwarfdump", "--verify", str(output)], check=True)
print(f"Generated UUID-matched OpenSSL resource symbols: {output}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
generate(args.binary, args.output)
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.CalledProcessError) as error:
print(f"OpenSSL symbols: {error}", file=sys.stderr)
sys.exit(1)
+13 -2
View File
@@ -10,8 +10,10 @@ import re
import subprocess
import sys
from generate_openssl_symbols import verify_symbols
def verify(app, require_release=False):
def verify(app, require_release=False, dsym_dir=None):
info = plistlib.loads((app / "Info.plist").read_bytes())
binary = app / info["CFBundleExecutable"]
subprocess.run(["xcrun", "lipo", str(binary), "-verify_arch", "arm64"], check=True)
@@ -63,6 +65,14 @@ def verify(app, require_release=False):
sdk_symbols = subprocess.check_output(["xcrun", "nm", "-gU", str(embedded_binary)], text=True)
if re.search(r"\b_(?:SSL_new|OPENSSL_init_crypto)\b", sdk_symbols):
raise ValueError("Unexpected dynamic OpenSSL implementation in resource framework")
# Archive validation includes the exact files that Organizer uploads.
if dsym_dir is None and app.parents[2].suffix == ".xcarchive":
dsym_dir = app.parents[2] / "dSYMs"
if dsym_dir is not None:
verify_symbols(binary, dsym_dir / f"{app.name}.dSYM")
if embedded_binary.exists():
verify_symbols(embedded_binary, dsym_dir / "OpenSSL.framework.dSYM")
print("Verified app and embedded OpenSSL dSYM UUIDs")
linked = subprocess.check_output(["xcrun", "otool", "-L", str(binary)], text=True)
if "OpenSSL.framework" in linked:
raise ValueError("OpenSSL must be statically linked into the application")
@@ -79,8 +89,9 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("app", type=Path)
parser.add_argument("--require-release", action="store_true")
parser.add_argument("--dsym-dir", type=Path)
args = parser.parse_args()
verify(args.app, args.require_release)
verify(args.app.resolve(), args.require_release, args.dsym_dir)
if __name__ == "__main__":
+1
View File
@@ -0,0 +1 @@
dist/
+231
View File
@@ -0,0 +1,231 @@
# CrossDesk MCP
让本机 Agent 通过 MCP 观察并操作远端 CrossDesk,同时为用户提供浏览器、终端或 MCP Apps 监看面板。控制端不需要安装 CrossDesk 桌面客户端;被控端仍需运行兼容的 CrossDesk,并连接支持 `cli` 注册的信令服务器。
此目录实现 MCP 包 `@chunkdash/crossdesk-mcp` 0.1.0,绑定原生 CLI 包 0.2.0。**源码实现和本地打包不代表这些版本已经发布到 npm。** 发布后的安装示例需要以实际可用版本为准。
## 从源码运行
仓库根目录构建原生程序(已有工作区可保留原有桌面构建选项):
```sh
sh apps/cli/scripts/prepare-deps.sh
xmake f -y --CROSSDESK_BUILD_DESKTOP=n --CROSSDESK_BUILD_CLI=y --USE_CUDA=n -m release
xmake build crossdesk-cli
cd apps/mcp
npm ci
npm run build
```
Node.js 要求 22 或以上。在 Agent 宿主中配置本地 stdio 进程,例如 macOS arm64 源码构建:
```json
{
"mcpServers": {
"crossdesk": {
"command": "node",
"args": [
"/absolute/path/crossdesk/apps/mcp/dist/main.js",
"serve", "--stdio", "--panel=auto",
"--native-binary", "/absolute/path/crossdesk/build/macosx/arm64/release/crossdesk-cli"
]
}
}
}
```
Windows 和 Linux 使用各自构建产物路径;`--native-binary` 必须指向可信原生可执行程序,不接受 shell 命令。也可以通过 `CROSSDESK_NATIVE_BINARY` 显式指定开发产物。未指定时只从包内的固定版本平台依赖解析,不搜索 PATH。服务启动不连接远端、不打开浏览器;连接时才检查 `doctor` 协议并启动原生子进程。
发布包的配置形式:
```json
{
"mcpServers": {
"crossdesk": {
"command": "npx",
"args": ["-y", "@chunkdash/crossdesk-mcp@<已发布版本>", "serve", "--stdio", "--panel=auto"]
}
}
}
```
平台依赖覆盖 macOS arm64/x64、glibc Linux arm64/x64 和 Windows x64。安装时保留 optional dependencies;不需要另装全局 CLI。原生运行要求沿用 [CLI 分发文档](../cli/docs/npm-distribution.md)。`npm ci` 仅安装此源码目录的开发依赖,开发运行需使用 `--native-binary`;生成的发布包才包含固定平台依赖。
## 用户连接流程
1. 对 Agent 说“打开 CrossDesk”。`crossdesk_open` 创建 `view_id`,返回面板选择和等待用户状态。
2. 在面板选择已保存设备,或输入 9 位设备 ID;密码填写在面板里。可选择仅查看或允许 Agent 控制。
3. “保存设备”“记住密码”“允许以后自动连接”分别控制设备簿、系统凭据库、持久权限。后两项要求保存设备,默认均关闭。保存密码不自动授予控制权限。
4. 有待执行的远程任务时,Agent 在打开面板后立即调用 `crossdesk_get_session({view_id, wait_ms: 25000})` 等待连接。连接就绪后,工具直接返回会话 ID 和权限状态,Agent 继续任务;用户无需回到对话发送连接确认,也无需点击继续按钮。浏览器和 Apps 面板使用同一流程。
5. Agent 获取独立截图,用截图的 `observation_id` 和图像坐标提交动作。面板预览不消耗模型截图序列。
`crossdesk_open` 立即返回,让 Apps 宿主有机会渲染面板;等待连接在后续 `crossdesk_get_session` 调用中完成。按 `view_id` 查询默认最多等待 25 秒,`wait_ms: 0` 则立即查询;未就绪时返回 `wait_timed_out: true`,Agent 在原任务仍待执行时继续等待。按 `session_id` 查询仍立即返回。取消等待只取消本次查询,不断开用户正在建立或使用的连接。用户主动断开后返回 `closed`,Agent 停止等待,不自动重连。
面板发起的连接失败后,按 `view_id` 等待也会返回 `failed` 和错误码,避免 Agent 一直停留在等待用户状态。断开正在建立的连接会取消整个连接尝试。多个面板和 Agent 同时查询状态时共用一次原生查询,单次查询取消或暂时繁忙不会断开会话。`crossdesk_connect` 在连接成功但面板初始化失败时仍返回有效的 `session_id`,并附加 `panel_error`。
自动继续依赖宿主保持当前 Agent 任务及工具调用流程。它不通过网页伪造用户消息,也不承诺从已经结束的对话中主动唤醒 Agent;此类唤醒由宿主负责。
人工暂停由原生层锁定,模型不能通过 `set_control(true)` 恢复;只有当前授权面板的恢复按钮可以恢复。仅查看连接不能升级为控制连接,需重新连接并授权。关闭/隐藏面板仅停止预览,远程会话保留;断开按钮或 `crossdesk_disconnect` 才结束会话。
同一 MCP 进程默认只保留一个活动远程会话。相同配置目录中的进程用设备锁避免同时连接同一目标;它不协调另一个系统用户、另一份配置目录或独立桌面客户端。
## 面板策略
`--panel` 优先于设备配置中的 `panel`,默认 `auto`。
| 模式 | 行为 |
| --- | --- |
| `auto` | 有本机 GUI 时打开浏览器;无 GUI 且检测到终端环境时提供 CLI 画面入口;两者均无则使用 `off` |
| `apps` | 只使用 MCP Apps;能力不匹配返回 `PANEL_UNSUPPORTED` |
| `browser` | 只使用本地浏览器,不附加 Apps 工具资源元数据 |
| `terminal` | 提供独立终端 `view` 命令,共用当前 MCP 会话,不启动网页服务 |
| `off` | 不启动网页服务,保留截图和操作工具,凭据通过独立 `setup` 配置 |
`auto` 不再优先选择 MCP Apps;需要宿主内嵌面板时显式使用 `--panel=apps`。Apps 使用 `extensions["io.modelcontextprotocol/ui"].mimeTypes` 中的 `text/html;profile=mcp-app` 判断能力。旧协议读取 initialize 能力;2026-07-28 协议读取当前请求的能力,不按宿主产品名猜测支持情况。Apps 的卡片、侧栏或窗口形式由宿主决定。
Linux 根据 `DISPLAY` / `WAYLAND_DISPLAY` 判断 GUI;macOS 检查当前用户的桌面登录会话,SSH 会话不自动打开远端 Mac 的浏览器;Windows 排除 SSH 和 Services 会话。终端判断包含 TTY、`SSH_TTY` 和非 `dumb` 的 `TERM`,因为 MCP 的 stdin/stdout 通常是管道。环境变量被宿主清除或识别不适用时,可显式设置 `--panel=terminal` 或 `--panel=browser`。
终端模式的 `crossdesk_open` / `crossdesk_connect` 返回 `terminal_command`。用户在同一主机的另一个交互终端执行(源码运行时将 `crossdesk-mcp` 替换为 `node /absolute/path/apps/mcp/dist/main.js`):
```sh
crossdesk-mcp view --view <view_id> --config-dir <相同的配置目录>
```
该命令提供设备选择、隐藏密码输入和本次控制授权;已建立会话则直接显示画面。终端通过受限配置目录中的运行描述符和认证本地 IPC 复用 MCP 的原生连接,不启动第二个远程连接,也不占用 Agent 的终端或 MCP stdio。Agent 应展示命令供用户执行,再通过 `crossdesk_get_session` 等待;不能在工具输出捕获通道中运行 `view`。无交互终端时 `view` 返回 `VIEW_REQUIRES_TERMINAL`。
终端画面采用原生 CLI 的 ANSI 四分块渲染器,目标 8 FPS,最多 160 列 × 60 行,根据终端环境使用 8/256/真彩色。默认字符宽高比 0.5,可用 `--cell-aspect`(0.2–2)调整。此入口暂不使用 Kitty/Sixel。`p` 暂停 Agent、`r` 恢复已授权控制、`d` 断开、`q` / Ctrl+C 仅关闭画面并恢复终端;关闭画面后会话保留。暂停仍由原生层锁定,Agent 不能自行恢复。
浏览器/Apps 与终端均绘制 Agent 最后成功发送的鼠标位置,支持移动、点击、滚动和拖拽;坐标来自原生层对截图缩放及裁剪的映射。暂停或关闭控制时隐藏,切换显示器或图像尺寸变化时清除。该指针是 Agent 的操作位置提示,不代表远端输入执行 ACK,也不跟踪远端用户自己的鼠标。它不写入模型截图或源视频。
Apps 资源为 `ui://crossdesk/viewer.html`,工具只在允许使用 Apps 且当前请求支持时暴露 UI 元数据和面板专用接口。页面回报 `crossdesk_ui_ready` 后才标记就绪;10 秒未回报显示 `not_confirmed`,不自动弹第二个浏览器。用户明确要求回退时调用 `crossdesk_open_browser`;该工具不附带 Apps 元数据,`apps`/`off` 策略拒绝覆盖。
浏览器面板只监听随机端口的 `127.0.0.1`,与 MCP 服务同一进程。它不是 MCP Streamable HTTP,也不向局域网提供 MCP 接入。MCP、CLI、用户浏览器应在同一控制端电脑上运行;SSH 容器/远程宿主的浏览器转发不属于此本地接入模式。
页面标题为 CrossDesk MCP,仅保留正式应用标志,使用文字按钮和简洁状态提示。布局填满浏览器或宿主面板的可用宽高,远程画面保持原比例自动缩放;连接设置在高度不足时独立滚动。连接后侧栏显示设备与授权信息,暂停、恢复和断开按钮位于画面工具栏。「放大画面」收起侧栏,按 Esc 还原;窄屏默认显示连接表单,连接后显示画面,可用「连接信息」展开设备详情。界面资源均可离线使用,保存设备与持久授权仍由用户分别选择。
首次打开使用 URL fragment 中的短期一次性 bootstrap,页面立即清除 fragment,并换取 HttpOnly/SameSite cookie 和 CSRF 令牌。模型只收到无特权的网页地址。复制无凭据地址到另一浏览器不能获得会话控制权。
无法自动打开浏览器时,在自己的终端运行工具结果 `pairing_command` 中的命令和参数。例如:
```sh
crossdesk-mcp setup --open-panel --view <view_id> --config-dir <相同的配置目录>
```
通过源码运行时用 `node /absolute/path/apps/mcp/dist/main.js` 替换 `crossdesk-mcp`。配对通过本用户配置目录中的受限运行描述符和本地 IPC 完成,不允许匿名 HTTP 请求签发控制凭证。`setup` 使用用户终端的桌面环境打开浏览器;仍无法打开时,只在该交互终端显示 60 秒有效的一次性地址,不将它返回 MCP 或发送到聊天。面板最多保留 32 个视图;再次打开时会清理超过 30 分钟未使用的视图。浏览器会话最长 12 小时,失效后重新打开。
## 无面板配置与凭据
在用户自己的交互终端执行(不能在宿主 stdio 通道中交互输入密码):
```sh
crossdesk-mcp setup
```
配置默认存放于 `~/.config/crossdesk/mcp/`,可用 `--config-dir` 或 `CROSSDESK_MCP_CONFIG_DIR` 覆盖。`devices.json` 包含设备、面板/视频选项及凭据引用;密码保存到 macOS Keychain、Windows 凭据库或 Linux Secret Service。凭据库不可用就返回明确错误,没有明文文件降级。面板的临时连接仍可使用用户现场输入的密码。持久保存失败会保留已建立连接,并在面板显示错误。
也可在 `setup` 中指定外部密码环境变量名称,服务读取该变量作为凭据提供器。示例配置(没有密码值):
```json
{
"version": 1,
"panel": "off",
"server": "api.crossdesk.cn",
"port": 9099,
"devices": [{
"alias": "work-pc",
"device_id": "123456789",
"server": "api.crossdesk.cn",
"port": 9099,
"authorization": "control",
"credential": "environment",
"environment_variable": "MY_CROSSDESK_PASSWORD"
}]
}
```
授权范围和可用凭据缺一不可。模型不能提供任意 `device_id` 绕过面板确认;模型侧 `crossdesk_connect` 仅接受已授权设备别名。不要把密码发给 Agent,也不要把包含密码的命令行写进宿主配置。
Apps 依赖宿主遵守 app-only 工具可见性和 `_meta` 的模型不可见约定;服务另检查每个视图的随机 UI 能力令牌和 generation。app-only 标记本身不是可信身份凭据。能够读取同用户进程/文件或执行任意本机代码的 Agent 不受此边界隔离。
## 模型工具
| 工具 | 作用 |
| --- | --- |
| `crossdesk_open` | 打开设备选择/连接面板,返回 `view_id` |
| `crossdesk_open_browser` | 用户显式请求的浏览器入口/回退 |
| `crossdesk_list_devices` | 本机设备簿和授权摘要,不提供云发现 |
| `crossdesk_connect` | 通过别名连接已经授权且有凭据的设备 |
| `crossdesk_get_session` | `session_id`、`view_id` 严格二选一;按 `view_id` 可等待连接,`wait_ms` 范围 0–25000 |
| `crossdesk_screenshot` | 返回 PNG image content 和观测元数据 |
| `crossdesk_action` | 结构化输入,可附带动作之后的截图 |
| `crossdesk_set_control` | 在已授权范围内启停 Agent 输入 |
| `crossdesk_select_display` | 切换显示器,使旧观测失效 |
| `crossdesk_disconnect` | 断开并释放输入状态、子进程和设备锁 |
动作包括 `move`、`click`、`double_click`、`scroll`、`drag`、`key_press`、`hotkey`、`type_text`。不提供 shell、任意键按下保持、剪贴板或文件操作。按键使用 Windows VK 对应的标准名称:`A`–`Z`、`0`–`9`、`F1`–`F12`、`CTRL`、`ALT`、`SHIFT`、`META`、`ENTER`、`ESC`、方向键等;应用快捷键仍需根据远端系统选择。
鼠标动作和 `key_press` 支持可选的 `modifiers: ["CTRL", "ALT", "SHIFT", "META"]`(选择需要的键,不能重复),用于组合点击、选择、拖拽和快捷键。修饰键仅在本次动作期间保持,结束、取消或人工暂停时释放。`drag` 可指定 `button: "left" | "right" | "middle"`,默认左键。标点键支持 `SEMICOLON`、`EQUAL`、`COMMA`、`MINUS`、`PERIOD`、`SLASH`、`BACKQUOTE`、`BRACKET_LEFT`、`BACKSLASH`、`BRACKET_RIGHT`、`QUOTE`;这些是 VK 键位名称,实际字符取决于远端键盘布局,输入文字应使用 `type_text`。例如:
```json
{"session_id":"…","operation_id":"select-item-1","observation_id":"…","action":{"type":"click","x":120,"y":80,"modifiers":["SHIFT"]}}
```
截图默认最长边 1280,最大 2048;允许指定源帧像素区域。返回 `source_size`、`source_rect`、`image_size`、`generation`、`geometry_epoch`、`frame_id`、`frame_age_ms` 和 `observation_id`。动作坐标使用返回图像坐标,不使用浏览器 CSS 像素。观测保留最多 32 个,30 秒过期;切换显示器、连接代际或图像几何变化立即失效。截图使用不超过 2 秒的帧,PNG 不超过 2 MiB,必要时继续缩小输出并返回真实尺寸。
`timeout_ms` 限制等待可用帧的时间,PNG 编码独立执行;`0` 表示只使用当前已就绪的新鲜帧,无帧返回 `FRAME_TIMEOUT`,编码器繁忙返回 `BUSY`。截图按到达顺序处理,并优先于预览。视频超过 2 秒未更新时拒绝新的键鼠输入,恢复新鲜画面后可继续;已提交操作的去重查询仍可读取原结果。
`operation_id` 在当前原生会话中缓存最近 128 个操作,至少在未被容量淘汰的 5 分钟窗口内支持同参数查询;不同参数复用 ID 返回冲突。`submitted` 仅说明本地发送完成,远端没有执行 ACK。超时、断网、取消或发送失败可能返回 `outcome_unknown`/`side_effect_possible`,禁止自动重放。`observe_after` 默认开启,后续图像只证明取得更新帧,不证明操作执行成功。
## 实时视频与按需截图
实时视频提供两条路径,默认 `browser`,两条路径均由原生 CLI 的本机 WebSocket 直接发送给浏览器。Node 只处理会话、授权票据和 MCP 工具,不读取或转发实时视频字节;不再创建视频管道,不经过 MCP stdio 或模型上下文,不逐帧转 PNG、不重新编码视频。
| `video.decode_path` | 画面路径 |
| --- | --- |
| `browser` | MiniRTC 输出原始 H.264 Annex B → 浏览器 WebCodecs 解码 → canvas |
| `minirtc` | MiniRTC 解码 → 紧凑 NV12 原始帧 → 浏览器 VideoFrame / canvas;浏览器不再解码 H.264 |
`video.decoder` 默认 `auto`:优先使用可用硬件解码器,不支持时使用软件。`software` 禁用本程序的硬件选择与硬件回退。浏览器路径使用 WebCodecs 的 `prefer-hardware` / `prefer-software`;这些值是浏览器 API 的偏好,浏览器可以忽略,不能据此宣称已确认物理硬件或软件后端。原生路径由 MiniRTC 的解码器工厂选择,本机 macOS 使用 VideoToolbox 或 OpenH264;其他平台使用 MiniRTC 已支持的后端。状态中的 `native_video_decoder` 返回 MiniRTC 报告的后端名称(统计可用前为空),不代表浏览器后端。
在 `~/.config/crossdesk/mcp/devices.json` 的根对象中加入:
```json
"video": {
"decode_path": "minirtc",
"decoder": "auto"
}
```
也可在 Agent 宿主的 MCP 启动参数中配置,命令行优先于文件:
```sh
crossdesk-mcp serve --stdio --video-path browser --video-decoder auto
crossdesk-mcp serve --stdio --video-path minirtc --video-decoder software
```
修改后重启 MCP,再建立连接。选项适用于整个 MCP 进程,两条路径均将解码选项传给原生端;浏览器路径中的原生解码用于截图缓存。截图工具或动作后的截图请求才触发 PNG 编码。这里配置的是控制端解码器,不更改远端编码器。原有配置文件无需新增字段即可继续使用。
Agent 模式默认请求高帧率档位,分辨率上限 1920 × 1080;实际分辨率和帧率由远端能力、网络和本机解码性能决定。面板显示实际尺寸与呈现 FPS。浏览器路径需要 WebCodecs H.264 解码能力;MiniRTC 路径仅需浏览器支持从 NV12 创建 VideoFrame 并绘制。能力不足时明确报错,不自动退回 PNG 轮询。NV12 不压缩,1080p / 30 FPS 约需 93 MB/s 本机传输,4K / 30 FPS 约需 373 MB/s;它不增加远端到控制端的 H.264 网络码率。移除 Node 转发没有消除 NV12 自身的本机传输与浏览器像素处理开销;这不是 GPU 零拷贝。
视频 WebSocket 在原生 CLI 的独立 I/O 线程中运行,只监听随机 `127.0.0.1` 端口,与 Node 面板 HTTP 端口不同。浏览器面板通过 cookie/CSRF 授权获取视频票据,Apps 通过 app-only `crossdesk_video_open` 和视图令牌获取。票据 15 秒内一次性有效,绑定视图、会话和代际,通过 WebSocket 第一条消息提交,不写入 URL、日志或模型可见工具结果。WebSocket 只提供画面、收帧 ACK 和关键帧恢复请求,不能执行远端输入操作。最多 8 个活动观看者。H.264 丢帧后等待关键帧恢复;NV12 每帧独立,每个观看者最多一帧未确认,原生发送队列只保留最新画面;H.264 最多 8 帧未确认并受字节阈值限制。10 秒未确认最早一帧则关闭该视频通道,不阻塞其他观看者或 MCP 控制。视图撤销、显示器/连接代际变化、断开和进程退出会关闭对应视频连接;暂停 Agent 控制仍继续播放。页面隐藏或卸载时释放视频订阅,恢复可见时重新订阅。
浏览器页面和 MCP Apps 资源的 CSP 允许原生服务使用的 `ws://127.0.0.1:*`(仅动态端口),HTTP 控制仍限制到 Node 面板的确切地址。原生服务另外校验确切 Host、Origin 和一次性票据。宿主仍可能限制 loopback、WebSocket、WebCodecs 或 iframe 权限;视频失败时提供重试和浏览器入口,`--panel=apps` 的严格策略仍禁止浏览器回退。浏览器和 Apps 共用同一播放器,具体宿主需要独立验收。
## 打包
```sh
npm run build
npm run pack:npm -- --out-dir /absolute/path/artifacts
```
脚本生成可发布 tarball,包含面板、运行代码、源代码、许可和固定版本的五个平台可选依赖。CI 的 `MCP package` 工作流仅构建并上传 `mcp-package`,不发布 npm。原生包继续由 CLI 工作流构建,`doctor` 必须同时声明自动化协议和 `automation_video_protocols: ["h264-annexb/1", "nv12/1"]` 和 `automation_video_decoders: ["auto", "software"]`,以及 `automation_video_transport: "loopback-websocket/1"`、`automation_terminal_protocol: "ansi/1"`;先发布对应 0.2.0 平台包,再发布 MCP tarball。尚未进行真实跨平台发布/远端验收时,不应把构建成功等同于各宿主和设备上的联调完成。
从发布 tarball 重建 TypeScript/面板时,将包中的 `build-package.json` 复制为 `package.json`,运行 `npm ci && npm run build`。原生源码和依赖来源随平台包提供,详见 [源码来源](../cli/docs/source-provenance.md)。
## 本地审阅验证(2026-11-03)
动作参数校验和输入步骤生成集中在 `apps/cli/automation_protocol.*`,主循环负责调度、取消和权限检查。截图按色度网格对齐后仅转换所需区域,PNG 在容量受限的缓冲区中单次压缩;原生帧仅在没有其他读取者时复用内存。Node 按行累计响应字节,在完整响应到达时解码,避免反复扫描和复制大截图。
本机 macOS arm64 完成 TypeScript/面板构建、原生 CLI 构建、现有 wire/keyboard-state 测试,以及工程外的 MCP、会话和原生动作回归检查。ASan/UBSan 检查覆盖动作调度和输入清理;140 组随机图像覆盖完整帧、奇偶裁剪边界、缩放及容量回退,优化前后 PNG 字节一致。
使用 1920 × 1080 合成 NV12、最长边 1280、每项 6 次的 `-O2` 本地基准:完整画面编码约 22.5 → 11.5 ms,321 × 241 裁剪约 2.1 → 0.9 ms。数字仅衡量图像转换与编码,不包含网络、解码、远端执行或宿主渲染;未连接真实远端或完成 Windows/Linux 验收。额外测试代码、脚本、数据和产物均存放于工程外系统临时目录。
+977
View File
@@ -0,0 +1,977 @@
{
"name": "@chunkdash/crossdesk-mcp",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@chunkdash/crossdesk-mcp",
"version": "0.1.0",
"license": "GPL-3.0-only",
"dependencies": {
"@modelcontextprotocol/client": "2.4.0",
"@modelcontextprotocol/core": "2.4.0",
"@modelcontextprotocol/ext-apps": "2.0.4",
"@modelcontextprotocol/server": "2.4.0",
"@napi-rs/keyring": "2.1.2",
"zod": "4.6.7"
},
"bin": {
"crossdesk-mcp": "dist/main.js"
},
"devDependencies": {
"@types/node": "22.19.15",
"esbuild": "0.28.2",
"typescript": "5.9.3"
},
"engines": {
"node": ">=22"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@modelcontextprotocol/client": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",
"integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",
"license": "Apache-2.0",
"dependencies": {
"@modelcontextprotocol/core": "2.4.0",
"cross-spawn": "^7.0.5",
"eventsource": "^3.0.2",
"eventsource-parser": "^3.0.8",
"jose": "^6.1.3",
"pkce-challenge": "^5.0.0",
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@modelcontextprotocol/core": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
"integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
"license": "Apache-2.0",
"dependencies": {
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@modelcontextprotocol/ext-apps": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.4.tgz",
"integrity": "sha512-B+PcbuGiaf0e5I3uy4iO5tS3Abo+5w8JvZFzHMzQdq9yVwP836zJkw2+KCGOQ0r4TM1fuQi4JdnbuWjkS4aBvg==",
"license": "MIT",
"workspaces": [
"examples/*"
],
"dependencies": {
"@standard-schema/spec": "^1.1.0"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
"zod": "^4.2.0"
},
"peerDependenciesMeta": {
"@modelcontextprotocol/server": {
"optional": true
},
"react": {
"optional": true
},
"react-dom": {
"optional": true
}
}
},
"node_modules/@modelcontextprotocol/server": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz",
"integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==",
"license": "Apache-2.0",
"dependencies": {
"@modelcontextprotocol/core": "2.4.0",
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@napi-rs/keyring": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring/-/keyring-2.1.2.tgz",
"integrity": "sha512-9i1SR6tYeQ3o1beLeVMxhN6Fq513m9TZlTs+46+4JgvSNkaFoW9S4WrpV5MjzE+0CzVoC+dZ4RfZDIgW6+afnQ==",
"license": "MIT",
"engines": {
"node": ">= 10"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"optionalDependencies": {
"@napi-rs/keyring-darwin-arm64": "2.1.2",
"@napi-rs/keyring-darwin-x64": "2.1.2",
"@napi-rs/keyring-freebsd-x64": "2.1.2",
"@napi-rs/keyring-linux-arm-gnueabihf": "2.1.2",
"@napi-rs/keyring-linux-arm64-gnu": "2.1.2",
"@napi-rs/keyring-linux-arm64-musl": "2.1.2",
"@napi-rs/keyring-linux-riscv64-gnu": "2.1.2",
"@napi-rs/keyring-linux-x64-gnu": "2.1.2",
"@napi-rs/keyring-linux-x64-musl": "2.1.2",
"@napi-rs/keyring-win32-arm64-msvc": "2.1.2",
"@napi-rs/keyring-win32-ia32-msvc": "2.1.2",
"@napi-rs/keyring-win32-x64-msvc": "2.1.2"
}
},
"node_modules/@napi-rs/keyring-darwin-arm64": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-darwin-arm64/-/keyring-darwin-arm64-2.1.2.tgz",
"integrity": "sha512-vsInUWUzWS6/WzR/TFNwmdtmwKWjnnR8TOpvZ/pjjxDAkJB/waz37PWzp2b8AFcw1aCcq2aQ7k2vvbLQy8pTrw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-darwin-x64": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-darwin-x64/-/keyring-darwin-x64-2.1.2.tgz",
"integrity": "sha512-wQihYroaQ3r++R6u5c9Gj0TCw1l1F53LCb5aLOXfVvT4DsnDnpe7p7VGYo4/33bLe0iqVevtAj+ET3yKCtOlJQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-freebsd-x64": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-freebsd-x64/-/keyring-freebsd-x64-2.1.2.tgz",
"integrity": "sha512-Ve5ha7MbJsq+4TYyXYiTy4IeZOnYxkBB05uH2+nIrEKBkHmyfHttF814EfWAfoJa63KqBhYRXdYJo0o1WVL2sg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-linux-arm-gnueabihf": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-arm-gnueabihf/-/keyring-linux-arm-gnueabihf-2.1.2.tgz",
"integrity": "sha512-zxijTnVnTApEyJMjgnLdVQL1g1DAudku/5brrWNDRWj4J0q0nFhUZEtzUA+nY2FvgDjl4s+2YCZYXSTH4TFMUg==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-linux-arm64-gnu": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-arm64-gnu/-/keyring-linux-arm64-gnu-2.1.2.tgz",
"integrity": "sha512-PM+SAcl/yGzgGbeeCsKrnlG4T5DBIDjmDqtKm5an1bJz0o0gwSzR3BMiXf04JenkcqascZpdcIReoEvLj0cvCw==",
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-linux-arm64-musl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-arm64-musl/-/keyring-linux-arm64-musl-2.1.2.tgz",
"integrity": "sha512-+ERS9oyInPCALN957cViBDbYJc724/Q+rZ8ZAz4rOHj4B4v0VR4OAWThdYZgZqD54sZVV0MdyX24qva97hYoAQ==",
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-linux-riscv64-gnu": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-riscv64-gnu/-/keyring-linux-riscv64-gnu-2.1.2.tgz",
"integrity": "sha512-pGADtqeT3U1SaFZGjkVsmZVjeNOQx0fr77S+NWszXjZboyaUOLlGKgqG6ssAWzcwxv8uPhKc9Ij17ujNZhSqLw==",
"cpu": [
"riscv64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-linux-x64-gnu": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-x64-gnu/-/keyring-linux-x64-gnu-2.1.2.tgz",
"integrity": "sha512-Fj5TmTnl2oriuCT5DDEYlhgxYes20uGfgOg10LK9PyPVsI8/PQ1m8I4rq/4A5hkrMtY7wvFb70YmX/yPHDYWvQ==",
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-linux-x64-musl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-linux-x64-musl/-/keyring-linux-x64-musl-2.1.2.tgz",
"integrity": "sha512-C+KhAeU6x2A43FV3dOmMvUraJb8zsC9VZfsunjZ1cgtuAb208TALaUuAY0jThOphXqhyhBJOs2xTCQhOrRkJIw==",
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-win32-arm64-msvc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-win32-arm64-msvc/-/keyring-win32-arm64-msvc-2.1.2.tgz",
"integrity": "sha512-kBq80ZZfjXoa5wHG9kgAVhYYjaPOLgHh5ngt7r1ftwFXPXDPXKH7oM2r2j2Q64cs0pVtmodVtn5Q9e6xCwzQUQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-win32-ia32-msvc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-win32-ia32-msvc/-/keyring-win32-ia32-msvc-2.1.2.tgz",
"integrity": "sha512-bhgKvVbWlZ6iR/tmvb2ht6/o0OzarUX9W7hjg+G+eVdGjR1prwtQ9lYo5ZESdn/+zyF1MIFvHkOCGja9YqDcww==",
"cpu": [
"ia32"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@napi-rs/keyring-win32-x64-msvc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@napi-rs/keyring-win32-x64-msvc/-/keyring-win32-x64-msvc-2.1.2.tgz",
"integrity": "sha512-yQtFdfuwqM0ezKlYO6r2n44in2LGzd4MC679Ddhvojip3t1hn+q/4I+gJU+cIJQVd5FAZSKNrK4tGfew3UTpAQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@standard-schema/spec": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "22.19.15",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.15.tgz",
"integrity": "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/esbuild": {
"version": "0.28.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.2",
"@esbuild/android-arm": "0.28.2",
"@esbuild/android-arm64": "0.28.2",
"@esbuild/android-x64": "0.28.2",
"@esbuild/darwin-arm64": "0.28.2",
"@esbuild/darwin-x64": "0.28.2",
"@esbuild/freebsd-arm64": "0.28.2",
"@esbuild/freebsd-x64": "0.28.2",
"@esbuild/linux-arm": "0.28.2",
"@esbuild/linux-arm64": "0.28.2",
"@esbuild/linux-ia32": "0.28.2",
"@esbuild/linux-loong64": "0.28.2",
"@esbuild/linux-mips64el": "0.28.2",
"@esbuild/linux-ppc64": "0.28.2",
"@esbuild/linux-riscv64": "0.28.2",
"@esbuild/linux-s390x": "0.28.2",
"@esbuild/linux-x64": "0.28.2",
"@esbuild/netbsd-arm64": "0.28.2",
"@esbuild/netbsd-x64": "0.28.2",
"@esbuild/openbsd-arm64": "0.28.2",
"@esbuild/openbsd-x64": "0.28.2",
"@esbuild/openharmony-arm64": "0.28.2",
"@esbuild/sunos-x64": "0.28.2",
"@esbuild/win32-arm64": "0.28.2",
"@esbuild/win32-ia32": "0.28.2",
"@esbuild/win32-x64": "0.28.2"
}
},
"node_modules/eventsource": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
"integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
"license": "MIT",
"dependencies": {
"eventsource-parser": "^3.0.1"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/eventsource-parser": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
"integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/jose": {
"version": "6.2.15",
"resolved": "https://registry.npmjs.org/jose/-/jose-6.2.15.tgz",
"integrity": "sha512-qdF6ewcZARtef63fJ9AKKZPgxw+t7USH6HLXYcD4CrdmSvDp79rpJSPFEKc90QBeGS63u1KQtN2MZQHC0yDIzA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/pkce-challenge": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
"integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
"license": "MIT",
"engines": {
"node": ">=16.20.0"
}
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
+38
View File
@@ -0,0 +1,38 @@
{
"name": "@chunkdash/crossdesk-mcp",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Local CrossDesk MCP tools and remote desktop panels",
"license": "GPL-3.0-only",
"author": "DI JUNKUN",
"repository": {
"type": "git",
"url": "git+https://github.com/kunkundi/crossdesk.git",
"directory": "apps/mcp"
},
"engines": {
"node": ">=22"
},
"bin": {
"crossdesk-mcp": "dist/main.js"
},
"scripts": {
"build": "tsc && tsc -p tsconfig.ui.json && node scripts/build-ui.mjs",
"check": "tsc --noEmit && tsc -p tsconfig.ui.json",
"pack:npm": "node scripts/pack.mjs"
},
"dependencies": {
"@modelcontextprotocol/client": "2.4.0",
"@modelcontextprotocol/core": "2.4.0",
"@modelcontextprotocol/ext-apps": "2.0.4",
"@modelcontextprotocol/server": "2.4.0",
"@napi-rs/keyring": "2.1.2",
"zod": "4.6.7"
},
"devDependencies": {
"@types/node": "22.19.15",
"esbuild": "0.28.2",
"typescript": "5.9.3"
}
}
+35
View File
@@ -0,0 +1,35 @@
import { build } from "esbuild";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
// Unmodified apps/desktop/resources/linux/crossdesk_128x128.png.
// Keep a local copy so the npm source package rebuilds without desktop assets.
const logo = "data:image/png;base64," +
(await readFile(resolve(root, "ui/assets/crossdesk.png"))).toString("base64");
await mkdir(resolve(root, "dist"), { recursive: true });
for (const mode of ["apps", "browser"]) {
const result = await build({
entryPoints: [resolve(root, "ui/viewer.ts")],
bundle: true,
minify: true,
platform: "browser",
target: "es2022",
outfile: "viewer.js",
write: false,
define: {
CROSSDESK_APPS: String(mode === "apps"),
CROSSDESK_LOGO: JSON.stringify(logo),
},
});
const script = result.outputFiles
.find((f) => f.path.endsWith(".js"))
.text.replaceAll("</script", "<\\/script");
const css = result.outputFiles.find((f) => f.path.endsWith(".css")).text;
const nonce = mode === "browser" ? ' nonce="__CROSSDESK_NONCE__"' : "";
await writeFile(
resolve(root, `dist/viewer-${mode}.html`),
`<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#ffffff"><link rel="icon" type="image/png" href="${logo}"><title>CrossDesk MCP</title><style${nonce}>${css}</style></head><body><div id="app"></div><script${nonce}>${script}</script></body></html>`,
);
}
+107
View File
@@ -0,0 +1,107 @@
import {
mkdtemp,
readFile,
writeFile,
mkdir,
cp,
chmod,
rm,
access,
} from "node:fs/promises";
import { dirname, resolve, join } from "node:path";
import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
import { execFileSync } from "node:child_process";
import { parseArgs } from "node:util";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const repository = resolve(root, "../..");
const { values } = parseArgs({ options: { "out-dir": { type: "string" } } });
const output = resolve(values["out-dir"] ?? join(repository, "build/npm-mcp"));
const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
const cli = JSON.parse(
await readFile(join(root, "../cli/package.json"), "utf8"),
);
const platforms = JSON.parse(
await readFile(join(root, "../cli/npm/platforms.json"), "utf8"),
);
const native = await import(new URL("../dist/native.js", import.meta.url));
if (native.NATIVE_VERSION !== cli.version)
throw new Error("MCP and CLI native versions must match.");
for (const file of ["main.js", "viewer-browser.html", "viewer-apps.html"])
await access(join(root, "dist", file));
const staging = await mkdtemp(join(tmpdir(), "crossdesk-mcp-pack-"));
try {
for (const entry of [
"dist",
"src",
"ui",
"scripts",
"tsconfig.json",
"tsconfig.ui.json",
"package-lock.json",
"README.md",
])
await cp(join(root, entry), join(staging, entry), { recursive: true });
await cp(join(repository, "LICENSE"), join(staging, "LICENSE"));
await writeFile(
join(staging, "build-package.json"),
JSON.stringify(project, null, 2) + "\n",
);
const manifest = {
...project,
private: false,
files: [
"dist",
"src",
"ui",
"scripts/build-ui.mjs",
"tsconfig.json",
"tsconfig.ui.json",
"build-package.json",
"package-lock.json",
"README.md",
"LICENSE",
],
optionalDependencies: Object.fromEntries(
Object.values(platforms).map((p) => [p.packageName, cli.version]),
),
publishConfig: { access: "public" },
};
delete manifest.scripts;
delete manifest.devDependencies;
await writeFile(
join(staging, "package.json"),
JSON.stringify(manifest, null, 2) + "\n",
);
await chmod(join(staging, "dist/main.js"), 0o755);
await mkdir(output, { recursive: true });
const filename = `${project.name.replace(/^@/, "").replace("/", "-")}-${project.version}.tgz`;
try {
await access(join(output, filename));
throw new Error(`Output already exists: ${filename}`);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const args = [
"pack",
"--json",
"--ignore-scripts",
"--pack-destination",
output,
];
if (process.platform === "win32" && !process.env.npm_execpath)
throw new Error("On Windows use npm run pack:npm.");
const result = execFileSync(
process.env.npm_execpath ? process.execPath : "npm",
process.env.npm_execpath ? [process.env.npm_execpath, ...args] : args,
{ cwd: staging, encoding: "utf8" },
);
const parsed = JSON.parse(result);
const packages = Array.isArray(parsed) ? parsed : Object.values(parsed);
if (packages.length !== 1 || packages[0].filename !== filename)
throw new Error("Unexpected package archive.");
process.stdout.write(join(output, filename) + "\n");
} finally {
await rm(staging, { recursive: true, force: true });
}

Some files were not shown because too many files have changed in this diff Show More