mirror of
https://github.com/kunkundi/crossdesk.git
synced 2026-10-16 00:33:22 +08:00
Compare commits
35
Commits
572a018a72
...
v1.6.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
149d20cbd1 | ||
|
|
b935df917f | ||
|
|
fab7edeff1 | ||
|
|
85ca13aa75 | ||
|
|
ff7bda6988 | ||
|
|
380a2a225c | ||
|
|
a535ded76d | ||
|
|
fc67a1543c | ||
|
|
31acb6b2f0 | ||
|
|
2d1241c0a0 | ||
|
|
0031c411e5 | ||
|
|
bc8dbcbf68 | ||
|
|
2d49024bd6 | ||
|
|
597c1dd2c9 | ||
|
|
a83b6badd0 | ||
|
|
6a71a3173a | ||
|
|
c345c69e81 | ||
|
|
f8535a797b | ||
|
|
163506f81e | ||
|
|
a4baca222c | ||
|
|
3992ea56db | ||
|
|
51d392ef48 | ||
|
|
f347fc2387 | ||
|
|
0b28d1bc99 | ||
|
|
e894f4a763 | ||
|
|
e65a30e969 | ||
|
|
52f6f23f93 | ||
|
|
3d2235ad4e | ||
|
|
0b2eb5b106 | ||
|
|
94760b2a3c | ||
|
|
bbbcfb9d6f | ||
|
|
9ef64cc00f | ||
|
|
b8389a8aa0 | ||
|
|
7ac8163931 | ||
|
|
704938a157 |
+40
-17
@@ -375,6 +375,16 @@ jobs:
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Select corresponding source tag
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
|
||||
echo "CROSSDESK_SOURCE_TAG=${GITHUB_REF_NAME}" >> "${GITHUB_ENV}"
|
||||
echo "CROSSDESK_RELEASE_BUILD=YES" >> "${GITHUB_ENV}"
|
||||
fi
|
||||
|
||||
- name: Read independent iOS version
|
||||
id: ios_version
|
||||
@@ -403,15 +413,23 @@ jobs:
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: apps/ios/.xmake/packages
|
||||
key: "${{ runner.os }}-xmake${{ env.XMAKE_VERSION }}-deps-ios-arm64-xcode26.6-xrepo1211093-min16-${{ github.run_id }}"
|
||||
key: "${{ runner.os }}-xmake${{ env.XMAKE_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-${{ github.run_id }}"
|
||||
restore-keys: |
|
||||
${{ runner.os }}-xmake${{ env.XMAKE_VERSION }}-deps-ios-arm64-xcode26.6-xrepo1211093-min16-
|
||||
${{ runner.os }}-xmake${{ env.XMAKE_VERSION }}-deps-ios-arm64-source-v1-xcode26.6-xrepo1211093-min16-
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.13"
|
||||
|
||||
- name: Verify iOS license catalog
|
||||
run: |
|
||||
python3 -B -m unittest discover -s apps/ios/tests -p 'third_party_licenses_test.py' -v
|
||||
python3 -B apps/ios/scripts/generate_third_party_licenses.py
|
||||
|
||||
- name: Verify iOS privacy controls
|
||||
run: python3 -B -m unittest discover -s apps/ios/tests -p 'privacy_controls_test.py' -v
|
||||
|
||||
- name: Install xmake
|
||||
uses: xmake-io/github-action-setup-xmake@v1
|
||||
with:
|
||||
@@ -477,6 +495,11 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERIFY_FLAGS=()
|
||||
if [[ "${CROSSDESK_RELEASE_BUILD:-NO}" == "YES" ]]; then
|
||||
VERIFY_FLAGS+=(--require-release)
|
||||
fi
|
||||
python3 apps/ios/scripts/verify_app_bundle.py "${APP_PATH}" "${VERIFY_FLAGS[@]}"
|
||||
xcrun lipo -info "${EXECUTABLE_PATH}"
|
||||
echo "Minimum iOS version: ${MINIMUM_OS}"
|
||||
|
||||
@@ -489,6 +512,9 @@ jobs:
|
||||
|
||||
mkdir -p "${PACKAGE_DIR}"
|
||||
cp -R "${APP_PATH}" "${PACKAGE_DIR}/"
|
||||
cp apps/ios/licenses/sources.json "${PACKAGE_DIR}/ThirdPartySources.json"
|
||||
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
|
||||
@@ -689,7 +715,8 @@ jobs:
|
||||
@("crossdesk_service.exe", "crossdesk_service.exe"),
|
||||
@("crossdesk_session_helper.exe", "crossdesk_session_helper.exe"),
|
||||
@("crossdesk_privacy_cursor_helper.exe", "crossdesk_privacy_cursor_helper.exe"),
|
||||
@("crossdesk_privacy_window.dll", "crossdesk_privacy_window.dll")
|
||||
@("crossdesk_privacy_window.dll", "crossdesk_privacy_window.dll"),
|
||||
@("slint_cpp.dll", "slint_cpp.dll")
|
||||
)
|
||||
|
||||
foreach ($file in $portableFiles) {
|
||||
@@ -791,23 +818,19 @@ jobs:
|
||||
echo "PATCH_NUMBER=${PATCH_NUMBER}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Prepare release notes
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.version.outputs.VERSION_WITH_V }}
|
||||
VERSION_BASE: ${{ steps.version.outputs.VERSION_BASE }}
|
||||
run: |
|
||||
if [[ -f "docs/releases/${RELEASE_TAG}.md" ]]; then
|
||||
cp "docs/releases/${RELEASE_TAG}.md" release-notes.md
|
||||
elif [[ -f "docs/releases/v${VERSION_BASE}.md" ]]; then
|
||||
cp "docs/releases/v${VERSION_BASE}.md" release-notes.md
|
||||
else
|
||||
cat > release-notes.md << 'EOF'
|
||||
Binary release only. Source code is not included.
|
||||
cat > "$RUNNER_TEMP/release-notes.md" << EOF
|
||||
## Corresponding source
|
||||
|
||||
Source for these binaries: [${GITHUB_REF_NAME}](https://github.com/${GITHUB_REPOSITORY}/tree/${GITHUB_SHA}).
|
||||
Clone that version with recursive submodules. The repository includes the build scripts and dependency patches.
|
||||
[iOS source, modification and rebuild instructions](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_SHA}/apps/ios/README.md).
|
||||
The iOS archive also contains the exact source revision and third-party source catalog with archive checksums.
|
||||
|
||||
## Code signing policy
|
||||
|
||||
Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).
|
||||
EOF
|
||||
fi
|
||||
|
||||
- name: Rename artifacts
|
||||
run: |
|
||||
@@ -833,7 +856,7 @@ jobs:
|
||||
prerelease: false
|
||||
files: release/*
|
||||
generate_release_notes: false
|
||||
body_path: release-notes.md
|
||||
body_path: ${{ runner.temp }}/release-notes.md
|
||||
|
||||
- name: Create or update 'latest' tag
|
||||
run: |
|
||||
@@ -851,7 +874,7 @@ jobs:
|
||||
prerelease: false
|
||||
files: release/*
|
||||
generate_release_notes: false
|
||||
body_path: release-notes.md
|
||||
body_path: ${{ runner.temp }}/release-notes.md
|
||||
|
||||
- name: Upload artifacts to server
|
||||
uses: burnett01/rsync-deployments@5.2
|
||||
@@ -903,7 +926,7 @@ jobs:
|
||||
}
|
||||
EOF
|
||||
jq --arg release_name "Release ${{ steps.version.outputs.VERSION_WITH_V }}" \
|
||||
--rawfile release_notes release-notes.md \
|
||||
--rawfile release_notes "$RUNNER_TEMP/release-notes.md" \
|
||||
'.releaseName = $release_name | .releaseNotes = $release_notes' \
|
||||
version.json > version-with-notes.json
|
||||
mv version-with-notes.json version.json
|
||||
|
||||
+107
-59
@@ -1,99 +1,147 @@
|
||||
# CrossDesk Privacy Policy
|
||||
|
||||
Last updated: August 8, 2026
|
||||
Last updated: September 28, 2026
|
||||
|
||||
[中文](#中文) | [English](#english)
|
||||
|
||||
## 中文
|
||||
|
||||
### 适用范围
|
||||
更新日期:2026 年 9 月 28 日
|
||||
|
||||
本隐私政策适用于 CrossDesk 桌面客户端及项目提供的默认网络服务。用户自行部署或指定的服务器由相应服务器运营者负责,其数据处理方式不在本政策控制范围内。
|
||||
CrossDesk 重视您的个人信息与隐私保护。本政策说明我们在提供远程桌面服务时如何处理相关信息,以及您可以如何管理授权、保存的内容和数据请求。请在使用前阅读并了解本政策。
|
||||
|
||||
### 网络通信
|
||||
### 一、适用范围
|
||||
|
||||
CrossDesk 是远程桌面软件,需要通过网络完成设备发现、连接协商及远程会话。客户端可能进行以下网络通信:
|
||||
本政策适用于 CrossDesk 桌面客户端、iOS 客户端,以及由 CrossDesk 项目维护者(以下简称“我们”)提供的默认网络服务。
|
||||
|
||||
- **默认服务:** 未启用自托管时,客户端会连接预配置的 CrossDesk 服务(`api.crossdesk.cn`),用于设备注册、信令、网络地址转换(NAT)穿透,并在无法建立直接连接时提供中继。
|
||||
- **版本检查:** 客户端启动时会从 CrossDesk 版本服务(`version.crossdesk.cn`)获取最新版本信息。当前即使启用自托管,版本检查仍会访问 CrossDesk 版本服务。
|
||||
- **远程会话:** 用户主动发起或接受远程连接后,CrossDesk 会根据使用的功能在设备之间传输屏幕画面、音频、键盘和鼠标输入、剪贴板文本以及用户选择传输的文件。剪贴板文本可能在远程会话期间自动同步。这些数据可能通过直接连接传输,也可能在必要时通过配置的中继服务器转发。
|
||||
- **自托管:** 用户可以在设置中指定自己的信令及中继服务器。自托管服务器的日志、数据保存和访问规则由其运营者决定。
|
||||
如果您选择自行部署或使用其他运营者提供的服务器,该服务器所处理的信息、保存期限及安全管理由相应运营者负责。请在使用前了解其隐私政策。本政策中有关客户端本地数据处理的说明仍适用。
|
||||
|
||||
### 处理的信息
|
||||
### 二、我们处理的信息及用途
|
||||
|
||||
为提供上述功能,CrossDesk 可能处理:
|
||||
**设备连接与身份验证。** 为登记设备、验证连接权限、查询在线状态及建立远程连接,客户端与服务端会处理设备 ID、认证信息及在线状态。服务端还会保存设备身份及认证校验信息、在线与离线时间、客户端版本与平台、设备关联记录,并生成必要的运行和安全日志,用于维持服务、排查故障及防止滥用。
|
||||
|
||||
- 连接所需的设备标识及认证信息;
|
||||
- IP 地址、端口、连接时间、连接状态等必要的网络元数据;
|
||||
- 版本检查请求产生的标准网络请求信息;
|
||||
- 用户授权的远程会话中处理的屏幕、音频、控制指令、剪贴板及文件内容。
|
||||
**必要的网络信息。** 建立连接、网络地址转换穿透及中继转发需要处理 IP 地址、端口等网络信息。这些信息用于通信和网络诊断,不等同于读取设备的定位权限。连接服务、中继服务及网络请求可能产生相应日志。
|
||||
|
||||
### 信息的使用与保存
|
||||
**远程会话内容。** 您发起或接受远程连接后,软件根据使用的功能在参与会话的设备之间传输画面、音频、键盘和鼠标操作、剪贴板文本及文件。会话内容可能包含个人或工作信息,请仅连接您拥有或已获授权使用的设备,并按需管理共享内容。
|
||||
|
||||
- 设备标识、连接设置及用户偏好会保存在本地设备上,以便后续使用。
|
||||
- 通过官方信令和中继服务处理的信息仅用于建立、维持和转发 CrossDesk 连接,以及服务运行、安全防护和故障排查。
|
||||
- 中继传输的远程会话内容仅用于实时转发,不用于广告或用户画像。
|
||||
- CrossDesk 桌面客户端不包含广告功能,也不会主动上传诊断日志、崩溃报告或用户行为分析数据。
|
||||
- 自托管服务器可能保存的日志和数据由其运营者控制,请向相应运营者了解其隐私与保存政策。
|
||||
**版本检查。** 桌面客户端启动后会获取版本信息;iOS 客户端在连接成功并收到远端版本信息后,会获取最新桌面版本信息,用于提示升级。该请求不携带设备 ID 或远端版本号,但网络服务会处理完成请求所必需的网络信息。
|
||||
|
||||
### 用户选择
|
||||
CrossDesk 未集成广告投放、广告追踪或用户行为分析功能。客户端不会主动上传诊断日志、崩溃报告或用户行为分析数据。您主动向我们提交问题或日志时,请先移除与问题无关的个人信息及连接凭据。
|
||||
|
||||
用户可以:
|
||||
### 三、数据传输与相关服务
|
||||
|
||||
- 配置自托管服务器,以替代默认信令和中继服务;
|
||||
- 决定是否发起或接受远程会话;
|
||||
- 决定是否选择并传输文件;
|
||||
- 结束远程会话,以停止会话数据传输;
|
||||
- 删除 CrossDesk 的本地配置、缓存及日志文件。
|
||||
我们提供设备登记、连接协商、中继转发及版本检查服务。即使您使用自托管连接服务,客户端仍会按前述条件访问我们提供的版本服务。
|
||||
|
||||
### 政策更新与联系方式
|
||||
远程会话内容优先在参与会话的设备间直接传输,必要时通过配置的中继服务器转发。中继服务用于实时转发,不提供会话录像或文件归档。客户端本地保存的画面预览和接收文件,按本政策相关说明处理。
|
||||
|
||||
本政策可能随着 CrossDesk 功能或网络服务的变化而更新。更新内容将在本文件中发布。如有隐私相关问题,请联系 [junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)。
|
||||
自托管服务器由您选择的运营者管理。更换连接服务器后,设备登记、连接协商及中继数据将由相应运营者处理。
|
||||
|
||||
### 四、信息保存与安全措施
|
||||
|
||||
**客户端本地数据。** 软件会在本机保存连接设置、用户偏好、最近连接记录及必要的运行日志,以支持后续使用和故障排查。iOS 中的本机登录凭据及您选择记住的远程连接密码保存在系统钥匙串中,不通过 iCloud 钥匙串同步;旧版偏好中的本机登录凭据在成功迁入钥匙串后删除。
|
||||
|
||||
**远程画面预览。** iOS 默认不保存远程画面预览。只有您在“设置 → 隐私”单独开启并确认后,才会从下一次连接起,每次连接保存一张远程画面,用于最近连接预览。预览仅保存在本机,不上传,并设置为不纳入设备备份。您可以单独清除预览;关闭保存或撤回隐私授权也会清除已有预览。旧版本未经此选择保存的预览会在升级后清理。
|
||||
|
||||
**接收的文件。** iOS 接收文件保存在本应用的文件目录中,您可通过系统“文件”应用管理或删除。清除画面预览不会删除接收文件或最近连接记录。
|
||||
|
||||
**服务端记录。** 为支持再次连接、服务运维和安全排查,设备身份、状态、关联记录及运行日志可能在连接结束后继续保存。保存范围和期限受服务运行需要、部署规则及适用的保留要求约束。您可以通过下述联系方式查询与您设备相关的信息及保存期限,或提出删除请求。撤回隐私授权、删除本地记录或卸载客户端,不会自动删除已产生的服务端记录;日志、备份和快照需分别核查和处理。
|
||||
|
||||
iOS 通过系统钥匙串和文件保护机制保护相应本地数据,默认信令连接进行 TLS 证书校验。请妥善保管设备和连接凭据,避免向无关人员共享访问密码。
|
||||
|
||||
### 五、iOS 权限与授权选择
|
||||
|
||||
**隐私授权。** 首次使用,或从未提供此选择的旧版升级时,您需阅读本政策、主动勾选并点击同意后,客户端才会登记本机身份、连接信令服务和查询设备在线状态。拒绝后仍可查看设置、离线隐私政策和本地连接记录,远程连接功能暂不可用。
|
||||
|
||||
**撤回同意。** 您可以在“设置 → 隐私 → 隐私与授权”中查看隐私政策、授权状态或撤回授权。客户端将停止远程会话、信令连接和版本检查,关闭并清除本地画面预览。再次使用连接功能前需重新同意;重新同意不会自动开启画面预览保存。撤回不影响撤回前已经发生的信息处理,也不等同于删除服务端数据。
|
||||
|
||||
**系统权限与会话功能。** iOS 客户端作为控制端接收远程电脑的画面与音频,不采集本机屏幕、摄像头或麦克风。局域网访问权限用于连接本地网络中的设备,您可在系统设置中管理。发送文件通过系统文件选择器选择,不要求开放整个文件库。当前 iOS 界面不读取或发送本机剪贴板文本;远端发送的剪贴板文本可在会话中写入本机剪贴板。
|
||||
|
||||
应用及通信组件使用本地文件元数据、应用偏好和计时接口实现文件传输、设置保存及网络计时,不使用这些信息制作设备指纹或进行广告追踪。
|
||||
|
||||
### 六、查询与删除请求
|
||||
|
||||
您可以管理本地最近连接记录、保存的画面预览及接收文件。删除某条最近连接记录时,其预览及已保存的远程连接密码也会删除。
|
||||
|
||||
如需查询、获取数据摘要或删除默认服务中与您设备相关的记录,请通过下述邮箱联系我们,说明设备 ID 和请求范围。为避免未经授权的披露或删除,我们会核实请求权限;请勿通过邮件发送访问密码、私钥或其他敏感凭据。
|
||||
|
||||
删除服务端设备身份后,原身份及对应凭据将失效,再次连接可能登记为新设备。数据库记录的删除不表示日志、备份或其他设备上已接收的内容同时删除。使用自托管服务时,请向相应服务器运营者提出服务端数据请求。
|
||||
|
||||
### 七、政策更新与联系方式
|
||||
|
||||
本政策可能随功能及服务方式调整而更新,更新后的内容和日期将在隐私政策中公布。您可随时在应用设置中查阅当前随应用提供的政策文本。
|
||||
|
||||
如对本政策或个人信息处理有疑问,请联系:
|
||||
|
||||
邮箱:[junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
### Scope
|
||||
Updated: September 28, 2026
|
||||
|
||||
This Privacy Policy applies to the CrossDesk desktop client and the default network services provided by the project. Servers deployed or selected by users are operated by their respective administrators, and their data-processing practices are outside the control of this policy.
|
||||
CrossDesk respects your privacy. This policy explains how information is processed when we provide remote desktop services and how you can manage consent, locally saved content and data requests. Please read this policy before using the software.
|
||||
|
||||
### Network communications
|
||||
### 1. Scope
|
||||
|
||||
CrossDesk is remote desktop software and requires network communications for device discovery, connection negotiation, and remote sessions. The client may perform the following communications:
|
||||
This policy applies to the CrossDesk desktop and iOS clients and the default network services provided by the CrossDesk project maintainers ("we" or "us").
|
||||
|
||||
- **Default services:** Unless self-hosting is enabled, the client connects to preconfigured CrossDesk services (`api.crossdesk.cn`) for device registration, signaling, network address translation (NAT) traversal, and relay when a direct connection cannot be established.
|
||||
- **Update checks:** On startup, the client retrieves current release information from the CrossDesk version service (`version.crossdesk.cn`). Update checks currently continue to use the CrossDesk version service even when self-hosting is enabled.
|
||||
- **Remote sessions:** After a user initiates or accepts a remote connection, CrossDesk transmits the data required by enabled features between devices. This may include screen content, audio, keyboard and mouse input, clipboard text, and files selected by the user. Clipboard text may be synchronized automatically during a remote session. Data may travel over a direct connection or through the configured relay server when necessary.
|
||||
- **Self-hosting:** Users may configure their own signaling and relay servers. Logging, retention, and access policies for a self-hosted server are determined by its operator.
|
||||
If you deploy your own server or choose a server provided by another operator, that operator is responsible for its data processing, retention and security practices. Please review its privacy policy before use. The descriptions of local client data processing in this policy still apply.
|
||||
|
||||
### Information processed
|
||||
### 2. Information processed and its purposes
|
||||
|
||||
To provide these functions, CrossDesk may process:
|
||||
**Device connections and authentication.** To register devices, verify connection permissions, query availability and establish remote connections, the clients and server process device IDs, authentication information and presence. The server also retains device identity and authentication verification records, online and offline times, client versions and platforms, and device associations. Necessary operational and security logs support service operation, troubleshooting and abuse prevention.
|
||||
|
||||
- device identifiers and authentication information required for connections;
|
||||
- necessary network metadata, such as IP addresses, ports, connection times, and connection status;
|
||||
- standard network request information generated by update checks; and
|
||||
- screen, audio, control, clipboard, and file content processed during a remote session authorized by the user.
|
||||
**Necessary network information.** Connections, network address translation traversal and relay forwarding require IP addresses, ports and other network information. This supports communication and network diagnostics and does not involve reading the device's location permission. Connection services, relay services and network requests may generate related logs.
|
||||
|
||||
### Use and storage of information
|
||||
**Remote-session content.** After you initiate or accept a remote connection, the software transfers content between participating devices according to the features used. This includes screens, audio, keyboard and mouse input, clipboard text and files. Such content may contain personal or work information. Connect only to devices you own or are authorized to access, and manage shared content accordingly.
|
||||
|
||||
- Device identifiers, connection settings, and user preferences are stored locally for subsequent use.
|
||||
- Information processed by the official signaling and relay services is used only to establish, maintain, and relay CrossDesk connections and for service operation, security, and troubleshooting.
|
||||
- Remote-session content passing through a relay is used only for real-time forwarding and is not used for advertising or user profiling.
|
||||
- The CrossDesk desktop client does not contain advertising functionality and does not intentionally upload diagnostic logs, crash reports, or behavioral analytics.
|
||||
- Logs and data that may be retained by self-hosted servers are controlled by their operators. Contact the relevant operator for its privacy and retention practices.
|
||||
**Version checks.** The desktop client retrieves release information after startup. After connecting and receiving the remote host's version, the iOS client retrieves the latest desktop release information to suggest updates. These requests do not contain device IDs or the remote host's version, but the service processes network information necessary to complete the request.
|
||||
|
||||
### User choices
|
||||
CrossDesk does not integrate advertising, advertising tracking or behavioral analytics. The clients do not proactively upload diagnostic logs, crash reports or behavioral analytics data. If you choose to submit an issue or logs, remove unrelated personal information and connection credentials first.
|
||||
|
||||
Users may:
|
||||
### 3. Data transmission and related services
|
||||
|
||||
- configure a self-hosted server instead of the default signaling and relay services;
|
||||
- choose whether to initiate or accept a remote session;
|
||||
- choose whether to select and transfer files;
|
||||
- end a remote session to stop session-data transmission; and
|
||||
- remove local CrossDesk configuration, cache, and log files.
|
||||
We provide device registration, connection negotiation, relay forwarding and version checks. Even when you use a self-hosted connection service, the client still accesses our version service under the conditions described above.
|
||||
|
||||
### Changes and contact
|
||||
Remote-session content is transmitted directly between participating devices where possible, or through the configured relay server when needed. The relay service forwards content in real time and does not provide session recording or file archiving. Locally saved previews and received files are handled as described in this policy.
|
||||
|
||||
This policy may be updated as CrossDesk features or network services change. Updates will be published in this file. For privacy-related questions, contact [junkun.di@hotmail.com](mailto:junkun.di@hotmail.com).
|
||||
Self-hosted servers are managed by the operator you choose. If you change the connection server, the corresponding operator will process device registration, connection negotiation and relay data.
|
||||
|
||||
### 4. Storage and security measures
|
||||
|
||||
**Local client data.** The software stores connection settings, preferences, recent connections and necessary operational logs on the device for subsequent use and troubleshooting. On iOS, local login credentials and remote connection passwords you choose to remember are stored in the system Keychain without iCloud Keychain synchronization. Legacy local login credentials in preferences are removed after successful migration to the Keychain.
|
||||
|
||||
**Remote desktop previews.** Saving previews is off by default on iOS. Only after you separately enable and confirm it in Settings → Privacy will the app save one remote frame per connection, starting with the next connection, for recent-connection previews. Previews remain local, are not uploaded and are marked as excluded from device backups. You can clear them separately. Disabling saving or withdrawing network consent also clears them. Previews saved by older versions without this choice are cleared on upgrade.
|
||||
|
||||
**Received files.** Received files on iOS are stored in the app's file directory and can be managed or deleted through Files. Clearing previews does not delete received files or recent-connection records.
|
||||
|
||||
**Server records.** Device identities, presence, associations and operational logs may remain after a connection ends to support reconnection, service operation and security troubleshooting. Their scope and retention depend on operational needs, deployment rules and applicable retention requirements. You can contact us below to ask about records and retention periods related to your device or request deletion. Withdrawing network consent, deleting local records or uninstalling the client does not automatically delete existing server records. Logs, backups and snapshots require separate review and handling.
|
||||
|
||||
On iOS, the system Keychain and file protection mechanisms protect the relevant local data, and default signaling connections validate TLS certificates. Keep your devices and connection credentials secure and avoid sharing access passwords with unrelated people.
|
||||
|
||||
### 5. iOS permissions and consent choices
|
||||
|
||||
**Privacy authorization.** On first use, or when upgrading from a version without this choice, you must read this policy, actively select the checkbox and agree before the client registers a local identity, connects to signaling or queries device presence. If you decline, settings, the offline policy and local connection history remain available, while remote connections are unavailable.
|
||||
|
||||
**Withdrawal.** You can review the privacy policy and your authorization status or withdraw consent in Settings → Privacy → Privacy and Authorization. The client stops remote sessions, signaling and version checks, disables preview saving and clears local previews. Consent is required again before reconnecting. Agreeing again does not automatically enable preview saving. Withdrawal does not undo processing that already occurred or delete server data.
|
||||
|
||||
**System permissions and session features.** The iOS client receives remote computer screens and audio as a controller; it does not capture the local screen, camera or microphone. Local network access supports connections to devices on your network and can be managed in system settings. File sending uses the system document picker without requiring access to the entire file library. The current iOS interface does not read or send local clipboard text. Text sent by the remote device may be written to the local clipboard during a session.
|
||||
|
||||
The app and its communication components use local file metadata, preferences and timing APIs for file transfer, settings and network timing, not for device fingerprinting or advertising tracking.
|
||||
|
||||
### 6. Access and deletion requests
|
||||
|
||||
You can manage local recent connections, saved previews and received files. Removing a recent connection also removes its preview and remembered remote connection password.
|
||||
|
||||
To request access to information, a data summary or deletion of records associated with your device in the default service, contact the email address below with the device ID and scope of your request. We verify the requester's authority to avoid unauthorized disclosure or deletion. Do not send access passwords, private keys or other sensitive credentials by email.
|
||||
|
||||
Deleting a server-side device identity invalidates that identity and its credentials; reconnecting may register a new device. Deleting database records does not mean that logs, backups or content already received by other devices are also deleted. For a self-hosted service, direct server-side data requests to its operator.
|
||||
|
||||
### 7. Policy changes and contact
|
||||
|
||||
This policy may be updated as features and services change. Updated text and its date will be published in the privacy policy. You can review the policy bundled with your app in its settings at any time.
|
||||
|
||||
For questions about this policy or the processing of personal information, contact:
|
||||
|
||||
Email: [junkun.di@hotmail.com](mailto:junkun.di@hotmail.com)
|
||||
|
||||
@@ -147,6 +147,7 @@ sudo apt install "./crossdesk-linux-amd64-<version>.deb"
|
||||
| 视频编码格式 | H.264 / AV1;硬件编解码是否可用取决于平台、硬件与构建选项 |
|
||||
| 启用中继服务 | 允许借助 TURN 中继建立连接;P2P 连接失败时先检查此项 |
|
||||
| 强制中继连接 | 启用中继服务后可勾选,让连接通过中继建立;关闭中继服务会同时关闭此项 |
|
||||
| 保存远程画面预览 | 默认开启,保存远程画面预览;关闭后缩略图区域显示被控端平台,并清除已有预览,保留连接记录和密码 |
|
||||
| 被连接时开启隐私屏 | 设置本机被远程连接时是否自动启用隐私屏;会话中可从控制端工具栏切换 |
|
||||
| 自托管配置 | 填写服务器地址和信令服务端口,并勾选启用 |
|
||||
| 开机自启 / 启用守护进程 | 调整启动与进程守护行为,按界面提示重启后生效 |
|
||||
|
||||
@@ -147,6 +147,7 @@ Open **☰ → Settings** in the top-right corner and click **OK** to save. Conf
|
||||
| Video Encode Format | H.264 / AV1; hardware codec availability depends on the platform, device, and build options |
|
||||
| Enable TURN Service | Allow relay-assisted connections; check this setting if P2P fails |
|
||||
| Force Relay | Require relay connections when TURN is enabled; turning TURN off also disables this option |
|
||||
| Save remote screen previews | On by default. When disabled, the thumbnail area shows the remote device’s platform and existing previews are cleared; connection records and passwords are preserved |
|
||||
| Privacy screen on connect | Automatically enable privacy when this computer is controlled remotely; the controller can toggle it from the session toolbar |
|
||||
| Self-Hosted Config | Set the server address and signaling port, then enable the checkbox |
|
||||
| Auto Start / Enable Daemon | Configure startup and process supervision; restart as indicated by the UI |
|
||||
|
||||
@@ -90,8 +90,10 @@ installApp:
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_session_helper.exe"
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_privacy_cursor_helper.exe"
|
||||
File "..\..\..\..\build\windows\x64\release\crossdesk_privacy_window.dll"
|
||||
; Bundle runtime DLLs from the release output directory
|
||||
File /x crossdesk_privacy_window.dll "..\..\..\..\build\windows\x64\release\*.dll"
|
||||
; Require the Slint runtime so an incomplete build cannot be packaged.
|
||||
File "..\..\..\..\build\windows\x64\release\slint_cpp.dll"
|
||||
; Bundle the remaining runtime DLLs from the release output directory
|
||||
File /x crossdesk_privacy_window.dll /x slint_cpp.dll "..\..\..\..\build\windows\x64\release\*.dll"
|
||||
; Amyuni usbmmidd_v2 virtual display driver for headless hosts. xmake
|
||||
; copies apps\desktop\resources\windows\usbmmidd_v2 into the release
|
||||
; output directory after building crossdesk; its License.txt ships with it.
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "config_center.h"
|
||||
#include "daemon.h"
|
||||
#include "path_manager.h"
|
||||
#include "platform/single_instance.h"
|
||||
#include "rd_log.h"
|
||||
#include "render.h"
|
||||
|
||||
@@ -183,28 +184,34 @@ int HandleServiceCliCommand(const std::string& command) {
|
||||
} // namespace
|
||||
#endif
|
||||
|
||||
static int RunApplication(int argc, char* argv[]) {
|
||||
// Service operations and config migration can log before the GUI starts.
|
||||
// Configure the directory first, including CLI and daemon child paths.
|
||||
static bool IsDaemonChild(int argc, char* argv[]) {
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::strcmp(argv[i], "--child") == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static crossdesk::platform::InstanceResult AcquireInstance(
|
||||
crossdesk::platform::SingleInstanceGuard& guard,
|
||||
crossdesk::platform::InstanceRole role) {
|
||||
std::string error;
|
||||
const auto result = guard.TryAcquire(role, error);
|
||||
if (result == crossdesk::platform::InstanceResult::kAlreadyRunning) {
|
||||
std::cerr << "CrossDesk is already running for this user.\n";
|
||||
} else if (result == crossdesk::platform::InstanceResult::kError) {
|
||||
std::cerr << "CrossDesk cannot start: " << error << '\n';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static int RunApplication(
|
||||
int argc, char* argv[],
|
||||
crossdesk::platform::SingleInstanceGuard& client_instance) {
|
||||
// The instance guards are held before any configuration or logger is opened.
|
||||
auto path_manager = std::make_unique<crossdesk::PathManager>("CrossDesk");
|
||||
crossdesk::InitLogger(path_manager->GetLogPath().string());
|
||||
|
||||
#ifdef _WIN32
|
||||
if (argc > 1 && IsServiceCliCommand(argv[1])) {
|
||||
return HandleServiceCliCommand(argv[1]);
|
||||
}
|
||||
#endif
|
||||
|
||||
// check if running as child process
|
||||
bool is_child = false;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--child") == 0) {
|
||||
is_child = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_child) {
|
||||
if (IsDaemonChild(argc, argv)) {
|
||||
// child process: run render directly
|
||||
crossdesk::Render render;
|
||||
return render.Run();
|
||||
@@ -230,11 +237,23 @@ static int RunApplication(int argc, char* argv[]) {
|
||||
#endif
|
||||
|
||||
if (enable_daemon) {
|
||||
// The launcher lease stays in main for the supervisor's entire lifetime.
|
||||
// Each --child must acquire its own client lease, so it is neither blocked
|
||||
// by its supervisor nor able to bypass the single-client restriction.
|
||||
client_instance.Release();
|
||||
// start daemon with restart monitoring
|
||||
Daemon daemon("CrossDesk");
|
||||
|
||||
// define main loop function: run render and stop daemon on normal exit
|
||||
Daemon::MainLoopFunc main_loop = [&daemon]() {
|
||||
Daemon::MainLoopFunc main_loop = [&daemon, &client_instance]() {
|
||||
// Executable discovery can fail and make the supervisor run the GUI in
|
||||
// process. This fallback must retain the same client ownership rule.
|
||||
if (AcquireInstance(client_instance,
|
||||
crossdesk::platform::InstanceRole::kClient) !=
|
||||
crossdesk::platform::InstanceResult::kAcquired) {
|
||||
daemon.stop();
|
||||
return;
|
||||
}
|
||||
crossdesk::Render render;
|
||||
render.Run();
|
||||
daemon.stop();
|
||||
@@ -267,26 +286,51 @@ int main(int argc, char* argv[]) {
|
||||
std::cout << console.Text("console_cli_help");
|
||||
return 0;
|
||||
}
|
||||
const int result = crossdesk::RunWithLinuxDisplay(
|
||||
argc, argv, [&] { return RunApplication(argc, argv); }, [&] {
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
if (argc == 2 &&
|
||||
std::strcmp(argv[1], crossdesk::kSlintRendererProbeArgument) == 0) {
|
||||
return crossdesk::RunSlintRendererProbe();
|
||||
}
|
||||
if (argc > 1 && IsServiceCliCommand(argv[1])) {
|
||||
EnsureConsoleForCli();
|
||||
crossdesk::platform::SingleInstanceGuard cli_instance;
|
||||
if (AcquireInstance(cli_instance, crossdesk::platform::InstanceRole::kServiceCli) !=
|
||||
crossdesk::platform::InstanceResult::kAcquired) return 1;
|
||||
crossdesk::PathManager paths("CrossDesk");
|
||||
crossdesk::InitLogger(paths.GetLogPath().string(), "crossdesk-service-cli");
|
||||
return HandleServiceCliCommand(argv[1]);
|
||||
}
|
||||
#endif
|
||||
|
||||
using crossdesk::platform::InstanceResult;
|
||||
using crossdesk::platform::InstanceRole;
|
||||
crossdesk::platform::SingleInstanceGuard launcher_instance;
|
||||
crossdesk::platform::SingleInstanceGuard client_instance;
|
||||
if (!IsDaemonChild(argc, argv)) {
|
||||
const auto result = AcquireInstance(launcher_instance, InstanceRole::kLauncher);
|
||||
if (result != InstanceResult::kAcquired)
|
||||
return result == InstanceResult::kAlreadyRunning ? 0 : 1;
|
||||
}
|
||||
const auto result = AcquireInstance(client_instance, InstanceRole::kClient);
|
||||
if (result != InstanceResult::kAcquired)
|
||||
return result == InstanceResult::kAlreadyRunning ? 0 : 1;
|
||||
|
||||
#ifdef __linux__
|
||||
const int exit_code = crossdesk::RunWithLinuxDisplay(
|
||||
argc, argv, [&] { return RunApplication(argc, argv, client_instance); }, [&] {
|
||||
crossdesk::PathManager paths("CrossDesk");
|
||||
if (console.Enable(paths.GetLogPath(), paths.GetCachePath() / "config.ini")) return true;
|
||||
std::cerr << "无法初始化日志或控制台,启动失败。\n";
|
||||
return false;
|
||||
});
|
||||
if (console.active()) {
|
||||
console.Notify(result == 0 ? console.Text("console_exited")
|
||||
: console.Text("console_stopped") + " " + std::to_string(result) +
|
||||
console.Notify(exit_code == 0 ? console.Text("console_exited")
|
||||
: console.Text("console_stopped") + " " + std::to_string(exit_code) +
|
||||
"; " + console.Text("console_log_file") + ": " + console.diagnostic_path());
|
||||
}
|
||||
return result;
|
||||
return exit_code;
|
||||
#else
|
||||
#ifdef _WIN32
|
||||
if (argc == 2 &&
|
||||
std::strcmp(argv[1], crossdesk::kSlintRendererProbeArgument) == 0) {
|
||||
return crossdesk::RunSlintRendererProbe();
|
||||
}
|
||||
#endif
|
||||
return RunApplication(argc, argv);
|
||||
return RunApplication(argc, argv, client_instance);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ int ConfigCenter::Load() {
|
||||
enable_daemon_ = ini_->GetBoolValue(section_, "enable_daemon", enable_daemon_);
|
||||
enable_privacy_screen_.store(
|
||||
ini_->GetBoolValue(section_, "enable_privacy_screen", true));
|
||||
save_remote_previews_.store(
|
||||
ini_->GetBoolValue(section_, "save_remote_previews", true));
|
||||
portable_service_prompt_suppressed_ =
|
||||
ini_->GetBoolValue(section_, "portable_service_prompt_suppressed",
|
||||
portable_service_prompt_suppressed_);
|
||||
@@ -214,6 +216,8 @@ int ConfigCenter::Save() {
|
||||
ini_->SetBoolValue(section_, "enable_daemon", enable_daemon_);
|
||||
ini_->SetBoolValue(section_, "enable_privacy_screen",
|
||||
enable_privacy_screen_.load());
|
||||
ini_->SetBoolValue(section_, "save_remote_previews",
|
||||
save_remote_previews_.load());
|
||||
ini_->SetBoolValue(section_, "portable_service_prompt_suppressed",
|
||||
portable_service_prompt_suppressed_);
|
||||
|
||||
@@ -344,6 +348,18 @@ int ConfigCenter::SetPrivacyScreen(bool enable_privacy_screen) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ConfigCenter::SetSaveRemotePreviews(bool enabled) {
|
||||
if (StoreValues({{"save_remote_previews", enabled ? "true" : "false"}}) != 0) {
|
||||
return -1;
|
||||
}
|
||||
save_remote_previews_.store(enabled);
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ConfigCenter::IsSaveRemotePreviews() const {
|
||||
return save_remote_previews_.load();
|
||||
}
|
||||
|
||||
int ConfigCenter::SetPortableServicePromptSuppressed(bool suppressed) {
|
||||
portable_service_prompt_suppressed_ = suppressed;
|
||||
ini_->SetBoolValue(section_, "portable_service_prompt_suppressed",
|
||||
|
||||
@@ -46,6 +46,7 @@ class ConfigCenter {
|
||||
int SetAutostart(bool enable_autostart);
|
||||
int SetDaemon(bool enable_daemon);
|
||||
int SetPrivacyScreen(bool enable_privacy_screen);
|
||||
int SetSaveRemotePreviews(bool enabled);
|
||||
int SetPortableServicePromptSuppressed(bool suppressed);
|
||||
int SetFileTransferSavePath(const std::string& path);
|
||||
|
||||
@@ -69,6 +70,7 @@ class ConfigCenter {
|
||||
bool IsEnableAutostart() const;
|
||||
bool IsEnableDaemon() const;
|
||||
bool IsEnablePrivacyScreen() const;
|
||||
bool IsSaveRemotePreviews() const;
|
||||
bool IsPortableServicePromptSuppressed() const;
|
||||
std::string GetFileTransferSavePath() const;
|
||||
|
||||
@@ -97,6 +99,7 @@ class ConfigCenter {
|
||||
bool enable_autostart_ = false;
|
||||
bool enable_daemon_ = false;
|
||||
std::atomic<bool> enable_privacy_screen_{true};
|
||||
std::atomic<bool> save_remote_previews_{true};
|
||||
bool portable_service_prompt_suppressed_ = false;
|
||||
std::string file_transfer_save_path_ = "";
|
||||
};
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
@@ -61,6 +62,7 @@
|
||||
#endif
|
||||
#include "rd_log.h"
|
||||
#include "server_window_state.h"
|
||||
#include "ui/announcement_text.h"
|
||||
#include "ui/ui_localization.h"
|
||||
#include "update_checker.h"
|
||||
#include "window_geometry.h"
|
||||
@@ -657,6 +659,41 @@ struct WindowDragState {
|
||||
float global_to_physical_scale = 1;
|
||||
slint::PhysicalPosition window_start;
|
||||
slint::PhysicalPosition last_target;
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
std::unique_ptr<Display, decltype(&XCloseDisplay)> x11_display{nullptr,
|
||||
XCloseDisplay};
|
||||
slint::Timer pointer_timer;
|
||||
#endif
|
||||
|
||||
bool ReadGlobalPointer(float* x, float* y) {
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
const char* driver = SDL_GetCurrentVideoDriver();
|
||||
if (driver && std::strcmp(driver, "x11") == 0) {
|
||||
// Slint can dispatch motion before SDL pumps its XInput2 events, and
|
||||
// pointer warps do not emit raw motion at all. Query X11 directly so
|
||||
// dragging never depends on SDL's cached global pointer position.
|
||||
if (!x11_display) {
|
||||
x11_display.reset(XOpenDisplay(nullptr));
|
||||
}
|
||||
if (!x11_display) {
|
||||
return false;
|
||||
}
|
||||
::Window root, child;
|
||||
int root_x, root_y, local_x, local_y;
|
||||
unsigned int buttons;
|
||||
if (!XQueryPointer(x11_display.get(), DefaultRootWindow(x11_display.get()),
|
||||
&root, &child, &root_x, &root_y, &local_x, &local_y,
|
||||
&buttons)) {
|
||||
return false;
|
||||
}
|
||||
*x = static_cast<float>(root_x);
|
||||
*y = static_cast<float>(root_y);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
SDL_GetGlobalMouseState(x, y);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
bool CanUseGlobalPointerPosition() {
|
||||
@@ -849,9 +886,10 @@ void DragWindow(WindowHandle& component, int phase, float mouse_x,
|
||||
state.last_local_y = mouse_y;
|
||||
state.window_start = window.position();
|
||||
state.last_target = state.window_start;
|
||||
state.use_global_pointer = CanUseGlobalPointerPosition();
|
||||
state.use_global_pointer =
|
||||
CanUseGlobalPointerPosition() &&
|
||||
state.ReadGlobalPointer(&state.pointer_start_x, &state.pointer_start_y);
|
||||
if (state.use_global_pointer) {
|
||||
SDL_GetGlobalMouseState(&state.pointer_start_x, &state.pointer_start_y);
|
||||
#if defined(__APPLE__)
|
||||
// Cocoa reports global pointer positions in logical screen points,
|
||||
// while Slint/winit accepts physical window positions.
|
||||
@@ -860,9 +898,32 @@ void DragWindow(WindowHandle& component, int phase, float mouse_x,
|
||||
state.global_to_physical_scale = 1.0f;
|
||||
#endif
|
||||
}
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
if (state.use_global_pointer && state.x11_display) {
|
||||
// Moving the window can leave consecutive pointer events at identical
|
||||
// local coordinates, so Slint need not emit another TouchArea::moved.
|
||||
// Follow the global pointer throughout the drag, including those moves.
|
||||
state.pointer_timer.start(
|
||||
slint::TimerMode::Repeated, std::chrono::milliseconds(16),
|
||||
[weak = slint::ComponentWeakHandle(component), &state] {
|
||||
if (auto window = weak.lock()) {
|
||||
DragWindow(*window, 2, 0, 0, state);
|
||||
} else {
|
||||
state.active = false;
|
||||
state.pointer_timer.stop();
|
||||
}
|
||||
});
|
||||
}
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (phase == 0) {
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
state.pointer_timer.stop();
|
||||
if (state.use_global_pointer && state.x11_display) {
|
||||
DragWindow(component, 2, mouse_x, mouse_y, state);
|
||||
}
|
||||
#endif
|
||||
state.active = false;
|
||||
return;
|
||||
}
|
||||
@@ -874,7 +935,9 @@ void DragWindow(WindowHandle& component, int phase, float mouse_x,
|
||||
if (state.use_global_pointer) {
|
||||
float pointer_x = 0;
|
||||
float pointer_y = 0;
|
||||
SDL_GetGlobalMouseState(&pointer_x, &pointer_y);
|
||||
if (!state.ReadGlobalPointer(&pointer_x, &pointer_y)) {
|
||||
return;
|
||||
}
|
||||
const int delta_x = static_cast<int>(std::lround(
|
||||
(pointer_x - state.pointer_start_x) * state.global_to_physical_scale));
|
||||
const int delta_y = static_cast<int>(std::lround(
|
||||
@@ -906,6 +969,8 @@ void DragWindow(WindowHandle& component, int phase, float mouse_x,
|
||||
} // namespace
|
||||
|
||||
struct GuiApplication::SlintUi {
|
||||
uint64_t announcement_version = UINT64_MAX;
|
||||
std::string announcement_selected_id, announcement_selected_revision;
|
||||
slint::ComponentHandle<ui::MainWindow> main = ui::MainWindow::create();
|
||||
std::shared_ptr<slint::VectorModel<ui::ReleaseNoteBlock>>
|
||||
release_note_blocks_model =
|
||||
@@ -981,6 +1046,8 @@ int GuiApplication::Run() {
|
||||
dll_log_path_ = exec_log_path_;
|
||||
InitializeLogger();
|
||||
cache_path_ = path_manager_->GetCachePath().string();
|
||||
announcements_.SetStorageDirectory(path_manager_->GetCachePath() /
|
||||
"announcement_reads");
|
||||
config_center_ = std::make_unique<ConfigCenter>(cache_path_ + "/config.ini");
|
||||
|
||||
LOG_INFO("CrossDesk version: {} (Slint UI)", CROSSDESK_VERSION);
|
||||
@@ -988,7 +1055,7 @@ int GuiApplication::Run() {
|
||||
strncpy(signal_server_ip_self_, config_center_->GetSignalServerHost().c_str(),
|
||||
sizeof(signal_server_ip_self_) - 1);
|
||||
const int signal_port = config_center_->GetSignalServerPort();
|
||||
if (signal_port > 0) {
|
||||
if (signal_port > 0 && signal_port <= 65535) {
|
||||
std::snprintf(signal_server_port_self_, sizeof(signal_server_port_self_),
|
||||
"%d", signal_port);
|
||||
}
|
||||
@@ -1027,6 +1094,8 @@ int GuiApplication::Run() {
|
||||
ui_->main->show();
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons(ui_->main->window().win32_hwnd());
|
||||
#elif defined(__APPLE__)
|
||||
ConfigureMainWindowChrome(ui_->main->window().appkit_view());
|
||||
#endif
|
||||
slint::run_event_loop(slint::EventLoopMode::RunUntilQuit);
|
||||
Cleanup();
|
||||
@@ -1037,6 +1106,9 @@ void GuiApplication::InitializeLogger() { InitLogger(exec_log_path_); }
|
||||
|
||||
void GuiApplication::InitializeSettings() {
|
||||
settings_.Load();
|
||||
if (thumbnail_->SetSavePreviews(config_center_->IsSaveRemotePreviews()) != 0) {
|
||||
LOG_ERROR("Failed to clear saved remote previews");
|
||||
}
|
||||
settings_.LoadRecentConnectionAliases();
|
||||
localization_language_index_ =
|
||||
localization::detail::ClampLanguageIndex(language_button_value_);
|
||||
@@ -1120,6 +1192,9 @@ void GuiApplication::InitializeUi() {
|
||||
}
|
||||
#endif
|
||||
#if defined(__linux__) && !defined(__APPLE__)
|
||||
// Detect the desktop session before temporarily hiding Wayland variables
|
||||
// for the XWayland GUI backend below.
|
||||
const bool is_wayland_session = IsWaylandSession();
|
||||
// Winit prefers Wayland whenever WAYLAND_DISPLAY/WAYLAND_SOCKET is present.
|
||||
// Hide them only while Slint selects its process-wide window backend, then
|
||||
// restore the environment before the rest of the application starts.
|
||||
@@ -1141,6 +1216,8 @@ void GuiApplication::InitializeUi() {
|
||||
#elif defined(__linux__)
|
||||
ui_->main->set_custom_titlebar(use_x11_custom_titlebar_);
|
||||
ui_->main->set_wayland_titlebar(use_xwayland_gui_);
|
||||
// Set this only at startup so dismissing the notice lasts until exit.
|
||||
ui_->main->set_wayland_notice_open(is_wayland_session);
|
||||
#endif
|
||||
ui_->main->set_release_note_blocks(ui_->release_note_blocks_model);
|
||||
RegisterFontAwesome(ui_->main->window());
|
||||
@@ -1167,6 +1244,7 @@ void GuiApplication::InitializeSystemTray() {
|
||||
#endif
|
||||
ui_->main->window().set_minimized(false);
|
||||
#if defined(__APPLE__)
|
||||
ConfigureMainWindowChrome(ui_->main->window().appkit_view());
|
||||
MacActivateWindow(ui_->main->window().appkit_view());
|
||||
// A window restored from the tray may only obtain its NSWindow after the
|
||||
// callback returns, so let the regular UI tick configure it.
|
||||
@@ -1240,6 +1318,7 @@ void GuiApplication::ResetSettingsUi() {
|
||||
ui_->main->set_self_hosted_enabled(enable_self_hosted_);
|
||||
ui_->main->set_autostart_enabled(enable_autostart_);
|
||||
ui_->main->set_daemon_enabled(enable_daemon_);
|
||||
ui_->main->set_save_remote_previews(config_center_->IsSaveRemotePreviews());
|
||||
ui_->main->set_privacy_on_connect_enabled(
|
||||
config_center_->IsEnablePrivacyScreen());
|
||||
#ifdef _WIN32
|
||||
@@ -1258,6 +1337,49 @@ void GuiApplication::ResetSettingsUi() {
|
||||
}
|
||||
|
||||
void GuiApplication::BindMainCallbacks() {
|
||||
ui_->main->on_delete_announcement([this](slint::SharedString id,
|
||||
slint::SharedString revision) {
|
||||
const auto parse = [](const slint::SharedString& value)
|
||||
-> std::optional<int64_t> {
|
||||
const std::string_view text(value.data());
|
||||
int64_t number = 0;
|
||||
const auto result =
|
||||
std::from_chars(text.data(), text.data() + text.size(), number);
|
||||
if (result.ec != std::errc{} ||
|
||||
result.ptr != text.data() + text.size() || number <= 0)
|
||||
return std::nullopt;
|
||||
return number;
|
||||
};
|
||||
const auto announcement_id = parse(id);
|
||||
const auto announcement_revision = parse(revision);
|
||||
if (!announcement_id || !announcement_revision) return;
|
||||
announcements_.Dismiss(*announcement_id, *announcement_revision);
|
||||
SyncAnnouncements();
|
||||
});
|
||||
ui_->main->on_refresh_announcements([this] { announcements_.Refresh(); });
|
||||
ui_->main->on_open_announcement_link([this](slint::SharedString link) {
|
||||
const std::string url(link);
|
||||
if (announcement_text::IsWebUrl(url)) OpenUrl(url);
|
||||
});
|
||||
ui_->main->on_load_more_announcements([this] {
|
||||
announcements_.LoadMore();
|
||||
SyncAnnouncements();
|
||||
});
|
||||
ui_->main->on_open_announcement([this](slint::SharedString id,
|
||||
slint::SharedString revision) {
|
||||
const auto snapshot = announcements_.Get();
|
||||
for (const auto& item : snapshot.items) {
|
||||
if (std::to_string(item["id"].get<int64_t>()) != id.data() ||
|
||||
std::to_string(item["revision"].get<int64_t>()) != revision.data())
|
||||
continue;
|
||||
ui_->announcement_selected_id = id.data();
|
||||
ui_->announcement_selected_revision = revision.data();
|
||||
ui_->announcement_version = UINT64_MAX;
|
||||
announcements_.Read(item["id"], item["revision"]);
|
||||
SyncAnnouncements();
|
||||
break;
|
||||
}
|
||||
});
|
||||
auto& main = ui_->main;
|
||||
main->window().on_close_requested([this] {
|
||||
// Keep the application and all active sessions alive. The tray helper
|
||||
@@ -1481,6 +1603,12 @@ void GuiApplication::BindStreamCallbacks() {
|
||||
return;
|
||||
}
|
||||
auto& stream = *ui_->stream;
|
||||
stream->on_dismiss_remote_update([this] {
|
||||
if (auto props = SelectedSession()) {
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
props->remote_update_dismissed_ = true;
|
||||
}
|
||||
});
|
||||
auto close_stream_sessions = [this] {
|
||||
std::vector<std::string> ids;
|
||||
{
|
||||
@@ -2029,7 +2157,7 @@ void GuiApplication::ShareLocalCursorState() {
|
||||
if (!delivery.has_sent ||
|
||||
delivery.last_sent.render_mode != outgoing.render_mode ||
|
||||
delivery.last_sent.hidden_reason != outgoing.hidden_reason) {
|
||||
LOG_INFO("Send cursor presentation to [{}]: mode={}, reason={}",
|
||||
LOG_DEBUG("Send cursor presentation to [{}]: mode={}, reason={}",
|
||||
recipient.remote_id, static_cast<int>(outgoing.render_mode),
|
||||
static_cast<int>(outgoing.hidden_reason));
|
||||
}
|
||||
@@ -2269,16 +2397,81 @@ void GuiApplication::UpdateLocalization() {
|
||||
ui_->localized_language = language;
|
||||
}
|
||||
|
||||
void GuiApplication::SyncAnnouncements() {
|
||||
if (signal_connected_) {
|
||||
announcements_.Configure(params_.signal_server_ip,
|
||||
params_.signal_server_port, client_id_);
|
||||
}
|
||||
const auto request = announcements_.TakePendingRequest();
|
||||
if (!request.is_null()) {
|
||||
const auto payload = request.dump();
|
||||
if (!peer_ || SendSignalMessage(peer_, payload.data(), payload.size()) != 0)
|
||||
announcements_.Failed(request["request_id"]);
|
||||
}
|
||||
if (ui_->announcement_version == announcements_.Version()) return;
|
||||
const auto state = announcements_.Get();
|
||||
ui_->announcement_version = state.version;
|
||||
ui_->main->set_announcement_unread(state.unread);
|
||||
ui_->main->set_announcement_total(state.total);
|
||||
ui_->main->set_announcement_loading(state.loading);
|
||||
ui_->main->set_announcement_failed(state.failed);
|
||||
ui_->main->set_announcement_read_save_failed(state.read_save_failed);
|
||||
ui_->main->set_announcement_delete_failed(state.delete_failed);
|
||||
ui_->main->set_announcement_loaded(state.loaded);
|
||||
std::vector<ui::AnnouncementItem> rows;
|
||||
bool selected_found = false;
|
||||
for (const auto& item : state.items) {
|
||||
ui::AnnouncementItem row;
|
||||
const auto id = std::to_string(item["id"].get<int64_t>());
|
||||
const auto revision = std::to_string(item["revision"].get<int64_t>());
|
||||
row.id = UiText(id);
|
||||
row.revision = UiText(revision);
|
||||
row.title = UiText(item["title"].get<std::string>());
|
||||
const auto timestamp =
|
||||
static_cast<time_t>(item["updated_at"].get<int64_t>());
|
||||
std::tm local{};
|
||||
#ifdef _WIN32
|
||||
localtime_s(&local, ×tamp);
|
||||
#else
|
||||
localtime_r(×tamp, &local);
|
||||
#endif
|
||||
char date[32]{};
|
||||
std::strftime(date, sizeof(date), "%Y-%m-%d %H:%M", &local);
|
||||
row.date = UiText(date);
|
||||
row.read = item["read"].get<bool>();
|
||||
if (id == ui_->announcement_selected_id &&
|
||||
revision == ui_->announcement_selected_revision) {
|
||||
selected_found = true;
|
||||
ui_->main->set_announcement_selected_id(row.id);
|
||||
ui_->main->set_announcement_selected_title(row.title);
|
||||
ui_->main->set_announcement_selected_body(
|
||||
announcement_text::Format(item["body"].get<std::string>()));
|
||||
ui_->main->set_announcement_selected_date(row.date);
|
||||
ui_->main->set_announcement_selected_read(row.read);
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
}
|
||||
if (!selected_found) {
|
||||
ui_->announcement_selected_id.clear();
|
||||
ui_->main->set_announcement_selected_id("");
|
||||
ui_->main->set_announcement_selected_body(slint::StyledText{});
|
||||
}
|
||||
ui_->main->set_announcements(
|
||||
std::make_shared<slint::VectorModel<ui::AnnouncementItem>>(
|
||||
std::move(rows)));
|
||||
}
|
||||
|
||||
void GuiApplication::SyncMainWindow() {
|
||||
if (!ui_) {
|
||||
return;
|
||||
}
|
||||
SyncAnnouncements();
|
||||
#if _WIN32
|
||||
ConfigureWindowsWindowIcons(ui_->main->window().win32_hwnd());
|
||||
#endif
|
||||
#if defined(__APPLE__)
|
||||
if (ui_->main_native_titlebar_attempts > 0) {
|
||||
if (HideDisabledMainWindowZoomButton()) {
|
||||
if (ConfigureMainWindowChrome(ui_->main->window().appkit_view())) {
|
||||
ui_->main_native_titlebar_attempts = 0;
|
||||
} else {
|
||||
--ui_->main_native_titlebar_attempts;
|
||||
@@ -2328,9 +2521,11 @@ void GuiApplication::SyncMainWindow() {
|
||||
}
|
||||
|
||||
std::ostringstream signature_builder;
|
||||
signature_builder << config_center_->IsSaveRemotePreviews() << '\n';
|
||||
for (const auto& [key, connection] : recent_connections_) {
|
||||
signature_builder << key << '\0' << connection.remote_id << '\0'
|
||||
<< connection.remote_host_name << '\0'
|
||||
<< static_cast<int>(connection.platform) << '\0'
|
||||
<< settings_.RecentConnectionDisplayName(connection)
|
||||
<< '\0'
|
||||
<< device_presence_cache_.IsOnline(connection.remote_id)
|
||||
@@ -2345,22 +2540,27 @@ void GuiApplication::SyncMainWindow() {
|
||||
std::vector<ui::RecentConnection> model;
|
||||
model.reserve(recent_connections_.size());
|
||||
for (const auto& [_, connection] : recent_connections_) {
|
||||
ui::RecentConnection item;
|
||||
// Slint-generated scalar fields have no defaults. With no image,
|
||||
// has_thumbnail must remain false so the remote platform is rendered.
|
||||
ui::RecentConnection item{};
|
||||
item.remote_id = UiText(connection.remote_id);
|
||||
item.host_name = UiText(connection.remote_host_name);
|
||||
item.display_name =
|
||||
UiText(settings_.RecentConnectionDisplayName(connection));
|
||||
item.online = device_presence_cache_.IsOnline(connection.remote_id);
|
||||
item.platform = UiText(HostPlatformName(connection.platform));
|
||||
std::vector<unsigned char> rgba;
|
||||
int image_width = 0;
|
||||
int image_height = 0;
|
||||
if (!connection.image_path.empty() &&
|
||||
if (config_center_->IsSaveRemotePreviews() &&
|
||||
!connection.image_path.empty() &&
|
||||
thumbnail_->DecodeImage(connection.image_path, &rgba, &image_width,
|
||||
&image_height)) {
|
||||
slint::SharedPixelBuffer<slint::Rgba8Pixel> pixels(image_width,
|
||||
image_height);
|
||||
std::memcpy(pixels.begin(), rgba.data(), rgba.size());
|
||||
item.thumbnail = slint::Image(std::move(pixels));
|
||||
item.has_thumbnail = true;
|
||||
}
|
||||
model.push_back(std::move(item));
|
||||
}
|
||||
@@ -2525,6 +2725,11 @@ void GuiApplication::SyncXWaylandWindowActivation() {
|
||||
#endif
|
||||
|
||||
void GuiApplication::SetStreamKeyboardFocus(bool focused) {
|
||||
// The local upgrade dialog owns input even while the native window is active.
|
||||
if (focused && ui_ && ui_->stream &&
|
||||
(*ui_->stream)->get_remote_update_visible()) {
|
||||
focused = false;
|
||||
}
|
||||
if (focus_on_stream_window_ == focused) {
|
||||
return;
|
||||
}
|
||||
@@ -2702,6 +2907,21 @@ void GuiApplication::SyncStreamWindow() {
|
||||
return;
|
||||
}
|
||||
const ConnectionStatus status = props->connection_status_.load();
|
||||
bool remote_update_available = false;
|
||||
if (status == ConnectionStatus::Connected) {
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
// Wait for host_info: a version still in transit is not a legacy peer.
|
||||
if (props->remote_host_info_received_ && !props->remote_update_dismissed_) {
|
||||
remote_update_available = props->remote_app_version_.empty() ||
|
||||
(update_checker_->latest() &&
|
||||
AvailableAppUpdate(props->remote_app_version_,
|
||||
*update_checker_->latest()).has_value());
|
||||
}
|
||||
}
|
||||
(*ui_->stream)->set_remote_update_visible(remote_update_available);
|
||||
if (remote_update_available) {
|
||||
SetStreamKeyboardFocus(false);
|
||||
}
|
||||
const bool waiting_for_frame =
|
||||
status == ConnectionStatus::Connected &&
|
||||
!(*ui_->stream)->get_has_frame();
|
||||
@@ -2803,7 +3023,7 @@ void GuiApplication::SyncStreamWindow() {
|
||||
ui_->display_model->set_vector(std::move(displays));
|
||||
(*ui_->stream)->set_selected_display(props->selected_display_);
|
||||
|
||||
const auto& net = props->net_traffic_stats_;
|
||||
const auto net = props->net_traffic_stats_.Load();
|
||||
(*ui_->stream)->set_stats_encryption_enabled(
|
||||
status == ConnectionStatus::Connected && net.srtp_active);
|
||||
std::vector<ui::NetworkStatsRow> stats_rows;
|
||||
@@ -2892,12 +3112,14 @@ void GuiApplication::SyncStreamWindow() {
|
||||
props->file_transfer_.file_transfer_window_visible_);
|
||||
|
||||
const auto fps_now = std::chrono::steady_clock::now();
|
||||
bool refresh_stats = false;
|
||||
if (!props->net_traffic_stats_button_pressed_) {
|
||||
props->fps_ = 0;
|
||||
props->frame_count_ = 0;
|
||||
props->last_time_ = {};
|
||||
} else if (props->last_time_.time_since_epoch().count() == 0) {
|
||||
props->last_time_ = fps_now;
|
||||
refresh_stats = true;
|
||||
} else {
|
||||
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
fps_now - props->last_time_)
|
||||
@@ -2906,9 +3128,42 @@ void GuiApplication::SyncStreamWindow() {
|
||||
props->fps_ = static_cast<int>(props->frame_count_ * 1000 / elapsed);
|
||||
props->frame_count_ = 0;
|
||||
props->last_time_ = fps_now;
|
||||
refresh_stats = true;
|
||||
}
|
||||
}
|
||||
(*ui_->stream)->set_stats_fps(UiText(std::to_string(props->fps_)));
|
||||
if (!props->net_traffic_stats_button_pressed_ ||
|
||||
status != ConnectionStatus::Connected) {
|
||||
props->video_latency_snapshot_.reset();
|
||||
} else if (refresh_stats) {
|
||||
props->video_latency_snapshot_ = props->video_latency_->Get(fps_now);
|
||||
}
|
||||
const auto& latency = props->video_latency_snapshot_;
|
||||
(*ui_->stream)
|
||||
->set_stats_video_latency(UiText(
|
||||
latency ? std::to_string(
|
||||
static_cast<int>(std::lround(latency->average_ms))) +
|
||||
" ms"
|
||||
: "—"));
|
||||
const auto display_rtt = props->net_traffic_stats_.SmoothedRttMs(fps_now);
|
||||
const bool rtt_available = props->net_traffic_stats_button_pressed_ &&
|
||||
status == ConnectionStatus::Connected &&
|
||||
display_rtt.has_value();
|
||||
std::string connection_latency = "—";
|
||||
if (rtt_available) {
|
||||
connection_latency =
|
||||
*display_rtt < 1
|
||||
? "<1 ms"
|
||||
: std::to_string(static_cast<int>(std::lround(*display_rtt))) + " ms";
|
||||
}
|
||||
(*ui_->stream)->set_stats_connection_latency(UiText(connection_latency));
|
||||
if (refresh_stats && status == ConnectionStatus::Connected) {
|
||||
LOG_DEBUG("Latency stats: remote={} video_ms={} video_samples={} "
|
||||
"rtt_raw_ms={} rtt_display_ms={}",
|
||||
props->remote_id_, latency ? latency->average_ms : -1,
|
||||
latency ? latency->samples : 0, net.rtt_ms,
|
||||
display_rtt.value_or(-1));
|
||||
}
|
||||
}
|
||||
|
||||
void GuiApplication::SyncStreamVideoFrame() {
|
||||
@@ -2928,6 +3183,7 @@ void GuiApplication::SyncStreamVideoFrame() {
|
||||
frame.width = props->video_width_;
|
||||
frame.height = props->video_height_;
|
||||
frame.sequence = props->video_frame_sequence_;
|
||||
frame.timing = props->video_frame_timing_;
|
||||
}
|
||||
|
||||
const auto result = ui_->video_presenter->Present(frame);
|
||||
@@ -3197,6 +3453,13 @@ void GuiApplication::SaveSettingsFromUi() {
|
||||
main->set_force_relay_enabled(config_center_->IsForceRelay());
|
||||
config_center_->SetAutostart(enable_autostart_);
|
||||
config_center_->SetDaemon(enable_daemon_);
|
||||
if (config_center_->SetSaveRemotePreviews(main->get_save_remote_previews()) != 0) {
|
||||
LOG_ERROR("Failed to save remote preview preference");
|
||||
}
|
||||
if (thumbnail_->SetSavePreviews(config_center_->IsSaveRemotePreviews()) != 0) {
|
||||
LOG_ERROR("Failed to clear saved remote previews");
|
||||
}
|
||||
reload_recent_connections_ = true;
|
||||
#ifdef _WIN32
|
||||
if (!HasActiveSession()) {
|
||||
const auto capture_method = static_cast<ScreenCaptureMethod>(
|
||||
|
||||
@@ -56,6 +56,7 @@ private:
|
||||
void HandlePasswordChangeResult();
|
||||
void HandleCredentialRecovery();
|
||||
void SyncMainWindow();
|
||||
void SyncAnnouncements();
|
||||
void SyncConnectionDialog();
|
||||
void SyncPlatformDialogs();
|
||||
void SyncStreamWindow();
|
||||
|
||||
@@ -20,6 +20,18 @@ struct TranslationRow {
|
||||
|
||||
// Single source of truth for all UI strings.
|
||||
#define CROSSDESK_LOCALIZATION_ALL(X) \
|
||||
X(messages, u8"消息", "Messages", u8"Сообщения") \
|
||||
X(message_unread, u8"未读", "Unread", u8"Не прочитано") \
|
||||
X(message_read, u8"已读", "Read", u8"Прочитано") \
|
||||
X(message_empty, u8"暂无公告", "No announcements", u8"Нет объявлений") \
|
||||
X(message_select, u8"选择公告查看详情", "Select an announcement to read", u8"Выберите объявление") \
|
||||
X(message_loading, u8"正在加载…", "Loading…", u8"Загрузка…") \
|
||||
X(message_read_save_error, u8"无法保存本地阅读状态,请重新打开公告重试。", "Unable to save reading status locally. Open the announcement again to retry.", u8"Не удалось сохранить статус чтения. Откройте объявление снова.") \
|
||||
X(message_close, u8"关闭", "Close", u8"Закрыть") \
|
||||
X(message_delete, u8"删除", "Delete", u8"Удалить") \
|
||||
X(message_delete_title, u8"删除公告", "Delete announcement", u8"Удалить объявление") \
|
||||
X(message_delete_confirmation, u8"删除这条公告?", "Delete this announcement?", u8"Удалить это объявление?") \
|
||||
X(message_delete_error, u8"无法删除这条公告,请重试。", "Unable to delete this announcement. Please try again.", u8"Не удалось удалить объявление. Повторите попытку.") \
|
||||
X(console_cli_help, u8"Linux 无头运行选项:\n --headless 自动选择已有桌面并启用控制台\n --headless-display DISPLAY 高级:指定已有显示会话\n --headless-size WIDTHxHEIGHT 新建虚拟屏幕;默认1920x1080,偶数尺寸320..8192\n --headless-session EXECUTABLE 启动桌面环境(startxfce4;none 仅启动裸屏幕)\n --no-headless 禁用自动回退\n正常启动会自动选择已有桌面,无需填写显示编号。控制台输入 settings 管理设置。\n", "Linux headless options:\n --headless Select an existing desktop and enable the console\n --headless-display DISPLAY Advanced: override desktop selection\n --headless-size WIDTHxHEIGHT New virtual display; default 1920x1080, even 320..8192\n --headless-session EXECUTABLE Start a desktop (startxfce4; none for a bare display)\n --no-headless Disable automatic fallback\nNormal startup selects your existing desktop automatically. Enter settings in the console to configure it.\n", u8"Параметры запуска без монитора:\n --headless Выбрать рабочий стол и включить консоль\n --headless-display DISPLAY Дополнительно: указать сеанс дисплея\n --headless-size WIDTHxHEIGHT Новый виртуальный экран; 1920x1080 по умолчанию, чётные размеры 320..8192\n --headless-session EXECUTABLE Запустить рабочий стол (startxfce4; none — только экран)\n --no-headless Отключить автоматический резервный запуск\nРабочий стол выбирается автоматически. Команда settings открывает настройки консоли.\n") \
|
||||
X(console_title, u8"CrossDesk 无头控制台", "CrossDesk headless console", u8"Консоль CrossDesk") \
|
||||
X(console_log_file, u8"日志文件", "Log file", u8"Файл журнала") \
|
||||
@@ -79,6 +91,8 @@ struct TranslationRow {
|
||||
X(console_setting_files, u8"文件保存目录", "Received file directory", u8"Каталог получаемых файлов") \
|
||||
X(console_setting_autostart, u8"登录桌面时自启", "Start at desktop login", u8"Запуск при входе в систему") \
|
||||
X(console_setting_daemon, u8"守护进程(无头控制台中不生效)", "Daemon (inactive in headless console)", u8"Фоновый режим (не действует в консоли)") \
|
||||
X(save_remote_previews, u8"保存远程画面预览:", "Save remote screen previews:", u8"Сохранять превью экрана:") \
|
||||
X(unknown_platform, u8"未知平台", "Unknown platform", u8"Неизвестная платформа") \
|
||||
X(privacy_screen, u8"隐私屏", "Privacy screen", u8"Приватный экран") \
|
||||
X(privacy_enable, u8"开启隐私屏", "Enable privacy screen", u8"Включить приватный экран") \
|
||||
X(privacy_disable, u8"关闭隐私屏", "Disable privacy screen", u8"Выключить приватный экран") \
|
||||
@@ -191,6 +205,9 @@ struct TranslationRow {
|
||||
u8"Способ захвата:") \
|
||||
X(screen_capture_method_auto, u8"自动", "Auto", u8"Авто") \
|
||||
X(video_settings, u8"画面设置", "Video settings", u8"Настройки видео") \
|
||||
X(remote_update_title, u8"被控端版本过低", "Remote device needs an update", u8"Версия на удалённом устройстве устарела") \
|
||||
X(remote_update, u8"请升级到最新版本。", "Please update to the latest version.", u8"Обновите её до последней версии.") \
|
||||
X(remote_update_dismiss, u8"知道了", "Got it", u8"Понятно") \
|
||||
X(video_settings_pending, u8"正在应用…", "Applying…", u8"Применение…") \
|
||||
X(video_settings_failed, u8"调整失败,请重试。", "Could not apply settings. Try again.", u8"Не удалось применить настройки. Повторите попытку.") \
|
||||
X(video_settings_unavailable, u8"连接建立后可调整,需被控端支持。", "Available when connected to a supported remote device.", u8"Доступно при подключении к поддерживаемому устройству.") \
|
||||
@@ -256,6 +273,7 @@ struct TranslationRow {
|
||||
X(no_such_id, u8"无此ID", "No such ID", u8"ID не найден") \
|
||||
X(about, u8"关于", "About", u8"О программе") \
|
||||
X(notification, u8"通知", "Notification", u8"Уведомление") \
|
||||
X(new_version, u8"新版本", "New version", u8"Новая версия") \
|
||||
X(new_version_available, u8"新版本可用", "New Version Available", \
|
||||
u8"Доступна новая версия") \
|
||||
X(check_for_updates, u8"检查更新", "Check for updates", \
|
||||
@@ -305,6 +323,8 @@ struct TranslationRow {
|
||||
"File Transfer Save Path:", u8"Путь сохранения файлов:") \
|
||||
X(default_desktop, u8"桌面", "Desktop", u8"Рабочий стол") \
|
||||
X(resolution, u8"分辨率", "Res", u8"Разрешение") \
|
||||
X(video_latency, u8"视频延时", "Video delay", u8"Задержка") \
|
||||
X(connection_latency, u8"连接延时", "Connection RTT", u8"Задержка соединения") \
|
||||
X(connection_mode, u8"连接模式", "Mode", u8"Режим") \
|
||||
X(connection_mode_direct, u8"直连", "Direct", u8"Прямой") \
|
||||
X(connection_mode_relay, u8"中继", "Relay", u8"Релейный") \
|
||||
@@ -323,6 +343,34 @@ struct TranslationRow {
|
||||
X(permission_required_message, u8"该应用需要授权以下权限:", \
|
||||
"The application requires the following permissions:", \
|
||||
u8"Для работы приложения требуются следующие разрешения:") \
|
||||
X(wayland_notice_title, u8"Wayland 会话提示", "Wayland Session Notice", \
|
||||
u8"Уведомление о сеансе Wayland") \
|
||||
X(wayland_notice_subtitle, u8"检测到当前桌面会话使用 Wayland。", \
|
||||
"The current desktop session uses Wayland.", \
|
||||
u8"Текущий сеанс рабочего стола использует Wayland.") \
|
||||
X(wayland_permission_title, u8"每次共享均需本机授权", \
|
||||
"Local approval required each time", \
|
||||
u8"Разрешение требуется каждый раз") \
|
||||
X(wayland_notice_message, \
|
||||
u8"受 Wayland 安全机制限制,每次启动远程桌面共享时," \
|
||||
u8"均需在本机手动授权屏幕共享与远程控制,授权后方可正常使用。", \
|
||||
"Wayland security restrictions require you to authorize screen sharing " \
|
||||
"and remote control locally each time you start sharing this desktop. " \
|
||||
"Remote access is available only after authorization.", \
|
||||
u8"Из-за ограничений безопасности Wayland при каждом запуске общего " \
|
||||
u8"доступа к рабочему столу необходимо вручную разрешать на этом " \
|
||||
u8"компьютере показ экрана и удалённое управление. Удалённый доступ " \
|
||||
u8"возможен только после разрешения.") \
|
||||
X(wayland_recommendation_title, u8"建议使用 X11(Xorg)", \
|
||||
"X11 (Xorg) is recommended", u8"Рекомендуем X11 (Xorg)") \
|
||||
X(wayland_recommendation_message, \
|
||||
u8"为便于持续使用远程桌面,建议注销当前桌面会话," \
|
||||
u8"在登录界面选择 X11(Xorg)会话后重新登录。", \
|
||||
"For ongoing remote desktop access, we recommend logging out, selecting " \
|
||||
"an X11 (Xorg) session on the login screen, and logging in again.", \
|
||||
u8"Для постоянного удалённого доступа рекомендуем завершить сеанс, " \
|
||||
u8"выбрать X11 (Xorg) на экране входа и войти снова.") \
|
||||
X(wayland_notice_acknowledge, u8"我知道了", "Got it", u8"Понятно") \
|
||||
X(show_main_window, u8"显示主界面", "Show Main Window", \
|
||||
u8"Показать главное окно") \
|
||||
X(privacy_screen_unlock_hint, u8"按下快捷键,解除隐私屏", \
|
||||
|
||||
@@ -82,7 +82,7 @@ void SessionDeviceManager::RecordCaptureCadence(
|
||||
: capture_secure_callbacks_ == capture_callbacks_
|
||||
? "secure_desktop"
|
||||
: "mixed";
|
||||
LOG_INFO(
|
||||
LOG_DEBUG(
|
||||
"Capture delivery: source={} normal_callbacks={} secure_callbacks={} "
|
||||
"target_fps={} input_fps={:.2f} "
|
||||
"forwarded_fps={:.2f} callbacks={} rate_dropped={} "
|
||||
@@ -225,7 +225,7 @@ int SessionDeviceManager::InitializeScreenCapturer() {
|
||||
last_video_frame_stream_id_ != stream_id;
|
||||
if (resumed_after_gap || stream_changed) {
|
||||
if (RequestVideoKeyFrame(owner_.peer_, stream_id.c_str()) == 0) {
|
||||
LOG_INFO("Request video key frame before sending captured frame, "
|
||||
LOG_DEBUG("Request video key frame before sending captured frame, "
|
||||
"stream='{}', gap_ms={}, stream_changed={}",
|
||||
stream_id, duration_ms, stream_changed);
|
||||
}
|
||||
|
||||
@@ -298,7 +298,7 @@ void FileTransferManager::HandleAck(const char *data, size_t size) {
|
||||
uint32_t rate_bps = 0;
|
||||
if (props) {
|
||||
const uint32_t bitrate =
|
||||
props->net_traffic_stats_.data_outbound_stats.bitrate;
|
||||
props->net_traffic_stats_.DataOutboundBitrate();
|
||||
if (bitrate > 0 && state->file_sending_.load()) {
|
||||
rate_bps = static_cast<uint32_t>(bitrate * 0.99f);
|
||||
const uint32_t current_rate = state->file_send_rate_bps_.load();
|
||||
|
||||
@@ -87,6 +87,7 @@ struct SlintVideoPresenter::Impl {
|
||||
VideoRenderSize gl_image_size;
|
||||
VideoRenderSize gl_pending_size;
|
||||
bool gl_pending_dirty = false;
|
||||
VideoLatencyFrame gl_pending_timing;
|
||||
#endif
|
||||
|
||||
SurfaceState CurrentState() const {
|
||||
@@ -192,6 +193,7 @@ struct SlintVideoPresenter::Impl {
|
||||
glPixelStorei(GL_UNPACK_ALIGNMENT, previous_unpack_alignment);
|
||||
glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(previous_texture));
|
||||
gl_pending_dirty = false;
|
||||
gl_pending_timing.MarkSubmitted();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -322,7 +324,7 @@ SlintVideoPresenter::PresentResult SlintVideoPresenter::Present(
|
||||
impl_->seeded_frame_sequence[frame.remote_id] != frame.sequence) {
|
||||
const auto submit_result = impl_->renderer.SubmitCachedNv12(
|
||||
frame.remote_id, frame.nv12->data(), frame.nv12->size(), frame.width,
|
||||
frame.height);
|
||||
frame.height, frame.timing);
|
||||
if (submit_result == VideoRenderer::SubmitResult::submitted ||
|
||||
submit_result == VideoRenderer::SubmitResult::dropped) {
|
||||
impl_->seeded_frame_sequence[frame.remote_id] = frame.sequence;
|
||||
@@ -440,6 +442,7 @@ SlintVideoPresenter::PresentResult SlintVideoPresenter::Present(
|
||||
impl_->gl_pending_frame.swap(impl_->gl_conversion_frame);
|
||||
impl_->gl_pending_size = {output_width, output_height};
|
||||
impl_->gl_pending_dirty = true;
|
||||
impl_->gl_pending_timing = frame.timing;
|
||||
}
|
||||
const VideoRenderSize output_size{output_width, output_height};
|
||||
if (impl_->gl_image_size != output_size) {
|
||||
@@ -469,6 +472,7 @@ SlintVideoPresenter::PresentResult SlintVideoPresenter::Present(
|
||||
}
|
||||
|
||||
(*impl_->stream)->set_frame(slint::Image(std::move(pixels)));
|
||||
frame.timing.MarkSubmitted();
|
||||
(*impl_->stream)->set_has_frame(true);
|
||||
(*impl_->stream)->set_receiving_text("");
|
||||
result.width = frame.width;
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "rendering/video_latency.h"
|
||||
|
||||
namespace slint {
|
||||
template <typename T> class ComponentHandle;
|
||||
}
|
||||
@@ -42,6 +44,7 @@ public:
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
uint64_t sequence = 0;
|
||||
VideoLatencyFrame timing;
|
||||
};
|
||||
|
||||
struct PresentResult {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-26
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _VIDEO_LATENCY_H_
|
||||
#define _VIDEO_LATENCY_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class VideoLatencyStats;
|
||||
|
||||
// Travels with the exact queued pixels, including native frames. Its clock is
|
||||
// translated once at the receive callback; rendering needs no live PeerPtr.
|
||||
struct VideoLatencyFrame {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
std::shared_ptr<VideoLatencyStats> stats;
|
||||
uint64_t id = 0;
|
||||
Clock::time_point capture_time{};
|
||||
void MarkPresented(Clock::time_point now = Clock::now()) const;
|
||||
// Fallback for renderers which expose submission but no presentation time.
|
||||
void MarkSubmitted(Clock::time_point now = Clock::now()) const;
|
||||
};
|
||||
|
||||
class VideoLatencyStats
|
||||
: public std::enable_shared_from_this<VideoLatencyStats> {
|
||||
public:
|
||||
using Clock = VideoLatencyFrame::Clock;
|
||||
struct Snapshot {
|
||||
double average_ms;
|
||||
size_t samples;
|
||||
};
|
||||
|
||||
VideoLatencyFrame Frame(uint64_t captured_us, int64_t local_now_us,
|
||||
Clock::time_point now = Clock::now()) {
|
||||
if (captured_us == 0 || local_now_us <= 0 ||
|
||||
captured_us > uint64_t(local_now_us) ||
|
||||
uint64_t(local_now_us) - captured_us > 5'000'000)
|
||||
return {};
|
||||
std::lock_guard lock(mutex_);
|
||||
return {shared_from_this(), ++issued_id_,
|
||||
now - std::chrono::microseconds(local_now_us - captured_us)};
|
||||
}
|
||||
|
||||
void Record(const VideoLatencyFrame& frame, Clock::time_point now) {
|
||||
std::lock_guard lock(mutex_);
|
||||
// Redraws, cached snapshots and late completions must not count twice.
|
||||
if (frame.id <= last_id_) return;
|
||||
last_id_ = frame.id;
|
||||
const double ms =
|
||||
std::chrono::duration<double, std::milli>(now - frame.capture_time)
|
||||
.count();
|
||||
if (ms < 0 || ms > 5000) return;
|
||||
samples_.push_back({now, ms});
|
||||
Prune(now);
|
||||
}
|
||||
|
||||
std::optional<Snapshot> Get(Clock::time_point now = Clock::now()) {
|
||||
std::lock_guard lock(mutex_);
|
||||
Prune(now);
|
||||
if (samples_.empty()) return std::nullopt;
|
||||
double sum = 0;
|
||||
for (const auto& sample : samples_) {
|
||||
sum += sample.ms;
|
||||
}
|
||||
return Snapshot{sum / samples_.size(), samples_.size()};
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
std::lock_guard lock(mutex_);
|
||||
samples_.clear();
|
||||
last_id_ = issued_id_; // Invalidate frames still held by a renderer.
|
||||
}
|
||||
|
||||
private:
|
||||
void Prune(Clock::time_point now) {
|
||||
while (!samples_.empty() &&
|
||||
(now - samples_.front().time > std::chrono::seconds(1) ||
|
||||
samples_.size() > 240))
|
||||
samples_.pop_front();
|
||||
}
|
||||
struct Sample {
|
||||
Clock::time_point time;
|
||||
double ms;
|
||||
};
|
||||
std::mutex mutex_;
|
||||
uint64_t issued_id_ = 0;
|
||||
uint64_t last_id_ = 0;
|
||||
std::deque<Sample> samples_;
|
||||
};
|
||||
|
||||
inline void VideoLatencyFrame::MarkSubmitted(Clock::time_point now) const {
|
||||
MarkPresented(now);
|
||||
}
|
||||
|
||||
inline void VideoLatencyFrame::MarkPresented(Clock::time_point now) const {
|
||||
if (stats) stats->Record(*this, now);
|
||||
}
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,483 @@
|
||||
#include "runtime/announcement_inbox.h"
|
||||
|
||||
#include <openssl/sha.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <fstream>
|
||||
#include <set>
|
||||
#include <system_error>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
using nlohmann::json;
|
||||
bool Integer(const json& object, const char* key, int64_t low, int64_t high) {
|
||||
return object.contains(key) && object[key].is_number_integer() &&
|
||||
object[key] >= low && object[key] <= high;
|
||||
}
|
||||
std::string ScopeFilename(const std::string& scope) {
|
||||
unsigned char digest[SHA256_DIGEST_LENGTH];
|
||||
SHA256(reinterpret_cast<const unsigned char*>(scope.data()), scope.size(),
|
||||
digest);
|
||||
std::string name;
|
||||
constexpr char hex[] = "0123456789abcdef";
|
||||
for (auto byte : digest) {
|
||||
name += hex[byte >> 4];
|
||||
name += hex[byte & 15];
|
||||
}
|
||||
return name + ".json";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
AnnouncementInbox::Snapshot AnnouncementInbox::Get() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return state_;
|
||||
}
|
||||
uint64_t AnnouncementInbox::Version() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return state_.version;
|
||||
}
|
||||
void AnnouncementInbox::SetStorageDirectory(
|
||||
const std::filesystem::path& directory) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
directory_ = directory;
|
||||
}
|
||||
void AnnouncementInbox::Configure(std::string host, int port,
|
||||
const std::string& device_id) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (directory_.empty() || host.empty() || port <= 0 || device_id.empty())
|
||||
return;
|
||||
for (auto& ch : host)
|
||||
if (ch >= 'A' && ch <= 'Z') ch += 'a' - 'A';
|
||||
if (host.back() == '.') host.pop_back();
|
||||
const auto scope = json::array({host, port, device_id}).dump();
|
||||
if (scope_ == scope) return;
|
||||
scope_ = scope;
|
||||
read_file_ = directory_ / ScopeFilename(scope);
|
||||
const auto version = state_.version + 1;
|
||||
state_ = {};
|
||||
state_.version = version;
|
||||
catalog_.clear();
|
||||
catalog_revision_ = -1;
|
||||
page_ids_.clear();
|
||||
page_bodies_.clear();
|
||||
visible_limit_ = 20;
|
||||
LoadLocalState();
|
||||
BeginCatalog();
|
||||
}
|
||||
void AnnouncementInbox::Reset() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const auto version = state_.version + 1;
|
||||
state_ = {};
|
||||
state_.version = version;
|
||||
scope_.clear();
|
||||
read_file_.clear();
|
||||
reads_.clear();
|
||||
dismissed_.clear();
|
||||
page_ids_.clear();
|
||||
page_bodies_.clear();
|
||||
visible_limit_ = 20;
|
||||
catalog_.clear();
|
||||
catalog_revision_ = -1;
|
||||
connected_ = false;
|
||||
BeginCatalog();
|
||||
}
|
||||
void AnnouncementInbox::BeginCatalog() {
|
||||
pending_catalog_.clear();
|
||||
pending_revision_ = -1;
|
||||
pending_total_ = 0;
|
||||
phase_ = Phase::Catalog;
|
||||
request_id_.clear();
|
||||
state_.loading = false;
|
||||
refresh_ = connected_;
|
||||
++state_.version;
|
||||
}
|
||||
void AnnouncementInbox::SetConnected(bool connected) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
connected_ = connected;
|
||||
BeginCatalog();
|
||||
}
|
||||
void AnnouncementInbox::Refresh() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
BeginCatalog();
|
||||
}
|
||||
void AnnouncementInbox::LoadMore() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!connected_ || state_.loading || refresh_ || state_.failed ||
|
||||
catalog_revision_ < 0 || visible_limit_ >= state_.total)
|
||||
return;
|
||||
visible_limit_ += (std::min)(20, state_.total - visible_limit_);
|
||||
RebuildVisibleItems();
|
||||
++state_.version;
|
||||
}
|
||||
void AnnouncementInbox::UpdateReadingState() {
|
||||
state_.total = 0;
|
||||
state_.unread = 0;
|
||||
for (const auto& [id, revision] : catalog_) {
|
||||
if (IsDismissed(id, revision)) continue;
|
||||
++state_.total;
|
||||
const auto read = reads_.find(id);
|
||||
if (read == reads_.end() || read->second != revision) ++state_.unread;
|
||||
}
|
||||
for (auto& item : state_.items) {
|
||||
const auto read = reads_.find(item["id"]);
|
||||
item["read"] = read != reads_.end() && read->second == item["revision"];
|
||||
}
|
||||
}
|
||||
bool AnnouncementInbox::Read(int64_t id, int64_t revision) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (const auto& item : state_.items) {
|
||||
if (item["id"] != id || item["revision"] != revision) continue;
|
||||
if (item["read"].get<bool>()) return true;
|
||||
auto updated = reads_;
|
||||
updated[id] = revision;
|
||||
if (!SaveLocalState(updated, dismissed_)) {
|
||||
state_.read_save_failed = true;
|
||||
++state_.version;
|
||||
return false;
|
||||
}
|
||||
reads_ = std::move(updated);
|
||||
state_.read_save_failed = false;
|
||||
state_.delete_failed = false;
|
||||
UpdateReadingState();
|
||||
++state_.version;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool AnnouncementInbox::IsDismissed(int64_t id, int64_t revision) const {
|
||||
const auto found = dismissed_.find(id);
|
||||
return found != dismissed_.end() && found->second == revision;
|
||||
}
|
||||
|
||||
bool AnnouncementInbox::Dismiss(int64_t id, int64_t revision) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (const auto& item : state_.items) {
|
||||
if (item["id"] != id || item["revision"] != revision) continue;
|
||||
auto updated = dismissed_;
|
||||
updated[id] = revision;
|
||||
if (!SaveLocalState(reads_, updated)) {
|
||||
state_.delete_failed = true;
|
||||
++state_.version;
|
||||
return false;
|
||||
}
|
||||
dismissed_ = std::move(updated);
|
||||
state_.delete_failed = false;
|
||||
state_.read_save_failed = false;
|
||||
// An index refresh already in flight must finish before reusing its order.
|
||||
if (phase_ == Phase::Catalog && (state_.loading || refresh_)) {
|
||||
auto visible = json::array();
|
||||
for (const auto& current : state_.items)
|
||||
if (!IsDismissed(current["id"], current["revision"]))
|
||||
visible.push_back(current);
|
||||
state_.items = std::move(visible);
|
||||
UpdateReadingState();
|
||||
} else {
|
||||
request_id_.clear();
|
||||
state_.loading = false;
|
||||
RebuildVisibleItems();
|
||||
}
|
||||
++state_.version;
|
||||
return true;
|
||||
}
|
||||
// The confirmation may refer to an announcement updated while it was open.
|
||||
state_.delete_failed = true;
|
||||
++state_.version;
|
||||
return false;
|
||||
}
|
||||
|
||||
void AnnouncementInbox::RebuildVisibleItems() {
|
||||
UpdateReadingState();
|
||||
const int wanted = (std::min)(visible_limit_, state_.total);
|
||||
auto visible = json::array();
|
||||
std::set<int> retained_pages;
|
||||
int position = 0;
|
||||
phase_ = Phase::Page;
|
||||
refresh_ = false;
|
||||
for (int physical = 0;
|
||||
wanted > 0 && physical < static_cast<int>(catalog_.size());
|
||||
physical += 20) {
|
||||
const auto ids = page_ids_.find(physical);
|
||||
if (ids == page_ids_.end()) {
|
||||
pending_page_offset_ = physical;
|
||||
refresh_ = connected_;
|
||||
break;
|
||||
}
|
||||
std::set<int64_t> page_selection;
|
||||
for (auto id : ids->second) {
|
||||
const auto entry = catalog_.find(id);
|
||||
if (entry == catalog_.end() || IsDismissed(id, entry->second)) continue;
|
||||
if (position < wanted) page_selection.insert(id);
|
||||
++position;
|
||||
}
|
||||
if (page_selection.empty()) {
|
||||
page_bodies_.erase(physical);
|
||||
continue;
|
||||
}
|
||||
retained_pages.insert(physical);
|
||||
const auto bodies = page_bodies_.find(physical);
|
||||
if (bodies == page_bodies_.end()) {
|
||||
pending_page_offset_ = physical;
|
||||
refresh_ = connected_;
|
||||
break;
|
||||
}
|
||||
for (const auto& item : bodies->second)
|
||||
if (page_selection.count(item["id"])) visible.push_back(item);
|
||||
if (visible.size() == static_cast<size_t>(wanted)) break;
|
||||
}
|
||||
if (visible.size() == static_cast<size_t>(wanted)) {
|
||||
for (auto it = page_bodies_.begin(); it != page_bodies_.end();)
|
||||
if (!retained_pages.count(it->first))
|
||||
it = page_bodies_.erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
// A failed body fetch must not erase announcements already received. Keep
|
||||
// still-published, unchanged versions until the replacement batch arrives.
|
||||
if (visible.size() < static_cast<size_t>(wanted)) {
|
||||
std::set<int64_t> retained_ids;
|
||||
for (const auto& item : visible) retained_ids.insert(item["id"].get<int64_t>());
|
||||
for (const auto& item : state_.items) {
|
||||
const int64_t id = item["id"];
|
||||
const auto current = catalog_.find(id);
|
||||
if (current == catalog_.end() || current->second != item["revision"] ||
|
||||
IsDismissed(id, current->second) || !retained_ids.insert(id).second)
|
||||
continue;
|
||||
visible.push_back(item);
|
||||
if (visible.size() == static_cast<size_t>(wanted)) break;
|
||||
}
|
||||
}
|
||||
state_.items = std::move(visible);
|
||||
state_.loaded = true;
|
||||
UpdateReadingState();
|
||||
}
|
||||
|
||||
void AnnouncementInbox::Fail() {
|
||||
request_id_.clear();
|
||||
refresh_ = false;
|
||||
state_.loading = false;
|
||||
state_.failed = true;
|
||||
++state_.version;
|
||||
}
|
||||
nlohmann::json AnnouncementInbox::TakePendingRequest(
|
||||
std::chrono::steady_clock::time_point now) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!connected_ || scope_.empty()) return nullptr;
|
||||
if (state_.loading && now >= deadline_) Fail();
|
||||
if (!refresh_) return nullptr;
|
||||
refresh_ = false;
|
||||
request_id_ = std::to_string(++serial_);
|
||||
state_.loading = true;
|
||||
state_.failed = false;
|
||||
++state_.version;
|
||||
deadline_ = now + std::chrono::seconds(12);
|
||||
return {{"type", "announcements_list"},
|
||||
{"request_id", request_id_},
|
||||
{"summary_only", phase_ == Phase::Catalog},
|
||||
{"offset", phase_ == Phase::Catalog
|
||||
? static_cast<int>(pending_catalog_.size())
|
||||
: pending_page_offset_}};
|
||||
}
|
||||
void AnnouncementInbox::Failed(const std::string& request_id) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (request_id == request_id_) Fail();
|
||||
}
|
||||
void AnnouncementInbox::Receive(const nlohmann::json& message) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!message.is_object() || !message.contains("request_id") ||
|
||||
message["request_id"] != request_id_ || request_id_.empty())
|
||||
return;
|
||||
if (message.contains("error")) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
const bool summary = phase_ == Phase::Catalog;
|
||||
const int limit = summary ? 200 : 20;
|
||||
if (!Integer(message, "offset", 0, INT32_MAX) ||
|
||||
!Integer(message, "total", 0, INT32_MAX) ||
|
||||
!Integer(message, "catalog_revision", 0, INT64_MAX) ||
|
||||
!message.contains("summary_only") || message["summary_only"] != summary ||
|
||||
!message.contains("items") || !message["items"].is_array() ||
|
||||
message["items"].size() > static_cast<size_t>(limit)) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
const int offset = message["offset"], total = message["total"];
|
||||
const int64_t revision = message["catalog_revision"];
|
||||
if (offset > total ||
|
||||
message["items"].size() !=
|
||||
static_cast<size_t>((std::min)(limit, total - offset))) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
const auto expected_revision =
|
||||
summary ? pending_revision_ : catalog_revision_;
|
||||
if (expected_revision >= 0 && expected_revision != revision) {
|
||||
BeginCatalog();
|
||||
return;
|
||||
}
|
||||
for (const auto& item : message["items"]) {
|
||||
if (!item.is_object() || !Integer(item, "id", 1, INT64_MAX) ||
|
||||
!Integer(item, "revision", 1, INT64_MAX)) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
if (!summary) {
|
||||
if (!Integer(item, "updated_at", 1, 32503680000LL)) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
for (const auto* key : {"title", "body"}) {
|
||||
if (!item.contains(key) || !item[key].is_string() ||
|
||||
item[key].get_ref<const std::string&>().size() >
|
||||
(std::string(key) == "title" ? 240u : 8000u)) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const auto found = catalog_.find(item["id"]);
|
||||
if (found == catalog_.end() || found->second != item["revision"]) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
request_id_.clear();
|
||||
state_.loading = false;
|
||||
if (summary) {
|
||||
if (pending_revision_ < 0) {
|
||||
pending_revision_ = revision;
|
||||
pending_total_ = total;
|
||||
}
|
||||
if (pending_total_ != total ||
|
||||
offset != static_cast<int>(pending_catalog_.size())) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
for (const auto& item : message["items"]) {
|
||||
if (!pending_catalog_.emplace(item["id"], item["revision"]).second) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (static_cast<int>(pending_catalog_.size()) < total) {
|
||||
refresh_ = true;
|
||||
++state_.version;
|
||||
return;
|
||||
}
|
||||
if (catalog_revision_ != revision) {
|
||||
page_ids_.clear();
|
||||
page_bodies_.clear();
|
||||
}
|
||||
catalog_ = std::move(pending_catalog_);
|
||||
catalog_revision_ = revision;
|
||||
// Prune expired records in memory; the next local action persists them.
|
||||
for (auto* records : {&reads_, &dismissed_}) {
|
||||
for (auto it = records->begin(); it != records->end();)
|
||||
if (!catalog_.count(it->first))
|
||||
it = records->erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
} else {
|
||||
if (total != static_cast<int>(catalog_.size())) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
if (offset != pending_page_offset_) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
std::set<int64_t> unique;
|
||||
std::vector<int64_t> ids;
|
||||
for (const auto& item : message["items"]) {
|
||||
const int64_t id = item["id"];
|
||||
if (!unique.insert(id).second) {
|
||||
Fail();
|
||||
return;
|
||||
}
|
||||
ids.push_back(id);
|
||||
}
|
||||
page_ids_[offset] = std::move(ids);
|
||||
page_bodies_[offset] = message["items"];
|
||||
}
|
||||
RebuildVisibleItems();
|
||||
state_.failed = false;
|
||||
++state_.version;
|
||||
}
|
||||
|
||||
void AnnouncementInbox::LoadLocalState() {
|
||||
reads_.clear();
|
||||
dismissed_.clear();
|
||||
std::error_code ec;
|
||||
const auto size = std::filesystem::file_size(read_file_, ec);
|
||||
if (ec || size > 16 * 1024 * 1024) return;
|
||||
std::ifstream input(read_file_, std::ios::binary);
|
||||
const auto data = json::parse(input, nullptr, false);
|
||||
if (!data.is_object() || !data.contains("scope") || data["scope"] != scope_ ||
|
||||
!data.contains("version") ||
|
||||
(data["version"] != 1 && data["version"] != 2) ||
|
||||
!data.contains("reads") || !data["reads"].is_object())
|
||||
return;
|
||||
const auto load = [](const json& entries, Revisions& destination) {
|
||||
if (!entries.is_object()) return;
|
||||
for (const auto& entry : entries.items()) {
|
||||
int64_t id = 0;
|
||||
const auto parsed = std::from_chars(
|
||||
entry.key().data(), entry.key().data() + entry.key().size(), id);
|
||||
if (parsed.ec == std::errc{} &&
|
||||
parsed.ptr == entry.key().data() + entry.key().size() && id > 0 &&
|
||||
entry.value().is_number_integer() && entry.value() > 0 &&
|
||||
entry.value() <= INT64_MAX)
|
||||
destination[id] = entry.value();
|
||||
}
|
||||
};
|
||||
load(data["reads"], reads_);
|
||||
if (data.contains("dismissed")) load(data["dismissed"], dismissed_);
|
||||
}
|
||||
bool AnnouncementInbox::SaveLocalState(const Revisions& reads,
|
||||
const Revisions& dismissed) const {
|
||||
if (read_file_.empty()) return false;
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(directory_, ec);
|
||||
if (ec) return false;
|
||||
const auto encode = [](const Revisions& records) {
|
||||
auto entries = json::object();
|
||||
for (const auto& [id, revision] : records)
|
||||
entries[std::to_string(id)] = revision;
|
||||
return entries;
|
||||
};
|
||||
const auto payload = json({{"version", 2},
|
||||
{"scope", scope_},
|
||||
{"reads", encode(reads)},
|
||||
{"dismissed", encode(dismissed)}})
|
||||
.dump();
|
||||
auto temporary = read_file_;
|
||||
temporary += ".tmp-" +
|
||||
std::to_string(
|
||||
std::chrono::steady_clock::now().time_since_epoch().count());
|
||||
{
|
||||
std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
|
||||
output.write(payload.data(), static_cast<std::streamsize>(payload.size()));
|
||||
output.close();
|
||||
if (!output) {
|
||||
std::filesystem::remove(temporary, ec);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#ifdef _WIN32
|
||||
const bool saved =
|
||||
MoveFileExW(temporary.c_str(), read_file_.c_str(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
|
||||
#else
|
||||
std::filesystem::rename(temporary, read_file_, ec);
|
||||
const bool saved = !ec;
|
||||
#endif
|
||||
if (!saved) std::filesystem::remove(temporary, ec);
|
||||
return saved;
|
||||
}
|
||||
} // namespace crossdesk
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-29
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _ANNOUNCEMENT_INBOX_H_
|
||||
#define _ANNOUNCEMENT_INBOX_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
// Announcement data is shared; read and dismissed versions stay on this device.
|
||||
class AnnouncementInbox {
|
||||
public:
|
||||
struct Snapshot {
|
||||
nlohmann::json items = nlohmann::json::array();
|
||||
int total = 0, unread = 0;
|
||||
bool loaded = false, loading = false, failed = false;
|
||||
bool read_save_failed = false;
|
||||
bool delete_failed = false;
|
||||
uint64_t version = 0;
|
||||
};
|
||||
Snapshot Get() const;
|
||||
uint64_t Version() const;
|
||||
void SetStorageDirectory(const std::filesystem::path& directory);
|
||||
// Called on the UI thread after login supplies the actual device ID.
|
||||
void Configure(std::string host, int port, const std::string& device_id);
|
||||
void Reset();
|
||||
void SetConnected(bool connected);
|
||||
void Refresh();
|
||||
void LoadMore();
|
||||
bool Read(int64_t id, int64_t revision);
|
||||
bool Dismiss(int64_t id, int64_t revision);
|
||||
nlohmann::json TakePendingRequest(std::chrono::steady_clock::time_point now =
|
||||
std::chrono::steady_clock::now());
|
||||
void Failed(const std::string& request_id);
|
||||
void Receive(const nlohmann::json& message);
|
||||
|
||||
private:
|
||||
using Revisions = std::map<int64_t, int64_t>;
|
||||
enum class Phase { Catalog, Page };
|
||||
void BeginCatalog();
|
||||
void Fail();
|
||||
void UpdateReadingState();
|
||||
bool IsDismissed(int64_t id, int64_t revision) const;
|
||||
void RebuildVisibleItems();
|
||||
void LoadLocalState();
|
||||
bool SaveLocalState(const Revisions& reads, const Revisions& dismissed) const;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
Snapshot state_;
|
||||
std::filesystem::path directory_, read_file_;
|
||||
std::string scope_, request_id_;
|
||||
Revisions reads_, dismissed_, catalog_, pending_catalog_;
|
||||
// Keep bodies for the loaded list prefix. Lightweight page IDs let us skip
|
||||
// locally deleted entries without sending deletion state upstream.
|
||||
std::map<int, std::vector<int64_t>> page_ids_;
|
||||
std::map<int, nlohmann::json> page_bodies_;
|
||||
int pending_page_offset_ = 0;
|
||||
int visible_limit_ = 20;
|
||||
int64_t catalog_revision_ = -1, pending_revision_ = -1;
|
||||
int pending_total_ = 0;
|
||||
Phase phase_ = Phase::Catalog;
|
||||
bool connected_ = false, refresh_ = false;
|
||||
uint64_t serial_ = 0;
|
||||
std::chrono::steady_clock::time_point deadline_{};
|
||||
};
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-26
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CONNECTION_LATENCY_H_
|
||||
#define _CONNECTION_LATENCY_H_
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
|
||||
namespace crossdesk::gui_detail {
|
||||
|
||||
// Presentation-only smoothing. The transport's raw RTT remains available for
|
||||
// recovery, congestion control and diagnostics. A missing one-second report
|
||||
// does not flicker, but a disconnected/stalled peer cannot leave a stale value.
|
||||
class ConnectionLatencyStats {
|
||||
public:
|
||||
using Clock = std::chrono::steady_clock;
|
||||
|
||||
void Update(double rtt_ms, Clock::time_point now = Clock::now()) {
|
||||
if (!std::isfinite(rtt_ms) || rtt_ms < 0 || rtt_ms > 2000) return;
|
||||
std::lock_guard lock(mutex_);
|
||||
if (average_ms_ && now < updated_) return;
|
||||
if (!Fresh(now)) {
|
||||
average_ms_ = rtt_ms;
|
||||
} else {
|
||||
*average_ms_ += 0.25 * (rtt_ms - *average_ms_);
|
||||
}
|
||||
updated_ = now;
|
||||
}
|
||||
|
||||
std::optional<double> Get(Clock::time_point now = Clock::now()) const {
|
||||
std::lock_guard lock(mutex_);
|
||||
return Fresh(now) ? average_ms_ : std::nullopt;
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
std::lock_guard lock(mutex_);
|
||||
average_ms_.reset();
|
||||
}
|
||||
|
||||
private:
|
||||
bool Fresh(Clock::time_point now) const {
|
||||
// The UI may snapshot `now` just before the report thread updates us.
|
||||
// A newer valid report must not cause a one-frame unavailable flicker.
|
||||
return average_ms_ && now - updated_ < std::chrono::seconds(3);
|
||||
}
|
||||
mutable std::mutex mutex_;
|
||||
std::optional<double> average_ms_;
|
||||
Clock::time_point updated_{};
|
||||
};
|
||||
|
||||
} // namespace crossdesk::gui_detail
|
||||
|
||||
#endif
|
||||
@@ -236,7 +236,8 @@ void GuiRuntime::CloseRemoteSession(std::shared_ptr<RemoteSession> props) {
|
||||
std::shared_ptr<std::vector<unsigned char>> frame_snapshot;
|
||||
int video_width = 0;
|
||||
int video_height = 0;
|
||||
{
|
||||
const bool save_preview = config_center_->IsSaveRemotePreviews();
|
||||
if (save_preview) {
|
||||
std::lock_guard<std::mutex> lock(props->video_frame_mutex_);
|
||||
frame_snapshot = props->front_frame_;
|
||||
video_width = props->video_width_;
|
||||
@@ -249,7 +250,8 @@ void GuiRuntime::CloseRemoteSession(std::shared_ptr<RemoteSession> props) {
|
||||
}
|
||||
}
|
||||
auto* native_renderer = video_renderer_.get();
|
||||
if ((!frame_snapshot || frame_snapshot->empty()) && native_renderer) {
|
||||
if (save_preview && (!frame_snapshot || frame_snapshot->empty()) &&
|
||||
native_renderer) {
|
||||
auto native_snapshot = std::make_shared<std::vector<unsigned char>>();
|
||||
if (native_renderer->CopyLatestNv12(props->remote_id_,
|
||||
native_snapshot.get(), &video_width,
|
||||
@@ -269,9 +271,14 @@ void GuiRuntime::CloseRemoteSession(std::shared_ptr<RemoteSession> props) {
|
||||
std::unique_lock lock(remote_sessions_mutex_);
|
||||
peer = std::exchange(props->peer_, nullptr);
|
||||
}
|
||||
HostPlatform platform;
|
||||
{
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
platform = props->recent_platform_;
|
||||
}
|
||||
const auto queued_at = std::chrono::steady_clock::now();
|
||||
session_cleanup_tasks_[props->remote_id_] = session_cleanup_queue_.PostTask(
|
||||
[props, peer, frame_snapshot, video_width, video_height,
|
||||
[props, peer, frame_snapshot, video_width, video_height, platform,
|
||||
thumbnail = thumbnail_, queued_at]() mutable {
|
||||
if (peer) {
|
||||
LOG_INFO("[{}] Background leave connection [{}]", props->local_id_,
|
||||
@@ -279,12 +286,16 @@ void GuiRuntime::CloseRemoteSession(std::shared_ptr<RemoteSession> props) {
|
||||
LeaveConnection(peer, props->remote_id_.c_str());
|
||||
DestroyPeer(&peer);
|
||||
}
|
||||
if (thumbnail && frame_snapshot && !frame_snapshot->empty() &&
|
||||
video_width > 0 && video_height > 0) {
|
||||
thumbnail->SaveToThumbnail(
|
||||
reinterpret_cast<char*>(frame_snapshot->data()), video_width,
|
||||
video_height, props->remote_id_, props->remote_host_name_,
|
||||
props->remember_password_ ? props->remote_password_ : "");
|
||||
if (thumbnail && props->was_connected_) {
|
||||
const char* nv12 = frame_snapshot && !frame_snapshot->empty()
|
||||
? reinterpret_cast<const char*>(frame_snapshot->data()) : nullptr;
|
||||
if (thumbnail->SaveToThumbnail(
|
||||
nv12, video_width, video_height, props->remote_id_,
|
||||
props->remote_host_name_,
|
||||
props->remember_password_ ? props->remote_password_ : "",
|
||||
platform) != 0) {
|
||||
LOG_ERROR("[{}] Failed to save recent connection", props->remote_id_);
|
||||
}
|
||||
}
|
||||
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - queued_at).count();
|
||||
@@ -301,8 +312,12 @@ void GuiRuntime::CloseServerController(const std::string& remote_id) {
|
||||
}
|
||||
|
||||
void GuiRuntime::CloseConnectionPeer() {
|
||||
if (!peer_) return;
|
||||
if (!peer_) {
|
||||
announcements_.Reset();
|
||||
return;
|
||||
}
|
||||
peer_events_->Deactivate();
|
||||
announcements_.Reset();
|
||||
std::vector<std::string> controllers;
|
||||
{
|
||||
std::shared_lock lock(connection_status_mutex_);
|
||||
@@ -417,8 +432,11 @@ void GuiRuntime::WaitForSessionCleanup() {
|
||||
|
||||
void GuiRuntime::ResetRemoteSessionResources(
|
||||
std::shared_ptr<RemoteSession> props) {
|
||||
props->net_traffic_stats_.Reset();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->video_frame_mutex_);
|
||||
props->video_latency_->Reset();
|
||||
props->video_frame_timing_ = {};
|
||||
props->front_frame_.reset();
|
||||
props->back_frame_.reset();
|
||||
props->thumbnail_frame_.reset();
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include "features/settings/settings_manager.h"
|
||||
#include "privacy_controller.h"
|
||||
#include "runtime/gui_state.h"
|
||||
#include "runtime/announcement_inbox.h"
|
||||
#include "runtime/peer_event_handler.h"
|
||||
#include "runtime/privacy_session_policy.h"
|
||||
|
||||
@@ -99,6 +100,7 @@ class GuiRuntime : protected gui_detail::GuiState {
|
||||
#endif
|
||||
|
||||
PrivacyController privacy_;
|
||||
AnnouncementInbox announcements_;
|
||||
PrivacySessionPolicy privacy_sessions_;
|
||||
std::mutex privacy_commands_mutex_;
|
||||
std::deque<std::pair<std::string, PrivacyCommand>> privacy_commands_;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-26
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _NET_TRAFFIC_STATS_CACHE_H_
|
||||
#define _NET_TRAFFIC_STATS_CACHE_H_
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#include "minirtc.h"
|
||||
#include "runtime/connection_latency.h"
|
||||
|
||||
namespace crossdesk::gui_detail {
|
||||
|
||||
// Fields are independent observations and may come from different reports.
|
||||
// Relaxed accesses keep each field safe without publishing any other state.
|
||||
class NetTrafficStatsCache {
|
||||
static_assert(std::atomic<uint32_t>::is_always_lock_free &&
|
||||
std::atomic<float>::is_always_lock_free &&
|
||||
std::atomic<double>::is_always_lock_free &&
|
||||
std::atomic<bool>::is_always_lock_free,
|
||||
"Network statistics require lock-free scalar atomics");
|
||||
|
||||
public:
|
||||
void Store(const MiniRtcNetTrafficStats& stats) {
|
||||
video_inbound_stats_.Store(stats.video_inbound_stats);
|
||||
video_outbound_stats_.Store(stats.video_outbound_stats);
|
||||
audio_inbound_stats_.Store(stats.audio_inbound_stats);
|
||||
audio_outbound_stats_.Store(stats.audio_outbound_stats);
|
||||
data_inbound_stats_.Store(stats.data_inbound_stats);
|
||||
data_outbound_stats_.Store(stats.data_outbound_stats);
|
||||
total_inbound_stats_.Store(stats.total_inbound_stats);
|
||||
total_outbound_stats_.Store(stats.total_outbound_stats);
|
||||
srtp_active_.store(stats.srtp_active, std::memory_order_relaxed);
|
||||
rtt_ms_.store(stats.rtt_ms, std::memory_order_relaxed);
|
||||
connection_latency_.Update(stats.rtt_ms);
|
||||
}
|
||||
|
||||
MiniRtcNetTrafficStats Load() const {
|
||||
MiniRtcNetTrafficStats stats{};
|
||||
stats.video_inbound_stats = video_inbound_stats_.Load();
|
||||
stats.video_outbound_stats = video_outbound_stats_.Load();
|
||||
stats.audio_inbound_stats = audio_inbound_stats_.Load();
|
||||
stats.audio_outbound_stats = audio_outbound_stats_.Load();
|
||||
stats.data_inbound_stats = data_inbound_stats_.Load();
|
||||
stats.data_outbound_stats = data_outbound_stats_.Load();
|
||||
stats.total_inbound_stats = total_inbound_stats_.Load();
|
||||
stats.total_outbound_stats = total_outbound_stats_.Load();
|
||||
stats.srtp_active = srtp_active_.load(std::memory_order_relaxed);
|
||||
stats.rtt_ms = rtt_ms_.load(std::memory_order_relaxed);
|
||||
return stats;
|
||||
}
|
||||
|
||||
uint32_t DataOutboundBitrate() const {
|
||||
return data_outbound_stats_.bitrate.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
std::optional<double> SmoothedRttMs(
|
||||
ConnectionLatencyStats::Clock::time_point now =
|
||||
ConnectionLatencyStats::Clock::now()) const {
|
||||
return connection_latency_.Get(now);
|
||||
}
|
||||
|
||||
void ResetLatency() { connection_latency_.Reset(); }
|
||||
|
||||
void Reset() {
|
||||
Store(MiniRtcNetTrafficStats{});
|
||||
ResetLatency();
|
||||
}
|
||||
|
||||
private:
|
||||
struct InboundStats {
|
||||
void Store(const MiniRtcInboundStats& stats) {
|
||||
bitrate.store(stats.bitrate, std::memory_order_relaxed);
|
||||
rtp_packet_count.store(stats.rtp_packet_count, std::memory_order_relaxed);
|
||||
loss_rate.store(stats.loss_rate, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
MiniRtcInboundStats Load() const {
|
||||
return {bitrate.load(std::memory_order_relaxed),
|
||||
rtp_packet_count.load(std::memory_order_relaxed),
|
||||
loss_rate.load(std::memory_order_relaxed)};
|
||||
}
|
||||
|
||||
std::atomic<uint32_t> bitrate{0};
|
||||
std::atomic<uint32_t> rtp_packet_count{0};
|
||||
std::atomic<float> loss_rate{0};
|
||||
};
|
||||
|
||||
struct OutboundStats {
|
||||
void Store(const MiniRtcOutboundStats& stats) {
|
||||
bitrate.store(stats.bitrate, std::memory_order_relaxed);
|
||||
rtp_packet_count.store(stats.rtp_packet_count, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
MiniRtcOutboundStats Load() const {
|
||||
return {bitrate.load(std::memory_order_relaxed),
|
||||
rtp_packet_count.load(std::memory_order_relaxed)};
|
||||
}
|
||||
|
||||
std::atomic<uint32_t> bitrate{0};
|
||||
std::atomic<uint32_t> rtp_packet_count{0};
|
||||
};
|
||||
|
||||
InboundStats video_inbound_stats_;
|
||||
OutboundStats video_outbound_stats_;
|
||||
InboundStats audio_inbound_stats_;
|
||||
OutboundStats audio_outbound_stats_;
|
||||
InboundStats data_inbound_stats_;
|
||||
OutboundStats data_outbound_stats_;
|
||||
InboundStats total_inbound_stats_;
|
||||
OutboundStats total_outbound_stats_;
|
||||
std::atomic<bool> srtp_active_{false};
|
||||
std::atomic<double> rtt_ms_{-1};
|
||||
ConnectionLatencyStats connection_latency_;
|
||||
};
|
||||
|
||||
} // namespace crossdesk::gui_detail
|
||||
|
||||
#endif
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "runtime/peer_event_handler.h"
|
||||
|
||||
#include <app_version.h>
|
||||
#include <remote_action.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -294,7 +295,7 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
props->remote_cursor_state_received_ = true;
|
||||
props->cursor_presentation_.Observe(merged, SDL_GetTicks());
|
||||
if (changed) {
|
||||
LOG_INFO("Received cursor state: seq={}, visible={}, shape={}, "
|
||||
LOG_DEBUG("Received cursor state: seq={}, visible={}, shape={}, "
|
||||
"mode={}, reason={}",
|
||||
remote_action.cs.seq, remote_action.cs.visible,
|
||||
static_cast<int>(remote_action.cs.shape),
|
||||
@@ -318,6 +319,14 @@ void PeerEventHandler::OnReceiveDataBuffer(
|
||||
}
|
||||
|
||||
if (is_client_mode) {
|
||||
if (props && source_id == props->control_data_label_) {
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
props->remote_host_info_received_ = true;
|
||||
props->remote_platform_ = remote_action.i.platform;
|
||||
props->recent_platform_ = remote_action.i.platform;
|
||||
props->remote_app_version_ = IsValidAppVersion(remote_action.i.app_version)
|
||||
? remote_action.i.app_version : "";
|
||||
}
|
||||
// Negotiate live settings only on the reliable control stream. Old
|
||||
// hosts omit this capability and retain their existing video behavior.
|
||||
if (props && source_id == props->control_data_label_) {
|
||||
|
||||
@@ -32,6 +32,19 @@
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
#if defined(_WIN32)
|
||||
constexpr HostPlatform kClientPlatform = HostPlatform::Windows;
|
||||
#elif defined(__APPLE__)
|
||||
constexpr HostPlatform kClientPlatform = HostPlatform::MacOS;
|
||||
#elif defined(__linux__)
|
||||
constexpr HostPlatform kClientPlatform = HostPlatform::Linux;
|
||||
#else
|
||||
constexpr HostPlatform kClientPlatform = HostPlatform::Unknown;
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
void PeerEventHandler::SendClientInfo(PeerPtr* peer,
|
||||
const std::string& client_id) {
|
||||
@@ -39,19 +52,9 @@ void PeerEventHandler::SendClientInfo(PeerPtr* peer,
|
||||
return;
|
||||
}
|
||||
|
||||
#if defined(_WIN32)
|
||||
constexpr const char* kClientPlatform = "windows";
|
||||
#elif defined(__APPLE__)
|
||||
constexpr const char* kClientPlatform = "macos";
|
||||
#elif defined(__linux__)
|
||||
constexpr const char* kClientPlatform = "linux";
|
||||
#else
|
||||
constexpr const char* kClientPlatform = "unknown";
|
||||
#endif
|
||||
|
||||
const nlohmann::json message = {{"type", "client_info"},
|
||||
{"version", CROSSDESK_VERSION},
|
||||
{"platform", kClientPlatform}};
|
||||
{"platform", HostPlatformName(kClientPlatform)}};
|
||||
const std::string payload = message.dump();
|
||||
if (SendSignalMessage(peer, payload.data(), payload.size()) != 0) {
|
||||
LOG_WARN("[{}] failed to report client information", client_id);
|
||||
@@ -76,7 +79,11 @@ void PeerEventHandler::OnSignalMessage(const char* message, size_t size,
|
||||
return;
|
||||
}
|
||||
std::string type = j["type"].get<std::string>();
|
||||
if (type == "presence") {
|
||||
if (type == "announcements_changed") {
|
||||
runtime->announcements_.Refresh();
|
||||
} else if (type == "announcements") {
|
||||
runtime->announcements_.Receive(j);
|
||||
} else if (type == "presence") {
|
||||
if (j.contains("devices") && j["devices"].is_array()) {
|
||||
for (auto& dev : j["devices"]) {
|
||||
if (!dev.is_object()) {
|
||||
@@ -169,6 +176,7 @@ void PeerEventHandler::OnSignalStatus(SignalStatus status, const char* user_id,
|
||||
|
||||
std::string client_id(user_id, user_id_size);
|
||||
if (client_id == runtime->client_id_) {
|
||||
runtime->announcements_.SetConnected(status == SignalStatus::SignalConnected);
|
||||
runtime->signal_status_ = status;
|
||||
runtime->device_presence_cache_.SetSignalConnected(
|
||||
status == SignalStatus::SignalConnected);
|
||||
@@ -270,7 +278,8 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
{
|
||||
RemoteAction remote_action = MakeHostInformation(
|
||||
GetHostName(), runtime->devices_.host_display_list(),
|
||||
/*supports_privacy_screen=*/true);
|
||||
/*supports_privacy_screen=*/true, CROSSDESK_VERSION,
|
||||
kClientPlatform);
|
||||
remote_action.i.supports_video_settings = true;
|
||||
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
|
||||
LOG_INFO("Local display [{}:{}]", i + 1,
|
||||
@@ -291,6 +300,7 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
runtime->need_to_create_stream_window_ = true;
|
||||
}
|
||||
props->connection_established_ = true;
|
||||
props->was_connected_ = true;
|
||||
runtime->start_keyboard_capturer_ = true;
|
||||
break;
|
||||
}
|
||||
@@ -300,6 +310,14 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
runtime->keyboard_.ReleaseRemotePressedKeys(remote_id,
|
||||
"connection_closed");
|
||||
props->connection_established_ = false;
|
||||
{
|
||||
std::lock_guard lock(props->remote_version_mutex_);
|
||||
props->remote_host_info_received_ = false;
|
||||
props->remote_app_version_.clear();
|
||||
props->remote_platform_ = HostPlatform::Unknown;
|
||||
props->remote_update_dismissed_ = false;
|
||||
}
|
||||
props->net_traffic_stats_.Reset();
|
||||
props->enable_mouse_control_ = false;
|
||||
runtime->ResetRemoteServiceStatus(*props);
|
||||
{
|
||||
@@ -324,7 +342,8 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
needs_native_snapshot =
|
||||
!props->thumbnail_frame_ || props->thumbnail_frame_->empty();
|
||||
}
|
||||
if (needs_native_snapshot) {
|
||||
if (needs_native_snapshot &&
|
||||
runtime->config_center_->IsSaveRemotePreviews()) {
|
||||
auto* native_renderer = runtime->video_renderer_.get();
|
||||
auto snapshot = std::make_shared<std::vector<unsigned char>>();
|
||||
if (native_renderer &&
|
||||
@@ -336,6 +355,8 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->video_frame_mutex_);
|
||||
props->video_latency_->Reset();
|
||||
props->video_frame_timing_ = {};
|
||||
props->front_frame_.reset();
|
||||
props->back_frame_.reset();
|
||||
if (native_snapshot &&
|
||||
@@ -392,7 +413,8 @@ void PeerEventHandler::OnConnectionStatus(ConnectionStatus status,
|
||||
{
|
||||
RemoteAction remote_action = MakeHostInformation(
|
||||
GetHostName(), runtime->devices_.host_display_list(),
|
||||
/*supports_privacy_screen=*/true);
|
||||
/*supports_privacy_screen=*/true, CROSSDESK_VERSION,
|
||||
kClientPlatform);
|
||||
remote_action.i.supports_video_settings = true;
|
||||
for (std::size_t i = 0; i < remote_action.i.display_num; i++) {
|
||||
LOG_INFO("Local display [{}:{}]", i + 1,
|
||||
@@ -508,6 +530,7 @@ void PeerEventHandler::OnNetStatusReport(
|
||||
auto props = runtime->FindRemoteSession(remote_id);
|
||||
if (!props) return;
|
||||
if (props->traversal_mode_ != mode) {
|
||||
props->net_traffic_stats_.ResetLatency();
|
||||
props->traversal_mode_ = mode;
|
||||
LOG_INFO("Net mode: [{}]", int(props->traversal_mode_));
|
||||
}
|
||||
@@ -518,7 +541,7 @@ void PeerEventHandler::OnNetStatusReport(
|
||||
|
||||
// only display client side net status if connected to itself
|
||||
if (!(runtime->peer_reserved_ && !strstr(client_id, "C-"))) {
|
||||
props->net_traffic_stats_ = *net_traffic_stats;
|
||||
props->net_traffic_stats_.Store(*net_traffic_stats);
|
||||
}
|
||||
}
|
||||
} // namespace crossdesk
|
||||
|
||||
@@ -36,7 +36,7 @@ void PeerEventHandler::OnReceiveVideoBuffer(
|
||||
auto callback = handler->EnterCallback();
|
||||
if (!callback) return;
|
||||
GuiRuntime* runtime = handler ? &handler->owner_ : nullptr;
|
||||
if (!runtime) {
|
||||
if (!runtime || !video_frame) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -45,13 +45,18 @@ void PeerEventHandler::OnReceiveVideoBuffer(
|
||||
if (!props) return;
|
||||
|
||||
if (props->connection_established_) {
|
||||
const auto timing_now = VideoLatencyFrame::Clock::now();
|
||||
const auto timing = props->video_latency_->Frame(
|
||||
video_frame->captured_timestamp, GetSystemTimeMicros(props->peer_),
|
||||
timing_now);
|
||||
bool background_snapshot_only = false;
|
||||
auto* native_renderer = runtime->video_renderer_.get();
|
||||
if (native_renderer && native_renderer->IsActive()) {
|
||||
VideoRenderer::SubmitResult submit_result =
|
||||
VideoRenderer::SubmitResult::failed;
|
||||
if (const auto* native = GetNativeVideoFrame(video_frame)) {
|
||||
submit_result = native_renderer->SubmitNativeFrame(remote_id, *native);
|
||||
submit_result =
|
||||
native_renderer->SubmitNativeFrame(remote_id, *native, timing);
|
||||
// A CPU NV12 native frame is valid MiniRTC input, but the macOS Metal
|
||||
// fast path only accepts CVPixelBuffer. Materialize it when that path
|
||||
// rejects a software decoder's descriptor. This also supports peers
|
||||
@@ -69,14 +74,14 @@ void PeerEventHandler::OnReceiveVideoBuffer(
|
||||
submit_result = native_renderer->SubmitNv12(
|
||||
remote_id, fallback.data(), fallback.size(),
|
||||
static_cast<int>(native->width),
|
||||
static_cast<int>(native->height));
|
||||
static_cast<int>(native->height), timing);
|
||||
}
|
||||
}
|
||||
} else
|
||||
{
|
||||
submit_result = native_renderer->SubmitNv12(
|
||||
remote_id, reinterpret_cast<const uint8_t*>(video_frame->data),
|
||||
video_frame->size, video_frame->width, video_frame->height);
|
||||
video_frame->size, video_frame->width, video_frame->height, timing);
|
||||
}
|
||||
if (submit_result == VideoRenderer::SubmitResult::submitted) {
|
||||
std::lock_guard<std::mutex> lock(props->video_frame_mutex_);
|
||||
@@ -170,6 +175,7 @@ void PeerEventHandler::OnReceiveVideoBuffer(
|
||||
props->video_size_ = frame_size;
|
||||
|
||||
props->front_frame_.swap(props->back_frame_);
|
||||
props->video_frame_timing_ = timing;
|
||||
props->thumbnail_frame_ = props->front_frame_;
|
||||
props->thumbnail_width_ = video_frame->width;
|
||||
props->thumbnail_height_ = video_frame->height;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -23,6 +24,8 @@
|
||||
#include "display_info.h"
|
||||
#include "cursor_presentation.h"
|
||||
#include "minirtc.h"
|
||||
#include "rendering/video_latency.h"
|
||||
#include "runtime/net_traffic_stats_cache.h"
|
||||
|
||||
namespace crossdesk { class PeerEventHandler; }
|
||||
|
||||
@@ -84,6 +87,7 @@ struct RemoteSession {
|
||||
bool signal_connected_ = false;
|
||||
SignalStatus signal_status_ = SignalStatus::SignalClosed;
|
||||
bool connection_established_ = false;
|
||||
std::atomic<bool> was_connected_{false};
|
||||
bool rejoin_ = false;
|
||||
bool net_traffic_stats_button_pressed_ = false;
|
||||
bool enable_mouse_control_ = true;
|
||||
@@ -115,9 +119,21 @@ struct RemoteSession {
|
||||
int selected_display_ = 0;
|
||||
size_t video_size_ = 0;
|
||||
uint64_t video_frame_sequence_ = 0;
|
||||
VideoLatencyFrame video_frame_timing_;
|
||||
std::shared_ptr<VideoLatencyStats> video_latency_ =
|
||||
std::make_shared<VideoLatencyStats>();
|
||||
bool tab_selected_ = false;
|
||||
bool tab_opened_ = true;
|
||||
std::string remote_host_name_;
|
||||
// Host metadata and dismissal state belong to this connection and are
|
||||
// protected by remote_version_mutex_.
|
||||
std::mutex remote_version_mutex_;
|
||||
bool remote_host_info_received_ = false;
|
||||
std::string remote_app_version_;
|
||||
HostPlatform remote_platform_ = HostPlatform::Unknown;
|
||||
// Retain history metadata after disconnect resets the live capabilities.
|
||||
HostPlatform recent_platform_ = HostPlatform::Unknown;
|
||||
bool remote_update_dismissed_ = false;
|
||||
bool remote_service_status_received_ = false;
|
||||
std::mutex video_settings_mutex_;
|
||||
// Requested and confirmed settings for this remote session only.
|
||||
@@ -150,7 +166,9 @@ struct RemoteSession {
|
||||
int fps_ = 0;
|
||||
int frame_count_ = 0;
|
||||
std::chrono::steady_clock::time_point last_time_;
|
||||
MiniRtcNetTrafficStats net_traffic_stats_{};
|
||||
// UI-thread snapshot refreshed with FPS once per second.
|
||||
std::optional<VideoLatencyStats::Snapshot> video_latency_snapshot_;
|
||||
NetTrafficStatsCache net_traffic_stats_;
|
||||
|
||||
using QueuedFile = FileTransferState::QueuedFile;
|
||||
using FileTransferStatus = FileTransferState::FileTransferStatus;
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-29
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _ANNOUNCEMENT_TEXT_H_
|
||||
#define _ANNOUNCEMENT_TEXT_H_
|
||||
|
||||
#include <slint.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace crossdesk::announcement_text {
|
||||
|
||||
inline size_t WebSchemeLength(std::string_view url) {
|
||||
for (const std::string_view prefix : {"https://", "http://"}) {
|
||||
if (url.size() >= prefix.size() &&
|
||||
std::equal(prefix.begin(), prefix.end(), url.begin(),
|
||||
[](char expected, unsigned char actual) {
|
||||
return expected == std::tolower(actual);
|
||||
})) {
|
||||
return prefix.size();
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline bool IsWebUrl(std::string_view url) {
|
||||
const size_t scheme = WebSchemeLength(url);
|
||||
if (!scheme || url.size() == scheme ||
|
||||
std::any_of(url.begin(), url.end(), [](unsigned char ch) {
|
||||
return ch <= 0x20 || ch == 0x7f || ch == '\\' || ch == '<' ||
|
||||
ch == '>' || ch == '"';
|
||||
})) {
|
||||
return false;
|
||||
}
|
||||
const auto authority =
|
||||
url.substr(scheme, url.find_first_of("/?#", scheme) - scheme);
|
||||
return !authority.empty() && authority.back() != '@';
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
|
||||
inline size_t UrlEnd(std::string_view text, size_t start) {
|
||||
// Do not include surrounding prose punctuation in a bare URL. Balanced
|
||||
// parentheses and IPv6 brackets are part of the address when present.
|
||||
const std::string_view punctuation =
|
||||
reinterpret_cast<const char*>(u8",。;:!?、()【】《》「」『』“”‘’");
|
||||
int parentheses = 0, brackets = 0;
|
||||
size_t end = start;
|
||||
for (; end < text.size(); ++end) {
|
||||
const unsigned char ch = text[end];
|
||||
if (ch <= 0x20 || ch == 0x7f ||
|
||||
std::string_view("<>\"'`\\{}").find(ch) != std::string_view::npos ||
|
||||
(ch >= 0xe0 && end + 3 <= text.size() &&
|
||||
punctuation.find(text.substr(end, 3)) != std::string_view::npos)) {
|
||||
break;
|
||||
}
|
||||
if (ch == '(') ++parentheses;
|
||||
if (ch == ')' && parentheses-- == 0) break;
|
||||
if (ch == '[') ++brackets;
|
||||
if (ch == ']' && brackets-- == 0) break;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
inline void AppendLiteral(std::string& output, std::string_view text) {
|
||||
for (const unsigned char ch : text) {
|
||||
// Entity-encode spaces so leading indentation is not parsed as code.
|
||||
if (ch == ' ') {
|
||||
output += " ";
|
||||
} else if (ch == '\t') {
|
||||
output += "	";
|
||||
} else {
|
||||
if (ch < 0x80 && std::ispunct(ch)) output += '\\';
|
||||
output += static_cast<char>(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void AppendLink(std::string& output, std::string_view label,
|
||||
std::string_view url) {
|
||||
output += '[';
|
||||
AppendLiteral(output, label);
|
||||
output += "](<";
|
||||
for (const char ch : url) {
|
||||
// Markdown decodes entities in link destinations; keep query strings exact.
|
||||
if (ch == '&')
|
||||
output += "&";
|
||||
else
|
||||
output += ch;
|
||||
}
|
||||
output += ">)";
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
inline slint::StyledText Format(std::string_view body) {
|
||||
std::string markdown;
|
||||
markdown.reserve(body.size());
|
||||
bool has_link = false;
|
||||
for (size_t pos = 0; pos < body.size();) {
|
||||
if (body[pos] == '[') {
|
||||
const size_t label_end = body.find("](", pos + 1);
|
||||
if (label_end != std::string_view::npos && label_end > pos + 1 &&
|
||||
body.substr(pos + 1, label_end - pos - 1).find_first_of("[]\r\n") ==
|
||||
std::string_view::npos &&
|
||||
WebSchemeLength(body.substr(label_end + 2))) {
|
||||
const size_t end = detail::UrlEnd(body, label_end + 2);
|
||||
const auto url = body.substr(label_end + 2, end - label_end - 2);
|
||||
if (end < body.size() && body[end] == ')' && IsWebUrl(url)) {
|
||||
detail::AppendLink(markdown,
|
||||
body.substr(pos + 1, label_end - pos - 1), url);
|
||||
pos = end + 1;
|
||||
has_link = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (WebSchemeLength(body.substr(pos))) {
|
||||
size_t end = detail::UrlEnd(body, pos);
|
||||
while (end > pos && std::string_view(".,;:!?").find(body[end - 1]) !=
|
||||
std::string_view::npos) {
|
||||
--end;
|
||||
}
|
||||
const auto url = body.substr(pos, end - pos);
|
||||
if (IsWebUrl(url)) {
|
||||
detail::AppendLink(markdown, url, url);
|
||||
pos = end;
|
||||
has_link = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (body[pos] == '\r' && pos + 1 < body.size() && body[pos + 1] == '\n') {
|
||||
++pos;
|
||||
continue;
|
||||
}
|
||||
if (body[pos] == '\n') {
|
||||
// Preserve empty lines instead of letting Markdown collapse them.
|
||||
if (markdown.empty() || markdown.back() == '\n') markdown += " ";
|
||||
markdown += '\n';
|
||||
} else {
|
||||
detail::AppendLiteral(markdown, body.substr(pos, 1));
|
||||
}
|
||||
++pos;
|
||||
}
|
||||
if (has_link) {
|
||||
if (markdown.back() == '\n') markdown += " ";
|
||||
if (const auto styled = slint::StyledText::from_markdown(markdown))
|
||||
return *styled;
|
||||
}
|
||||
return slint::StyledText::from_plain_text(body);
|
||||
}
|
||||
|
||||
} // namespace crossdesk::announcement_text
|
||||
|
||||
#endif
|
||||
@@ -339,6 +339,7 @@ export component MiniToggleSwitch inherits Rectangle {
|
||||
|
||||
export component CompactButton inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <length> text-size: ImGuiFontStyle.body;
|
||||
in property <bool> primary: false;
|
||||
in property <bool> enabled: true;
|
||||
callback clicked;
|
||||
@@ -355,7 +356,7 @@ export component CompactButton inherits Rectangle {
|
||||
Text {
|
||||
text: root.text;
|
||||
color: root.enabled ? #24272d : #8e9298;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-size: root.text-size;
|
||||
overflow: elide;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
@@ -365,6 +366,7 @@ export component CompactButton inherits Rectangle {
|
||||
|
||||
export component PrimaryButton inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <length> text-size: ImGuiFontStyle.body;
|
||||
in property <bool> enabled: true;
|
||||
callback clicked;
|
||||
|
||||
@@ -379,7 +381,7 @@ export component PrimaryButton inherits Rectangle {
|
||||
Text {
|
||||
text: root.text;
|
||||
color: white;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-size: root.text-size;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Single AOT entry point. Generating one header for the entire UI avoids
|
||||
// duplicate imported-component definitions when C++ uses all three windows.
|
||||
export { AnnouncementItem, MessageStrings } from "message_panel.slint";
|
||||
export { MainWindow, RecentConnection, UpdateCheckStatus, UiStrings } from "main_window.slint";
|
||||
export { StreamWindow, StreamTab, FileTransferEntry, NetworkStatsRow, StreamStrings } from "stream_window.slint";
|
||||
export { ServerWindow, ControllerEntry } from "server_window.slint";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { LineEdit, ScrollView } from "std-widgets.slint";
|
||||
import { AnnouncementItem, MessagePanel, MessageStrings } from "message_panel.slint";
|
||||
import { FontAwesomeIcons, IconButton, CompactComboBox, ImGuiCheckBox, MiniToggleSwitch, CompactButton, PrimaryButton, SecondaryButton, ToggleSwitch, SectionTitle, DialogSurface, ImGuiLineStyle, ImGuiFontStyle } from "common.slint";
|
||||
|
||||
export struct RecentConnection {
|
||||
@@ -7,6 +8,8 @@ export struct RecentConnection {
|
||||
host-name: string,
|
||||
online: bool,
|
||||
thumbnail: image,
|
||||
has-thumbnail: bool,
|
||||
platform: string,
|
||||
}
|
||||
|
||||
export struct ReleaseNoteBlock {
|
||||
@@ -49,6 +52,8 @@ export global UiStrings {
|
||||
in-out property <string> self-hosted: "Self-hosted server";
|
||||
in-out property <string> autostart: "Start with system";
|
||||
in-out property <string> daemon: "Run in background";
|
||||
in-out property <string> save-remote-previews: "Save remote screen previews:";
|
||||
in-out property <string> unknown-platform: "Unknown platform";
|
||||
in-out property <string> privacy-on-connect: "Privacy screen on connect";
|
||||
in-out property <string> file-save-path: "File save path";
|
||||
in-out property <string> default-desktop: "Desktop";
|
||||
@@ -61,6 +66,7 @@ export global UiStrings {
|
||||
in-out property <string> signal-disconnected: "Signal server disconnected";
|
||||
in-out property <string> tls-error: "Signal server TLS certificate error";
|
||||
in-out property <string> update-available: "A new version is available";
|
||||
in-out property <string> new-version: "New version";
|
||||
in-out property <string> check-for-updates: "Check for updates";
|
||||
in-out property <string> checking-for-updates: "Checking for updates…";
|
||||
in-out property <string> up-to-date: "You’re up to date";
|
||||
@@ -76,6 +82,13 @@ export global UiStrings {
|
||||
in-out property <string> permission-required: "The application requires the following permissions:";
|
||||
in-out property <string> screen-recording-permission: "Screen recording permission";
|
||||
in-out property <string> accessibility-permission: "Accessibility permission";
|
||||
in-out property <string> wayland-notice-title: "Wayland Session Notice";
|
||||
in-out property <string> wayland-notice-subtitle;
|
||||
in-out property <string> wayland-permission-title;
|
||||
in-out property <string> wayland-notice-message;
|
||||
in-out property <string> wayland-recommendation-title;
|
||||
in-out property <string> wayland-recommendation-message;
|
||||
in-out property <string> wayland-notice-acknowledge: "Got it";
|
||||
in-out property <string> service-setup-title: "Install CrossDesk Service";
|
||||
in-out property <string> service-setup-message: "Administrator permission is required to control this device while it is locked.";
|
||||
in-out property <string> service-settings-label: "Lock Screen Service:";
|
||||
@@ -135,19 +148,50 @@ component DialogPromptText inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// Shared online-state artwork. Both the recent-connection card and the
|
||||
// server status bar use the same pure green center and proportional glow.
|
||||
// Explicit device labels make state readable without interpreting a dot.
|
||||
// Opaque surfaces keep the badge legible over both dark and light previews.
|
||||
component ConnectionStatusBadge inherits Rectangle {
|
||||
in property <string> label;
|
||||
in property <bool> online: false;
|
||||
|
||||
preferred-width: badge-label.preferred-width + 16px;
|
||||
width: self.preferred-width;
|
||||
height: 20px;
|
||||
border-radius: self.height / 2;
|
||||
background: root.online ? #eaf8f0 : #f2f4f7;
|
||||
border-width: 1px;
|
||||
border-color: root.online ? #bce3cd : #d5dbe3;
|
||||
|
||||
badge-label := Text {
|
||||
x: 8px;
|
||||
width: max(0px, parent.width - 16px);
|
||||
height: parent.height;
|
||||
text: root.label;
|
||||
color: root.online ? #16a34a : #596575;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the green center and fade the surrounding glow into the status bar.
|
||||
component OnlineStatusIndicator inherits Rectangle {
|
||||
in property <length> dot-diameter: 8px;
|
||||
|
||||
width: root.dot-diameter * 2.2;
|
||||
height: self.width;
|
||||
border-radius: self.width / 2;
|
||||
// Slint's default radial radius is half the bounding-box diagonal.
|
||||
// Fade out at the circle's edge (1 / sqrt(2)), before rounded clipping.
|
||||
background: @radial-gradient(
|
||||
circle,
|
||||
#00ff0030 0%,
|
||||
#00ff0018 48%,
|
||||
transparent 100%
|
||||
#00ff0040 0%,
|
||||
#00ff0038 32%,
|
||||
#00ff0018 50%,
|
||||
#00ff0007 62%,
|
||||
#00ff0000 70.7%
|
||||
);
|
||||
|
||||
Rectangle {
|
||||
@@ -262,6 +306,27 @@ export component MainWindow inherits Window {
|
||||
in property <bool> signal-connected: false;
|
||||
in property <bool> signal-tls-error: false;
|
||||
in property <[RecentConnection]> recent-connections;
|
||||
in property <[AnnouncementItem]> announcements;
|
||||
in property <int> announcement-unread;
|
||||
private property <string> announcement-unread-label:
|
||||
root.announcement-unread > 99 ? "99+" : "" + root.announcement-unread;
|
||||
in property <int> announcement-total;
|
||||
in property <bool> announcement-loading;
|
||||
in property <bool> announcement-failed;
|
||||
in property <bool> announcement-read-save-failed;
|
||||
in property <bool> announcement-delete-failed;
|
||||
in property <bool> announcement-loaded;
|
||||
in-out property <bool> messages-open: false;
|
||||
in property <string> announcement-selected-id;
|
||||
in property <string> announcement-selected-title;
|
||||
in property <styled-text> announcement-selected-body;
|
||||
in property <string> announcement-selected-date;
|
||||
in property <bool> announcement-selected-read;
|
||||
callback open-announcement(string, string);
|
||||
callback open-announcement-link(string);
|
||||
callback delete-announcement(string, string);
|
||||
callback refresh-announcements;
|
||||
callback load-more-announcements;
|
||||
in property <bool> update-available: false;
|
||||
in property <UpdateCheckStatus> update-check-status: idle;
|
||||
private property <string> update-status-text:
|
||||
@@ -284,6 +349,7 @@ export component MainWindow inherits Window {
|
||||
in property <bool> permission-dialog-open: false;
|
||||
in property <bool> screen-recording-granted: true;
|
||||
in property <bool> accessibility-granted: true;
|
||||
in-out property <bool> wayland-notice-open: false;
|
||||
in property <bool> portable-service-settings-visible: false;
|
||||
in property <bool> portable-service-dialog-open: false;
|
||||
in property <bool> portable-service-suppressed-notice-open: false;
|
||||
@@ -306,6 +372,7 @@ export component MainWindow inherits Window {
|
||||
in-out property <bool> self-hosted-enabled: false;
|
||||
in-out property <bool> autostart-enabled: false;
|
||||
in-out property <bool> daemon-enabled: false;
|
||||
in-out property <bool> save-remote-previews: true;
|
||||
// Show the preference on every platform; only adapted hosts can change it.
|
||||
in property <bool> privacy-setting-available: false;
|
||||
in-out property <bool> privacy-on-connect-enabled: true;
|
||||
@@ -363,8 +430,6 @@ export component MainWindow inherits Window {
|
||||
private property <string> delete-remote-id: "";
|
||||
private property <bool> copy-toast: false;
|
||||
private property <bool> compact-language: root.language-index == 0;
|
||||
private property <bool> update-icon-blink-on:
|
||||
root.update-available && mod(animation-tick(), 2s) < 1s;
|
||||
private property <bool> recent-tooltip-visible: false;
|
||||
private property <string> recent-tooltip-name: "";
|
||||
private property <string> recent-tooltip-host: "";
|
||||
@@ -393,6 +458,14 @@ export component MainWindow inherits Window {
|
||||
}
|
||||
}
|
||||
|
||||
changed wayland-notice-open => {
|
||||
if root.wayland-notice-open { focus-sink.focus(); }
|
||||
}
|
||||
|
||||
changed messages-open => {
|
||||
if root.messages-open { focus-sink.focus(); }
|
||||
}
|
||||
|
||||
reset-remote-id => {
|
||||
root.remote-id-input = "";
|
||||
remote-id-editor.focus();
|
||||
@@ -597,7 +670,22 @@ export component MainWindow inherits Window {
|
||||
border-width: 0px;
|
||||
border-radius: 0px;
|
||||
|
||||
focus-sink := FocusScope { x: 0px; y: 0px; width: 0px; height: 0px; }
|
||||
focus-sink := FocusScope {
|
||||
x: 0px; y: 0px; width: 0px; height: 0px;
|
||||
key-pressed(event) => {
|
||||
if root.wayland-notice-open {
|
||||
if event.text == Key.Return || event.text == Key.Escape {
|
||||
root.wayland-notice-open = false;
|
||||
}
|
||||
return accept;
|
||||
}
|
||||
if root.messages-open {
|
||||
if event.text == Key.Escape { root.messages-open = false; }
|
||||
return accept;
|
||||
}
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
TouchArea { clicked => { focus-sink.focus(); } }
|
||||
|
||||
// Slint owns the client area below the native macOS title bar. Draw
|
||||
@@ -623,22 +711,80 @@ export component MainWindow inherits Window {
|
||||
icon-size: 14px;
|
||||
hover-background: #e1e5eb;
|
||||
pressed-background: #cbd1d9;
|
||||
tooltip: root.announcement-unread > 0
|
||||
? MessageStrings.unread + " " + root.announcement-unread + (root.update-available ? " · " + UiStrings.update-available : "")
|
||||
: root.update-available ? UiStrings.update-available : "";
|
||||
z: 8;
|
||||
clicked => { root.menu-open = !root.menu-open; }
|
||||
}
|
||||
if root.update-available && !root.menu-open && root.update-icon-blink-on: Text {
|
||||
x: menu-button.x + 16px;
|
||||
y: menu-button.y + 1px;
|
||||
// Unread messages take precedence so the menu has only one indicator.
|
||||
if root.update-available && root.announcement-unread <= 0: Rectangle {
|
||||
x: menu-button.x + menu-button.width - self.width + 4px;
|
||||
y: menu-button.y - 1px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
text: FontAwesomeIcons.circle-arrow-up;
|
||||
color: #24272d;
|
||||
font-family: "Font Awesome 6 Free";
|
||||
font-weight: 900;
|
||||
font-size: 13px;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
border-radius: 8px;
|
||||
border-width: 1px;
|
||||
border-color: white;
|
||||
background: #2563eb;
|
||||
opacity: root.menu-open || mod(animation-tick(), 2s) < 1s ? 1 : 0;
|
||||
z: 9;
|
||||
accessible-role: button;
|
||||
accessible-label: UiStrings.update-available;
|
||||
accessible-action-default => { root.menu-open = !root.menu-open; }
|
||||
// Center the visible mark independently of font baseline metrics.
|
||||
Rectangle {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 2px;
|
||||
height: 10px;
|
||||
accessible-role: none;
|
||||
Rectangle {
|
||||
y: 0px;
|
||||
width: parent.width;
|
||||
height: 6px;
|
||||
border-radius: 1px;
|
||||
background: white;
|
||||
}
|
||||
Rectangle {
|
||||
y: 8px;
|
||||
width: parent.width;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
background: white;
|
||||
}
|
||||
}
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.menu-open = !root.menu-open; }
|
||||
}
|
||||
}
|
||||
if root.announcement-unread > 0: Rectangle {
|
||||
x: menu-button.x + menu-button.width - self.width + 4px;
|
||||
y: menu-button.y - 1px;
|
||||
width: max(16px, unread-badge-label.preferred-width + 8px);
|
||||
height: 16px;
|
||||
border-radius: 8px;
|
||||
border-width: 1px;
|
||||
border-color: white;
|
||||
background: #d92d20;
|
||||
z: 9;
|
||||
accessible-role: button;
|
||||
accessible-label: MessageStrings.messages + " · " + MessageStrings.unread + " " + root.announcement-unread;
|
||||
accessible-action-default => { root.menu-open = !root.menu-open; }
|
||||
unread-badge-label := Text {
|
||||
text: root.announcement-unread-label;
|
||||
color: white;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
accessible-role: none;
|
||||
}
|
||||
TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => { root.menu-open = !root.menu-open; }
|
||||
}
|
||||
}
|
||||
|
||||
// Local and remote desktop panels.
|
||||
@@ -864,51 +1010,88 @@ export component MainWindow inherits Window {
|
||||
private property <length> toolbar-width: 79px;
|
||||
private property <length> toolbar-right-padding: 3px;
|
||||
|
||||
Image {
|
||||
Rectangle {
|
||||
x: 7px;
|
||||
y: 7px;
|
||||
width: connection-card.content-width;
|
||||
height: 84px;
|
||||
source: connection.thumbnail;
|
||||
image-fit: cover;
|
||||
}
|
||||
Rectangle {
|
||||
x: 7px;
|
||||
y: 91px;
|
||||
width: connection-card.content-width;
|
||||
height: 25px;
|
||||
background: #00000018;
|
||||
border-radius: 3px;
|
||||
Text {
|
||||
x: 4px;
|
||||
y: 1px;
|
||||
height: parent.height - self.y;
|
||||
width: max(0px, parent.width - self.x - 4px
|
||||
- (card-touch.has-hover
|
||||
? connection-card.toolbar-width + connection-card.toolbar-right-padding
|
||||
: 0px));
|
||||
text: connection.display-name;
|
||||
color: #30343b;
|
||||
// The ImGui card footer uses its own 0.52 font
|
||||
// scale and renders slightly larger than the
|
||||
// compact body text used in dialogs.
|
||||
font-size: ImGuiFontStyle.base;
|
||||
overflow: elide;
|
||||
vertical-alignment: center;
|
||||
height: 109px;
|
||||
border-radius: 4px;
|
||||
clip: true;
|
||||
|
||||
Rectangle {
|
||||
x: 0px;
|
||||
y: 0px;
|
||||
width: parent.width;
|
||||
height: 84px;
|
||||
background: connection.platform == "windows" ? @linear-gradient(135deg, #1f61b3, #337ac4) :
|
||||
connection.platform == "macos" ? @linear-gradient(135deg, #6e4aad, #8c63c4) :
|
||||
connection.platform == "linux" ? @linear-gradient(135deg, #a14f14, #ba631f) :
|
||||
connection.platform == "ios" ? @linear-gradient(135deg, #146e66, #1f8278) :
|
||||
@linear-gradient(135deg, #596675, #737d8c);
|
||||
if connection.has-thumbnail: Image {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
source: connection.thumbnail;
|
||||
image-fit: cover;
|
||||
}
|
||||
if !connection.has-thumbnail: Text {
|
||||
x: 8px;
|
||||
width: parent.width - 16px;
|
||||
height: parent.height;
|
||||
text: connection.platform == "windows" ? "Windows" :
|
||||
connection.platform == "macos" ? "macOS" :
|
||||
connection.platform == "linux" ? "Linux" :
|
||||
connection.platform == "ios" ? "iOS" : UiStrings.unknown-platform;
|
||||
color: white;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
x: 0px;
|
||||
y: 84px;
|
||||
width: parent.width;
|
||||
height: 25px;
|
||||
background: #00000018;
|
||||
Text {
|
||||
x: 4px;
|
||||
y: 1px;
|
||||
height: parent.height - self.y;
|
||||
width: max(0px, parent.width - self.x - 4px
|
||||
- (card-touch.has-hover
|
||||
? connection-card.toolbar-width + connection-card.toolbar-right-padding
|
||||
: 0px));
|
||||
text: connection.display-name;
|
||||
color: #30343b;
|
||||
// The ImGui card footer uses its own 0.52 font
|
||||
// scale and renders slightly larger than the
|
||||
// compact body text used in dialogs.
|
||||
font-size: ImGuiFontStyle.base;
|
||||
overflow: elide;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
ConnectionStatusBadge {
|
||||
x: 6px;
|
||||
y: 6px;
|
||||
width: min(self.preferred-width, parent.width - 12px);
|
||||
label: connection.online ? UiStrings.online : UiStrings.offline;
|
||||
online: connection.online;
|
||||
}
|
||||
// The software renderer only clips rectangular bounds.
|
||||
// This outer border masks the four corners there too.
|
||||
Rectangle {
|
||||
x: -parent.border-radius;
|
||||
y: -parent.border-radius;
|
||||
width: parent.width + 2 * parent.border-radius;
|
||||
height: parent.height + 2 * parent.border-radius;
|
||||
border-width: parent.border-radius;
|
||||
border-radius: 2 * parent.border-radius;
|
||||
border-color: recent-list.background;
|
||||
}
|
||||
}
|
||||
if connection.online: OnlineStatusIndicator {
|
||||
x: 16px - self.width / 2;
|
||||
y: 16px - self.height / 2;
|
||||
dot-diameter: 9px;
|
||||
}
|
||||
if !connection.online: Rectangle {
|
||||
x: 11.5px;
|
||||
y: 11.5px;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 4.5px;
|
||||
background: #9ca3af;
|
||||
}
|
||||
card-touch := TouchArea {
|
||||
x: 7px;
|
||||
@@ -1094,9 +1277,10 @@ export component MainWindow inherits Window {
|
||||
if root.menu-open: Rectangle {
|
||||
x: menu-button.x + menu-button.width - self.width;
|
||||
y: menu-button.y + menu-button.height + 2px;
|
||||
width: min(118px, max(menu-settings-label.preferred-width,
|
||||
menu-about-label.preferred-width + (root.update-available ? 25px : 0px)) + 28px);
|
||||
height: 64px;
|
||||
width: max(80px, max(menu-settings-label.preferred-width,
|
||||
max(menu-messages-label.preferred-width + (root.announcement-unread > 0 ? menu-message-badge.width + 8px : 0px),
|
||||
menu-about-label.preferred-width + (root.update-available ? menu-update-badge.width + 8px : 0px))) + 24px);
|
||||
height: 93px;
|
||||
background: white;
|
||||
border-width: 1px;
|
||||
border-color: ImGuiLineStyle.border;
|
||||
@@ -1117,7 +1301,7 @@ export component MainWindow inherits Window {
|
||||
accessible-label: UiStrings.settings;
|
||||
accessible-action-default => { settings-touch.clicked(); }
|
||||
menu-settings-label := Text {
|
||||
x: 9px;
|
||||
x: 7px;
|
||||
height: parent.height;
|
||||
text: UiStrings.settings;
|
||||
color: #2d3138;
|
||||
@@ -1129,6 +1313,47 @@ export component MainWindow inherits Window {
|
||||
clicked => { root.menu-open = false; root.settings-open = true; }
|
||||
}
|
||||
}
|
||||
menu-messages := Rectangle {
|
||||
height: 27px;
|
||||
background: messages-touch.pressed ? #d8dadd
|
||||
: messages-touch.has-hover ? #f0f1f2 : white;
|
||||
border-radius: 3px;
|
||||
accessible-role: button;
|
||||
accessible-label: MessageStrings.messages + (root.announcement-unread > 0 ? " · " + MessageStrings.unread + " " + root.announcement-unread : "");
|
||||
accessible-action-default => { messages-touch.clicked(); }
|
||||
menu-messages-label := Text {
|
||||
x: 7px;
|
||||
height: parent.height;
|
||||
text: MessageStrings.messages;
|
||||
color: #2d3138;
|
||||
vertical-alignment: center;
|
||||
accessible-role: none;
|
||||
}
|
||||
menu-message-badge := Rectangle {
|
||||
visible: root.announcement-unread > 0;
|
||||
x: parent.width - self.width - 7px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: max(18px, menu-message-count.preferred-width + 10px);
|
||||
height: 18px;
|
||||
border-radius: 9px;
|
||||
background: #fee4e2;
|
||||
accessible-role: none;
|
||||
menu-message-count := Text {
|
||||
text: root.announcement-unread-label;
|
||||
font-size: 10px; font-weight: 600; color: #b42318;
|
||||
horizontal-alignment: center; vertical-alignment: center;
|
||||
accessible-role: none;
|
||||
}
|
||||
}
|
||||
messages-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
clicked => {
|
||||
root.menu-open = false;
|
||||
root.messages-open = true;
|
||||
root.refresh-announcements();
|
||||
}
|
||||
}
|
||||
}
|
||||
menu-about := Rectangle {
|
||||
height: 27px;
|
||||
background: about-touch.pressed ? #d8dadd
|
||||
@@ -1137,28 +1362,31 @@ export component MainWindow inherits Window {
|
||||
border-width: 0px;
|
||||
border-radius: 3px;
|
||||
accessible-role: button;
|
||||
accessible-label: UiStrings.about;
|
||||
accessible-label: UiStrings.about + (root.update-available ? " · " + UiStrings.update-available : "");
|
||||
accessible-action-default => { about-touch.clicked(); }
|
||||
menu-about-label := Text {
|
||||
x: 9px;
|
||||
x: 7px;
|
||||
height: parent.height;
|
||||
text: UiStrings.about;
|
||||
color: #2d3138;
|
||||
vertical-alignment: center;
|
||||
accessible-role: none;
|
||||
}
|
||||
if root.update-available && root.update-icon-blink-on: Text {
|
||||
x: menu-about-label.x + menu-about-label.preferred-width + 7px;
|
||||
width: 18px;
|
||||
height: parent.height;
|
||||
text: FontAwesomeIcons.circle-arrow-up;
|
||||
color: #2d3138;
|
||||
font-family: "Font Awesome 6 Free";
|
||||
font-weight: 900;
|
||||
font-size: 16px;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
menu-update-badge := Rectangle {
|
||||
visible: root.update-available;
|
||||
x: parent.width - self.width - 7px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: menu-update-label.preferred-width + 12px;
|
||||
height: 18px;
|
||||
border-radius: 9px;
|
||||
background: #dbeafe;
|
||||
accessible-role: none;
|
||||
menu-update-label := Text {
|
||||
text: UiStrings.new-version;
|
||||
font-size: 11px; font-weight: 400; color: #1d4ed8;
|
||||
horizontal-alignment: center; vertical-alignment: center;
|
||||
accessible-role: none;
|
||||
}
|
||||
}
|
||||
about-touch := TouchArea {
|
||||
mouse-cursor: pointer;
|
||||
@@ -1174,6 +1402,40 @@ export component MainWindow inherits Window {
|
||||
background: ImGuiLineStyle.separator;
|
||||
z: 1;
|
||||
}
|
||||
Rectangle {
|
||||
x: 4px;
|
||||
y: 60.5px;
|
||||
width: parent.width - 8px;
|
||||
height: 1px;
|
||||
background: ImGuiLineStyle.separator;
|
||||
z: 1;
|
||||
}
|
||||
}
|
||||
|
||||
if root.messages-open: Rectangle {
|
||||
background: #00000042;
|
||||
z: 40;
|
||||
TouchArea { clicked => { focus-sink.focus(); } }
|
||||
MessagePanel {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 520px;
|
||||
height: 330px;
|
||||
items: root.announcements;
|
||||
unread-count: root.announcement-unread; total: root.announcement-total;
|
||||
loading: root.announcement-loading; failed: root.announcement-failed; loaded: root.announcement-loaded;
|
||||
read-save-failed: root.announcement-read-save-failed;
|
||||
delete-failed: root.announcement-delete-failed;
|
||||
connected: root.signal-connected;
|
||||
selected-id: root.announcement-selected-id; selected-title: root.announcement-selected-title;
|
||||
selected-body: root.announcement-selected-body; selected-date: root.announcement-selected-date;
|
||||
selected-read: root.announcement-selected-read;
|
||||
open-message(id, revision) => { root.open-announcement(id, revision); }
|
||||
open-link(url) => { root.open-announcement-link(url); }
|
||||
delete-message(id, revision) => { root.delete-announcement(id, revision); }
|
||||
load-more => { root.load-more-announcements(); }
|
||||
close => { root.messages-open = false; }
|
||||
}
|
||||
}
|
||||
|
||||
copy-timer := Timer {
|
||||
@@ -1513,6 +1775,11 @@ export component MainWindow inherits Window {
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 145px : 212px; height: 24px; text: UiStrings.force-relay; color: root.turn-enabled ? #202124 : #8b8f95; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
ImGuiCheckBox { x: root.compact-language ? 157px : 224px; y: 3px; checked <=> root.force-relay-enabled; enabled: root.turn-enabled && !root.settings-session-active; }
|
||||
}
|
||||
Rectangle {
|
||||
height: 30px;
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 145px : 212px; height: 24px; text: UiStrings.save-remote-previews; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
ImGuiCheckBox { x: root.compact-language ? 157px : 224px; y: 3px; checked <=> root.save-remote-previews; }
|
||||
}
|
||||
Rectangle {
|
||||
height: 30px;
|
||||
Text { x: 8px; y: 3px; width: root.compact-language ? 145px : 212px; height: 24px; text: UiStrings.privacy-on-connect; color: root.privacy-setting-available ? #202124 : #8b8f95; font-size: ImGuiFontStyle.body; overflow: elide; vertical-alignment: center; }
|
||||
@@ -1776,6 +2043,105 @@ export component MainWindow inherits Window {
|
||||
}
|
||||
}
|
||||
|
||||
// Linux Wayland sessions show this advisory once per application launch.
|
||||
if root.wayland-notice-open: Rectangle {
|
||||
background: #14233b66;
|
||||
z: 50;
|
||||
TouchArea { clicked => { focus-sink.focus(); } }
|
||||
DialogSurface {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 512px;
|
||||
height: wayland-notice-content.preferred-height;
|
||||
border-radius: 14px;
|
||||
border-color: #dce3ee;
|
||||
drop-shadow-color: #07142b30;
|
||||
drop-shadow-blur: 28px;
|
||||
drop-shadow-offset-y: 10px;
|
||||
|
||||
wayland-notice-content := VerticalLayout {
|
||||
padding: 24px; spacing: 18px;
|
||||
VerticalLayout {
|
||||
spacing: 7px;
|
||||
Text {
|
||||
text: UiStrings.wayland-notice-title;
|
||||
color: #1c2b43;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
Text {
|
||||
text: UiStrings.wayland-notice-subtitle;
|
||||
color: #68758a;
|
||||
font-size: ImGuiFontStyle.base;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
background: #fff8eb;
|
||||
border-color: #f0dfba;
|
||||
border-width: 1px;
|
||||
border-radius: 9px;
|
||||
VerticalLayout {
|
||||
padding: 14px; spacing: 8px;
|
||||
Text {
|
||||
text: UiStrings.wayland-permission-title;
|
||||
color: #805719;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
Text {
|
||||
text: UiStrings.wayland-notice-message;
|
||||
color: #6c5a3d;
|
||||
font-size: ImGuiFontStyle.base;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
background: #f3f7fd;
|
||||
border-color: #dfe8f5;
|
||||
border-width: 1px;
|
||||
border-radius: 9px;
|
||||
VerticalLayout {
|
||||
padding: 14px; spacing: 8px;
|
||||
Text {
|
||||
text: UiStrings.wayland-recommendation-title;
|
||||
color: #244c87;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
Text {
|
||||
text: UiStrings.wayland-recommendation-message;
|
||||
color: #59677c;
|
||||
font-size: ImGuiFontStyle.base;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Rectangle { height: 1px; background: #e9edf3; }
|
||||
HorizontalLayout {
|
||||
height: 34px; alignment: end;
|
||||
PrimaryButton {
|
||||
width: 104px; height: 34px;
|
||||
border-radius: 7px;
|
||||
text-size: ImGuiFontStyle.base;
|
||||
text: UiStrings.wayland-notice-acknowledge;
|
||||
accessible-role: button;
|
||||
accessible-label: UiStrings.wayland-notice-acknowledge;
|
||||
accessible-action-default => { root.wayland-notice-open = false; }
|
||||
clicked => { root.wayland-notice-open = false; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Portable Windows builds prompt for the optional lock-screen service.
|
||||
if root.portable-service-dialog-open: Rectangle {
|
||||
background: #00000052;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { ScrollView } from "std-widgets.slint";
|
||||
import { CompactButton, DialogSurface, IconButton, FontAwesomeIcons, ImGuiFontStyle } from "common.slint";
|
||||
|
||||
export struct AnnouncementItem {
|
||||
id: string,
|
||||
revision: string,
|
||||
title: string,
|
||||
date: string,
|
||||
read: bool,
|
||||
}
|
||||
|
||||
export global MessageStrings {
|
||||
in-out property <string> messages: "Messages";
|
||||
in-out property <string> unread: "Unread";
|
||||
in-out property <string> read: "Read";
|
||||
in-out property <string> empty: "No announcements";
|
||||
in-out property <string> select-message: "Select an announcement to read";
|
||||
in-out property <string> loading: "Loading…";
|
||||
in-out property <string> read-save-error: "Unable to save reading status locally. Open the announcement again to retry.";
|
||||
in-out property <string> close: "Close";
|
||||
in-out property <string> delete-message: "Delete";
|
||||
in-out property <string> delete-title: "Delete announcement";
|
||||
in-out property <string> delete-confirmation: "Delete this announcement?";
|
||||
in-out property <string> delete-error: "Unable to delete this announcement. Please try again.";
|
||||
in-out property <string> cancel: "Cancel";
|
||||
}
|
||||
|
||||
export component MessagePanel inherits DialogSurface {
|
||||
in property <[AnnouncementItem]> items;
|
||||
in property <int> unread-count;
|
||||
in property <int> total;
|
||||
in property <bool> loading;
|
||||
in property <bool> failed;
|
||||
in property <bool> read-save-failed;
|
||||
in property <bool> delete-failed;
|
||||
in property <bool> loaded;
|
||||
in property <bool> connected;
|
||||
in property <string> selected-id;
|
||||
in property <string> selected-title;
|
||||
in property <styled-text> selected-body;
|
||||
in property <string> selected-date;
|
||||
in property <bool> selected-read;
|
||||
callback open-message(string, string);
|
||||
callback open-link(string);
|
||||
callback delete-message(string, string);
|
||||
callback load-more;
|
||||
callback close;
|
||||
private property <string> notice-text: root.delete-failed ? MessageStrings.delete-error
|
||||
: root.read-save-failed ? MessageStrings.read-save-error : "";
|
||||
private property <length> content-top: title-bar.height + (root.notice-text == "" ? 14px : 50px);
|
||||
private property <color> separator-color: #e6e8eb;
|
||||
private property <string> pending-delete-id;
|
||||
private property <string> pending-delete-revision;
|
||||
function request-delete(id: string, revision: string) {
|
||||
root.pending-delete-id = id;
|
||||
root.pending-delete-revision = revision;
|
||||
confirmation-keys.focus();
|
||||
}
|
||||
confirmation-keys := FocusScope {
|
||||
width: 0px; height: 0px;
|
||||
key-pressed(event) => {
|
||||
if event.text == Key.Escape {
|
||||
if root.pending-delete-id != "" { root.pending-delete-id = ""; }
|
||||
else { root.close(); }
|
||||
return accept;
|
||||
}
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
background: white;
|
||||
border-radius: 7px;
|
||||
TouchArea { }
|
||||
title-bar := Rectangle {
|
||||
x: 0px; y: 0px; width: parent.width; height: 21px;
|
||||
background: #d3d3d3; border-radius: 7px;
|
||||
Rectangle { y: parent.height - 7px; height: 7px; background: #d3d3d3; }
|
||||
message-heading := Text {
|
||||
x: 6px; width: parent.width - 100px; height: parent.height;
|
||||
text: MessageStrings.messages;
|
||||
font-size: ImGuiFontStyle.base; font-weight: 600; color: #202124;
|
||||
vertical-alignment: center; overflow: elide;
|
||||
}
|
||||
if root.unread-count > 0: Rectangle {
|
||||
x: message-heading.x + message-heading.preferred-width + 8px;
|
||||
y: (parent.height - self.height) / 2; height: 16px;
|
||||
width: max(16px, unread-count-label.preferred-width + 8px);
|
||||
border-radius: 8px; background: #eaf2ff;
|
||||
accessible-role: text;
|
||||
accessible-label: MessageStrings.unread + " " + root.unread-count;
|
||||
unread-count-label := Text {
|
||||
text: "" + root.unread-count; color: #2563eb;
|
||||
font-size: ImGuiFontStyle.small; font-weight: 600;
|
||||
horizontal-alignment: center; vertical-alignment: center;
|
||||
accessible-role: none;
|
||||
}
|
||||
}
|
||||
if root.loading: Text {
|
||||
x: parent.width - 150px; width: 110px; height: parent.height;
|
||||
text: MessageStrings.loading; color: #61656c; font-size: ImGuiFontStyle.small;
|
||||
horizontal-alignment: right; vertical-alignment: center;
|
||||
}
|
||||
IconButton {
|
||||
x: parent.width - 25px; y: 2px; width: 19px; height: parent.height - 4px;
|
||||
border-radius: 3px;
|
||||
icon: FontAwesomeIcons.xmark; icon-size: ImGuiFontStyle.base;
|
||||
icon-color: #202124;
|
||||
hover-background: #bfc2c7; pressed-background: #b2b2b2;
|
||||
accessible-role: button;
|
||||
accessible-label: MessageStrings.close;
|
||||
accessible-action-default => { root.close(); }
|
||||
clicked => { root.close(); }
|
||||
}
|
||||
}
|
||||
if root.notice-text != "": Rectangle {
|
||||
x: 16px; y: title-bar.height + 10px; width: parent.width - 32px; height: 28px;
|
||||
border-radius: 4px;
|
||||
background: #fef2f2;
|
||||
Text {
|
||||
x: 8px; width: parent.width - 16px; height: parent.height;
|
||||
text: root.notice-text; font-size: ImGuiFontStyle.body; overflow: elide;
|
||||
color: #b3261e;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
announcement-list := Rectangle {
|
||||
x: 16px; y: root.content-top; width: 168px; height: parent.height - self.y - 16px;
|
||||
announcements-scroll := ScrollView {
|
||||
width: parent.width; height: parent.height;
|
||||
VerticalLayout {
|
||||
width: announcements-scroll.width; spacing: 0px; padding: 0px;
|
||||
padding-right: 8px;
|
||||
alignment: start;
|
||||
for item[index] in root.items: Rectangle {
|
||||
height: 54px;
|
||||
background: root.selected-id == item.id ? #eaf2ff : entry-touch.has-hover ? #f0f1f2 : transparent;
|
||||
border-radius: 4px;
|
||||
Text { x: 8px; y: 6px; width: parent.width - 32px; height: 18px; text: item.title; overflow: elide; font-size: ImGuiFontStyle.base; font-weight: item.read ? 400 : 600; color: #202124; vertical-alignment: center; }
|
||||
if !item.read: Rectangle {
|
||||
x: parent.width - 17px; y: 13px; width: 5px; height: 5px;
|
||||
border-radius: 2.5px; background: #2563eb;
|
||||
accessible-role: none;
|
||||
}
|
||||
Text { x: 8px; y: 28px; width: parent.width - 36px; height: 16px; text: item.date; color: #61656c; font-size: ImGuiFontStyle.small; overflow: elide; vertical-alignment: center; }
|
||||
accessible-role: button;
|
||||
accessible-label: item.title + " " + (item.read ? MessageStrings.read : MessageStrings.unread);
|
||||
accessible-action-default => { root.open-message(item.id, item.revision); }
|
||||
entry-touch := TouchArea { mouse-cursor: pointer; clicked => { root.open-message(item.id, item.revision); } }
|
||||
IconButton {
|
||||
x: parent.width - 24px; y: 26px; width: 20px; height: 20px;
|
||||
icon: FontAwesomeIcons.xmark; icon-size: ImGuiFontStyle.small;
|
||||
icon-color: #61656c; danger: true;
|
||||
accessible-role: button;
|
||||
accessible-label: MessageStrings.delete-message + " " + item.title;
|
||||
accessible-action-default => { root.request-delete(item.id, item.revision); }
|
||||
clicked => { root.request-delete(item.id, item.revision); }
|
||||
}
|
||||
if index < root.items.length - 1: Rectangle {
|
||||
x: 8px; y: parent.height - 1px;
|
||||
width: parent.width - 16px; height: 1px;
|
||||
background: root.separator-color;
|
||||
accessible-role: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.items.length == 0 && root.total == 0 && root.loaded && root.connected && !root.loading && !root.failed: Text {
|
||||
x: 16px; y: root.content-top; width: parent.width - 32px; height: announcement-list.height;
|
||||
text: MessageStrings.empty; wrap: word-wrap;
|
||||
color: #61656c; font-size: ImGuiFontStyle.body;
|
||||
horizontal-alignment: center; vertical-alignment: center;
|
||||
}
|
||||
content-divider := Rectangle {
|
||||
x: announcement-list.x + announcement-list.width + 12px;
|
||||
y: root.content-top; width: 1px; height: announcement-list.height;
|
||||
background: root.separator-color;
|
||||
visible: root.items.length > 0 || root.selected-id != "";
|
||||
accessible-role: none;
|
||||
}
|
||||
announcement-details := Rectangle {
|
||||
x: content-divider.x + content-divider.width + 12px;
|
||||
y: root.content-top; width: parent.width - self.x - 16px; height: announcement-list.height;
|
||||
if root.selected-id == "" && root.items.length > 0: Text { x: 8px; width: parent.width - 16px; text: MessageStrings.select-message; color: #61656c; font-size: ImGuiFontStyle.body; wrap: word-wrap; horizontal-alignment: center; vertical-alignment: center; }
|
||||
if root.selected-id != "": details-scroll := ScrollView {
|
||||
width: parent.width; height: parent.height;
|
||||
VerticalLayout {
|
||||
width: details-scroll.width; padding: 8px; padding-top: 6px; padding-right: 16px;
|
||||
spacing: 12px; alignment: start;
|
||||
VerticalLayout {
|
||||
vertical-stretch: 0; spacing: 4px;
|
||||
Text { vertical-stretch: 0; min-height: 18px; text: root.selected-title; wrap: word-wrap; font-size: ImGuiFontStyle.base; font-weight: 600; color: #202124; vertical-alignment: center; }
|
||||
Text { vertical-stretch: 0; min-height: 16px; text: root.selected-date; accessible-label: root.selected-date + " · " + (root.selected-read ? MessageStrings.read : MessageStrings.unread); color: #61656c; font-size: ImGuiFontStyle.small; wrap: word-wrap; vertical-alignment: center; }
|
||||
}
|
||||
Rectangle { height: 1px; background: root.separator-color; }
|
||||
StyledText {
|
||||
vertical-stretch: 0;
|
||||
text: root.selected-body;
|
||||
default-color: #202124; default-font-size: ImGuiFontStyle.body;
|
||||
link-color: #2563eb;
|
||||
link-clicked(url) => { root.open-link(url); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Timer {
|
||||
interval: 100ms;
|
||||
running: root.connected && !root.loading && !root.failed
|
||||
&& root.pending-delete-id == "" && root.items.length > 0
|
||||
&& root.items.length < root.total && announcements-scroll.viewport-height > 0px
|
||||
&& announcements-scroll.viewport-height + announcements-scroll.viewport-y <= announcements-scroll.height + 80px;
|
||||
triggered => { root.load-more(); }
|
||||
}
|
||||
if root.pending-delete-id != "": Rectangle {
|
||||
background: #00000042; border-radius: root.border-radius; z: 30;
|
||||
TouchArea { clicked => { confirmation-keys.focus(); } }
|
||||
DialogSurface {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 230px; height: confirmation-content.preferred-height;
|
||||
border-radius: root.border-radius;
|
||||
TouchArea { clicked => { confirmation-keys.focus(); } }
|
||||
confirmation-content := VerticalLayout {
|
||||
padding: 16px;
|
||||
padding-top: 26px;
|
||||
padding-bottom: 26px;
|
||||
spacing: 20px;
|
||||
Text { text: MessageStrings.delete-confirmation; font-size: ImGuiFontStyle.base; color: #202124; wrap: word-wrap; horizontal-alignment: center; }
|
||||
HorizontalLayout {
|
||||
alignment: center; spacing: 8px;
|
||||
cancel-delete-button := CompactButton {
|
||||
width: 72px; text: MessageStrings.cancel;
|
||||
accessible-role: button; accessible-label: MessageStrings.cancel;
|
||||
accessible-action-default => { cancel-delete-button.clicked(); }
|
||||
clicked => { root.pending-delete-id = ""; }
|
||||
}
|
||||
confirm-delete-button := CompactButton {
|
||||
width: 72px; text: MessageStrings.delete-message; primary: true;
|
||||
accessible-role: button; accessible-label: MessageStrings.delete-title;
|
||||
accessible-action-default => { confirm-delete-button.clicked(); }
|
||||
clicked => {
|
||||
root.delete-message(root.pending-delete-id, root.pending-delete-revision);
|
||||
root.pending-delete-id = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComboBox, ScrollView } from "std-widgets.slint";
|
||||
import { FontAwesomeIcons, IconButton, PrimaryButton, ImGuiLineStyle, ImGuiFontStyle } from "common.slint";
|
||||
import { FontAwesomeIcons, IconButton, PrimaryButton, DialogSurface, ImGuiLineStyle, ImGuiFontStyle } from "common.slint";
|
||||
|
||||
export struct StreamTab {
|
||||
remote-id: string,
|
||||
@@ -23,6 +23,9 @@ export struct NetworkStatsRow {
|
||||
}
|
||||
|
||||
export global StreamStrings {
|
||||
in-out property <string> remote-update-title: "Remote device needs an update";
|
||||
in-out property <string> remote-update: "Please update to the latest version.";
|
||||
in-out property <string> remote-update-dismiss: "Got it";
|
||||
in-out property <string> video-settings: "Video settings";
|
||||
in-out property <string> video-settings-unavailable: "The remote device does not support live video settings";
|
||||
in-out property <string> video-quality: "Video quality";
|
||||
@@ -56,6 +59,8 @@ export global StreamStrings {
|
||||
in-out property <string> stats-out: "Out";
|
||||
in-out property <string> stats-loss-rate: "Loss Rate";
|
||||
in-out property <string> stats-resolution: "Res";
|
||||
in-out property <string> stats-video-latency: "Video delay";
|
||||
in-out property <string> stats-connection-latency: "Connection RTT";
|
||||
in-out property <string> stats-connection-mode: "Mode";
|
||||
in-out property <string> stats-encryption: "Encryption";
|
||||
in-out property <string> stats-encryption-enabled: "Enabled";
|
||||
@@ -194,6 +199,8 @@ export component StreamWindow inherits Window {
|
||||
in property <bool> has-frame: false;
|
||||
in property <string> status-text: "";
|
||||
in property <string> receiving-text: "";
|
||||
in property <bool> remote-update-visible: false;
|
||||
callback dismiss-remote-update;
|
||||
in property <[string]> displays;
|
||||
in-out property <int> selected-display: 0;
|
||||
in property <bool> mouse-control-enabled: true;
|
||||
@@ -218,6 +225,8 @@ export component StreamWindow inherits Window {
|
||||
in property <[NetworkStatsRow]> stats-rows;
|
||||
in property <string> stats-fps: "0";
|
||||
in property <string> stats-resolution: "";
|
||||
in property <string> stats-video-latency: "—";
|
||||
in property <string> stats-connection-latency: "—";
|
||||
in property <string> stats-connection-mode: "";
|
||||
in property <bool> stats-encryption-enabled: false;
|
||||
in property <bool> file-transfer-visible: false;
|
||||
@@ -253,7 +262,7 @@ export component StreamWindow inherits Window {
|
||||
private property <length> stats-row-height: 18px;
|
||||
private property <length> stats-header-height: 18px;
|
||||
private property <length> stats-content-height:
|
||||
root.stats-header-height + root.stats-rows.length * root.stats-row-height + 44px;
|
||||
root.stats-header-height + root.stats-rows.length * root.stats-row-height + 65px;
|
||||
private property <bool> display-menu-open: false;
|
||||
private property <bool> display-menu-animation-enabled: false;
|
||||
private property <float> display-menu-progress: 0.0;
|
||||
@@ -267,6 +276,15 @@ export component StreamWindow inherits Window {
|
||||
changed selected-tab => { root.video-menu-open = false; }
|
||||
changed control-expanded => { if !root.control-expanded { root.video-menu-open = false; } }
|
||||
changed window-active => { if !root.window-active { root.video-menu-open = false; } }
|
||||
changed remote-update-visible => {
|
||||
if root.remote-update-visible {
|
||||
root.video-menu-open = false;
|
||||
root.display-menu-open = false;
|
||||
root.shortcut-menu-open = false;
|
||||
}
|
||||
input-focus.focus();
|
||||
root.keyboard-focus-changed(!root.remote-update-visible);
|
||||
}
|
||||
private property <bool> control-tooltip-visible: false;
|
||||
private property <ControlBarTooltip> hovered-control: {
|
||||
if root.window-active && !root.control-dragging
|
||||
@@ -341,6 +359,7 @@ export component StreamWindow inherits Window {
|
||||
}
|
||||
|
||||
is-local-control-area(pointer-x, pointer-y) => {
|
||||
if root.remote-update-visible { return true; }
|
||||
let over-control = pointer-x >= control.x
|
||||
&& pointer-x <= control.x + control.width
|
||||
&& pointer-y >= control.y
|
||||
@@ -651,9 +670,11 @@ export component StreamWindow inherits Window {
|
||||
|
||||
drop-zone := DropArea {
|
||||
can-drop(event) => {
|
||||
return root.can-drop-file(event.data) ? DragAction.copy : DragAction.none;
|
||||
return !root.remote-update-visible && root.can-drop-file(event.data)
|
||||
? DragAction.copy : DragAction.none;
|
||||
}
|
||||
dropped(event) => {
|
||||
if root.remote-update-visible { return DragAction.none; }
|
||||
root.file-dropped(event.data);
|
||||
return DragAction.copy;
|
||||
}
|
||||
@@ -664,11 +685,20 @@ export component StreamWindow inherits Window {
|
||||
focus-gained => { root.keyboard-focus-changed(true); }
|
||||
focus-lost => { root.keyboard-focus-changed(false); }
|
||||
key-pressed(event) => {
|
||||
root.key-input(event.text, true, event.modifiers.control, event.modifiers.alt, event.modifiers.shift, event.modifiers.meta);
|
||||
if !root.remote-update-visible {
|
||||
root.key-input(event.text, true, event.modifiers.control, event.modifiers.alt, event.modifiers.shift, event.modifiers.meta);
|
||||
}
|
||||
accept
|
||||
}
|
||||
key-released(event) => {
|
||||
root.key-input(event.text, false, event.modifiers.control, event.modifiers.alt, event.modifiers.shift, event.modifiers.meta);
|
||||
if root.remote-update-visible {
|
||||
// Dismiss on release so the same key cannot reach the peer.
|
||||
if event.text == Key.Escape || event.text == Key.Return {
|
||||
root.dismiss-remote-update();
|
||||
}
|
||||
} else {
|
||||
root.key-input(event.text, false, event.modifiers.control, event.modifiers.alt, event.modifiers.shift, event.modifiers.meta);
|
||||
}
|
||||
accept
|
||||
}
|
||||
pointer := TouchArea {
|
||||
@@ -719,7 +749,12 @@ export component StreamWindow inherits Window {
|
||||
root.suppress-next-remote-pointer-release = false;
|
||||
input-focus.focus();
|
||||
}
|
||||
if event.kind == PointerEventKind.down
|
||||
// A gesture started before the modal appeared keeps
|
||||
// pointer capture. Let its release reach the peer.
|
||||
if root.remote-update-visible && !root.control-dragging
|
||||
&& event.kind == PointerEventKind.up {
|
||||
root.pointer-input(event.button, event.kind, self.mouse-x, self.mouse-y);
|
||||
} else if event.kind == PointerEventKind.down
|
||||
&& event.button == PointerEventButton.left
|
||||
&& over-control {
|
||||
root.begin-control-drag(self.mouse-x, self.mouse-y);
|
||||
@@ -903,18 +938,22 @@ export component StreamWindow inherits Window {
|
||||
private property <length> details-right-width:
|
||||
right-label-width-probe.preferred-width + 6px
|
||||
+ max(resolution-width-probe.preferred-width,
|
||||
connection-latency-width-probe.preferred-width,
|
||||
encryption-width-probe.preferred-width
|
||||
+ (root.stats-encryption-enabled ? 14px : 0px));
|
||||
private property <length> details-right-x: self.width / 2;
|
||||
private property <length> details-right-x:
|
||||
min(self.width / 2, self.width - self.details-right-width - 6px);
|
||||
|
||||
left-label-width-probe := Text {
|
||||
visible: false;
|
||||
text: "FPS\n" + StreamStrings.stats-connection-mode;
|
||||
text: "FPS\n" + StreamStrings.stats-video-latency
|
||||
+ "\n" + StreamStrings.stats-connection-mode;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
}
|
||||
right-label-width-probe := Text {
|
||||
visible: false;
|
||||
text: StreamStrings.stats-resolution + "\n" + StreamStrings.stats-encryption;
|
||||
text: StreamStrings.stats-resolution + "\n" + StreamStrings.stats-connection-latency
|
||||
+ "\n" + StreamStrings.stats-encryption;
|
||||
font-size: ImGuiFontStyle.small;
|
||||
}
|
||||
resolution-width-probe := Text {
|
||||
@@ -923,6 +962,12 @@ export component StreamWindow inherits Window {
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: 600;
|
||||
}
|
||||
connection-latency-width-probe := Text {
|
||||
visible: false;
|
||||
text: root.stats-connection-latency;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: 600;
|
||||
}
|
||||
encryption-width-probe := Text {
|
||||
visible: false;
|
||||
text: root.stats-encryption-enabled
|
||||
@@ -1029,12 +1074,14 @@ export component StreamWindow inherits Window {
|
||||
for metric[index] in [
|
||||
{ label: "FPS", value: root.stats-fps },
|
||||
{ label: StreamStrings.stats-resolution, value: root.stats-resolution },
|
||||
{ label: StreamStrings.stats-video-latency, value: root.stats-video-latency },
|
||||
{ label: StreamStrings.stats-connection-latency, value: root.stats-connection-latency },
|
||||
{ label: StreamStrings.stats-connection-mode, value: root.stats-connection-mode },
|
||||
{ label: StreamStrings.stats-encryption, value: root.stats-encryption-enabled
|
||||
? StreamStrings.stats-encryption-enabled : StreamStrings.stats-encryption-disabled },
|
||||
]: Rectangle {
|
||||
private property <length> encryption-icon-width:
|
||||
index == 3 && root.stats-encryption-enabled ? 14px : 0px;
|
||||
index == 5 && root.stats-encryption-enabled ? 14px : 0px;
|
||||
x: mod(index, 2) == 1 ? stats-table.details-right-x : 6px;
|
||||
y: root.stats-header-height + root.stats-rows.length * stats-table.row-height
|
||||
+ 2px + floor(index / 2) * 21px;
|
||||
@@ -1058,14 +1105,14 @@ export component StreamWindow inherits Window {
|
||||
height: parent.height;
|
||||
width: parent.width - self.x - parent.encryption-icon-width;
|
||||
text: metric.value;
|
||||
color: index == 3 && root.stats-encryption-enabled ? #18794e : #253247;
|
||||
color: index == 5 && root.stats-encryption-enabled ? #18794e : #253247;
|
||||
font-size: ImGuiFontStyle.body;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: left;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
if index == 3 && root.stats-encryption-enabled: Text {
|
||||
if index == 5 && root.stats-encryption-enabled: Text {
|
||||
x: metric-value.x + min(metric-value.preferred-width, metric-value.width) + 4px;
|
||||
y: metric-value.y + (metric-value.height - self.height) / 2;
|
||||
width: 10px;
|
||||
@@ -1256,6 +1303,80 @@ export component StreamWindow inherits Window {
|
||||
}
|
||||
}
|
||||
|
||||
if root.remote-update-visible: Rectangle {
|
||||
width: parent.width; height: parent.height;
|
||||
background: #0c162c52;
|
||||
z: 13;
|
||||
TouchArea {
|
||||
mouse-cursor: default;
|
||||
scroll-event(event) => { accept }
|
||||
}
|
||||
}
|
||||
remote-update-banner := DialogSurface {
|
||||
visible: root.remote-update-visible;
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: min(max(64px, parent.height * 0.18), max(16px, parent.height - self.height - 16px));
|
||||
width: min(520px, parent.width - 48px);
|
||||
height: max(208px, remote-update-message.y + remote-update-message.height + 92px);
|
||||
border-color: #e5e9f0;
|
||||
border-radius: 14px;
|
||||
drop-shadow-color: #07142b30;
|
||||
drop-shadow-blur: 32px;
|
||||
drop-shadow-offset-y: 12px;
|
||||
z: 14;
|
||||
TouchArea {
|
||||
mouse-cursor: default;
|
||||
pointer-event(event) => {
|
||||
if event.kind == PointerEventKind.down {
|
||||
root.suppress-next-remote-pointer-release = true;
|
||||
}
|
||||
}
|
||||
scroll-event(event) => { accept }
|
||||
}
|
||||
Rectangle {
|
||||
x: 32px; y: 32px; width: 48px; height: 48px;
|
||||
background: #edf4ff; border-radius: 12px;
|
||||
Path {
|
||||
x: 12px; y: 12px; width: 24px; height: 24px;
|
||||
viewbox-width: 24; viewbox-height: 24;
|
||||
commands: "M 12 16 L 12 3 M 6.5 8.5 L 12 3 L 17.5 8.5 M 4 15 L 4 20 Q 4 21 5 21 L 19 21 Q 20 21 20 20 L 20 15";
|
||||
fill: transparent;
|
||||
stroke: #2463c7; stroke-width: 1.8px;
|
||||
}
|
||||
}
|
||||
remote-update-title := Text {
|
||||
x: 100px; y: 34px; width: parent.width - 144px;
|
||||
height: max(28px, self.preferred-height);
|
||||
text: StreamStrings.remote-update-title;
|
||||
color: #1b2433; font-size: 20px; font-weight: 600;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
remote-update-message := Text {
|
||||
x: remote-update-title.x;
|
||||
y: remote-update-title.y + remote-update-title.height + 8px;
|
||||
width: remote-update-title.width;
|
||||
height: max(22px, self.preferred-height);
|
||||
text: StreamStrings.remote-update;
|
||||
color: #667085; font-size: 15px;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
IconButton {
|
||||
x: parent.width - 44px; y: 12px; width: 32px; height: 32px;
|
||||
icon: FontAwesomeIcons.xmark; icon-size: 14px;
|
||||
icon-color: #8a93a3;
|
||||
hover-background: #f2f4f7;
|
||||
clicked => { root.dismiss-remote-update(); }
|
||||
}
|
||||
PrimaryButton {
|
||||
x: parent.width - 136px; y: parent.height - 68px;
|
||||
width: 104px; height: 36px;
|
||||
border-radius: 7px;
|
||||
text: StreamStrings.remote-update-dismiss;
|
||||
text-size: 14px;
|
||||
clicked => { root.dismiss-remote-update(); }
|
||||
}
|
||||
}
|
||||
|
||||
// Transfer progress overlay at bottom-left.
|
||||
if root.file-transfer-visible: Rectangle {
|
||||
x: 18px; y: parent.height - min(210px, parent.height * 0.35); width: min(430px, parent.width * 0.6); height: min(190px, parent.height * 0.32);
|
||||
|
||||
@@ -26,6 +26,21 @@ inline int ApplyMainWindowStrings(
|
||||
const int language =
|
||||
localization::detail::ClampLanguageIndex(language_index);
|
||||
auto& strings = window->global<ui::UiStrings>();
|
||||
auto& messages = window->global<ui::MessageStrings>();
|
||||
messages.set_messages(Text(localization::messages[language]));
|
||||
messages.set_unread(Text(localization::message_unread[language]));
|
||||
messages.set_read(Text(localization::message_read[language]));
|
||||
messages.set_empty(Text(localization::message_empty[language]));
|
||||
messages.set_select_message(Text(localization::message_select[language]));
|
||||
messages.set_loading(Text(localization::message_loading[language]));
|
||||
messages.set_read_save_error(Text(localization::message_read_save_error[language]));
|
||||
messages.set_close(Text(localization::message_close[language]));
|
||||
messages.set_delete_message(Text(localization::message_delete[language]));
|
||||
messages.set_delete_title(Text(localization::message_delete_title[language]));
|
||||
messages.set_delete_confirmation(Text(localization::message_delete_confirmation[language]));
|
||||
messages.set_delete_error(Text(localization::message_delete_error[language]));
|
||||
messages.set_cancel(Text(localization::cancel[language]));
|
||||
|
||||
strings.set_local_desktop(Text(localization::local_desktop[language]));
|
||||
strings.set_remote_desktop(Text(localization::remote_desktop[language]));
|
||||
strings.set_recent_connections(
|
||||
@@ -65,6 +80,8 @@ inline int ApplyMainWindowStrings(
|
||||
Text(localization::self_hosted_server_config[language]));
|
||||
strings.set_autostart(Text(localization::enable_autostart[language]));
|
||||
strings.set_daemon(Text(localization::enable_daemon[language]));
|
||||
strings.set_save_remote_previews(Text(localization::save_remote_previews[language]));
|
||||
strings.set_unknown_platform(Text(localization::unknown_platform[language]));
|
||||
strings.set_privacy_on_connect(Text(localization::privacy_on_connect[language]));
|
||||
strings.set_file_save_path(
|
||||
Text(localization::file_transfer_save_path[language]));
|
||||
@@ -80,6 +97,7 @@ inline int ApplyMainWindowStrings(
|
||||
strings.set_tls_error(Text(localization::signal_tls_cert_error[language]));
|
||||
strings.set_update_available(
|
||||
Text(localization::new_version_available[language]));
|
||||
strings.set_new_version(Text(localization::new_version[language]));
|
||||
strings.set_check_for_updates(Text(localization::check_for_updates[language]));
|
||||
strings.set_checking_for_updates(
|
||||
Text(localization::checking_for_updates[language]));
|
||||
@@ -102,6 +120,20 @@ inline int ApplyMainWindowStrings(
|
||||
Text(localization::screen_recording_permission[language]));
|
||||
strings.set_accessibility_permission(
|
||||
Text(localization::accessibility_permission[language]));
|
||||
strings.set_wayland_notice_title(
|
||||
Text(localization::wayland_notice_title[language]));
|
||||
strings.set_wayland_notice_subtitle(
|
||||
Text(localization::wayland_notice_subtitle[language]));
|
||||
strings.set_wayland_permission_title(
|
||||
Text(localization::wayland_permission_title[language]));
|
||||
strings.set_wayland_notice_message(
|
||||
Text(localization::wayland_notice_message[language]));
|
||||
strings.set_wayland_recommendation_title(
|
||||
Text(localization::wayland_recommendation_title[language]));
|
||||
strings.set_wayland_recommendation_message(
|
||||
Text(localization::wayland_recommendation_message[language]));
|
||||
strings.set_wayland_notice_acknowledge(
|
||||
Text(localization::wayland_notice_acknowledge[language]));
|
||||
strings.set_service_setup_title(
|
||||
Text(localization::windows_service_setup_title[language]));
|
||||
strings.set_service_setup_message(
|
||||
@@ -133,6 +165,9 @@ inline int ApplyStreamWindowStrings(
|
||||
const int language =
|
||||
localization::detail::ClampLanguageIndex(language_index);
|
||||
auto& strings = window->template global<ui::StreamStrings>();
|
||||
strings.set_remote_update_title(Text(localization::remote_update_title[language]));
|
||||
strings.set_remote_update(Text(localization::remote_update[language]));
|
||||
strings.set_remote_update_dismiss(Text(localization::remote_update_dismiss[language]));
|
||||
strings.set_select_display(Text(localization::select_display[language]));
|
||||
strings.set_send_shortcut(Text(localization::send_shortcut[language]));
|
||||
strings.set_privacy_enable(Text(localization::privacy_enable[language]));
|
||||
@@ -175,6 +210,8 @@ inline int ApplyStreamWindowStrings(
|
||||
strings.set_stats_out(Text(localization::out[language]));
|
||||
strings.set_stats_loss_rate(Text(localization::loss_rate[language]));
|
||||
strings.set_stats_resolution(Text(localization::resolution[language]));
|
||||
strings.set_stats_video_latency(Text(localization::video_latency[language]));
|
||||
strings.set_stats_connection_latency(Text(localization::connection_latency[language]));
|
||||
strings.set_stats_connection_mode(
|
||||
Text(localization::connection_mode[language]));
|
||||
strings.set_stats_encryption(
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
#include "rd_log.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <filesystem>
|
||||
#include <iomanip>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#include "spdlog/sinks/rotating_file_sink.h"
|
||||
@@ -16,6 +12,7 @@ namespace crossdesk {
|
||||
namespace {
|
||||
|
||||
std::string g_log_dir = "logs";
|
||||
std::string g_logger_name = LOGGER_NAME;
|
||||
std::once_flag g_logger_once_flag;
|
||||
std::mutex g_logger_mutex;
|
||||
std::shared_ptr<spdlog::logger> g_logger;
|
||||
@@ -29,20 +26,20 @@ std::string NormalizeLogDirectory(const std::string& log_dir) {
|
||||
|
||||
} // namespace
|
||||
|
||||
void InitLogger(const std::string& log_dir) {
|
||||
void InitLogger(const std::string& log_dir, const std::string& logger_name) {
|
||||
const auto directory = NormalizeLogDirectory(log_dir);
|
||||
std::lock_guard<std::mutex> lock(g_logger_mutex);
|
||||
if (g_logger) {
|
||||
if (directory != g_log_dir) {
|
||||
if (directory != g_log_dir || logger_name != g_logger_name) {
|
||||
g_logger->warn(
|
||||
"InitLogger called after logger initialized. Ignoring log_dir: {}, "
|
||||
"using previous log_dir: {}",
|
||||
directory, g_log_dir);
|
||||
"InitLogger called after logger initialized. Keeping logger {} in {}",
|
||||
g_logger_name, g_log_dir);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
g_log_dir = directory;
|
||||
g_logger_name = logger_name;
|
||||
}
|
||||
|
||||
std::shared_ptr<spdlog::logger> get_logger() {
|
||||
@@ -53,32 +50,23 @@ std::shared_ptr<spdlog::logger> get_logger() {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(g_log_dir, ec);
|
||||
|
||||
auto now = std::chrono::system_clock::now() + std::chrono::hours(8);
|
||||
auto now_time = std::chrono::system_clock::to_time_t(now);
|
||||
|
||||
std::tm tm_info;
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&tm_info, &now_time);
|
||||
#else
|
||||
gmtime_r(&now_time, &tm_info);
|
||||
#endif
|
||||
|
||||
std::stringstream ss;
|
||||
ss << LOGGER_NAME;
|
||||
ss << std::put_time(&tm_info, "-%Y%m%d-%H%M%S.log");
|
||||
|
||||
std::string filename = g_log_dir + "/" + ss.str();
|
||||
// Reuse the same rotation set across restarts. Timestamped base names
|
||||
// give each launch its own backups and let the directory grow forever.
|
||||
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
|
||||
g_log_dir + "/" + g_logger_name + ".log", 5 * 1024 * 1024, 3);
|
||||
|
||||
std::vector<spdlog::sink_ptr> sinks;
|
||||
sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
|
||||
sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
|
||||
filename, 5 * 1024 * 1024, 3));
|
||||
sinks.push_back(file_sink);
|
||||
|
||||
auto logger = std::make_shared<spdlog::logger>(LOGGER_NAME, sinks.begin(),
|
||||
auto logger = std::make_shared<spdlog::logger>(g_logger_name, sinks.begin(),
|
||||
sinks.end());
|
||||
logger->set_level(SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG
|
||||
? spdlog::level::debug
|
||||
: spdlog::level::info);
|
||||
logger->flush_on(spdlog::level::info);
|
||||
spdlog::register_logger(logger);
|
||||
logger->info("Logger initialized: path={}", filename);
|
||||
logger->info("Logger initialized: path={}", file_sink->filename());
|
||||
g_logger = std::move(logger);
|
||||
});
|
||||
|
||||
|
||||
@@ -10,21 +10,26 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
#ifndef SPDLOG_ACTIVE_LEVEL
|
||||
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
|
||||
#endif
|
||||
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
constexpr auto LOGGER_NAME = "crossdesk";
|
||||
|
||||
void InitLogger(const std::string& log_dir);
|
||||
void InitLogger(const std::string& log_dir,
|
||||
const std::string& logger_name = LOGGER_NAME);
|
||||
|
||||
std::shared_ptr<spdlog::logger> get_logger();
|
||||
|
||||
#define LOG_TRACE(...) SPDLOG_LOGGER_TRACE(get_logger(), __VA_ARGS__)
|
||||
#define LOG_DEBUG(...) SPDLOG_LOGGER_DEBUG(get_logger(), __VA_ARGS__)
|
||||
#define LOG_INFO(...) SPDLOG_LOGGER_INFO(get_logger(), __VA_ARGS__)
|
||||
#define LOG_WARN(...) SPDLOG_LOGGER_WARN(get_logger(), __VA_ARGS__)
|
||||
#define LOG_ERROR(...) SPDLOG_LOGGER_ERROR(get_logger(), __VA_ARGS__)
|
||||
#define LOG_FATAL(...) SPDLOG_LOGGER_CRITICAL(get_logger(), __VA_ARGS__)
|
||||
} // namespace crossdesk
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -59,6 +59,7 @@ struct FrameSlot {
|
||||
int height = 0;
|
||||
std::string remote_id;
|
||||
uint64_t sequence = 0;
|
||||
VideoLatencyFrame timing;
|
||||
SlotUse use = SlotUse::available;
|
||||
bool valid = false;
|
||||
};
|
||||
@@ -320,6 +321,7 @@ struct OpenGlVideoRenderer::Impl {
|
||||
bool unpack_subimage_available = false;
|
||||
std::string uploaded_stream;
|
||||
uint64_t uploaded_sequence = 0;
|
||||
VideoLatencyFrame uploaded_timing;
|
||||
|
||||
#if CROSSDESK_OPENGL_CUDA_INTEROP
|
||||
enum class CudaUploadResult {
|
||||
@@ -1023,25 +1025,22 @@ void OpenGlVideoRenderer::DiscardStream(std::string_view remote_id) {
|
||||
}
|
||||
}
|
||||
|
||||
OpenGlVideoRenderer::SubmitResult
|
||||
OpenGlVideoRenderer::SubmitNv12(std::string_view remote_id,
|
||||
const uint8_t *data, size_t size,
|
||||
int width, int height) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, true);
|
||||
OpenGlVideoRenderer::SubmitResult OpenGlVideoRenderer::SubmitNv12(
|
||||
std::string_view remote_id, const uint8_t *data, size_t size, int width,
|
||||
int height, VideoLatencyFrame timing) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, true, timing);
|
||||
}
|
||||
|
||||
OpenGlVideoRenderer::SubmitResult
|
||||
OpenGlVideoRenderer::SubmitCachedNv12(std::string_view remote_id,
|
||||
const uint8_t *data, size_t size,
|
||||
int width, int height) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, false);
|
||||
OpenGlVideoRenderer::SubmitResult OpenGlVideoRenderer::SubmitCachedNv12(
|
||||
std::string_view remote_id, const uint8_t *data, size_t size, int width,
|
||||
int height, VideoLatencyFrame timing) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, false,
|
||||
timing);
|
||||
}
|
||||
|
||||
OpenGlVideoRenderer::SubmitResult
|
||||
OpenGlVideoRenderer::SubmitNv12Internal(std::string_view remote_id,
|
||||
const uint8_t *data, size_t size,
|
||||
int width, int height,
|
||||
bool replace_pending) {
|
||||
OpenGlVideoRenderer::SubmitResult OpenGlVideoRenderer::SubmitNv12Internal(
|
||||
std::string_view remote_id, const uint8_t *data, size_t size, int width,
|
||||
int height, bool replace_pending, VideoLatencyFrame timing) {
|
||||
if (!IsReady()) {
|
||||
return SubmitResult::failed;
|
||||
}
|
||||
@@ -1104,14 +1103,15 @@ OpenGlVideoRenderer::SubmitNv12Internal(std::string_view remote_id,
|
||||
target->height = height;
|
||||
target->remote_id.assign(remote_id);
|
||||
target->sequence = frames.next_sequence++;
|
||||
target->timing = timing;
|
||||
target->use = SlotUse::pending;
|
||||
target->valid = true;
|
||||
return SubmitResult::submitted;
|
||||
}
|
||||
|
||||
OpenGlVideoRenderer::SubmitResult
|
||||
OpenGlVideoRenderer::SubmitNativeFrame(std::string_view remote_id,
|
||||
const MiniRtcNativeVideoFrame &frame) {
|
||||
OpenGlVideoRenderer::SubmitResult OpenGlVideoRenderer::SubmitNativeFrame(
|
||||
std::string_view remote_id, const MiniRtcNativeVideoFrame &frame,
|
||||
VideoLatencyFrame timing) {
|
||||
if (!IsReady()) {
|
||||
return SubmitResult::failed;
|
||||
}
|
||||
@@ -1183,6 +1183,7 @@ OpenGlVideoRenderer::SubmitNativeFrame(std::string_view remote_id,
|
||||
target->height = static_cast<int>(native->height);
|
||||
target->remote_id.assign(remote_id);
|
||||
target->sequence = frames.next_sequence++;
|
||||
target->timing = timing;
|
||||
target->use = SlotUse::pending;
|
||||
target->valid = true;
|
||||
return SubmitResult::submitted;
|
||||
@@ -1204,6 +1205,7 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
|
||||
const unsigned char *y_data = nullptr;
|
||||
const unsigned char *uv_data = nullptr;
|
||||
NativeVideoFrameRef active_native_frame;
|
||||
VideoLatencyFrame timing;
|
||||
{
|
||||
std::lock_guard lock(impl_->frames->mutex);
|
||||
for (size_t index = 0; index < impl_->frames->slots.size(); ++index) {
|
||||
@@ -1221,6 +1223,7 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
|
||||
source_width = selected.width;
|
||||
source_height = selected.height;
|
||||
active_native_frame = selected.native_frame;
|
||||
timing = selected.timing;
|
||||
if (!selected.bytes.empty()) {
|
||||
const size_t y_size = static_cast<size_t>(source_width) * source_height;
|
||||
y_data = selected.bytes.data();
|
||||
@@ -1421,6 +1424,7 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
|
||||
impl_->texture_height = source_height;
|
||||
impl_->uploaded_stream.assign(remote_id);
|
||||
impl_->uploaded_sequence = sequence;
|
||||
impl_->uploaded_timing = timing;
|
||||
if (!use_pixel_unpack_buffer) {
|
||||
impl_->cpu_texture_width = source_width;
|
||||
impl_->cpu_texture_height = source_height;
|
||||
@@ -1549,6 +1553,8 @@ OpenGlVideoRenderer::RenderLatest(std::string_view remote_id,
|
||||
}
|
||||
#endif
|
||||
const GLenum draw_error = glGetError();
|
||||
if (has_video && draw_error == GL_NO_ERROR)
|
||||
impl_->uploaded_timing.MarkSubmitted();
|
||||
RenderOutcome outcome{
|
||||
!upload_succeeded || draw_error != GL_NO_ERROR
|
||||
? RenderResult::failed
|
||||
|
||||
@@ -39,11 +39,14 @@ public:
|
||||
|
||||
// Thread-safe; called from MiniRTC's decode callback thread.
|
||||
SubmitResult SubmitNv12(std::string_view remote_id, const uint8_t *data,
|
||||
size_t size, int width, int height) override;
|
||||
size_t size, int width, int height,
|
||||
VideoLatencyFrame timing = {}) override;
|
||||
SubmitResult SubmitCachedNv12(std::string_view remote_id, const uint8_t *data,
|
||||
size_t size, int width, int height) override;
|
||||
size_t size, int width, int height,
|
||||
VideoLatencyFrame timing = {}) override;
|
||||
SubmitResult SubmitNativeFrame(std::string_view remote_id,
|
||||
const MiniRtcNativeVideoFrame &frame) override;
|
||||
const MiniRtcNativeVideoFrame &frame,
|
||||
VideoLatencyFrame timing = {}) override;
|
||||
|
||||
// Draws below Slint while its OpenGL context is current. All dimensions are
|
||||
// physical pixels in the window client area. corner_radius_pixels clips the
|
||||
@@ -61,7 +64,8 @@ public:
|
||||
private:
|
||||
SubmitResult SubmitNv12Internal(std::string_view remote_id,
|
||||
const uint8_t *data, size_t size, int width,
|
||||
int height, bool replace_pending);
|
||||
int height, bool replace_pending,
|
||||
VideoLatencyFrame timing);
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
#include "platform/single_instance.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace crossdesk::platform {
|
||||
|
||||
SingleInstanceGuard::SingleInstanceGuard(std::string application)
|
||||
: application_(std::move(application)) {}
|
||||
|
||||
SingleInstanceGuard::~SingleInstanceGuard() { Release(); }
|
||||
|
||||
InstanceResult SingleInstanceGuard::TryAcquire(InstanceRole role,
|
||||
std::string& error) {
|
||||
error.clear();
|
||||
if (handle_ != -1) return InstanceResult::kAcquired;
|
||||
if (!ValidInstanceApplication(application_)) {
|
||||
error = "Invalid single-instance application name";
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
// A fixed local path also coordinates launches with different TMPDIR/XDG
|
||||
// settings. O_CLOEXEC prevents unrelated desktop/helper processes retaining it.
|
||||
const std::string path = "/tmp/" + application_ + "-" +
|
||||
std::to_string(geteuid()) + "-" +
|
||||
InstanceRoleName(role) + ".lock";
|
||||
const int fd = open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC | O_NOFOLLOW, 0600);
|
||||
if (fd < 0) {
|
||||
error = "Cannot open single-instance lock: " + std::string(std::strerror(errno));
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
struct stat info {};
|
||||
if (fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) || info.st_uid != geteuid()) {
|
||||
close(fd);
|
||||
error = "Single-instance lock is not a regular file owned by this user";
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
int result;
|
||||
do {
|
||||
result = flock(fd, LOCK_EX | LOCK_NB);
|
||||
} while (result != 0 && errno == EINTR);
|
||||
if (result == 0) {
|
||||
handle_ = fd;
|
||||
return InstanceResult::kAcquired;
|
||||
}
|
||||
const int lock_error = errno;
|
||||
close(fd);
|
||||
if (lock_error == EWOULDBLOCK || lock_error == EAGAIN)
|
||||
return InstanceResult::kAlreadyRunning;
|
||||
error = "Cannot acquire single-instance lock: " +
|
||||
std::string(std::strerror(lock_error));
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
|
||||
void SingleInstanceGuard::Release() {
|
||||
if (handle_ == -1) return;
|
||||
// Close rather than LOCK_UN: a forked headless application may still own the
|
||||
// same open file description. Never unlink a lock that another launch opened.
|
||||
close(static_cast<int>(handle_));
|
||||
handle_ = -1;
|
||||
}
|
||||
|
||||
} // namespace crossdesk::platform
|
||||
@@ -78,7 +78,7 @@ bool HeadlessConsole::Enable(const std::filesystem::path& log_directory,
|
||||
error_ = err;
|
||||
interactive_ = isatty(STDIN_FILENO) && isatty(output_);
|
||||
// Initialize after redirecting output so even the logger's first message
|
||||
// stays in its original crossdesk-YYYYMMDD-HHMMSS.log file.
|
||||
// stays in crossdesk.log.
|
||||
try {
|
||||
InitLogger(log_directory.string());
|
||||
for (const auto& sink : get_logger()->sinks()) {
|
||||
|
||||
@@ -35,8 +35,6 @@ int PlatformMouseController::Init(std::vector<DisplayInfo> display_info_list) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
root_ = DefaultRootWindow(display_);
|
||||
|
||||
int event_base, error_base, major_version, minor_version;
|
||||
if (!XTestQueryExtension(display_, &event_base, &error_base, &major_version,
|
||||
&minor_version)) {
|
||||
@@ -166,7 +164,10 @@ void PlatformMouseController::SetMousePosition(int x, int y) {
|
||||
if (!display_) {
|
||||
return;
|
||||
}
|
||||
XWarpPointer(display_, None, root_, 0, 0, 0, 0, x, y);
|
||||
// Inject motion through XTest so XInput2 raw-motion listeners (including
|
||||
// SDL's global pointer cache) see the movement.
|
||||
// XWarpPointer moves the cursor without producing those raw events.
|
||||
XTestFakeMotionEvent(display_, DefaultScreen(display_), x, y, CurrentTime);
|
||||
XFlush(display_);
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,6 @@ class PlatformMouseController final : public MouseController {
|
||||
enum class WaylandAbsoluteMode { kUnknown, kPixels, kNormalized, kDisabled };
|
||||
|
||||
_XDisplay* display_ = nullptr;
|
||||
unsigned long root_ = 0;
|
||||
std::vector<DisplayInfo> display_info_list_;
|
||||
int screen_width_ = 0;
|
||||
int screen_height_ = 0;
|
||||
|
||||
@@ -35,18 +35,20 @@ class MacMetalVideoRenderer final : public VideoRenderer {
|
||||
|
||||
// Copies one tightly packed NV12 frame into a free shared Metal slot.
|
||||
SubmitResult SubmitNv12(std::string_view remote_id, const uint8_t* data,
|
||||
size_t size, int width, int height) override;
|
||||
size_t size, int width, int height,
|
||||
VideoLatencyFrame timing = {}) override;
|
||||
|
||||
// Retains an IOSurface-backed VideoToolbox CVPixelBuffer until the Metal
|
||||
// command buffer using it has completed.
|
||||
SubmitResult SubmitNativeFrame(std::string_view remote_id,
|
||||
const MiniRtcNativeVideoFrame& frame) override;
|
||||
const MiniRtcNativeVideoFrame& frame,
|
||||
VideoLatencyFrame timing = {}) override;
|
||||
|
||||
// Seeds a newly selected stream from its retained CPU snapshot without
|
||||
// replacing a newer decoded frame that is already queued or rendering.
|
||||
SubmitResult SubmitCachedNv12(std::string_view remote_id,
|
||||
const uint8_t* data, size_t size, int width,
|
||||
int height) override;
|
||||
SubmitResult SubmitCachedNv12(std::string_view remote_id, const uint8_t* data,
|
||||
size_t size, int width, int height,
|
||||
VideoLatencyFrame timing = {}) override;
|
||||
|
||||
// Attaches a native CAMetalLayer-backed sibling below Slint's NSView and
|
||||
// restores the containing AppKit window's ordinary opaque titlebar.
|
||||
@@ -76,7 +78,8 @@ class MacMetalVideoRenderer final : public VideoRenderer {
|
||||
private:
|
||||
SubmitResult SubmitNv12Internal(std::string_view remote_id,
|
||||
const uint8_t* data, size_t size, int width,
|
||||
int height, bool replace_pending);
|
||||
int height, bool replace_pending,
|
||||
VideoLatencyFrame timing);
|
||||
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <CoreVideo/CVMetalTextureCache.h>
|
||||
#import <Metal/Metal.h>
|
||||
#import <QuartzCore/CABase.h>
|
||||
#import <QuartzCore/CAMetalLayer.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
@@ -340,6 +342,7 @@ struct FrameSlot {
|
||||
int height = 0;
|
||||
std::string remote_id;
|
||||
uint64_t sequence = 0;
|
||||
VideoLatencyFrame timing;
|
||||
SlotUse use = SlotUse::available;
|
||||
bool valid = false;
|
||||
|
||||
@@ -744,14 +747,16 @@ void MacMetalVideoRenderer::DiscardStream(std::string_view remote_id) {
|
||||
}
|
||||
}
|
||||
|
||||
MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNv12(
|
||||
std::string_view remote_id, const uint8_t* data, size_t size, int width,
|
||||
int height) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, true);
|
||||
MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNv12(std::string_view remote_id,
|
||||
const uint8_t* data,
|
||||
size_t size, int width,
|
||||
int height,
|
||||
VideoLatencyFrame timing) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, true, timing);
|
||||
}
|
||||
|
||||
MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNativeFrame(
|
||||
std::string_view remote_id, const MiniRtcNativeVideoFrame& frame) {
|
||||
std::string_view remote_id, const MiniRtcNativeVideoFrame& frame, VideoLatencyFrame timing) {
|
||||
if (!IsReady()) {
|
||||
return SubmitResult::failed;
|
||||
}
|
||||
@@ -781,8 +786,7 @@ MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNativeFrame(
|
||||
packed_nv12.size()) != 0) {
|
||||
return SubmitResult::failed;
|
||||
}
|
||||
return SubmitNv12(remote_id, packed_nv12.data(), packed_nv12.size(), width,
|
||||
height);
|
||||
return SubmitNv12(remote_id, packed_nv12.data(), packed_nv12.size(), width, height, timing);
|
||||
};
|
||||
|
||||
CVPixelBufferRef pixel_buffer =
|
||||
@@ -878,6 +882,7 @@ MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNativeFrame(
|
||||
target->height = height;
|
||||
target->remote_id.assign(remote_id);
|
||||
target->sequence = frames.next_sequence++;
|
||||
target->timing = timing;
|
||||
target->use = SlotUse::pending;
|
||||
target->valid = true;
|
||||
if (!impl_->native_path_logged.exchange(true, std::memory_order_acq_rel)) {
|
||||
@@ -887,14 +892,14 @@ MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNativeFrame(
|
||||
}
|
||||
|
||||
MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitCachedNv12(
|
||||
std::string_view remote_id, const uint8_t* data, size_t size, int width,
|
||||
int height) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, false);
|
||||
std::string_view remote_id, const uint8_t* data, size_t size, int width, int height,
|
||||
VideoLatencyFrame timing) {
|
||||
return SubmitNv12Internal(remote_id, data, size, width, height, false, timing);
|
||||
}
|
||||
|
||||
MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNv12Internal(
|
||||
std::string_view remote_id, const uint8_t* data, size_t size, int width,
|
||||
int height, bool replace_pending) {
|
||||
std::string_view remote_id, const uint8_t* data, size_t size, int width, int height,
|
||||
bool replace_pending, VideoLatencyFrame timing) {
|
||||
if (!IsReady()) {
|
||||
return SubmitResult::failed;
|
||||
}
|
||||
@@ -968,6 +973,7 @@ MacMetalVideoRenderer::SubmitResult MacMetalVideoRenderer::SubmitNv12Internal(
|
||||
|
||||
target->remote_id.assign(remote_id);
|
||||
target->sequence = frames.next_sequence++;
|
||||
target->timing = timing;
|
||||
target->use = SlotUse::pending;
|
||||
target->valid = true;
|
||||
return SubmitResult::submitted;
|
||||
@@ -1189,6 +1195,7 @@ MacMetalVideoRenderer::RenderOutcome MacMetalVideoRenderer::RenderLatest(
|
||||
|
||||
id<MTLTexture> y_texture = nil;
|
||||
id<MTLTexture> uv_texture = nil;
|
||||
VideoLatencyFrame timing;
|
||||
{
|
||||
std::lock_guard lock(impl_->frames->mutex);
|
||||
auto& slot = impl_->frames->slots[slot_index];
|
||||
@@ -1202,6 +1209,7 @@ MacMetalVideoRenderer::RenderOutcome MacMetalVideoRenderer::RenderLatest(
|
||||
slot.use = SlotUse::in_flight;
|
||||
y_texture = slot.y_texture;
|
||||
uv_texture = slot.uv_texture;
|
||||
timing = slot.timing;
|
||||
}
|
||||
|
||||
MTLRenderPassDescriptor* pass = [MTLRenderPassDescriptor renderPassDescriptor];
|
||||
@@ -1259,6 +1267,19 @@ MacMetalVideoRenderer::RenderOutcome MacMetalVideoRenderer::RenderLatest(
|
||||
slot.use = SlotUse::available;
|
||||
}
|
||||
}];
|
||||
[drawable addPresentedHandler:^(id<MTLDrawable> presented) {
|
||||
// presentedTime uses the Core Animation host clock. Translate its age
|
||||
// into our steady clock, excluding callback scheduling delay. Capturing
|
||||
// timing by value keeps this safe after a session/renderer is destroyed.
|
||||
const double presented_time = presented.presentedTime;
|
||||
const auto now = VideoLatencyFrame::Clock::now();
|
||||
const double age = CACurrentMediaTime() - presented_time;
|
||||
if (presented_time > 0 && std::isfinite(age) && age >= 0 && age <= 5) {
|
||||
timing.MarkPresented(
|
||||
now - std::chrono::duration_cast<VideoLatencyFrame::Clock::duration>(
|
||||
std::chrono::duration<double>(age)));
|
||||
}
|
||||
}];
|
||||
[command_buffer presentDrawable:drawable];
|
||||
[command_buffer commit];
|
||||
impl_->rendered_stream.assign(remote_id);
|
||||
|
||||
@@ -80,25 +80,36 @@ bool StartNativeWindowDrag() {
|
||||
}
|
||||
}
|
||||
|
||||
bool HideDisabledMainWindowZoomButton() {
|
||||
bool ConfigureMainWindowChrome(void *opaque_slint_view) {
|
||||
@autoreleasepool {
|
||||
for (NSWindow *window in [NSApp windows]) {
|
||||
if (![window.title isEqualToString:@"CrossDesk"]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
NSButton *zoom_button =
|
||||
[window standardWindowButton:NSWindowZoomButton];
|
||||
// The main window has a fixed size, so AppKit disables its zoom button.
|
||||
// Stream windows remain resizable and must keep their native button.
|
||||
if (zoom_button == nil || zoom_button.enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
zoom_button.hidden = YES;
|
||||
return true;
|
||||
NSView *slint_view = (__bridge NSView *)opaque_slint_view;
|
||||
NSWindow *window = slint_view.window;
|
||||
if (window == nil ||
|
||||
(window.styleMask & NSWindowStyleMaskTitled) == 0) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
|
||||
NSButton *zoom_button =
|
||||
[window standardWindowButton:NSWindowZoomButton];
|
||||
if (zoom_button == nil || zoom_button.enabled) {
|
||||
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;
|
||||
zoom_button.hidden = YES;
|
||||
|
||||
NSView *frame_view = window.contentView.superview;
|
||||
frame_view.needsLayout = YES;
|
||||
[frame_view layoutSubtreeIfNeeded];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -903,12 +903,15 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
// method is still running on another thread.
|
||||
std::mutex _capturer_lock;
|
||||
ScreenCapturerSckImpl *_capturer;
|
||||
dispatch_queue_t _completion_queue;
|
||||
}
|
||||
|
||||
- (instancetype)initWithCapturer:(ScreenCapturerSckImpl *)capturer {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_capturer = capturer;
|
||||
_completion_queue = dispatch_queue_create("CrossDesk.ScreenCaptureKit.Completions",
|
||||
DISPATCH_QUEUE_SERIAL);
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(privacyCoversChanged:)
|
||||
name:@"CrossDeskPrivacyCoversChanged" object:nil];
|
||||
}
|
||||
@@ -922,18 +925,25 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
- (void)configurationFinished:(SCStream*)stream generation:(uint64_t)generation
|
||||
revision:(uint64_t)revision complete:(BOOL)complete
|
||||
configuration:(SCStreamConfiguration*)configuration error:(NSError*)error {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer)
|
||||
_capturer->ConfigurationFinished(stream, generation, revision, complete, configuration, error);
|
||||
// SCK may call a completion inline (notably updateContentFilter when nothing
|
||||
// changed). The caller can still hold both _capturer_lock and the capturer's
|
||||
// state lock. Always defer before acquiring either lock, including errors.
|
||||
// The block retains this helper; releaseCapturer revokes queued callbacks
|
||||
// before the C++ capturer is destroyed.
|
||||
dispatch_async(_completion_queue, ^{
|
||||
std::lock_guard<std::mutex> lock(self->_capturer_lock);
|
||||
if (self->_capturer)
|
||||
self->_capturer->ConfigurationFinished(stream, generation, revision, complete,
|
||||
configuration, error);
|
||||
});
|
||||
}
|
||||
- (void)onShareableContentCreated:(SCShareableContent *)content generation:(uint64_t)generation
|
||||
revision:(uint64_t)revision {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer) {
|
||||
_capturer->OnShareableContentCreated(content, generation, revision);
|
||||
} else {
|
||||
LOG_ERROR("Invalid capturer");
|
||||
}
|
||||
dispatch_async(_completion_queue, ^{
|
||||
std::lock_guard<std::mutex> lock(self->_capturer_lock);
|
||||
if (self->_capturer)
|
||||
self->_capturer->OnShareableContentCreated(content, generation, revision);
|
||||
});
|
||||
}
|
||||
|
||||
- (void)stream:(SCStream *)stream
|
||||
@@ -971,8 +981,10 @@ void ScreenCapturerSckImpl::StartOrReconfigureCapturer() {
|
||||
}
|
||||
|
||||
- (void)stream:(SCStream*)stream didStopWithError:(NSError*)error {
|
||||
std::lock_guard<std::mutex> lock(_capturer_lock);
|
||||
if (_capturer) _capturer->CaptureStopped(stream, error);
|
||||
dispatch_async(_completion_queue, ^{
|
||||
std::lock_guard<std::mutex> lock(self->_capturer_lock);
|
||||
if (self->_capturer) self->_capturer->CaptureStopped(stream, error);
|
||||
});
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-26
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SINGLE_INSTANCE_H_
|
||||
#define _SINGLE_INSTANCE_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk::platform {
|
||||
|
||||
enum class InstanceRole { kLauncher, kClient, kServiceCli };
|
||||
enum class InstanceResult { kAcquired, kAlreadyRunning, kError };
|
||||
|
||||
// Per-user ownership, independent of the install/portable directory. The OS
|
||||
// releases ownership on process exit, including crashes; no PID files to age out.
|
||||
class SingleInstanceGuard {
|
||||
public:
|
||||
explicit SingleInstanceGuard(std::string application = "CrossDesk");
|
||||
~SingleInstanceGuard();
|
||||
SingleInstanceGuard(const SingleInstanceGuard&) = delete;
|
||||
SingleInstanceGuard& operator=(const SingleInstanceGuard&) = delete;
|
||||
|
||||
InstanceResult TryAcquire(InstanceRole role, std::string& error);
|
||||
void Release();
|
||||
|
||||
private:
|
||||
std::string application_;
|
||||
std::intptr_t handle_ = -1;
|
||||
};
|
||||
|
||||
inline const char* InstanceRoleName(InstanceRole role) {
|
||||
switch (role) {
|
||||
case InstanceRole::kLauncher: return "launcher";
|
||||
case InstanceRole::kClient: return "client";
|
||||
case InstanceRole::kServiceCli: return "service-cli";
|
||||
}
|
||||
return "client";
|
||||
}
|
||||
|
||||
inline bool ValidInstanceApplication(const std::string& application) {
|
||||
return !application.empty() && application.size() <= 100 &&
|
||||
application.find_first_not_of(
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") ==
|
||||
std::string::npos;
|
||||
}
|
||||
|
||||
} // namespace crossdesk::platform
|
||||
|
||||
#endif
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "minirtc.h"
|
||||
#include "rendering/video_latency.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
@@ -54,14 +55,17 @@ public:
|
||||
|
||||
virtual SubmitResult SubmitNv12(std::string_view remote_id,
|
||||
const uint8_t* data, size_t size, int width,
|
||||
int height) = 0;
|
||||
int height,
|
||||
VideoLatencyFrame timing = {}) = 0;
|
||||
virtual SubmitResult SubmitCachedNv12(std::string_view remote_id,
|
||||
const uint8_t* data, size_t size,
|
||||
int width, int height) = 0;
|
||||
int width, int height,
|
||||
VideoLatencyFrame timing = {}) = 0;
|
||||
// Retains a platform-native decoded frame when the backend supports its
|
||||
// storage and handle types. Unsupported backends keep the default fallback.
|
||||
virtual SubmitResult SubmitNativeFrame(std::string_view,
|
||||
const MiniRtcNativeVideoFrame&) {
|
||||
const MiniRtcNativeVideoFrame&,
|
||||
VideoLatencyFrame = {}) {
|
||||
return SubmitResult::failed;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,9 +8,10 @@ namespace crossdesk {
|
||||
// left-mouse-down event. Returns false when no suitable native event exists.
|
||||
bool StartNativeWindowDrag();
|
||||
|
||||
// Hides the disabled native zoom button on CrossDesk's fixed-size main
|
||||
// window. Returns true once the matching AppKit window has been configured.
|
||||
bool HideDisabledMainWindowZoomButton();
|
||||
// Sets a fixed white native titlebar and hides the disabled zoom button on
|
||||
// the fixed-size main window. |slint_view| is its AppKit NSView*. Returns false
|
||||
// while the native window or its fixed-size constraints are not ready.
|
||||
bool ConfigureMainWindowChrome(void* slint_view);
|
||||
|
||||
// Configures live resize and replaces the stream window's native Space
|
||||
// fullscreen action with an immediate, single-window fullscreen transition.
|
||||
|
||||
@@ -547,7 +547,7 @@ void ScreenCapturerDxgi::CaptureLoop() {
|
||||
if (last_logged_cursor_embedding_ < 0 ||
|
||||
(software_cursor_output_ &&
|
||||
last_logged_cursor_embedding_ != static_cast<int>(cursor_embedded))) {
|
||||
LOG_INFO("DXGI cursor: monitor={} usbmmidd={} mouse_update={} "
|
||||
LOG_DEBUG("DXGI cursor: monitor={} usbmmidd={} mouse_update={} "
|
||||
"separate_pointer_visible={} pointer_shape_bytes={} "
|
||||
"compose_cursor={} embedded={}",
|
||||
frame_monitor, software_cursor_output_,
|
||||
|
||||
@@ -1638,7 +1638,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
|
||||
const ULONGLONG elapsed = GetTickCount64() - stats_started;
|
||||
if (elapsed == 0 || (!force && elapsed < 5000)) return;
|
||||
if (shared_frames || fallback_frames || shared_waits || shared_restarts) {
|
||||
LOG_INFO(
|
||||
LOG_DEBUG(
|
||||
"Secure capture delivery: shared_fps={:.1f}, fallback_fps={:.1f}, "
|
||||
"pending_waits={}, shared_restarts={}, status_max_ms={}",
|
||||
shared_frames * 1000.0 / elapsed, fallback_frames * 1000.0 / elapsed,
|
||||
|
||||
@@ -12,7 +12,7 @@ void InitializePluginLogger() {
|
||||
static std::once_flag once;
|
||||
std::call_once(once, []() {
|
||||
crossdesk::PathManager path_manager("CrossDesk");
|
||||
crossdesk::InitLogger(path_manager.GetLogPath().string());
|
||||
crossdesk::InitLogger(path_manager.GetLogPath().string(), "crossdesk-wgc");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#include "platform/single_instance.h"
|
||||
|
||||
#include <windows.h>
|
||||
#include <sddl.h>
|
||||
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk::platform {
|
||||
|
||||
SingleInstanceGuard::SingleInstanceGuard(std::string application)
|
||||
: application_(std::move(application)) {}
|
||||
|
||||
SingleInstanceGuard::~SingleInstanceGuard() { Release(); }
|
||||
|
||||
InstanceResult SingleInstanceGuard::TryAcquire(InstanceRole role,
|
||||
std::string& error) {
|
||||
error.clear();
|
||||
if (handle_ != -1) return InstanceResult::kAcquired;
|
||||
if (!ValidInstanceApplication(application_)) {
|
||||
error = "Invalid single-instance application name";
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
HANDLE token = nullptr;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
|
||||
error = "Cannot read current user token: " + std::to_string(GetLastError());
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
DWORD size = 0;
|
||||
GetTokenInformation(token, TokenUser, nullptr, 0, &size);
|
||||
std::vector<unsigned char> buffer(size);
|
||||
if (!GetTokenInformation(token, TokenUser, buffer.data(), size, &size)) {
|
||||
const DWORD code = GetLastError();
|
||||
CloseHandle(token);
|
||||
error = "Cannot read current user SID: " + std::to_string(code);
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
CloseHandle(token);
|
||||
wchar_t* sid = nullptr;
|
||||
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER*>(buffer.data())->User.Sid,
|
||||
&sid)) {
|
||||
error = "Cannot format current user SID: " + std::to_string(GetLastError());
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
const std::string role_name = InstanceRoleName(role);
|
||||
const std::wstring name = L"Global\\" +
|
||||
std::wstring(application_.begin(), application_.end()) + L"." + sid + L"." +
|
||||
std::wstring(role_name.begin(), role_name.end());
|
||||
LocalFree(sid);
|
||||
// Object lifetime is the lease. No thread-owned mutex to transfer to a daemon.
|
||||
HANDLE mutex = CreateMutexW(nullptr, FALSE, name.c_str());
|
||||
const DWORD code = GetLastError();
|
||||
if (!mutex) {
|
||||
error = "Cannot create single-instance mutex: " + std::to_string(code);
|
||||
return InstanceResult::kError;
|
||||
}
|
||||
if (code == ERROR_ALREADY_EXISTS) {
|
||||
CloseHandle(mutex);
|
||||
return InstanceResult::kAlreadyRunning;
|
||||
}
|
||||
handle_ = reinterpret_cast<std::intptr_t>(mutex);
|
||||
return InstanceResult::kAcquired;
|
||||
}
|
||||
|
||||
void SingleInstanceGuard::Release() {
|
||||
if (handle_ == -1) return;
|
||||
CloseHandle(reinterpret_cast<HANDLE>(handle_));
|
||||
handle_ = -1;
|
||||
}
|
||||
|
||||
} // namespace crossdesk::platform
|
||||
@@ -1,11 +1,17 @@
|
||||
#include "thumbnail.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include <openssl/aes.h>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/rand.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
@@ -104,116 +110,217 @@ int Thumbnail::SetThumbnailDpiScale(float dpi_scale) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Thumbnail::SaveToThumbnail(const char* yuv420p, int width, int height,
|
||||
namespace {
|
||||
|
||||
bool IsRemoteId(const std::string& id) {
|
||||
return id.size() == 9 &&
|
||||
std::all_of(id.begin(), id.end(),
|
||||
[](unsigned char c) { return c >= '0' && c <= '9'; });
|
||||
}
|
||||
|
||||
std::string ConnectionKey(const Thumbnail::RecentConnection& connection) {
|
||||
return connection.remote_id + (connection.remember_password ? "Y" : "N") +
|
||||
connection.remote_host_name +
|
||||
(connection.remember_password ? "@" + connection.password : "");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool Thumbnail::WriteRecord(const RecentConnection& connection) {
|
||||
const auto path =
|
||||
std::filesystem::path(save_path_) / (connection.remote_id + ".json");
|
||||
const auto temporary = path.string() + ".tmp";
|
||||
const nlohmann::json record = {
|
||||
{"remote_id", connection.remote_id},
|
||||
{"host_name", connection.remote_host_name},
|
||||
{"password",
|
||||
connection.remember_password
|
||||
? AES_encrypt(connection.password, aes128_key_, aes128_iv_)
|
||||
: ""},
|
||||
{"platform", HostPlatformName(connection.platform)}};
|
||||
std::ofstream output(temporary, std::ios::binary | std::ios::trunc);
|
||||
output << record.dump();
|
||||
output.close();
|
||||
if (!output) return false;
|
||||
std::error_code error;
|
||||
#ifdef _WIN32
|
||||
// Windows rename does not replace an existing destination.
|
||||
if (!MoveFileExW(std::filesystem::path(temporary).c_str(), path.c_str(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
|
||||
std::filesystem::remove(temporary, error);
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
std::filesystem::rename(temporary, path, error);
|
||||
if (error) {
|
||||
std::filesystem::remove(temporary, error);
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Thumbnail::ReadRecord(const std::filesystem::path& path,
|
||||
RecentConnection* connection) {
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
const auto record = nlohmann::json::parse(input, nullptr, false);
|
||||
if (!record.is_object()) return false;
|
||||
try {
|
||||
connection->remote_id = record.value("remote_id", "");
|
||||
if (!IsRemoteId(connection->remote_id) ||
|
||||
path.stem() != connection->remote_id)
|
||||
return false;
|
||||
connection->remote_host_name = record.value("host_name", "");
|
||||
const auto password = record.value("password", "");
|
||||
connection->remember_password = !password.empty();
|
||||
connection->password =
|
||||
password.empty() ? "" : AES_decrypt(password, aes128_key_, aes128_iv_);
|
||||
connection->platform =
|
||||
ParseHostPlatform(record.value("platform", "unknown"));
|
||||
const auto image = path.parent_path() / (connection->remote_id + ".png");
|
||||
if (save_previews_ && std::filesystem::is_regular_file(image)) {
|
||||
connection->image_path = image;
|
||||
}
|
||||
return true;
|
||||
} catch (const nlohmann::json::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
int Thumbnail::SetSavePreviews(bool enabled) {
|
||||
std::lock_guard lock(mutex_);
|
||||
save_previews_ = enabled;
|
||||
if (enabled) return 0;
|
||||
// Migrate legacy filenames before removing their image contents, preserving
|
||||
// credentials, names and recency even when previews have never been enabled.
|
||||
std::vector<std::pair<std::string, RecentConnection>> connections;
|
||||
return LoadThumbnailLocked(connections);
|
||||
}
|
||||
|
||||
int Thumbnail::SaveToThumbnail(const char* nv12, int width, int height,
|
||||
const std::string& remote_id,
|
||||
const std::string& host_name,
|
||||
const std::string& password) {
|
||||
if (!rgba_buffer_) {
|
||||
rgba_buffer_ = new char[thumbnail_width_ * thumbnail_height_ * 4];
|
||||
}
|
||||
const std::string& password,
|
||||
HostPlatform platform) {
|
||||
std::lock_guard lock(mutex_);
|
||||
// Preserve the existing opt-in via Remember password for recent connections.
|
||||
if (password.empty()) return 0;
|
||||
if (!IsRemoteId(remote_id)) return -1;
|
||||
RecentConnection connection;
|
||||
ReadRecord(std::filesystem::path(save_path_) / (remote_id + ".json"),
|
||||
&connection);
|
||||
connection.remote_id = remote_id;
|
||||
connection.remote_host_name = host_name;
|
||||
connection.password = password;
|
||||
connection.remember_password = true;
|
||||
if (platform != HostPlatform::Unknown) connection.platform = platform;
|
||||
if (!WriteRecord(connection)) return -1;
|
||||
|
||||
if (yuv420p) {
|
||||
ScaleNv12ToABGR((char*)yuv420p, width, height, thumbnail_width_,
|
||||
thumbnail_height_, rgba_buffer_);
|
||||
} else {
|
||||
// If yuv420p is null, fill the buffer with black pixels
|
||||
std::memset(rgba_buffer_, 0x00, thumbnail_width_ * thumbnail_height_ * 4);
|
||||
for (int i = 0; i < thumbnail_width_ * thumbnail_height_; ++i) {
|
||||
// Set alpha channel to opaque
|
||||
rgba_buffer_[i * 4 + 3] = static_cast<char>(0xFF);
|
||||
const auto image = std::filesystem::path(save_path_) / (remote_id + ".png");
|
||||
if (save_previews_ && nv12 && width > 0 && height > 0) {
|
||||
if (!rgba_buffer_) {
|
||||
rgba_buffer_ = new char[thumbnail_width_ * thumbnail_height_ * 4];
|
||||
}
|
||||
ScaleNv12ToABGR(const_cast<char*>(nv12), width, height, thumbnail_width_,
|
||||
thumbnail_height_, rgba_buffer_);
|
||||
if (!stbi_write_png(image.string().c_str(), thumbnail_width_,
|
||||
thumbnail_height_, 4, rgba_buffer_,
|
||||
thumbnail_width_ * 4))
|
||||
return -1;
|
||||
} else if (!save_previews_) {
|
||||
std::error_code error;
|
||||
std::filesystem::remove(image, error);
|
||||
if (error) return -1;
|
||||
}
|
||||
|
||||
std::string image_file_name;
|
||||
if (password.empty()) {
|
||||
return 0;
|
||||
} else {
|
||||
// delete the old thumbnail
|
||||
std::string filename_with_remote_id = remote_id;
|
||||
DeleteThumbnail(filename_with_remote_id);
|
||||
}
|
||||
|
||||
std::string cipher_password = AES_encrypt(password, aes128_key_, aes128_iv_);
|
||||
image_file_name = remote_id + 'Y' + host_name + '@' + cipher_password;
|
||||
std::string file_path = save_path_ + image_file_name;
|
||||
stbi_write_png(file_path.data(), thumbnail_width_, thumbnail_height_, 4,
|
||||
rgba_buffer_, thumbnail_width_ * 4);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Thumbnail::LoadThumbnail(
|
||||
std::vector<std::pair<std::string, Thumbnail::RecentConnection>>&
|
||||
recent_connections,
|
||||
std::vector<std::pair<std::string, RecentConnection>>& recent_connections,
|
||||
int* width, int* height) {
|
||||
recent_connections.clear();
|
||||
std::lock_guard lock(mutex_);
|
||||
if (width) *width = thumbnail_width_;
|
||||
if (height) *height = thumbnail_height_;
|
||||
return LoadThumbnailLocked(recent_connections);
|
||||
}
|
||||
|
||||
std::vector<std::filesystem::path> image_paths =
|
||||
FindThumbnailPath(save_path_);
|
||||
|
||||
if (image_paths.size() == 0) {
|
||||
return -1;
|
||||
} else {
|
||||
for (int i = 0; i < image_paths.size(); i++) {
|
||||
// size_t pos1 = image_paths[i].string().find('/') + 1;
|
||||
std::string cipher_image_name = image_paths[i].filename().string();
|
||||
std::string remote_id;
|
||||
std::string cipher_password;
|
||||
std::string remote_host_name;
|
||||
std::string password;
|
||||
std::string original_image_name;
|
||||
bool remember_password = false;
|
||||
|
||||
if (cipher_image_name.size() > 9 && 'Y' == cipher_image_name[9] &&
|
||||
cipher_image_name.size() >= 16) {
|
||||
size_t pos_y = cipher_image_name.find('Y');
|
||||
size_t pos_at = cipher_image_name.find('@');
|
||||
|
||||
if (pos_y == std::string::npos || pos_at == std::string::npos ||
|
||||
pos_y >= pos_at) {
|
||||
LOG_ERROR("Invalid filename");
|
||||
continue;
|
||||
}
|
||||
|
||||
remote_id = cipher_image_name.substr(0, pos_y);
|
||||
remote_host_name =
|
||||
cipher_image_name.substr(pos_y + 1, pos_at - pos_y - 1);
|
||||
cipher_password = cipher_image_name.substr(pos_at + 1);
|
||||
password = AES_decrypt(cipher_password, aes128_key_, aes128_iv_);
|
||||
remember_password = true;
|
||||
|
||||
original_image_name = remote_id + 'Y' + remote_host_name + "@" +
|
||||
password;
|
||||
} else {
|
||||
size_t pos_n = cipher_image_name.find('N');
|
||||
// size_t pos_at = cipher_image_name.find('@');
|
||||
|
||||
if (pos_n == std::string::npos) {
|
||||
LOG_ERROR("Invalid filename");
|
||||
continue;
|
||||
}
|
||||
|
||||
remote_id = cipher_image_name.substr(0, pos_n);
|
||||
remote_host_name = cipher_image_name.substr(pos_n + 1);
|
||||
|
||||
original_image_name = remote_id + 'N' + remote_host_name;
|
||||
}
|
||||
|
||||
std::string image_path = save_path_ + cipher_image_name;
|
||||
Thumbnail::RecentConnection recent_connection;
|
||||
recent_connection.remote_id = remote_id;
|
||||
recent_connection.remote_host_name = remote_host_name;
|
||||
recent_connection.password = password;
|
||||
recent_connection.remember_password = remember_password;
|
||||
recent_connection.image_path = image_path;
|
||||
recent_connections.emplace_back(
|
||||
std::make_pair(original_image_name, recent_connection));
|
||||
}
|
||||
return 0;
|
||||
int Thumbnail::LoadThumbnailLocked(
|
||||
std::vector<std::pair<std::string, RecentConnection>>& recent_connections) {
|
||||
recent_connections.clear();
|
||||
int result = 0;
|
||||
std::map<std::string, RecentConnection> records;
|
||||
const auto paths = FindThumbnailPath(save_path_);
|
||||
for (const auto& path : paths) {
|
||||
if (path.extension() != ".json") continue;
|
||||
RecentConnection connection;
|
||||
if (ReadRecord(path, &connection))
|
||||
records.emplace(connection.remote_id, connection);
|
||||
}
|
||||
return 0;
|
||||
for (const auto& path : paths) {
|
||||
const auto filename = path.filename().string();
|
||||
if (filename.size() < 10 || !IsRemoteId(filename.substr(0, 9)) ||
|
||||
(filename[9] != 'Y' && filename[9] != 'N'))
|
||||
continue;
|
||||
const auto remote_id = filename.substr(0, 9);
|
||||
if (!records.count(remote_id)) {
|
||||
RecentConnection connection;
|
||||
connection.remote_id = remote_id;
|
||||
connection.remember_password = filename[9] == 'Y';
|
||||
const auto separator = filename.find('@', 10);
|
||||
if (connection.remember_password && separator == std::string::npos)
|
||||
continue;
|
||||
connection.remote_host_name =
|
||||
filename.substr(10, connection.remember_password ? separator - 10
|
||||
: std::string::npos);
|
||||
if (connection.remember_password) {
|
||||
connection.password = AES_decrypt(filename.substr(separator + 1),
|
||||
aes128_key_, aes128_iv_);
|
||||
}
|
||||
if (!WriteRecord(connection)) {
|
||||
result = -1;
|
||||
recent_connections.emplace_back(ConnectionKey(connection), connection);
|
||||
continue;
|
||||
}
|
||||
const auto metadata =
|
||||
std::filesystem::path(save_path_) / (remote_id + ".json");
|
||||
std::filesystem::last_write_time(metadata,
|
||||
std::filesystem::last_write_time(path));
|
||||
records.emplace(remote_id, connection);
|
||||
}
|
||||
auto& connection = records.at(remote_id);
|
||||
if (save_previews_ && connection.image_path.empty()) {
|
||||
const auto image =
|
||||
std::filesystem::path(save_path_) / (remote_id + ".png");
|
||||
std::error_code error;
|
||||
std::filesystem::copy_file(
|
||||
path, image, std::filesystem::copy_options::overwrite_existing,
|
||||
error);
|
||||
if (error) {
|
||||
// Keep the original preview available and retry migration next load.
|
||||
connection.image_path = path;
|
||||
result = -1;
|
||||
continue;
|
||||
}
|
||||
connection.image_path = image;
|
||||
}
|
||||
std::error_code error;
|
||||
std::filesystem::remove(path, error);
|
||||
if (error) result = -1;
|
||||
}
|
||||
// Sort by metadata timestamps, unaffected by preview deletion or migration.
|
||||
for (const auto& path : FindThumbnailPath(save_path_)) {
|
||||
if (path.extension() == ".json") {
|
||||
const auto it = records.find(path.stem().string());
|
||||
if (it != records.end()) {
|
||||
recent_connections.emplace_back(ConnectionKey(it->second), it->second);
|
||||
}
|
||||
} else if (!save_previews_ && path.extension() == ".png") {
|
||||
std::error_code error;
|
||||
std::filesystem::remove(path, error);
|
||||
if (error) result = -1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Thumbnail::DecodeImage(const std::filesystem::path& image_path,
|
||||
@@ -242,16 +349,17 @@ bool Thumbnail::DecodeImage(const std::filesystem::path& image_path,
|
||||
}
|
||||
|
||||
int Thumbnail::DeleteThumbnail(const std::string& filename_keyword) {
|
||||
std::lock_guard lock(mutex_);
|
||||
const auto remote_id = filename_keyword.substr(0, 9);
|
||||
if (!IsRemoteId(remote_id)) return -1;
|
||||
for (const auto& entry : std::filesystem::directory_iterator(save_path_)) {
|
||||
if (entry.is_regular_file()) {
|
||||
const std::string filename = entry.path().filename().string();
|
||||
std::string id_hostname = filename_keyword.substr(0, filename.find('@'));
|
||||
if (filename.find(id_hostname) != std::string::npos) {
|
||||
std::filesystem::remove(entry.path());
|
||||
}
|
||||
const auto name = entry.path().filename().string();
|
||||
if (entry.is_regular_file() && name.size() > 9 &&
|
||||
name.substr(0, 9) == remote_id &&
|
||||
(name[9] == '.' || name[9] == 'Y' || name[9] == 'N')) {
|
||||
std::filesystem::remove(entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -280,6 +388,7 @@ std::vector<std::filesystem::path> Thumbnail::FindThumbnailPath(
|
||||
}
|
||||
|
||||
int Thumbnail::DeleteAllFilesInDirectory() {
|
||||
std::lock_guard lock(mutex_);
|
||||
if (std::filesystem::exists(save_path_) &&
|
||||
std::filesystem::is_directory(save_path_)) {
|
||||
for (const auto& entry : std::filesystem::directory_iterator(save_path_)) {
|
||||
|
||||
@@ -10,9 +10,12 @@
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "remote_action.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class Thumbnail {
|
||||
@@ -23,6 +26,7 @@ class Thumbnail {
|
||||
std::string remote_host_name;
|
||||
std::string password;
|
||||
bool remember_password = false;
|
||||
HostPlatform platform = HostPlatform::Unknown;
|
||||
};
|
||||
|
||||
public:
|
||||
@@ -34,10 +38,14 @@ class Thumbnail {
|
||||
public:
|
||||
int SetThumbnailDpiScale(float dpi_scale);
|
||||
|
||||
int SaveToThumbnail(const char* yuv420p, int width, int height,
|
||||
// Serialized with writes so disabling also clears any in-flight preview.
|
||||
int SetSavePreviews(bool enabled);
|
||||
|
||||
int SaveToThumbnail(const char* nv12, int width, int height,
|
||||
const std::string& remote_id,
|
||||
const std::string& host_name,
|
||||
const std::string& password);
|
||||
const std::string& password,
|
||||
HostPlatform platform = HostPlatform::Unknown);
|
||||
|
||||
int LoadThumbnail(
|
||||
std::vector<std::pair<std::string, Thumbnail::RecentConnection>>&
|
||||
@@ -69,6 +77,11 @@ class Thumbnail {
|
||||
}
|
||||
|
||||
private:
|
||||
int LoadThumbnailLocked(
|
||||
std::vector<std::pair<std::string, RecentConnection>>& connections);
|
||||
bool WriteRecord(const RecentConnection& connection);
|
||||
bool ReadRecord(const std::filesystem::path& path, RecentConnection* connection);
|
||||
|
||||
std::vector<std::filesystem::path> FindThumbnailPath(
|
||||
const std::filesystem::path& directory);
|
||||
|
||||
@@ -79,6 +92,8 @@ class Thumbnail {
|
||||
unsigned char* iv);
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
bool save_previews_ = true;
|
||||
int thumbnail_width_ = 160;
|
||||
int thumbnail_height_ = 90;
|
||||
char* rgba_buffer_ = nullptr;
|
||||
|
||||
@@ -11,224 +11,15 @@
|
||||
|
||||
#include "rd_log.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
std::vector<int> SplitVersion(const std::string& ver);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr size_t kMaxInlinePatchDigits = 4;
|
||||
|
||||
struct ParsedVersion {
|
||||
std::vector<int> numbers;
|
||||
std::string date;
|
||||
bool has_patch = false;
|
||||
int patch = 0;
|
||||
};
|
||||
|
||||
bool IsDigit(char c) {
|
||||
return std::isdigit(static_cast<unsigned char>(c)) != 0;
|
||||
}
|
||||
|
||||
bool IsAlphaNumeric(char c) {
|
||||
return std::isalnum(static_cast<unsigned char>(c)) != 0;
|
||||
}
|
||||
|
||||
bool IsAllDigits(const std::string& value) {
|
||||
if (value.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (char c : value) {
|
||||
if (!IsDigit(c)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TryParseNonNegativeInt(const std::string& value, int* result) {
|
||||
if (!IsAllDigits(value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const long long parsed = std::stoll(value);
|
||||
if (parsed > std::numeric_limits<int>::max()) {
|
||||
return false;
|
||||
}
|
||||
*result = static_cast<int>(parsed);
|
||||
return true;
|
||||
} catch (...) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool TryParseInlinePatch(const std::string& value, int* result) {
|
||||
if (value.size() > kMaxInlinePatchDigits) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return TryParseNonNegativeInt(value, result);
|
||||
}
|
||||
|
||||
size_t FindNumericStart(const std::string& version) {
|
||||
size_t start = 0;
|
||||
while (start < version.size() && !IsDigit(version[start])) {
|
||||
start++;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
size_t FindNumericEnd(const std::string& version, size_t start) {
|
||||
size_t end = start;
|
||||
while (end < version.size() &&
|
||||
(IsDigit(version[end]) || version[end] == '.')) {
|
||||
end++;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
bool HasDigitBoundary(const std::string& value, size_t pos, size_t len) {
|
||||
const bool before_ok = pos == 0 || !IsDigit(value[pos - 1]);
|
||||
const size_t end = pos + len;
|
||||
const bool after_ok = end >= value.size() || !IsDigit(value[end]);
|
||||
return before_ok && after_ok;
|
||||
}
|
||||
|
||||
bool IsCompactDateAt(const std::string& value, size_t pos) {
|
||||
if (pos + 8 > value.size() || !HasDigitBoundary(value, pos, 8)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < 8; ++i) {
|
||||
if (!IsDigit(value[pos + i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string CompactDateToIso(const std::string& compact_date) {
|
||||
return compact_date.substr(0, 4) + "-" + compact_date.substr(4, 2) + "-" +
|
||||
compact_date.substr(6, 2);
|
||||
}
|
||||
|
||||
bool ExtractDateFromText(const std::string& value,
|
||||
std::string* date,
|
||||
size_t* date_end) {
|
||||
for (size_t i = 0; i < value.size(); ++i) {
|
||||
if (IsCompactDateAt(value, i)) {
|
||||
*date = CompactDateToIso(value.substr(i, 8));
|
||||
*date_end = i + 8;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
ParsedVersion ParseVersion(const std::string& version) {
|
||||
const size_t numeric_start = FindNumericStart(version);
|
||||
const size_t numeric_end = FindNumericEnd(version, numeric_start);
|
||||
|
||||
ParsedVersion parsed;
|
||||
parsed.numbers = SplitVersion(version.substr(numeric_start,
|
||||
numeric_end - numeric_start));
|
||||
|
||||
const std::string suffix = version.substr(numeric_end);
|
||||
size_t pos = 0;
|
||||
while (pos < suffix.size()) {
|
||||
while (pos < suffix.size() && !IsAlphaNumeric(suffix[pos])) {
|
||||
pos++;
|
||||
}
|
||||
|
||||
const size_t token_start = pos;
|
||||
while (pos < suffix.size() && IsAlphaNumeric(suffix[pos])) {
|
||||
pos++;
|
||||
}
|
||||
|
||||
if (token_start == pos) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const std::string token = suffix.substr(token_start, pos - token_start);
|
||||
if (parsed.date.empty() && IsCompactDateAt(token, 0)) {
|
||||
parsed.date = CompactDateToIso(token);
|
||||
continue;
|
||||
}
|
||||
|
||||
int patch = 0;
|
||||
if (!parsed.has_patch && TryParseInlinePatch(token, &patch)) {
|
||||
parsed.has_patch = true;
|
||||
parsed.patch = patch;
|
||||
}
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
int CompareNumericVersion(const std::vector<int>& current,
|
||||
const std::vector<int>& latest) {
|
||||
std::vector<int> current_parts = current;
|
||||
std::vector<int> latest_parts = latest;
|
||||
const size_t len = std::max(current_parts.size(), latest_parts.size());
|
||||
current_parts.resize(len, 0);
|
||||
latest_parts.resize(len, 0);
|
||||
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
if (latest_parts[i] > current_parts[i]) {
|
||||
return 1;
|
||||
}
|
||||
if (latest_parts[i] < current_parts[i]) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ReadPatchField(const nlohmann::json& json, int* patch) {
|
||||
if (!json.contains("patch")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& patch_value = json["patch"];
|
||||
if (patch_value.is_number_unsigned()) {
|
||||
const auto parsed = patch_value.get<unsigned long long>();
|
||||
if (parsed > static_cast<unsigned long long>(std::numeric_limits<int>::max())) {
|
||||
return false;
|
||||
}
|
||||
*patch = static_cast<int>(parsed);
|
||||
return true;
|
||||
}
|
||||
if (patch_value.is_number_integer()) {
|
||||
const long long parsed = patch_value.get<long long>();
|
||||
if (parsed < 0 || parsed > std::numeric_limits<int>::max()) {
|
||||
return false;
|
||||
}
|
||||
*patch = static_cast<int>(parsed);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (patch_value.is_string()) {
|
||||
return TryParseNonNegativeInt(patch_value.get<std::string>(), patch);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void LogHttpError(const httplib::Result& result) {
|
||||
LOG_WARN("Failed to fetch version.json: error={}, message={}",
|
||||
static_cast<int>(result.error()), httplib::to_string(result.error()));
|
||||
@@ -310,125 +101,6 @@ void ConfigureLinuxCaCerts(httplib::Client* cli) {
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string ExtractNumericPart(const std::string& ver) {
|
||||
const size_t start = FindNumericStart(ver);
|
||||
const size_t end = FindNumericEnd(ver, start);
|
||||
return ver.substr(start, end - start);
|
||||
}
|
||||
|
||||
std::vector<int> SplitVersion(const std::string& ver) {
|
||||
std::vector<int> nums;
|
||||
std::istringstream ss(ver);
|
||||
std::string token;
|
||||
while (std::getline(ss, token, '.')) {
|
||||
try {
|
||||
nums.push_back(std::stoi(token));
|
||||
} catch (...) {
|
||||
nums.push_back(0);
|
||||
}
|
||||
}
|
||||
return nums;
|
||||
}
|
||||
|
||||
// extract date from version string (format: v1.2.3-20251113-abc
|
||||
// or 1.2.3-20251113-abc)
|
||||
std::string ExtractDateFromVersion(const std::string& version) {
|
||||
const size_t numeric_start = FindNumericStart(version);
|
||||
const size_t numeric_end = FindNumericEnd(version, numeric_start);
|
||||
const std::string suffix = version.substr(numeric_end);
|
||||
std::string date;
|
||||
size_t date_end = 0;
|
||||
if (ExtractDateFromText(suffix, &date, &date_end)) {
|
||||
return date;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// compare two dates in YYYY-MM-DD format
|
||||
bool IsNewerDate(const std::string& date1, const std::string& date2) {
|
||||
if (date1.empty() || date2.empty()) return false;
|
||||
// simple string comparison works for ISO date format (YYYY-MM-DD)
|
||||
return date2 > date1;
|
||||
}
|
||||
|
||||
bool IsNewerVersion(const std::string& current, const std::string& latest) {
|
||||
return IsNewerVersionWithMetadata(current, latest, "", -1);
|
||||
}
|
||||
|
||||
bool IsNewerVersionWithMetadata(const std::string& current,
|
||||
const std::string& latest,
|
||||
const std::string& latest_date,
|
||||
int latest_patch) {
|
||||
(void)latest_date;
|
||||
|
||||
const ParsedVersion current_version = ParseVersion(current);
|
||||
const ParsedVersion latest_version = ParseVersion(latest);
|
||||
|
||||
const int numeric_compare =
|
||||
CompareNumericVersion(current_version.numbers, latest_version.numbers);
|
||||
if (numeric_compare > 0) {
|
||||
return true;
|
||||
}
|
||||
if (numeric_compare < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool metadata_has_patch = latest_patch >= 0;
|
||||
const bool latest_has_patch = metadata_has_patch || latest_version.has_patch;
|
||||
if (latest_has_patch || current_version.has_patch) {
|
||||
const int resolved_latest_patch =
|
||||
metadata_has_patch ? latest_patch
|
||||
: (latest_version.has_patch ? latest_version.patch
|
||||
: 0);
|
||||
const int resolved_current_patch =
|
||||
current_version.has_patch ? current_version.patch : 0;
|
||||
return resolved_latest_patch > resolved_current_patch;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
std::optional<VersionInfo> ParseVersionInfo(const nlohmann::json& json) {
|
||||
if (!json.is_object()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto read_string = [&](const char* key) -> std::string {
|
||||
const auto it = json.find(key);
|
||||
return it != json.end() && it->is_string() ? it->get<std::string>()
|
||||
: std::string{};
|
||||
};
|
||||
VersionInfo info;
|
||||
info.version = read_string("latest_version");
|
||||
if (info.version.empty()) {
|
||||
info.version = read_string("version");
|
||||
}
|
||||
if (!info.version.empty() &&
|
||||
(info.version.front() == 'v' || info.version.front() == 'V')) {
|
||||
info.version.erase(0, 1);
|
||||
}
|
||||
// Invalid/missing version data is a failed check, never "up to date".
|
||||
const auto numeric_end = FindNumericEnd(info.version, 0);
|
||||
if (numeric_end == 0 || info.version[numeric_end - 1] == '.' ||
|
||||
(numeric_end < info.version.size() &&
|
||||
(numeric_end + 1 == info.version.size() ||
|
||||
(info.version[numeric_end] != '-' && info.version[numeric_end] != '+')))) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::istringstream parts(info.version.substr(0, numeric_end));
|
||||
std::string part;
|
||||
int number = 0;
|
||||
while (std::getline(parts, part, '.')) {
|
||||
if (!TryParseNonNegativeInt(part, &number)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
info.release_name = read_string("releaseName");
|
||||
info.release_notes = read_string("releaseNotes");
|
||||
info.release_date = read_string("releaseDate");
|
||||
ReadPatchField(json, &info.patch);
|
||||
return info;
|
||||
}
|
||||
|
||||
std::optional<VersionInfo> CheckUpdate() {
|
||||
httplib::Client cli("https://version.crossdesk.cn");
|
||||
|
||||
|
||||
@@ -8,30 +8,13 @@
|
||||
#define _VERSION_CHECKER_H_
|
||||
|
||||
#include <nlohmann/json_fwd.hpp>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <app_version.h>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
struct VersionInfo {
|
||||
std::string version;
|
||||
std::string release_name;
|
||||
std::string release_notes;
|
||||
std::string release_date;
|
||||
int patch = -1;
|
||||
};
|
||||
|
||||
std::optional<VersionInfo> ParseVersionInfo(const nlohmann::json& json);
|
||||
std::optional<VersionInfo> CheckUpdate();
|
||||
|
||||
bool IsNewerVersion(const std::string& current, const std::string& latest);
|
||||
|
||||
// Pass latest_patch < 0 when patch metadata is unavailable.
|
||||
bool IsNewerVersionWithMetadata(const std::string& current,
|
||||
const std::string& latest,
|
||||
const std::string& latest_date,
|
||||
int latest_patch);
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "fa_solid_900.h"
|
||||
#include "ui/ui_localization.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
@@ -134,12 +135,13 @@ bool ConfigureDocumentationDemo(
|
||||
std::cerr << "Missing documentation thumbnail: " << path << '\n';
|
||||
return false;
|
||||
}
|
||||
crossdesk::ui::RecentConnection connection;
|
||||
crossdesk::ui::RecentConnection connection{};
|
||||
connection.remote_id = device.id;
|
||||
connection.display_name = device.name;
|
||||
connection.host_name = device.name;
|
||||
connection.online = true;
|
||||
connection.thumbnail = thumbnail;
|
||||
connection.has_thumbnail = true;
|
||||
connections.emplace_back(std::move(connection));
|
||||
}
|
||||
window->set_recent_connections(
|
||||
@@ -184,6 +186,7 @@ void ResetMainCaptureState(
|
||||
window->set_permission_dialog_open(false);
|
||||
window->set_screen_recording_granted(true);
|
||||
window->set_accessibility_granted(true);
|
||||
window->set_wayland_notice_open(false);
|
||||
window->set_settings_session_active(false);
|
||||
window->set_portable_service_settings_visible(false);
|
||||
window->set_portable_service_dialog_open(false);
|
||||
@@ -275,6 +278,8 @@ void ConfigureMainCapturePage(
|
||||
window->set_permission_dialog_open(true);
|
||||
window->set_screen_recording_granted(false);
|
||||
window->set_accessibility_granted(false);
|
||||
} else if (options.page == "wayland-notice") {
|
||||
window->set_wayland_notice_open(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,7 +386,8 @@ int RunCaptureMode(
|
||||
|
||||
slint::Window *capture_window = &window->window();
|
||||
const bool capture_stream =
|
||||
options.page == "stream" || options.page == "stream-video-settings";
|
||||
options.page == "stream" || options.page == "stream-video-settings" ||
|
||||
options.page == "stream-update" || options.page == "stream-update-legacy";
|
||||
if (capture_stream) {
|
||||
ConfigureStreamCapturePage(stream, options.language);
|
||||
if (!options.demo_assets_path.empty()) {
|
||||
@@ -408,6 +414,11 @@ int RunCaptureMode(
|
||||
stream->set_video_settings_enabled(true);
|
||||
stream->set_video_menu_open(true);
|
||||
}
|
||||
if (options.page == "stream-update" || options.page == "stream-update-legacy") {
|
||||
stream->set_remote_update_visible(true);
|
||||
stream->on_dismiss_remote_update(
|
||||
[stream] { stream->set_remote_update_visible(false); });
|
||||
}
|
||||
window->hide();
|
||||
stream->show();
|
||||
capture_window = &stream->window();
|
||||
@@ -535,7 +546,7 @@ int main() {
|
||||
assert(std::string(window->get_remote_id_input()).empty());
|
||||
|
||||
std::vector<crossdesk::ui::RecentConnection> connections;
|
||||
crossdesk::ui::RecentConnection connection;
|
||||
crossdesk::ui::RecentConnection connection{};
|
||||
connection.remote_id = "987654321";
|
||||
connection.display_name = "Office PC";
|
||||
connection.host_name = "office-pc";
|
||||
@@ -638,6 +649,92 @@ int main() {
|
||||
assert(keyboard_focus_changed);
|
||||
assert(keyboard_input_received);
|
||||
|
||||
stream->window().dispatch_key_release_event("a");
|
||||
|
||||
// The modal owns keyboard and pointer input. Complete a gesture that was
|
||||
// already sent to the peer before showing it, then block new gestures.
|
||||
int remote_key_events = 0;
|
||||
int remote_pointer_presses = 0;
|
||||
int remote_pointer_releases = 0;
|
||||
int notice_dismissals = 0;
|
||||
stream->on_key_input(
|
||||
[&](slint::SharedString, bool, bool, bool, bool, bool) {
|
||||
++remote_key_events;
|
||||
});
|
||||
stream->on_pointer_input(
|
||||
[&](slint::PointerEventButton, slint::PointerEventKind kind, float, float) {
|
||||
if (kind == slint::PointerEventKind::Down) ++remote_pointer_presses;
|
||||
if (kind == slint::PointerEventKind::Up) ++remote_pointer_releases;
|
||||
});
|
||||
stream->on_dismiss_remote_update([&] {
|
||||
++notice_dismissals;
|
||||
stream->set_remote_update_visible(false);
|
||||
});
|
||||
const auto outside_notice =
|
||||
slint::LogicalPosition(slint::Point<float>{640.0f, 500.0f});
|
||||
stream->window().dispatch_pointer_press_event(
|
||||
outside_notice, slint::PointerEventButton::Left);
|
||||
stream->set_remote_update_visible(true);
|
||||
stream->window().dispatch_pointer_release_event(
|
||||
outside_notice, slint::PointerEventButton::Left);
|
||||
if (remote_pointer_presses != 1 || remote_pointer_releases != 1) {
|
||||
std::cerr << "Showing the upgrade dialog must finish an active remote gesture\n";
|
||||
return 9;
|
||||
}
|
||||
const float notice_y =
|
||||
std::max(64.0f, stream->get_video_area_height() * 0.18f) + 24.0f;
|
||||
if (!stream->invoke_is_local_control_area(640.0f, notice_y) ||
|
||||
!stream->invoke_is_local_control_area(640.0f, 500.0f)) {
|
||||
std::cerr << "Remote upgrade dialog and backdrop must consume local input\n";
|
||||
return 9;
|
||||
}
|
||||
stream->window().dispatch_pointer_press_event(
|
||||
outside_notice, slint::PointerEventButton::Left);
|
||||
stream->window().dispatch_pointer_release_event(
|
||||
outside_notice, slint::PointerEventButton::Left);
|
||||
stream->window().dispatch_key_press_event("a");
|
||||
stream->window().dispatch_key_release_event("a");
|
||||
if (remote_pointer_presses != 1 || remote_pointer_releases != 1 ||
|
||||
remote_key_events != 0 || notice_dismissals != 0) {
|
||||
std::cerr << "Upgrade dialog input must stay local\n";
|
||||
return 9;
|
||||
}
|
||||
stream->window().dispatch_key_press_event("\x1b");
|
||||
stream->window().dispatch_key_release_event("\x1b");
|
||||
if (stream->get_remote_update_visible() || notice_dismissals != 1 ||
|
||||
remote_key_events != 0) {
|
||||
std::cerr << "Escape must dismiss the dialog without forwarding the key\n";
|
||||
return 9;
|
||||
}
|
||||
if (stream->invoke_is_local_control_area(640.0f, notice_y)) {
|
||||
std::cerr << "Dismissed upgrade notice must release its input area\n";
|
||||
return 9;
|
||||
}
|
||||
stream->window().dispatch_key_press_event("a");
|
||||
stream->window().dispatch_key_release_event("a");
|
||||
stream->window().dispatch_pointer_press_event(
|
||||
outside_notice, slint::PointerEventButton::Left);
|
||||
stream->window().dispatch_pointer_release_event(
|
||||
outside_notice, slint::PointerEventButton::Left);
|
||||
if (remote_key_events != 2 || remote_pointer_presses != 2 ||
|
||||
remote_pointer_releases != 2) {
|
||||
std::cerr << "Dismissing the upgrade dialog must restore remote input\n";
|
||||
return 9;
|
||||
}
|
||||
|
||||
stream->set_remote_update_visible(true);
|
||||
const auto notice_button = slint::LogicalPosition(slint::Point<float>{
|
||||
816.0f, stream->get_video_area_top() + notice_y - 24.0f + 158.0f});
|
||||
stream->window().dispatch_pointer_press_event(
|
||||
notice_button, slint::PointerEventButton::Left);
|
||||
stream->window().dispatch_pointer_release_event(
|
||||
notice_button, slint::PointerEventButton::Left);
|
||||
if (stream->get_remote_update_visible() || notice_dismissals != 2 ||
|
||||
remote_pointer_presses != 2 || remote_pointer_releases != 2) {
|
||||
std::cerr << "Upgrade confirmation click must not reach the peer\n";
|
||||
return 9;
|
||||
}
|
||||
|
||||
crossdesk::ui::FileTransferEntry transfer;
|
||||
transfer.name = "archive.zip";
|
||||
transfer.status = "Sending";
|
||||
|
||||
@@ -97,5 +97,37 @@ int main() {
|
||||
ok &= ExpectEqual("plain comparison has no hidden metadata from prior checks",
|
||||
crossdesk::IsNewerVersion("1.3.5", "1.3.5"), false);
|
||||
|
||||
const auto release = crossdesk::ParseVersionInfoJSON(
|
||||
R"({"latest_version":"v1.5.3-20260928","patch":2})");
|
||||
ok &= ExpectEqual("shared release JSON parser",
|
||||
release.has_value(), true);
|
||||
if (release) {
|
||||
for (const auto& version : {"1.5.3-2-20260927", "1.5.3-3-20260928", "1.6.0"}) {
|
||||
ok &= ExpectEqual(std::string("no remote update for ") + version,
|
||||
crossdesk::AvailableAppUpdate(version, *release).has_value(),
|
||||
false);
|
||||
}
|
||||
for (const auto& version : {"", " ", "unknown", "ios-native", "1..5", "1.5-"}) {
|
||||
ok &= ExpectEqual(std::string("unavailable peer version is legacy: ") + version,
|
||||
!crossdesk::IsValidAppVersion(version) &&
|
||||
crossdesk::AvailableAppUpdate(version, *release) == "1.5.3-2",
|
||||
true);
|
||||
}
|
||||
for (const auto& version : {"1.5.2", "v1.5.3-20260928", "1.5.3-1-20260929",
|
||||
"1.5.3-20260928-1"}) {
|
||||
ok &= ExpectEqual(std::string("remote update includes metadata patch for ") + version,
|
||||
crossdesk::AvailableAppUpdate(version, *release) == "1.5.3-2",
|
||||
true);
|
||||
}
|
||||
}
|
||||
ok &= ExpectEqual("legacy peer cannot supply a missing latest release label",
|
||||
crossdesk::AvailableAppUpdate("", crossdesk::VersionInfo{}).has_value(),
|
||||
false);
|
||||
for (const auto& response : {"", "not JSON", "{}", "[]",
|
||||
R"({"version":null})", R"({"version":"unknown"})"}) {
|
||||
ok &= ExpectEqual("invalid release response gives no update",
|
||||
crossdesk::ParseVersionInfoJSON(response).has_value(), false);
|
||||
}
|
||||
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,9 @@ function setup_options_and_dependencies()
|
||||
add_defines("USE_WAYLAND=" .. (is_config("USE_WAYLAND", true) and "1" or "0"))
|
||||
add_defines("USE_DRM=" .. (is_config("USE_DRM", true) and "1" or "0"))
|
||||
if is_mode("debug") then
|
||||
add_defines("CROSSDESK_DEBUG")
|
||||
add_defines("CROSSDESK_DEBUG", "SPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_DEBUG")
|
||||
else
|
||||
add_defines("SPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_INFO")
|
||||
end
|
||||
|
||||
add_requireconfs("**.python", {version = "3.12", override = true, configs = {pgo = false}})
|
||||
|
||||
@@ -42,8 +42,10 @@ rule("slint")
|
||||
local outputs = target:data("slint.outputs")[sourcefile]
|
||||
local depfile = outputs.header .. ".d"
|
||||
-- Slint writes the -o path literally into each generated #include.
|
||||
-- The custom UI uses fixed light backgrounds. Keep default text and
|
||||
-- standard widgets light as well, regardless of the system theme.
|
||||
local argv = {sourcefile, "-f", "cpp", "-o", path.absolute(outputs.header),
|
||||
"--depfile", depfile, "--style", "fluent",
|
||||
"--depfile", depfile, "--style", "fluent-light",
|
||||
"--embed-resources=embed-files", "--cpp-namespace", "crossdesk::ui"}
|
||||
local missing_output = not os.isfile(outputs.header)
|
||||
for _, cppfile in ipairs(outputs.sources) do
|
||||
|
||||
@@ -38,9 +38,23 @@ function setup_targets()
|
||||
local runtime_dir = path.join(slint:installdir(), "lib")
|
||||
local runtime_dll = path.join(runtime_dir, "slint_cpp.dll")
|
||||
assert(os.isfile(runtime_dll), "Slint runtime not found: " .. runtime_dll)
|
||||
import("utils.binary.deplibs")
|
||||
local dependencies = deplibs(runtime_dll, {plat = "windows", arch = target:arch()})
|
||||
assert(dependencies and #dependencies > 0, "Cannot inspect Slint runtime dependencies: " .. runtime_dll)
|
||||
for _, dependency in ipairs(dependencies) do
|
||||
local name = path.filename(dependency):lower()
|
||||
assert(not (name:match("^vcruntime%d.*%.dll$") or name:match("^msvcp%d.*%.dll$") or
|
||||
name:match("^msvcr%d.*%.dll$") or name:match("^concrt%d.*%.dll$")),
|
||||
"Slint runtime depends on " .. dependency .. "; rebuild the Slint package with static CRT")
|
||||
end
|
||||
os.cp(runtime_dll, target:targetdir())
|
||||
end
|
||||
|
||||
-- Keep runtime deployment independent of each target's after_build callback.
|
||||
rule("crossdesk.slint_runtime")
|
||||
after_build(copy_slint_runtime)
|
||||
rule_end()
|
||||
|
||||
-- Amyuni usbmmidd_v2 virtual display driver for headless Windows hosts.
|
||||
-- The installer and the portable archive pick it up from the target
|
||||
-- directory; the runtime looks for it next to the executables.
|
||||
@@ -135,6 +149,16 @@ function setup_targets()
|
||||
"apps/desktop/src/gui/runtime")
|
||||
add_files("apps/desktop/tests/cursor_position_test.cpp")
|
||||
|
||||
target("single_instance")
|
||||
set_kind("object")
|
||||
add_includedirs("apps/desktop/src", {public = true})
|
||||
if is_os("windows") then
|
||||
add_files("apps/desktop/src/platform/windows/single_instance.cpp")
|
||||
add_syslinks("Advapi32")
|
||||
else
|
||||
add_files("apps/desktop/src/platform/common/posix_single_instance.cpp")
|
||||
end
|
||||
|
||||
target("repository_structure_test")
|
||||
set_kind("binary")
|
||||
set_default(false)
|
||||
@@ -198,13 +222,13 @@ function setup_targets()
|
||||
add_includedirs("apps/desktop/src/gui", "apps/desktop/src/gui/assets/fonts",
|
||||
"apps/desktop/src/gui/assets/localization")
|
||||
add_files("apps/desktop/tests/slint_ui_smoke_test.cpp")
|
||||
after_build(copy_slint_runtime)
|
||||
add_rules("crossdesk.slint_runtime")
|
||||
|
||||
target("version_checker_test")
|
||||
set_kind("binary")
|
||||
set_default(false)
|
||||
add_packages("cpp-httplib", "nlohmann_json")
|
||||
add_deps("rd_log")
|
||||
add_deps("rd_log", "crossdesk_wire")
|
||||
add_includedirs("apps/desktop/src/version_checker")
|
||||
add_files("apps/desktop/tests/version_checker_test.cpp",
|
||||
"apps/desktop/src/version_checker/version_checker.cpp")
|
||||
@@ -362,7 +386,7 @@ function setup_targets()
|
||||
|
||||
target("thumbnail")
|
||||
set_kind("object")
|
||||
add_packages("libyuv", "openssl3")
|
||||
add_packages("libyuv", "openssl3", "nlohmann_json")
|
||||
add_deps("rd_log", "desktop_common")
|
||||
add_files("apps/desktop/src/thumbnail/*.cpp")
|
||||
add_includedirs("apps/desktop/src/thumbnail", {public = true})
|
||||
@@ -397,7 +421,7 @@ function setup_targets()
|
||||
set_kind("object")
|
||||
add_packages("cpp-httplib")
|
||||
add_packages("nlohmann_json", {public = true})
|
||||
add_deps("rd_log")
|
||||
add_deps("rd_log", "crossdesk_wire")
|
||||
add_files("apps/desktop/src/version_checker/*.cpp")
|
||||
add_includedirs("apps/desktop/src/version_checker", {public = true})
|
||||
if is_os("macosx") then
|
||||
@@ -540,7 +564,7 @@ function setup_targets()
|
||||
|
||||
target("crossdesk")
|
||||
set_kind("binary")
|
||||
add_deps("rd_log", "desktop_common", "gui")
|
||||
add_deps("rd_log", "desktop_common", "gui", "single_instance")
|
||||
add_files("apps/desktop/src/app/*.cpp")
|
||||
add_includedirs("apps/desktop/src", "apps/desktop/src/app", {public = true})
|
||||
if is_os("windows") then
|
||||
@@ -559,6 +583,6 @@ function setup_targets()
|
||||
"apps/desktop/src/platform/linux/daemon_backend.cpp",
|
||||
"apps/desktop/src/platform/linux/headless/headless_session.cpp")
|
||||
end
|
||||
after_build(copy_slint_runtime)
|
||||
add_rules("crossdesk.slint_runtime")
|
||||
after_build(copy_usbmmidd_package)
|
||||
end
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
100000000000000000000018 /* RecentConnection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000018 /* RecentConnection.swift */; };
|
||||
100000000000000000000016 /* RemoteVideoSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000016 /* RemoteVideoSettings.swift */; };
|
||||
100000000000000000000017 /* RemoteNetworkStatistics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000017 /* RemoteNetworkStatistics.swift */; };
|
||||
100000000000000000000001 /* CrossDeskMobileApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000001 /* CrossDeskMobileApp.swift */; };
|
||||
100000000000000000000002 /* RemoteSessionModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000002 /* RemoteSessionModel.swift */; };
|
||||
100000000000000000000003 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000003 /* ContentView.swift */; };
|
||||
@@ -15,9 +18,24 @@
|
||||
100000000000000000000006 /* NativeMetalVideoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000009 /* NativeMetalVideoView.swift */; };
|
||||
100000000000000000000007 /* RemoteTouchInputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20000000000000000000000A /* RemoteTouchInputView.swift */; };
|
||||
100000000000000000000008 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 20000000000000000000000D /* Assets.xcassets */; };
|
||||
100000000000000000000009 /* ThirdPartyLicensesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20000000000000000000000E /* ThirdPartyLicensesView.swift */; };
|
||||
10000000000000000000000A /* ThirdPartyLicenses.json in Resources */ = {isa = PBXBuildFile; fileRef = 20000000000000000000000F /* ThirdPartyLicenses.json */; };
|
||||
10000000000000000000000B /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000010 /* PrivacyInfo.xcprivacy */; };
|
||||
10000000000000000000000C /* OpenSSL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 200000000000000000000011 /* OpenSSL.framework */; };
|
||||
10000000000000000000000D /* OpenSSL.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 200000000000000000000011 /* OpenSSL.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
100000000000000000000012 /* PrivacyPreferences.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000012 /* PrivacyPreferences.swift */; };
|
||||
100000000000000000000013 /* ThumbnailFileStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000013 /* ThumbnailFileStore.swift */; };
|
||||
100000000000000000000014 /* PrivacyViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000014 /* PrivacyViews.swift */; };
|
||||
100000000000000000000015 /* PRIVACY.md in Resources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000015 /* PRIVACY.md */; };
|
||||
100000000000000000000019 /* AnnouncementInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 200000000000000000000019 /* AnnouncementInbox.swift */; };
|
||||
10000000000000000000001A /* AnnouncementText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20000000000000000000001A /* AnnouncementText.swift */; };
|
||||
10000000000000000000001B /* AnnouncementInboxView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20000000000000000000001B /* AnnouncementInboxView.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
200000000000000000000018 /* RecentConnection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecentConnection.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000016 /* RemoteVideoSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteVideoSettings.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000017 /* RemoteNetworkStatistics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteNetworkStatistics.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000001 /* CrossDeskMobileApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CrossDeskMobileApp.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000002 /* RemoteSessionModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteSessionModel.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000003 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
|
||||
@@ -31,13 +49,37 @@
|
||||
20000000000000000000000B /* CrossDeskMobile.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CrossDeskMobile.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
20000000000000000000000C /* build_minirtc_ios.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = build_minirtc_ios.sh; sourceTree = "<group>"; };
|
||||
20000000000000000000000D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
20000000000000000000000E /* ThirdPartyLicensesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThirdPartyLicensesView.swift; sourceTree = "<group>"; };
|
||||
20000000000000000000000F /* ThirdPartyLicenses.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = Resources/ThirdPartyLicenses.json; sourceTree = "<group>"; };
|
||||
200000000000000000000010 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
200000000000000000000011 /* OpenSSL.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = OpenSSL.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
200000000000000000000012 /* PrivacyPreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivacyPreferences.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000013 /* ThumbnailFileStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThumbnailFileStore.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000014 /* PrivacyViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivacyViews.swift; sourceTree = "<group>"; };
|
||||
200000000000000000000015 /* PRIVACY.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = ../../../PRIVACY.md; sourceTree = "<group>"; };
|
||||
200000000000000000000019 /* AnnouncementInbox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnnouncementInbox.swift; sourceTree = "<group>"; };
|
||||
20000000000000000000001A /* AnnouncementText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnnouncementText.swift; sourceTree = "<group>"; };
|
||||
20000000000000000000001B /* AnnouncementInboxView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AnnouncementInboxView.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
300000000000000000000002 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (10000000000000000000000D /* OpenSSL.framework in Embed Frameworks */, );
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
300000000000000000000001 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
10000000000000000000000C /* OpenSSL.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -57,8 +99,21 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
200000000000000000000001 /* CrossDeskMobileApp.swift */,
|
||||
200000000000000000000015 /* PRIVACY.md */,
|
||||
200000000000000000000014 /* PrivacyViews.swift */,
|
||||
200000000000000000000013 /* ThumbnailFileStore.swift */,
|
||||
200000000000000000000012 /* PrivacyPreferences.swift */,
|
||||
200000000000000000000002 /* RemoteSessionModel.swift */,
|
||||
200000000000000000000019 /* AnnouncementInbox.swift */,
|
||||
20000000000000000000001A /* AnnouncementText.swift */,
|
||||
20000000000000000000001B /* AnnouncementInboxView.swift */,
|
||||
200000000000000000000018 /* RecentConnection.swift */,
|
||||
200000000000000000000016 /* RemoteVideoSettings.swift */,
|
||||
200000000000000000000017 /* RemoteNetworkStatistics.swift */,
|
||||
200000000000000000000003 /* ContentView.swift */,
|
||||
20000000000000000000000E /* ThirdPartyLicensesView.swift */,
|
||||
20000000000000000000000F /* ThirdPartyLicenses.json */,
|
||||
200000000000000000000010 /* PrivacyInfo.xcprivacy */,
|
||||
200000000000000000000004 /* RemoteSessionView.swift */,
|
||||
400000000000000000000003 /* Bridge */,
|
||||
400000000000000000000004 /* Rendering */,
|
||||
@@ -107,6 +162,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
20000000000000000000000B /* CrossDeskMobile.app */,
|
||||
200000000000000000000011 /* OpenSSL.framework */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -122,6 +178,7 @@
|
||||
600000000000000000000001 /* Sources */,
|
||||
300000000000000000000001 /* Frameworks */,
|
||||
600000000000000000000002 /* Resources */,
|
||||
300000000000000000000002 /* Embed Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -172,6 +229,9 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
100000000000000000000008 /* Assets.xcassets in Resources */,
|
||||
10000000000000000000000A /* ThirdPartyLicenses.json in Resources */,
|
||||
10000000000000000000000B /* PrivacyInfo.xcprivacy in Resources */,
|
||||
100000000000000000000015 /* PRIVACY.md in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -193,10 +253,16 @@
|
||||
);
|
||||
outputPaths = (
|
||||
"$(PROJECT_DIR)/Vendor/iphoneos/$(CONFIGURATION)/libCrossDeskMiniRTC.a",
|
||||
"$(BUILT_PRODUCTS_DIR)/OpenSSL.framework/OpenSSL",
|
||||
"$(BUILT_PRODUCTS_DIR)/OpenSSL.framework/Info.plist",
|
||||
"$(BUILT_PRODUCTS_DIR)/OpenSSL.framework/PrivacyInfo.xcprivacy",
|
||||
"$(BUILT_PRODUCTS_DIR)/OpenSSL.framework/LICENSE.txt",
|
||||
"$(BUILT_PRODUCTS_DIR)/OpenSSL.framework/BuildMetadata.json",
|
||||
"$(TARGET_BUILD_DIR)/$(UNLOCALIZED_RESOURCES_FOLDER_PATH)/SourceMetadata.json",
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/zsh;
|
||||
shellScript = "\"${PROJECT_DIR}/scripts/build_minirtc_ios.sh\"\n";
|
||||
shellScript = "set -e\npython3 \"${PROJECT_DIR}/scripts/generate_third_party_licenses.py\"\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/generate_third_party_licenses.py\" --inputs \"${PROJECT_DIR}/Vendor/iphoneos/${CONFIGURATION}/libCrossDeskMiniRTC.a.inputs.sha256\" --target-info \"${PROJECT_DIR}/Vendor/iphoneos/${CONFIGURATION}/minirtc-target-info.txt\" --xmake-version \"${PROJECT_DIR}/Vendor/iphoneos/${CONFIGURATION}/xmake-version.txt\" --xmake-repository \"$(cat \"${PROJECT_DIR}/Vendor/iphoneos/${CONFIGURATION}/xmake-repository.txt\")\"\npython3 \"${PROJECT_DIR}/scripts/package_openssl_ios.py\" --inputs \"${PROJECT_DIR}/Vendor/iphoneos/${CONFIGURATION}/libCrossDeskMiniRTC.a.inputs.sha256\" --output \"${BUILT_PRODUCTS_DIR}/OpenSSL.framework\"\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
@@ -207,11 +273,21 @@
|
||||
files = (
|
||||
100000000000000000000001 /* CrossDeskMobileApp.swift in Sources */,
|
||||
100000000000000000000002 /* RemoteSessionModel.swift in Sources */,
|
||||
100000000000000000000019 /* AnnouncementInbox.swift in Sources */,
|
||||
10000000000000000000001A /* AnnouncementText.swift in Sources */,
|
||||
10000000000000000000001B /* AnnouncementInboxView.swift in Sources */,
|
||||
100000000000000000000018 /* RecentConnection.swift in Sources */,
|
||||
100000000000000000000016 /* RemoteVideoSettings.swift in Sources */,
|
||||
100000000000000000000017 /* RemoteNetworkStatistics.swift in Sources */,
|
||||
100000000000000000000003 /* ContentView.swift in Sources */,
|
||||
100000000000000000000009 /* ThirdPartyLicensesView.swift in Sources */,
|
||||
100000000000000000000004 /* RemoteSessionView.swift in Sources */,
|
||||
100000000000000000000005 /* CrossDeskRTCBridge.mm in Sources */,
|
||||
100000000000000000000006 /* NativeMetalVideoView.swift in Sources */,
|
||||
100000000000000000000007 /* RemoteTouchInputView.swift in Sources */,
|
||||
100000000000000000000012 /* PrivacyPreferences.swift in Sources */,
|
||||
100000000000000000000013 /* ThumbnailFileStore.swift in Sources */,
|
||||
100000000000000000000014 /* PrivacyViews.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -270,6 +346,7 @@
|
||||
ENABLE_BITCODE = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
FRAMEWORK_SEARCH_PATHS = ("$(inherited)", "$(BUILT_PRODUCTS_DIR)", );
|
||||
HEADER_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(PROJECT_DIR)/../../deps/submodules/minirtc/src/api",
|
||||
@@ -319,6 +396,7 @@
|
||||
ENABLE_BITCODE = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
GENERATE_INFOPLIST_FILE = NO;
|
||||
FRAMEWORK_SEARCH_PATHS = ("$(inherited)", "$(BUILT_PRODUCTS_DIR)", );
|
||||
HEADER_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(PROJECT_DIR)/../../deps/submodules/minirtc/src/api",
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import Combine
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
struct Announcement: Decodable, Identifiable, Equatable {
|
||||
let id: Int64
|
||||
let revision: Int64
|
||||
let title: String
|
||||
let body: String
|
||||
let updated_at: Int64
|
||||
var read = false
|
||||
|
||||
// Reading state belongs to this device, never to the server response.
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case id, revision, title, body, updated_at
|
||||
}
|
||||
|
||||
var date: Date { Date(timeIntervalSince1970: TimeInterval(updated_at)) }
|
||||
}
|
||||
|
||||
struct AnnouncementSnapshot: Equatable {
|
||||
var items: [Announcement] = []
|
||||
var total = 0
|
||||
var unread = 0
|
||||
var loaded = false
|
||||
var loading = false
|
||||
var failed = false
|
||||
var readSaveFailed = false
|
||||
var deleteFailed = false
|
||||
}
|
||||
|
||||
/// Main-thread inbox using the desktop announcements_list protocol and local
|
||||
/// revision semantics. Summary pages count all unread items; bodies load in 20s.
|
||||
final class AnnouncementInbox: ObservableObject {
|
||||
@Published private(set) var state = AnnouncementSnapshot()
|
||||
var send: ((Data, String) -> Void)?
|
||||
|
||||
private struct Entry: Decodable {
|
||||
let id: Int64
|
||||
let revision: Int64
|
||||
}
|
||||
|
||||
private struct Response: Decodable {
|
||||
let request_id: String
|
||||
let summary_only: Bool
|
||||
let offset: Int
|
||||
let total: Int
|
||||
let catalog_revision: Int64
|
||||
let items: [Entry]
|
||||
}
|
||||
|
||||
private struct BodyResponse: Decodable { let items: [Announcement] }
|
||||
private struct Request: Encodable {
|
||||
let type = "announcements_list"
|
||||
let request_id: String
|
||||
let summary_only: Bool
|
||||
let offset: Int
|
||||
}
|
||||
|
||||
private struct LocalState: Codable {
|
||||
let version: Int
|
||||
let scope: String
|
||||
let reads: [String: Int64]
|
||||
let dismissed: [String: Int64]?
|
||||
}
|
||||
|
||||
private let directory: URL
|
||||
private var scope = ""
|
||||
private var file: URL?
|
||||
private var reads: [Int64: Int64] = [:]
|
||||
private var dismissed: [Int64: Int64] = [:]
|
||||
private var catalog: [Int64: Int64] = [:]
|
||||
private var pendingCatalog: [Int64: Int64] = [:]
|
||||
private var pageIDs: [Int: [Int64]] = [:]
|
||||
private var pageBodies: [Int: [Announcement]] = [:]
|
||||
private var catalogRevision: Int64 = -1
|
||||
private var pendingRevision: Int64 = -1
|
||||
private var pendingTotal = 0
|
||||
private var pageOffset = 0
|
||||
private var visibleLimit = 20
|
||||
private var summary = true
|
||||
private var connected = false
|
||||
private var requestID: String?
|
||||
private var timeout: Timer?
|
||||
|
||||
init(directory: URL = FileManager.default.urls(
|
||||
for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("AnnouncementReads", isDirectory: true)) {
|
||||
self.directory = directory
|
||||
}
|
||||
|
||||
deinit { timeout?.invalidate() }
|
||||
|
||||
func configure(host: String, port: Int, deviceID: String) {
|
||||
guard !host.isEmpty, port > 0, !deviceID.isEmpty else { return }
|
||||
var host = host.lowercased()
|
||||
if host.hasSuffix(".") { host.removeLast() }
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: [host, port, deviceID],
|
||||
options: [.fragmentsAllowed]),
|
||||
let nextScope = String(data: data, encoding: .utf8),
|
||||
scope != nextScope else { return }
|
||||
let wasConnected = connected
|
||||
reset()
|
||||
connected = wasConnected
|
||||
scope = nextScope
|
||||
let name = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
|
||||
file = directory.appendingPathComponent(name + ".json")
|
||||
loadLocalState()
|
||||
refresh()
|
||||
}
|
||||
|
||||
func reset() {
|
||||
cancelRequest()
|
||||
state = AnnouncementSnapshot()
|
||||
scope = ""
|
||||
file = nil
|
||||
reads = [:]
|
||||
dismissed = [:]
|
||||
catalog = [:]
|
||||
pendingCatalog = [:]
|
||||
pageIDs = [:]
|
||||
pageBodies = [:]
|
||||
catalogRevision = -1
|
||||
pendingRevision = -1
|
||||
pendingTotal = 0
|
||||
visibleLimit = 20
|
||||
connected = false
|
||||
}
|
||||
|
||||
func setConnected(_ value: Bool) {
|
||||
connected = value
|
||||
refresh()
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
cancelRequest()
|
||||
pendingCatalog = [:]
|
||||
pendingRevision = -1
|
||||
pendingTotal = 0
|
||||
summary = true
|
||||
request(offset: 0)
|
||||
}
|
||||
|
||||
func loadMore() {
|
||||
guard connected, !state.loading, !state.failed, catalogRevision >= 0,
|
||||
visibleLimit < state.total else { return }
|
||||
visibleLimit += min(20, state.total - visibleLimit)
|
||||
rebuildVisibleItems()
|
||||
}
|
||||
|
||||
func markRead(_ item: Announcement) {
|
||||
guard state.items.contains(where: { $0.id == item.id && $0.revision == item.revision }),
|
||||
reads[item.id] != item.revision else { return }
|
||||
var updated = reads
|
||||
updated[item.id] = item.revision
|
||||
guard saveLocalState(reads: updated, dismissed: dismissed) else {
|
||||
state.readSaveFailed = true
|
||||
return
|
||||
}
|
||||
reads = updated
|
||||
state.readSaveFailed = false
|
||||
state.deleteFailed = false
|
||||
updateReadingState()
|
||||
}
|
||||
|
||||
func dismiss(_ item: Announcement) {
|
||||
// A confirmation can outlive the displayed revision.
|
||||
guard state.items.contains(where: { $0.id == item.id && $0.revision == item.revision }) else {
|
||||
state.deleteFailed = true
|
||||
return
|
||||
}
|
||||
var updated = dismissed
|
||||
updated[item.id] = item.revision
|
||||
guard saveLocalState(reads: reads, dismissed: updated) else {
|
||||
state.deleteFailed = true
|
||||
return
|
||||
}
|
||||
dismissed = updated
|
||||
state.deleteFailed = false
|
||||
state.readSaveFailed = false
|
||||
if summary && state.loading {
|
||||
state.items.removeAll { dismissed[$0.id] == $0.revision }
|
||||
updateReadingState()
|
||||
} else {
|
||||
cancelRequest()
|
||||
rebuildVisibleItems()
|
||||
}
|
||||
}
|
||||
|
||||
func failed(requestID: String) {
|
||||
guard self.requestID == requestID else { return }
|
||||
cancelRequest()
|
||||
state.failed = true
|
||||
}
|
||||
|
||||
func receive(_ data: Data) {
|
||||
guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
let id = object["request_id"] as? String, id == requestID else { return }
|
||||
let decoder = JSONDecoder()
|
||||
guard object["error"] == nil, let response = try? decoder.decode(Response.self, from: data) else {
|
||||
failed(requestID: id)
|
||||
return
|
||||
}
|
||||
let limit = summary ? 200 : 20
|
||||
guard response.summary_only == summary, response.offset >= 0,
|
||||
response.total >= response.offset, response.total <= Int32.max,
|
||||
response.catalog_revision >= 0,
|
||||
response.items.count == min(limit, response.total - response.offset),
|
||||
response.items.allSatisfy({ $0.id > 0 && $0.revision > 0 }) else {
|
||||
failed(requestID: id)
|
||||
return
|
||||
}
|
||||
let expectedRevision = summary ? pendingRevision : catalogRevision
|
||||
if expectedRevision >= 0 && expectedRevision != response.catalog_revision {
|
||||
refresh()
|
||||
return
|
||||
}
|
||||
if summary {
|
||||
guard response.offset == pendingCatalog.count,
|
||||
pendingRevision < 0 || pendingTotal == response.total else {
|
||||
failed(requestID: id)
|
||||
return
|
||||
}
|
||||
for item in response.items {
|
||||
guard pendingCatalog.updateValue(item.revision, forKey: item.id) == nil else {
|
||||
failed(requestID: id)
|
||||
return
|
||||
}
|
||||
}
|
||||
pendingRevision = response.catalog_revision
|
||||
pendingTotal = response.total
|
||||
cancelRequest()
|
||||
if pendingCatalog.count < pendingTotal {
|
||||
request(offset: pendingCatalog.count)
|
||||
return
|
||||
}
|
||||
if catalogRevision != pendingRevision {
|
||||
pageIDs = [:]
|
||||
pageBodies = [:]
|
||||
}
|
||||
catalog = pendingCatalog
|
||||
catalogRevision = pendingRevision
|
||||
reads = reads.filter { catalog[$0.key] != nil }
|
||||
dismissed = dismissed.filter { catalog[$0.key] != nil }
|
||||
} else {
|
||||
guard response.offset == pageOffset, response.total == catalog.count,
|
||||
Set(response.items.map(\.id)).count == response.items.count,
|
||||
let bodies = try? decoder.decode(BodyResponse.self, from: data).items,
|
||||
bodies.allSatisfy({ item in
|
||||
catalog[item.id] == item.revision &&
|
||||
(1...32_503_680_000).contains(item.updated_at) &&
|
||||
item.title.utf8.count <= 240 && item.body.utf8.count <= 8000
|
||||
}) else {
|
||||
failed(requestID: id)
|
||||
return
|
||||
}
|
||||
cancelRequest()
|
||||
pageIDs[response.offset] = bodies.map(\.id)
|
||||
pageBodies[response.offset] = bodies
|
||||
}
|
||||
state.failed = false
|
||||
rebuildVisibleItems()
|
||||
}
|
||||
|
||||
private func cancelRequest() {
|
||||
timeout?.invalidate()
|
||||
timeout = nil
|
||||
requestID = nil
|
||||
state.loading = false
|
||||
}
|
||||
|
||||
private func request(offset: Int) {
|
||||
guard connected, !scope.isEmpty else { return }
|
||||
let id = UUID().uuidString
|
||||
guard let data = try? JSONEncoder().encode(Request(
|
||||
request_id: id, summary_only: summary, offset: offset)) else { return }
|
||||
requestID = id
|
||||
state.loading = true
|
||||
state.failed = false
|
||||
let timer = Timer(timeInterval: 12, repeats: false) { [weak self] _ in
|
||||
self?.failed(requestID: id)
|
||||
}
|
||||
timeout = timer
|
||||
RunLoop.main.add(timer, forMode: .common)
|
||||
send?(data, id)
|
||||
}
|
||||
|
||||
private func updateReadingState() {
|
||||
let visible = catalog.filter { dismissed[$0.key] != $0.value }
|
||||
state.total = visible.count
|
||||
state.unread = visible.filter { reads[$0.key] != $0.value }.count
|
||||
state.items = state.items.map { item in
|
||||
var item = item
|
||||
item.read = reads[item.id] == item.revision
|
||||
return item
|
||||
}
|
||||
}
|
||||
|
||||
private func rebuildVisibleItems() {
|
||||
updateReadingState()
|
||||
let wanted = min(visibleLimit, state.total)
|
||||
var visible: [Announcement] = []
|
||||
var retainedPages: Set<Int> = []
|
||||
var position = 0
|
||||
var nextOffset: Int?
|
||||
summary = false
|
||||
if wanted > 0 {
|
||||
for offset in stride(from: 0, to: catalog.count, by: 20) {
|
||||
guard let ids = pageIDs[offset] else { nextOffset = offset; break }
|
||||
var selection: Set<Int64> = []
|
||||
for id in ids {
|
||||
guard let revision = catalog[id], dismissed[id] != revision else { continue }
|
||||
if position < wanted { selection.insert(id) }
|
||||
position += 1
|
||||
}
|
||||
if selection.isEmpty { pageBodies[offset] = nil; continue }
|
||||
retainedPages.insert(offset)
|
||||
guard let bodies = pageBodies[offset] else { nextOffset = offset; break }
|
||||
visible += bodies.filter { selection.contains($0.id) }
|
||||
if visible.count == wanted { break }
|
||||
}
|
||||
}
|
||||
if visible.count == wanted {
|
||||
pageBodies = pageBodies.filter { retainedPages.contains($0.key) }
|
||||
} else {
|
||||
// Retain unchanged bodies while fetching a refreshed catalog.
|
||||
var retained = Set(visible.map(\.id))
|
||||
for item in state.items where catalog[item.id] == item.revision &&
|
||||
dismissed[item.id] != item.revision && retained.insert(item.id).inserted {
|
||||
visible.append(item)
|
||||
if visible.count == wanted { break }
|
||||
}
|
||||
}
|
||||
state.items = visible
|
||||
state.loaded = true
|
||||
updateReadingState()
|
||||
if let nextOffset {
|
||||
pageOffset = nextOffset
|
||||
request(offset: nextOffset)
|
||||
}
|
||||
}
|
||||
|
||||
private func loadLocalState() {
|
||||
guard let file,
|
||||
let size = try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize,
|
||||
size <= 16 * 1024 * 1024,
|
||||
let data = try? Data(contentsOf: file),
|
||||
let saved = try? JSONDecoder().decode(LocalState.self, from: data),
|
||||
saved.scope == scope, [1, 2].contains(saved.version) else { return }
|
||||
func revisions(_ entries: [String: Int64]) -> [Int64: Int64] {
|
||||
var result: [Int64: Int64] = [:]
|
||||
for (key, revision) in entries {
|
||||
if let id = Int64(key), id > 0, revision > 0 { result[id] = revision }
|
||||
}
|
||||
return result
|
||||
}
|
||||
reads = revisions(saved.reads)
|
||||
dismissed = revisions(saved.dismissed ?? [:])
|
||||
}
|
||||
|
||||
private func saveLocalState(reads: [Int64: Int64], dismissed: [Int64: Int64]) -> Bool {
|
||||
guard let file else { return false }
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
var directory = directory
|
||||
var values = URLResourceValues()
|
||||
values.isExcludedFromBackup = true
|
||||
try directory.setResourceValues(values)
|
||||
let saved = LocalState(version: 2, scope: scope,
|
||||
reads: Dictionary(uniqueKeysWithValues: reads.map { (String($0.key), $0.value) }),
|
||||
dismissed: Dictionary(uniqueKeysWithValues: dismissed.map { (String($0.key), $0.value) }))
|
||||
try JSONEncoder().encode(saved).write(to: file, options: .atomic)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import SwiftUI
|
||||
|
||||
struct AnnouncementBadge: View {
|
||||
@ObservedObject var inbox: AnnouncementInbox
|
||||
|
||||
var body: some View {
|
||||
Image(systemName: "bell")
|
||||
.font(.system(size: 18, weight: .semibold))
|
||||
.frame(width: 40, height: 40)
|
||||
.background(Color(.secondarySystemGroupedBackground),
|
||||
in: RoundedRectangle(cornerRadius: 10, style: .continuous))
|
||||
.overlay(alignment: .topTrailing) {
|
||||
if inbox.state.unread > 0 {
|
||||
Text(inbox.state.unread > 99 ? "99+" : "\(inbox.state.unread)")
|
||||
.font(.system(size: 10, weight: .bold))
|
||||
.foregroundStyle(.white)
|
||||
.padding(.horizontal, 4)
|
||||
.frame(minWidth: 16, minHeight: 16)
|
||||
.background(.red, in: Capsule())
|
||||
.offset(x: 5, y: -3)
|
||||
}
|
||||
}
|
||||
.accessibilityElement(children: .ignore)
|
||||
.accessibilityLabel("通知公告")
|
||||
.accessibilityValue(inbox.state.unread > 0 ? "\(inbox.state.unread) 条未读" : "无未读公告")
|
||||
}
|
||||
}
|
||||
|
||||
struct AnnouncementSelection: Hashable {
|
||||
let id: Int64
|
||||
let revision: Int64
|
||||
}
|
||||
|
||||
private enum AnnouncementDate {
|
||||
static let formatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm"
|
||||
return formatter
|
||||
}()
|
||||
|
||||
static func string(_ item: Announcement) -> String { formatter.string(from: item.date) }
|
||||
}
|
||||
|
||||
struct AnnouncementInboxView: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@ObservedObject var inbox: AnnouncementInbox
|
||||
@State private var pendingDelete: Announcement?
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
if inbox.state.deleteFailed {
|
||||
Text("无法删除这条公告,请重试。")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
if inbox.state.failed && session.announcementsConnected {
|
||||
HStack {
|
||||
Text("公告加载失败,请重试。")
|
||||
Spacer()
|
||||
Button("重试") { session.refreshAnnouncements() }
|
||||
.disabled(!session.announcementsConnected)
|
||||
}
|
||||
}
|
||||
Section {
|
||||
ForEach(inbox.state.items) { item in
|
||||
NavigationLink(value: HomeDestination.announcement(
|
||||
AnnouncementSelection(id: item.id, revision: item.revision))) {
|
||||
HStack(alignment: .top, spacing: 10) {
|
||||
Circle()
|
||||
.fill(item.read ? Color.clear : Color.accentColor)
|
||||
.frame(width: 7, height: 7)
|
||||
.padding(.top, 7)
|
||||
.accessibilityHidden(true)
|
||||
VStack(alignment: .leading, spacing: 7) {
|
||||
Text(verbatim: item.title)
|
||||
.fontWeight(item.read ? .regular : .semibold)
|
||||
.foregroundStyle(.primary)
|
||||
.lineLimit(2)
|
||||
Text(AnnouncementDate.string(item))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 5)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityValue(item.read ? "已读" : "未读")
|
||||
}
|
||||
.swipeActions {
|
||||
Button("删除", role: .destructive) { pendingDelete = item }
|
||||
}
|
||||
.contextMenu {
|
||||
Button("删除公告", role: .destructive) { pendingDelete = item }
|
||||
}
|
||||
}
|
||||
if inbox.state.loading {
|
||||
HStack { Spacer(); ProgressView("加载中…"); Spacer() }
|
||||
} else if inbox.state.items.count < inbox.state.total && !inbox.state.failed {
|
||||
Button("加载更多") { inbox.loadMore() }
|
||||
.frame(maxWidth: .infinity)
|
||||
.disabled(!session.announcementsConnected)
|
||||
.onAppear { inbox.loadMore() }
|
||||
} else if inbox.state.loaded && inbox.state.total == 0 &&
|
||||
!inbox.state.failed && session.announcementsConnected {
|
||||
Text("暂无公告")
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, minHeight: 120)
|
||||
}
|
||||
} header: {
|
||||
Text("共 \(inbox.state.total) 条 · \(inbox.state.unread) 条未读")
|
||||
}
|
||||
}
|
||||
.navigationTitle("通知公告")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .navigationBarTrailing) {
|
||||
Button { session.refreshAnnouncements() } label: {
|
||||
Image(systemName: "arrow.clockwise")
|
||||
}
|
||||
.accessibilityLabel("刷新公告")
|
||||
.disabled(inbox.state.loading || !session.announcementsConnected)
|
||||
}
|
||||
}
|
||||
.refreshable {
|
||||
session.refreshAnnouncements()
|
||||
while inbox.state.loading && !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
}
|
||||
}
|
||||
.onAppear { session.refreshAnnouncements() }
|
||||
.alert("删除公告", isPresented: Binding(
|
||||
get: { pendingDelete != nil },
|
||||
set: { if !$0 { pendingDelete = nil } }
|
||||
)) {
|
||||
Button("取消", role: .cancel) { pendingDelete = nil }
|
||||
Button("删除", role: .destructive) {
|
||||
if let item = pendingDelete { inbox.dismiss(item) }
|
||||
pendingDelete = nil
|
||||
}
|
||||
} message: {
|
||||
Text("删除这条公告?")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AnnouncementDetailView: View {
|
||||
@ObservedObject var inbox: AnnouncementInbox
|
||||
let selection: AnnouncementSelection
|
||||
@Environment(\.openURL) private var openURL
|
||||
|
||||
private var item: Announcement? {
|
||||
inbox.state.items.first { $0.id == selection.id && $0.revision == selection.revision }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
if let item {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text(verbatim: item.title)
|
||||
.font(.title2.weight(.semibold))
|
||||
Text("\(AnnouncementDate.string(item)) · \(item.read ? "已读" : "未读")")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
if inbox.state.readSaveFailed {
|
||||
Text("无法保存本地阅读状态,请重试。")
|
||||
.foregroundStyle(.red)
|
||||
Button("重试保存阅读状态") { inbox.markRead(item) }
|
||||
}
|
||||
Text(AnnouncementText.format(item.body))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.environment(\.openURL, OpenURLAction { url in
|
||||
guard AnnouncementText.isWebURL(url) else { return .discarded }
|
||||
openURL(url)
|
||||
return .handled
|
||||
})
|
||||
}
|
||||
.padding(20)
|
||||
} else {
|
||||
Text("这条公告已更新或删除,请返回公告列表查看。")
|
||||
.foregroundStyle(.secondary)
|
||||
.padding(20)
|
||||
}
|
||||
}
|
||||
.navigationTitle("公告详情")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.onAppear {
|
||||
if let item { inbox.markRead(item) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Foundation
|
||||
|
||||
enum AnnouncementText {
|
||||
/// Match desktop: preserve plain text and line breaks; recognize only web
|
||||
/// URLs and [label](URL), without interpreting arbitrary Markdown or HTML.
|
||||
static func format(_ body: String) -> AttributedString {
|
||||
let text = Array(body.replacingOccurrences(of: "\r\n", with: "\n"))
|
||||
var output = AttributedString()
|
||||
var literal = ""
|
||||
var position = 0
|
||||
|
||||
func hasScheme(at start: Int) -> Bool {
|
||||
let prefix = String(text[start..<min(text.count, start + 8)]).lowercased()
|
||||
return prefix.hasPrefix("https://") || prefix.hasPrefix("http://")
|
||||
}
|
||||
|
||||
func urlEnd(from start: Int) -> Int {
|
||||
let punctuation = Set("<>\"'`\\{},。;:!?、()【】《》「」『』“”‘’")
|
||||
var parentheses = 0
|
||||
var brackets = 0
|
||||
var end = start
|
||||
while end < text.count {
|
||||
let character = text[end]
|
||||
if punctuation.contains(character) || character.unicodeScalars.contains(where: {
|
||||
$0.value <= 0x20 || $0.value == 0x7f
|
||||
}) { break }
|
||||
if character == "(" { parentheses += 1 }
|
||||
if character == ")" {
|
||||
if parentheses == 0 { break }
|
||||
parentheses -= 1
|
||||
}
|
||||
if character == "[" { brackets += 1 }
|
||||
if character == "]" {
|
||||
if brackets == 0 { break }
|
||||
brackets -= 1
|
||||
}
|
||||
end += 1
|
||||
}
|
||||
return end
|
||||
}
|
||||
|
||||
func appendLink(label: String, destination: String) -> Bool {
|
||||
guard let url = URL(string: destination), isWebURL(url) else { return false }
|
||||
output.append(AttributedString(literal))
|
||||
literal = ""
|
||||
var link = AttributedString(label)
|
||||
link.link = url
|
||||
output.append(link)
|
||||
return true
|
||||
}
|
||||
|
||||
while position < text.count {
|
||||
if text[position] == "[",
|
||||
let labelEnd = text[(position + 1)...].firstIndex(of: "]"),
|
||||
labelEnd > position + 1, labelEnd + 2 < text.count,
|
||||
text[labelEnd + 1] == "(",
|
||||
!text[(position + 1)..<labelEnd].contains(where: { "[]\r\n".contains($0) }),
|
||||
hasScheme(at: labelEnd + 2) {
|
||||
let end = urlEnd(from: labelEnd + 2)
|
||||
if end < text.count, text[end] == ")",
|
||||
appendLink(label: String(text[(position + 1)..<labelEnd]),
|
||||
destination: String(text[(labelEnd + 2)..<end])) {
|
||||
position = end + 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
if hasScheme(at: position) {
|
||||
var end = urlEnd(from: position)
|
||||
while end > position, ".,;:!?".contains(text[end - 1]) { end -= 1 }
|
||||
let address = String(text[position..<end])
|
||||
if appendLink(label: address, destination: address) {
|
||||
position = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
literal.append(text[position])
|
||||
position += 1
|
||||
}
|
||||
output.append(AttributedString(literal))
|
||||
return output
|
||||
}
|
||||
|
||||
static func isWebURL(_ url: URL) -> Bool {
|
||||
guard let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme),
|
||||
let host = url.host, !host.isEmpty else { return false }
|
||||
return !url.absoluteString.unicodeScalars.contains {
|
||||
$0.value <= 0x20 || $0.value == 0x7f || "\\<>\"".unicodeScalars.contains($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ typedef NS_ENUM(NSInteger, CrossDeskSignalState) {
|
||||
CrossDeskSignalStateReconnecting,
|
||||
CrossDeskSignalStateServerClosed,
|
||||
CrossDeskSignalStateTLSCertificateError,
|
||||
CrossDeskSignalStateCredentialUnavailable,
|
||||
};
|
||||
|
||||
typedef NS_ENUM(NSInteger, CrossDeskConnectionState) {
|
||||
@@ -43,10 +44,35 @@ typedef NS_ENUM(NSInteger, CrossDeskVideoAdaptationPolicy) {
|
||||
|
||||
@class CrossDeskRTCBridge;
|
||||
|
||||
typedef NS_ENUM(NSInteger, CrossDeskTraversalMode) {
|
||||
CrossDeskTraversalModeUnknown = 0,
|
||||
CrossDeskTraversalModeDirect,
|
||||
CrossDeskTraversalModeRelay,
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
uint32_t inboundBitrate;
|
||||
uint32_t outboundBitrate;
|
||||
float lossRate;
|
||||
} CrossDeskTrafficStats;
|
||||
|
||||
/// Value snapshot: no MiniRTC callback-owned memory crosses the main queue.
|
||||
typedef struct {
|
||||
CrossDeskTrafficStats video;
|
||||
CrossDeskTrafficStats audio;
|
||||
CrossDeskTrafficStats data;
|
||||
CrossDeskTrafficStats total;
|
||||
double rttMilliseconds;
|
||||
BOOL srtpActive;
|
||||
CrossDeskTraversalMode traversalMode;
|
||||
} CrossDeskNetworkStats;
|
||||
|
||||
@protocol CrossDeskRTCBridgeDelegate <NSObject>
|
||||
@optional
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didChangeSignalState:(CrossDeskSignalState)state;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didChangeIdentityStorageError:(BOOL)hasError;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didChangeConnectionState:(CrossDeskConnectionState)state
|
||||
remoteID:(NSString *)remoteID;
|
||||
@@ -55,14 +81,28 @@ typedef NS_ENUM(NSInteger, CrossDeskVideoAdaptationPolicy) {
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceivePixelBuffer:(CVPixelBufferRef)pixelBuffer
|
||||
width:(NSInteger)width
|
||||
height:(NSInteger)height;
|
||||
height:(NSInteger)height
|
||||
captureUptime:(NSTimeInterval)captureUptime;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceiveHostName:(NSString *)hostName
|
||||
appVersion:(NSString *)appVersion
|
||||
platform:(NSString *)platform
|
||||
displayNames:(NSArray<NSString *> *)displayNames
|
||||
displaySizes:(NSArray<NSValue *> *)displaySizes;
|
||||
displaySizes:(NSArray<NSValue *> *)displaySizes
|
||||
supportsVideoSettings:(BOOL)supportsVideoSettings;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceiveVideoSettingsQuality:(NSInteger)quality
|
||||
frameRate:(NSInteger)frameRate
|
||||
preference:(NSInteger)preference
|
||||
requestID:(uint32_t)requestID
|
||||
accepted:(BOOL)accepted;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceivePresence:(NSDictionary<NSString *, NSNumber *> *)presence
|
||||
snapshot:(BOOL)snapshot;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceiveAnnouncementMessage:(NSData *)message;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didFailAnnouncementRequest:(NSString *)requestID;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceiveCursorVisible:(BOOL)visible
|
||||
shape:(NSInteger)shape
|
||||
@@ -85,9 +125,8 @@ typedef NS_ENUM(NSInteger, CrossDeskVideoAdaptationPolicy) {
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didReceiveFileAtURL:(NSURL *)fileURL;
|
||||
- (void)rtcBridge:(CrossDeskRTCBridge *)bridge
|
||||
didUpdateBitrate:(NSUInteger)bitsPerSecond
|
||||
lossRate:(float)lossRate
|
||||
usingTURN:(BOOL)usingTURN;
|
||||
didUpdateNetworkStats:(CrossDeskNetworkStats)stats
|
||||
NS_SWIFT_NAME(rtcBridge(_:didUpdateNetworkStats:));
|
||||
@end
|
||||
|
||||
/// Objective-C++ boundary around the native MiniRTC C API.
|
||||
@@ -98,17 +137,30 @@ typedef NS_ENUM(NSInteger, CrossDeskVideoAdaptationPolicy) {
|
||||
|
||||
@property(nonatomic, weak, nullable) id<CrossDeskRTCBridgeDelegate> delegate;
|
||||
|
||||
// Uses the same release/patch ordering as the desktop controller.
|
||||
+ (nullable NSString *)availableUpdateForAppVersion:(NSString *)appVersion
|
||||
releaseJSON:(NSData *)releaseJSON
|
||||
NS_SWIFT_NAME(availableUpdate(appVersion:releaseJSON:));
|
||||
|
||||
- (void)configureWithSignalHost:(NSString *)host
|
||||
signalPort:(NSInteger)signalPort;
|
||||
- (void)setHardwareAccelerationEnabled:(BOOL)enabled;
|
||||
- (void)setVideoAdaptationPolicy:(CrossDeskVideoAdaptationPolicy)policy;
|
||||
- (void)sendVideoSettingsWithQuality:(NSInteger)quality
|
||||
frameRate:(NSInteger)frameRate
|
||||
preference:(NSInteger)preference
|
||||
requestID:(uint32_t)requestID
|
||||
NS_SWIFT_NAME(sendVideoSettings(quality:frameRate:preference:requestID:));
|
||||
- (void)requestPresenceForRemoteIDs:(NSArray<NSString *> *)remoteIDs
|
||||
subscribe:(BOOL)subscribe
|
||||
NS_SWIFT_NAME(requestPresence(remoteIDs:subscribe:));
|
||||
- (void)invalidatePresence;
|
||||
- (void)sendAnnouncementRequest:(NSData *)request requestID:(NSString *)requestID
|
||||
NS_SWIFT_NAME(sendAnnouncementRequest(_:requestID:));
|
||||
|
||||
- (void)connectToRemoteID:(NSString *)remoteID password:(NSString *)password;
|
||||
- (void)disconnect;
|
||||
// Close both session and signaling peers, including automatic reconnection.
|
||||
- (void)stopNetworking;
|
||||
- (void)requestKeyFrame;
|
||||
|
||||
- (void)sendPointerAtX:(float)x
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#import "CrossDeskRTCBridge.h"
|
||||
|
||||
#import <CoreMedia/CoreMedia.h>
|
||||
#import <Security/Security.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
#include <algorithm>
|
||||
@@ -17,6 +18,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include <display_stream_id.h>
|
||||
#include <app_version.h>
|
||||
#include <file_transfer_format.h>
|
||||
#include <remote_action.h>
|
||||
#include <stream_names.h>
|
||||
@@ -75,7 +77,6 @@ struct RTCState {
|
||||
CallbackContext controller_context;
|
||||
std::string signal_host;
|
||||
int signal_port = 0;
|
||||
bool hardware_acceleration = true;
|
||||
VideoDegradationPreference video_adaptation_policy =
|
||||
VideoDegradationPreference::MaintainResolution;
|
||||
bool identity_ready = false;
|
||||
@@ -102,6 +103,113 @@ bool IsReusableIdentity(const std::string &identity) {
|
||||
separator + 1 < identity.size();
|
||||
}
|
||||
|
||||
std::string ProvisionedIdentityCredential(const std::string &received,
|
||||
const std::string ¤t) {
|
||||
// A successful re-login can acknowledge the ID without echoing its password.
|
||||
// Retain the credential used to authenticate that same ID.
|
||||
if (!IsReusableIdentity(received) && IsReusableIdentity(current) &&
|
||||
current.substr(0, current.find('@')) == received) return current;
|
||||
return received;
|
||||
}
|
||||
|
||||
NSString *IdentityCredentialAccount(NSString *host, NSInteger port) {
|
||||
// Preserve the old server-scoped key so upgrades retain the same identity.
|
||||
return [NSString stringWithFormat:@"CrossDeskIdentity.%@.%ld", host, (long)port];
|
||||
}
|
||||
|
||||
NSMutableDictionary *IdentityCredentialQuery(NSString *account) {
|
||||
return [@{
|
||||
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
|
||||
(__bridge id)kSecAttrService: @"cn.crossdesk.mobile.signaling-identity",
|
||||
(__bridge id)kSecAttrAccount: account,
|
||||
(__bridge id)kSecAttrSynchronizable: @NO,
|
||||
} mutableCopy];
|
||||
}
|
||||
|
||||
bool IsReusableIdentityValue(NSString *value) {
|
||||
return [value isKindOfClass:NSString.class] && value.UTF8String &&
|
||||
IsReusableIdentity(std::string(value.UTF8String));
|
||||
}
|
||||
|
||||
OSStatus SaveIdentityCredential(NSString *account, NSString *value) {
|
||||
if (!IsReusableIdentityValue(value)) return errSecParam;
|
||||
NSMutableDictionary *query = IdentityCredentialQuery(account);
|
||||
NSDictionary *attributes = @{
|
||||
(__bridge id)kSecValueData: [value dataUsingEncoding:NSUTF8StringEncoding],
|
||||
(__bridge id)kSecAttrAccessible:
|
||||
(__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
||||
};
|
||||
// Update in place: deleting first could lose a valid credential on failure.
|
||||
OSStatus status = SecItemUpdate((__bridge CFDictionaryRef)query,
|
||||
(__bridge CFDictionaryRef)attributes);
|
||||
if (status == errSecItemNotFound) {
|
||||
NSMutableDictionary *item = [query mutableCopy];
|
||||
[item addEntriesFromDictionary:attributes];
|
||||
status = SecItemAdd((__bridge CFDictionaryRef)item, nullptr);
|
||||
if (status == errSecDuplicateItem) {
|
||||
status = SecItemUpdate((__bridge CFDictionaryRef)query,
|
||||
(__bridge CFDictionaryRef)attributes);
|
||||
}
|
||||
}
|
||||
if (status == errSecSuccess) {
|
||||
[[NSUserDefaults standardUserDefaults] removeObjectForKey:account];
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
OSStatus LoadIdentityCredential(NSString *account, NSString **value) {
|
||||
*value = nil;
|
||||
NSMutableDictionary *query = IdentityCredentialQuery(account);
|
||||
query[(__bridge id)kSecReturnData] = @YES;
|
||||
query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
|
||||
CFTypeRef result = nullptr;
|
||||
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
|
||||
id object = CFBridgingRelease(result);
|
||||
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
|
||||
if (status == errSecSuccess) {
|
||||
NSString *stored = [object isKindOfClass:NSData.class]
|
||||
? [[NSString alloc] initWithData:object encoding:NSUTF8StringEncoding] : nil;
|
||||
if (!IsReusableIdentityValue(stored)) return errSecDecode;
|
||||
*value = stored;
|
||||
// A Keychain value wins over a stale copy left by an interrupted migration.
|
||||
[defaults removeObjectForKey:account];
|
||||
return errSecSuccess;
|
||||
}
|
||||
if (status != errSecItemNotFound) return status;
|
||||
|
||||
NSString *legacy = [defaults objectForKey:account];
|
||||
if (!legacy) return errSecItemNotFound;
|
||||
if (!IsReusableIdentityValue(legacy)) {
|
||||
// Older passwordless IDs cannot authenticate on a subsequent app launch.
|
||||
[defaults removeObjectForKey:account];
|
||||
return errSecItemNotFound;
|
||||
}
|
||||
status = SaveIdentityCredential(account, legacy);
|
||||
if (status == errSecSuccess) *value = legacy;
|
||||
return status;
|
||||
}
|
||||
|
||||
OSStatus MigrateLegacyIdentityCredentials() {
|
||||
OSStatus first_error = errSecSuccess;
|
||||
for (NSString *key in NSUserDefaults.standardUserDefaults.dictionaryRepresentation) {
|
||||
if (![key hasPrefix:@"CrossDeskIdentity."]) continue;
|
||||
NSString *unused = nil;
|
||||
OSStatus status = LoadIdentityCredential(key, &unused);
|
||||
if (status != errSecSuccess && status != errSecItemNotFound &&
|
||||
first_error == errSecSuccess) first_error = status;
|
||||
}
|
||||
return first_error;
|
||||
}
|
||||
|
||||
OSStatus RemoveIdentityCredential(NSString *account) {
|
||||
OSStatus status = SecItemDelete((__bridge CFDictionaryRef)IdentityCredentialQuery(account));
|
||||
if (status == errSecSuccess || status == errSecItemNotFound) {
|
||||
[[NSUserDefaults standardUserDefaults] removeObjectForKey:account];
|
||||
return errSecSuccess;
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
void CopyCString(char *destination, size_t capacity,
|
||||
const std::string &source) {
|
||||
if (!destination || capacity == 0) return;
|
||||
@@ -217,20 +325,27 @@ void DispatchMain(dispatch_block_t block) {
|
||||
sourceIDSize:(size_t)sourceIDSize;
|
||||
- (void)enqueueVideoPixelBuffer:(CVPixelBufferRef)pixelBuffer
|
||||
width:(NSInteger)width
|
||||
height:(NSInteger)height;
|
||||
height:(NSInteger)height
|
||||
captureUptime:(NSTimeInterval)captureUptime;
|
||||
- (void)resetVideoDelivery;
|
||||
- (void)notifyVideoSettings:(crossdesk::VideoSettings)settings
|
||||
generation:(uint64_t)generation;
|
||||
- (void)handleAudio:(const char *)data size:(size_t)size;
|
||||
- (void)handleData:(const char *)data
|
||||
size:(size_t)size
|
||||
sourceID:(const char *)sourceID
|
||||
sourceIDSize:(size_t)sourceIDSize;
|
||||
- (void)handleStats:(const MiniRtcNetTrafficStats *)stats mode:(TraversalMode)mode;
|
||||
sourceIDSize:(size_t)sourceIDSize
|
||||
generation:(uint64_t)generation;
|
||||
- (void)handleStats:(const MiniRtcNetTrafficStats *)stats
|
||||
mode:(TraversalMode)mode
|
||||
generation:(uint64_t)generation;
|
||||
- (void)sendMessage:(const std::string &)message
|
||||
reliable:(BOOL)reliable
|
||||
stream:(const char *)stream;
|
||||
- (void)createIdentityPeer;
|
||||
- (void)createControllerPeer;
|
||||
- (void)destroyIdentityPeer;
|
||||
- (void)reportIdentityStorageStatus:(OSStatus)status;
|
||||
- (void)destroyControllerPeer;
|
||||
@end
|
||||
|
||||
@@ -269,7 +384,8 @@ void OnDataBuffer(const char *data, size_t size, const char *, size_t,
|
||||
[owner handleData:data
|
||||
size:size
|
||||
sourceID:source_id
|
||||
sourceIDSize:source_id_size];
|
||||
sourceIDSize:source_id_size
|
||||
generation:context->generation];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,7 +436,7 @@ void OnNetworkStats(const char *peer_id, size_t peer_id_size,
|
||||
generation:context->generation];
|
||||
} else if (context->role == PeerRole::Controller && stats &&
|
||||
[owner isControllerGenerationActive:context->generation]) {
|
||||
[owner handleStats:stats mode:mode];
|
||||
[owner handleStats:stats mode:mode generation:context->generation];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +448,8 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
state.signal_host);
|
||||
params.signal_server_port = state.signal_port;
|
||||
CopyCString(params.log_path, sizeof(params.log_path), state.log_path);
|
||||
params.hardware_acceleration = state.hardware_acceleration;
|
||||
// iOS H.264 is provided exclusively by VideoToolbox.
|
||||
params.hardware_acceleration = true;
|
||||
params.native_video_output = true;
|
||||
params.av1_encoding = false;
|
||||
params.turn_mode = TurnMode::TurnAutoUdpTcp;
|
||||
@@ -367,6 +484,7 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
CVPixelBufferRef _pendingVideoBuffer;
|
||||
NSInteger _pendingVideoWidth;
|
||||
NSInteger _pendingVideoHeight;
|
||||
NSTimeInterval _pendingVideoCaptureUptime;
|
||||
bool _videoDeliveryScheduled;
|
||||
uint64_t _videoDeliveryGeneration;
|
||||
std::mutex _fileMutex;
|
||||
@@ -377,6 +495,17 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
std::atomic<uint64_t> _identityGeneration;
|
||||
std::atomic<uint64_t> _signalGeneration;
|
||||
std::atomic<uint64_t> _presenceGeneration;
|
||||
std::atomic<uint64_t> _networkingGeneration;
|
||||
}
|
||||
|
||||
+ (nullable NSString *)availableUpdateForAppVersion:(NSString *)appVersion
|
||||
releaseJSON:(NSData *)releaseJSON {
|
||||
const auto latest = crossdesk::ParseVersionInfoJSON(std::string_view(
|
||||
static_cast<const char *>(releaseJSON.bytes), releaseJSON.length));
|
||||
if (!latest) return nil;
|
||||
const auto update = crossdesk::AvailableAppUpdate(appVersion.UTF8String ?: "",
|
||||
*latest);
|
||||
return update ? [NSString stringWithUTF8String:update->c_str()] : nil;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
@@ -397,6 +526,7 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
_pendingVideoBuffer = nullptr;
|
||||
_pendingVideoWidth = 0;
|
||||
_pendingVideoHeight = 0;
|
||||
_pendingVideoCaptureUptime = 0;
|
||||
_videoDeliveryScheduled = false;
|
||||
_videoDeliveryGeneration = 0;
|
||||
_selectedDisplay.store(0);
|
||||
@@ -406,6 +536,7 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
_identityGeneration.store(0);
|
||||
_signalGeneration.store(0);
|
||||
_presenceGeneration.store(0);
|
||||
_networkingGeneration.store(0);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@@ -451,11 +582,22 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
const char *log_c_string = logDirectory.UTF8String;
|
||||
const std::string log_path = log_c_string ? log_c_string : "logs";
|
||||
|
||||
const uint64_t networking_generation = _networkingGeneration.load();
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
if (networking_generation != self->_networkingGeneration.load()) return;
|
||||
const bool unchanged = self->_state->signal_host == host_value &&
|
||||
self->_state->signal_port == signalPort &&
|
||||
self->_state->identity_peer != nullptr;
|
||||
if (unchanged) return;
|
||||
const OSStatus migration_status = MigrateLegacyIdentityCredentials();
|
||||
[self reportIdentityStorageStatus:migration_status];
|
||||
if (unchanged) {
|
||||
if (IsReusableIdentity(self->_state->identity_with_password)) {
|
||||
NSString *value = [NSString stringWithUTF8String:self->_state->identity_with_password.c_str()];
|
||||
[self reportIdentityStorageStatus:SaveIdentityCredential(
|
||||
IdentityCredentialAccount(trimmed, signalPort), value)];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
[self destroyControllerPeer];
|
||||
[self destroyIdentityPeer];
|
||||
@@ -467,37 +609,33 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
self->_state->identity_with_password.clear();
|
||||
self->_state->identity_base.clear();
|
||||
|
||||
NSString *key = [NSString stringWithFormat:@"CrossDeskIdentity.%@.%ld",
|
||||
trimmed, (long)signalPort];
|
||||
NSString *cached = [[NSUserDefaults standardUserDefaults]
|
||||
stringForKey:key];
|
||||
if (cached.length > 0) {
|
||||
const std::string cached_identity = cached.UTF8String ?: "";
|
||||
if (IsReusableIdentity(cached_identity)) {
|
||||
self->_state->identity_with_password = cached_identity;
|
||||
self->_state->identity_base = BaseIdentity(cached_identity);
|
||||
DispatchMain(^{
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:
|
||||
@selector(rtcBridge:didProvisionIdentity:)]) {
|
||||
[delegate rtcBridge:self didProvisionIdentity:cached];
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// A bare ID cannot authenticate after its first signaling session.
|
||||
// Older iOS builds stored it anyway, causing every later launch to be
|
||||
// rejected as "Incorrect password". Drop it and request a fresh
|
||||
// server-issued ID/password pair.
|
||||
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
|
||||
}
|
||||
NSString *cached = nil;
|
||||
OSStatus load_status = LoadIdentityCredential(
|
||||
IdentityCredentialAccount(trimmed, signalPort), &cached);
|
||||
if (load_status == errSecSuccess) {
|
||||
self->_state->identity_with_password = cached.UTF8String;
|
||||
self->_state->identity_base = BaseIdentity(self->_state->identity_with_password);
|
||||
} else if (load_status != errSecItemNotFound) {
|
||||
[self reportIdentityStorageStatus:load_status];
|
||||
// Locked/unavailable Keychain is not the same as a missing identity.
|
||||
[self handleSignalState:CrossDeskSignalStateCredentialUnavailable
|
||||
role:PeerRole::Identity
|
||||
generation:self->_identityGeneration.load()];
|
||||
return;
|
||||
}
|
||||
[self createIdentityPeer];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)setHardwareAccelerationEnabled:(BOOL)enabled {
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
self->_state->hardware_acceleration = enabled;
|
||||
if (load_status == errSecSuccess) {
|
||||
NSString *identifier = [NSString stringWithUTF8String:self->_state->identity_base.c_str()];
|
||||
const uint64_t identity_generation = self->_identityGeneration.load();
|
||||
DispatchMain(^{
|
||||
if (networking_generation != self->_networkingGeneration.load() ||
|
||||
identity_generation != self->_identityGeneration.load()) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:@selector(rtcBridge:didProvisionIdentity:)]) {
|
||||
[delegate rtcBridge:self didProvisionIdentity:identifier];
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -525,6 +663,72 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
_presenceGeneration.fetch_add(1);
|
||||
}
|
||||
|
||||
- (void)sendAnnouncementRequest:(NSData *)request requestID:(NSString *)requestID {
|
||||
NSData *payload = [request copy];
|
||||
NSString *identifier = [requestID copy];
|
||||
const uint64_t generation = _identityGeneration.load();
|
||||
const uint64_t signal_generation = _signalGeneration.load();
|
||||
const uint64_t networking_generation = _networkingGeneration.load();
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
if (generation != self->_identityGeneration.load() ||
|
||||
signal_generation != self->_signalGeneration.load() ||
|
||||
networking_generation != self->_networkingGeneration.load()) return;
|
||||
if (self->_state->identity_peer && self->_state->identity_ready &&
|
||||
!self->_state->identity_base.empty() &&
|
||||
SendSignalMessage(self->_state->identity_peer,
|
||||
static_cast<const char *>(payload.bytes), payload.length) == 0) return;
|
||||
DispatchMain(^{
|
||||
if (generation != self->_identityGeneration.load() ||
|
||||
signal_generation != self->_signalGeneration.load() ||
|
||||
networking_generation != self->_networkingGeneration.load()) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:@selector(rtcBridge:didFailAnnouncementRequest:)]) {
|
||||
[delegate rtcBridge:self didFailAnnouncementRequest:identifier];
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
- (void)sendVideoSettingsWithQuality:(NSInteger)quality
|
||||
frameRate:(NSInteger)frameRate
|
||||
preference:(NSInteger)preference
|
||||
requestID:(uint32_t)requestID {
|
||||
if (quality < 0 || quality > 2 || (frameRate != 30 && frameRate != 60) ||
|
||||
preference < 0 || preference > 2) return;
|
||||
const uint64_t generation = _activeControllerGeneration.load();
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
if (![self isControllerGenerationActive:generation] ||
|
||||
!self->_state->controller_peer) return;
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::video_settings;
|
||||
action.vs = {static_cast<int>(quality), static_cast<int>(frameRate),
|
||||
static_cast<int>(preference), requestID, false};
|
||||
const auto message = action.to_json();
|
||||
if (SendReliableDataFrame(self->_state->controller_peer, message.data(),
|
||||
message.size(), kControlStream) != 0) {
|
||||
[self notifyVideoSettings:action.vs generation:generation];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)notifyVideoSettings:(crossdesk::VideoSettings)settings
|
||||
generation:(uint64_t)generation {
|
||||
DispatchMain(^{
|
||||
if (![self isControllerGenerationActive:generation]) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:
|
||||
@selector(rtcBridge:didReceiveVideoSettingsQuality:frameRate:
|
||||
preference:requestID:accepted:)]) {
|
||||
[delegate rtcBridge:self
|
||||
didReceiveVideoSettingsQuality:settings.quality
|
||||
frameRate:settings.frame_rate
|
||||
preference:settings.preference
|
||||
requestID:settings.request_id
|
||||
accepted:settings.accepted];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)requestPresenceForRemoteIDs:(NSArray<NSString *> *)remoteIDs
|
||||
subscribe:(BOOL)subscribe {
|
||||
NSArray<NSString *> *owned_ids = [remoteIDs copy];
|
||||
@@ -607,6 +811,24 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
});
|
||||
}
|
||||
|
||||
- (void)stopNetworking {
|
||||
_networkingGeneration.fetch_add(1);
|
||||
_controllerGenerationCounter.fetch_add(1);
|
||||
_activeControllerGeneration.store(0);
|
||||
_identityGeneration.fetch_add(1);
|
||||
_signalGeneration.fetch_add(1);
|
||||
_presenceGeneration.fetch_add(1);
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
self->_state->pending_remote_id.clear();
|
||||
self->_state->pending_password.clear();
|
||||
[self destroyControllerPeer];
|
||||
[self destroyIdentityPeer];
|
||||
self->_state->signal_host.clear();
|
||||
self->_state->identity_with_password.clear();
|
||||
self->_state->identity_base.clear();
|
||||
});
|
||||
}
|
||||
|
||||
- (void)requestKeyFrame {
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
if (self->_state->controller_peer) {
|
||||
@@ -848,6 +1070,20 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
});
|
||||
}
|
||||
|
||||
- (void)reportIdentityStorageStatus:(OSStatus)status {
|
||||
const BOOL has_error = status != errSecSuccess;
|
||||
if (has_error) {
|
||||
// Log only the OSStatus, never an account, credential or Keychain payload.
|
||||
NSLog(@"CrossDesk identity Keychain operation failed (%d)", (int)status);
|
||||
}
|
||||
DispatchMain(^{
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:@selector(rtcBridge:didChangeIdentityStorageError:)]) {
|
||||
[delegate rtcBridge:self didChangeIdentityStorageError:has_error];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)createIdentityPeer {
|
||||
if (_state->identity_peer || _state->signal_host.empty()) return;
|
||||
_state->identity_context.generation = _identityGeneration.fetch_add(1) + 1;
|
||||
@@ -968,10 +1204,16 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
self->_state->identity_recovery_attempted = true;
|
||||
NSString *host = [NSString stringWithUTF8String:
|
||||
self->_state->signal_host.c_str()];
|
||||
NSString *key = [NSString stringWithFormat:@"CrossDeskIdentity.%@.%d",
|
||||
host,
|
||||
self->_state->signal_port];
|
||||
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
|
||||
OSStatus status = RemoveIdentityCredential(
|
||||
IdentityCredentialAccount(host, self->_state->signal_port));
|
||||
[self reportIdentityStorageStatus:status];
|
||||
if (status != errSecSuccess) {
|
||||
[self destroyIdentityPeer];
|
||||
[self handleSignalState:CrossDeskSignalStateCredentialUnavailable
|
||||
role:PeerRole::Identity
|
||||
generation:self->_identityGeneration.load()];
|
||||
return;
|
||||
}
|
||||
[self destroyIdentityPeer];
|
||||
self->_state->identity_with_password.clear();
|
||||
self->_state->identity_base.clear();
|
||||
@@ -1005,10 +1247,11 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
size:(size_t)size
|
||||
role:(PeerRole)role
|
||||
generation:(uint64_t)generation {
|
||||
constexpr size_t kMaxPresenceMessageSize = 256 * 1024;
|
||||
// Twenty 8 KiB bodies may expand substantially when JSON-escaped.
|
||||
constexpr size_t kMaxSignalMessageSize = 1024 * 1024;
|
||||
if (role != PeerRole::Identity || generation != _identityGeneration.load() ||
|
||||
!message || size == 0 ||
|
||||
size > kMaxPresenceMessageSize) {
|
||||
size > kMaxSignalMessageSize) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1024,6 +1267,19 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
NSString *type = object[@"type"];
|
||||
if (![type isKindOfClass:NSString.class]) return;
|
||||
|
||||
if ([type isEqualToString:@"announcements"] ||
|
||||
[type isEqualToString:@"announcements_changed"]) {
|
||||
DispatchMain(^{
|
||||
if (generation != self->_identityGeneration.load() ||
|
||||
signal_generation != self->_signalGeneration.load()) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:@selector(rtcBridge:didReceiveAnnouncementMessage:)]) {
|
||||
[delegate rtcBridge:self didReceiveAnnouncementMessage:payload];
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
NSMutableDictionary<NSString *, NSNumber *> *presence =
|
||||
[NSMutableDictionary dictionary];
|
||||
if ([type isEqualToString:@"presence"]) {
|
||||
@@ -1084,25 +1340,25 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
const std::string identity_copy = identity;
|
||||
dispatch_async(_rtcQueue, ^{
|
||||
if (generation != self->_identityGeneration.load()) return;
|
||||
self->_state->identity_with_password = identity_copy;
|
||||
self->_state->identity_base = BaseIdentity(identity_copy);
|
||||
const std::string credential = ProvisionedIdentityCredential(
|
||||
identity_copy, self->_state->identity_with_password);
|
||||
self->_state->identity_with_password = credential;
|
||||
self->_state->identity_base = BaseIdentity(credential);
|
||||
NSString *host = [NSString stringWithUTF8String:
|
||||
self->_state->signal_host.c_str()];
|
||||
NSString *key = [NSString stringWithFormat:@"CrossDeskIdentity.%@.%d",
|
||||
host, self->_state->signal_port];
|
||||
NSString *value = [NSString stringWithUTF8String:identity_copy.c_str()];
|
||||
if (IsReusableIdentity(identity_copy)) {
|
||||
[[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
|
||||
} else {
|
||||
// Keep a passwordless identity only for this process. It is valid for
|
||||
// the current login but is not safe to reuse on the next app launch.
|
||||
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
|
||||
}
|
||||
NSString *account = IdentityCredentialAccount(host, self->_state->signal_port);
|
||||
NSString *value = [NSString stringWithUTF8String:credential.c_str()];
|
||||
OSStatus status = IsReusableIdentity(credential)
|
||||
? SaveIdentityCredential(account, value)
|
||||
: RemoveIdentityCredential(account);
|
||||
[self reportIdentityStorageStatus:status];
|
||||
// Only the public device ID crosses into UI state; keep its password here.
|
||||
NSString *identifier = [NSString stringWithUTF8String:self->_state->identity_base.c_str()];
|
||||
DispatchMain(^{
|
||||
if (generation != self->_identityGeneration.load()) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:@selector(rtcBridge:didProvisionIdentity:)]) {
|
||||
[delegate rtcBridge:self didProvisionIdentity:value];
|
||||
[delegate rtcBridge:self didProvisionIdentity:identifier];
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1132,9 +1388,14 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
: "iPhone-" + self->_state->identity_base;
|
||||
RemoteAction action{};
|
||||
action.type = ControlType::host_infomation;
|
||||
action.i.platform = crossdesk::HostPlatform::IOS;
|
||||
CopyCString(action.i.host_name, sizeof(action.i.host_name),
|
||||
controller_name);
|
||||
action.i.host_name_size = std::strlen(action.i.host_name);
|
||||
NSString *appVersion = [[NSBundle mainBundle]
|
||||
objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
|
||||
CopyCString(action.i.app_version, sizeof(action.i.app_version),
|
||||
appVersion.UTF8String ?: "");
|
||||
action.i.display_list = nullptr;
|
||||
action.i.display_num = 0;
|
||||
action.i.left = nullptr;
|
||||
@@ -1189,6 +1450,17 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
static_cast<size_t>(_selectedDisplay.load()));
|
||||
if (source != expected) return;
|
||||
}
|
||||
// Translate the transport's calibrated capture time once, while the peer is
|
||||
// alive. Carry it with the exact pixels through coalescing and UI submission.
|
||||
const NSTimeInterval now = NSProcessInfo.processInfo.systemUptime;
|
||||
const int64_t peer_now = GetSystemTimeMicros(_state->controller_peer);
|
||||
NSTimeInterval capture_uptime = 0;
|
||||
if (frame->captured_timestamp > 0 && peer_now > 0 &&
|
||||
frame->captured_timestamp <= static_cast<uint64_t>(peer_now) &&
|
||||
static_cast<uint64_t>(peer_now) - frame->captured_timestamp <= 5'000'000) {
|
||||
capture_uptime = now -
|
||||
(static_cast<uint64_t>(peer_now) - frame->captured_timestamp) / 1'000'000.0;
|
||||
}
|
||||
const MiniRtcNativeVideoFrame *native_frame = frame->native_frame;
|
||||
const bool has_native_pixel_buffer =
|
||||
native_frame &&
|
||||
@@ -1202,7 +1474,8 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
native_frame->payload.cv_pixel_buffer);
|
||||
[self enqueueVideoPixelBuffer:pixel_buffer
|
||||
width:frame->width
|
||||
height:frame->height];
|
||||
height:frame->height
|
||||
captureUptime:capture_uptime];
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1294,13 +1567,15 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
|
||||
[self enqueueVideoPixelBuffer:pixel_buffer
|
||||
width:frame_width
|
||||
height:frame_height];
|
||||
height:frame_height
|
||||
captureUptime:capture_uptime];
|
||||
CVPixelBufferRelease(pixel_buffer);
|
||||
}
|
||||
|
||||
- (void)enqueueVideoPixelBuffer:(CVPixelBufferRef)pixelBuffer
|
||||
width:(NSInteger)width
|
||||
height:(NSInteger)height {
|
||||
height:(NSInteger)height
|
||||
captureUptime:(NSTimeInterval)captureUptime {
|
||||
if (!pixelBuffer) return;
|
||||
|
||||
CVPixelBufferRetain(pixelBuffer);
|
||||
@@ -1314,6 +1589,7 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
_pendingVideoBuffer = pixelBuffer;
|
||||
_pendingVideoWidth = width;
|
||||
_pendingVideoHeight = height;
|
||||
_pendingVideoCaptureUptime = captureUptime;
|
||||
generation = _videoDeliveryGeneration;
|
||||
if (!_videoDeliveryScheduled) {
|
||||
_videoDeliveryScheduled = true;
|
||||
@@ -1326,15 +1602,18 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
CVPixelBufferRef latest_buffer = nullptr;
|
||||
NSInteger latest_width = 0;
|
||||
NSInteger latest_height = 0;
|
||||
NSTimeInterval latest_capture_uptime = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(self->_pendingVideoMutex);
|
||||
if (generation != self->_videoDeliveryGeneration) return;
|
||||
latest_buffer = self->_pendingVideoBuffer;
|
||||
latest_width = self->_pendingVideoWidth;
|
||||
latest_height = self->_pendingVideoHeight;
|
||||
latest_capture_uptime = self->_pendingVideoCaptureUptime;
|
||||
self->_pendingVideoBuffer = nullptr;
|
||||
self->_pendingVideoWidth = 0;
|
||||
self->_pendingVideoHeight = 0;
|
||||
self->_pendingVideoCaptureUptime = 0;
|
||||
self->_videoDeliveryScheduled = false;
|
||||
}
|
||||
|
||||
@@ -1347,11 +1626,12 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
}
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:
|
||||
@selector(rtcBridge:didReceivePixelBuffer:width:height:)]) {
|
||||
@selector(rtcBridge:didReceivePixelBuffer:width:height:captureUptime:)]) {
|
||||
[delegate rtcBridge:self
|
||||
didReceivePixelBuffer:latest_buffer
|
||||
width:latest_width
|
||||
height:latest_height];
|
||||
height:latest_height
|
||||
captureUptime:latest_capture_uptime];
|
||||
}
|
||||
CVPixelBufferRelease(latest_buffer);
|
||||
});
|
||||
@@ -1366,6 +1646,7 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
_pendingVideoBuffer = nullptr;
|
||||
_pendingVideoWidth = 0;
|
||||
_pendingVideoHeight = 0;
|
||||
_pendingVideoCaptureUptime = 0;
|
||||
_videoDeliveryScheduled = false;
|
||||
}
|
||||
if (pending_buffer) CVPixelBufferRelease(pending_buffer);
|
||||
@@ -1386,19 +1667,27 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
- (void)handleData:(const char *)data
|
||||
size:(size_t)size
|
||||
sourceID:(const char *)sourceID
|
||||
sourceIDSize:(size_t)sourceIDSize {
|
||||
sourceIDSize:(size_t)sourceIDSize
|
||||
generation:(uint64_t)generation {
|
||||
if (!data || size == 0 || !sourceID) return;
|
||||
const std::string source(sourceID, sourceIDSize);
|
||||
if (source == kControlStream) {
|
||||
RemoteAction action{};
|
||||
if (!action.from_json(std::string(data, size)) ||
|
||||
action.type != ControlType::host_infomation) {
|
||||
if (!action.from_json(std::string(data, size))) return;
|
||||
if (action.type == ControlType::video_settings_status) {
|
||||
[self notifyVideoSettings:action.vs generation:generation];
|
||||
return;
|
||||
}
|
||||
if (action.type != ControlType::host_infomation) return;
|
||||
const BOOL supports_video_settings = action.i.supports_video_settings;
|
||||
NSString *platform = [NSString stringWithUTF8String:
|
||||
crossdesk::HostPlatformName(action.i.platform)];
|
||||
NSString *host_name = [[NSString alloc]
|
||||
initWithBytes:action.i.host_name
|
||||
length:action.i.host_name_size
|
||||
encoding:NSUTF8StringEncoding];
|
||||
NSString *app_version = crossdesk::IsValidAppVersion(action.i.app_version)
|
||||
? [NSString stringWithUTF8String:action.i.app_version] : nil;
|
||||
NSMutableArray<NSString *> *display_names =
|
||||
[NSMutableArray arrayWithCapacity:action.i.display_num];
|
||||
NSMutableArray<NSValue *> *display_sizes =
|
||||
@@ -1419,14 +1708,18 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
}
|
||||
crossdesk::FreeRemoteAction(action);
|
||||
DispatchMain(^{
|
||||
if (![self isControllerGenerationActive:generation]) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:
|
||||
@selector(rtcBridge:didReceiveHostName:displayNames:
|
||||
displaySizes:)]) {
|
||||
@selector(rtcBridge:didReceiveHostName:appVersion:platform:displayNames:
|
||||
displaySizes:supportsVideoSettings:)]) {
|
||||
[delegate rtcBridge:self
|
||||
didReceiveHostName:host_name ?: @""
|
||||
appVersion:app_version ?: @""
|
||||
platform:platform
|
||||
displayNames:display_names
|
||||
displaySizes:display_sizes];
|
||||
displaySizes:display_sizes
|
||||
supportsVideoSettings:supports_video_settings];
|
||||
}
|
||||
});
|
||||
return;
|
||||
@@ -1649,19 +1942,31 @@ Params MakeParams(const RTCState &state, const std::string &user_id,
|
||||
}
|
||||
}
|
||||
|
||||
- (void)handleStats:(const MiniRtcNetTrafficStats *)stats mode:(TraversalMode)mode {
|
||||
- (void)handleStats:(const MiniRtcNetTrafficStats *)stats
|
||||
mode:(TraversalMode)mode
|
||||
generation:(uint64_t)generation {
|
||||
if (!stats) return;
|
||||
const NSUInteger bitrate = stats->total_inbound_stats.bitrate;
|
||||
const float loss = stats->video_inbound_stats.loss_rate;
|
||||
const BOOL using_turn = mode == TraversalMode::Relay;
|
||||
const auto traffic = [](const MiniRtcInboundStats &inbound,
|
||||
const MiniRtcOutboundStats &outbound) {
|
||||
return CrossDeskTrafficStats{inbound.bitrate, outbound.bitrate,
|
||||
inbound.loss_rate};
|
||||
};
|
||||
const CrossDeskNetworkStats snapshot{
|
||||
traffic(stats->video_inbound_stats, stats->video_outbound_stats),
|
||||
traffic(stats->audio_inbound_stats, stats->audio_outbound_stats),
|
||||
traffic(stats->data_inbound_stats, stats->data_outbound_stats),
|
||||
traffic(stats->total_inbound_stats, stats->total_outbound_stats),
|
||||
stats->rtt_ms, static_cast<BOOL>(stats->srtp_active),
|
||||
mode == TraversalMode::P2P ? CrossDeskTraversalModeDirect
|
||||
: mode == TraversalMode::Relay ? CrossDeskTraversalModeRelay
|
||||
: CrossDeskTraversalModeUnknown};
|
||||
DispatchMain(^{
|
||||
// Disconnect/reconnect can happen while this report waits on the UI queue.
|
||||
if (![self isControllerGenerationActive:generation]) return;
|
||||
id<CrossDeskRTCBridgeDelegate> delegate = self.delegate;
|
||||
if ([delegate respondsToSelector:
|
||||
@selector(rtcBridge:didUpdateBitrate:lossRate:usingTURN:)]) {
|
||||
[delegate rtcBridge:self
|
||||
didUpdateBitrate:bitrate
|
||||
lossRate:loss
|
||||
usingTURN:using_turn];
|
||||
@selector(rtcBridge:didUpdateNetworkStats:)]) {
|
||||
[delegate rtcBridge:self didUpdateNetworkStats:snapshot];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import SwiftUI
|
||||
import UIKit
|
||||
|
||||
enum HomeDestination: Hashable {
|
||||
case settings
|
||||
case announcements
|
||||
case announcement(AnnouncementSelection)
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@@ -11,12 +17,40 @@ struct ContentView: View {
|
||||
RemoteSessionView(session: session)
|
||||
.transition(.opacity)
|
||||
} else {
|
||||
ConnectionHomeView(session: session)
|
||||
.transition(.opacity)
|
||||
NavigationStack {
|
||||
ConnectionHomeView(session: session)
|
||||
.navigationTitle("")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
// Keep inbox and detail in the same value-based stack.
|
||||
// Mixing an isPresented inbox with a value-based detail
|
||||
// can reinsert the inbox above the detail on updates.
|
||||
.navigationDestination(for: HomeDestination.self) { destination in
|
||||
switch destination {
|
||||
case .settings:
|
||||
ServerSettingsView(session: session)
|
||||
case .announcements:
|
||||
AnnouncementInboxView(session: session, inbox: session.announcements)
|
||||
case .announcement(let selection):
|
||||
AnnouncementDetailView(inbox: session.announcements, selection: selection)
|
||||
}
|
||||
}
|
||||
}
|
||||
.toolbarBackground(Color(.systemGroupedBackground), for: .navigationBar)
|
||||
.toolbarBackground(.visible, for: .navigationBar)
|
||||
.transition(.opacity)
|
||||
}
|
||||
}
|
||||
.animation(.easeInOut(duration: 0.2), value: session.sessionVisible)
|
||||
.preferredColorScheme(session.sessionVisible ? .dark : .light)
|
||||
.sheet(isPresented: Binding(
|
||||
get: { session.privacyNoticeVisible },
|
||||
set: { if !$0 { session.dismissPrivacyNotice() } }
|
||||
)) {
|
||||
PrivacyConsentView(session: session)
|
||||
.presentationDetents([.large])
|
||||
.presentationDragIndicator(.hidden)
|
||||
.interactiveDismissDisabled()
|
||||
}
|
||||
.alert("连接提示", isPresented: Binding(
|
||||
get: { session.connectionFailureMessage != nil },
|
||||
set: { if !$0 { session.dismissConnectionFailure() } }
|
||||
@@ -30,17 +64,14 @@ struct ContentView: View {
|
||||
AppOrientation.update(to: .portrait)
|
||||
}
|
||||
if scenePhase == .active {
|
||||
session.refreshRecentConnectionPresenceAfterForeground()
|
||||
session.resumeVideoAfterForeground()
|
||||
session.applicationDidBecomeActive()
|
||||
}
|
||||
}
|
||||
.onChange(of: scenePhase) { phase in
|
||||
if phase == .active {
|
||||
session.refreshRecentConnectionPresenceAfterForeground()
|
||||
session.resumeVideoAfterForeground()
|
||||
session.applicationDidBecomeActive()
|
||||
} else if phase == .background {
|
||||
session.suspendVideoForBackground()
|
||||
session.suspendPresenceMonitoring()
|
||||
session.applicationDidEnterBackground()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,7 +161,6 @@ private struct ConnectionHomeView: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@FocusState private var remoteIDFocused: Bool
|
||||
@State private var passwordPromptVisible = false
|
||||
@State private var settingsVisible = false
|
||||
@State private var promptRemoteID = ""
|
||||
@State private var promptPassword = ""
|
||||
@State private var promptRememberPassword = false
|
||||
@@ -197,7 +227,6 @@ private struct ConnectionHomeView: View {
|
||||
Color(.systemGroupedBackground).ignoresSafeArea()
|
||||
|
||||
VStack(spacing: 0) {
|
||||
header
|
||||
remoteConnectionPanel
|
||||
.padding(.top, 24)
|
||||
recentConnectionsPanel
|
||||
@@ -212,6 +241,13 @@ private struct ConnectionHomeView: View {
|
||||
}
|
||||
|
||||
}
|
||||
.toolbar {
|
||||
if #available(iOS 26.0, *) {
|
||||
navigationToolbar.sharedBackgroundVisibility(.hidden)
|
||||
} else {
|
||||
navigationToolbar
|
||||
}
|
||||
}
|
||||
.background {
|
||||
KeyboardDismissTapView {
|
||||
remoteIDFocused = false
|
||||
@@ -230,11 +266,6 @@ private struct ConnectionHomeView: View {
|
||||
.presentationDetents([.height(340)])
|
||||
.presentationDragIndicator(.visible)
|
||||
}
|
||||
.sheet(isPresented: $settingsVisible) {
|
||||
ServerSettingsView(session: session)
|
||||
.presentationDetents([.fraction(0.80)])
|
||||
.presentationDragIndicator(.visible)
|
||||
}
|
||||
.alert("设备离线", isPresented: Binding(
|
||||
get: { session.deviceOfflineAlertVisible },
|
||||
set: { visible in
|
||||
@@ -251,32 +282,36 @@ private struct ConnectionHomeView: View {
|
||||
session.remoteID = formatted
|
||||
}
|
||||
}
|
||||
.onDisappear { remoteIDFocused = false }
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Label {
|
||||
Text(session.signalStatus)
|
||||
.font(.caption.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
} icon: {
|
||||
Image(systemName: signalSymbol)
|
||||
.font(.caption.weight(.bold))
|
||||
@ToolbarContentBuilder
|
||||
private var navigationToolbar: some ToolbarContent {
|
||||
ToolbarItem(placement: .navigationBarLeading) {
|
||||
if session.hasNetworkConsent {
|
||||
signalStatusBadge
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
} else {
|
||||
Button {
|
||||
remoteIDFocused = false
|
||||
session.showPrivacyNotice()
|
||||
} label: {
|
||||
signalStatusBadge
|
||||
.fixedSize(horizontal: true, vertical: false)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityHint("打开隐私政策")
|
||||
}
|
||||
.foregroundStyle(signalTint)
|
||||
.padding(.horizontal, 11)
|
||||
.frame(height: 34)
|
||||
.background(signalTint.opacity(0.11), in: Capsule())
|
||||
.overlay {
|
||||
Capsule()
|
||||
.stroke(signalTint.opacity(0.22), lineWidth: 1)
|
||||
}
|
||||
ToolbarItem(placement: .navigationBarTrailing) {
|
||||
NavigationLink(value: HomeDestination.announcements) {
|
||||
AnnouncementBadge(inbox: session.announcements)
|
||||
}
|
||||
|
||||
Spacer()
|
||||
|
||||
Button {
|
||||
settingsVisible = true
|
||||
} label: {
|
||||
.foregroundStyle(.primary)
|
||||
.disabled(session.isConnecting)
|
||||
}
|
||||
ToolbarItem(placement: .navigationBarTrailing) {
|
||||
NavigationLink(value: HomeDestination.settings) {
|
||||
Image(systemName: "gearshape")
|
||||
.font(.system(size: 18, weight: .semibold))
|
||||
.frame(width: 40, height: 40)
|
||||
@@ -285,9 +320,30 @@ private struct ConnectionHomeView: View {
|
||||
style: .continuous))
|
||||
}
|
||||
.foregroundStyle(.primary)
|
||||
.disabled(session.isConnecting)
|
||||
.accessibilityLabel("设置")
|
||||
}
|
||||
.padding(.top, 8)
|
||||
}
|
||||
|
||||
private var signalStatusBadge: some View {
|
||||
HStack(spacing: 6) {
|
||||
if session.hasNetworkConsent {
|
||||
Image(systemName: signalSymbol)
|
||||
.font(.caption.weight(.bold))
|
||||
}
|
||||
Text(session.signalStatus)
|
||||
.font(.caption.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
}
|
||||
.foregroundStyle(signalTint)
|
||||
.padding(.horizontal, 11)
|
||||
.frame(height: 34)
|
||||
.background(signalTint.opacity(0.11), in: Capsule())
|
||||
.overlay {
|
||||
Capsule()
|
||||
.stroke(signalTint.opacity(0.22), lineWidth: 1)
|
||||
}
|
||||
.contentShape(Capsule())
|
||||
}
|
||||
|
||||
private var remoteConnectionPanel: some View {
|
||||
@@ -470,6 +526,11 @@ private struct ConnectionHomeView: View {
|
||||
}
|
||||
|
||||
private func presentPasswordPrompt(for identifier: String) {
|
||||
guard session.hasNetworkConsent else {
|
||||
remoteIDFocused = false
|
||||
session.showPrivacyNotice()
|
||||
return
|
||||
}
|
||||
let trimmed = identifier.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else {
|
||||
remoteIDFocused = true
|
||||
@@ -511,6 +572,26 @@ private struct RecentConnectionCard: View {
|
||||
let connect: () -> Void
|
||||
let delete: () -> Void
|
||||
|
||||
private var platformColors: [Color] {
|
||||
switch connection.platform {
|
||||
case .windows:
|
||||
return [Color(red: 0.12, green: 0.38, blue: 0.70),
|
||||
Color(red: 0.20, green: 0.48, blue: 0.77)]
|
||||
case .linux:
|
||||
return [Color(red: 0.63, green: 0.31, blue: 0.08),
|
||||
Color(red: 0.73, green: 0.39, blue: 0.12)]
|
||||
case .macos:
|
||||
return [Color(red: 0.43, green: 0.29, blue: 0.68),
|
||||
Color(red: 0.55, green: 0.39, blue: 0.77)]
|
||||
case .ios:
|
||||
return [Color(red: 0.08, green: 0.43, blue: 0.40),
|
||||
Color(red: 0.12, green: 0.51, blue: 0.47)]
|
||||
case .unknown:
|
||||
return [Color(red: 0.35, green: 0.40, blue: 0.46),
|
||||
Color(red: 0.45, green: 0.49, blue: 0.55)]
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Button(action: connect) {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
@@ -520,13 +601,16 @@ private struct RecentConnectionCard: View {
|
||||
.resizable()
|
||||
.scaledToFill()
|
||||
} else {
|
||||
LinearGradient(colors: [
|
||||
Color(red: 0.18, green: 0.48, blue: 0.86),
|
||||
Color(red: 0.38, green: 0.68, blue: 0.96)
|
||||
], startPoint: .topLeading, endPoint: .bottomTrailing)
|
||||
Image(systemName: "display")
|
||||
.font(.system(size: 34, weight: .medium))
|
||||
.foregroundStyle(.white.opacity(0.9))
|
||||
LinearGradient(colors: platformColors,
|
||||
startPoint: .topLeading,
|
||||
endPoint: .bottomTrailing)
|
||||
Text(connection.platform.displayName)
|
||||
.font(.title3.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.8)
|
||||
.foregroundStyle(.white)
|
||||
.padding(8)
|
||||
.accessibilityLabel("被控端平台:\(connection.platform.displayName)")
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
@@ -669,87 +753,178 @@ private struct PasswordPromptView: View {
|
||||
|
||||
private struct ServerSettingsView: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var serverConfigurationExpanded = false
|
||||
@State private var usesCustomServer: Bool
|
||||
@State private var customServerHost: String
|
||||
@State private var customServerPort: String
|
||||
@State private var serverConfigurationError: String?
|
||||
@FocusState private var focusedServerField: ServerField?
|
||||
|
||||
private enum ServerField: Hashable {
|
||||
case host, port
|
||||
}
|
||||
|
||||
init(session: RemoteSessionModel) {
|
||||
self.session = session
|
||||
let isCustom = !session.usesOfficialServer
|
||||
_usesCustomServer = State(initialValue: isCustom)
|
||||
_customServerHost = State(initialValue: isCustom ? session.signalHost : "")
|
||||
_customServerPort = State(initialValue: isCustom ? session.signalPort : "")
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
Form {
|
||||
Section("鼠标控制") {
|
||||
Picker("控制模式", selection: $session.mouseControlMode) {
|
||||
ForEach(MouseControlMode.allCases) { mode in
|
||||
Text(mode.title).tag(mode)
|
||||
Form {
|
||||
Section("鼠标控制") {
|
||||
Picker("控制模式", selection: $session.mouseControlMode) {
|
||||
ForEach(MouseControlMode.allCases) { mode in
|
||||
Text(mode.title).tag(mode)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
Text(session.mouseControlMode.detail)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Section("画面偏好") {
|
||||
Picker("偏好模式", selection: $session.videoAdaptationPolicy) {
|
||||
ForEach(VideoAdaptationPolicy.allCases) { policy in
|
||||
Text(policy.title).tag(policy)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
Text(session.videoAdaptationPolicy.detail)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
}
|
||||
Section {
|
||||
DisclosureGroup(isExpanded: $serverConfigurationExpanded) {
|
||||
Toggle("使用自定义服务器", isOn: $usesCustomServer)
|
||||
if usesCustomServer {
|
||||
LabeledContent("地址") {
|
||||
TextField("填写服务器地址", text: $customServerHost)
|
||||
.textInputAutocapitalization(.never)
|
||||
.autocorrectionDisabled()
|
||||
.keyboardType(.URL)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.focused($focusedServerField, equals: .host)
|
||||
.submitLabel(.next)
|
||||
.onSubmit { focusedServerField = .port }
|
||||
.accessibilityLabel("服务器地址")
|
||||
}
|
||||
LabeledContent("端口") {
|
||||
TextField("填写端口", text: $customServerPort)
|
||||
.keyboardType(.numberPad)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.focused($focusedServerField, equals: .port)
|
||||
.accessibilityLabel("服务器端口")
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
Text(session.mouseControlMode.detail)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Section("视频编解码") {
|
||||
Picker("处理方式", selection: $session.videoCodecMode) {
|
||||
ForEach(VideoCodecMode.allCases) { mode in
|
||||
Text(mode.title).tag(mode)
|
||||
}
|
||||
if usesCustomServer {
|
||||
Text("结束编辑后生效。关闭开关可立即切回默认配置。")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
Text(session.videoCodecMode.detail)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Text("修改后从下一次连接开始生效。")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.tertiary)
|
||||
}
|
||||
Section("画面偏好") {
|
||||
Picker("偏好模式", selection: $session.videoAdaptationPolicy) {
|
||||
ForEach(VideoAdaptationPolicy.allCases) { policy in
|
||||
Text(policy.title).tag(policy)
|
||||
}
|
||||
} label: {
|
||||
HStack {
|
||||
Text("服务器")
|
||||
Spacer()
|
||||
Text(usesCustomServer ? "自定义" : "默认")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
|
||||
Text(session.videoAdaptationPolicy.detail)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Text("修改后从下一次连接开始生效。")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.tertiary)
|
||||
}
|
||||
Section {
|
||||
TextField("信令服务器", text: $session.signalHost)
|
||||
.textInputAutocapitalization(.never)
|
||||
.autocorrectionDisabled()
|
||||
TextField("信令端口", text: $session.signalPort)
|
||||
.keyboardType(.numberPad)
|
||||
} header: {
|
||||
Text("服务器")
|
||||
} footer: {
|
||||
Text(session.localIdentity.isEmpty
|
||||
? "正在获取本机 ID…"
|
||||
: "本机 ID \(session.localIdentity)")
|
||||
.font(.caption2.monospacedDigit())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .center)
|
||||
.padding(.top, 16)
|
||||
.textSelection(.enabled)
|
||||
} footer: {
|
||||
if let serverConfigurationError {
|
||||
Text(serverConfigurationError)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
if let warning = session.identityStorageWarning {
|
||||
Text(warning)
|
||||
.foregroundStyle(.orange)
|
||||
}
|
||||
Text(!session.hasNetworkConsent ? "完成隐私授权后登记本机身份" : session.localIdentity.isEmpty
|
||||
? "正在获取本机 ID…"
|
||||
: "本机 ID \(session.localIdentity)")
|
||||
.font(.caption2.monospacedDigit())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .center)
|
||||
.padding(.top, 16)
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
PrivacySettingsSection(session: session)
|
||||
Section {
|
||||
NavigationLink("关于") {
|
||||
ThirdPartyLicensesView()
|
||||
}
|
||||
}
|
||||
.navigationTitle("设置")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button("应用") {
|
||||
session.configureBridge()
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
ToolbarItem(placement: .cancellationAction) {
|
||||
Button("取消") { dismiss() }
|
||||
}
|
||||
.navigationTitle("设置")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.scrollDismissesKeyboard(.interactively)
|
||||
.background {
|
||||
KeyboardDismissTapView {
|
||||
focusedServerField = nil
|
||||
}
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
.onChange(of: serverConfigurationExpanded) { expanded in
|
||||
if !expanded {
|
||||
focusedServerField = nil
|
||||
validateAndApplyServerConfiguration()
|
||||
}
|
||||
}
|
||||
.onChange(of: usesCustomServer) { isCustom in
|
||||
if !isCustom { useDefaultServer() }
|
||||
}
|
||||
.onChange(of: focusedServerField) { field in
|
||||
if field == nil { validateAndApplyServerConfiguration() }
|
||||
}
|
||||
.onDisappear {
|
||||
// Native back navigation can remove the view before focus updates.
|
||||
focusedServerField = nil
|
||||
validateAndApplyServerConfiguration()
|
||||
}
|
||||
.toolbar {
|
||||
ToolbarItemGroup(placement: .keyboard) {
|
||||
Spacer()
|
||||
Button("完成") {
|
||||
focusedServerField = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func useDefaultServer() {
|
||||
serverConfigurationError = nil
|
||||
focusedServerField = nil
|
||||
customServerHost = ""
|
||||
customServerPort = ""
|
||||
guard !session.usesOfficialServer else { return }
|
||||
session.restoreOfficialServerConfiguration()
|
||||
session.configureBridge()
|
||||
}
|
||||
|
||||
private func validateAndApplyServerConfiguration() {
|
||||
guard usesCustomServer else { return }
|
||||
let host = customServerHost.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let port = customServerPort.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !host.isEmpty else {
|
||||
serverConfigurationError = "请输入服务器地址,或关闭“使用自定义服务器”。"
|
||||
return
|
||||
}
|
||||
guard let portNumber = Int(port), (1...65535).contains(portNumber) else {
|
||||
serverConfigurationError = "请输入 1–65535 范围内的端口,或关闭“使用自定义服务器”。"
|
||||
return
|
||||
}
|
||||
serverConfigurationError = nil
|
||||
customServerHost = host
|
||||
customServerPort = String(portNumber)
|
||||
if session.signalHost != host || session.signalPort != customServerPort {
|
||||
session.signalHost = host
|
||||
session.signalPort = customServerPort
|
||||
session.configureBridge()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>CA92.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>C617.1</string>
|
||||
<string>3B52.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>35F9.1</string>
|
||||
<string>8FFB.1</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,56 @@
|
||||
import Foundation
|
||||
|
||||
/// Consent is deliberately independent of existing device IDs and credentials.
|
||||
/// A missing value (including an upgrade from older versions) is not consent.
|
||||
struct PrivacyPreferences {
|
||||
private let defaults: UserDefaults
|
||||
private let networkKey = "crossdesk.mobile.network-consent.v1"
|
||||
private let thumbnailsKey = "crossdesk.mobile.save-thumbnails.v1"
|
||||
|
||||
init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
var hasNetworkConsent: Bool { defaults.bool(forKey: networkKey) }
|
||||
var savesThumbnails: Bool {
|
||||
hasNetworkConsent && defaults.bool(forKey: thumbnailsKey)
|
||||
}
|
||||
|
||||
func setNetworkConsent(_ allowed: Bool) {
|
||||
defaults.set(allowed, forKey: networkKey)
|
||||
if !allowed { defaults.set(false, forKey: thumbnailsKey) }
|
||||
}
|
||||
|
||||
func setSavesThumbnails(_ allowed: Bool) {
|
||||
defaults.set(allowed && hasNetworkConsent, forKey: thumbnailsKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refusal dismisses the notice for this visit only. A background/foreground
|
||||
/// round trip starts another visit; transient inactive states do not.
|
||||
struct PrivacyNoticeState {
|
||||
private(set) var isVisible: Bool
|
||||
private var needsPresentationOnActivation = false
|
||||
|
||||
init(hasNetworkConsent: Bool) {
|
||||
isVisible = !hasNetworkConsent
|
||||
}
|
||||
|
||||
mutating func show() {
|
||||
isVisible = true
|
||||
}
|
||||
|
||||
mutating func dismiss() {
|
||||
isVisible = false
|
||||
}
|
||||
|
||||
mutating func didEnterBackground() {
|
||||
needsPresentationOnActivation = true
|
||||
}
|
||||
|
||||
mutating func didBecomeActive(hasNetworkConsent: Bool) {
|
||||
guard needsPresentationOnActivation else { return }
|
||||
needsPresentationOnActivation = false
|
||||
isVisible = !hasNetworkConsent
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import SwiftUI
|
||||
|
||||
struct PrivacyConsentView: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@State private var hasReadPolicy = false
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
ScrollView {
|
||||
PrivacyPolicyDocument()
|
||||
.padding(.horizontal, 20)
|
||||
.padding(.vertical, 20)
|
||||
}
|
||||
.background(Color(.systemBackground))
|
||||
.safeAreaInset(edge: .bottom, spacing: 0) {
|
||||
consentActions
|
||||
}
|
||||
.navigationTitle("隐私政策")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
}
|
||||
|
||||
private var consentActions: some View {
|
||||
VStack(spacing: 0) {
|
||||
Divider()
|
||||
|
||||
VStack(spacing: 12) {
|
||||
Toggle(isOn: $hasReadPolicy) {
|
||||
Text("我已阅读并同意《隐私政策》")
|
||||
.font(.subheadline)
|
||||
}
|
||||
.toggleStyle(ConsentCheckboxStyle())
|
||||
|
||||
Button {
|
||||
guard hasReadPolicy else { return }
|
||||
session.acceptNetworkConsent()
|
||||
} label: {
|
||||
Text("同意并继续")
|
||||
.font(.body.weight(.semibold))
|
||||
.frame(maxWidth: .infinity, minHeight: 24)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.controlSize(.large)
|
||||
.tint(.blue)
|
||||
.disabled(!hasReadPolicy || !PrivacyPolicyDocument.isAvailable)
|
||||
|
||||
Button {
|
||||
session.declineNetworkConsent()
|
||||
} label: {
|
||||
Text("暂不同意")
|
||||
.font(.body)
|
||||
.frame(maxWidth: .infinity, minHeight: 44)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
.padding(.horizontal, 20)
|
||||
.padding(.vertical, 12)
|
||||
}
|
||||
.background(Color(.systemBackground))
|
||||
}
|
||||
}
|
||||
|
||||
private struct ConsentCheckboxStyle: ToggleStyle {
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
Button {
|
||||
configuration.isOn.toggle()
|
||||
} label: {
|
||||
HStack(alignment: .center, spacing: 9) {
|
||||
Image(systemName: configuration.isOn ? "checkmark.square.fill" : "square")
|
||||
.font(.title3)
|
||||
.foregroundStyle(configuration.isOn ? Color.accentColor : .secondary)
|
||||
configuration.label
|
||||
.foregroundStyle(.primary)
|
||||
.multilineTextAlignment(.leading)
|
||||
}
|
||||
.frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel("我已阅读并同意隐私政策")
|
||||
.accessibilityValue(configuration.isOn ? "已勾选" : "未勾选")
|
||||
}
|
||||
}
|
||||
|
||||
struct PrivacySettingsSection: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@State private var confirmThumbnails = false
|
||||
@State private var confirmClear = false
|
||||
|
||||
var body: some View {
|
||||
Section {
|
||||
NavigationLink {
|
||||
PrivacyAuthorizationView(session: session)
|
||||
} label: {
|
||||
HStack {
|
||||
Text("隐私与授权")
|
||||
Spacer()
|
||||
Text(session.hasNetworkConsent ? "已授权" : "未授权")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
Toggle("保存远程画面预览", isOn: Binding(
|
||||
get: { session.savesConnectionThumbnails },
|
||||
set: { enabled in
|
||||
if enabled { confirmThumbnails = true }
|
||||
else { session.setSavesConnectionThumbnails(false) }
|
||||
}
|
||||
))
|
||||
.disabled(!session.hasNetworkConsent || session.thumbnailCleanupInProgress)
|
||||
Button(session.thumbnailCleanupInProgress ? "正在清除…" : "清除预览图", role: .destructive) {
|
||||
confirmClear = true
|
||||
}
|
||||
.disabled(session.thumbnailCleanupInProgress)
|
||||
if let error = session.thumbnailCleanupError {
|
||||
Text(error).font(.footnote).foregroundStyle(.secondary)
|
||||
}
|
||||
} header: {
|
||||
Text("隐私")
|
||||
} footer: {
|
||||
Text("画面预览默认关闭。开启后,从下一次连接起保存一张远程画面到本机,显示在最近连接中,不上传且不纳入设备备份。关闭开关会清除已有预览;连接记录和接收的文件不受影响。")
|
||||
}
|
||||
.alert("保存远程画面预览?", isPresented: $confirmThumbnails) {
|
||||
Button("开启保存") { session.setSavesConnectionThumbnails(true) }
|
||||
Button("取消", role: .cancel) { }
|
||||
} message: {
|
||||
Text("预览可能包含远程电脑上的个人或工作信息。开启后,每次连接会自动将一张画面保存在本机并显示在最近连接中。你可以随时关闭并清除。")
|
||||
}
|
||||
.alert("清除预览图?", isPresented: $confirmClear) {
|
||||
Button("清除", role: .destructive) { session.clearConnectionThumbnails() }
|
||||
Button("取消", role: .cancel) { }
|
||||
} message: {
|
||||
Text(session.savesConnectionThumbnails
|
||||
? "将删除本机保存的所有远程预览图,保留连接记录、密码和接收的文件。后续连接仍会保存新的预览图。"
|
||||
: "将删除本机保存的所有远程预览图,保留连接记录、密码和接收的文件。")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct PrivacyAuthorizationView: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
@State private var confirmWithdrawal = false
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
Section {
|
||||
LabeledContent("授权状态", value: session.hasNetworkConsent ? "已授权" : "未授权")
|
||||
NavigationLink("隐私政策") { PrivacyPolicyView() }
|
||||
} footer: {
|
||||
if !session.hasNetworkConsent {
|
||||
Text("授权后可使用远程连接。")
|
||||
}
|
||||
}
|
||||
|
||||
Section {
|
||||
if session.hasNetworkConsent {
|
||||
Button("撤回隐私授权", role: .destructive) {
|
||||
confirmWithdrawal = true
|
||||
}
|
||||
} else {
|
||||
Button("阅读并授权") { session.showPrivacyNotice() }
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("隐私与授权")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.alert("是否撤回隐私授权?", isPresented: $confirmWithdrawal) {
|
||||
Button("撤回授权", role: .destructive) { session.revokeNetworkConsent() }
|
||||
Button("取消", role: .cancel) { }
|
||||
} message: {
|
||||
Text("将停止远程连接、关闭画面预览保存并清除已有预览。连接记录和接收文件会保留,已有服务端数据不会删除。您可随时重新授权。")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bundled policy is readable before any network consent or external request.
|
||||
private struct PrivacyPolicyDocument: View {
|
||||
private static let text: String? = {
|
||||
guard let url = Bundle.main.url(forResource: "PRIVACY", withExtension: "md"),
|
||||
let text = try? String(contentsOf: url, encoding: .utf8),
|
||||
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }
|
||||
// The app's interface is Chinese; show the complete Chinese translation.
|
||||
if let start = text.range(of: "## 中文\n"),
|
||||
let end = text.range(of: "## English", range: start.upperBound..<text.endIndex) {
|
||||
return String(text[start.upperBound..<end.lowerBound])
|
||||
}
|
||||
return text
|
||||
}()
|
||||
static var isAvailable: Bool { text != nil }
|
||||
private static let paragraphs = (text ?? "隐私政策暂时无法读取,请拒绝联网并重新安装应用。")
|
||||
.components(separatedBy: "\n\n")
|
||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
.filter { !$0.isEmpty && $0 != "---" }
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
ForEach(Self.paragraphs.indices, id: \.self) { index in
|
||||
let paragraph = Self.paragraphs[index]
|
||||
if paragraph.hasPrefix("#") {
|
||||
Text(paragraph.trimmingCharacters(in: CharacterSet(charactersIn: "# ")))
|
||||
.font(.headline)
|
||||
.padding(.top, 4)
|
||||
} else if paragraph.hasPrefix("更新日期:") {
|
||||
Text(paragraph)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
Text((try? AttributedString(markdown: paragraph,
|
||||
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)))
|
||||
?? AttributedString(paragraph))
|
||||
.font(.body)
|
||||
.lineSpacing(4)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
|
||||
struct PrivacyPolicyView: View {
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
PrivacyPolicyDocument().padding()
|
||||
}
|
||||
.navigationTitle("隐私政策")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import Foundation
|
||||
|
||||
enum RemoteHostPlatform: String, Codable {
|
||||
case unknown, windows, macos, linux, ios
|
||||
|
||||
var displayName: String {
|
||||
switch self {
|
||||
case .windows: return "Windows"
|
||||
case .macos: return "macOS"
|
||||
case .linux: return "Linux"
|
||||
case .ios: return "iOS"
|
||||
case .unknown: return "未知"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RecentConnection: Codable, Identifiable, Equatable {
|
||||
let remoteID: String
|
||||
var displayName: String
|
||||
var lastConnectedAt: Date
|
||||
var remembersPassword: Bool
|
||||
var thumbnailFileName: String?
|
||||
var platform: RemoteHostPlatform
|
||||
|
||||
var id: String { remoteID }
|
||||
|
||||
init(remoteID: String, displayName: String, lastConnectedAt: Date,
|
||||
remembersPassword: Bool, thumbnailFileName: String?,
|
||||
platform: RemoteHostPlatform = .unknown) {
|
||||
self.remoteID = remoteID
|
||||
self.displayName = displayName
|
||||
self.lastConnectedAt = lastConnectedAt
|
||||
self.remembersPassword = remembersPassword
|
||||
self.thumbnailFileName = thumbnailFileName
|
||||
self.platform = platform
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case remoteID, displayName, lastConnectedAt, remembersPassword, thumbnailFileName, platform
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let values = try decoder.container(keyedBy: CodingKeys.self)
|
||||
remoteID = try values.decode(String.self, forKey: .remoteID)
|
||||
displayName = try values.decode(String.self, forKey: .displayName)
|
||||
lastConnectedAt = try values.decode(Date.self, forKey: .lastConnectedAt)
|
||||
remembersPassword = try values.decode(Bool.self, forKey: .remembersPassword)
|
||||
thumbnailFileName = try values.decodeIfPresent(String.self, forKey: .thumbnailFileName)
|
||||
// Adding platform metadata must not discard records saved by older apps.
|
||||
platform = (try? values.decode(RemoteHostPlatform.self, forKey: .platform)) ?? .unknown
|
||||
}
|
||||
|
||||
mutating func updateHostInfo(name: String, platform: RemoteHostPlatform) {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !trimmed.isEmpty { displayName = trimmed }
|
||||
self.platform = platform
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import Foundation
|
||||
|
||||
struct RemoteTrafficStatistics {
|
||||
var inboundBitrate: UInt32 = 0
|
||||
var outboundBitrate: UInt32 = 0
|
||||
var lossRate: Float = 0
|
||||
}
|
||||
|
||||
struct RemoteNetworkReport {
|
||||
enum Mode { case unknown, direct, relay }
|
||||
|
||||
var video = RemoteTrafficStatistics()
|
||||
var audio = RemoteTrafficStatistics()
|
||||
var data = RemoteTrafficStatistics()
|
||||
var total = RemoteTrafficStatistics()
|
||||
var mode: Mode = .unknown
|
||||
var srtpActive = false
|
||||
var rttMilliseconds: Double = -1
|
||||
}
|
||||
|
||||
struct RemoteNetworkSnapshot {
|
||||
var report: RemoteNetworkReport?
|
||||
var framesPerSecond = 0
|
||||
var videoLatencyMilliseconds: Double?
|
||||
var rttMilliseconds: Double?
|
||||
|
||||
var connectionMode: String {
|
||||
switch report?.mode {
|
||||
case .direct: return "P2P 直连"
|
||||
case .relay: return "TURN 中继"
|
||||
default: return "—"
|
||||
}
|
||||
}
|
||||
|
||||
static func bitrate(_ value: UInt32?) -> String {
|
||||
guard let value else { return "—" }
|
||||
if value >= 1_000_000 {
|
||||
return String(format: "%.1f Mbps", Double(value) / 1_000_000)
|
||||
}
|
||||
if value >= 1_000 {
|
||||
return String(format: "%.0f Kbps", Double(value) / 1_000)
|
||||
}
|
||||
return "\(value) bps"
|
||||
}
|
||||
|
||||
static func lossRate(_ value: Float?) -> String {
|
||||
guard let value, value.isFinite, value >= 0 else { return "—" }
|
||||
// MiniRTC's total is the sum of media fractions, as on desktop.
|
||||
return String(format: "%.1f%%", value * 100)
|
||||
}
|
||||
|
||||
static func latency(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite, value >= 0 else { return "—" }
|
||||
return value < 1 ? "<1 ms" : String(format: "%.0f ms", value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Main-thread presentation statistics. Time is monotonic and injectable so
|
||||
/// missing reports, idle video and reconnections have deterministic behavior.
|
||||
struct RemoteNetworkStatistics {
|
||||
private var report: RemoteNetworkReport?
|
||||
private var reportTime: TimeInterval = 0
|
||||
private var averageRTT: Double?
|
||||
private var rttTime: TimeInterval = 0
|
||||
private var lastFrameID: UInt64 = 0
|
||||
private var frames: [(time: TimeInterval, latency: Double?)] = []
|
||||
private var displayedSnapshot = RemoteNetworkSnapshot()
|
||||
private var displayTime: TimeInterval?
|
||||
|
||||
mutating func receive(_ report: RemoteNetworkReport, at now: TimeInterval) {
|
||||
self.report = report
|
||||
reportTime = now
|
||||
let rtt = report.rttMilliseconds
|
||||
guard rtt.isFinite, rtt >= 0, rtt <= 2_000 else { return }
|
||||
if let previous = averageRTT, now - rttTime < 3 {
|
||||
averageRTT = previous + 0.25 * (rtt - previous)
|
||||
} else {
|
||||
averageRTT = rtt
|
||||
}
|
||||
rttTime = now
|
||||
}
|
||||
|
||||
mutating func recordSubmittedFrame(id: UInt64, captureUptime: TimeInterval,
|
||||
at now: TimeInterval) {
|
||||
// Cached redraws and foreground resubmission are not new video frames.
|
||||
guard id > lastFrameID else { return }
|
||||
lastFrameID = id
|
||||
let latency = (now - captureUptime) * 1_000
|
||||
let valid = captureUptime > 0 && latency.isFinite && (0...5_000).contains(latency)
|
||||
frames.removeAll { now - $0.time >= 1 }
|
||||
frames.append((now, valid ? latency : nil))
|
||||
if frames.count > 240 { frames.removeFirst(frames.count - 240) }
|
||||
}
|
||||
|
||||
mutating func resetVideo() {
|
||||
frames.removeAll(keepingCapacity: true)
|
||||
displayedSnapshot.framesPerSecond = 0
|
||||
displayedSnapshot.videoLatencyMilliseconds = nil
|
||||
}
|
||||
|
||||
/// SwiftUI also redraws this menu for every video frame. A periodic view
|
||||
/// schedules updates but does not throttle those redraws, so freeze the
|
||||
/// displayed measurements between one-second samples.
|
||||
mutating func displaySnapshot(at now: TimeInterval) -> RemoteNetworkSnapshot {
|
||||
if let displayTime, now - displayTime < 1 {
|
||||
return displayedSnapshot
|
||||
}
|
||||
displayedSnapshot = snapshot(at: now)
|
||||
displayTime = now
|
||||
return displayedSnapshot
|
||||
}
|
||||
|
||||
func snapshot(at now: TimeInterval) -> RemoteNetworkSnapshot {
|
||||
let recentFrames = frames.filter { now - $0.time < 1 }
|
||||
let delays = recentFrames.compactMap(\.latency)
|
||||
return RemoteNetworkSnapshot(
|
||||
report: now - reportTime < 3 ? report : nil,
|
||||
framesPerSecond: recentFrames.count,
|
||||
videoLatencyMilliseconds: delays.isEmpty ? nil : delays.reduce(0, +) / Double(delays.count),
|
||||
rttMilliseconds: now - rttTime < 3 ? averageRTT : nil
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -42,43 +42,6 @@ enum MouseControlMode: String, CaseIterable, Identifiable {
|
||||
}
|
||||
}
|
||||
|
||||
enum VideoCodecMode: String, CaseIterable, Identifiable {
|
||||
case hardware
|
||||
case software
|
||||
|
||||
private static let defaultsKey = "crossdesk.mobile.video-codec-mode"
|
||||
|
||||
var id: String { rawValue }
|
||||
|
||||
var title: String {
|
||||
switch self {
|
||||
case .hardware: return "硬件"
|
||||
case .software: return "软件"
|
||||
}
|
||||
}
|
||||
|
||||
var detail: String {
|
||||
switch self {
|
||||
case .hardware:
|
||||
return "使用 VideoToolbox,延迟和耗电更低,推荐日常使用。"
|
||||
case .software:
|
||||
return "使用 OpenH264 软件编解码,适合兼容性测试。"
|
||||
}
|
||||
}
|
||||
|
||||
static var saved: VideoCodecMode {
|
||||
guard let rawValue = UserDefaults.standard.string(forKey: defaultsKey),
|
||||
let mode = VideoCodecMode(rawValue: rawValue) else {
|
||||
return .hardware
|
||||
}
|
||||
return mode
|
||||
}
|
||||
|
||||
func save() {
|
||||
UserDefaults.standard.set(rawValue, forKey: Self.defaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
enum VideoAdaptationPolicy: String, CaseIterable, Identifiable {
|
||||
case frameRatePriority
|
||||
case qualityPriority
|
||||
@@ -131,22 +94,15 @@ enum VideoAdaptationPolicy: String, CaseIterable, Identifiable {
|
||||
private struct RemoteVideoFrame {
|
||||
let pixelBuffer: CVPixelBuffer
|
||||
let encodedSize: CGSize
|
||||
}
|
||||
|
||||
struct RecentConnection: Codable, Identifiable, Equatable {
|
||||
let remoteID: String
|
||||
var displayName: String
|
||||
var lastConnectedAt: Date
|
||||
var remembersPassword: Bool
|
||||
var thumbnailFileName: String?
|
||||
|
||||
var id: String { remoteID }
|
||||
let id: UInt64
|
||||
let captureUptime: TimeInterval
|
||||
}
|
||||
|
||||
private enum RecentConnectionStore {
|
||||
private static let defaultsKey = "crossdesk.mobile.recent-connections.v1"
|
||||
private static let thumbnailQueue =
|
||||
DispatchQueue(label: "cn.crossdesk.mobile.thumbnails", qos: .utility)
|
||||
private static let thumbnails = ThumbnailFileStore(directory:
|
||||
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("RecentConnectionThumbnails", isDirectory: true))
|
||||
private static let context = CIContext(options: [.cacheIntermediates: false])
|
||||
|
||||
static func load() -> [RecentConnection] {
|
||||
@@ -163,85 +119,54 @@ private enum RecentConnectionStore {
|
||||
UserDefaults.standard.set(data, forKey: defaultsKey)
|
||||
}
|
||||
|
||||
static func thumbnailURL(fileName: String) -> URL? {
|
||||
guard let directory = thumbnailDirectory() else { return nil }
|
||||
return directory.appendingPathComponent(fileName, isDirectory: false)
|
||||
static func thumbnailURL(fileName: String) -> URL {
|
||||
thumbnails.url(for: fileName)
|
||||
}
|
||||
|
||||
private static func thumbnailFileName(for remoteID: String) -> String {
|
||||
let safeID = remoteID.filter { $0.isLetter || $0.isNumber || $0 == "-" }
|
||||
return "\(safeID.isEmpty ? "remote" : safeID).jpg"
|
||||
}
|
||||
|
||||
static func captureThumbnail(from pixelBuffer: CVPixelBuffer,
|
||||
remoteID: String,
|
||||
completion: @escaping (String?) -> Void) {
|
||||
thumbnailQueue.async {
|
||||
let fileName: String? = autoreleasepool {
|
||||
let image = CIImage(cvPixelBuffer: pixelBuffer)
|
||||
let targetSize = CGSize(width: 640, height: 360)
|
||||
guard image.extent.width > 0, image.extent.height > 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Scale in Core Image before materializing a CGImage. Creating
|
||||
// a full 4K bitmap and then drawing it into a thumbnail can add
|
||||
// tens of megabytes to the first-frame memory peak.
|
||||
let scale = max(targetSize.width / image.extent.width,
|
||||
targetSize.height / image.extent.height)
|
||||
let scaled = image.transformed(by: CGAffineTransform(
|
||||
scaleX: scale,
|
||||
y: scale
|
||||
))
|
||||
let cropRect = CGRect(
|
||||
x: scaled.extent.midX - targetSize.width / 2,
|
||||
y: scaled.extent.midY - targetSize.height / 2,
|
||||
width: targetSize.width,
|
||||
height: targetSize.height
|
||||
).integral
|
||||
guard let thumbnailImage = context.createCGImage(
|
||||
scaled.cropped(to: cropRect),
|
||||
from: cropRect
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let safeID = remoteID.filter {
|
||||
$0.isLetter || $0.isNumber || $0 == "-"
|
||||
}
|
||||
let name = "\(safeID.isEmpty ? "remote" : safeID).jpg"
|
||||
guard let url = thumbnailURL(fileName: name),
|
||||
let data = UIImage(cgImage: thumbnailImage)
|
||||
.jpegData(compressionQuality: 0.78) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
do {
|
||||
try data.write(to: url, options: .atomic)
|
||||
return name
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
DispatchQueue.main.async { completion(fileName) }
|
||||
let name = thumbnailFileName(for: remoteID)
|
||||
thumbnails.save(fileName: name, makeData: {
|
||||
let image = CIImage(cvPixelBuffer: pixelBuffer)
|
||||
let targetSize = CGSize(width: 640, height: 360)
|
||||
guard image.extent.width > 0, image.extent.height > 0 else { return nil }
|
||||
// Scale before materializing a bitmap to avoid a full-size frame copy.
|
||||
let scale = max(targetSize.width / image.extent.width,
|
||||
targetSize.height / image.extent.height)
|
||||
let scaled = image.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
|
||||
let cropRect = CGRect(x: scaled.extent.midX - targetSize.width / 2,
|
||||
y: scaled.extent.midY - targetSize.height / 2,
|
||||
width: targetSize.width, height: targetSize.height).integral
|
||||
guard let thumbnailImage = context.createCGImage(scaled.cropped(to: cropRect),
|
||||
from: cropRect) else { return nil }
|
||||
return UIImage(cgImage: thumbnailImage).jpegData(compressionQuality: 0.78)
|
||||
}) { name in
|
||||
DispatchQueue.main.async { completion(name) }
|
||||
}
|
||||
}
|
||||
|
||||
static func removeThumbnail(fileName: String?) {
|
||||
guard let fileName, let url = thumbnailURL(fileName: fileName) else { return }
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
static func removeThumbnail(for connection: RecentConnection) {
|
||||
// The first capture may still be queued, before its filename has been
|
||||
// attached to the recent connection. Delete that pending file too.
|
||||
let pendingFileName = thumbnailFileName(for: connection.remoteID)
|
||||
thumbnails.remove(fileName: pendingFileName)
|
||||
if let fileName = connection.thumbnailFileName, fileName != pendingFileName {
|
||||
thumbnails.remove(fileName: fileName)
|
||||
}
|
||||
}
|
||||
|
||||
private static func thumbnailDirectory() -> URL? {
|
||||
guard let base = FileManager.default.urls(for: .applicationSupportDirectory,
|
||||
in: .userDomainMask).first else {
|
||||
return nil
|
||||
}
|
||||
let directory = base.appendingPathComponent("RecentConnectionThumbnails",
|
||||
isDirectory: true)
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: directory,
|
||||
withIntermediateDirectories: true)
|
||||
return directory
|
||||
} catch {
|
||||
return nil
|
||||
static func removeAllThumbnails(completion: @escaping (Bool) -> Void) {
|
||||
thumbnails.removeAll { success in
|
||||
DispatchQueue.main.async { completion(success) }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private enum ConnectionCredentialStore {
|
||||
@@ -356,22 +281,34 @@ private final class RemoteAudioPlayer {
|
||||
}
|
||||
|
||||
final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDelegate {
|
||||
@Published var signalHost = "api.crossdesk.cn"
|
||||
@Published var signalPort = "9099"
|
||||
static let officialSignalHost = "api.crossdesk.cn"
|
||||
static let officialSignalPort = "9099"
|
||||
|
||||
private let privacyPreferences = PrivacyPreferences()
|
||||
@Published private(set) var hasNetworkConsent = PrivacyPreferences().hasNetworkConsent
|
||||
@Published private var privacyNotice = PrivacyNoticeState(
|
||||
hasNetworkConsent: PrivacyPreferences().hasNetworkConsent
|
||||
)
|
||||
@Published private(set) var savesConnectionThumbnails = PrivacyPreferences().savesThumbnails
|
||||
@Published private(set) var thumbnailCleanupInProgress = false
|
||||
@Published private(set) var thumbnailCleanupError: String?
|
||||
private var thumbnailGeneration = UUID()
|
||||
|
||||
@Published var signalHost = RemoteSessionModel.officialSignalHost
|
||||
@Published var signalPort = RemoteSessionModel.officialSignalPort
|
||||
@Published var mouseControlMode = MouseControlMode.saved {
|
||||
didSet { mouseControlMode.save() }
|
||||
}
|
||||
@Published var videoCodecMode = VideoCodecMode.saved {
|
||||
didSet { videoCodecMode.save() }
|
||||
}
|
||||
@Published var videoAdaptationPolicy = VideoAdaptationPolicy.saved {
|
||||
didSet { videoAdaptationPolicy.save() }
|
||||
}
|
||||
@Published private(set) var videoSettings = RemoteVideoSettingsState()
|
||||
@Published var remoteID = ""
|
||||
@Published var password = ""
|
||||
@Published private(set) var signalStatus = "正在连接信令服务"
|
||||
@Published private(set) var signalStatus = "等待隐私授权"
|
||||
@Published private(set) var connectionStatus = "未连接"
|
||||
@Published private(set) var localIdentity = ""
|
||||
@Published private(set) var identityStorageWarning: String?
|
||||
@Published private(set) var isConnecting = false
|
||||
@Published private(set) var isConnected = false
|
||||
@Published private(set) var sessionVisible = false
|
||||
@@ -382,9 +319,8 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
@Published private(set) var remoteCursorPositionRevision: UInt64 = 0
|
||||
@Published private(set) var remoteCursorVisualOffset = CGPoint.zero
|
||||
@Published private(set) var hasRemoteCursorState = false
|
||||
@Published private(set) var bitrate: UInt = 0
|
||||
@Published private(set) var lossRate: Float = 0
|
||||
@Published private(set) var usingTURN = false
|
||||
private var networkStatistics = RemoteNetworkStatistics()
|
||||
private var videoFrameID: UInt64 = 0
|
||||
@Published private(set) var displays: [String] = ["显示器 1"]
|
||||
@Published private(set) var displaySizes: [CGSize] = []
|
||||
@Published var selectedDisplay = 0
|
||||
@@ -398,10 +334,19 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
@Published private(set) var recentConnectionPresence: [String: Bool] = [:]
|
||||
@Published private(set) var deviceOfflineAlertVisible = false
|
||||
@Published private(set) var connectionFailureMessage: String?
|
||||
@Published private(set) var remoteUpdateMessage: String?
|
||||
@Published private(set) var remotePlatform: RemoteHostPlatform = .unknown
|
||||
|
||||
let bridge = CrossDeskRTCBridge()
|
||||
let announcements = AnnouncementInbox()
|
||||
private let audioPlayer = RemoteAudioPlayer()
|
||||
private var activeRemoteID = ""
|
||||
private var remoteAppVersion = ""
|
||||
private var remoteHostInfoReceived = false
|
||||
private var remoteVersionCheckAttempted = false
|
||||
private var remoteVersionCheckGeneration = UUID()
|
||||
private var remoteVersionCheckTask: URLSessionDataTask?
|
||||
private static let remoteUpdateNotice = "被控端版本过低,请升级到最新版本。"
|
||||
private var pendingRememberPassword = false
|
||||
private var connectionRecorded = false
|
||||
private var shouldCaptureThumbnail = false
|
||||
@@ -409,6 +354,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
private var remoteCursorSequence: UInt32?
|
||||
private var videoWasBackgrounded = false
|
||||
private var videoRecoveryTask: Task<Void, Never>?
|
||||
private var videoSettingsTimeoutTask: Task<Void, Never>?
|
||||
private var pendingPresenceRemoteID: String?
|
||||
private var presenceProbeGeneration: UInt64 = 0
|
||||
private var signalConnected = false
|
||||
@@ -428,6 +374,8 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
private var bridgeConfiguration: BridgeConfiguration?
|
||||
|
||||
var pixelBuffer: CVPixelBuffer? { videoFrame?.pixelBuffer }
|
||||
var currentVideoFrameID: UInt64 { videoFrame?.id ?? 0 }
|
||||
var frameCaptureUptime: TimeInterval { videoFrame?.captureUptime ?? 0 }
|
||||
var frameSize: CGSize { videoFrame?.encodedSize ?? .zero }
|
||||
var displayGeometrySize: CGSize {
|
||||
guard displaySizes.indices.contains(selectedDisplay) else {
|
||||
@@ -440,15 +388,113 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
override init() {
|
||||
super.init()
|
||||
bridge.delegate = self
|
||||
configureBridge()
|
||||
announcements.send = { [weak bridge] data, requestID in
|
||||
bridge?.sendAnnouncementRequest(data, requestID: requestID)
|
||||
}
|
||||
if !savesConnectionThumbnails { clearConnectionThumbnails() }
|
||||
if hasNetworkConsent { configureBridge() }
|
||||
}
|
||||
|
||||
deinit {
|
||||
presenceTimer?.invalidate()
|
||||
remoteVersionCheckTask?.cancel()
|
||||
}
|
||||
|
||||
var privacyNoticeVisible: Bool { privacyNotice.isVisible }
|
||||
|
||||
func applicationDidBecomeActive() {
|
||||
privacyNotice.didBecomeActive(hasNetworkConsent: hasNetworkConsent)
|
||||
refreshRecentConnectionPresenceAfterForeground()
|
||||
refreshAnnouncements()
|
||||
resumeVideoAfterForeground()
|
||||
}
|
||||
|
||||
func applicationDidEnterBackground() {
|
||||
privacyNotice.didEnterBackground()
|
||||
suspendVideoForBackground()
|
||||
suspendPresenceMonitoring()
|
||||
}
|
||||
|
||||
func showPrivacyNotice() {
|
||||
privacyNotice.show()
|
||||
}
|
||||
|
||||
func dismissPrivacyNotice() {
|
||||
privacyNotice.dismiss()
|
||||
}
|
||||
|
||||
func acceptNetworkConsent() {
|
||||
privacyPreferences.setNetworkConsent(true)
|
||||
hasNetworkConsent = true
|
||||
privacyNotice.dismiss()
|
||||
configureBridge()
|
||||
}
|
||||
|
||||
func declineNetworkConsent() {
|
||||
revokeNetworkConsent()
|
||||
privacyNotice.dismiss()
|
||||
}
|
||||
|
||||
func revokeNetworkConsent() {
|
||||
privacyPreferences.setNetworkConsent(false)
|
||||
hasNetworkConsent = false
|
||||
signalConnected = false
|
||||
stopPresenceMonitoring()
|
||||
invalidatePresence()
|
||||
resetConnection()
|
||||
// disconnect() only closes the remote session. Consent withdrawal must
|
||||
// also destroy the persistent signaling peer and its reconnect loop.
|
||||
bridge.stopNetworking()
|
||||
announcements.reset()
|
||||
bridgeConfiguration = nil
|
||||
localIdentity = ""
|
||||
signalStatus = "等待隐私授权"
|
||||
savesConnectionThumbnails = false
|
||||
clearConnectionThumbnails()
|
||||
}
|
||||
|
||||
func setSavesConnectionThumbnails(_ allowed: Bool) {
|
||||
privacyPreferences.setSavesThumbnails(allowed)
|
||||
savesConnectionThumbnails = privacyPreferences.savesThumbnails
|
||||
if !savesConnectionThumbnails { clearConnectionThumbnails() }
|
||||
// Enabling applies on the next connection, never to a frame captured
|
||||
// before the user opted in.
|
||||
}
|
||||
|
||||
func clearConnectionThumbnails() {
|
||||
thumbnailGeneration = UUID()
|
||||
shouldCaptureThumbnail = false
|
||||
for index in recentConnections.indices {
|
||||
recentConnections[index].thumbnailFileName = nil
|
||||
}
|
||||
RecentConnectionStore.save(recentConnections)
|
||||
thumbnailCleanupInProgress = true
|
||||
thumbnailCleanupError = nil
|
||||
let generation = thumbnailGeneration
|
||||
RecentConnectionStore.removeAllThumbnails { [weak self] success in
|
||||
guard let self, self.thumbnailGeneration == generation else { return }
|
||||
self.thumbnailCleanupInProgress = false
|
||||
self.thumbnailCleanupError = success
|
||||
? nil
|
||||
: "部分预览图未能清除,请重试。"
|
||||
}
|
||||
}
|
||||
|
||||
var usesOfficialServer: Bool {
|
||||
signalHost == Self.officialSignalHost && signalPort == Self.officialSignalPort
|
||||
}
|
||||
|
||||
func restoreOfficialServerConfiguration() {
|
||||
signalHost = Self.officialSignalHost
|
||||
signalPort = Self.officialSignalPort
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func configureBridge() -> Bool {
|
||||
guard hasNetworkConsent else {
|
||||
signalStatus = "等待隐私授权"
|
||||
return false
|
||||
}
|
||||
let host = signalHost.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard let signal = Int(signalPort),
|
||||
(1...65535).contains(signal),
|
||||
@@ -460,6 +506,8 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
if bridgeConfiguration != configuration {
|
||||
bridgeConfiguration = configuration
|
||||
signalConnected = false
|
||||
localIdentity = ""
|
||||
announcements.reset()
|
||||
signalStatus = "正在连接信令服务"
|
||||
stopPresenceMonitoring()
|
||||
invalidatePresence()
|
||||
@@ -467,7 +515,6 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
} else if signalConnected {
|
||||
signalStatus = "已连接服务器"
|
||||
}
|
||||
bridge.setHardwareAccelerationEnabled(videoCodecMode == .hardware)
|
||||
bridge.setVideoAdaptationPolicy(videoAdaptationPolicy.bridgeValue)
|
||||
bridge.configure(withSignalHost: host,
|
||||
signalPort: signal)
|
||||
@@ -481,6 +528,10 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
func connect() {
|
||||
guard hasNetworkConsent else {
|
||||
showPrivacyNotice()
|
||||
return
|
||||
}
|
||||
connectionFailureMessage = nil
|
||||
let identifier = remoteID.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !identifier.isEmpty else {
|
||||
@@ -500,13 +551,16 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func beginRemoteConnection(_ identifier: String) {
|
||||
networkStatistics = RemoteNetworkStatistics()
|
||||
resetRemoteHostInfo()
|
||||
cancelVideoRecovery()
|
||||
resetVideoSettings()
|
||||
cancelPresenceProbe()
|
||||
activeRemoteID = identifier
|
||||
activeDisplayName = ""
|
||||
displaySizes = []
|
||||
connectionRecorded = false
|
||||
shouldCaptureThumbnail = true
|
||||
shouldCaptureThumbnail = savesConnectionThumbnails
|
||||
isConnecting = true
|
||||
isConnected = false
|
||||
sessionVisible = false
|
||||
@@ -516,7 +570,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func beginPresenceProbe(_ identifier: String) {
|
||||
guard signalConnected, presenceIsForeground else {
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground else {
|
||||
showDeviceOffline()
|
||||
return
|
||||
}
|
||||
@@ -555,7 +609,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func requestPresenceProbe(_ identifier: String) {
|
||||
guard signalConnected, presenceIsForeground else { return }
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground else { return }
|
||||
// Older servers ignore subscribe=false and replace the watched list.
|
||||
var identifiers = recentConnections.map(\.remoteID)
|
||||
if !identifiers.contains(identifier) { identifiers.append(identifier) }
|
||||
@@ -592,6 +646,8 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func resetConnection() {
|
||||
resetRemoteHostInfo()
|
||||
resetVideoSettings()
|
||||
connectionFailureMessage = nil
|
||||
cancelVideoRecovery()
|
||||
let wasCheckingPresence = pendingPresenceRemoteID != nil
|
||||
@@ -606,7 +662,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
videoFrame = nil
|
||||
resetRemoteCursorState()
|
||||
frameCount = 0
|
||||
bitrate = 0
|
||||
networkStatistics = RemoteNetworkStatistics()
|
||||
displays = ["显示器 1"]
|
||||
displaySizes = []
|
||||
selectedDisplay = 0
|
||||
@@ -616,11 +672,63 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
func retry() {
|
||||
resetRemoteHostInfo()
|
||||
cancelVideoRecovery()
|
||||
bridge.disconnect()
|
||||
connect()
|
||||
}
|
||||
|
||||
func dismissRemoteUpdate() {
|
||||
remoteUpdateMessage = nil
|
||||
}
|
||||
|
||||
private func resetRemoteHostInfo() {
|
||||
remoteVersionCheckTask?.cancel()
|
||||
remoteVersionCheckTask = nil
|
||||
remoteVersionCheckGeneration = UUID()
|
||||
remoteVersionCheckAttempted = false
|
||||
remoteAppVersion = ""
|
||||
remotePlatform = .unknown
|
||||
remoteHostInfoReceived = false
|
||||
remoteUpdateMessage = nil
|
||||
}
|
||||
|
||||
private func checkRemoteVersionIfNeeded() {
|
||||
guard hasNetworkConsent, isConnected, remoteHostInfoReceived,
|
||||
!remoteVersionCheckAttempted else { return }
|
||||
remoteVersionCheckAttempted = true
|
||||
if remoteAppVersion.isEmpty {
|
||||
remoteUpdateMessage = Self.remoteUpdateNotice
|
||||
return
|
||||
}
|
||||
let generation = remoteVersionCheckGeneration
|
||||
let appVersion = remoteAppVersion
|
||||
// Only public release metadata is fetched; no peer ID or version is sent.
|
||||
let url = URL(string: "https://version.crossdesk.cn/version.json")!
|
||||
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData,
|
||||
timeoutInterval: 15)
|
||||
remoteVersionCheckTask = URLSession.shared.dataTask(with: request) {
|
||||
[weak self] data, response, error in
|
||||
let latest: String?
|
||||
if error == nil, let data,
|
||||
(response as? HTTPURLResponse)?.statusCode == 200 {
|
||||
latest = CrossDeskRTCBridge.availableUpdate(appVersion: appVersion,
|
||||
releaseJSON: data)
|
||||
} else {
|
||||
latest = nil
|
||||
}
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self,
|
||||
self.remoteVersionCheckGeneration == generation,
|
||||
self.isConnected else { return }
|
||||
self.remoteVersionCheckTask = nil
|
||||
guard latest != nil else { return }
|
||||
self.remoteUpdateMessage = Self.remoteUpdateNotice
|
||||
}
|
||||
}
|
||||
remoteVersionCheckTask?.resume()
|
||||
}
|
||||
|
||||
func savedPassword(for remoteID: String) -> String {
|
||||
ConnectionCredentialStore.password(for: remoteID) ?? ""
|
||||
}
|
||||
@@ -635,11 +743,11 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
func thumbnailImage(for connection: RecentConnection) -> UIImage? {
|
||||
guard let fileName = connection.thumbnailFileName,
|
||||
let url = RecentConnectionStore.thumbnailURL(fileName: fileName) else {
|
||||
guard savesConnectionThumbnails,
|
||||
let fileName = connection.thumbnailFileName else {
|
||||
return nil
|
||||
}
|
||||
return UIImage(contentsOfFile: url.path)
|
||||
return UIImage(contentsOfFile: RecentConnectionStore.thumbnailURL(fileName: fileName).path)
|
||||
}
|
||||
|
||||
func isRecentConnectionOnline(_ connection: RecentConnection) -> Bool {
|
||||
@@ -647,14 +755,14 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func isDeviceOnline(_ identifier: String) -> Bool {
|
||||
guard signalConnected, presenceIsForeground, !awaitingPresenceSnapshot,
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground, !awaitingPresenceSnapshot,
|
||||
recentConnectionPresence[identifier] == true,
|
||||
let updatedAt = presenceUpdatedAt[identifier] else { return false }
|
||||
return updatedAt.duration(to: presenceClock.now) < Self.presenceMaxAge
|
||||
}
|
||||
|
||||
private func refreshRecentConnectionPresence() {
|
||||
guard signalConnected, presenceIsForeground else { return }
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground else { return }
|
||||
lastPresenceRefreshAt = presenceClock.now
|
||||
bridge.requestPresence(remoteIDs: recentConnections.map(\.remoteID),
|
||||
subscribe: true)
|
||||
@@ -669,7 +777,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func startPresenceMonitoring() {
|
||||
guard signalConnected, presenceIsForeground, presenceTimer == nil else { return }
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground, presenceTimer == nil else { return }
|
||||
let timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in
|
||||
self?.maintainPresence()
|
||||
}
|
||||
@@ -683,7 +791,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
private func maintainPresence() {
|
||||
guard signalConnected, presenceIsForeground else { return }
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground else { return }
|
||||
let now = presenceClock.now
|
||||
let expired = presenceUpdatedAt.compactMap { identifier, updatedAt in
|
||||
updatedAt.duration(to: now) >= Self.presenceMaxAge ? identifier : nil
|
||||
@@ -710,6 +818,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
|
||||
func suspendVideoForBackground() {
|
||||
videoWasBackgrounded = true
|
||||
networkStatistics.resetVideo()
|
||||
cancelVideoRecovery()
|
||||
}
|
||||
|
||||
@@ -758,7 +867,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
recentConnectionPresence.removeValue(forKey: connection.remoteID)
|
||||
presenceUpdatedAt.removeValue(forKey: connection.remoteID)
|
||||
RecentConnectionStore.save(recentConnections)
|
||||
RecentConnectionStore.removeThumbnail(fileName: connection.thumbnailFileName)
|
||||
RecentConnectionStore.removeThumbnail(for: connection)
|
||||
ConnectionCredentialStore.removePassword(for: connection.remoteID)
|
||||
refreshRecentConnectionPresence()
|
||||
}
|
||||
@@ -782,7 +891,8 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
displayName: title,
|
||||
lastConnectedAt: Date(),
|
||||
remembersPassword: pendingRememberPassword,
|
||||
thumbnailFileName: previous?.thumbnailFileName
|
||||
thumbnailFileName: previous?.thumbnailFileName,
|
||||
platform: remoteHostInfoReceived ? remotePlatform : (previous?.platform ?? .unknown)
|
||||
)
|
||||
recentConnections.removeAll { $0.remoteID == activeRemoteID }
|
||||
recentConnections.insert(connection, at: 0)
|
||||
@@ -790,24 +900,27 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
refreshRecentConnectionPresence()
|
||||
}
|
||||
|
||||
private func updateActiveConnectionName(_ name: String) {
|
||||
private func updateActiveConnectionHostInfo(_ name: String) {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty, !activeRemoteID.isEmpty else { return }
|
||||
activeDisplayName = trimmed
|
||||
guard !activeRemoteID.isEmpty else { return }
|
||||
if !trimmed.isEmpty { activeDisplayName = trimmed }
|
||||
guard let index = recentConnections.firstIndex(where: {
|
||||
$0.remoteID == activeRemoteID
|
||||
}) else { return }
|
||||
recentConnections[index].displayName = trimmed
|
||||
recentConnections[index].updateHostInfo(name: trimmed, platform: remotePlatform)
|
||||
RecentConnectionStore.save(recentConnections)
|
||||
}
|
||||
|
||||
private func captureRecentThumbnailIfNeeded(_ pixelBuffer: CVPixelBuffer) {
|
||||
guard shouldCaptureThumbnail, !activeRemoteID.isEmpty else { return }
|
||||
guard hasNetworkConsent, savesConnectionThumbnails,
|
||||
shouldCaptureThumbnail, !activeRemoteID.isEmpty else { return }
|
||||
shouldCaptureThumbnail = false
|
||||
let generation = thumbnailGeneration
|
||||
let identifier = activeRemoteID
|
||||
RecentConnectionStore.captureThumbnail(from: pixelBuffer,
|
||||
remoteID: identifier) { [weak self] fileName in
|
||||
guard let self, let fileName,
|
||||
guard let self, let fileName, self.hasNetworkConsent,
|
||||
self.savesConnectionThumbnails, self.thumbnailGeneration == generation,
|
||||
let index = self.recentConnections.firstIndex(where: {
|
||||
$0.remoteID == identifier
|
||||
}) else { return }
|
||||
@@ -819,12 +932,68 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
func selectDisplay(_ index: Int) {
|
||||
guard displays.indices.contains(index) else { return }
|
||||
selectedDisplay = index
|
||||
networkStatistics.resetVideo()
|
||||
videoFrame = nil
|
||||
resetRemoteCursorState()
|
||||
frameCount = 0
|
||||
bridge.switch(toDisplay: index)
|
||||
}
|
||||
|
||||
var canChangeVideoSettings: Bool {
|
||||
isConnected && videoSettings.supported
|
||||
}
|
||||
|
||||
var videoSettingsFeedback: String {
|
||||
if !canChangeVideoSettings {
|
||||
return "连接建立后可调整,需被控端支持。"
|
||||
}
|
||||
if videoSettings.failed { return "调整失败,请重试。" }
|
||||
return videoSettings.pending ? "正在应用…" : ""
|
||||
}
|
||||
|
||||
func updateVideoSettings(quality: Int? = nil, frameRate: Int? = nil,
|
||||
preference: Int? = nil) {
|
||||
guard hasNetworkConsent, canChangeVideoSettings else { return }
|
||||
var settings = videoSettings.selection
|
||||
if let quality { settings.quality = quality }
|
||||
if let frameRate { settings.frameRate = frameRate }
|
||||
if let preference { settings.preference = preference }
|
||||
guard let requestID = videoSettings.begin(settings) else { return }
|
||||
videoSettingsTimeoutTask?.cancel()
|
||||
bridge.sendVideoSettings(quality: settings.quality,
|
||||
frameRate: settings.frameRate,
|
||||
preference: settings.preference,
|
||||
requestID: requestID)
|
||||
videoSettingsTimeoutTask = Task { @MainActor [weak self] in
|
||||
do {
|
||||
try await Task.sleep(nanoseconds: 5_000_000_000)
|
||||
} catch { return }
|
||||
self?.videoSettings.expire(requestID: requestID)
|
||||
}
|
||||
}
|
||||
|
||||
private func resetVideoSettings() {
|
||||
videoSettingsTimeoutTask?.cancel()
|
||||
videoSettingsTimeoutTask = nil
|
||||
videoSettings = RemoteVideoSettingsState(
|
||||
preference: videoAdaptationPolicy.bridgeValue.rawValue)
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge,
|
||||
didReceiveVideoSettingsQuality quality: Int,
|
||||
frameRate: Int, preference: Int,
|
||||
requestID: UInt32, accepted: Bool) {
|
||||
guard hasNetworkConsent, isConnected else { return }
|
||||
videoSettings.receive(RemoteVideoSettings(quality: quality,
|
||||
frameRate: frameRate,
|
||||
preference: preference),
|
||||
requestID: requestID, accepted: accepted)
|
||||
if !videoSettings.pending {
|
||||
videoSettingsTimeoutTask?.cancel()
|
||||
videoSettingsTimeoutTask = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func resetRemoteCursorState() {
|
||||
remoteCursorVisible = true
|
||||
remoteCursorShape = 0
|
||||
@@ -869,9 +1038,17 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
bridge.sendWindowsKeyCode(keyCode, isDown: isDown)
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge, didChangeIdentityStorageError hasError: Bool) {
|
||||
identityStorageWarning = hasError
|
||||
? "本机登录凭据暂时无法安全存取。请解锁设备后,在设置中点击“应用”重试。"
|
||||
: nil
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge,
|
||||
didChange state: CrossDeskSignalState) {
|
||||
guard hasNetworkConsent else { return }
|
||||
signalConnected = state.rawValue == 1
|
||||
announcements.setConnected(signalConnected)
|
||||
invalidatePresence()
|
||||
switch state.rawValue {
|
||||
case 0: signalStatus = "正在连接信令服务"
|
||||
@@ -881,6 +1058,7 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
case 4: signalStatus = "信令服务重连中"
|
||||
case 5: signalStatus = "信令服务器已关闭连接"
|
||||
case 6: signalStatus = "TLS 证书校验失败"
|
||||
case 7: signalStatus = "无法访问本机登录凭据,请解锁后重试"
|
||||
default: signalStatus = "未知信令状态"
|
||||
}
|
||||
if signalConnected {
|
||||
@@ -912,6 +1090,8 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
case 1:
|
||||
connectionStatus = "已连接"
|
||||
sessionVisible = true
|
||||
if videoSettings.requestID == 0 { updateVideoSettings() }
|
||||
checkRemoteVersionIfNeeded()
|
||||
recordSuccessfulConnectionIfNeeded()
|
||||
audioPlayer.setEnabled(audioEnabled)
|
||||
bridge.setAudioEnabled(audioEnabled)
|
||||
@@ -941,17 +1121,44 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge, didProvisionIdentity identity: String) {
|
||||
guard hasNetworkConsent else { return }
|
||||
localIdentity = identity.split(separator: "@").first.map(String.init) ?? identity
|
||||
if let configuration = bridgeConfiguration {
|
||||
announcements.configure(host: configuration.host, port: configuration.signalPort,
|
||||
deviceID: localIdentity)
|
||||
}
|
||||
refreshRecentConnectionPresence()
|
||||
if let pendingPresenceRemoteID {
|
||||
requestPresenceProbe(pendingPresenceRemoteID)
|
||||
}
|
||||
}
|
||||
|
||||
var announcementsConnected: Bool { hasNetworkConsent && signalConnected }
|
||||
|
||||
func refreshAnnouncements() {
|
||||
guard announcementsConnected else { return }
|
||||
announcements.refresh()
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge, didReceiveAnnouncementMessage message: Data) {
|
||||
guard announcementsConnected else { return }
|
||||
let object = (try? JSONSerialization.jsonObject(with: message)) as? [String: Any]
|
||||
if object?["type"] as? String == "announcements_changed" {
|
||||
announcements.refresh()
|
||||
} else {
|
||||
announcements.receive(message)
|
||||
}
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge, didFailAnnouncementRequest requestID: String) {
|
||||
guard hasNetworkConsent else { return }
|
||||
announcements.failed(requestID: requestID)
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge,
|
||||
didReceivePresence presence: [String: NSNumber],
|
||||
snapshot: Bool) {
|
||||
guard signalConnected, presenceIsForeground,
|
||||
guard hasNetworkConsent, signalConnected, presenceIsForeground,
|
||||
snapshot || !awaitingPresenceSnapshot else { return }
|
||||
var updated = snapshot ? [:] : recentConnectionPresence
|
||||
if snapshot {
|
||||
@@ -983,15 +1190,19 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge,
|
||||
didReceive pixelBuffer: CVPixelBuffer,
|
||||
width: Int,
|
||||
height: Int) {
|
||||
guard !videoWasBackgrounded else { return }
|
||||
height: Int,
|
||||
captureUptime: TimeInterval) {
|
||||
guard hasNetworkConsent, isConnected, !videoWasBackgrounded else { return }
|
||||
cancelVideoRecovery()
|
||||
// Buffer and encoded dimensions must be one observable value. Adaptive
|
||||
// resolution changes must never expose a new frame with the previous
|
||||
// frame's geometry to SwiftUI.
|
||||
videoFrameID &+= 1
|
||||
videoFrame = RemoteVideoFrame(
|
||||
pixelBuffer: pixelBuffer,
|
||||
encodedSize: CGSize(width: width, height: height)
|
||||
encodedSize: CGSize(width: width, height: height),
|
||||
id: videoFrameID,
|
||||
captureUptime: captureUptime
|
||||
)
|
||||
frameCount &+= 1
|
||||
captureRecentThumbnailIfNeeded(pixelBuffer)
|
||||
@@ -999,9 +1210,24 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge,
|
||||
didReceiveHostName hostName: String,
|
||||
appVersion: String,
|
||||
platform: String,
|
||||
displayNames remoteDisplayNames: [String],
|
||||
displaySizes remoteDisplaySizes: [NSValue]) {
|
||||
updateActiveConnectionName(hostName)
|
||||
displaySizes remoteDisplaySizes: [NSValue],
|
||||
supportsVideoSettings: Bool) {
|
||||
let previouslySupported = videoSettings.supported
|
||||
videoSettings.setSupported(supportsVideoSettings)
|
||||
if !supportsVideoSettings {
|
||||
videoSettingsTimeoutTask?.cancel()
|
||||
videoSettingsTimeoutTask = nil
|
||||
} else if !previouslySupported {
|
||||
updateVideoSettings()
|
||||
}
|
||||
remoteHostInfoReceived = true
|
||||
remoteAppVersion = appVersion
|
||||
remotePlatform = RemoteHostPlatform(rawValue: platform) ?? .unknown
|
||||
checkRemoteVersionIfNeeded()
|
||||
updateActiveConnectionHostInfo(hostName)
|
||||
let names = remoteDisplayNames.enumerated().map { index, displayName in
|
||||
let name = displayName.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return name.isEmpty ? "显示器 \(index + 1)" : name
|
||||
@@ -1051,10 +1277,12 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge, didReceiveAudioPCM pcmData: Data) {
|
||||
guard hasNetworkConsent, isConnected else { return }
|
||||
audioPlayer.enqueue(pcmData)
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge, didReceiveClipboardText text: String) {
|
||||
guard hasNetworkConsent, isConnected else { return }
|
||||
UIPasteboard.general.string = text
|
||||
clipboardStatus = "已接收远端剪贴板"
|
||||
}
|
||||
@@ -1080,22 +1308,37 @@ final class RemoteSessionModel: NSObject, ObservableObject, CrossDeskRTCBridgeDe
|
||||
}
|
||||
|
||||
func rtcBridge(_ bridge: CrossDeskRTCBridge,
|
||||
didUpdateBitrate bitsPerSecond: UInt,
|
||||
lossRate: Float,
|
||||
usingTURN: Bool) {
|
||||
bitrate = bitsPerSecond
|
||||
self.lossRate = lossRate
|
||||
self.usingTURN = usingTURN
|
||||
didUpdateNetworkStats stats: CrossDeskNetworkStats) {
|
||||
guard hasNetworkConsent, isConnected else { return }
|
||||
func traffic(_ value: CrossDeskTrafficStats) -> RemoteTrafficStatistics {
|
||||
RemoteTrafficStatistics(inboundBitrate: value.inboundBitrate,
|
||||
outboundBitrate: value.outboundBitrate,
|
||||
lossRate: value.lossRate)
|
||||
}
|
||||
let mode: RemoteNetworkReport.Mode
|
||||
switch stats.traversalMode {
|
||||
case .direct: mode = .direct
|
||||
case .relay: mode = .relay
|
||||
default: mode = .unknown
|
||||
}
|
||||
networkStatistics.receive(RemoteNetworkReport(
|
||||
video: traffic(stats.video), audio: traffic(stats.audio),
|
||||
data: traffic(stats.data), total: traffic(stats.total), mode: mode,
|
||||
srtpActive: stats.srtpActive.boolValue, rttMilliseconds: stats.rttMilliseconds
|
||||
), at: ProcessInfo.processInfo.systemUptime)
|
||||
}
|
||||
|
||||
var formattedBitrate: String {
|
||||
if bitrate >= 1_000_000 {
|
||||
return String(format: "%.1f Mbps", Double(bitrate) / 1_000_000)
|
||||
}
|
||||
if bitrate >= 1_000 {
|
||||
return String(format: "%.0f Kbps", Double(bitrate) / 1_000)
|
||||
}
|
||||
return "\(bitrate) bps"
|
||||
// Called after the exact frame enters AVSampleBufferDisplayLayer. Keep this
|
||||
// accumulator unpublished: submitting pixels occurs during a SwiftUI update.
|
||||
func recordVideoFrameSubmission(id: UInt64, captureUptime: TimeInterval) {
|
||||
guard isConnected, !videoWasBackgrounded, id == videoFrame?.id else { return }
|
||||
networkStatistics.recordSubmittedFrame(id: id, captureUptime: captureUptime,
|
||||
at: ProcessInfo.processInfo.systemUptime)
|
||||
}
|
||||
|
||||
var networkSnapshot: RemoteNetworkSnapshot {
|
||||
guard isConnected else { return RemoteNetworkSnapshot() }
|
||||
return networkStatistics.displaySnapshot(at: ProcessInfo.processInfo.systemUptime)
|
||||
}
|
||||
|
||||
var videoStatus: String {
|
||||
|
||||
@@ -53,7 +53,12 @@ struct RemoteSessionView: View {
|
||||
videoSize: session.displayGeometrySize
|
||||
) {
|
||||
ZStack(alignment: .topLeading) {
|
||||
NativeVideoView(pixelBuffer: session.pixelBuffer)
|
||||
NativeVideoView(
|
||||
pixelBuffer: session.pixelBuffer,
|
||||
frameID: session.currentVideoFrameID,
|
||||
captureUptime: session.frameCaptureUptime,
|
||||
onFrameSubmitted: session.recordVideoFrameSubmission
|
||||
)
|
||||
|
||||
if let cursorPosition,
|
||||
session.pixelBuffer != nil {
|
||||
@@ -147,6 +152,14 @@ struct RemoteSessionView: View {
|
||||
.zIndex(50)
|
||||
}
|
||||
}
|
||||
.alert("升级提示", isPresented: Binding(
|
||||
get: { session.remoteUpdateMessage != nil },
|
||||
set: { if !$0 { session.dismissRemoteUpdate() } }
|
||||
)) {
|
||||
Button("知道了", role: .cancel) { session.dismissRemoteUpdate() }
|
||||
} message: {
|
||||
Text(session.remoteUpdateMessage ?? "")
|
||||
}
|
||||
.onDisappear {
|
||||
keyboardInputVisible = false
|
||||
viewport = RemoteViewportState()
|
||||
@@ -258,7 +271,7 @@ struct RemoteSessionView: View {
|
||||
)
|
||||
let panelSize = CGSize(
|
||||
width: min(340, max(280, containerSize.width - 160)),
|
||||
height: min(250, max(220, containerSize.height - 48))
|
||||
height: min(310, max(0, containerSize.height - 16))
|
||||
)
|
||||
let panelCenter = floatingPanelCenter(
|
||||
orbCenter: orbCenter,
|
||||
@@ -1056,6 +1069,10 @@ private struct CrossDeskStatusOrb: View {
|
||||
|
||||
private struct FloatingSessionMenu: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
private enum Page { case controls, videoSettings, networkStats }
|
||||
@State private var page: Page = .controls
|
||||
@State private var displayedNetworkSnapshot = RemoteNetworkSnapshot()
|
||||
@State private var displayedFrameSize = CGSize.zero
|
||||
let showKeyboard: () -> Void
|
||||
let chooseFile: () -> Void
|
||||
let close: () -> Void
|
||||
@@ -1067,15 +1084,28 @@ private struct FloatingSessionMenu: View {
|
||||
var body: some View {
|
||||
VStack(spacing: 9) {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(session.isConnected ? Color.green : Color.orange)
|
||||
.frame(width: 9, height: 9)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(session.connectionStatus)
|
||||
if page != .controls {
|
||||
Button {
|
||||
page = .controls
|
||||
} label: {
|
||||
Image(systemName: "chevron.left")
|
||||
.frame(width: 28, height: 32)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel("返回控制栏")
|
||||
Text(page == .videoSettings ? "画面设置" : "网络状态")
|
||||
.font(.subheadline.weight(.semibold))
|
||||
Text(statusDetail)
|
||||
.font(.caption2.monospacedDigit())
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
Circle()
|
||||
.fill(session.isConnected ? Color.green : Color.orange)
|
||||
.frame(width: 9, height: 9)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(session.connectionStatus)
|
||||
.font(.subheadline.weight(.semibold))
|
||||
Text(statusDetail)
|
||||
.font(.caption2.monospacedDigit())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
Button(action: close) {
|
||||
@@ -1084,65 +1114,90 @@ private struct FloatingSessionMenu: View {
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel("关闭控制栏")
|
||||
}
|
||||
|
||||
LazyVGrid(columns: columns, spacing: 7) {
|
||||
FloatingControlButton(title: "键盘", symbol: "keyboard",
|
||||
action: showKeyboard)
|
||||
if page == .videoSettings, !session.videoSettingsFeedback.isEmpty {
|
||||
Text(session.videoSettingsFeedback)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
Menu {
|
||||
ForEach(Array(session.displays.enumerated()), id: \.offset) { index, name in
|
||||
Button {
|
||||
session.selectDisplay(index)
|
||||
} label: {
|
||||
if index == session.selectedDisplay {
|
||||
Label(name, systemImage: "checkmark")
|
||||
} else {
|
||||
Text(name)
|
||||
ScrollView {
|
||||
if page == .videoSettings {
|
||||
FloatingVideoSettings(session: session)
|
||||
} else if page == .networkStats {
|
||||
FloatingNetworkStatistics(snapshot: displayedNetworkSnapshot,
|
||||
frameSize: displayedFrameSize)
|
||||
} else {
|
||||
VStack(spacing: 9) {
|
||||
LazyVGrid(columns: columns, spacing: 7) {
|
||||
FloatingControlButton(title: "键盘", symbol: "keyboard",
|
||||
action: showKeyboard)
|
||||
|
||||
Menu {
|
||||
ForEach(Array(session.displays.enumerated()), id: \.offset) { index, name in
|
||||
Button {
|
||||
session.selectDisplay(index)
|
||||
} label: {
|
||||
if index == session.selectedDisplay {
|
||||
Label(name, systemImage: "checkmark")
|
||||
} else {
|
||||
Text(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
FloatingControlLabel(title: "显示器", symbol: "display")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
|
||||
FloatingControlButton(title: "画面设置", symbol: "slider.horizontal.3") {
|
||||
page = .videoSettings
|
||||
}
|
||||
FloatingControlButton(
|
||||
title: session.audioEnabled ? "声音" : "静音",
|
||||
symbol: session.audioEnabled ? "speaker.wave.2" : "speaker.slash",
|
||||
action: session.toggleAudio
|
||||
)
|
||||
FloatingControlButton(
|
||||
title: session.mouseControlMode == .relative ? "相对鼠标" : "绝对鼠标",
|
||||
symbol: "computermouse",
|
||||
action: {
|
||||
session.mouseControlMode = session.mouseControlMode == .relative
|
||||
? .absolute : .relative
|
||||
}
|
||||
)
|
||||
FloatingControlButton(title: "发送文件",
|
||||
symbol: "folder.badge.plus",
|
||||
action: chooseFile)
|
||||
FloatingControlButton(title: "网络状态", symbol: "chart.bar.xaxis") {
|
||||
page = .networkStats
|
||||
}
|
||||
FloatingControlButton(title: "Ctrl+Alt+Del",
|
||||
symbol: "lock.trianglebadge.exclamationmark",
|
||||
action: session.bridge.sendSecureAttentionSequence)
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
FloatingControlLabel(title: "显示器", symbol: "display")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
|
||||
FloatingControlButton(
|
||||
title: session.audioEnabled ? "声音" : "静音",
|
||||
symbol: session.audioEnabled ? "speaker.wave.2" : "speaker.slash",
|
||||
action: session.toggleAudio
|
||||
)
|
||||
FloatingControlButton(
|
||||
title: session.mouseControlMode == .relative ? "相对鼠标" : "绝对鼠标",
|
||||
symbol: "computermouse",
|
||||
action: {
|
||||
session.mouseControlMode = session.mouseControlMode == .relative
|
||||
? .absolute : .relative
|
||||
}
|
||||
)
|
||||
FloatingControlButton(title: "发送文件",
|
||||
symbol: "folder.badge.plus",
|
||||
action: chooseFile)
|
||||
FloatingControlButton(title: "Ctrl+Alt+Del",
|
||||
symbol: "lock.trianglebadge.exclamationmark",
|
||||
action: session.bridge.sendSecureAttentionSequence)
|
||||
}
|
||||
|
||||
if !session.transferStatus.isEmpty || !session.clipboardStatus.isEmpty {
|
||||
HStack(spacing: 8) {
|
||||
Text(!session.transferStatus.isEmpty
|
||||
? session.transferStatus : session.clipboardStatus)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
if session.transferProgress > 0 && session.transferProgress < 1 {
|
||||
ProgressView(value: session.transferProgress)
|
||||
.frame(width: 60)
|
||||
}
|
||||
if let file = session.receivedFileURL {
|
||||
ShareLink(item: file) {
|
||||
Image(systemName: "square.and.arrow.up")
|
||||
if !session.transferStatus.isEmpty || !session.clipboardStatus.isEmpty {
|
||||
HStack(spacing: 8) {
|
||||
Text(!session.transferStatus.isEmpty
|
||||
? session.transferStatus : session.clipboardStatus)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
Spacer(minLength: 0)
|
||||
if session.transferProgress > 0 && session.transferProgress < 1 {
|
||||
ProgressView(value: session.transferProgress)
|
||||
.frame(width: 60)
|
||||
}
|
||||
if let file = session.receivedFileURL {
|
||||
ShareLink(item: file) {
|
||||
Image(systemName: "square.and.arrow.up")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1166,22 +1221,161 @@ private struct FloatingSessionMenu: View {
|
||||
}
|
||||
.shadow(color: .black.opacity(0.34), radius: 18, y: 7)
|
||||
.environment(\.colorScheme, .light)
|
||||
.task(id: session.selectedDisplay) {
|
||||
// This task survives ordinary video-frame redraws and is cancelled
|
||||
// when the menu closes. Rendering only reads the sampled values.
|
||||
while !Task.isCancelled {
|
||||
displayedNetworkSnapshot = session.networkSnapshot
|
||||
displayedFrameSize = session.frameSize
|
||||
do {
|
||||
try await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var statusDetail: String {
|
||||
var components = [session.usingTURN ? "TURN" : "P2P"]
|
||||
let frameSize = session.frameSize
|
||||
let snapshot = displayedNetworkSnapshot
|
||||
var components = [snapshot.connectionMode]
|
||||
let frameSize = displayedFrameSize
|
||||
if frameSize.width > 0 && frameSize.height > 0 {
|
||||
components.append("\(Int(frameSize.width))×\(Int(frameSize.height))")
|
||||
}
|
||||
components.append(session.formattedBitrate)
|
||||
if session.lossRate > 0 {
|
||||
components.append(String(format: "丢包 %.1f%%", session.lossRate * 100))
|
||||
components.append(RemoteNetworkSnapshot.bitrate(snapshot.report?.total.inboundBitrate))
|
||||
if let loss = snapshot.report?.video.lossRate, loss > 0 {
|
||||
components.append("丢包 \(RemoteNetworkSnapshot.lossRate(loss))")
|
||||
}
|
||||
return components.joined(separator: " · ")
|
||||
}
|
||||
}
|
||||
|
||||
private struct FloatingNetworkStatistics: View {
|
||||
let snapshot: RemoteNetworkSnapshot
|
||||
let frameSize: CGSize
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 10) {
|
||||
VStack(spacing: 0) {
|
||||
trafficRow("", inbound: "接收", outbound: "发送", loss: "丢包率")
|
||||
.foregroundStyle(.secondary)
|
||||
trafficRow("视频", statistics: snapshot.report?.video)
|
||||
trafficRow("音频", statistics: snapshot.report?.audio)
|
||||
trafficRow("数据", statistics: snapshot.report?.data)
|
||||
trafficRow("合计", statistics: snapshot.report?.total)
|
||||
.fontWeight(.semibold)
|
||||
.background(Color.blue.opacity(0.07), in: RoundedRectangle(cornerRadius: 5))
|
||||
}
|
||||
.font(.caption2.monospacedDigit())
|
||||
|
||||
Divider()
|
||||
|
||||
VStack(spacing: 7) {
|
||||
detail("帧率", value: "\(snapshot.framesPerSecond) FPS")
|
||||
detail("分辨率", value: resolution)
|
||||
detail("画面延时", value: RemoteNetworkSnapshot.latency(snapshot.videoLatencyMilliseconds))
|
||||
detail("连接延时(RTT)", value: RemoteNetworkSnapshot.latency(snapshot.rttMilliseconds))
|
||||
detail("连接方式", value: snapshot.connectionMode)
|
||||
HStack {
|
||||
Text("媒体加密")
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer(minLength: 8)
|
||||
if let report = snapshot.report {
|
||||
Label(report.srtpActive ? "SRTP 已启用" : "未启用",
|
||||
systemImage: report.srtpActive ? "lock.shield" : "lock.open")
|
||||
.foregroundStyle(report.srtpActive ? Color.green : Color.secondary)
|
||||
} else {
|
||||
Text("—")
|
||||
}
|
||||
}
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
.font(.caption.monospacedDigit())
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
|
||||
private var resolution: String {
|
||||
guard frameSize.width > 0, frameSize.height > 0 else { return "—" }
|
||||
return "\(Int(frameSize.width)) × \(Int(frameSize.height))"
|
||||
}
|
||||
|
||||
private func detail(_ title: String, value: String) -> some View {
|
||||
HStack {
|
||||
Text(title).foregroundStyle(.secondary)
|
||||
Spacer(minLength: 8)
|
||||
Text(value)
|
||||
}
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
|
||||
private func trafficRow(_ title: String, statistics: RemoteTrafficStatistics?) -> some View {
|
||||
trafficRow(title,
|
||||
inbound: RemoteNetworkSnapshot.bitrate(statistics?.inboundBitrate),
|
||||
outbound: RemoteNetworkSnapshot.bitrate(statistics?.outboundBitrate),
|
||||
loss: RemoteNetworkSnapshot.lossRate(statistics?.lossRate))
|
||||
.accessibilityLabel("\(title),接收 \(RemoteNetworkSnapshot.bitrate(statistics?.inboundBitrate)),发送 \(RemoteNetworkSnapshot.bitrate(statistics?.outboundBitrate)),丢包率 \(RemoteNetworkSnapshot.lossRate(statistics?.lossRate))")
|
||||
}
|
||||
|
||||
private func trafficRow(_ title: String, inbound: String,
|
||||
outbound: String, loss: String) -> some View {
|
||||
HStack(spacing: 4) {
|
||||
Text(title).frame(width: 28, alignment: .leading)
|
||||
Text(inbound).frame(maxWidth: .infinity, alignment: .trailing)
|
||||
Text(outbound).frame(maxWidth: .infinity, alignment: .trailing)
|
||||
Text(loss).frame(width: 46, alignment: .trailing)
|
||||
}
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.75)
|
||||
.padding(.horizontal, 4)
|
||||
.padding(.vertical, 5)
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
|
||||
private struct FloatingVideoSettings: View {
|
||||
@ObservedObject var session: RemoteSessionModel
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
settingRow("画面质量", options: ["低", "中", "高"],
|
||||
values: [0, 1, 2], selection: Binding(
|
||||
get: { session.videoSettings.selection.quality },
|
||||
set: { session.updateVideoSettings(quality: $0) }
|
||||
))
|
||||
settingRow("画面采集帧率", options: ["30 fps", "60 fps"],
|
||||
values: [30, 60], selection: Binding(
|
||||
get: { session.videoSettings.selection.frameRate },
|
||||
set: { session.updateVideoSettings(frameRate: $0) }
|
||||
))
|
||||
settingRow("画面偏好", options: VideoAdaptationPolicy.allCases.map(\.title),
|
||||
values: VideoAdaptationPolicy.allCases.map { $0.bridgeValue.rawValue },
|
||||
selection: Binding(
|
||||
get: { session.videoSettings.selection.preference },
|
||||
set: { session.updateVideoSettings(preference: $0) }
|
||||
))
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
|
||||
private func settingRow(_ title: String, options: [String], values: [Int],
|
||||
selection: Binding<Int>) -> some View {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
Text(title)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Picker(title, selection: selection) {
|
||||
ForEach(options.indices, id: \.self) { index in
|
||||
Text(options[index]).tag(values[index])
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
.disabled(!session.canChangeVideoSettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct FloatingControlButton: View {
|
||||
let title: String
|
||||
let symbol: String
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// Values match crossdesk::VideoSettings on the reliable control stream.
|
||||
struct RemoteVideoSettings: Equatable {
|
||||
var quality = 2
|
||||
var frameRate = 60
|
||||
var preference = 1
|
||||
|
||||
var isValid: Bool {
|
||||
(0...2).contains(quality) && [30, 60].contains(frameRate) &&
|
||||
(0...2).contains(preference)
|
||||
}
|
||||
}
|
||||
|
||||
struct RemoteVideoSettingsState {
|
||||
private(set) var supported = false
|
||||
private(set) var selection: RemoteVideoSettings
|
||||
private(set) var applied: RemoteVideoSettings
|
||||
private(set) var requestID: UInt32 = 0
|
||||
private(set) var pending = false
|
||||
private(set) var failed = false
|
||||
private var appliedRequestID: UInt32 = 0
|
||||
|
||||
init(preference: Int = 1) {
|
||||
let settings = RemoteVideoSettings(preference: preference)
|
||||
selection = settings
|
||||
applied = settings
|
||||
}
|
||||
|
||||
mutating func setSupported(_ value: Bool) {
|
||||
supported = value
|
||||
if !value {
|
||||
selection = applied
|
||||
pending = false
|
||||
failed = false
|
||||
}
|
||||
}
|
||||
|
||||
mutating func begin(_ settings: RemoteVideoSettings) -> UInt32? {
|
||||
guard supported, settings.isValid else { return nil }
|
||||
requestID &+= 1
|
||||
selection = settings
|
||||
pending = true
|
||||
failed = false
|
||||
return requestID
|
||||
}
|
||||
|
||||
mutating func receive(_ settings: RemoteVideoSettings,
|
||||
requestID responseID: UInt32, accepted: Bool) {
|
||||
guard supported, settings.isValid,
|
||||
Int32(bitPattern: requestID &- responseID) >= 0 else { return }
|
||||
// A superseded success still establishes the rollback value for a
|
||||
// newer request. A stale response must never replace its selection.
|
||||
if accepted, Int32(bitPattern: responseID &- appliedRequestID) >= 0 {
|
||||
applied = settings
|
||||
appliedRequestID = responseID
|
||||
}
|
||||
guard responseID == requestID else { return }
|
||||
pending = false
|
||||
failed = !accepted
|
||||
selection = applied
|
||||
}
|
||||
|
||||
mutating func expire(requestID expiredID: UInt32) {
|
||||
guard pending, expiredID == requestID else { return }
|
||||
selection = applied
|
||||
pending = false
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,18 @@ import UIKit
|
||||
struct NativeVideoView: UIViewRepresentable {
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
let pixelBuffer: CVPixelBuffer?
|
||||
let frameID: UInt64
|
||||
let captureUptime: TimeInterval
|
||||
let onFrameSubmitted: (UInt64, TimeInterval) -> Void
|
||||
|
||||
func makeUIView(context: Context) -> SampleBufferVideoView {
|
||||
SampleBufferVideoView(frame: .zero)
|
||||
}
|
||||
|
||||
func updateUIView(_ uiView: SampleBufferVideoView, context: Context) {
|
||||
uiView.display(pixelBuffer, isActive: scenePhase == .active)
|
||||
if uiView.display(pixelBuffer, isActive: scenePhase == .active) {
|
||||
onFrameSubmitted(frameID, captureUptime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +62,10 @@ final class SampleBufferVideoView: UIView {
|
||||
videoLayer.videoGravity = .resize
|
||||
}
|
||||
|
||||
func display(_ pixelBuffer: CVPixelBuffer?, isActive: Bool) {
|
||||
/// True only when a new buffer was submitted; no presentation timestamp is
|
||||
/// exposed by this display layer, so latency ends at submission like the
|
||||
/// desktop renderer's submission fallback.
|
||||
func display(_ pixelBuffer: CVPixelBuffer?, isActive: Bool) -> Bool {
|
||||
if renderingActive != isActive {
|
||||
renderingActive = isActive
|
||||
// Backgrounding can invalidate the display layer without changing
|
||||
@@ -72,9 +80,9 @@ final class SampleBufferVideoView: UIView {
|
||||
submittedFrames = 0
|
||||
droppedFrames = 0
|
||||
videoLayer.flushAndRemoveImage()
|
||||
return
|
||||
return false
|
||||
}
|
||||
guard renderingActive else { return }
|
||||
guard renderingActive else { return false }
|
||||
|
||||
// Check recovery before deduplicating frames: a failed layer may need
|
||||
// to display the same buffer again even if no new decoded frame arrives.
|
||||
@@ -87,7 +95,7 @@ final class SampleBufferVideoView: UIView {
|
||||
|
||||
// SwiftUI can refresh for unrelated status fields. Only deduplicate a
|
||||
// frame after it was actually submitted to a healthy, active layer.
|
||||
guard lastPixelBuffer !== pixelBuffer else { return }
|
||||
guard lastPixelBuffer !== pixelBuffer else { return false }
|
||||
|
||||
// Never let AVSampleBufferDisplayLayer turn temporary rendering
|
||||
// pressure into seconds of latency. Its queued buffers are already
|
||||
@@ -101,7 +109,7 @@ final class SampleBufferVideoView: UIView {
|
||||
droppedFrames)
|
||||
}
|
||||
}
|
||||
guard videoLayer.isReadyForMoreMediaData else { return }
|
||||
guard videoLayer.isReadyForMoreMediaData else { return false }
|
||||
|
||||
var formatDescription: CMVideoFormatDescription?
|
||||
guard CMVideoFormatDescriptionCreateForImageBuffer(
|
||||
@@ -110,7 +118,7 @@ final class SampleBufferVideoView: UIView {
|
||||
formatDescriptionOut: &formatDescription
|
||||
) == noErr, let formatDescription else {
|
||||
NSLog("CrossDesk could not create a video format description")
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
var timing = CMSampleTimingInfo(
|
||||
@@ -127,7 +135,7 @@ final class SampleBufferVideoView: UIView {
|
||||
sampleBufferOut: &sampleBuffer
|
||||
) == noErr, let sampleBuffer else {
|
||||
NSLog("CrossDesk could not create a video sample buffer")
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
if let attachments = CMSampleBufferGetSampleAttachmentsArray(
|
||||
@@ -162,5 +170,6 @@ final class SampleBufferVideoView: UIView {
|
||||
self.videoLayer.error?.localizedDescription ?? "none")
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,249 @@
|
||||
import SwiftUI
|
||||
import UIKit
|
||||
|
||||
private struct LicenseDocument: Decodable, Identifiable {
|
||||
let title: String
|
||||
let text: String
|
||||
var id: String { title }
|
||||
}
|
||||
|
||||
private struct LicensedComponent: Decodable, Identifiable {
|
||||
let id: String
|
||||
let name: String
|
||||
let version: String
|
||||
let license: String
|
||||
let sourceURL: URL
|
||||
let buildSourceURL: URL?
|
||||
let documents: [LicenseDocument]
|
||||
|
||||
var displayVersion: String {
|
||||
if id == "crossdesk" {
|
||||
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""
|
||||
}
|
||||
let currentVersion = SourceMetadata.bundled?.componentSources[id]?.version ?? version
|
||||
return currentVersion.count == 40 ? String(currentVersion.prefix(12)) : currentVersion
|
||||
}
|
||||
|
||||
var resolvedSourceURL: URL {
|
||||
if id == "crossdesk" {
|
||||
return SourceMetadata.bundled?.sourceURL ?? sourceURL
|
||||
}
|
||||
return SourceMetadata.bundled?.componentSources[id]?.sourceURL ?? sourceURL
|
||||
}
|
||||
|
||||
var resolvedBuildSourceURL: URL? {
|
||||
SourceMetadata.bundled?.componentSources[id]?.buildSourceURL ?? buildSourceURL
|
||||
}
|
||||
}
|
||||
|
||||
private struct LicenseCatalog: Decodable {
|
||||
let schemaVersion: Int
|
||||
let components: [LicensedComponent]
|
||||
|
||||
static let bundled: Result<LicenseCatalog, Error> = Result {
|
||||
guard let url = Bundle.main.url(forResource: "ThirdPartyLicenses", withExtension: "json") else {
|
||||
throw CocoaError(.fileNoSuchFile)
|
||||
}
|
||||
let catalog = try JSONDecoder().decode(LicenseCatalog.self, from: Data(contentsOf: url))
|
||||
let requiredComponents: Set<String> = ["crossdesk", "openfec"]
|
||||
guard catalog.schemaVersion == 1,
|
||||
requiredComponents.isSubset(of: Set(catalog.components.map(\.id))) else {
|
||||
throw CocoaError(.fileReadCorruptFile)
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
}
|
||||
|
||||
struct ComponentSourceMetadata: Decodable {
|
||||
let version: String?
|
||||
let sourceURL: URL?
|
||||
let buildSourceURL: URL?
|
||||
}
|
||||
|
||||
struct SourceMetadata: Decodable {
|
||||
let revision: String
|
||||
let tag: String?
|
||||
let isModified: Bool
|
||||
let sourceURL: URL
|
||||
let buildInstructionsURL: URL
|
||||
let privacyPolicyURL: URL
|
||||
let componentSources: [String: ComponentSourceMetadata]
|
||||
|
||||
static let bundled: SourceMetadata? = {
|
||||
guard let url = Bundle.main.url(forResource: "SourceMetadata", withExtension: "json"),
|
||||
let data = try? Data(contentsOf: url) else { return nil }
|
||||
return try? JSONDecoder().decode(SourceMetadata.self, from: data)
|
||||
}()
|
||||
}
|
||||
|
||||
struct ThirdPartyLicensesView: View {
|
||||
var body: some View {
|
||||
Group {
|
||||
switch LicenseCatalog.bundled {
|
||||
case .success(let catalog):
|
||||
List {
|
||||
if let application = catalog.components.first(where: { $0.id == "crossdesk" }) {
|
||||
Section {
|
||||
LabeledContent("版本", value: application.displayVersion)
|
||||
}
|
||||
Section {
|
||||
NavigationLink("软件许可") {
|
||||
ComponentLicenseView(component: application)
|
||||
}
|
||||
NavigationLink("开源组件") {
|
||||
OpenSourceComponentsView(catalog: catalog)
|
||||
}
|
||||
NavigationLink("源码与构建说明") {
|
||||
SourceCodeView(application: application)
|
||||
}
|
||||
} footer: {
|
||||
Text("许可与版权声明可离线查阅。")
|
||||
}
|
||||
}
|
||||
}
|
||||
case .failure:
|
||||
VStack(spacing: 12) {
|
||||
Image(systemName: "doc.text.magnifyingglass")
|
||||
.font(.largeTitle)
|
||||
Text("无法读取开源许可")
|
||||
.font(.headline)
|
||||
Text("应用中的许可文件缺失或损坏,请重新安装应用。")
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
.navigationTitle("关于 CrossDesk")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
}
|
||||
|
||||
private struct OpenSourceComponentsView: View {
|
||||
let catalog: LicenseCatalog
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
if let openFEC = catalog.components.first(where: { $0.id == "openfec" }) {
|
||||
Section("OpenFEC 告知") {
|
||||
Text("本应用使用 OpenFEC 提供前向纠错功能,遵循 CeCILL-C 1.0 许可。该许可规定了有限保证及责任限制,详情见许可全文。")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
Text("(c) Copyright 2009 - 2012 INRIA - All rights reserved")
|
||||
.font(.footnote)
|
||||
NavigationLink("OpenFEC 许可与源码") {
|
||||
ComponentLicenseView(component: openFEC)
|
||||
}
|
||||
}
|
||||
}
|
||||
Section {
|
||||
ForEach(catalog.components.filter { $0.id != "crossdesk" && $0.id != "openfec" }) { component in
|
||||
NavigationLink {
|
||||
ComponentLicenseView(component: component)
|
||||
} label: {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(component.name)
|
||||
Text(component.license)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
} footer: {
|
||||
Text("各组件遵循所列开源许可证,其授予的权利不受本应用普通使用条款限制。查看源码需要网络连接。")
|
||||
}
|
||||
}
|
||||
.navigationTitle("开源组件")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
}
|
||||
|
||||
private struct SourceCodeView: View {
|
||||
let application: LicensedComponent
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
Section("本版本源码与构建说明") {
|
||||
if let source = SourceMetadata.bundled {
|
||||
LabeledContent("源码版本", value: source.tag ?? String(source.revision.prefix(12)))
|
||||
.textSelection(.enabled)
|
||||
if source.isModified {
|
||||
Text("开发版本包含尚未发布的修改,以下链接为基础版本源码。")
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Link("查看源码", destination: source.sourceURL)
|
||||
Link("构建说明", destination: source.buildInstructionsURL)
|
||||
} else {
|
||||
Text("本版本源码信息暂不可用。")
|
||||
.foregroundStyle(.secondary)
|
||||
Link("项目主页", destination: application.sourceURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("源码与构建说明")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
}
|
||||
|
||||
private struct ComponentLicenseView: View {
|
||||
let component: LicensedComponent
|
||||
|
||||
var body: some View {
|
||||
List {
|
||||
Section {
|
||||
LabeledContent("版本", value: component.displayVersion)
|
||||
.textSelection(.enabled)
|
||||
LabeledContent("许可", value: component.license)
|
||||
Link("查看源码", destination: component.resolvedSourceURL)
|
||||
if let buildSourceURL = component.resolvedBuildSourceURL {
|
||||
Link("构建配方与项目补丁", destination: buildSourceURL)
|
||||
}
|
||||
}
|
||||
Section("许可与版权声明") {
|
||||
ForEach(component.documents) { document in
|
||||
NavigationLink {
|
||||
LicenseTextView(text: document.text)
|
||||
.navigationTitle(documentTitle(document.title))
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
} label: {
|
||||
Text(documentTitle(document.title))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle(component.name)
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
}
|
||||
|
||||
private func documentTitle(_ title: String) -> String {
|
||||
switch title {
|
||||
case "Source copyright and license notices": return "版权与许可声明"
|
||||
case "apps/ios/licenses/OPEN_SOURCE_NOTICE.txt": return "开源软件权利说明"
|
||||
case "LICENSE" where component.id == "crossdesk": return "GNU GPL 第 3 版"
|
||||
default: return title
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UITextView keeps long license documents selectable and efficient to scroll.
|
||||
private struct LicenseTextView: UIViewRepresentable {
|
||||
let text: String
|
||||
|
||||
func makeUIView(context: Context) -> UITextView {
|
||||
let view = UITextView()
|
||||
view.isEditable = false
|
||||
view.isSelectable = true
|
||||
view.dataDetectorTypes = [.link]
|
||||
view.adjustsFontForContentSizeCategory = true
|
||||
view.font = .preferredFont(forTextStyle: .body)
|
||||
view.textColor = .label
|
||||
view.backgroundColor = .systemBackground
|
||||
view.textContainerInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
|
||||
return view
|
||||
}
|
||||
|
||||
func updateUIView(_ view: UITextView, context: Context) {
|
||||
if view.text != text { view.text = text }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import Foundation
|
||||
|
||||
/// Serialize writes and deletions so an in-flight capture cannot recreate a
|
||||
/// preview after a clear/revocation has finished.
|
||||
final class ThumbnailFileStore {
|
||||
let directory: URL
|
||||
private let queue = DispatchQueue(label: "cn.crossdesk.mobile.thumbnails",
|
||||
qos: .utility)
|
||||
|
||||
init(directory: URL) {
|
||||
self.directory = directory
|
||||
}
|
||||
|
||||
func url(for fileName: String) -> URL {
|
||||
directory.appendingPathComponent(fileName, isDirectory: false)
|
||||
}
|
||||
|
||||
func save(fileName: String, makeData: @escaping () -> Data?,
|
||||
completion: @escaping (String?) -> Void) {
|
||||
queue.async {
|
||||
let saved: String? = autoreleasepool {
|
||||
guard let data = makeData() else { return nil }
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: self.directory,
|
||||
withIntermediateDirectories: true)
|
||||
var directory = self.directory
|
||||
var values = URLResourceValues()
|
||||
values.isExcludedFromBackup = true
|
||||
try directory.setResourceValues(values)
|
||||
#if os(iOS)
|
||||
try data.write(to: self.url(for: fileName),
|
||||
options: [.atomic, .completeFileProtection])
|
||||
#else
|
||||
try data.write(to: self.url(for: fileName), options: .atomic)
|
||||
#endif
|
||||
return fileName
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
completion(saved)
|
||||
}
|
||||
}
|
||||
|
||||
func remove(fileName: String) {
|
||||
queue.async { try? FileManager.default.removeItem(at: self.url(for: fileName)) }
|
||||
}
|
||||
|
||||
func removeAll(completion: @escaping (Bool) -> Void) {
|
||||
queue.async {
|
||||
do {
|
||||
if FileManager.default.fileExists(atPath: self.directory.path) {
|
||||
try FileManager.default.removeItem(at: self.directory)
|
||||
}
|
||||
completion(true)
|
||||
} catch {
|
||||
completion(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>method</key>
|
||||
<string>app-store-connect</string>
|
||||
<key>destination</key>
|
||||
<string>export</string>
|
||||
<key>signingStyle</key>
|
||||
<string>automatic</string>
|
||||
<key>manageAppVersionAndBuildNumber</key>
|
||||
<false/>
|
||||
<key>uploadSymbols</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
||||
+268
-10
@@ -7,7 +7,7 @@ There is no `WKWebView` or browser runtime.
|
||||
## Requirements
|
||||
|
||||
- Xcode 16 or newer
|
||||
- Xmake available on `PATH`
|
||||
- Xmake 3.1.1 available on `PATH` (or selected with `XMAKE_BIN`)
|
||||
- A physical arm64 iPhone or iPad running iOS 16 or newer
|
||||
|
||||
## Build
|
||||
@@ -22,6 +22,28 @@ cd crossdesk
|
||||
|
||||
For an existing checkout, run `git submodule update --init --recursive` from
|
||||
the repository root. All remaining commands below use that root directory.
|
||||
For a released app, select the tag shown in **Settings → About and open-source
|
||||
licenses** when cloning: `git clone --branch <source-tag> --recurse-submodules
|
||||
https://github.com/kunkundi/crossdesk.git`. The iOS marketing version is independent
|
||||
of the repository tag; use the source tag or commit recorded in the app.
|
||||
|
||||
Install [Xmake 3.1.1](https://github.com/xmake-io/xmake/releases/tag/v3.1.1),
|
||||
CMake, and a current Python 3 with setuptools/wheel. Pin the package repository
|
||||
in a separate Xmake global directory before building:
|
||||
|
||||
```sh
|
||||
export XMAKE_GLOBALDIR="$HOME/.cache/crossdesk/xmake-ios"
|
||||
xmake repo --update
|
||||
git -C "$XMAKE_GLOBALDIR/.xmake/repositories/xmake-repo" fetch origin 121109352da272cd1a3d4ed52f2dcda34f839955
|
||||
git -C "$XMAKE_GLOBALDIR/.xmake/repositories/xmake-repo" checkout --detach 121109352da272cd1a3d4ed52f2dcda34f839955
|
||||
```
|
||||
|
||||
Keep `XMAKE_GLOBALDIR` set for command-line Xcode builds. For builds launched
|
||||
from the Xcode app, set it as a user-defined build setting on the target, or
|
||||
pin the default `~/.xmake/repositories/xmake-repo` instead. The build checks
|
||||
the tool version, package repository commit and reviewed recipe hashes.
|
||||
Application dependencies are built from source, with Xmake precompiled
|
||||
package downloads disabled.
|
||||
|
||||
1. Open `apps/ios/CrossDeskMobile.xcodeproj` and select the `CrossDeskMobile`
|
||||
target and scheme.
|
||||
@@ -34,7 +56,8 @@ the repository root. All remaining commands below use that root directory.
|
||||
|
||||
The first build phase builds MiniRTC and the CrossDesk wire library, downloads
|
||||
and builds their dependencies, then merges the iPhoneOS archives into a local library under
|
||||
`Vendor/`. This build path targets physical devices; simulator builds are
|
||||
`Vendor/`. OpenSSL is kept separate and packaged as a static framework with SDK
|
||||
privacy resources in the Xcode products directory. This build path targets physical devices; simulator builds are
|
||||
not supported. The exact tool versions used by CI are recorded in the
|
||||
[workflow](../../.github/workflows/build.yml).
|
||||
|
||||
@@ -54,19 +77,147 @@ for that server. Remote control sessions then log in as `C-<identity>` and use
|
||||
the desktop-compatible `DisplayN`, `control_audio`, `mouse`, `keyboard`,
|
||||
`control_data`, `clipboard`, `file`, and `file_feedback` streams.
|
||||
|
||||
## Announcements
|
||||
|
||||
The home toolbar's bell opens **通知公告** and shows the unread count (capped
|
||||
at `99+` on the badge). The persistent identity peer fetches announcements after
|
||||
signaling connects, so a remote desktop session is not required. Opening the
|
||||
inbox, returning to the foreground, reconnecting, and `announcements_changed`
|
||||
events refresh the catalog. Pull to refresh or use the refresh button to retry.
|
||||
|
||||
The iOS inbox follows the desktop `announcements_list` protocol: summaries load
|
||||
in batches of 200 to count all unread announcements, while full bodies load in
|
||||
batches of 20 as the list scrolls. Opening a detail marks that revision read.
|
||||
Swipe or long-press a row to delete it after confirmation. Read and deleted
|
||||
revisions persist only on this device, scoped by server, port and device ID;
|
||||
updating an announcement makes its new revision visible and unread again.
|
||||
Plain text, line breaks, HTTP(S) URLs and `[label](URL)` links are supported.
|
||||
|
||||
Local state lives in Application Support and is excluded from backups. Failed
|
||||
writes leave the item unread or undeleted and display a retry message. Failed
|
||||
requests time out after 12 seconds and retain previously loaded content.
|
||||
Changing servers or withdrawing network consent clears the displayed inbox and
|
||||
invalidates pending responses; consent is required before fetching again.
|
||||
|
||||
## Video codecs
|
||||
|
||||
Every iOS build includes VideoToolbox, OpenH264, dav1d, and SVT-AV1. H.264 uses
|
||||
VideoToolbox by default; choose software processing under **设置 → 视频编解码 →
|
||||
处理方式** (Settings → Video codec → Processing mode) to use OpenH264 for H.264.
|
||||
The change takes effect on the next connection. AV1 encoding uses SVT-AV1 and AV1 decoding
|
||||
uses dav1d; VideoToolbox AV1 hardware decoding is currently unsupported.
|
||||
Every iOS build includes VideoToolbox, dav1d, and SVT-AV1. H.264 uses
|
||||
VideoToolbox exclusively; OpenH264 is excluded from the iOS dependencies and
|
||||
native archive. The hardware/software processing setting has been removed,
|
||||
and preferences saved by older versions are no longer read. H.264 codec
|
||||
initialization failure is reported without a software fallback.
|
||||
AV1 encoding uses SVT-AV1 and AV1 decoding uses dav1d; VideoToolbox AV1 hardware
|
||||
decoding is currently unsupported. Desktop builds retain OpenH264.
|
||||
|
||||
The native build script checks the merged archive for OpenH264 entry points
|
||||
and rejects a build if they are present, including in cached archives.
|
||||
|
||||
## Third-party licenses
|
||||
|
||||
**设置 → 关于** shows the app version and links to the application's
|
||||
license, open-source components, and source/build information. `crossdesk_wire`
|
||||
is part of CrossDesk's own source and is covered by its application license,
|
||||
not a separate third-party entry. OpenFEC is acknowledged at the top of the
|
||||
open-source components page, with its INRIA copyright, CeCILL-C terms and limited
|
||||
warranty/liability notice. Its embedded BSD and CC-BY-SA notices are preserved
|
||||
in the source-notices document as well.
|
||||
|
||||
`licenses/sources.json` pins the reviewed source archives (SHA-256), notice-review
|
||||
Git revisions, selected legal files and source-notice extraction rules.
|
||||
`CrossDeskMobile/Resources/ThirdPartyLicenses.json` is the generated resource
|
||||
bundled by Xcode. The catalog covers CrossDesk and 33 dependency entries for the default iOS build,
|
||||
including header-only dependencies, GLib's proxy-libintl, spdlog's bundled fmt,
|
||||
WebRTC-derived code, inih, and the applicable patent notices. Host build tools,
|
||||
OpenH264, desktop-only libraries, and the disabled libpsl built-in suffix list
|
||||
are excluded.
|
||||
|
||||
Regenerate from the pinned source distributions with Python 3.9 or newer:
|
||||
|
||||
```sh
|
||||
python3 apps/ios/scripts/generate_third_party_licenses.py --generate
|
||||
```
|
||||
|
||||
The collector uses original checksum-verified archives, including GLib's
|
||||
`COPYING` file even when Xmake excludes it from an extracted build directory.
|
||||
It reuses matching Xmake downloads or caches downloads outside the repository
|
||||
in `~/.cache/crossdesk/licenses/`. License text is preserved, with explicit
|
||||
character decoding for the legacy OpenFEC files. Copyright comment blocks are
|
||||
collected from the reviewed runtime source directories; the catalog is an
|
||||
attribution superset, not a claim that every source file survives linker
|
||||
dead stripping.
|
||||
|
||||
Normal Xcode builds verify the checked-in resource, local license files and
|
||||
package recipes offline before compiling native code. After compilation they
|
||||
also compare all resolved dependency versions (including header-only packages)
|
||||
with the catalog and check the merged archive's input hashes and pinned
|
||||
toolchain. A missing, stale or altered catalog fails the build. Ordinary MiniRTC
|
||||
code changes do not require changing the notice-review revision or regenerating
|
||||
the catalog. Changes to dependencies, license texts or embedded third-party
|
||||
notices still require reviewing and updating the affected catalog entries;
|
||||
regeneration alone does not select a new dependency version.
|
||||
`MINIRTC_ENABLE_AOM=true` also requires a reviewed AOM entry.
|
||||
|
||||
The source screen links to the exact application tag/commit, MiniRTC commit,
|
||||
and custom dependency recipes/patches. `SourceMetadata.json` is generated in
|
||||
the app bundle, not in the checkout. Development builds with local edits are
|
||||
explicitly identified as modified. Version-tag CI builds reject an unclean
|
||||
checkout or a mismatched tag. The release archive also carries
|
||||
`ThirdPartySources.json`, `SourceMetadata.json` and the open-source rights
|
||||
notice. `ThirdPartySources.json` preserves the notice-review catalog;
|
||||
`SourceMetadata.json` records the actual build commit and per-component version,
|
||||
source and recipe links used by the license screen, including MiniRTC, inih and
|
||||
WebRTC-derived code. These links update automatically on every build without
|
||||
rewriting the checked-in license resource. Release notes provide the
|
||||
corresponding source and build links.
|
||||
Keep the source tags, submodule commits and referenced dependency source
|
||||
archives available for recipients of that release.
|
||||
|
||||
To change a library, edit MiniRTC in its submodule, or modify the relevant
|
||||
package recipe/patch under `deps/submodules/minirtc/thirdparty`. If a package
|
||||
recipe changes, change its package configuration revision (or rebuild that
|
||||
package) so Xmake does not reuse a previous binary. Review affected notices,
|
||||
update recipe hashes, and commit MiniRTC. When the notice catalog changes,
|
||||
record the reviewed revision in `sources.json` and regenerate the catalog.
|
||||
Build the application again to relink it with
|
||||
the modified library. Use your own team and bundle identifier to install the
|
||||
modified build; the maintainer's signing credentials are not required.
|
||||
|
||||
These materials implement source identification and attribution. They do not
|
||||
by themselves resolve GPL/LGPL distribution-term compatibility or grant
|
||||
additional permissions from other copyright holders. Applicable modification,
|
||||
reverse-engineering and installation-information rights must also be respected.
|
||||
See [LGPLv3 section 4](https://www.gnu.org/licenses/lgpl-3.0.html) and
|
||||
[GPLv3 section 6](https://www.gnu.org/licenses/gpl-3.0.html).
|
||||
|
||||
## Optional codecs
|
||||
|
||||
The unused libaom backends are excluded by default. To include them for development,
|
||||
set the `MINIRTC_ENABLE_AOM` environment variable (or Xcode user-defined build setting)
|
||||
to `true`. This includes libaom in the merged native archive without changing the
|
||||
AV1 factories' choice of SVT-AV1 and dav1d.
|
||||
|
||||
## Privacy choices
|
||||
|
||||
A launch without stored consent shows the privacy notice before signaling
|
||||
registration, including after a previous refusal or withdrawal. Returning from
|
||||
the background also shows it until consent is granted. Declining dismisses it
|
||||
for the current visit and leaves settings, local history and the bundled
|
||||
privacy policy available. Settings → Privacy → Privacy and Authorization shows consent status and can
|
||||
withdraw consent to stop both the persistent identity peer and remote session. Consent is required
|
||||
again before reconnecting; foregrounding or relaunching does not grant it.
|
||||
|
||||
The notice opens as a native large sheet with a scrolling document above a fixed
|
||||
consent area. The agreement checkbox starts unchecked; **同意并继续** stays
|
||||
disabled until it is selected and the bundled policy is available.
|
||||
**暂不同意** dismisses the sheet for this visit. Swipe-to-dismiss is disabled
|
||||
so either action is explicit.
|
||||
|
||||
Remote desktop previews default to off, including on upgrade. Enabling and
|
||||
confirming saving in Settings → Privacy applies from the next connection. Previews stay local
|
||||
and are excluded from device backups. Disabling saving or withdrawing consent
|
||||
clears them; clearing is serialized after pending writes to prevent resurrection.
|
||||
Old previews saved without this choice are removed on upgrade.
|
||||
|
||||
## Physical-device test checklist
|
||||
|
||||
Run the app from Xcode on a physical device and connect to a current desktop
|
||||
@@ -74,9 +225,11 @@ build. Test the features in this order so a media problem is not confused with
|
||||
a data-channel problem:
|
||||
|
||||
1. **Video:** after the session connects, the waiting panel should be replaced
|
||||
by the remote desktop. Tap the floating icon to see the connection state,
|
||||
P2P/TURN mode, decoded resolution, and bitrate. The current menu does not
|
||||
display a frame counter.
|
||||
by the remote desktop. Tap the floating icon, then **网络状态** (Network
|
||||
status), to see video/audio/data/total receive and send bitrates, receive
|
||||
loss rates, submitted FPS, decoded resolution, video delay, connection RTT,
|
||||
P2P/TURN mode, and the actual SRTP encryption state. Scroll the panel in
|
||||
either orientation to see all metrics.
|
||||
2. **Audio:** play continuous sound on the remote computer, then toggle the
|
||||
speaker button. Audio is Opus-decoded by MiniRTC and played as 48 kHz mono
|
||||
16-bit PCM through `AVAudioEngine`.
|
||||
@@ -93,6 +246,30 @@ a data-channel problem:
|
||||
app's `Documents/Received` directory and can be exported with the share
|
||||
button beside the transfer status or Finder's Files tab.
|
||||
|
||||
Network status samples and caches displayed measurements once per second while
|
||||
the panel is open; video-frame redraws reuse that snapshot. Traffic and connection RTT
|
||||
expire after three seconds without a valid report; RTT uses the desktop's
|
||||
0.25-weight smoothing. FPS counts distinct frames submitted to the native
|
||||
display layer during the last second. Video delay averages calibrated capture
|
||||
time through display submission over that same window; it is an estimate, not
|
||||
a measurement of physical screen presentation. Missing calibration or stale
|
||||
samples show **—**, and idle video reaches zero FPS. Switching displays or
|
||||
backgrounding clears video samples; disconnecting clears all statistics.
|
||||
Receive loss rates are fractions converted to percentages. As on desktop,
|
||||
MiniRTC's total loss is the sum of the media loss rates, not a packet-weighted
|
||||
overall loss rate.
|
||||
|
||||
The reliable control channel's `host_info` also advertises `platform` as
|
||||
`windows`, `linux`, `macos`, `ios`, or `unknown`. Desktop and iOS controllers
|
||||
retain the received platform for the current session. Missing, malformed, or
|
||||
unrecognized values from older or other peers map to unknown (`未知` on iOS),
|
||||
without rejecting the remaining host information. Reconnecting clears the
|
||||
previous peer's platform; iOS sends `ios` in its own host information.
|
||||
On iOS, the received platform is also saved with each recent connection.
|
||||
When preview saving is off or no preview is available, the thumbnail placeholder
|
||||
shows the platform name. Existing history without platform metadata shows
|
||||
`未知` until host information is received from a subsequent connection.
|
||||
|
||||
For black-screen diagnosis, keep Xcode's debug console open and look for
|
||||
`CrossDesk` and `VideoToolbox` messages. With VideoToolbox H.264 decoding selected, look for
|
||||
`VideoToolbox decoded frame` from MiniRTC and `CrossDesk delivered latest frame`
|
||||
@@ -101,3 +278,84 @@ If decoded frames do not reach the bridge, check that the selected stream is
|
||||
named `Display1`, `Display2`, and so on. If no frames decode, check the selected
|
||||
codec and the desktop capture/encoding logs, then reconnect or switch displays
|
||||
to request a new key frame.
|
||||
|
||||
## App Store archive and bundle validation
|
||||
|
||||
OpenSSL is on Apple's
|
||||
[required SDK privacy-manifest list](https://developer.apple.com/support/third-party-SDK-requirements/).
|
||||
The iOS build compiles OpenSSL from source, packages it separately as
|
||||
`OpenSSL.framework`, then links and embeds it using Xcode's
|
||||
[static framework support](https://developer.apple.com/documentation/xcode/creating-a-static-framework).
|
||||
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.
|
||||
|
||||
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
|
||||
supported iOS versions; the random-device fallback is not compiled. Existing
|
||||
in-memory certificate/key handling remains available, while `OSSL_STORE` file
|
||||
URLs are intentionally unsupported. Signaling trust and hostname validation
|
||||
use Apple Security rather than OpenSSL's build-host certificate paths.
|
||||
Desktop OpenSSL builds are unchanged.
|
||||
|
||||
`package_openssl_ios.py` checks the actual OpenSSL archives for file metadata,
|
||||
disk-space and boot-time API imports before producing the framework. Its
|
||||
`sysctlbyname` calls are limited to the reviewed `armcap.c` CPU implementation
|
||||
selection, not fingerprinting. The SDK privacy manifest declares no tracking,
|
||||
SDK data collection or required-reason API use for this specific configuration.
|
||||
This is not a declaration about generic OpenSSL builds or the application's
|
||||
signaling/relay data processing. Source or configuration changes require another
|
||||
review; the packager rejects known forbidden imports even when reusing a cache.
|
||||
|
||||
`PrivacyInfo.xcprivacy` declares app preferences (`CA92.1`), sandbox and
|
||||
user-selected file metadata (`C617.1`, `3B52.1`), and elapsed/event timing
|
||||
(`35F9.1`, `8FFB.1`). MiniRTC uses timing for pacing, timeouts, RTT and media
|
||||
packet timestamps. The iOS GLib recipe disables unused filesystem-capacity
|
||||
and system-volume discovery. These APIs must not be repurposed for fingerprinting.
|
||||
The app-level manifest does not assert that the service collects no data: App Store
|
||||
Connect privacy answers also depend on actual signaling/relay-server practices.
|
||||
The application links to the [privacy policy](../../PRIVACY.md), including iOS
|
||||
clipboard, file, local thumbnail and Keychain behavior.
|
||||
|
||||
Validate a built bundle using:
|
||||
|
||||
```sh
|
||||
python3 apps/ios/scripts/verify_app_bundle.py /path/to/CrossDeskMobile.app
|
||||
```
|
||||
|
||||
For a release, first commit all application and submodule changes, regenerate
|
||||
notices for the committed dependency revision, and check out the intended
|
||||
version tag. Publish the tag and its referenced MiniRTC commit to the public repositories
|
||||
before distributing the app. Local tag verification cannot prove that recipients
|
||||
can fetch an unpublished commit. With an App Store-capable development team
|
||||
configured in Xcode:
|
||||
|
||||
```sh
|
||||
xcodebuild -project apps/ios/CrossDeskMobile.xcodeproj \
|
||||
-scheme CrossDeskMobile -configuration Release \
|
||||
-destination 'generic/platform=iOS' \
|
||||
-archivePath /tmp/CrossDeskMobile.xcarchive \
|
||||
CROSSDESK_RELEASE_BUILD=YES archive
|
||||
|
||||
python3 apps/ios/scripts/verify_app_bundle.py \
|
||||
/tmp/CrossDeskMobile.xcarchive/Products/Applications/CrossDeskMobile.app \
|
||||
--require-release
|
||||
|
||||
xcodebuild -exportArchive -archivePath /tmp/CrossDeskMobile.xcarchive \
|
||||
-exportOptionsPlist apps/ios/ExportOptions-AppStore.plist \
|
||||
-exportPath /tmp/CrossDeskMobile-AppStore
|
||||
```
|
||||
|
||||
Set a new `CURRENT_PROJECT_VERSION` for each upload. The export configuration
|
||||
creates a local App Store export; it does not submit the app. Distribution
|
||||
signing requires the appropriate Apple Developer Program membership and
|
||||
provisioning. The unsigned GitHub artifact is for development, not an App Store
|
||||
submission. Organizer/App Store Connect validation remains necessary.
|
||||
|
||||
The app embeds OpenSSL and libsrtp. Do not declare that encryption is limited
|
||||
to Apple system APIs or set `ITSAppUsesNonExemptEncryption=NO` without completing
|
||||
the applicable [export-compliance determination](https://developer.apple.com/help/app-store-connect/manage-app-information/overview-of-export-compliance).
|
||||
After that determination, supply the appropriate declaration and any required
|
||||
approval code in the distribution build. The repository deliberately does not
|
||||
preselect an exemption.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
CrossDesk 开源软件权利说明 / Open-source software rights
|
||||
|
||||
CrossDesk 按 GNU GPL 第 3 版发布,MiniRTC 按 GNU LGPL 第 3 版发布。
|
||||
其他组件适用各自列明的许可证。使用、复制、修改及再分发这些组件的权利,
|
||||
以相应许可证为准;本应用的普通使用条款不限制开源许可证授予你的权利。
|
||||
许可证中的保证、责任限制及其他条件仍然适用。
|
||||
|
||||
“本版本源码与构建说明”提供与发行版本对应的源码入口、子模块信息、
|
||||
依赖配方、补丁及构建说明。可以修改相关库后重新构建和链接应用。
|
||||
在自己的 iPhone 或 iPad 上运行修改版时,需要使用自己的 Apple 开发签名,
|
||||
并按构建文档设置开发团队和 Bundle Identifier。
|
||||
|
||||
CrossDesk is distributed under GNU GPL version 3; MiniRTC is distributed
|
||||
under GNU LGPL version 3. Other components are governed by their listed
|
||||
licenses. Your rights to use, copy, modify and redistribute those components
|
||||
are governed by the applicable licenses. The application's ordinary terms
|
||||
of use do not restrict rights granted by those open-source licenses.
|
||||
The licenses' warranty, liability and other provisions continue to apply.
|
||||
|
||||
The version-specific source and build links identify the application source,
|
||||
submodules, dependency recipes, patches and build instructions. You can
|
||||
modify the libraries and rebuild and relink the application. Running a
|
||||
modified build on your own iPhone or iPad requires your own Apple development
|
||||
signing setup, team and bundle identifier as described in the build guide.
|
||||
@@ -0,0 +1,906 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"platform": "iphoneos-arm64",
|
||||
"components": [
|
||||
{
|
||||
"id": "asio",
|
||||
"name": "Asio",
|
||||
"version": "1.32.0",
|
||||
"license": "BSL-1.0",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/chriskohlhoff/asio/archive/refs/tags/asio-1-32-0.tar.gz",
|
||||
"sha256": "f1b94b80eeb00bb63a3c8cef5047d4e409df4d8a3fe502305976965827d95672"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "asio/COPYING",
|
||||
"sha256": "5cc69ca9afd3417ed8e58bcd9c0bb730375e9e3e92b5aaf6483b93a2837e0cac"
|
||||
},
|
||||
{
|
||||
"path": "asio/LICENSE_1_0.txt",
|
||||
"sha256": "c9bff75738922193e67fa726fa225535870d2aa1059f91452c411736284ad566"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52bddc12cf0837117e935ea5d71aa5c35e7fd6ae802aa7401c6dba598cae0989",
|
||||
"recipe_path": "xmake-repo/packages/a/asio/xmake.lua",
|
||||
"package": "asio",
|
||||
"notice_prefixes": [
|
||||
"asio/include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "concurrentqueue",
|
||||
"name": "ConcurrentQueue",
|
||||
"version": "v1.0.4",
|
||||
"license": "(BSD-2-Clause OR BSL-1.0) / Zlib (semaphore)",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/cameron314/concurrentqueue/archive/refs/tags/v1.0.4.tar.gz",
|
||||
"sha256": "87fbc9884d60d0d4bf3462c18f4c0ee0a9311d0519341cac7cbd361c885e5281"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE.md",
|
||||
"sha256": "22331571e5e3dbe4c79ad715e23127bdf3beabd75052c953ddabf191ef799e14"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "23c69dc09488527b0d6adf1d25f795a9f0afdc7a1d594c44603c2dd07162faa4",
|
||||
"recipe_path": "xmake-repo/packages/c/concurrentqueue/xmake.lua",
|
||||
"package": "concurrentqueue",
|
||||
"notice_prefixes": [
|
||||
"concurrentqueue.h",
|
||||
"blockingconcurrentqueue.h",
|
||||
"lightweightsemaphore.h"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "crossdesk",
|
||||
"name": "CrossDesk",
|
||||
"version": "application source",
|
||||
"license": "GPL-3.0-only",
|
||||
"source": {
|
||||
"kind": "repository",
|
||||
"url": "https://github.com/kunkundi/crossdesk",
|
||||
"revision": null
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986"
|
||||
},
|
||||
{
|
||||
"path": "apps/ios/licenses/OPEN_SOURCE_NOTICE.txt",
|
||||
"sha256": "34720d126e6373603d0c1802a8c3276802b93f2a8fbbf2b61837c6fdefea8877"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "dav1d",
|
||||
"name": "dav1d",
|
||||
"version": "1.4.3",
|
||||
"license": "BSD-2-Clause and patent grant",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://code.videolan.org/videolan/dav1d/-/archive/e9986de7f4264940af6fa1df1498fd2754077de4/dav1d-e9986de7f4264940af6fa1df1498fd2754077de4.tar.gz",
|
||||
"sha256": "ba147ff83d6c73f578a12f8eece636226e9c1f40cd55a11841a3bcb2c88cd46a",
|
||||
"revision": "e9986de7f4264940af6fa1df1498fd2754077de4"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "b327887de263238deaa80c34cdd2ff3e0ba1d35db585ce14a37ce3e74ee389e9"
|
||||
},
|
||||
{
|
||||
"path": "doc/PATENTS",
|
||||
"sha256": "335eca574598bf4ca181b12f708d6669e5a5e78c8e1513e5b35fa1f03901484b"
|
||||
}
|
||||
],
|
||||
"package": "dav1d",
|
||||
"notice_prefixes": [
|
||||
"src/",
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "glib",
|
||||
"name": "GLib / GObject / GIO / GModule / GThread / GVDB",
|
||||
"version": "2.84.1",
|
||||
"license": "LGPL-2.1-or-later and embedded notices",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://download.gnome.org/sources/glib/2.84/glib-2.84.1.tar.xz",
|
||||
"sha256": "2b4bc2ec49611a5fc35f86aca855f2ed0196e69e53092bab6bb73396bf30789a"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "fa6f36630bb1e0c571d34b2bbdf188d08495c9dbf58f28cac112f303fc1f58fb"
|
||||
},
|
||||
{
|
||||
"path": "LICENSES/Apache-2.0.txt",
|
||||
"sha256": "074e6e32c86a4c0ef8b3ed25b721ca23aca83df277cd88106ef7177c354615ff"
|
||||
},
|
||||
{
|
||||
"path": "LICENSES/CC0-1.0.txt",
|
||||
"sha256": "a2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499"
|
||||
},
|
||||
{
|
||||
"path": "LICENSES/LGPL-2.1-only.txt",
|
||||
"sha256": "fa6f36630bb1e0c571d34b2bbdf188d08495c9dbf58f28cac112f303fc1f58fb"
|
||||
},
|
||||
{
|
||||
"path": "LICENSES/LLVM-exception.txt",
|
||||
"sha256": "e34c58338bd89d43e709e226610d8f32b3e3c47f4ad9a99a8dc1d4ac7842488e"
|
||||
},
|
||||
{
|
||||
"path": "LICENSES/MIT.txt",
|
||||
"sha256": "b85dcd3e453d05982552c52b5fc9e0bdd6d23c6f8e844b984a88af32570b0cc0"
|
||||
},
|
||||
{
|
||||
"path": "LICENSES/MPL-1.1.txt",
|
||||
"sha256": "6214f8b1300bb9f37b16ebc146f8f61af0187e0025042ff95c8b3030744a8795"
|
||||
},
|
||||
{
|
||||
"path": "subprojects/gvdb/COPYING",
|
||||
"sha256": "bdbcdaa7858872393e9d6b216bbdc8a23e99d98dd6cdb7cda19458025b9e19fc"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "773cac2e1a5aec087abc9347c7278f3fca40e36212b33a5f01012875cfbf7e6c",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/glib/xmake.lua",
|
||||
"package": "glib",
|
||||
"notice_prefixes": [
|
||||
"glib/",
|
||||
"gobject/",
|
||||
"gio/",
|
||||
"gmodule/",
|
||||
"subprojects/gvdb/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "gssdp",
|
||||
"name": "GSSDP",
|
||||
"version": "1.6.4",
|
||||
"license": "LGPL-2.1-or-later",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://download.gnome.org/sources/gssdp/1.6/gssdp-1.6.4.tar.xz",
|
||||
"sha256": "ff97fdfb7f561d3e6813b4f6a2145259e7c2eff43cc0e63f3fd031d0b6266032"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "dc626520dcd53a22f727af3ee42c770e56c97a64fe3adb063799d8ab032fe551"
|
||||
},
|
||||
{
|
||||
"path": "AUTHORS",
|
||||
"sha256": "66b5509fcdd21acaab5d7a3856e699bada9e9ebf0485312abbe987711bc7bd27"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52667099a445f7004b9200df4ed771dd74e73745a5c6dc7fe728168e9f8b3e7a",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/gupnp/xmake.lua",
|
||||
"package": "gssdp",
|
||||
"notice_prefixes": [
|
||||
"libgssdp/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "gupnp",
|
||||
"name": "GUPnP",
|
||||
"version": "1.6.9",
|
||||
"license": "LGPL-2.1-or-later",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://download.gnome.org/sources/gupnp/1.6/gupnp-1.6.9.tar.xz",
|
||||
"sha256": "2edb6ee3613558e62f538735368aee27151b7e09d4e2e2c51606833da801869b"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "dc626520dcd53a22f727af3ee42c770e56c97a64fe3adb063799d8ab032fe551"
|
||||
},
|
||||
{
|
||||
"path": "AUTHORS",
|
||||
"sha256": "fadd2ab40439bc89d2e9540c02aef1f23edea96983af9cceaef345a9423d3c70"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52667099a445f7004b9200df4ed771dd74e73745a5c6dc7fe728168e9f8b3e7a",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/gupnp/xmake.lua",
|
||||
"package": "gupnp",
|
||||
"notice_prefixes": [
|
||||
"libgupnp/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "gupnp-igd",
|
||||
"name": "GUPnP IGD",
|
||||
"version": "1.6.0",
|
||||
"license": "LGPL-2.1-or-later",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://download.gnome.org/sources/gupnp-igd/1.6/gupnp-igd-1.6.0.tar.xz",
|
||||
"sha256": "4099978339ab22126d4968f2a332b6d094fc44c78797860781f1fc2f11771b74"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "6095e9ffa777dd22839f7801aa845b31c9ed07f3d6bf8a26dc5d2dec8ccc0ef3"
|
||||
},
|
||||
{
|
||||
"path": "AUTHORS",
|
||||
"sha256": "77a943ea347578cfcffc032616707d43e5f5e03a12f864c0d421c3d632fc1582"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52667099a445f7004b9200df4ed771dd74e73745a5c6dc7fe728168e9f8b3e7a",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/gupnp/xmake.lua",
|
||||
"package": "gupnp-igd",
|
||||
"notice_prefixes": [
|
||||
"libgupnp-igd/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "inih",
|
||||
"name": "inih / INIReader",
|
||||
"version": "24d9d9deefb95ede2cdb18e77cb01350101f70f8",
|
||||
"license": "BSD-3-Clause",
|
||||
"source": {
|
||||
"kind": "repository",
|
||||
"url": "https://github.com/kunkundi/minirtc",
|
||||
"revision": "24d9d9deefb95ede2cdb18e77cb01350101f70f8"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "deps/submodules/minirtc/src/inih/LICENSE",
|
||||
"sha256": "bd2a675a5a26fbff77f171f3a15afb1a9c7855be1a01c7e3fd16b8d2617acdda"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "nlohmann_json",
|
||||
"name": "JSON for Modern C++ / Hedley",
|
||||
"version": "v3.11.3",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/nlohmann/json/archive/refs/tags/v3.11.3.tar.gz",
|
||||
"sha256": "0d8ef5af7f9794e3263480193c491549b2ba6cc74bb018906202ada498a79406"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE.MIT",
|
||||
"sha256": "86b998c792894ccb911a1cb7994f7a9652894e7a094c0b5e45be2f553f45cf14"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "eadd211f0521a18207e9544c0c5a08c41dca578fce99df5c2577f6fcf2a0fdce",
|
||||
"recipe_path": "xmake-repo/packages/n/nlohmann_json/xmake.lua",
|
||||
"package": "nlohmann_json",
|
||||
"notice_prefixes": [
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "kcp",
|
||||
"name": "KCP",
|
||||
"version": "1.7",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/skywind3000/kcp/archive/refs/tags/1.7.tar.gz",
|
||||
"sha256": "b4d26994d95599ab0c44e1f93002f9fda275094a879d66c192d79d596529199e"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "6587fd02a924b97dbd6758b0573ddec056fb494a84f3709c5aaa33ce1f7f029c"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "f86cac2c4b884f3347a39a59f3dd8de566c257c7fd481c6e49b05f4730f12c4f",
|
||||
"recipe_path": "xmake-repo/packages/k/kcp/xmake.lua",
|
||||
"package": "kcp",
|
||||
"notice_prefixes": [
|
||||
"ikcp.c",
|
||||
"ikcp.h"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "libdatachannel",
|
||||
"name": "libdatachannel",
|
||||
"version": "v0.24.5",
|
||||
"license": "MPL-2.0",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/paullouisageneau/libdatachannel/archive/refs/tags/v0.24.5.tar.gz",
|
||||
"sha256": "454537c3cd526bed935d847bb2dff4046f266eef84d43b2a5f2f2f293c0026f4"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "b3ec15652a47d65e0a1f85f62d02c098c5cf5b8d8c3cf7b03ff099efa7016326",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/libdatachannel/xmake.lua",
|
||||
"package": "libdatachannel",
|
||||
"notice_prefixes": [
|
||||
"include/",
|
||||
"src/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "libffi",
|
||||
"name": "libffi",
|
||||
"version": "3.4.8",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/libffi/libffi/releases/download/v3.4.8/libffi-3.4.8.tar.gz",
|
||||
"sha256": "bc9842a18898bfacb0ed1252c4febcc7e78fa139fd27fdc7a3e30d9d9356119b"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "67894089811f93fca47a76f85e017da6f8582d4ba0905963c6e0f1ad6df7a195"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "de19ac4e3e91ef5715ac582c75e0d10404dc14ec4e33b2e764dc2637a78d24e9",
|
||||
"recipe_path": "xmake-repo/packages/l/libffi/xmake.lua",
|
||||
"package": "libffi",
|
||||
"notice_prefixes": [
|
||||
"src/",
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "libnice",
|
||||
"name": "libnice",
|
||||
"version": "0.1.24",
|
||||
"license": "MPL-1.1 OR LGPL-2.1-or-later",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://gitlab.freedesktop.org/libnice/libnice/-/archive/0.1.24/libnice-0.1.24.tar.gz",
|
||||
"sha256": "1da5ac13ed5d4e175e0d2d46ad3748c6635244f8f3eb2b8e31578ef59aa2ddce"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "e5504e5ffe894870ea1a652df957a120ead9c3f9a5e9d314ca41ba06f2d72024"
|
||||
},
|
||||
{
|
||||
"path": "COPYING.LGPL",
|
||||
"sha256": "a9bdde5616ecdd1e980b44f360600ee8783b1f99b8cc83a2beb163a0a390e861"
|
||||
},
|
||||
{
|
||||
"path": "COPYING.MPL",
|
||||
"sha256": "3b3c75ae6c663c4f93987647eb5463d33dc1602a1aded3ac479773f2c3928e3a"
|
||||
},
|
||||
{
|
||||
"path": "AUTHORS",
|
||||
"sha256": "d72eb6fa9d5e93abb11d13b6c6f04fda2ba183d0705e703887cda243f6f1eead"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "7d7c30d7d63245d0190e64b050184f6ff6933ef9133bff5329d62a7b9b685441",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/libnice/xmake.lua",
|
||||
"package": "libnice",
|
||||
"notice_prefixes": [
|
||||
"agent/",
|
||||
"nice/",
|
||||
"random/",
|
||||
"socket/",
|
||||
"stun/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "upnp-libpsl",
|
||||
"name": "libpsl",
|
||||
"version": "0.21.5",
|
||||
"license": "MIT / BSD-3-Clause",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/rockdaboot/libpsl/releases/download/0.21.5/libpsl-0.21.5.tar.gz",
|
||||
"sha256": "1dcc9ceae8b128f3c0b3f654decd0e1e891afc6ff81098f227ef260449dae208"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "322392e6001b2b3b0fca705dc9f11f26e12441188ecde50eb1d22909980b2925"
|
||||
},
|
||||
{
|
||||
"path": "src/LICENSE.chromium",
|
||||
"sha256": "1d7f52747a9169751cdf2641a8299c0098e9ecdf9429296ffd55bdb14c9ed5b3"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52667099a445f7004b9200df4ed771dd74e73745a5c6dc7fe728168e9f8b3e7a",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/gupnp/xmake.lua",
|
||||
"package": "upnp-libpsl",
|
||||
"notice_prefixes": [
|
||||
"src/",
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "libsoup",
|
||||
"name": "libsoup",
|
||||
"version": "3.6.5",
|
||||
"license": "LGPL-2.0-or-later",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://download.gnome.org/sources/libsoup/3.6/libsoup-3.6.5.tar.xz",
|
||||
"sha256": "6891765aac3e949017945c3eaebd8cc8216df772456dc9f460976fbdb7ada234"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "b7993225104d90ddd8024fd838faf300bea5e83d91203eab98e29512acebd69c"
|
||||
},
|
||||
{
|
||||
"path": "AUTHORS",
|
||||
"sha256": "f8776285b4556368878a1b903a1f0e6d6cee342284961562a7716a2dacc28321"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52667099a445f7004b9200df4ed771dd74e73745a5c6dc7fe728168e9f8b3e7a",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/gupnp/xmake.lua",
|
||||
"package": "libsoup",
|
||||
"notice_prefixes": [
|
||||
"libsoup/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "libsrtp",
|
||||
"name": "libsrtp",
|
||||
"version": "v2.7.0",
|
||||
"license": "BSD-3-Clause",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/cisco/libsrtp/archive/refs/tags/v2.7.0.tar.gz",
|
||||
"sha256": "54facb1727a557c2a76b91194dcb2d0a453aaf8e2d0cbbf1e3c2848c323e28ad"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "8e19d42a1eec9561f3f347253ddf2e385c55f392f025bb0fd41b88dbf38db5ae"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "9629edb8d395ea3017af1702cafea57173ca0a6a1ea305a6174b1936598faec6",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/libsrtp/xmake.lua",
|
||||
"package": "libsrtp",
|
||||
"notice_prefixes": [
|
||||
"srtp/",
|
||||
"crypto/",
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "upnp-libxml2",
|
||||
"name": "libxml2",
|
||||
"version": "2.14.6",
|
||||
"license": "MIT and embedded notices",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://download.gnome.org/sources/libxml2/2.14/libxml2-2.14.6.tar.xz",
|
||||
"sha256": "7ce458a0affeb83f0b55f1f4f9e0e55735dbfc1a9de124ee86fb4a66b597203a"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "Copyright",
|
||||
"sha256": "5d4873884a890122a4b9b20ad56ac6f7da1d796a5bfcf04a427970ac96217626"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "52667099a445f7004b9200df4ed771dd74e73745a5c6dc7fe728168e9f8b3e7a",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/gupnp/xmake.lua",
|
||||
"package": "upnp-libxml2",
|
||||
"notice_prefixes": [
|
||||
"include/"
|
||||
],
|
||||
"notice_root_files": true
|
||||
},
|
||||
{
|
||||
"id": "libyuv",
|
||||
"name": "libyuv",
|
||||
"version": "2025.8.14",
|
||||
"license": "BSD-3-Clause and patent grant",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://codeload.github.com/kunkundi/libyuv/tar.gz/ec10b61c58ee4b8fbe648d2744d9dad9ccba6430",
|
||||
"sha256": "e6e83acefcb9322a498a04c2c417491ceab18cf9750d306110ab5ab27d84377b",
|
||||
"revision": "ec10b61c58ee4b8fbe648d2744d9dad9ccba6430"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "2b2cc1180c7e6988328ad2033b04b80117419db9c4c584918bbb3cfec7e9364f"
|
||||
},
|
||||
{
|
||||
"path": "PATENTS",
|
||||
"sha256": "4da84211f947c6f9f7dd8fbce513e1522e01833407ae732b8c9a2bbb75fed495"
|
||||
},
|
||||
{
|
||||
"path": "AUTHORS",
|
||||
"sha256": "0c4a51c72a06b3431bb2b750e3b04dbe3694b22e2fcae6e370216424eec56d52"
|
||||
}
|
||||
],
|
||||
"package": "libyuv",
|
||||
"notice_prefixes": [
|
||||
"source/",
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "minirtc",
|
||||
"name": "MiniRTC",
|
||||
"version": "24d9d9deefb95ede2cdb18e77cb01350101f70f8",
|
||||
"license": "LGPL-3.0-only",
|
||||
"source": {
|
||||
"kind": "repository",
|
||||
"url": "https://github.com/kunkundi/minirtc",
|
||||
"revision": "24d9d9deefb95ede2cdb18e77cb01350101f70f8"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "deps/submodules/minirtc/LICENSE",
|
||||
"sha256": "ea8af5e789cb2d4e9b10bce3874982ade163b749b6bfbdb32e2df21c4d106de1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "nghttp2",
|
||||
"name": "nghttp2",
|
||||
"version": "1.68.0",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/nghttp2/nghttp2/releases/download/v1.68.0/nghttp2-1.68.0.tar.gz",
|
||||
"sha256": "2c16ffc588ad3f9e2613c3fad72db48ecb5ce15bc362fcc85b342e48daf51013"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "6b94f3abc1aabd0c72a7c7d92a77f79dda7c8a0cb3df839a97890b4116a2de2a"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "eec10214a906c663f74e3e6bf8952cddec39fec3cac710c10d8b9ea669c9ab79",
|
||||
"recipe_path": "xmake-repo/packages/n/nghttp2/xmake.lua",
|
||||
"package": "nghttp2",
|
||||
"notice_prefixes": [
|
||||
"lib/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "openfec",
|
||||
"name": "OpenFEC",
|
||||
"version": "1.4.2",
|
||||
"license": "CeCILL-C 1.0 / BSD / CC-BY-SA-3.0",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/kunkundi/openfec/archive/refs/tags/1.4.2.tar.gz",
|
||||
"sha256": "5aa19dc56038f4b19927efb53ca28e896fb05f068a4715de512f0709420f03be"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENCE_CeCILL-C_V1-en.txt",
|
||||
"sha256": "b48f5dc16f144cd79ddaadce3cc8ef183778a0b4f75ab4362e134b347ca20f3d",
|
||||
"encoding": "iso-8859-1"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "8644c6306ad6ba4c974dd949d56178c761b72d503fe7c4a577a23817effa6243",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/openfec/xmake.lua",
|
||||
"package": "openfec",
|
||||
"notice_prefixes": [
|
||||
"src/lib_common/",
|
||||
"src/lib_stable/"
|
||||
],
|
||||
"notice_encodings": {
|
||||
"src/lib_common/linear_binary_codes_utils/binary_matrix/of_hamming_weight.c": "gb18030",
|
||||
"src/lib_common/linear_binary_codes_utils/binary_matrix/of_hamming_weight.h": "gb18030"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "openssl3",
|
||||
"name": "OpenSSL",
|
||||
"version": "3.3.2",
|
||||
"license": "Apache-2.0 and embedded notices",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/openssl/openssl/archive/refs/tags/openssl-3.3.2.zip",
|
||||
"sha256": "4cda357946f9dd5541b565dba35348d614288e88aeb499045018970c789c9d61"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE.txt",
|
||||
"sha256": "7d5450cb2d142651b8afa315b5f238efc805dad827d91ba367d8516bc9d49e7a"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "864c308edf59fd802babd45d064d8575635ecd577e829df2b2c7ac7a4d06d4d7",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/openssl/xmake.lua",
|
||||
"package": "openssl3",
|
||||
"notice_prefixes": [
|
||||
"crypto/",
|
||||
"ssl/",
|
||||
"include/",
|
||||
"providers/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "libopus",
|
||||
"name": "Opus",
|
||||
"version": "1.5.1",
|
||||
"license": "BSD-3-Clause and patent grants",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://downloads.xiph.org/releases/opus/opus-1.5.1.tar.gz",
|
||||
"sha256": "b84610959b8d417b611aa12a22565e0a3732097c6389d19098d844543e340f85"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "01e1167d54a096d123cf6dfbbeb19587278845c6481d2d66d545669846079551"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "c965643eb4e093858c27c402e6cde544620460f2169c89d8ff2bab01111d022b",
|
||||
"recipe_path": "xmake-repo/packages/l/libopus/xmake.lua",
|
||||
"package": "libopus",
|
||||
"notice_prefixes": [
|
||||
"src/",
|
||||
"include/",
|
||||
"celt/",
|
||||
"silk/",
|
||||
"dnn/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "pcre2",
|
||||
"name": "PCRE2 / SLJIT",
|
||||
"version": "10.47",
|
||||
"license": "BSD-3-Clause / BSD-2-Clause",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.47/pcre2-10.47.tar.gz",
|
||||
"sha256": "c08ae2388ef333e8403e670ad70c0a11f1eed021fd88308d7e02f596fcd9dc16"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENCE.md",
|
||||
"sha256": "197d8a73ffee0d6b09adba2f9c677b5f5aede24edf89258a68e48248d010d811"
|
||||
},
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "99272c55f3dcfa07a8a7e15a5c1a33096e4727de74241d65fa049fccfdd59507"
|
||||
},
|
||||
{
|
||||
"path": "deps/sljit/LICENSE",
|
||||
"sha256": "5f216505c0f6ea3273caec89e766eef93cdeb7bbb0c429f9360116d7c938feeb"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "821f1fbc91434f4324be88eeea754db09c5d7be31446242764861ca2aee136b7",
|
||||
"recipe_path": "xmake-repo/packages/p/pcre2/xmake.lua",
|
||||
"package": "pcre2",
|
||||
"notice_prefixes": [
|
||||
"src/",
|
||||
"deps/sljit/sljitLir.c",
|
||||
"deps/sljit/sljitLir.h"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "plog",
|
||||
"name": "plog",
|
||||
"version": "1.1.11",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/SergiusTheBest/plog/archive/refs/tags/1.1.11.tar.gz",
|
||||
"sha256": "d60b8b35f56c7c852b7f00f58cbe9c1c2e9e59566c5b200512d0cdbb6309a7c2"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "e4d01796524cbc13b1571a1f0914823c6a23b316ba039e7014f47a4eef7fd4c3"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "deb525d09b5b79351eeb524ab3bc6a3009e434974e585e5e8852c491d7fa07c8",
|
||||
"recipe_path": "xmake-repo/packages/p/plog/xmake.lua",
|
||||
"package": "plog",
|
||||
"notice_prefixes": [
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "proxy-libintl",
|
||||
"name": "proxy-libintl (GLib libintl)",
|
||||
"version": "33934de09af6a6627eb44e310a8079df009abdbb",
|
||||
"license": "LGPL-2.0-or-later",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://codeload.github.com/frida/proxy-libintl/tar.gz/33934de09af6a6627eb44e310a8079df009abdbb",
|
||||
"sha256": "4ab5af85ec6124cb526a15c58bbc0877d241807e30855779808dbf9292d861aa",
|
||||
"revision": "33934de09af6a6627eb44e310a8079df009abdbb"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "d245807f90032872d1438d741ed21e2490e1175dc8aa3afa5ddb6c8e529b58e5"
|
||||
}
|
||||
],
|
||||
"bundled_by": "glib",
|
||||
"notice_prefixes": [
|
||||
"src/",
|
||||
"libintl.c",
|
||||
"libintl.h"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "spdlog",
|
||||
"name": "spdlog / fmt 10.2.1",
|
||||
"version": "v1.14.1",
|
||||
"license": "MIT",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/gabime/spdlog/archive/refs/tags/v1.14.1.zip",
|
||||
"sha256": "429dfdf3afc1984feb59e414353c21c110bc79609f6d7899d52f6aa388646f6d"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "4ccecab18d1ff0b61174fe3d6c430541625d3ddb865b0d5887db296f883c76e7"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "5b299effb366420b4920c5b89e6535b76173136d91ee01f8f7d3423486a93549",
|
||||
"recipe_path": "xmake-repo/packages/s/spdlog/xmake.lua",
|
||||
"package": "spdlog",
|
||||
"notice_prefixes": [
|
||||
"include/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "sqlite3",
|
||||
"name": "SQLite",
|
||||
"version": "3.50.0+400",
|
||||
"license": "Public domain",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://sqlite.org/2025/sqlite-autoconf-3500400.tar.gz",
|
||||
"sha256": "a3db587a1b92ee5ddac2f66b3edb41b26f9c867275782d46c3a088977d6a5b18"
|
||||
},
|
||||
"documents": [],
|
||||
"recipe_sha256": "a752522259dbd722ea79beaa01e5287429ccb37643ccffbecf5fa30ec4df30fd",
|
||||
"recipe_path": "xmake-repo/packages/s/sqlite3/xmake.lua",
|
||||
"package": "sqlite3",
|
||||
"notice_prefixes": [
|
||||
"sqlite3.h"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "svt-av1",
|
||||
"name": "SVT-AV1",
|
||||
"version": "v3.0.2",
|
||||
"license": "BSD-3-Clause-Clear / BSD-2-Clause, AOMedia patent license and embedded notices",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://gitlab.com/AOMediaCodec/SVT-AV1/-/archive/efc905a7c2ed155b3654d7968173622734eeb0c0/SVT-AV1-efc905a7c2ed155b3654d7968173622734eeb0c0.tar.gz",
|
||||
"sha256": "50a897d58470b06f99b386dc691ab63e802962421e6abdb75e4d234a3e73cd6a",
|
||||
"revision": "efc905a7c2ed155b3654d7968173622734eeb0c0"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE.md",
|
||||
"sha256": "0acc2fcb27472bdc9aaf8b71f37055bbdac4f54671b7d922f241bd7fcd0dd3e6"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE-BSD2.md",
|
||||
"sha256": "c582fcbeb9cf972a60d298bfaf41dc5adff2dd14208946edcb9bb56a281e8438"
|
||||
},
|
||||
{
|
||||
"path": "PATENTS.md",
|
||||
"sha256": "20678ab10402659106dc4c147c97b2a6e94b5c0695415e15a8f195ebc3547922"
|
||||
},
|
||||
{
|
||||
"path": "third_party/fastfeat/LICENSE",
|
||||
"sha256": "043dcfd059386f9facd376351b2bd79325778744aa442177390cdfcca54babed"
|
||||
},
|
||||
{
|
||||
"path": "third_party/safestringlib/LICENSE",
|
||||
"sha256": "c0f99a208799ca20c9ccf31a30533d49334eb458dca5a3d14f9afe3e884e5d7d"
|
||||
}
|
||||
],
|
||||
"package": "svt-av1",
|
||||
"notice_prefixes": [
|
||||
"Source/",
|
||||
"third_party/fastfeat/",
|
||||
"third_party/safestringlib/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "usrsctp",
|
||||
"name": "usrsctp",
|
||||
"version": "0.9.5+0",
|
||||
"license": "BSD-3-Clause and embedded notices",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/sctplab/usrsctp/archive/refs/tags/0.9.5.0.tar.gz",
|
||||
"sha256": "260107caf318650a57a8caa593550e39bca6943e93f970c80d6c17e59d62cd92"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE.md",
|
||||
"sha256": "fa53711b25af4b9a9b8dadfea3cb38166ec4b96760c8d62b284055554537d9ef"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "e3dac7d1db8e5bc79d99851e2486371af19962a4b8fca6eaac3156c00eb73b92",
|
||||
"recipe_path": "xmake-repo/packages/u/usrsctp/xmake.lua",
|
||||
"package": "usrsctp",
|
||||
"notice_prefixes": [
|
||||
"usrsctplib/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "webrtc",
|
||||
"name": "WebRTC-derived code in MiniRTC",
|
||||
"version": "24d9d9deefb95ede2cdb18e77cb01350101f70f8",
|
||||
"license": "BSD-3-Clause and patent grant",
|
||||
"source": {
|
||||
"kind": "repository",
|
||||
"url": "https://github.com/kunkundi/minirtc",
|
||||
"revision": "24d9d9deefb95ede2cdb18e77cb01350101f70f8"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "deps/submodules/minirtc/thirdparty/webrtc/LICENSE",
|
||||
"sha256": "ab00a482b6a3902e40211b43c5d0441962ea99b6cc7c25c0f243fa270b78d482"
|
||||
},
|
||||
{
|
||||
"path": "deps/submodules/minirtc/thirdparty/webrtc/PATENTS",
|
||||
"sha256": "01462e2068d1a04c2274f3389773014c14ed9bc3446b28303543bd3e3c064145"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "websocketpp",
|
||||
"name": "WebSocket++",
|
||||
"version": "0.8.2",
|
||||
"license": "BSD-3-Clause and embedded notices",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/zaphoyd/websocketpp/archive/refs/tags/0.8.2.tar.gz",
|
||||
"sha256": "6ce889d85ecdc2d8fa07408d6787e7352510750daa66b5ad44aacb47bea76755"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "COPYING",
|
||||
"sha256": "b31e597bc777d884a39663c11d0557a0af40780e1f451de11ea5103924a69667"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "beac245a717c2bc3bc8d17265d9fc9b54f699f3833b11513f8723c4dbaffd539",
|
||||
"recipe_path": "deps/submodules/minirtc/thirdparty/websocketpp/xmake.lua",
|
||||
"package": "websocketpp",
|
||||
"notice_prefixes": [
|
||||
"websocketpp/"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "zlib",
|
||||
"name": "zlib",
|
||||
"version": "v1.3.2",
|
||||
"license": "Zlib",
|
||||
"source": {
|
||||
"kind": "archive",
|
||||
"url": "https://github.com/madler/zlib/archive/refs/tags/v1.3.2.tar.gz",
|
||||
"sha256": "b99a0b86c0ba9360ec7e78c4f1e43b1cbdf1e6936c8fa0f6835c0cd694a495a1"
|
||||
},
|
||||
"documents": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"sha256": "e32ff4e00d9d94930537635291da39e7e612703334bf6fde8c7f1686fe8a45a2"
|
||||
}
|
||||
],
|
||||
"recipe_sha256": "7832bcb086709a0739ae1abeff035f7a103c7169dc8af61ebf91dd887fcbd054",
|
||||
"recipe_path": "xmake-repo/packages/z/zlib/xmake.lua",
|
||||
"package": "zlib",
|
||||
"notice_prefixes": [
|
||||
"zlib.h"
|
||||
]
|
||||
}
|
||||
],
|
||||
"bundle_sha256": "f54e5e2168bf6e91d81a413931a052d29f59e0c221df5e1de3f51bd27c662c3a",
|
||||
"toolchain": {
|
||||
"xmake_version": "3.1.1",
|
||||
"xmake_repository_revision": "121109352da272cd1a3d4ed52f2dcda34f839955"
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,10 @@ fi
|
||||
XMAKE_DEVELOPER_DIR="${DEVELOPER_DIR:-$(xcode-select -p)}"
|
||||
XMAKE_TOOLCHAIN_BIN="${XMAKE_DEVELOPER_DIR}/Toolchains/XcodeDefault.xctoolchain/usr/bin"
|
||||
run_xmake() {
|
||||
local xmake_env=()
|
||||
if [[ -n "${XMAKE_GLOBALDIR:-}" ]]; then
|
||||
xmake_env+=("XMAKE_GLOBALDIR=${XMAKE_GLOBALDIR}")
|
||||
fi
|
||||
/usr/bin/env -i \
|
||||
HOME="${HOME}" \
|
||||
PATH="${XMAKE_TOOLCHAIN_BIN}:${PATH}" \
|
||||
@@ -69,11 +73,16 @@ run_xmake() {
|
||||
DEVELOPER_DIR="${XMAKE_DEVELOPER_DIR}" \
|
||||
XMAKE_PKG_INSTALLDIR="${XMAKE_PKG_INSTALLDIR}" \
|
||||
CROSSDESK_SOURCE_DIR="${REPO_DIR}" \
|
||||
"${xmake_env[@]}" \
|
||||
"${XMAKE_BIN}" "$@"
|
||||
}
|
||||
|
||||
OUTPUT_DIR="${IOS_DIR}/Vendor/iphoneos/${CONFIG_NAME}"
|
||||
OUTPUT_LIBRARY="${OUTPUT_DIR}/libCrossDeskMiniRTC.a"
|
||||
XMAKE_REPOSITORY_DIR="$(run_xmake lua -c 'import("core.base.global"); print(path.join(global.directory(), "repositories", "xmake-repo"))')"
|
||||
mkdir -p "${OUTPUT_DIR}"
|
||||
print -r -- "${XMAKE_REPOSITORY_DIR}" > "${OUTPUT_DIR}/xmake-repository.txt"
|
||||
run_xmake --version > "${OUTPUT_DIR}/xmake-version.txt"
|
||||
MINIRTC_BUILD_DIR="${IOS_DIR}/.xmake/minirtc-build"
|
||||
MINIRTC_LIBRARY="${MINIRTC_BUILD_DIR}/iphoneos/arm64/${MODE}/libminirtc.a"
|
||||
WIRE_BUILD_DIR="${IOS_DIR}/.xmake/wire-build"
|
||||
@@ -106,7 +115,8 @@ configure_xmake() {
|
||||
clean_flags=(-c)
|
||||
fi
|
||||
run_xmake f -P "${project_dir}" "${clean_flags[@]}" -o "${build_dir}" \
|
||||
-p iphoneos -a arm64 -m "${MODE}" --target_minver=16.0 -y "$@"
|
||||
-p iphoneos -a arm64 -m "${MODE}" --target_minver=16.0 \
|
||||
--policies=package.precompiled:n -y "$@"
|
||||
mkdir -p "${build_dir}"
|
||||
print -r -- "${CONFIG_SIGNATURE}" > "${stamp}"
|
||||
}
|
||||
@@ -148,16 +158,19 @@ TARGET_INFO="$(cd "${MINIRTC_DIR}" && TERM=dumb NO_COLOR=1 \
|
||||
CLEAN_INFO="$(print -r -- "${TARGET_INFO}" | sed $'s/\033\\[[0-9;]*[[:alpha:]]//g')"
|
||||
LINK_DIRS=("${(@f)$(print -r -- "${CLEAN_INFO}" | sed -nE 's|.*-> (/.*)/lib -> package.*|\1/lib|p' | sort -u)}")
|
||||
|
||||
print -r -- "${CLEAN_INFO}" > "${OUTPUT_DIR}/minirtc-target-info.txt"
|
||||
|
||||
REQUIRED_LINKS=(
|
||||
nice glib-2.0 gobject-2.0 gmodule-2.0 gio-2.0 gthread-2.0 intl
|
||||
gupnp-igd-1.6 gupnp-1.6 gssdp-1.6 soup-3.0 nghttp2 sqlite3 psl xml2
|
||||
ffi pcre2-8 pcre2-posix z ssl crypto srtp2 openfec opus yuv kcp
|
||||
datachannel usrsctp openh264 dav1d SvtAv1Enc
|
||||
datachannel usrsctp dav1d SvtAv1Enc
|
||||
)
|
||||
if [[ "${MINIRTC_ENABLE_AOM}" == "true" ]]; then
|
||||
REQUIRED_LINKS+=(aom)
|
||||
fi
|
||||
DEPENDENCY_ARCHIVES=()
|
||||
MERGE_ARCHIVES=()
|
||||
|
||||
for link_name in "${REQUIRED_LINKS[@]}"; do
|
||||
archive_path=""
|
||||
@@ -173,6 +186,11 @@ for link_name in "${REQUIRED_LINKS[@]}"; do
|
||||
exit 66
|
||||
fi
|
||||
DEPENDENCY_ARCHIVES+=("${archive_path}")
|
||||
# OpenSSL is linked separately as a static framework with its SDK privacy
|
||||
# resources. Keep both archives in the input manifest for source validation.
|
||||
if [[ "${link_name}" != "ssl" && "${link_name}" != "crypto" ]]; then
|
||||
MERGE_ARCHIVES+=("${archive_path}")
|
||||
fi
|
||||
done
|
||||
|
||||
TEMP_LIBRARY="${OUTPUT_LIBRARY}.tmp"
|
||||
@@ -180,19 +198,33 @@ MERGE_MANIFEST="${OUTPUT_LIBRARY}.inputs.sha256"
|
||||
TEMP_MANIFEST="${MERGE_MANIFEST}.tmp"
|
||||
trap 'rm -f "${TEMP_LIBRARY}" "${TEMP_MANIFEST}"' EXIT
|
||||
|
||||
# Check the actual archive, including when reusing cached build products.
|
||||
verify_no_openh264() {
|
||||
local symbols
|
||||
symbols="$(DEVELOPER_DIR="${XMAKE_DEVELOPER_DIR}" xcrun nm -g "$1")"
|
||||
if [[ "${symbols}" == *WelsCreateDecoder* || \
|
||||
"${symbols}" == *WelsCreateSVCEncoder* || \
|
||||
"${symbols}" == *WelsGetCodecVersion* ]]; then
|
||||
print -u2 "OpenH264 symbols must not be present in the iOS native archive: $1"
|
||||
exit 65
|
||||
fi
|
||||
}
|
||||
|
||||
# Hash contents as well as paths so same-size archives replaced within the same
|
||||
# timestamp tick cannot leave a stale merged library. Preserve the output mtime
|
||||
# on no-op builds to avoid relinking the Xcode app.
|
||||
shasum -a 256 "${SCRIPT_DIR}/build_minirtc_ios.sh" "${MINIRTC_LIBRARY}" \
|
||||
"${DEPENDENCY_ARCHIVES[@]}" "${WIRE_LIBRARY}" > "${TEMP_MANIFEST}"
|
||||
if [[ -f "${OUTPUT_LIBRARY}" ]] && cmp -s "${TEMP_MANIFEST}" "${MERGE_MANIFEST}"; then
|
||||
verify_no_openh264 "${OUTPUT_LIBRARY}"
|
||||
print "Up to date: ${OUTPUT_LIBRARY}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
/usr/bin/libtool -static -o "${TEMP_LIBRARY}" \
|
||||
"${MINIRTC_LIBRARY}" "${DEPENDENCY_ARCHIVES[@]}" \
|
||||
"${MINIRTC_LIBRARY}" "${MERGE_ARCHIVES[@]}" \
|
||||
"${WIRE_LIBRARY}"
|
||||
verify_no_openh264 "${TEMP_LIBRARY}"
|
||||
mv -f "${TEMP_LIBRARY}" "${OUTPUT_LIBRARY}"
|
||||
mv -f "${TEMP_MANIFEST}" "${MERGE_MANIFEST}"
|
||||
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Collect iOS notices from pinned source archives; validate them offline at build time."""
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
IOS = Path(__file__).resolve().parents[1]
|
||||
REPO = IOS.parents[1]
|
||||
LOCK = IOS / "licenses/sources.json"
|
||||
OUTPUT = IOS / "CrossDeskMobile/Resources/ThirdPartyLicenses.json"
|
||||
COMMENT = re.compile(rb"/\*.*?\*/|(?://[^\n]*(?:\n|$))+", re.S)
|
||||
RIGHTS = re.compile(rb"copyright|SPDX-License|permission is hereby|author disclaims|public domain", re.I)
|
||||
|
||||
|
||||
def digest(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def json_bytes(value):
|
||||
return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode()
|
||||
|
||||
|
||||
def checked(data, expected, label):
|
||||
if digest(data) != expected:
|
||||
raise ValueError(f"Source checksum mismatch: {label}")
|
||||
return data
|
||||
|
||||
|
||||
def archive_path(component, cache):
|
||||
source = component["source"]
|
||||
target = cache / source["sha256"]
|
||||
if target.exists():
|
||||
checked(target.read_bytes(), source["sha256"], component["id"])
|
||||
return target
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
# Xmake may remove extracted sources or COPYING; read the original archive.
|
||||
candidates = (Path.home() / ".xmake/cache/packages").glob(
|
||||
f"*/{component['id'][0]}/{component['id']}/{component['version']}/*")
|
||||
for candidate in candidates:
|
||||
if candidate.is_file() and candidate.name.endswith((".tar.gz", ".tar.xz", ".zip")):
|
||||
data = candidate.read_bytes()
|
||||
if digest(data) == source["sha256"]:
|
||||
target.write_bytes(data)
|
||||
return target
|
||||
request = urllib.request.Request(source["url"], headers={"User-Agent": "CrossDesk-license-collector"})
|
||||
with urllib.request.urlopen(request, timeout=90) as response:
|
||||
data = checked(response.read(), source["sha256"], component["id"])
|
||||
target.write_bytes(data)
|
||||
return target
|
||||
|
||||
|
||||
@contextmanager
|
||||
def source_files(component, cache):
|
||||
if component["source"]["kind"] == "repository":
|
||||
yield {}, lambda name: (REPO / name).read_bytes()
|
||||
return
|
||||
path = archive_path(component, cache)
|
||||
if zipfile.is_zipfile(path):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
names = {name.split("/", 1)[1]: name for name in archive.namelist()
|
||||
if "/" in name and not name.endswith("/")}
|
||||
yield names, lambda name: archive.read(names[name])
|
||||
else:
|
||||
with tarfile.open(path) as archive:
|
||||
names = {member.name.split("/", 1)[1]: member.name for member in archive
|
||||
if "/" in member.name and not member.isdir()}
|
||||
# No filesystem extraction. tarfile resolves COPYING symlinks within
|
||||
# the verified archive, including GLib's LICENSES directory.
|
||||
yield names, lambda name: archive.extractfile(names[name]).read()
|
||||
|
||||
|
||||
def component_documents(component, names, read):
|
||||
documents = []
|
||||
for item in component["documents"]:
|
||||
data = checked(read(item["path"]), item["sha256"], item["path"])
|
||||
text = data.decode(item.get("encoding", "utf-8"))
|
||||
if "end_before" in item:
|
||||
if item["end_before"] not in text:
|
||||
raise ValueError(f"Missing notice boundary: {item['path']}")
|
||||
text = text.split(item["end_before"], 1)[0]
|
||||
documents.append({"title": item["path"], "text": text})
|
||||
notices = defaultdict(list)
|
||||
for name in sorted(names):
|
||||
path = Path(name)
|
||||
selected = any(name.startswith(prefix) for prefix in component.get("notice_prefixes", []))
|
||||
selected |= component.get("notice_root_files", False) and "/" not in name
|
||||
if not selected or path.suffix not in (".h", ".hpp", ".c", ".cc", ".cpp", ".S", ".s", ".inc"):
|
||||
continue
|
||||
if any(part.lower() in ("test", "tests", "benchmarks", "examples") for part in path.parts):
|
||||
continue
|
||||
for block in COMMENT.findall(read(name)[:16384]):
|
||||
if RIGHTS.search(block):
|
||||
# Preserve complete original comment blocks, including bundled
|
||||
# fmt, semaphore and per-file copyright/permission exceptions.
|
||||
encoding = component.get("notice_encodings", {}).get(name, "utf-8")
|
||||
notices[block.decode(encoding)].append(name)
|
||||
if notices:
|
||||
documents.append({"title": "Source copyright and license notices", "text": "\n\n".join(
|
||||
"Files: " + ", ".join(files) + "\n\n" + text for text, files in notices.items())})
|
||||
if not documents:
|
||||
raise ValueError(f"No notices collected for {component['id']}")
|
||||
return documents
|
||||
|
||||
|
||||
def generate(lock, cache):
|
||||
components = []
|
||||
for component in lock["components"]:
|
||||
with source_files(component, cache) as (names, read):
|
||||
documents = component_documents(component, names, read)
|
||||
source = component["source"]
|
||||
source_url = source["url"]
|
||||
if source["kind"] == "repository" and source.get("revision"):
|
||||
source_url += "/tree/" + source["revision"]
|
||||
entry = {key: component[key] for key in ("id", "name", "version", "license")} | {
|
||||
"sourceURL": source_url, "documents": documents}
|
||||
recipe = component.get("recipe_path", "")
|
||||
if recipe.startswith("deps/submodules/minirtc/"):
|
||||
mini = next(c for c in lock["components"] if c["id"] == "minirtc")
|
||||
entry["buildSourceURL"] = (mini["source"]["url"] + "/tree/" +
|
||||
mini["source"]["revision"] + "/" +
|
||||
str(Path(recipe).relative_to("deps/submodules/minirtc").parent))
|
||||
components.append(entry)
|
||||
print(f"Collected {component['name']} {component['version']}")
|
||||
return json_bytes({"schemaVersion": 1, "components": components})
|
||||
|
||||
|
||||
def verify(lock, inputs, target_info, xmake_repository=None, xmake_version=None):
|
||||
checked(OUTPUT.read_bytes(), lock["bundle_sha256"], str(OUTPUT))
|
||||
if xmake_version is not None:
|
||||
version = re.search(r"xmake v(\d+\.\d+\.\d+)", xmake_version.read_text())
|
||||
if not version or version[1] != lock["toolchain"]["xmake_version"]:
|
||||
raise ValueError("Xmake version differs from the reviewed iOS toolchain; see apps/ios/README.md")
|
||||
if xmake_repository is not None:
|
||||
revision = subprocess.check_output(
|
||||
["git", "-C", str(xmake_repository), "rev-parse", "HEAD"], text=True).strip()
|
||||
if revision != lock["toolchain"]["xmake_repository_revision"]:
|
||||
raise ValueError("Xmake package repository differs from the reviewed iOS source catalog")
|
||||
changes = subprocess.check_output(
|
||||
["git", "-C", str(xmake_repository), "status", "--porcelain", "--untracked-files=normal"],
|
||||
text=True).strip()
|
||||
if changes:
|
||||
raise ValueError("Xmake package repository has local changes; use the unmodified pinned revision")
|
||||
for component in lock["components"]:
|
||||
recipe = component.get("recipe_path", "")
|
||||
if recipe.startswith("deps/"):
|
||||
checked((REPO / recipe).read_bytes(), component["recipe_sha256"], recipe)
|
||||
elif recipe.startswith("xmake-repo/") and xmake_repository is not None:
|
||||
checked((xmake_repository / Path(recipe).relative_to("xmake-repo")).read_bytes(),
|
||||
component["recipe_sha256"], recipe)
|
||||
if component["source"]["kind"] == "repository":
|
||||
for item in component["documents"]:
|
||||
checked((REPO / item["path"]).read_bytes(), item["sha256"], item["path"])
|
||||
if inputs is None:
|
||||
return
|
||||
if target_info is None:
|
||||
raise ValueError("--target-info is required with --inputs (includes header-only dependencies)")
|
||||
known = {c["package"]: c["version"] for c in lock["components"] if "package" in c}
|
||||
seen = {}
|
||||
# Package names/versions come from resolved Xmake link and include paths,
|
||||
# never from an inventory of all packages left in the installation cache.
|
||||
pattern = r"/packages/[^/\s]+/([^/\s]+)/([^/\s]+)/[a-f0-9]+/"
|
||||
for name, version in re.findall(pattern, inputs.read_text() + target_info.read_text()):
|
||||
if name not in known or known[name] != version:
|
||||
raise ValueError(f"Unreviewed iOS dependency: {name} {version}; regenerate licenses from its source")
|
||||
seen[name] = version
|
||||
if set(seen) != set(known):
|
||||
raise ValueError(f"License/build dependency mismatch; missing: {sorted(set(known) - set(seen))}")
|
||||
for line in inputs.read_text().splitlines():
|
||||
sha, path = line.split(maxsplit=1)
|
||||
checked(Path(path).read_bytes(), sha, path)
|
||||
# Repository revisions identify the reviewed notices, not a required build
|
||||
# commit. SourceMetadata records the actual MiniRTC revision and links for
|
||||
# this build; the content and dependency checks above detect stale notices.
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--generate", action="store_true", help="download/check pinned sources and regenerate the bundled JSON")
|
||||
parser.add_argument("--cache", type=Path, default=Path.home() / ".cache/crossdesk/licenses")
|
||||
parser.add_argument("--inputs", type=Path, help="native archive .inputs.sha256 manifest")
|
||||
parser.add_argument("--target-info", type=Path, help="resolved Xmake minirtc target information")
|
||||
parser.add_argument("--xmake-repository", type=Path, help="verify the active pinned package repository and recipes")
|
||||
parser.add_argument("--xmake-version", type=Path, help="Xmake version output recorded by the native build")
|
||||
args = parser.parse_args()
|
||||
lock = json.loads(LOCK.read_text())
|
||||
if args.generate:
|
||||
data = generate(lock, args.cache)
|
||||
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUTPUT.write_bytes(data)
|
||||
lock["bundle_sha256"] = digest(data)
|
||||
LOCK.write_bytes(json_bytes(lock))
|
||||
verify(lock, args.inputs, args.target_info, args.xmake_repository, args.xmake_version)
|
||||
print(f"Verified {len(lock['components'])} iOS license components")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
|
||||
print(f"Third-party notices: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package source-built iOS OpenSSL as a static framework with privacy resources."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
IOS = Path(__file__).resolve().parents[1]
|
||||
PRIVACY = IOS / "OpenSSL/PrivacyInfo.xcprivacy"
|
||||
# The reviewed iOS configuration removes these calls rather than declaring
|
||||
# unrelated purposes for system entropy devices and certificate directories.
|
||||
FORBIDDEN_APIS = {
|
||||
"stat", "fstat", "lstat", "fstatat", "stat64", "fstat64", "lstat64",
|
||||
"getattrlist", "fgetattrlist", "getattrlistbulk", "getdirentriesattr",
|
||||
"statfs", "fstatfs", "statvfs", "fstatvfs", "getfsstat",
|
||||
"mach_absolute_time", "mach_continuous_time", "sysctl",
|
||||
}
|
||||
|
||||
|
||||
def package(inputs, output):
|
||||
catalog = json.loads((IOS / "CrossDeskMobile/Resources/ThirdPartyLicenses.json").read_text())
|
||||
component = next(c for c in catalog["components"] if c["id"] == "openssl3")
|
||||
archives = {}
|
||||
for line in inputs.read_text().splitlines():
|
||||
sha, name = line.split(maxsplit=1)
|
||||
path = Path(name)
|
||||
if path.name in {"libssl.a", "libcrypto.a"}:
|
||||
if path.name in archives:
|
||||
raise ValueError(f"Ambiguous OpenSSL input: {path.name}")
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != sha:
|
||||
raise ValueError(f"OpenSSL input checksum mismatch: {path}")
|
||||
archives[path.name] = (path, sha)
|
||||
if set(archives) != {"libssl.a", "libcrypto.a"}:
|
||||
raise ValueError("Both source-built OpenSSL archives must be present")
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="openssl-framework-", dir=output.parent) as temp:
|
||||
binary = Path(temp) / "OpenSSL"
|
||||
subprocess.run(["/usr/bin/libtool", "-static", "-o", str(binary),
|
||||
*(str(archives[name][0]) for name in sorted(archives))], check=True)
|
||||
subprocess.run(["xcrun", "lipo", str(binary), "-verify_arch", "arm64"], check=True)
|
||||
symbols = subprocess.check_output(["xcrun", "nm", "-u", str(binary)], text=True)
|
||||
imports = {line.split()[-1].lstrip("_").split("$")[0]
|
||||
for line in symbols.splitlines() if line.strip() and not line.endswith(":")}
|
||||
unexpected = imports & FORBIDDEN_APIS
|
||||
if unexpected:
|
||||
raise ValueError(f"OpenSSL privacy configuration has unreviewed APIs: {sorted(unexpected)}")
|
||||
# armcap.c queries only CPU instruction support/brand to select crypto
|
||||
# implementations. This is not boot time, disk space or fingerprinting.
|
||||
member = ""
|
||||
for line in symbols.splitlines():
|
||||
if line.endswith(":"):
|
||||
member = line
|
||||
elif "_sysctlbyname" in line and member != "libcrypto-lib-armcap.o:":
|
||||
raise ValueError(f"Unreviewed OpenSSL sysctl caller: {member}")
|
||||
# getrandom uses Darwin's getentropy via OpenSSL's existing DSO lookup;
|
||||
# the random device fallback is excluded at compile time.
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
files = {
|
||||
"OpenSSL": binary.read_bytes(),
|
||||
"PrivacyInfo.xcprivacy": PRIVACY.read_bytes(),
|
||||
"Info.plist": plistlib.dumps({
|
||||
"CFBundleIdentifier": "cn.crossdesk.OpenSSL",
|
||||
"CFBundleName": "OpenSSL",
|
||||
"CFBundleExecutable": "OpenSSL",
|
||||
"CFBundlePackageType": "FMWK",
|
||||
"CFBundleInfoDictionaryVersion": "6.0",
|
||||
"CFBundleVersion": component["version"],
|
||||
"CFBundleShortVersionString": component["version"],
|
||||
"CFBundleSupportedPlatforms": ["iPhoneOS"],
|
||||
"MinimumOSVersion": "16.0",
|
||||
}),
|
||||
"LICENSE.txt": "\n\n".join(d["text"] for d in component["documents"]).encode(),
|
||||
"BuildMetadata.json": (json.dumps({
|
||||
"version": component["version"],
|
||||
"sourceURL": component["sourceURL"],
|
||||
"buildSourceURL": component["buildSourceURL"],
|
||||
"archives": {name: sha for name, (_, sha) in sorted(archives.items())},
|
||||
"privacySHA256": hashlib.sha256(PRIVACY.read_bytes()).hexdigest(),
|
||||
}, indent=2) + "\n").encode(),
|
||||
}
|
||||
for name, data in files.items():
|
||||
target = output / name
|
||||
if not target.exists() or target.read_bytes() != data:
|
||||
target.write_bytes(data)
|
||||
print(f"Packaged source-built OpenSSL {component['version']}: {output}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--inputs", required=True, type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
package(args.inputs, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, StopIteration, subprocess.CalledProcessError) as error:
|
||||
print(f"OpenSSL framework: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Record the source corresponding to an iOS build without changing the checkout."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import quote
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
REPOSITORY_URL = "https://github.com/kunkundi/crossdesk"
|
||||
MINIRTC_URL = "https://github.com/kunkundi/minirtc"
|
||||
|
||||
|
||||
def git(*args, root=REPO):
|
||||
return subprocess.check_output(["git", "-C", str(root), *args], text=True).strip()
|
||||
|
||||
|
||||
def component_sources(lock, mini_revision):
|
||||
"""Resolve MiniRTC source and recipe links without rewriting reviewed notices."""
|
||||
mini_url = f"{MINIRTC_URL}/tree/{mini_revision}"
|
||||
sources = {}
|
||||
for component in lock["components"]:
|
||||
source = component["source"]
|
||||
entry = {}
|
||||
if source["kind"] == "repository" and source["url"] == MINIRTC_URL:
|
||||
entry.update(version=mini_revision, sourceURL=mini_url)
|
||||
recipe = component.get("recipe_path", "")
|
||||
if recipe.startswith("deps/submodules/minirtc/"):
|
||||
directory = Path(recipe).relative_to("deps/submodules/minirtc").parent
|
||||
entry["buildSourceURL"] = f"{mini_url}/{directory.as_posix()}"
|
||||
if entry:
|
||||
sources[component["id"]] = entry
|
||||
return sources
|
||||
|
||||
|
||||
def source_metadata(require_release=False, tag=None):
|
||||
revision = git("rev-parse", "HEAD")
|
||||
dirty = bool(git("status", "--porcelain", "--untracked-files=normal", "--ignore-submodules=none"))
|
||||
tags = git("tag", "--points-at", "HEAD").splitlines()
|
||||
if tag:
|
||||
if tag not in tags:
|
||||
raise ValueError(f"Source tag {tag!r} does not point to the build commit")
|
||||
else:
|
||||
# 'latest' is a moving alias, never a corresponding-source identifier.
|
||||
versions = sorted(t for t in tags if t.startswith("v"))
|
||||
tag = versions[0] if versions else None
|
||||
if require_release and (dirty or not tag or not tag.startswith("v")):
|
||||
raise ValueError("Release source must be a clean checkout of a version tag, with matching submodules")
|
||||
mini_revision = git("rev-parse", "HEAD", root=REPO / "deps/submodules/minirtc")
|
||||
lock_path = REPO / "apps/ios/licenses/sources.json"
|
||||
lock = json.loads(lock_path.read_text())
|
||||
ref = quote(tag if tag and not dirty else revision, safe="")
|
||||
return {
|
||||
"schemaVersion": 1,
|
||||
"repositoryURL": REPOSITORY_URL,
|
||||
"revision": revision,
|
||||
"tag": tag,
|
||||
"isModified": dirty,
|
||||
"sourceURL": f"{REPOSITORY_URL}/tree/{ref}",
|
||||
"buildInstructionsURL": f"{REPOSITORY_URL}/blob/{ref}/apps/ios/README.md",
|
||||
"privacyPolicyURL": f"{REPOSITORY_URL}/blob/{ref}/PRIVACY.md",
|
||||
"miniRTCRevision": mini_revision,
|
||||
"miniRTCSourceURL": f"{MINIRTC_URL}/tree/{mini_revision}",
|
||||
"componentSources": component_sources(lock, mini_revision),
|
||||
"licenseCatalogSHA256": lock["bundle_sha256"],
|
||||
"sourceCatalogSHA256": hashlib.sha256(lock_path.read_bytes()).hexdigest(),
|
||||
"toolchain": lock["toolchain"],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--tag", default=os.environ.get("CROSSDESK_SOURCE_TAG") or None)
|
||||
parser.add_argument("--require-release", action="store_true",
|
||||
default=os.environ.get("CROSSDESK_RELEASE_BUILD") == "YES")
|
||||
args = parser.parse_args()
|
||||
metadata = source_metadata(args.require_release, args.tag)
|
||||
data = (json.dumps(metadata, ensure_ascii=False, indent=2) + "\n").encode()
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not args.output.exists() or args.output.read_bytes() != data:
|
||||
args.output.write_bytes(data)
|
||||
print(f"Recorded iOS source: {metadata['revision']} (modified: {metadata['isModified']})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, subprocess.CalledProcessError) as error:
|
||||
print(f"iOS source metadata: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check release resources and known restricted imports in a built iOS app."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def verify(app, require_release=False):
|
||||
info = plistlib.loads((app / "Info.plist").read_bytes())
|
||||
binary = app / info["CFBundleExecutable"]
|
||||
subprocess.run(["xcrun", "lipo", str(binary), "-verify_arch", "arm64"], check=True)
|
||||
symbols = subprocess.check_output(["xcrun", "nm", "-u", str(binary)], text=True)
|
||||
imports = set(line.split()[-1] for line in symbols.splitlines() if line.strip())
|
||||
disk_apis = {"_statfs", "_fstatfs", "_statvfs", "_fstatvfs", "_getfsstat"}
|
||||
if imports & disk_apis:
|
||||
raise ValueError(f"Unreviewed disk-space APIs remain in iOS app: {sorted(imports & disk_apis)}")
|
||||
defined = subprocess.check_output(["xcrun", "nm", "-g", str(binary)], text=True)
|
||||
if re.search(r"\b_Wels(?:CreateDecoder|CreateSVCEncoder|GetCodecVersion)\b", defined):
|
||||
raise ValueError("OpenH264 must not be present in the iOS app")
|
||||
if re.search(r"\b_of_(?:hweight\w*|hw8table|popcount_3)\b", defined):
|
||||
raise ValueError("OpenFEC's optional CC-BY-SA-3.0 hamming-weight code requires a separate distribution review")
|
||||
privacy = plistlib.loads((app / "PrivacyInfo.xcprivacy").read_bytes())
|
||||
if not (app / "PRIVACY.md").read_text().strip():
|
||||
raise ValueError("The offline privacy policy must be bundled for pre-consent access")
|
||||
reasons = {entry["NSPrivacyAccessedAPIType"]: entry["NSPrivacyAccessedAPITypeReasons"]
|
||||
for entry in privacy["NSPrivacyAccessedAPITypes"]}
|
||||
required = {
|
||||
"NSPrivacyAccessedAPICategoryUserDefaults": {"CA92.1"},
|
||||
"NSPrivacyAccessedAPICategoryFileTimestamp": {"C617.1", "3B52.1"},
|
||||
"NSPrivacyAccessedAPICategorySystemBootTime": {"35F9.1", "8FFB.1"},
|
||||
}
|
||||
for category, codes in required.items():
|
||||
if set(reasons.get(category, [])) != codes:
|
||||
raise ValueError(f"Missing or changed reviewed privacy reasons: {category}")
|
||||
data = (app / "ThirdPartyLicenses.json").read_bytes()
|
||||
catalog = json.loads(data)
|
||||
ids = {c["id"] for c in catalog["components"]}
|
||||
if not {"crossdesk", "minirtc", "openfec"} <= ids or "openh264" in ids:
|
||||
raise ValueError("Unexpected iOS license catalog")
|
||||
openssl = next(c for c in catalog["components"] if c["id"] == "openssl3")
|
||||
framework = app / "Frameworks/OpenSSL.framework"
|
||||
sdk_info = plistlib.loads((framework / "Info.plist").read_bytes())
|
||||
sdk_privacy_data = (framework / "PrivacyInfo.xcprivacy").read_bytes()
|
||||
sdk_privacy = plistlib.loads(sdk_privacy_data)
|
||||
expected_privacy = {
|
||||
"NSPrivacyTracking": False,
|
||||
"NSPrivacyTrackingDomains": [],
|
||||
"NSPrivacyCollectedDataTypes": [],
|
||||
"NSPrivacyAccessedAPITypes": [],
|
||||
}
|
||||
if sdk_privacy != expected_privacy:
|
||||
raise ValueError("OpenSSL SDK privacy declaration differs from the reviewed iOS configuration")
|
||||
sdk_build = json.loads((framework / "BuildMetadata.json").read_text())
|
||||
if (sdk_info["CFBundleShortVersionString"] != openssl["version"]
|
||||
or sdk_build["version"] != openssl["version"]
|
||||
or sdk_build["sourceURL"] != openssl["sourceURL"]
|
||||
or sdk_build["buildSourceURL"] != openssl["buildSourceURL"]
|
||||
or sdk_build["privacySHA256"] != hashlib.sha256(sdk_privacy_data).hexdigest()):
|
||||
raise ValueError("OpenSSL SDK resources do not match the source/license catalog")
|
||||
if (framework / "LICENSE.txt").read_text() != "\n\n".join(d["text"] for d in openssl["documents"]):
|
||||
raise ValueError("OpenSSL SDK license resource differs from its source notices")
|
||||
embedded_binary = framework / sdk_info["CFBundleExecutable"]
|
||||
# Xcode removes the archive and may generate a small codeless-framework
|
||||
# stub. It must not ship a second static archive or dynamic OpenSSL copy.
|
||||
if embedded_binary.exists():
|
||||
if embedded_binary.read_bytes().startswith(b"!<arch>\n"):
|
||||
raise ValueError("Xcode must remove the static OpenSSL archive when embedding its resources")
|
||||
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")
|
||||
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")
|
||||
source = json.loads((app / "SourceMetadata.json").read_text())
|
||||
if source["licenseCatalogSHA256"] != hashlib.sha256(data).hexdigest():
|
||||
raise ValueError("Bundled licenses differ from the recorded source metadata")
|
||||
if require_release and (source["isModified"] or not source["tag"]):
|
||||
raise ValueError("The app was not built from an unmodified version tag")
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", source["revision"]):
|
||||
raise ValueError("Invalid source revision")
|
||||
print("Verified arm64 app, source/license resources, app privacy declarations and OpenSSL SDK privacy packaging")
|
||||
print("Signing, App Store validation and license authorization require separate review.")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("app", type=Path)
|
||||
parser.add_argument("--require-release", action="store_true")
|
||||
args = parser.parse_args()
|
||||
verify(args.app, args.require_release)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
|
||||
print(f"iOS bundle verification: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Exercise production statistics with deterministic monotonic time."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "darwin", "requires the Apple Swift runtime")
|
||||
class NetworkStatisticsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="crossdesk-network-statistics-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
root = Path(cls.temp.name)
|
||||
harness = root / "NetworkStatisticsTests.swift"
|
||||
harness.write_text(r'''
|
||||
import Foundation
|
||||
|
||||
func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
|
||||
if !condition() { fatalError(message) }
|
||||
}
|
||||
|
||||
func near(_ value: Double?, _ expected: Double) -> Bool {
|
||||
guard let value else { return false }
|
||||
return abs(value - expected) < 0.0001
|
||||
}
|
||||
|
||||
@main
|
||||
enum NetworkStatisticsTests {
|
||||
static func main() {
|
||||
var state = RemoteNetworkStatistics()
|
||||
var report = RemoteNetworkReport(
|
||||
video: RemoteTrafficStatistics(inboundBitrate: 8_000_000, outboundBitrate: 0, lossRate: 0.02),
|
||||
audio: RemoteTrafficStatistics(inboundBitrate: 64_000, outboundBitrate: 0, lossRate: 0.01),
|
||||
data: RemoteTrafficStatistics(inboundBitrate: 2_000, outboundBitrate: 3_000, lossRate: 0.03),
|
||||
total: RemoteTrafficStatistics(inboundBitrate: 8_066_000, outboundBitrate: 3_000, lossRate: 0.06),
|
||||
mode: .relay, srtpActive: true, rttMilliseconds: 20
|
||||
)
|
||||
let test = CommandLine.arguments[1]
|
||||
if test == "report" {
|
||||
expect(state.snapshot(at: 10).report == nil, "No measurements before a report")
|
||||
expect(state.snapshot(at: 10).connectionMode == "—", "Unknown is not P2P")
|
||||
state.receive(report, at: 10)
|
||||
let snapshot = state.snapshot(at: 10)
|
||||
expect(snapshot.report?.video.inboundBitrate == 8_000_000, "Video rate survives")
|
||||
expect(snapshot.report?.audio.inboundBitrate == 64_000, "Audio rate survives")
|
||||
expect(snapshot.report?.data.outboundBitrate == 3_000, "Data upload survives")
|
||||
expect(snapshot.report?.total.inboundBitrate == 8_066_000, "Total is transport-provided")
|
||||
expect(snapshot.report?.audio.lossRate == 0.01, "Media loss stays separate")
|
||||
expect(snapshot.report?.srtpActive == true && snapshot.connectionMode == "TURN 中继", "Actual security and route")
|
||||
report.mode = .direct
|
||||
report.srtpActive = false
|
||||
state.receive(report, at: 11)
|
||||
expect(state.snapshot(at: 11).connectionMode == "P2P 直连", "Route updates")
|
||||
expect(state.snapshot(at: 11).report?.srtpActive == false, "Security is not inferred from connection")
|
||||
} else if test == "expiry" {
|
||||
state.receive(report, at: 10)
|
||||
expect(state.snapshot(at: 12.99).report != nil, "One missed report does not flicker")
|
||||
let expired = state.snapshot(at: 13)
|
||||
expect(expired.report == nil && expired.rttMilliseconds == nil, "Stalled reports expire")
|
||||
expect(expired.connectionMode == "—", "Stale route expires")
|
||||
state = RemoteNetworkStatistics()
|
||||
expect(state.snapshot(at: 13).report == nil, "Reconnect clears prior peer")
|
||||
} else if test == "rtt" {
|
||||
state.receive(report, at: 10)
|
||||
report.rttMilliseconds = 100
|
||||
state.receive(report, at: 11)
|
||||
expect(near(state.snapshot(at: 11).rttMilliseconds, 40), "Desktop EWMA alpha is 0.25")
|
||||
for invalid in [-1.0, Double.nan, Double.infinity, 2_001] {
|
||||
report.rttMilliseconds = invalid
|
||||
state.receive(report, at: 12)
|
||||
expect(near(state.snapshot(at: 12).rttMilliseconds, 40), "Invalid RTT cannot contaminate average")
|
||||
}
|
||||
expect(state.snapshot(at: 14).rttMilliseconds == nil, "Invalid reports cannot keep RTT alive")
|
||||
expect(state.snapshot(at: 14).report != nil, "Traffic and RTT expire independently")
|
||||
report.rttMilliseconds = 0
|
||||
state.receive(report, at: 15)
|
||||
expect(near(state.snapshot(at: 15).rttMilliseconds, 0), "Zero RTT is valid; expired average is replaced")
|
||||
} else if test == "frames" {
|
||||
state.recordSubmittedFrame(id: 1, captureUptime: 9.9, at: 10)
|
||||
state.recordSubmittedFrame(id: 1, captureUptime: 9.9, at: 10.1)
|
||||
state.recordSubmittedFrame(id: 2, captureUptime: 10, at: 10.2)
|
||||
let snapshot = state.snapshot(at: 10.3)
|
||||
expect(snapshot.framesPerSecond == 2, "Redrawing a frame is not FPS")
|
||||
expect(near(snapshot.videoLatencyMilliseconds, 150), "Average includes time through display submission")
|
||||
expect(state.snapshot(at: 11).framesPerSecond == 1, "One-second rolling window")
|
||||
expect(state.snapshot(at: 11.3).framesPerSecond == 0, "Idle video must reach zero FPS")
|
||||
expect(state.snapshot(at: 11.3).videoLatencyMilliseconds == nil, "Idle latency expires")
|
||||
} else if test == "video_reset" {
|
||||
state.receive(report, at: 10)
|
||||
state.recordSubmittedFrame(id: 1, captureUptime: 9.9, at: 10)
|
||||
state.resetVideo()
|
||||
state.recordSubmittedFrame(id: 1, captureUptime: 9.9, at: 10.1)
|
||||
expect(state.snapshot(at: 10.1).framesPerSecond == 0, "Foreground cached frame is not counted again")
|
||||
expect(state.snapshot(at: 10.1).report != nil, "Switching displays preserves transport stats")
|
||||
state.recordSubmittedFrame(id: 2, captureUptime: 0, at: 10.2)
|
||||
state.recordSubmittedFrame(id: 3, captureUptime: 12, at: 10.3)
|
||||
state.recordSubmittedFrame(id: 4, captureUptime: 1, at: 10.4)
|
||||
state.recordSubmittedFrame(id: 5, captureUptime: .nan, at: 10.5)
|
||||
expect(state.snapshot(at: 10.5).framesPerSecond == 4, "Uncalibrated frames still count for FPS")
|
||||
expect(state.snapshot(at: 10.5).videoLatencyMilliseconds == nil, "Invalid capture estimates are unavailable")
|
||||
state.recordSubmittedFrame(id: 6, captureUptime: 10.5, at: 10.6)
|
||||
expect(near(state.snapshot(at: 10.6).videoLatencyMilliseconds, 100), "Calibration recovers without invalid samples")
|
||||
} else if test == "display_cadence" {
|
||||
state.receive(report, at: 10)
|
||||
state.recordSubmittedFrame(id: 1, captureUptime: 9.9, at: 10)
|
||||
let first = state.displaySnapshot(at: 10)
|
||||
expect(near(first.videoLatencyMilliseconds, 100), "Initial display sample")
|
||||
for frame in 1...59 {
|
||||
let now = 10 + Double(frame) / 60
|
||||
let delay = frame.isMultiple(of: 2) ? 0.3 : 0.2
|
||||
state.recordSubmittedFrame(id: UInt64(frame + 1), captureUptime: now - delay, at: now)
|
||||
report.rttMilliseconds = 100
|
||||
report.total.inboundBitrate = 9_000_000
|
||||
state.receive(report, at: now)
|
||||
let displayed = state.displaySnapshot(at: now)
|
||||
expect(near(displayed.videoLatencyMilliseconds, 100), "60 FPS callbacks cannot refresh the displayed delay")
|
||||
expect(displayed.framesPerSecond == first.framesPerSecond, "FPS is sampled with delay")
|
||||
expect(near(displayed.rttMilliseconds, 20), "RTT is frozen between ticks")
|
||||
expect(displayed.report?.total.inboundBitrate == 8_066_000, "Reports are sampled with video stats")
|
||||
}
|
||||
let next = state.displaySnapshot(at: 11)
|
||||
expect(next.framesPerSecond == 59, "The next tick samples all recent frames")
|
||||
expect((next.videoLatencyMilliseconds ?? 0) > 200, "Delay updates at the one-second boundary")
|
||||
expect(next.report?.total.inboundBitrate == 9_000_000, "The next tick sees current traffic")
|
||||
let idle = state.displaySnapshot(at: 12)
|
||||
expect(idle.framesPerSecond == 0 && idle.videoLatencyMilliseconds == nil, "Timer ticks expire idle video without new frames")
|
||||
let expired = state.displaySnapshot(at: 14)
|
||||
expect(expired.report == nil && expired.rttMilliseconds == nil, "Timer ticks expire missing reports")
|
||||
} else if test == "display_reset" {
|
||||
state.receive(report, at: 10)
|
||||
state.recordSubmittedFrame(id: 1, captureUptime: 9.9, at: 10)
|
||||
_ = state.displaySnapshot(at: 10)
|
||||
state.resetVideo()
|
||||
let switched = state.displaySnapshot(at: 10.1)
|
||||
expect(switched.framesPerSecond == 0 && switched.videoLatencyMilliseconds == nil, "Switching displays clears cached video immediately")
|
||||
expect(switched.report != nil, "Video reset keeps transport state")
|
||||
state = RemoteNetworkStatistics()
|
||||
let reconnected = state.displaySnapshot(at: 10.2)
|
||||
expect(reconnected.report == nil && reconnected.videoLatencyMilliseconds == nil, "A new session cannot reuse the old display cache")
|
||||
} else if test == "format" {
|
||||
expect(RemoteNetworkSnapshot.bitrate(nil) == "—", "Unavailable is not zero")
|
||||
expect(RemoteNetworkSnapshot.bitrate(0) == "0 bps", "Zero traffic is valid")
|
||||
expect(RemoteNetworkSnapshot.bitrate(64_000) == "64 Kbps", "Bitrate units")
|
||||
expect(RemoteNetworkSnapshot.bitrate(8_000_000) == "8.0 Mbps", "Mbps units")
|
||||
expect(RemoteNetworkSnapshot.latency(0) == "<1 ms", "Sub-millisecond RTT")
|
||||
expect(RemoteNetworkSnapshot.latency(nil) == "—", "Missing calibration")
|
||||
expect(RemoteNetworkSnapshot.lossRate(0.005) == "0.5%", "Small losses remain visible")
|
||||
expect(RemoteNetworkSnapshot.lossRate(1.2) == "120.0%", "Desktop aggregate is not silently clamped")
|
||||
expect(RemoteNetworkSnapshot.lossRate(.nan) == "—", "Nonfinite loss is unavailable")
|
||||
} else {
|
||||
fatalError("Unknown test")
|
||||
}
|
||||
}
|
||||
}
|
||||
''')
|
||||
source = Path(__file__).resolve().parents[1] / "CrossDeskMobile/RemoteNetworkStatistics.swift"
|
||||
cls.binary = root / "network-statistics-tests"
|
||||
subprocess.run(["xcrun", "swiftc", str(source), str(harness), "-o", str(cls.binary)],
|
||||
check=True, capture_output=True, text=True)
|
||||
|
||||
def test_channel_and_security_reports(self):
|
||||
self.run_case("report")
|
||||
|
||||
def test_missing_reports_and_reconnect(self):
|
||||
self.run_case("expiry")
|
||||
|
||||
def test_rtt_smoothing_and_recovery(self):
|
||||
self.run_case("rtt")
|
||||
|
||||
def test_frame_submission_and_idle_video(self):
|
||||
self.run_case("frames")
|
||||
|
||||
def test_display_switch_and_invalid_capture_time(self):
|
||||
self.run_case("video_reset")
|
||||
|
||||
def test_units_and_unavailable_values(self):
|
||||
self.run_case("format")
|
||||
|
||||
def test_display_refresh_is_independent_of_video_frames(self):
|
||||
self.run_case("display_cadence")
|
||||
|
||||
def test_display_cache_resets_with_video_and_session(self):
|
||||
self.run_case("display_reset")
|
||||
|
||||
def run_case(self, name):
|
||||
subprocess.run([str(self.binary), name], check=True, capture_output=True, text=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Run the production privacy preferences and preview file store on macOS."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "darwin", "requires the Apple Swift runtime")
|
||||
class PrivacyControlsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="crossdesk-privacy-tests-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
root = Path(cls.temp.name)
|
||||
harness = root / "PrivacyTests.swift"
|
||||
harness.write_text(r'''
|
||||
import Foundation
|
||||
|
||||
func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
|
||||
if !condition() { fatalError(message) }
|
||||
}
|
||||
|
||||
func wait(_ semaphore: DispatchSemaphore) {
|
||||
expect(semaphore.wait(timeout: .now() + 10) == .success, "Operation timed out")
|
||||
}
|
||||
|
||||
@main
|
||||
enum PrivacyTests {
|
||||
static func main() throws {
|
||||
let test = CommandLine.arguments[1]
|
||||
if test == "consent" || test == "upgrade" {
|
||||
let suite = "crossdesk.privacy.tests.\(UUID().uuidString)"
|
||||
let defaults = UserDefaults(suiteName: suite)!
|
||||
defer { defaults.removePersistentDomain(forName: suite) }
|
||||
if test == "upgrade" {
|
||||
// Existing identity/history must not be interpreted as consent.
|
||||
defaults.set("test-identity", forKey: "crossdesk.mobile.identity")
|
||||
defaults.set(Data("legacy history".utf8),
|
||||
forKey: "crossdesk.mobile.recent-connections.v1")
|
||||
}
|
||||
let preferences = PrivacyPreferences(defaults: defaults)
|
||||
expect(PrivacyNoticeState(hasNetworkConsent: preferences.hasNetworkConsent).isVisible,
|
||||
"New/legacy install must show the policy")
|
||||
expect(!preferences.hasNetworkConsent, "Must not start networking")
|
||||
expect(!preferences.savesThumbnails, "Saving must default to off")
|
||||
preferences.setSavesThumbnails(true)
|
||||
expect(!preferences.savesThumbnails, "Cannot enable captures without consent")
|
||||
preferences.setNetworkConsent(false)
|
||||
let declined = PrivacyPreferences(defaults: defaults)
|
||||
expect(!declined.hasNetworkConsent, "Decline must not allow networking")
|
||||
expect(PrivacyNoticeState(hasNetworkConsent: declined.hasNetworkConsent).isVisible,
|
||||
"Relaunch after refusal must show the policy again")
|
||||
declined.setNetworkConsent(true)
|
||||
expect(!declined.savesThumbnails, "Network consent is not screenshot consent")
|
||||
declined.setSavesThumbnails(true)
|
||||
let relaunched = PrivacyPreferences(defaults: defaults)
|
||||
expect(relaunched.hasNetworkConsent && relaunched.savesThumbnails,
|
||||
"Explicit choices must survive relaunch")
|
||||
expect(!PrivacyNoticeState(hasNetworkConsent: relaunched.hasNetworkConsent).isVisible,
|
||||
"Relaunch after agreement must not prompt again")
|
||||
relaunched.setNetworkConsent(false)
|
||||
expect(!relaunched.hasNetworkConsent && !relaunched.savesThumbnails,
|
||||
"Withdrawal revokes both permissions")
|
||||
expect(PrivacyNoticeState(hasNetworkConsent: relaunched.hasNetworkConsent).isVisible,
|
||||
"Relaunch after withdrawal must show the policy")
|
||||
relaunched.setNetworkConsent(true)
|
||||
expect(!relaunched.savesThumbnails, "Re-consent must not re-enable screenshots")
|
||||
} else if test == "notice_lifecycle" {
|
||||
var notice = PrivacyNoticeState(hasNetworkConsent: false)
|
||||
expect(notice.isVisible, "No consent must prompt on cold launch")
|
||||
notice.didBecomeActive(hasNetworkConsent: false)
|
||||
notice.dismiss()
|
||||
notice.didBecomeActive(hasNetworkConsent: false)
|
||||
expect(!notice.isVisible, "Refusal must not immediately reopen the notice")
|
||||
notice.didBecomeActive(hasNetworkConsent: false)
|
||||
expect(!notice.isVisible, "Transient inactivity or duplicate active callbacks are not another visit")
|
||||
for _ in 0..<3 {
|
||||
notice.didEnterBackground()
|
||||
notice.didBecomeActive(hasNetworkConsent: false)
|
||||
expect(notice.isVisible, "Every background/foreground round trip must prompt without consent")
|
||||
notice.dismiss()
|
||||
}
|
||||
notice.show()
|
||||
expect(notice.isVisible, "The status button can still open the policy manually")
|
||||
notice.dismiss()
|
||||
notice.didEnterBackground()
|
||||
notice.didBecomeActive(hasNetworkConsent: true)
|
||||
expect(!notice.isVisible, "Granting consent stops automatic prompts")
|
||||
notice.didEnterBackground()
|
||||
notice.didBecomeActive(hasNetworkConsent: false)
|
||||
expect(notice.isVisible, "Withdrawal restores the next-visit prompt")
|
||||
} else {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("crossdesk-thumbnails-\(UUID().uuidString)")
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = ThumbnailFileStore(directory: directory)
|
||||
let started = DispatchSemaphore(value: 0)
|
||||
let finishCapture = DispatchSemaphore(value: 0)
|
||||
let cleared = DispatchSemaphore(value: 0)
|
||||
store.save(fileName: "remote.jpg", makeData: {
|
||||
started.signal()
|
||||
wait(finishCapture)
|
||||
return Data("sensitive frame".utf8)
|
||||
}) { fileName in
|
||||
expect(fileName == "remote.jpg", "Capture must exercise the real write path")
|
||||
}
|
||||
wait(started)
|
||||
if test == "clear" {
|
||||
// Withdrawal/clear arrives while image conversion is still running.
|
||||
store.removeAll { success in
|
||||
expect(success, "Clear must succeed")
|
||||
cleared.signal()
|
||||
}
|
||||
} else {
|
||||
// Removing a recent connection must also win over its pending capture.
|
||||
store.remove(fileName: "remote.jpg")
|
||||
store.save(fileName: "barrier.jpg", makeData: { Data([1]) }) { _ in
|
||||
cleared.signal()
|
||||
}
|
||||
}
|
||||
finishCapture.signal()
|
||||
wait(cleared)
|
||||
expect(!FileManager.default.fileExists(atPath: store.url(for: "remote.jpg").path),
|
||||
"A pending write must not resurrect a deleted preview")
|
||||
// A later explicitly permitted capture can still be saved.
|
||||
let saved = DispatchSemaphore(value: 0)
|
||||
store.save(fileName: "new.jpg", makeData: { Data("new frame".utf8) }) { name in
|
||||
expect(name == "new.jpg", "New captures must work after clearing")
|
||||
saved.signal()
|
||||
}
|
||||
wait(saved)
|
||||
let data = try Data(contentsOf: store.url(for: "new.jpg"))
|
||||
expect(data == Data("new frame".utf8), "Saved preview must be intact")
|
||||
let values = try directory.resourceValues(forKeys: [.isExcludedFromBackupKey])
|
||||
expect(values.isExcludedFromBackup == true, "Previews must be excluded from backup")
|
||||
}
|
||||
}
|
||||
}
|
||||
''')
|
||||
source = Path(__file__).resolve().parents[1] / "CrossDeskMobile"
|
||||
cls.binary = root / "privacy-tests"
|
||||
subprocess.run([
|
||||
"xcrun", "swiftc", "-swift-version", "5",
|
||||
str(source / "PrivacyPreferences.swift"),
|
||||
str(source / "ThumbnailFileStore.swift"), str(harness),
|
||||
"-o", str(cls.binary),
|
||||
], check=True, capture_output=True, text=True)
|
||||
|
||||
def run_case(self, case):
|
||||
result = subprocess.run([str(self.binary), case], capture_output=True,
|
||||
text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_consent_persistence_and_withdrawal(self):
|
||||
self.run_case("consent")
|
||||
|
||||
def test_upgrade_requires_fresh_choices(self):
|
||||
self.run_case("upgrade")
|
||||
|
||||
def test_notice_on_each_unconsented_visit(self):
|
||||
self.run_case("notice_lifecycle")
|
||||
|
||||
def test_clear_wins_over_in_flight_capture(self):
|
||||
self.run_case("clear")
|
||||
|
||||
def test_remove_connection_wins_over_in_flight_capture(self):
|
||||
self.run_case("remove")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Check platform persistence without losing existing recent connections."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "darwin", "requires the Apple Swift runtime")
|
||||
class RecentConnectionTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="crossdesk-recent-connections-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
root = Path(cls.temp.name)
|
||||
harness = root / "RecentConnectionTests.swift"
|
||||
harness.write_text(r'''
|
||||
import Foundation
|
||||
|
||||
func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
|
||||
if !condition() { fatalError(message) }
|
||||
}
|
||||
|
||||
@main enum RecentConnectionTests {
|
||||
static func main() throws {
|
||||
let test = CommandLine.arguments[1]
|
||||
let decoder = JSONDecoder()
|
||||
let legacy = #"{"remoteID":"123456","displayName":"Work PC","lastConnectedAt":100,"remembersPassword":true,"thumbnailFileName":"123456.jpg"}"#
|
||||
if test == "legacy" {
|
||||
for field in ["", #", "platform":null"#, #", "platform":23"#,
|
||||
#", "platform":"future-os""#] {
|
||||
let record = String(legacy.dropLast()) + field + "}"
|
||||
let connections = try decoder.decode([RecentConnection].self,
|
||||
from: Data("[\(record)]".utf8))
|
||||
expect(connections.count == 1, "Old history must not be discarded")
|
||||
let connection = connections[0]
|
||||
expect(connection.platform == .unknown, "Missing or invalid platform is unknown")
|
||||
expect(connection.platform.displayName == "未知", "Unknown has a readable placeholder")
|
||||
expect(connection.remoteID == "123456" && connection.displayName == "Work PC",
|
||||
"Existing identity and name survive migration")
|
||||
expect(connection.lastConnectedAt == Date(timeIntervalSinceReferenceDate: 100) &&
|
||||
connection.remembersPassword && connection.thumbnailFileName == "123456.jpg",
|
||||
"Migration preserves dates, saved-password flags and previews")
|
||||
}
|
||||
} else if test == "round_trip" {
|
||||
let platforms: [RemoteHostPlatform] = [.windows, .linux, .macos, .ios, .unknown]
|
||||
let connections = platforms.enumerated().map { index, platform in
|
||||
RecentConnection(remoteID: String(index), displayName: "Host \(index)",
|
||||
lastConnectedAt: Date(timeIntervalSinceReferenceDate: Double(index)),
|
||||
remembersPassword: false, thumbnailFileName: nil, platform: platform)
|
||||
}
|
||||
let data = try JSONEncoder().encode(connections)
|
||||
let reloaded = try decoder.decode([RecentConnection].self, from: data)
|
||||
expect(reloaded == connections, "Platforms persist per device without requiring an image")
|
||||
} else if test == "host_info" {
|
||||
var connection = try decoder.decode(RecentConnection.self, from: Data(legacy.utf8))
|
||||
connection.updateHostInfo(name: " ", platform: .windows)
|
||||
expect(connection.displayName == "Work PC" && connection.platform == .windows,
|
||||
"An empty host name must not prevent a platform update")
|
||||
connection.updateHostInfo(name: " Linux workstation ", platform: .linux)
|
||||
expect(connection.displayName == "Linux workstation" && connection.platform == .linux,
|
||||
"New host information replaces the cached platform")
|
||||
connection.updateHostInfo(name: "", platform: .unknown)
|
||||
let data = try JSONEncoder().encode(connection)
|
||||
let reloaded = try decoder.decode(RecentConnection.self, from: data)
|
||||
expect(reloaded.platform == .unknown && reloaded.thumbnailFileName == "123456.jpg",
|
||||
"Legacy peers replace the old platform without removing a saved preview")
|
||||
} else {
|
||||
fatalError("Unknown test")
|
||||
}
|
||||
}
|
||||
}
|
||||
''')
|
||||
source = Path(__file__).resolve().parents[1] / "CrossDeskMobile/RecentConnection.swift"
|
||||
cls.binary = root / "recent-connection-tests"
|
||||
subprocess.run(["xcrun", "swiftc", str(source), str(harness), "-o", str(cls.binary)],
|
||||
check=True, capture_output=True, text=True)
|
||||
|
||||
def run_case(self, case):
|
||||
result = subprocess.run([str(self.binary), case], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr or result.stdout)
|
||||
|
||||
def test_existing_history_survives_platform_migration(self):
|
||||
self.run_case("legacy")
|
||||
|
||||
def test_platforms_persist_without_saved_previews(self):
|
||||
self.run_case("round_trip")
|
||||
|
||||
def test_received_host_info_replaces_cached_platform(self):
|
||||
self.run_case("host_info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Regression coverage for notice validation and build-specific source links."""
|
||||
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def load_script(name):
|
||||
path = Path(__file__).resolve().parents[1] / "scripts" / f"{name}.py"
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
licenses = load_script("generate_third_party_licenses")
|
||||
metadata = load_script("prepare_source_metadata")
|
||||
|
||||
|
||||
class LicenseValidationTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory(prefix="crossdesk-ios-licenses-")
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.root = Path(temporary.name)
|
||||
self.mini = self.root / "deps/submodules/minirtc"
|
||||
self.mini.mkdir(parents=True)
|
||||
self.notice = self.mini / "LICENSE"
|
||||
self.notice.write_text("Reviewed license text\n")
|
||||
self.recipe = self.mini / "thirdparty/opus/xmake.lua"
|
||||
self.recipe.parent.mkdir(parents=True)
|
||||
self.recipe.write_text('package("opus")\n')
|
||||
self.source = self.mini / "transport.cpp"
|
||||
self.source.write_text("int transport() { return 1; }\n")
|
||||
self.git("init", "-q")
|
||||
self.git("add", ".")
|
||||
self.git("commit", "-qm", "Reviewed source")
|
||||
self.reviewed_revision = self.git("rev-parse", "HEAD")
|
||||
|
||||
self.bundle = self.root / "ThirdPartyLicenses.json"
|
||||
self.bundle.write_text('{"schemaVersion": 1, "components": []}\n')
|
||||
self.archive = self.root / "packages/o/opus/1.0/abcd/lib/libopus.a"
|
||||
self.archive.parent.mkdir(parents=True)
|
||||
self.archive.write_bytes(b"reviewed archive")
|
||||
self.inputs = self.root / "inputs.sha256"
|
||||
self.inputs.write_text(f"{licenses.digest(self.archive.read_bytes())} {self.archive}\n")
|
||||
self.target = self.root / "target-info.txt"
|
||||
self.target.write_text(str(self.root / "packages/a/asio/1.0/abcd/include") + "\n")
|
||||
self.lock = {
|
||||
"bundle_sha256": licenses.digest(self.bundle.read_bytes()),
|
||||
"toolchain": {"xmake_version": "3.1.1"},
|
||||
"components": [
|
||||
{
|
||||
"id": "minirtc", "version": self.reviewed_revision,
|
||||
"source": {"kind": "repository", "url": metadata.MINIRTC_URL,
|
||||
"revision": self.reviewed_revision},
|
||||
"documents": [{"path": str(self.notice.relative_to(self.root)),
|
||||
"sha256": licenses.digest(self.notice.read_bytes())}],
|
||||
},
|
||||
{
|
||||
"id": "opus", "package": "opus", "version": "1.0",
|
||||
"source": {"kind": "archive", "url": "https://example.com/opus.tar.gz"},
|
||||
"recipe_path": str(self.recipe.relative_to(self.root)),
|
||||
"recipe_sha256": licenses.digest(self.recipe.read_bytes()),
|
||||
},
|
||||
{"id": "asio", "package": "asio", "version": "1.0",
|
||||
"source": {"kind": "archive", "url": "https://example.com/asio.tar.gz"}},
|
||||
],
|
||||
}
|
||||
for name, value in (("REPO", self.root), ("OUTPUT", self.bundle)):
|
||||
patcher = patch.object(licenses, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.check_output(
|
||||
["git", "-C", str(self.mini), "-c", "user.name=Test",
|
||||
"-c", "user.email=test@example.com", "-c", "commit.gpgsign=false", *args],
|
||||
text=True).strip()
|
||||
|
||||
def verify(self, preflight=False, **kwargs):
|
||||
licenses.verify(self.lock, None if preflight else self.inputs,
|
||||
None if preflight else self.target, **kwargs)
|
||||
|
||||
def test_source_only_commit_keeps_reviewed_catalog_and_uses_actual_links(self):
|
||||
self.source.write_text("int transport() { return 2; }\n")
|
||||
self.git("add", ".")
|
||||
self.git("commit", "-qm", "Change transport implementation")
|
||||
current = self.git("rev-parse", "HEAD")
|
||||
self.assertNotEqual(current, self.reviewed_revision)
|
||||
original_lock = copy.deepcopy(self.lock)
|
||||
original_bundle = self.bundle.read_bytes()
|
||||
self.verify(preflight=True)
|
||||
self.verify()
|
||||
sources = metadata.component_sources(self.lock, current)
|
||||
self.assertEqual(sources["minirtc"]["version"], current)
|
||||
self.assertEqual(sources["minirtc"]["sourceURL"], f"{metadata.MINIRTC_URL}/tree/{current}")
|
||||
self.assertEqual(sources["opus"]["buildSourceURL"],
|
||||
f"{metadata.MINIRTC_URL}/tree/{current}/thirdparty/opus")
|
||||
self.assertEqual(self.lock, original_lock)
|
||||
self.assertEqual(self.bundle.read_bytes(), original_bundle)
|
||||
|
||||
def test_changed_license_is_rejected_before_compilation(self):
|
||||
self.notice.write_text("Changed license text\n")
|
||||
with self.assertRaisesRegex(ValueError, "Source checksum mismatch: .*LICENSE"):
|
||||
self.verify(preflight=True)
|
||||
|
||||
def test_changed_recipe_is_rejected_before_compilation(self):
|
||||
self.recipe.write_text('package("different-opus")\n')
|
||||
with self.assertRaisesRegex(ValueError, "Source checksum mismatch: .*xmake.lua"):
|
||||
self.verify(preflight=True)
|
||||
|
||||
def test_changed_bundle_is_rejected_before_compilation(self):
|
||||
self.bundle.write_text("{}\n")
|
||||
with self.assertRaisesRegex(ValueError, "Source checksum mismatch:"):
|
||||
self.verify(preflight=True)
|
||||
|
||||
def test_unreviewed_header_only_dependency_is_rejected(self):
|
||||
self.target.write_text(str(self.root / "packages/a/asio/2.0/abcd/include") + "\n")
|
||||
with self.assertRaisesRegex(ValueError, "Unreviewed iOS dependency: asio 2.0"):
|
||||
self.verify()
|
||||
|
||||
def test_missing_dependency_is_rejected(self):
|
||||
self.target.write_text("")
|
||||
with self.assertRaisesRegex(ValueError, "License/build dependency mismatch; missing:.*asio"):
|
||||
self.verify()
|
||||
|
||||
def test_changed_native_archive_is_rejected(self):
|
||||
self.archive.write_bytes(b"changed archive")
|
||||
with self.assertRaisesRegex(ValueError, "Source checksum mismatch: .*libopus.a"):
|
||||
self.verify()
|
||||
|
||||
def test_unreviewed_toolchain_is_rejected(self):
|
||||
version = self.root / "xmake-version.txt"
|
||||
version.write_text("xmake v3.1.2\n")
|
||||
with self.assertRaisesRegex(ValueError, "Xmake version differs"):
|
||||
self.verify(xmake_version=version)
|
||||
|
||||
|
||||
class ComponentSourceTest(unittest.TestCase):
|
||||
def test_all_minirtc_components_and_custom_recipes_follow_build_revision(self):
|
||||
lock_path = Path(__file__).resolve().parents[1] / "licenses/sources.json"
|
||||
lock = json.loads(lock_path.read_text())
|
||||
reviewed = copy.deepcopy(lock)
|
||||
revision = "a" * 40
|
||||
base = f"{metadata.MINIRTC_URL}/tree/{revision}"
|
||||
sources = metadata.component_sources(lock, revision)
|
||||
for name in ("minirtc", "inih", "webrtc"):
|
||||
self.assertEqual(sources[name], {"version": revision, "sourceURL": base})
|
||||
self.assertEqual(sources["openssl3"], {"buildSourceURL": base + "/thirdparty/openssl"})
|
||||
self.assertNotIn("asio", sources)
|
||||
self.assertNotIn("crossdesk", sources)
|
||||
self.assertEqual(lock, reviewed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Exercise the production live-video settings state with the Apple Swift runtime."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "darwin", "requires the Apple Swift runtime")
|
||||
class VideoSettingsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="crossdesk-video-settings-tests-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
root = Path(cls.temp.name)
|
||||
harness = root / "VideoSettingsTests.swift"
|
||||
harness.write_text(r'''
|
||||
func expect(_ condition: @autoclosure () -> Bool, _ message: String) {
|
||||
if !condition() { fatalError(message) }
|
||||
}
|
||||
|
||||
@main
|
||||
enum VideoSettingsTests {
|
||||
static func main() {
|
||||
let test = CommandLine.arguments[1]
|
||||
let initial = RemoteVideoSettings(preference: 0)
|
||||
let first = RemoteVideoSettings(quality: 1, frameRate: 30, preference: 2)
|
||||
let second = RemoteVideoSettings(quality: 0, frameRate: 60, preference: 1)
|
||||
var state = RemoteVideoSettingsState(preference: 0)
|
||||
expect(state.selection == initial, "Session starts with the saved preference")
|
||||
expect(state.begin(first) == nil, "Old hosts cannot receive live settings")
|
||||
state.setSupported(true)
|
||||
|
||||
if test == "invalid" {
|
||||
for quality in -1...3 {
|
||||
for frameRate in [0, 24, 30, 60, 120] {
|
||||
for preference in -1...3 {
|
||||
let settings = RemoteVideoSettings(quality: quality,
|
||||
frameRate: frameRate, preference: preference)
|
||||
let valid = (0...2).contains(quality) &&
|
||||
[30, 60].contains(frameRate) && (0...2).contains(preference)
|
||||
expect((state.begin(settings) != nil) == valid,
|
||||
"Only desktop protocol values can be submitted")
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
let firstID = state.begin(first)!
|
||||
expect(state.pending && state.selection == first, "Selection is optimistic")
|
||||
expect(state.applied == initial, "Submission is not confirmation")
|
||||
|
||||
if test == "accepted" {
|
||||
state.receive(first, requestID: firstID, accepted: true)
|
||||
expect(!state.pending && !state.failed && state.selection == first,
|
||||
"An accepted response commits the selection")
|
||||
state.expire(requestID: firstID)
|
||||
expect(!state.failed, "A completed request cannot time out")
|
||||
} else if test == "rejected" {
|
||||
state.receive(first, requestID: firstID, accepted: false)
|
||||
expect(state.failed && !state.pending && state.selection == initial,
|
||||
"Rejection rolls back the optimistic selection")
|
||||
expect(state.begin(first) != nil && !state.failed && state.pending,
|
||||
"A failed selection can be retried")
|
||||
} else if test == "superseded" {
|
||||
let secondID = state.begin(second)!
|
||||
state.receive(first, requestID: firstID, accepted: true)
|
||||
state.expire(requestID: firstID)
|
||||
expect(state.selection == second && state.pending,
|
||||
"An old reply or timeout cannot overwrite a newer selection")
|
||||
state.receive(second, requestID: secondID, accepted: false)
|
||||
expect(state.selection == first && state.failed,
|
||||
"Rollback uses the most recently acknowledged settings")
|
||||
} else if test == "out_of_order" {
|
||||
let secondID = state.begin(second)!
|
||||
state.receive(second, requestID: secondID, accepted: true)
|
||||
state.receive(first, requestID: firstID, accepted: true)
|
||||
expect(state.selection == second && state.applied == second && !state.failed,
|
||||
"A stale success cannot revert a newer success")
|
||||
state.receive(first, requestID: secondID + 1, accepted: true)
|
||||
expect(state.applied == second, "Unsent request IDs are ignored")
|
||||
} else if test == "timeout" {
|
||||
state.expire(requestID: firstID)
|
||||
expect(state.failed && !state.pending && state.selection == initial,
|
||||
"Timeout restores the last applied settings")
|
||||
state.receive(first, requestID: firstID, accepted: true)
|
||||
expect(state.selection == first && !state.failed,
|
||||
"A late confirmation reconciles the actual remote state")
|
||||
} else if test == "unsupported" {
|
||||
state.setSupported(false)
|
||||
state.receive(first, requestID: firstID, accepted: true)
|
||||
state.expire(requestID: firstID)
|
||||
expect(!state.pending && !state.failed && state.selection == initial,
|
||||
"Losing capability clears pending feedback and ignores replies")
|
||||
expect(state.begin(second) == nil, "Unavailable controls cannot send")
|
||||
state = RemoteVideoSettingsState(preference: 2)
|
||||
expect(!state.supported && state.requestID == 0 &&
|
||||
state.selection == RemoteVideoSettings(preference: 2),
|
||||
"A new session resets capability, request IDs and settings")
|
||||
} else {
|
||||
fatalError("Unknown test")
|
||||
}
|
||||
}
|
||||
}
|
||||
''')
|
||||
source = Path(__file__).resolve().parents[1] / "CrossDeskMobile/RemoteVideoSettings.swift"
|
||||
cls.binary = root / "video-settings-tests"
|
||||
subprocess.run(["xcrun", "swiftc", str(source), str(harness),
|
||||
"-o", str(cls.binary)], check=True, capture_output=True, text=True)
|
||||
|
||||
def test_protocol_values(self):
|
||||
self.run_case("invalid")
|
||||
|
||||
def test_acceptance(self):
|
||||
self.run_case("accepted")
|
||||
|
||||
def test_rejection_and_retry(self):
|
||||
self.run_case("rejected")
|
||||
|
||||
def test_rapid_changes(self):
|
||||
self.run_case("superseded")
|
||||
|
||||
def test_out_of_order_responses(self):
|
||||
self.run_case("out_of_order")
|
||||
|
||||
def test_timeout_and_late_confirmation(self):
|
||||
self.run_case("timeout")
|
||||
|
||||
def test_unsupported_and_new_session(self):
|
||||
self.run_case("unsupported")
|
||||
|
||||
def run_case(self, name):
|
||||
subprocess.run([str(self.binary), name], check=True, capture_output=True, text=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Vendored
+1
-1
Submodule deps/submodules/minirtc updated: 8dce241e6e...ee7eaff649
Vendored
+18
-1
@@ -8,6 +8,10 @@ package("slint")
|
||||
add_versions("1.17.1", "68222567f8c70ff677cd4a98cd94fb4765ac0f797eb8f8608a646911c908dc2a")
|
||||
|
||||
add_configs("shared", {description = "Build the Slint runtime as a shared library", default = true, type = "boolean", readonly = true})
|
||||
if is_plat("windows") then
|
||||
-- Include CRT linkage in the package hash so cached /MD builds are not reused.
|
||||
add_configs("static_crt", {description = "Statically link the Windows C runtime", default = true, type = "boolean", readonly = true})
|
||||
end
|
||||
|
||||
add_deps("cmake~slint >=3.21 <4.0", {host = true, private = true, system = false})
|
||||
add_deps("rust 1.92.0", {host = true, private = true, system = false})
|
||||
@@ -51,13 +55,26 @@ package("slint")
|
||||
"-DSLINT_STYLE=fluent",
|
||||
"-DBUILD_SHARED_LIBS=ON"
|
||||
}
|
||||
local cmake = import("package.tools.cmake")
|
||||
local envs
|
||||
if package:is_plat("windows") then
|
||||
local rc = assert(package:build_getenv("mrc"),
|
||||
"failed to find the Windows resource compiler")
|
||||
rc = rc:gsub("\\", "/")
|
||||
table.insert(configs, "-DCMAKE_RC_COMPILER=" .. rc)
|
||||
table.insert(configs, "-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded")
|
||||
|
||||
-- Slint is a Rust cdylib: CMake's /MT setting alone does not affect it.
|
||||
-- Encoded flags take precedence over RUSTFLAGS set by Corrosion.
|
||||
envs = cmake.buildenvs(package)
|
||||
local rustflags = os.getenv("CARGO_ENCODED_RUSTFLAGS")
|
||||
if rustflags == nil then
|
||||
rustflags = table.concat((os.getenv("RUSTFLAGS") or ""):split("%s+"), "\31")
|
||||
end
|
||||
envs.CARGO_ENCODED_RUSTFLAGS = (rustflags ~= "" and rustflags .. "\31" or "") ..
|
||||
"-Ctarget-feature=+crt-static"
|
||||
end
|
||||
import("package.tools.cmake").install(package, configs)
|
||||
cmake.install(package, configs, {envs = envs})
|
||||
end)
|
||||
|
||||
on_test(function(package)
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
# **更新内容**
|
||||
|
||||
1. Windows 新增无显示器远程控制支持,内置虚拟显示器驱动,可自动创建 1920×1080 虚拟屏幕;无法启用时自动切换至兼容采集模式。
|
||||
2. 设置中新增“强制中继”选项,方便在直连不稳定的网络中使用中继连接。
|
||||
3. 主窗口新增随机密码刷新,优化密码重试时的输入体验,并统一为 6 位密码。
|
||||
4. 改善断线重连,修复旧会话阻碍重新连接及已保存密码未正确复用的问题。
|
||||
5. 修复 Windows 远程控制和 Web 控制中的键鼠输入、光标显示及会话路由问题。
|
||||
6. 改善 Windows 显示器热插拔后的屏幕编号、鼠标定位和隐私屏稳定性。
|
||||
7. 修复远程画面缩放后的鼠标位置偏差,以及部分视频帧无法正常显示的问题。
|
||||
8. 修复展开网络状态后屏幕切换菜单的位置偏移。
|
||||
|
||||
PC 客户端版本为 v1.5.2。Windows 无屏自动适配需将采集方式设为“自动”;自动安装和插入虚拟显示器需安装并运行 CrossDesk Service,或以管理员身份运行客户端。
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2026-09-28
|
||||
* Copyright (c) 2026 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _APP_VERSION_H_
|
||||
#define _APP_VERSION_H_
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
struct VersionInfo {
|
||||
std::string version;
|
||||
std::string release_name;
|
||||
std::string release_notes;
|
||||
std::string release_date;
|
||||
int patch = -1;
|
||||
};
|
||||
|
||||
// Shared desktop release parsing and comparison for desktop and iOS controllers.
|
||||
std::optional<VersionInfo> ParseVersionInfoJSON(std::string_view json);
|
||||
bool IsValidAppVersion(const std::string& version);
|
||||
|
||||
bool IsNewerVersion(const std::string& current, const std::string& latest);
|
||||
|
||||
// Pass latest_patch < 0 when patch metadata is unavailable.
|
||||
bool IsNewerVersionWithMetadata(const std::string& current,
|
||||
const std::string& latest,
|
||||
const std::string& latest_date,
|
||||
int latest_patch);
|
||||
|
||||
// Returns the latest release label when the peer is older. Missing or invalid
|
||||
// peer versions are treated as legacy; the latest release must still be valid.
|
||||
std::optional<std::string> AvailableAppUpdate(const std::string& current,
|
||||
const VersionInfo& latest);
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
@@ -116,9 +116,18 @@ struct CursorState {
|
||||
CursorHiddenReason hidden_reason;
|
||||
};
|
||||
|
||||
enum class HostPlatform { Unknown, Windows, MacOS, Linux, IOS };
|
||||
|
||||
const char* HostPlatformName(HostPlatform platform);
|
||||
HostPlatform ParseHostPlatform(const std::string& platform);
|
||||
|
||||
struct HostInfo {
|
||||
char host_name[64];
|
||||
std::size_t host_name_size;
|
||||
// Optional; an empty string means the peer version is unknown.
|
||||
char app_version[64];
|
||||
// Optional on the wire; missing or unrecognized values are unknown.
|
||||
HostPlatform platform;
|
||||
char** display_list;
|
||||
std::size_t display_num;
|
||||
int* left;
|
||||
@@ -213,9 +222,12 @@ struct HostDisplay {
|
||||
// heap-allocated with the same layout the decoder produces; release the
|
||||
// result with FreeRemoteAction. An allocation failure yields an empty display
|
||||
// list rather than a partially filled one.
|
||||
// Missing or oversized app versions are advertised as unknown (empty).
|
||||
RemoteAction MakeHostInformation(const std::string& host_name,
|
||||
const std::vector<HostDisplay>& displays,
|
||||
bool supports_privacy_screen);
|
||||
bool supports_privacy_screen,
|
||||
const std::string& app_version = {},
|
||||
HostPlatform platform = HostPlatform::Unknown);
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user