Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
263ed41e7a | ||
|
|
2c60a2c2b5 | ||
|
|
58ff78a823 | ||
|
|
a8ae0d6d66 | ||
|
|
2e333f64a4 | ||
|
|
e424b57fca | ||
|
|
b30f781fd6 | ||
|
|
68a35e65f2 | ||
|
|
7c21b4569c | ||
|
|
c6a358afbe | ||
|
|
458ffe44c6 | ||
|
|
2e7255f083 | ||
|
|
12f61b1fda |
@@ -2046,6 +2046,44 @@ jobs:
|
||||
*) echo "::error::build.py returned no '$want' feature: $FEATURES"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
# Run the drm-gated unit tests HERE, because nowhere else does. The ordinary linux CI
|
||||
# runs the suite, but `drm` is opt-in, so every test behind that feature -- the cursor
|
||||
# rotation and hotspot ones especially -- has no continuous coverage at all otherwise.
|
||||
# Debug rather than --release: these are pure logic tests and the release build is
|
||||
# already the slow part of this job.
|
||||
# A MINIMAL feature set, not the production $FEATURES: these are pure logic tests of
|
||||
# the drm paths, and pulling hwcodec in makes the test binary fail to link at all
|
||||
# (undefined reference to fcntl64 in this container), so the tests never run.
|
||||
#
|
||||
# Two packages, because `cargo test --lib` at the root builds the ROOT package only:
|
||||
# the provenance tests live in libs/scrap and would never be selected from here. The
|
||||
# ordinary linux CI runs --workspace but without the drm feature, so these are not
|
||||
# covered there either.
|
||||
#
|
||||
# awk sums the counts rather than bc, which this container does not install.
|
||||
#
|
||||
# A cargo test FILTER that matches nothing exits 0, so a rename would turn this into a
|
||||
# green no-op. Assert each command actually ran something.
|
||||
run_drm_tests() {
|
||||
local desc="$1"; shift
|
||||
local out
|
||||
out=$("$@" 2>&1) || { echo "$out"; echo "::error::drm tests failed: $desc"; exit 1; }
|
||||
local ran
|
||||
ran=$(echo "$out" | awk '/^running [0-9]+ tests?$/ { n += $2 } END { print n+0 }')
|
||||
echo "$desc ran $ran tests"
|
||||
if [ "$ran" -lt 1 ]; then
|
||||
echo "::error::$desc selected no tests; it was renamed or removed"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
run_drm_tests "rustdesk drm_capturer_tests" \
|
||||
cargo test --locked --lib --features drm drm_capturer_tests
|
||||
run_drm_tests "rustdesk ipc::test" \
|
||||
cargo test --locked --lib --features drm ipc::test
|
||||
run_drm_tests "scrap hotspot_provenance_tests" \
|
||||
cargo test --locked -p scrap --features drm hotspot_provenance_tests
|
||||
run_drm_tests "scrap hotspot_guess_tests" \
|
||||
cargo test --locked -p scrap --features drm hotspot_guess_tests
|
||||
cargo build --locked --lib --features "$FEATURES" --release
|
||||
rm -rf target/release/deps target/release/build
|
||||
rm -rf ~/.cargo
|
||||
@@ -2406,7 +2444,9 @@ jobs:
|
||||
sudo pip3 install git+https://github.com/rustdesk-org/appimage-builder.git
|
||||
# run appimage-builder
|
||||
pushd appimage
|
||||
./build-apprun.sh ${{ matrix.job.arch }}
|
||||
sudo appimage-builder --skip-tests --recipe ./AppImageBuilder-${{ matrix.job.arch }}.yml
|
||||
cmp AppDir/AppRun appimage-build/AppRun/v2.0.0/AppRun-Release-${{ matrix.job.arch }}
|
||||
|
||||
- name: Publish appimage package
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
--- a/src/common/shell_utils.c
|
||||
+++ b/src/common/shell_utils.c
|
||||
@@ -201,7 +201,8 @@
|
||||
|
||||
const char *begin = str;
|
||||
const char *end = str;
|
||||
- char buffer[1024] = {0x0};
|
||||
+ size_t buffer_size = strlen(str) + 1;
|
||||
+ char *buffer = calloc(buffer_size, sizeof(char));
|
||||
|
||||
while (*begin != '\0') {
|
||||
begin = apprun_string_consume_spaces(begin);
|
||||
@@ -209,7 +210,7 @@
|
||||
|
||||
if (*begin == '\\') {
|
||||
strncat(buffer, begin + 1, 1);
|
||||
- end = begin + 2;
|
||||
+ end = begin[1] != '\0' ? begin + 2 : begin + 1;
|
||||
consumed = true;
|
||||
}
|
||||
|
||||
@@ -218,7 +219,8 @@
|
||||
strncat(buffer, begin + 1, end - begin - 1);
|
||||
consumed = true;
|
||||
|
||||
- end++;
|
||||
+ if (*end != '\0')
|
||||
+ end++;
|
||||
}
|
||||
|
||||
if (!consumed && *begin == '\"') {
|
||||
@@ -226,7 +228,8 @@
|
||||
strncat(buffer, begin + 1, end - begin - 1);
|
||||
consumed = true;
|
||||
|
||||
- end++;
|
||||
+ if (*end != '\0')
|
||||
+ end++;
|
||||
}
|
||||
|
||||
if (!consumed && *begin != '\'' && *begin != '\"' && *begin != '\\') {
|
||||
@@ -240,11 +243,12 @@
|
||||
split_count++;
|
||||
}
|
||||
|
||||
- memset(buffer, 0, 1024);
|
||||
+ buffer[0] = '\0';
|
||||
}
|
||||
|
||||
begin = end;
|
||||
}
|
||||
|
||||
+ free(buffer);
|
||||
return splits;
|
||||
}
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# AppRun v2.0.0, which appimage-builder downloads, splits every argument into a 1 KiB stack
|
||||
# buffer, so any argument of 1024 bytes or more aborts the AppImage before RustDesk starts.
|
||||
# Build it with apprun-split-arguments.patch into the path appimage-builder checks before
|
||||
# downloading. ubuntu:16.04 is what upstream released from, so the host glibc floor is unchanged.
|
||||
set -euo pipefail
|
||||
|
||||
arch=$1
|
||||
version=v2.0.0
|
||||
commit=407700ccef58e1a64cc49856074aee4b1c75d599
|
||||
sha256=05729f2ae0a744369d2d19d0f37acfbdcb1ee064172955b7576883ccef5113b3
|
||||
image=ubuntu:16.04@sha256:1f1a2d56de1d604801a9671f301190704c25d604a416f59e03c04f5c6ffee0d6
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
|
||||
case $arch in
|
||||
x86_64) packages="cmake make g++" ;;
|
||||
aarch64) packages="cmake make g++ g++-aarch64-linux-gnu" ;;
|
||||
*) echo "Unsupported arch: $arch" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
tmp=$(mktemp -d)
|
||||
src=$tmp/src
|
||||
curl -fsSL -o "$tmp/apprun.tar.gz" "https://github.com/AppImageCrafters/AppRun/archive/$commit.tar.gz"
|
||||
echo "$sha256 $tmp/apprun.tar.gz" | sha256sum -c -
|
||||
mkdir "$src"
|
||||
tar -xzf "$tmp/apprun.tar.gz" -C "$src" --strip-components=1
|
||||
patch -d "$src" -p1 < "$here/apprun-split-arguments.patch"
|
||||
|
||||
docker run --rm -v "$src:/src" -w /src -e DEBIAN_FRONTEND=noninteractive "$image" bash -c "
|
||||
set -e
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends $packages
|
||||
mkdir build && cd build
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=../cmake/$arch-toolchain.cmake
|
||||
cmake --build . --target AppRun"
|
||||
|
||||
mkdir -p "$here/appimage-build/AppRun/$version"
|
||||
cp "$src/build/src/apprun/AppRun" "$here/appimage-build/AppRun/$version/AppRun-Release-$arch"
|
||||
@@ -390,9 +390,9 @@ def ffi_bindgen_function_refactor():
|
||||
# The commit is fetched directly by sha, so no branch or tag name takes part in the build: see
|
||||
# build_libdrmtap_so(). This is the SINGLE source of truth for the pin, deliberately not duplicated in
|
||||
# any workflow, so a bump is one edit here (plus the informational version comment in
|
||||
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.4.
|
||||
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.6.
|
||||
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
|
||||
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
|
||||
LIBDRMTAP_SHA_PINNED = '49b204f275af1a2d6dfead94effb4036c7d50a3a'
|
||||
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
|
||||
LIBDRMTAP_SHA = os.environ.get('DRMTAP_SHA', LIBDRMTAP_SHA_PINNED)
|
||||
# Every way of getting a different .so than the pin needs the same explicit opt-in. Otherwise the
|
||||
@@ -489,8 +489,10 @@ def build_libdrmtap_so():
|
||||
# override of the three -- no fetch, no sha verification, an object built by something this
|
||||
# script cannot see -- so it is the likeliest to hand over a CPU-only build, and skipping the
|
||||
# assertion on exactly this path would leave the check guarding only the case that was
|
||||
# already trustworthy.
|
||||
# already trustworthy. The helper check rides along for the same reason, and it matters
|
||||
# more here than anywhere: this is the branch the packaging workflow takes.
|
||||
_assert_so_has_egl(so)
|
||||
_assert_so_has_no_helper(so)
|
||||
return so
|
||||
# Fetch the pinned source if it is not already present. third_party/libdrmtap is not a submodule
|
||||
# anymore; it is git-ignored. The commit is fetched BY SHA rather than by cloning a branch:
|
||||
@@ -521,8 +523,22 @@ def build_libdrmtap_so():
|
||||
f'libdrmtap at {src} is {got_sha}, expected {LIBDRMTAP_SHA} '
|
||||
f'(stale checkout from a different pin; removed, re-run to re-fetch)')
|
||||
build_dir = os.path.join(src, 'build-pkg')
|
||||
# Configure a fresh dir, or RE-configure one an earlier build left behind. Without the second
|
||||
# branch a build-pkg created before this option was added keeps its old configuration, meson
|
||||
# skips setup, and the compile produces a helper-enabled .so. The assertion below then fails
|
||||
# the build rather than shipping it, so this is a developer-build correctness fix and not a
|
||||
# security one -- but it turns a confusing failure into no failure at all.
|
||||
if not os.path.exists(os.path.join(build_dir, 'build.ninja')):
|
||||
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release')
|
||||
# -Dhelper=disabled: rustdesk never uses the privileged helper. The capture context is
|
||||
# opened only in the root service (every drmtap_open lives in src/ipc/drm.rs), which
|
||||
# already has CAP_SYS_ADMIN, and the unprivileged side opens a render node instead. Without
|
||||
# this the library still carries the fallback: a fork/exec that walks six hardcoded paths,
|
||||
# two of them under /usr/local, and execs the first that passes access(X_OK) with no check
|
||||
# of its owner or mode -- inside the ROOT process. The option compiles that path out
|
||||
# entirely. Requested by the maintainer on rustdesk#16242.
|
||||
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release -Dhelper=disabled')
|
||||
else:
|
||||
system2(f'meson configure "{build_dir}" -Dhelper=disabled')
|
||||
# Build only the shared library, not the bundled helper binary or the static archive. Since
|
||||
# libdrmtap 0.4.11 the project is `both_libraries` (a version-scripted .so + a static .a), so the
|
||||
# bare `drmtap` target is ambiguous ("drmtap:shared_library" vs "drmtap:static_library"); ask for
|
||||
@@ -533,9 +549,31 @@ def build_libdrmtap_so():
|
||||
# require exactly one so a stale object from an earlier build is never silently picked.
|
||||
so = _single_real_so(sos, f'the libdrmtap meson build dir {build_dir}')
|
||||
_assert_so_has_egl(so)
|
||||
_assert_so_has_no_helper(so)
|
||||
return so
|
||||
|
||||
|
||||
def _assert_so_has_no_helper(so_path):
|
||||
# Asserted on the ARTIFACT for the same reason the EGL check is: a build flag cannot notice a
|
||||
# stale object left by an earlier build, or one substituted by hand, and `-Dhelper=disabled` is
|
||||
# silently accepted by meson versions that predate the option. What the option removes is the
|
||||
# whole fork/exec path, so the produced .so imports no socketpair and carries none of the
|
||||
# helper search paths; both go to zero, measured on libdrmtap 0.5.6 (4 -> 0 and 3 -> 0).
|
||||
#
|
||||
# This matters because the object is loaded by the ROOT service. With the path compiled in, a
|
||||
# caller that ever lost CAP_SYS_ADMIN would exec whatever sits at the first of six hardcoded
|
||||
# locations that passes access(X_OK), without checking its owner or its mode.
|
||||
with open(so_path, 'rb') as f:
|
||||
blob = f.read()
|
||||
found = [m.decode() for m in (b'socketpair', b'/usr/libexec/drmtap-helper') if m in blob]
|
||||
if found:
|
||||
raise Exception(
|
||||
f'{so_path} still carries the privileged-helper fallback ({", ".join(found)}). '
|
||||
f'It must be built with -Dhelper=disabled: rustdesk captures as root and never uses '
|
||||
f'the helper, so this is a fork/exec path in the privileged process that nothing '
|
||||
f'reaches. Delete third_party/libdrmtap/build-pkg and rebuild.')
|
||||
|
||||
|
||||
def _assert_so_has_egl(so_path):
|
||||
# libdrmtap treats egl/glesv2 as OPTIONAL dependencies: without their headers and pkg-config
|
||||
# files, meson silently builds a CPU-only stub. That stub still exports every symbol the loader
|
||||
@@ -863,8 +901,10 @@ def build_deb_from_folder(version, binary_folder, want_drm=False):
|
||||
# takes the .so straight out of a bundle somebody else produced, so it has the same
|
||||
# exposure as DRMTAP_PREBUILT_DIR (see the comment on that branch). A CPU-only stub
|
||||
# would ship, the loader would accept it, and capture would degrade to PipeWire
|
||||
# without a word.
|
||||
# without a word. A bundle produced before the helper was disabled is caught here too,
|
||||
# which is the point: it must not be repackaged into a deb.
|
||||
_assert_so_has_egl(so)
|
||||
_assert_so_has_no_helper(so)
|
||||
stage_libdrmtap_into_deb(so)
|
||||
system2(f'rm -f "{so}"')
|
||||
system2('rm -f tmpdeb/usr/share/rustdesk/libdrmtap.so tmpdeb/usr/share/rustdesk/libdrmtap.so.0')
|
||||
|
||||
+43
-35
@@ -1,39 +1,45 @@
|
||||
<p align="center">
|
||||
<img src="../res/logo-header.svg" alt="RustDesk - Ваша віддалена стільниця"><br>
|
||||
<a href="#публічні-сервери">Сервери</a> •
|
||||
<a href="#кроки-для-збірки">Збирання</a> •
|
||||
<img src="../res/logo-header.svg" alt="RustDesk - Ваш віддалений робочий стіл"><br>
|
||||
<a href="#кроки-для-збірки">Збірка</a> •
|
||||
<a href="#як-зібрати-за-допомогою-docker">Docker</a> •
|
||||
<a href="#структура-файлів">Структура</a> •
|
||||
<a href="#знімки-екрана">Знімки екрана</a><br>
|
||||
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>]<br>
|
||||
<b>Нам потрібна ваша допомога для перекладу цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації</a> RustDesk вашою рідною мовою</B>
|
||||
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>] | [<a href="README-NO.md">Norsk</a>] | [<a href="README-RO.md">Română</a>]<br>
|
||||
<b>Нам потрібна ваша допомога з перекладом цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу RustDesk</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації RustDesk</a> вашою рідною мовою</b>
|
||||
</p>
|
||||
|
||||
Спілкування з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
> [!CAUTION]
|
||||
> **Застереження щодо неналежного використання:** <br>
|
||||
> Розробники RustDesk не схвалюють і не підтримують неетичне або незаконне використання цього програмного забезпечення. Неналежне використання, зокрема несанкціонований доступ, керування або втручання в приватність, суворо суперечить нашим правилам. Автори не несуть відповідальності за неналежне використання застосунку.
|
||||
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
Спілкуйтеся з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
|
||||
Ще один застосунок для віддаленого керування стільницею, написаний на Rust. Працює з коробки, не потребує налаштування. Ви повністю контролюєте свої дані, не турбуючись про безпеку. Ви можете використовувати наш сервер ретрансляції, [налаштувати свій власний](https://rustdesk.com/server), або [написати свій власний сервер ретрансляції](https://github.com/rustdesk/rustdesk-server-demo).
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
|
||||
RustDesk — ще одне рішення для віддаленого робочого столу, написане на Rust. Працює одразу після запуску й не потребує налаштування. Ви повністю контролюєте свої дані та їхню безпеку. Можна використовувати наш rendezvous/relay-сервер, [налаштувати власний](https://rustdesk.com/server) або [написати власний rendezvous/relay-сервер](https://github.com/rustdesk/rustdesk-server-demo).
|
||||
|
||||

|
||||
|
||||
RustDesk вітає внесок кожного. Ознайомтеся з [CONTRIBUTING.md](CONTRIBUTING.md), щоб отримати допомогу на початковому етапі.
|
||||
RustDesk вітає внески від усіх охочих. Дивіться [CONTRIBUTING.md](CONTRIBUTING.md), щоб дізнатися, з чого почати.
|
||||
|
||||
[**ЧаПи**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
|
||||
[**FAQ**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
|
||||
|
||||
[**ЗАВАНТАЖЕННЯ ЗАСТОСУНКУ**](https://github.com/rustdesk/rustdesk/releases)
|
||||
[**ЗАВАНТАЖИТИ ГОТОВУ ЗБІРКУ**](https://github.com/rustdesk/rustdesk/releases)
|
||||
|
||||
[**НІЧНІ ЗБІРКИ**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
|
||||
|
||||
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
|
||||
[<img src="https://f-droid.org/badge/get-it-on.png"
|
||||
alt="Get it on F-Droid"
|
||||
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
|
||||
[<img src="https://flathub.org/api/badge?svg&locale=en"
|
||||
alt="Get it on Flathub"
|
||||
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
|
||||
|
||||
## Залежності
|
||||
|
||||
Стільничні версії використовують Flutter чи Sciter (застаріле) для графічного інтерфейсу. Ця інструкція лише для Sciter, оскільки він є більш простим та дружнім для початківців. Перегляньте [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) для збірки версії на Flutter.
|
||||
Версії для настільних ОС використовують Flutter або Sciter (застарілий) для графічного інтерфейсу. Ця інструкція стосується лише Sciter, оскільки з ним простіше почати. Для збірки версії на Flutter дивіться наш [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml).
|
||||
|
||||
Будь ласка, завантажте динамічну бібліотеку Sciter самостійно.
|
||||
Динамічну бібліотеку Sciter потрібно завантажити окремо.
|
||||
|
||||
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
|
||||
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
|
||||
@@ -41,14 +47,14 @@ RustDesk вітає внесок кожного. Ознайомтеся з [CONT
|
||||
|
||||
## Кроки для збірки
|
||||
|
||||
- Підготуйте середовище розробки Rust і середовище збирання C++.
|
||||
- Підготуйте середовище розробки Rust і середовище для збирання C++.
|
||||
|
||||
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg), і правильно встановіть змінну `VCPKG_ROOT`.
|
||||
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg) і правильно задайте змінну середовища `VCPKG_ROOT`.
|
||||
|
||||
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static
|
||||
- Linux/macOS: vcpkg install libvpx libyuv opus aom
|
||||
|
||||
- Запустіть `cargo run`
|
||||
- Запустіть `cargo run`.
|
||||
|
||||
## [Збирання](https://rustdesk.com/docs/en/dev/build/)
|
||||
|
||||
@@ -110,7 +116,7 @@ cd
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
source $HOME/.cargo/env
|
||||
git clone https://github.com/rustdesk/rustdesk
|
||||
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
|
||||
cd rustdesk
|
||||
mkdir -p target/debug
|
||||
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
|
||||
@@ -120,54 +126,56 @@ VCPKG_ROOT=$HOME/vcpkg cargo run
|
||||
|
||||
## Як зібрати за допомогою Docker
|
||||
|
||||
Почніть з клонування сховища та створення docker-контейнера:
|
||||
Спочатку клонуйте репозиторій і зберіть Docker-контейнер:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/rustdesk/rustdesk
|
||||
cd rustdesk
|
||||
git submodule update --init --recursive
|
||||
docker build -t "rustdesk-builder" .
|
||||
```
|
||||
|
||||
Надалі щоразу, коли вам буде потрібно зібрати застосунок, запускайте таку команду:
|
||||
Після цього щоразу, коли потрібно зібрати застосунок, запускайте таку команду:
|
||||
|
||||
```sh
|
||||
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
|
||||
```
|
||||
|
||||
Зверніть увагу, що перша збірка може зайняти більше часу, перш ніж залежності будуть кешовані, але наступні збірки будуть виконуватися швидше. Крім того, якщо вам потрібно вказати інші аргументи для команди збірки, ви можете зробити це в кінці команди у змінній `<OPTIONAL-ARGS>`. Наприклад, якщо ви хочете створити оптимізовану версію, ви маєте запустити наведену вище команду і в кінці рядка додати `--release`. Отриманий виконуваний файл буде доступний у цільовій папці вашої системи і може бути запущений за допомогою:
|
||||
Перша збірка може тривати довше, доки залежності не буде кешовано. Наступні збірки виконуватимуться швидше. Якщо потрібно передати додаткові аргументи команді збірки, додайте їх після `rustdesk-builder` у кінці команди `docker run`. Наприклад, для оптимізованої release-збірки додайте `--release`. Отриманий виконуваний файл буде доступний у каталозі `target` вашої системи та його можна запустити так:
|
||||
|
||||
```sh
|
||||
target/debug/rustdesk
|
||||
```
|
||||
|
||||
Або, якщо ви використовуєте виконуваний файл релізу:
|
||||
Або, якщо використовується release-збірка:
|
||||
|
||||
```sh
|
||||
target/release/rustdesk
|
||||
```
|
||||
|
||||
Будь ласка, переконайтеся, що ви запускаєте ці команди з кореня сховища RustDesk, інакше додаток не зможе знайти необхідні ресурси. Також зверніть увагу, що інші cargo підкоманди, такі як `install` або `run`, наразі не підтримуються цим методом, оскільки вони будуть встановлювати або запускати програму всередині контейнера, а не на хості.
|
||||
Запускайте ці команди з кореневого каталогу репозиторію RustDesk, інакше застосунок може не знайти потрібні ресурси. Також зверніть увагу, що інші підкоманди cargo, наприклад `install` або `run`, наразі не підтримуються цим способом, оскільки вони встановлюватимуть або запускатимуть програму всередині контейнера, а не на хост-системі.
|
||||
|
||||
## Структура файлів
|
||||
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфіг, обгортка tcp/udp, protobuf, функції fs для передавання файлів і деякі інші службові функції
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфігурація, обгортка tcp/udp та інші допоміжні функції, спільні із сервером
|
||||
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, функції файлової системи для передавання файлів, код клавіатури та платформоспецифічний код, що використовуються лише цим застосунком
|
||||
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: захоплення екрана
|
||||
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: специфічне для платформи керування клавіатурою/мишею
|
||||
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux, macOS.
|
||||
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: графічний інтерфейс користувача
|
||||
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: сервіси аудіо/буфера обміну/вводу/відео та мережевих підключень
|
||||
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: однорангове зʼєднання
|
||||
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: комунікація з [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування віддаленого прямого (обхід TCP NAT) або ретрансльованого зʼєднання
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: специфічний для платформи код
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для мобільних пристроїв
|
||||
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: платформоспецифічне керування клавіатурою та мишею
|
||||
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux і macOS
|
||||
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: застарілий інтерфейс Sciter (deprecated)
|
||||
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: служби аудіо, буфера обміну, введення та відео, а також мережеві з'єднання
|
||||
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: встановлення однорангового з'єднання
|
||||
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: зв'язок із [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування прямого віддаленого з'єднання (TCP hole punching) або з'єднання через ретранслятор
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: платформоспецифічний код
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для настільних і мобільних платформ
|
||||
|
||||
## Знімки екрана
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
@@ -901,7 +901,11 @@ class RustdeskImpl {
|
||||
}
|
||||
|
||||
String mainGetLocalOption({required String key, dynamic hint}) {
|
||||
return js.context.callMethod('getByName', ['option:local', key]);
|
||||
final v = js.context.callMethod('getByName', ['option:local', key]);
|
||||
if (key == 'lang' && (v == 'pt' || v == 'br')) {
|
||||
return 'pt-br';
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// Do not return the real environment variables.
|
||||
|
||||
@@ -705,6 +705,9 @@ message TestDelay {
|
||||
message PublicKey {
|
||||
bytes asymmetric_value = 1;
|
||||
bytes symmetric_value = 2;
|
||||
// The key exchange version the controller picked, the highest both sides speak; absent,
|
||||
// i.e. 0, is the original scheme.
|
||||
uint32 kx_version = 3;
|
||||
}
|
||||
|
||||
message SignedId { bytes id = 1; }
|
||||
|
||||
+1
-1
Submodule libs/hbb_common updated: d9895ff9cb...229b904508
@@ -14,7 +14,7 @@ wayland = ["gstreamer", "gstreamer-app", "gstreamer-video", "dbus", "tracing", "
|
||||
# `drm` is a pure runtime-dlopen backend: rustdesk loads `libdrmtap.so.0` at runtime (`drmtap_dl.rs`)
|
||||
# and NEVER link-time links it, so the graceful PipeWire fallback when the .so or EGL is absent is
|
||||
# preserved and the drm build pulls in no libdrm/seccomp/cap/EGL link-time deps. The .so is pinned by
|
||||
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.4). We deliberately do
|
||||
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.6). We deliberately do
|
||||
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
|
||||
# and a CAP_SYS_ADMIN helper and emits `-ldrm -lseccomp -lcap`, which would defeat the dlopen model.
|
||||
# Depends on `wayland`: the three drm modules live inside the `#[cfg(feature = "wayland")]` arm of
|
||||
@@ -38,7 +38,7 @@ serde = {version="1.0", features=["derive"]}
|
||||
[dependencies.winapi]
|
||||
version = "0.3"
|
||||
default-features = true
|
||||
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
|
||||
features = ["dxgi", "dxgi1_2", "dxgi1_5", "dxgi1_6", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block = "0.1"
|
||||
|
||||
@@ -8,6 +8,7 @@ use hbb_common::log;
|
||||
use std::ffi::CString;
|
||||
use std::io;
|
||||
use std::os::fd::{FromRawFd, OwnedFd};
|
||||
use std::os::raw::c_int;
|
||||
|
||||
// Trust-boundary limits and formats `drm_render` (the unprivileged converter) imports: two copies that drift apart would weaken one side.
|
||||
// 16384 covers 8K+ with headroom; anything larger is rejected as a bogus/hostile geometry.
|
||||
@@ -29,9 +30,274 @@ pub struct CursorSnapshot {
|
||||
pub height: u32,
|
||||
pub hotx: i32,
|
||||
pub hoty: i32,
|
||||
/// Whether the hotspot came from the plane's HOTSPOT_X/Y properties. Those exist on
|
||||
/// para-virtualised drivers only; on bare metal it is `infer_hotspot`'s guess, made on the
|
||||
/// bitmap as scanned out - which on a rotated output is the compositor's pre-rotated sprite,
|
||||
/// so the consumer must re-guess on the upright one.
|
||||
pub hot_measured: bool,
|
||||
pub colors: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Fold everything that makes a cursor a DIFFERENT cursor into its id.
|
||||
///
|
||||
/// The producer dedupes by comparing this against the last one it sent, so anything left out is
|
||||
/// something a change in which the consumer will never be told about. Geometry and the hotspot are
|
||||
/// the obvious ones: identical pixels at a new size or hotspot are a new shape.
|
||||
///
|
||||
/// `hot_measured` belongs here too, and that is less obvious. It is not metadata about the cursor,
|
||||
/// it selects what the consumer DOES with it: false means rotate the bitmap and re-infer a
|
||||
/// hotspot, true means map the supplied point. So a sample whose pixels and `(0, 0)` hotspot are
|
||||
/// unchanged but whose provenance flipped is a different cursor as far as the client is concerned,
|
||||
/// and without this it would be deduped away and never sent.
|
||||
fn cursor_id(hash: u64, width: u32, height: u32, hotx: i32, hoty: i32, hot_measured: bool) -> u64 {
|
||||
let mut id = hash;
|
||||
for v in [
|
||||
width as u64,
|
||||
height as u64,
|
||||
hotx as u32 as u64,
|
||||
hoty as u32 as u64,
|
||||
hot_measured as u64,
|
||||
] {
|
||||
id ^= v;
|
||||
id = id.wrapping_mul(1099511628211);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Encodes a provenance answer for the one-shot log below. -1 is "nothing reported yet".
|
||||
fn provenance_code(answered: Option<bool>) -> i8 {
|
||||
match answered {
|
||||
None => 0,
|
||||
Some(false) => 1,
|
||||
Some(true) => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this sample's provenance is worth a log line, given what was last reported.
|
||||
///
|
||||
/// Its own function because the obvious version of this is a line per cursor read, and a cursor is
|
||||
/// read far more often than it changes. A per-sample log here was a real defect in libdrmtap for
|
||||
/// the same reason. So: the first sample of a run, and thereafter only a genuine change of state.
|
||||
fn provenance_is_news(last: i8, now: i8) -> bool {
|
||||
last != now
|
||||
}
|
||||
|
||||
impl DrmReader {
|
||||
/// Say once, and again only if it changes, where the hotspot is coming from. Without this the
|
||||
/// three states are indistinguishable on a running box, which makes the decision unverifiable
|
||||
/// anywhere but a unit test.
|
||||
fn note_hotspot_provenance(&mut self, answered: Option<bool>, hot_measured: bool) {
|
||||
let now = provenance_code(answered);
|
||||
let last = std::mem::replace(&mut self.last_provenance, now);
|
||||
if !provenance_is_news(last, now) {
|
||||
return;
|
||||
}
|
||||
match answered {
|
||||
Some(true) => log::info!(
|
||||
"drm: cursor hotspot provenance: the driver published HOTSPOT_X/Y, using its value"
|
||||
),
|
||||
Some(false) => log::info!(
|
||||
"drm: cursor hotspot provenance: the plane exposes no HOTSPOT_X/Y, inferring the \
|
||||
hotspot from the bitmap"
|
||||
),
|
||||
None => log::info!(
|
||||
"drm: cursor hotspot provenance: unavailable (libdrmtap older than 0.5.6, or a \
|
||||
pre-0.5.6 privileged helper); falling back to the coordinate heuristic, which says \
|
||||
hot_measured={hot_measured}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `hot_x`/`hot_y` are the driver's answer rather than a guess.
|
||||
///
|
||||
/// `answered` is what `drmtap_cursor_hotspot_valid` said: `Some(v)` when it answered, `None` when
|
||||
/// the symbol is absent (a library older than 0.5.6) or it reported that nothing recorded an
|
||||
/// answer for this sample.
|
||||
///
|
||||
/// When it answered, that is the answer, full stop - including `Some(true)` on a `(0, 0)` hotspot,
|
||||
/// which is the whole reason the entry point exists: a para-virtualized driver really can put the
|
||||
/// hotspot at the top-left corner, and the coordinates alone cannot tell that apart from a plane
|
||||
/// that exposes no HOTSPOT_X/Y at all. When it could not answer, fall back to the old test. That
|
||||
/// test is wrong in both directions, but it is what this code did before, and it keeps a deployed
|
||||
/// older `.so` behaving exactly as it used to instead of changing under it.
|
||||
fn hot_measured_from(answered: Option<bool>, hot_x: i32, hot_y: i32) -> bool {
|
||||
match answered {
|
||||
Some(measured) => measured,
|
||||
None => hot_x != 0 || hot_y != 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A mirror has to agree on this many of every 100 pixels of the union to count as symmetry.
|
||||
/// Swept against master over two theme versions: below 86 the rule starts moving shapes whose
|
||||
/// corner guess was already right (`grabbing`), and from 92 up the directional cursors of the
|
||||
/// older theme stop being recognised and regress. 86 to 91 is the interval that holds on both,
|
||||
/// so this sits in the middle of it.
|
||||
const MIRROR_AGREEMENT_PERCENT: u64 = 88;
|
||||
|
||||
/// Guess the click point of a cursor bitmap, for the drivers that publish no hotspot.
|
||||
///
|
||||
/// Three facts drive it, in order of how much of the shape they read.
|
||||
///
|
||||
/// A shape that is mirror symmetric about one of the box's mid-lines has no distinguished end on
|
||||
/// that axis: a crosshair, an I-beam, a two-headed resize arrow. On such an axis the click point
|
||||
/// is the middle.
|
||||
///
|
||||
/// A shape that mirrors onto itself only under a half turn or about a DIAGONAL is a two-headed or
|
||||
/// corner resize cursor. Those are a pointer plus the marker of the edge being resized, and the
|
||||
/// theme puts the click point on that marker, which is the heavier end. The heavier end is also
|
||||
/// the only thing that separates `e-resize` from `w-resize`: they are the same picture reflected.
|
||||
///
|
||||
/// Everything else keeps the top-left corner of the opaque box, because cursors are DRAWN
|
||||
/// pointing up and to the left, so that corner is where an arrow's tip is. That is a fact about
|
||||
/// the sprite in its own upright frame, and the reason this guess is only meaningful when taken
|
||||
/// there rather than on a sprite the compositor pre-rotated.
|
||||
///
|
||||
/// Measured against the hotspots the theme declares, which is the value a compositor programs
|
||||
/// into HOTSPOT_X/Y where the property exists, and against what master delivers over the angles
|
||||
/// master handles (0, 90, 270). adwaita-icon-theme 50 at 24 px: mean error per shape 12.08 px
|
||||
/// down to 4.20, better on 83 of the 105 (shape, angle) cases and worse on 4. The same holds at
|
||||
/// 48 px and on adwaita-icon-theme 46.
|
||||
///
|
||||
/// Two shapes stay further out than master and no bitmap rule reaches them: `help`, whose click
|
||||
/// point the theme puts on the dot of its question mark, and `alias` by half a pixel. That is why
|
||||
/// a hotspot the driver publishes is always preferred to this, and why rustdesk#16122 recovers it
|
||||
/// exactly from the injected pointer instead of guessing.
|
||||
pub fn infer_hotspot(rgba: &[u8], w: usize, h: usize) -> (i32, i32) {
|
||||
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
|
||||
for (i, px) in rgba.chunks_exact(4).take(w * h).enumerate() {
|
||||
if px[3] >= 128 {
|
||||
let (x, y) = ((i % w) as i32, (i / w) as i32);
|
||||
minx = minx.min(x);
|
||||
maxx = maxx.max(x);
|
||||
miny = miny.min(y);
|
||||
maxy = maxy.max(y);
|
||||
}
|
||||
}
|
||||
if maxx < minx || maxy < miny {
|
||||
return (0, 0);
|
||||
}
|
||||
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
|
||||
let (cx, cy) = ((minx + maxx) / 2, (miny + maxy) / 2);
|
||||
// An elongated box keeps its centre whichever way it lies (rustdesk#16242): a bar has no
|
||||
// corner to speak of. Kept ahead of the mirror test so it still covers an elongated shape
|
||||
// that is NOT symmetric, which the theme happens not to contain but a custom cursor can.
|
||||
if bh > bw * 2 || bw > bh * 2 {
|
||||
return (cx, cy);
|
||||
}
|
||||
let opaque = |x: i32, y: i32| {
|
||||
rgba.get((y as usize * w + x as usize) * 4 + 3)
|
||||
.is_some_and(|&a| a >= 128)
|
||||
};
|
||||
let agrees = |i: u64, u: u64| u == 0 || i * 100 >= u * MIRROR_AGREEMENT_PERCENT;
|
||||
// One pass over the opaque box, comparing it with its own three mirrors, and the mass of each
|
||||
// half while we are here.
|
||||
let (mut ix, mut ux) = (0u64, 0u64);
|
||||
let (mut iy, mut uy) = (0u64, 0u64);
|
||||
let (mut ih, mut uh) = (0u64, 0u64);
|
||||
let (mut left, mut right, mut top, mut bottom) = (0u64, 0u64, 0u64, 0u64);
|
||||
let (half_w, half_h) = (bw / 2, bh / 2);
|
||||
for y in miny..=maxy {
|
||||
for x in minx..=maxx {
|
||||
let (fx, fy) = (maxx - (x - minx), maxy - (y - miny));
|
||||
let here = opaque(x, y);
|
||||
for (other, (i, u)) in [
|
||||
(opaque(fx, y), (&mut ix, &mut ux)),
|
||||
(opaque(x, fy), (&mut iy, &mut uy)),
|
||||
(opaque(fx, fy), (&mut ih, &mut uh)),
|
||||
] {
|
||||
*i += u64::from(here && other);
|
||||
*u += u64::from(here || other);
|
||||
}
|
||||
if here {
|
||||
if x - minx < half_w {
|
||||
left += 1;
|
||||
} else if maxx - x < half_w {
|
||||
right += 1;
|
||||
}
|
||||
if y - miny < half_h {
|
||||
top += 1;
|
||||
} else if maxy - y < half_h {
|
||||
bottom += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Symmetric under a half turn and the centre is the only point the shape cannot tell from
|
||||
// itself, whichever the per-axis answers are: a two-headed diagonal arrow mirrors to the
|
||||
// other diagonal on each axis alone, so neither axis reads as symmetric.
|
||||
if agrees(ih, uh) {
|
||||
return (cx, cy);
|
||||
}
|
||||
let diagonal = mirrors_about_a_diagonal(&opaque, minx, miny, bw, bh, &agrees);
|
||||
// An axis is DIRECTIONAL when the shape is a pointer plus an edge marker rather than a plain
|
||||
// arrow: the perpendicular axis mirrors (the n/e/s/w resize cursors), or the shape mirrors
|
||||
// about a diagonal (the corner ones). The marker is the end the click point belongs to, and
|
||||
// it is the heavier end, which is the only thing that tells `e-resize` from `w-resize` - they
|
||||
// are the same picture reflected. Everything else keeps the up-left corner.
|
||||
let side = |heavier_is_max: bool, lo: i32, hi: i32| if heavier_is_max { hi } else { lo };
|
||||
(
|
||||
if agrees(ix, ux) {
|
||||
cx
|
||||
} else if agrees(iy, uy) || diagonal {
|
||||
side(right > left, minx, maxx)
|
||||
} else {
|
||||
minx
|
||||
},
|
||||
if agrees(iy, uy) {
|
||||
cy
|
||||
} else if agrees(ix, ux) || diagonal {
|
||||
side(bottom > top, miny, maxy)
|
||||
} else {
|
||||
miny
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the opaque box mirrors onto itself about either of its diagonals.
|
||||
///
|
||||
/// A diagonal reflection of a `bw x bh` box is a `bh x bw` box, so the two can only be compared
|
||||
/// inside a square, and where the box is not square the answer depends on where in that square it
|
||||
/// is placed: the corner resize cursors are drawn against one corner, and padding away from that
|
||||
/// corner moves the shape off the diagonal it is symmetric about. `ne-resize` scores 0.62 anchored
|
||||
/// top-left and 0.98 anchored bottom-right; `nw-resize` is the other way round. So both anchorings
|
||||
/// are tried and the best answer wins, which is what "the shape is symmetric" means once the
|
||||
/// reflection is allowed to be shifted back into place.
|
||||
fn mirrors_about_a_diagonal(
|
||||
opaque: &impl Fn(i32, i32) -> bool,
|
||||
minx: i32,
|
||||
miny: i32,
|
||||
bw: i32,
|
||||
bh: i32,
|
||||
agrees: &impl Fn(u64, u64) -> bool,
|
||||
) -> bool {
|
||||
let k = bw.max(bh);
|
||||
for (dx, dy) in [(0, 0), (k - bw, k - bh)] {
|
||||
// The box placed at (dx, dy) inside a k x k square, empty everywhere else.
|
||||
let cell = |r: i32, c: i32| {
|
||||
let (x, y) = (c - dx, r - dy);
|
||||
(0..bw).contains(&x) && (0..bh).contains(&y) && opaque(minx + x, miny + y)
|
||||
};
|
||||
let (mut id, mut ud, mut ia, mut ua) = (0u64, 0u64, 0u64, 0u64);
|
||||
for r in 0..k {
|
||||
for c in 0..k {
|
||||
let here = cell(r, c);
|
||||
for (other, (i, u)) in [
|
||||
(cell(c, r), (&mut id, &mut ud)),
|
||||
(cell(k - 1 - c, k - 1 - r), (&mut ia, &mut ua)),
|
||||
] {
|
||||
*i += u64::from(here && other);
|
||||
*u += u64::from(here || other);
|
||||
}
|
||||
}
|
||||
}
|
||||
if agrees(id, ud) || agrees(ia, ua) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// One enumerated DRM display, physical geometry only (the server overlays the Wayland logical origin/scale where it can match one).
|
||||
pub struct DisplaySnapshot {
|
||||
pub name: String,
|
||||
@@ -101,6 +367,13 @@ pub struct DrmReader {
|
||||
lib: &'static DrmtapLib,
|
||||
ctx: *mut drmtap_ctx,
|
||||
buf: Vec<u8>,
|
||||
/// Last provenance reported by THIS reader, for the one-shot log. Per reader and not global:
|
||||
/// several readers run at once, one per captured display, and their provenance can legitimately
|
||||
/// differ and be stable -- a virtio-gpu output publishes HOTSPOT_X/Y while an i915 one on the
|
||||
/// same host does not. A single global would read those two steady streams as an endless
|
||||
/// alternation and log on every sample, which is the per-frame logging this was written to
|
||||
/// avoid. -1 is "nothing reported yet".
|
||||
last_provenance: i8,
|
||||
}
|
||||
|
||||
impl DrmReader {
|
||||
@@ -134,6 +407,7 @@ impl DrmReader {
|
||||
return None;
|
||||
}
|
||||
Some(DrmReader {
|
||||
last_provenance: -1,
|
||||
lib,
|
||||
ctx,
|
||||
buf: Vec::new(),
|
||||
@@ -363,6 +637,7 @@ impl DrmReader {
|
||||
height: 1,
|
||||
hotx: 0,
|
||||
hoty: 0,
|
||||
hot_measured: false,
|
||||
colors: vec![0, 0, 0, 0],
|
||||
})
|
||||
} else if !c.pixels.is_null()
|
||||
@@ -376,53 +651,45 @@ impl DrmReader {
|
||||
let src = std::slice::from_raw_parts(c.pixels, n);
|
||||
let mut hash: u64 = 1469598103934665603;
|
||||
let mut colors = Vec::with_capacity(n * 4);
|
||||
let (mut minx, mut miny, mut maxx, mut maxy) = (cw, ch, -1i32, -1i32);
|
||||
for (i, &p) in src.iter().enumerate() {
|
||||
let a = ((p >> 24) & 0xff) as u8;
|
||||
let r = ((p >> 16) & 0xff) as u8;
|
||||
let g = ((p >> 8) & 0xff) as u8;
|
||||
let b = (p & 0xff) as u8;
|
||||
colors.push(r);
|
||||
colors.push(g);
|
||||
colors.push(b);
|
||||
colors.push(a);
|
||||
for &p in src.iter() {
|
||||
colors.push(((p >> 16) & 0xff) as u8);
|
||||
colors.push(((p >> 8) & 0xff) as u8);
|
||||
colors.push((p & 0xff) as u8);
|
||||
colors.push(((p >> 24) & 0xff) as u8);
|
||||
hash ^= p as u64;
|
||||
hash = hash.wrapping_mul(1099511628211);
|
||||
if a >= 128 {
|
||||
let x = (i as i32) % cw;
|
||||
let y = (i as i32) / cw;
|
||||
if x < minx { minx = x; }
|
||||
if x > maxx { maxx = x; }
|
||||
if y < miny { miny = y; }
|
||||
if y > maxy { maxy = y; }
|
||||
}
|
||||
}
|
||||
let (hotx, hoty) = if c.hot_x != 0 || c.hot_y != 0 {
|
||||
// Ask the library where the hotspot came from instead of guessing from the
|
||||
// coordinates. `hot_x/hot_y == (0, 0)` means two opposite things - the plane
|
||||
// exposes no HOTSPOT_X/Y (every bare-metal driver), or it exposes them and the
|
||||
// driver's answer IS the top-left corner - and the old test below cannot separate
|
||||
// them: it overrides a real (0, 0) measurement with a guess from the bitmap, and
|
||||
// on a driver without the properties it would trust a hotspot nobody published.
|
||||
// Asked BEFORE cursor_release, which is what owns this sample.
|
||||
let answered = self.lib.cursor_hotspot_valid.and_then(|f| {
|
||||
let mut valid: c_int = 0;
|
||||
// 0 = answered; -ENOTSUP = nothing recorded an answer for this sample, which
|
||||
// is what a cursor read through a pre-0.5.6 privileged helper produces.
|
||||
(f(&c, &mut valid) == 0).then(|| valid != 0)
|
||||
});
|
||||
let hot_measured = hot_measured_from(answered, c.hot_x, c.hot_y);
|
||||
self.note_hotspot_provenance(answered, hot_measured);
|
||||
let (hotx, hoty) = if hot_measured {
|
||||
(c.hot_x, c.hot_y)
|
||||
} else if maxx >= minx && maxy >= miny {
|
||||
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
|
||||
if bh > bw * 2 {
|
||||
((minx + maxx) / 2, (miny + maxy) / 2)
|
||||
} else {
|
||||
(minx, miny)
|
||||
}
|
||||
} else {
|
||||
(0, 0)
|
||||
infer_hotspot(&colors, cw as usize, ch as usize)
|
||||
};
|
||||
// Fold geometry + hotspot into the id: identical pixels with a changed size or
|
||||
// hotspot must count as a new shape, otherwise drm_capture_worker suppresses the
|
||||
// update (it dedupes by id) and the client keeps rendering the stale cursor.
|
||||
let mut id = hash;
|
||||
for v in [cw as u32 as u64, ch as u32 as u64, hotx as u32 as u64, hoty as u32 as u64] {
|
||||
id ^= v;
|
||||
id = id.wrapping_mul(1099511628211);
|
||||
}
|
||||
let id = cursor_id(hash, cw as u32, ch as u32, hotx, hoty, hot_measured);
|
||||
Some(CursorSnapshot {
|
||||
id,
|
||||
width: cw as u32,
|
||||
height: ch as u32,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
colors,
|
||||
})
|
||||
} else {
|
||||
@@ -475,3 +742,239 @@ impl Drop for DrmReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hotspot_provenance_tests {
|
||||
use super::{cursor_id, hot_measured_from, provenance_code, provenance_is_news};
|
||||
|
||||
/// The log this makes observable is one line per CHANGE, not one per cursor read. A cursor is
|
||||
/// read far more often than its provenance changes, and a per-sample line here would be the
|
||||
/// same defect libdrmtap already had once.
|
||||
#[test]
|
||||
fn provenance_is_logged_once_and_then_only_on_a_change() {
|
||||
let (none, guessed, measured) = (
|
||||
provenance_code(None),
|
||||
provenance_code(Some(false)),
|
||||
provenance_code(Some(true)),
|
||||
);
|
||||
assert_ne!(none, guessed);
|
||||
assert_ne!(guessed, measured);
|
||||
assert_ne!(none, measured);
|
||||
// First sample of a run: -1 is the unset sentinel, so anything is news.
|
||||
assert!(provenance_is_news(-1, measured));
|
||||
// The same state again is not.
|
||||
assert!(!provenance_is_news(measured, measured));
|
||||
assert!(!provenance_is_news(guessed, guessed));
|
||||
// A real transition is.
|
||||
assert!(provenance_is_news(guessed, measured));
|
||||
assert!(provenance_is_news(measured, none));
|
||||
}
|
||||
|
||||
/// The dedup key has to move when the provenance does, or the consumer is never told that the
|
||||
/// same picture now means something different. This is the transition that produces it: the
|
||||
/// properties become readable, the driver's answer is the corner, and the bitmap is unchanged.
|
||||
#[test]
|
||||
fn provenance_changes_the_cursor_identity() {
|
||||
let guessed = cursor_id(0xabc, 24, 24, 0, 0, false);
|
||||
let measured = cursor_id(0xabc, 24, 24, 0, 0, true);
|
||||
assert_ne!(
|
||||
guessed, measured,
|
||||
"same pixels, same (0, 0), different meaning: the producer must not dedupe this away"
|
||||
);
|
||||
// And the pre-existing parts still count, so this did not trade one blind spot for another.
|
||||
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 32, 24, 0, 0, true));
|
||||
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 24, 24, 1, 0, true));
|
||||
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xdef, 24, 24, 0, 0, true));
|
||||
}
|
||||
|
||||
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
|
||||
/// para-virtualized driver that really publishes the hotspot at the image's top-left corner.
|
||||
/// `(0, 0)` measured is still measured, and re-inferring one from the bitmap would move a
|
||||
/// cursor the driver had already placed.
|
||||
#[test]
|
||||
fn a_measured_zero_hotspot_is_measured() {
|
||||
assert!(hot_measured_from(Some(true), 0, 0));
|
||||
}
|
||||
|
||||
/// And the mirror: when the library says it was NOT measured, that is the answer even if the
|
||||
/// coordinates happen to be non-zero. The old test would have trusted them.
|
||||
#[test]
|
||||
fn the_librarys_no_beats_the_coordinates() {
|
||||
assert!(!hot_measured_from(Some(false), 12, 11));
|
||||
assert!(!hot_measured_from(Some(false), 0, 0));
|
||||
}
|
||||
|
||||
/// No answer available: either the symbol is absent (a library older than 0.5.6) or nothing
|
||||
/// recorded one for this sample (a cursor read through an older privileged helper). Neither
|
||||
/// is "it was a guess", so the pre-existing behaviour is kept rather than resolved either way
|
||||
/// -- an older deployed .so must keep behaving as it used to.
|
||||
#[test]
|
||||
fn without_an_answer_the_old_heuristic_stands() {
|
||||
assert!(!hot_measured_from(None, 0, 0));
|
||||
assert!(hot_measured_from(None, 12, 11));
|
||||
assert!(hot_measured_from(None, 0, 5));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hotspot_guess_tests {
|
||||
use super::infer_hotspot;
|
||||
|
||||
/// A sprite from an ASCII picture: `#` is opaque, anything else transparent. Written this way
|
||||
/// because every case here is about a SHAPE, and a shape is unreadable as a byte array.
|
||||
fn sprite(rows: &[&str]) -> (Vec<u8>, usize, usize) {
|
||||
let (h, w) = (rows.len(), rows[0].len());
|
||||
let mut px = vec![0u8; w * h * 4];
|
||||
for (y, row) in rows.iter().enumerate() {
|
||||
assert_eq!(row.len(), w, "ragged picture");
|
||||
for (x, c) in row.bytes().enumerate() {
|
||||
if c == b'#' {
|
||||
px[(y * w + x) * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
(px, w, h)
|
||||
}
|
||||
|
||||
/// An arrow keeps the top-left corner of its box. Cursors are drawn pointing up and left, so
|
||||
/// that corner IS the tip - and it is a fact about the sprite upright, which is why the
|
||||
/// consumer re-takes this guess after turning a rotated sprite back.
|
||||
#[test]
|
||||
fn an_arrow_points_at_the_corner_of_its_box() {
|
||||
let (px, w, h) = sprite(&[
|
||||
".........",
|
||||
".#.......",
|
||||
".##......",
|
||||
".###.....",
|
||||
".####....",
|
||||
".#####...",
|
||||
".###.....",
|
||||
".#..##...",
|
||||
"......##.",
|
||||
]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (1, 1));
|
||||
}
|
||||
|
||||
/// A shape that mirrors onto itself about the box's mid-lines has no tip to point with, so
|
||||
/// the corner names nothing and the middle is the only answer the shape supports. This is the
|
||||
/// crosshair/cell/resize family, 17 of the installed theme's 35 shapes.
|
||||
#[test]
|
||||
fn a_symmetric_shape_is_held_by_its_middle() {
|
||||
let (px, w, h) = sprite(&[
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"#########",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (4, 4));
|
||||
}
|
||||
|
||||
/// Each axis is decided by its OWN mirror. This shape is symmetric left-to-right and not
|
||||
/// top-to-bottom, which is the single-direction resize family: the click point is centred
|
||||
/// across the axis that mirrors and stays at the edge on the axis that does not.
|
||||
#[test]
|
||||
fn one_symmetric_axis_centres_that_axis_only() {
|
||||
let (px, w, h) = sprite(&[
|
||||
"....#....",
|
||||
"...###...",
|
||||
"..#####..",
|
||||
".#######.",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
"....#....",
|
||||
]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (4, 0));
|
||||
}
|
||||
|
||||
/// A two-headed DIAGONAL arrow mirrors onto the other diagonal about either axis alone, so
|
||||
/// neither axis reads as symmetric - and it is still a shape with no tip. The half turn is
|
||||
/// what catches it.
|
||||
#[test]
|
||||
fn a_diagonal_two_headed_arrow_is_held_by_its_middle_too() {
|
||||
let (px, w, h) = sprite(&[
|
||||
"###......",
|
||||
"##.......",
|
||||
"#.#......",
|
||||
"...#.....",
|
||||
"....#....",
|
||||
".....#...",
|
||||
"......#.#",
|
||||
".......##",
|
||||
"......###",
|
||||
]);
|
||||
let (hx, hy) = infer_hotspot(&px, w, h);
|
||||
assert_eq!((hx, hy), (4, 4), "a half turn maps this shape onto itself");
|
||||
}
|
||||
|
||||
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
|
||||
/// theme puts the click point on the BAR. The bar is the heavy end, and it is the only thing
|
||||
/// that separates `e-resize` from `w-resize`: they are the same picture reflected, so a rule
|
||||
/// that always took the up-left corner had to be wrong for one of the two.
|
||||
#[test]
|
||||
fn a_directional_resize_cursor_is_held_by_its_bar() {
|
||||
let (px, w, h) = sprite(&[
|
||||
"......####",
|
||||
"..##..####",
|
||||
".###..####",
|
||||
"####..####",
|
||||
".###..####",
|
||||
"..##..####",
|
||||
"......####",
|
||||
]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (9, 3));
|
||||
// The mirror image has to answer the other side, or the rule is not reading the shape.
|
||||
let (px, w, h) = sprite(&[
|
||||
"####......",
|
||||
"####..##..",
|
||||
"####..###.",
|
||||
"####..####",
|
||||
"####..###.",
|
||||
"####..##..",
|
||||
"####......",
|
||||
]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (0, 3));
|
||||
}
|
||||
|
||||
/// A corner resize cursor is a bracket hugging one corner, and it mirrors onto itself about a
|
||||
/// DIAGONAL rather than about either axis, so neither per-axis test sees it. The click point
|
||||
/// is the inner corner of the bracket, which is the heavy end on both axes.
|
||||
///
|
||||
/// A real one's box is usually not square, and a diagonal reflection only lines up inside a
|
||||
/// square, so which corner of that square the box is placed against decides the answer:
|
||||
/// `ne-resize` scores 0.62 anchored one way and 0.98 the other, and `nw-resize` is the
|
||||
/// reverse. Both anchorings are therefore tried. That case cannot be built as a small
|
||||
/// picture - a non-square box can never be exactly diagonal-symmetric - so it is covered by
|
||||
/// the theme corpus instead, where dropping the second anchoring sends `ne-resize` back past
|
||||
/// master.
|
||||
#[test]
|
||||
fn a_corner_bracket_is_held_by_its_inner_corner() {
|
||||
let (px, w, h) = sprite(&[
|
||||
".....##", ".....##", ".....##", ".....##", ".....##", "#######", "#######",
|
||||
]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (6, 6));
|
||||
}
|
||||
|
||||
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
|
||||
/// keeps its centre. Nothing in the installed theme is shaped like this - its two I-beams are
|
||||
/// both symmetric - but a custom cursor can be, and this is the rustdesk#16242 round-one fix.
|
||||
#[test]
|
||||
fn an_elongated_shape_keeps_its_centre_even_when_it_is_lopsided() {
|
||||
let (px, w, h) = sprite(&["##########.", "#####......", "##########."]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (4, 1));
|
||||
}
|
||||
|
||||
/// Nothing opaque is not a shape, and must not read as a box at the origin with a hotspot in
|
||||
/// the middle of it.
|
||||
#[test]
|
||||
fn a_blank_sprite_has_no_hotspot_to_guess() {
|
||||
let (px, w, h) = sprite(&["...", "...", "..."]);
|
||||
assert_eq!(infer_hotspot(&px, w, h), (0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,12 @@ type FnGrabMapped = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_frame_info
|
||||
type FnFrameRelease = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_frame_info);
|
||||
type FnGetCursor = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_cursor_info) -> c_int;
|
||||
type FnCursorRelease = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_cursor_info);
|
||||
/// `drmtap_cursor_hotspot_valid`, added in libdrmtap 0.5.6. Answers, for the sample in hand,
|
||||
/// whether `hot_x`/`hot_y` were read from the driver's HOTSPOT_X/Y plane properties: 0 with
|
||||
/// `*valid` set, `-EINVAL` on a null argument, and `-ENOTSUP` when nothing recorded an answer,
|
||||
/// which is what a cursor read through an older privileged helper produces.
|
||||
type FnCursorHotspotValid =
|
||||
unsafe extern "C" fn(*const drmtap_cursor_info, *mut c_int) -> c_int;
|
||||
// Split-capture entry points (libdrmtap >= 0.4.10), required: `grab_desc` runs on the privileged
|
||||
// export side, `open_render`/`convert_dmabuf` on the unprivileged converter side.
|
||||
type FnGrabDesc =
|
||||
@@ -148,6 +154,10 @@ pub struct DrmtapLib {
|
||||
pub frame_release: FnFrameRelease,
|
||||
pub get_cursor: FnGetCursor,
|
||||
pub cursor_release: FnCursorRelease,
|
||||
/// Optional: it only exists from libdrmtap 0.5.6. Absent means the library cannot say where a
|
||||
/// hotspot came from, NOT that it was a guess; `drm_reader` keeps the old heuristic for that
|
||||
/// case and nothing else changes.
|
||||
pub cursor_hotspot_valid: Option<FnCursorHotspotValid>,
|
||||
pub grab_desc: FnGrabDesc,
|
||||
pub open_render: FnOpenRender,
|
||||
pub convert_dmabuf: FnConvertDmabuf,
|
||||
@@ -278,6 +288,8 @@ impl DrmtapLib {
|
||||
};
|
||||
let render_node: Option<FnRenderNode> =
|
||||
lib.get(b"drmtap_render_node").ok().map(|s| *s);
|
||||
let cursor_hotspot_valid: Option<FnCursorHotspotValid> =
|
||||
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
|
||||
// Log the load only now that every required symbol resolved: this fn still returns None on a missing one.
|
||||
let loaded_from = real
|
||||
.as_ref()
|
||||
@@ -309,6 +321,18 @@ impl DrmtapLib {
|
||||
points at and remove any leftover libdrmtap.so.0* beside it. {effect}"
|
||||
);
|
||||
}
|
||||
// Same shape as the check above, and for the same reason: a library that REPORTS a
|
||||
// version which exports the symbol and then does not have it is a stale or
|
||||
// hand-substituted object, and saying so beats silently taking the legacy path.
|
||||
if (minor, patch) >= (5, 6) && cursor_hotspot_valid.is_none() {
|
||||
log::warn!(
|
||||
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
|
||||
drmtap_cursor_hotspot_valid: it is a stale or pre-release build. Check what \
|
||||
the soname symlink points at. Cursor hotspot provenance falls back to \
|
||||
guessing from the coordinates, which cannot tell an absent HOTSPOT_X/Y from \
|
||||
a driver that really puts the hotspot at (0, 0)."
|
||||
);
|
||||
}
|
||||
Some(DrmtapLib {
|
||||
_lib: lib,
|
||||
open,
|
||||
@@ -319,6 +343,7 @@ impl DrmtapLib {
|
||||
frame_release,
|
||||
get_cursor,
|
||||
cursor_release,
|
||||
cursor_hotspot_valid,
|
||||
grab_desc,
|
||||
open_render,
|
||||
convert_dmabuf,
|
||||
|
||||
@@ -118,12 +118,15 @@ impl EncoderApi for VRamEncoder {
|
||||
});
|
||||
}
|
||||
if frames.len() > 0 {
|
||||
// This kind of problem is occurred after a period of time when using AMD encoding,
|
||||
// This kind of problem is occurred after a period of time when using the AMD SDK,
|
||||
// the encoding length is fixed at about 40, and the picture is still
|
||||
const MIN_BAD_LEN: usize = 100;
|
||||
const MAX_BAD_COUNTER: usize = 30;
|
||||
let this_frame_len = frames[0].data.len();
|
||||
if this_frame_len < MIN_BAD_LEN && this_frame_len == self.last_frame_len {
|
||||
if self.ctx.f.driver == Driver::AMF
|
||||
&& this_frame_len < MIN_BAD_LEN
|
||||
&& this_frame_len == self.last_frame_len
|
||||
{
|
||||
self.same_bad_len_counter += 1;
|
||||
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
|
||||
log::info!(
|
||||
|
||||
@@ -0,0 +1,629 @@
|
||||
//! HDR desktop -> SDR normalization for Desktop Duplication frames.
|
||||
//!
|
||||
//! With HDR enabled Windows composes the desktop as linear scRGB in
|
||||
//! R16G16B16A16_FLOAT, and SDR "white" sits at the user's SDR content
|
||||
//! brightness (DISPLAYCONFIG_SDR_WHITE_LEVEL) rather than at 1.0. The legacy
|
||||
//! DuplicateOutput converts that to BGRA8 by clipping, which is the washed-out
|
||||
//! picture reported for HDR hosts. This pass divides by the SDR white level,
|
||||
//! clamps, and applies the sRGB transfer, so SDR content comes out exactly as
|
||||
//! it would from an SDR desktop.
|
||||
//!
|
||||
//! It is a normalization, not a tone map: anything brighter than SDR white
|
||||
//! (HDR video, HDR games) clips to white on the SDR viewer, where the local
|
||||
//! HDR display would show it brighter than white. A roll-off would have to
|
||||
//! move SDR white below 1.0 to make headroom, trading the accuracy of the SDR
|
||||
//! content this pass exists for, so it is deliberately not done.
|
||||
//!
|
||||
//! Windows 11 22H2 also composes Advanced Color SDR (WCG) desktops in FP16,
|
||||
//! but there 1.0 is the display's reference white rather than 80 nits and no
|
||||
//! SDR white level applies. IDXGIOutput6 tells the two apart, and for a
|
||||
//! non-HDR output the pass only applies the scRGB -> sRGB transfer.
|
||||
//!
|
||||
//! The conversion is automatic and stays on the controlled side on purpose:
|
||||
//! the controller renders through Flutter external textures, which are 8-bit
|
||||
//! on every desktop platform, so there is nothing to gain from sending HDR.
|
||||
//! Real HDR pass-through, if the renderer ever supports it, should follow the
|
||||
//! Sunshine/Moonlight pattern instead: an `hdr` capability bit advertised by
|
||||
//! the controller behind an explicit user toggle, negotiated like i444.
|
||||
|
||||
use super::ComPtr;
|
||||
use hbb_common::log;
|
||||
use std::{
|
||||
io, mem, ptr,
|
||||
sync::{atomic::AtomicBool, OnceLock},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use winapi::{
|
||||
ctypes::c_void,
|
||||
shared::{
|
||||
basetsd::SIZE_T,
|
||||
dxgi::{CreateDXGIFactory1, IDXGIFactory1, IID_IDXGIFactory1, DXGI_OUTPUT_DESC},
|
||||
dxgi1_2::IDXGIOutput1,
|
||||
dxgi1_6::{IDXGIOutput6, IID_IDXGIOutput6, DXGI_OUTPUT_DESC1},
|
||||
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
dxgitype::{DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_SAMPLE_DESC},
|
||||
minwindef::{FALSE, LPCVOID, UINT, ULONG},
|
||||
ntdef::{LONG, LPCSTR, WCHAR},
|
||||
winerror::S_OK,
|
||||
},
|
||||
um::{
|
||||
d3d11::*,
|
||||
d3dcommon::{ID3DBlob, ID3DInclude, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D_SHADER_MACRO},
|
||||
libloaderapi::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32},
|
||||
unknwnbase::IUnknown,
|
||||
wingdi::{
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
|
||||
DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
|
||||
DISPLAYCONFIG_TOPOLOGY_ID,
|
||||
},
|
||||
winnt::HRESULT,
|
||||
},
|
||||
};
|
||||
|
||||
/// Set once the tone-map can never work in this process (no d3dcompiler, the
|
||||
/// shaders do not compile). Capturers then stop asking DXGI for float frames.
|
||||
/// Device-specific failures are not recorded here; the capturer that hit one
|
||||
/// re-duplicates without the tone-map on its own.
|
||||
pub static UNAVAILABLE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Failures no capturer on this machine can recover from, as opposed to
|
||||
/// device-specific ones that a recreated capturer may not hit again.
|
||||
pub fn is_permanent(err: &io::Error) -> bool {
|
||||
err.kind() == io::ErrorKind::Unsupported
|
||||
}
|
||||
|
||||
const VS_SRC: &str = "\
|
||||
float4 main(uint id : SV_VertexID) : SV_Position {
|
||||
float2 uv = float2((id << 1) & 2, id & 2);
|
||||
return float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);
|
||||
}";
|
||||
|
||||
const PS_SRC: &str = "\
|
||||
Texture2D<float4> src : register(t0);
|
||||
cbuffer Params : register(b0) { float inv_sdr_white; float3 pad; };
|
||||
float4 main(float4 pos : SV_Position) : SV_Target {
|
||||
float3 lin = saturate(src.Load(int3(pos.xy, 0)).rgb * inv_sdr_white);
|
||||
float3 lo = lin * 12.92;
|
||||
float3 hi = 1.055 * pow(lin, 1.0 / 2.4) - 0.055;
|
||||
return float4(lerp(hi, lo, step(lin, 0.0031308)), 1.0);
|
||||
}";
|
||||
|
||||
const OUTPUT_STATE_REFRESH: Duration = Duration::from_secs(1);
|
||||
|
||||
pub struct HdrToSdr {
|
||||
device: ComPtr<ID3D11Device>,
|
||||
context: ComPtr<ID3D11DeviceContext>,
|
||||
vs: ComPtr<ID3D11VertexShader>,
|
||||
ps: ComPtr<ID3D11PixelShader>,
|
||||
params: ComPtr<ID3D11Buffer>,
|
||||
target: ComPtr<ID3D11Texture2D>,
|
||||
rtv: ComPtr<ID3D11RenderTargetView>,
|
||||
srv: ComPtr<ID3D11ShaderResourceView>,
|
||||
// Texture `srv` was created for. The view keeps it alive, so the address
|
||||
// cannot be recycled behind our back.
|
||||
srv_source: *mut ID3D11Texture2D,
|
||||
width: u32,
|
||||
height: u32,
|
||||
device_name: [WCHAR; 32],
|
||||
// Advanced Color state is read from `output6`, which is re-enumerated from a
|
||||
// fresh factory whenever `factory` stops being current.
|
||||
factory: ComPtr<IDXGIFactory1>,
|
||||
output6: ComPtr<IDXGIOutput6>,
|
||||
is_hdr: bool,
|
||||
// DISPLAYCONFIG units (1000 == 80 nits == scRGB 1.0). `None` when it could
|
||||
// not be read, in which case 80 nits is assumed until it can.
|
||||
sdr_white_level: Option<u32>,
|
||||
queried_at: Instant,
|
||||
}
|
||||
|
||||
impl HdrToSdr {
|
||||
pub fn new(
|
||||
device: *mut ID3D11Device,
|
||||
context: *mut ID3D11DeviceContext,
|
||||
output: *mut IDXGIOutput1,
|
||||
device_name: &[WCHAR; 32],
|
||||
) -> io::Result<Self> {
|
||||
unsafe {
|
||||
if device.is_null() || context.is_null() {
|
||||
return Err(other("no d3d11 device"));
|
||||
}
|
||||
(*device).AddRef();
|
||||
let device = ComPtr(device);
|
||||
(*context).AddRef();
|
||||
let context = ComPtr(context);
|
||||
|
||||
let compile = load_d3d_compile()?;
|
||||
let vs_code = compile_shader(compile, VS_SRC, b"vs_4_0\0")?;
|
||||
let ps_code = compile_shader(compile, PS_SRC, b"ps_4_0\0")?;
|
||||
let mut vs = ptr::null_mut();
|
||||
check(
|
||||
(*device.0).CreateVertexShader(
|
||||
(*vs_code.0).GetBufferPointer(),
|
||||
(*vs_code.0).GetBufferSize(),
|
||||
ptr::null_mut(),
|
||||
&mut vs,
|
||||
),
|
||||
"CreateVertexShader",
|
||||
)?;
|
||||
let vs = ComPtr(vs);
|
||||
let mut ps = ptr::null_mut();
|
||||
check(
|
||||
(*device.0).CreatePixelShader(
|
||||
(*ps_code.0).GetBufferPointer(),
|
||||
(*ps_code.0).GetBufferSize(),
|
||||
ptr::null_mut(),
|
||||
&mut ps,
|
||||
),
|
||||
"CreatePixelShader",
|
||||
)?;
|
||||
let ps = ComPtr(ps);
|
||||
|
||||
// Not found leaves the factory null, so the first refresh enumerates
|
||||
// again instead of trusting the capturer's possibly stale output.
|
||||
let (factory, mut output6) = enumerate_output6(device_name);
|
||||
if output6.is_null() {
|
||||
output6 = query_output6(output as *mut IUnknown);
|
||||
}
|
||||
// Float frames are only requested where IDXGIOutput6 exists, so an
|
||||
// unreadable description still comes from an HDR-capable stack.
|
||||
let is_hdr = output_is_hdr(output6.0).unwrap_or(true);
|
||||
let sdr_white_level = if is_hdr {
|
||||
query_sdr_white_level(device_name)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if is_hdr && sdr_white_level.is_none() {
|
||||
log::warn!(
|
||||
"HDR output but the SDR white level cannot be read (needs Windows 10 1709+), \
|
||||
assuming 80 nits until it can"
|
||||
);
|
||||
}
|
||||
let init = params_data(sdr_white_level);
|
||||
let desc = D3D11_BUFFER_DESC {
|
||||
ByteWidth: mem::size_of_val(&init) as _,
|
||||
Usage: D3D11_USAGE_DEFAULT,
|
||||
BindFlags: D3D11_BIND_CONSTANT_BUFFER,
|
||||
CPUAccessFlags: 0,
|
||||
MiscFlags: 0,
|
||||
StructureByteStride: 0,
|
||||
};
|
||||
let data = D3D11_SUBRESOURCE_DATA {
|
||||
pSysMem: init.as_ptr() as _,
|
||||
SysMemPitch: 0,
|
||||
SysMemSlicePitch: 0,
|
||||
};
|
||||
let mut params = ptr::null_mut();
|
||||
check(
|
||||
(*device.0).CreateBuffer(&desc, &data, &mut params),
|
||||
"CreateBuffer",
|
||||
)?;
|
||||
let params = ComPtr(params);
|
||||
log::info!(
|
||||
"scRGB desktop conversion ready, hdr {is_hdr}, sdr white level {sdr_white_level:?}"
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
device,
|
||||
context,
|
||||
vs,
|
||||
ps,
|
||||
params,
|
||||
target: ComPtr(ptr::null_mut()),
|
||||
rtv: ComPtr(ptr::null_mut()),
|
||||
srv: ComPtr(ptr::null_mut()),
|
||||
srv_source: ptr::null_mut(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
device_name: *device_name,
|
||||
factory,
|
||||
output6,
|
||||
is_hdr,
|
||||
sdr_white_level,
|
||||
queried_at: Instant::now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders `source` (R16G16B16A16_FLOAT) into an owned B8G8R8A8_UNORM
|
||||
/// texture of the same size and returns it. The texture stays valid until
|
||||
/// the next call.
|
||||
pub fn convert(
|
||||
&mut self,
|
||||
source: *mut ID3D11Texture2D,
|
||||
desc: &D3D11_TEXTURE2D_DESC,
|
||||
) -> io::Result<*mut ID3D11Texture2D> {
|
||||
unsafe {
|
||||
self.refresh_output_state();
|
||||
self.ensure_target(desc.Width, desc.Height)?;
|
||||
self.ensure_source_view(source)?;
|
||||
|
||||
let ctx = self.context.0;
|
||||
let rtv = self.rtv.0;
|
||||
let srv = self.srv.0;
|
||||
let params = self.params.0;
|
||||
let viewport = D3D11_VIEWPORT {
|
||||
TopLeftX: 0.0,
|
||||
TopLeftY: 0.0,
|
||||
Width: self.width as f32,
|
||||
Height: self.height as f32,
|
||||
MinDepth: 0.0,
|
||||
MaxDepth: 1.0,
|
||||
};
|
||||
(*ctx).OMSetRenderTargets(1, &rtv, ptr::null_mut());
|
||||
(*ctx).OMSetBlendState(ptr::null_mut(), &[0.0; 4], 0xffff_ffff);
|
||||
(*ctx).OMSetDepthStencilState(ptr::null_mut(), 0);
|
||||
(*ctx).RSSetState(ptr::null_mut());
|
||||
(*ctx).RSSetViewports(1, &viewport);
|
||||
(*ctx).IASetInputLayout(ptr::null_mut());
|
||||
(*ctx).IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||
(*ctx).VSSetShader(self.vs.0, ptr::null(), 0);
|
||||
(*ctx).PSSetShader(self.ps.0, ptr::null(), 0);
|
||||
(*ctx).PSSetConstantBuffers(0, 1, ¶ms);
|
||||
(*ctx).PSSetShaderResources(0, 1, &srv);
|
||||
(*ctx).Draw(3, 0);
|
||||
// Unbind so the next frame's copy and the encoder never see the
|
||||
// target as a live render target or the desktop image as a bound
|
||||
// shader input.
|
||||
let no_srv: *mut ID3D11ShaderResourceView = ptr::null_mut();
|
||||
(*ctx).PSSetShaderResources(0, 1, &no_srv);
|
||||
(*ctx).OMSetRenderTargets(0, ptr::null(), ptr::null_mut());
|
||||
Ok(self.target.0)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn ensure_target(&mut self, width: u32, height: u32) -> io::Result<()> {
|
||||
if !self.target.is_null() && self.width == width && self.height == height {
|
||||
return Ok(());
|
||||
}
|
||||
let desc = D3D11_TEXTURE2D_DESC {
|
||||
Width: width,
|
||||
Height: height,
|
||||
MipLevels: 1,
|
||||
ArraySize: 1,
|
||||
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Usage: D3D11_USAGE_DEFAULT,
|
||||
BindFlags: D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
|
||||
CPUAccessFlags: 0,
|
||||
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
|
||||
};
|
||||
let mut target = ptr::null_mut();
|
||||
check(
|
||||
(*self.device.0).CreateTexture2D(&desc, ptr::null(), &mut target),
|
||||
"CreateTexture2D",
|
||||
)?;
|
||||
let target = ComPtr(target);
|
||||
let mut rtv = ptr::null_mut();
|
||||
check(
|
||||
(*self.device.0).CreateRenderTargetView(target.0 as *mut _, ptr::null(), &mut rtv),
|
||||
"CreateRenderTargetView",
|
||||
)?;
|
||||
self.rtv = ComPtr(rtv);
|
||||
self.target = target;
|
||||
self.width = width;
|
||||
self.height = height;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
unsafe fn ensure_source_view(&mut self, source: *mut ID3D11Texture2D) -> io::Result<()> {
|
||||
if !self.srv.is_null() && self.srv_source == source {
|
||||
return Ok(());
|
||||
}
|
||||
let mut srv = ptr::null_mut();
|
||||
check(
|
||||
(*self.device.0).CreateShaderResourceView(source as *mut _, ptr::null(), &mut srv),
|
||||
"CreateShaderResourceView",
|
||||
)?;
|
||||
self.srv = ComPtr(srv);
|
||||
self.srv_source = source;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Advanced Color state is dynamic: HDR can be switched on or off, or a WCG
|
||||
// desktop can turn into an HDR one, without the duplication being lost. An
|
||||
// output's description is a snapshot, so once the factory is no longer
|
||||
// current a new factory and output are needed to see the new state, as the
|
||||
// GetDesc1 docs require.
|
||||
unsafe fn refresh_output_state(&mut self) {
|
||||
if self.queried_at.elapsed() < OUTPUT_STATE_REFRESH {
|
||||
return;
|
||||
}
|
||||
self.queried_at = Instant::now();
|
||||
if self.factory.is_null() || (*self.factory.0).IsCurrent() == FALSE {
|
||||
let (factory, output6) = enumerate_output6(&self.device_name);
|
||||
if !output6.is_null() {
|
||||
self.factory = factory;
|
||||
self.output6 = output6;
|
||||
} else {
|
||||
// Keep reading the old output, but enumerate again next time.
|
||||
self.factory = ComPtr(ptr::null_mut());
|
||||
}
|
||||
}
|
||||
let is_hdr = output_is_hdr(self.output6.0).unwrap_or(self.is_hdr);
|
||||
let level = if is_hdr {
|
||||
query_sdr_white_level(&self.device_name)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A transiently unreadable level keeps the last known one.
|
||||
if is_hdr == self.is_hdr && (level.is_none() || level == self.sdr_white_level) {
|
||||
return;
|
||||
}
|
||||
log::info!(
|
||||
"output changed: hdr {} -> {is_hdr}, sdr white level {:?} -> {level:?}",
|
||||
self.is_hdr,
|
||||
self.sdr_white_level
|
||||
);
|
||||
if is_hdr && level.is_none() {
|
||||
log::warn!(
|
||||
"HDR output but the SDR white level cannot be read, assuming 80 nits until it can"
|
||||
);
|
||||
}
|
||||
self.is_hdr = is_hdr;
|
||||
self.sdr_white_level = level;
|
||||
let data = params_data(level);
|
||||
(*self.context.0).UpdateSubresource(
|
||||
self.params.0 as *mut _,
|
||||
0,
|
||||
ptr::null(),
|
||||
data.as_ptr() as _,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// `None` is either a non-HDR (WCG) output, where 1.0 already is the display's
|
||||
// reference white, or an HDR output whose level is unknown; both use 1.0.
|
||||
fn params_data(sdr_white_level: Option<u32>) -> [f32; 4] {
|
||||
[
|
||||
1000.0 / sdr_white_level.unwrap_or(1000) as f32,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
]
|
||||
}
|
||||
|
||||
// FP16 desktop composition means either HDR (scene-referred, 1.0 == 80 nits)
|
||||
// or, since Windows 11 22H2, Advanced Color SDR (display-referred), and only
|
||||
// IDXGIOutput6 (Windows 10 1703) tells them apart. `None` when it cannot be
|
||||
// read right now.
|
||||
unsafe fn output_is_hdr(output6: *mut IDXGIOutput6) -> Option<bool> {
|
||||
if output6.is_null() {
|
||||
return None;
|
||||
}
|
||||
let mut desc: DXGI_OUTPUT_DESC1 = mem::zeroed();
|
||||
if (*output6).GetDesc1(&mut desc) != S_OK {
|
||||
return None;
|
||||
}
|
||||
Some(desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020)
|
||||
}
|
||||
|
||||
unsafe fn query_output6(object: *mut IUnknown) -> ComPtr<IDXGIOutput6> {
|
||||
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
|
||||
if !object.is_null() {
|
||||
(*object).QueryInterface(
|
||||
&IID_IDXGIOutput6,
|
||||
&mut output6 as *mut *mut _ as *mut *mut _,
|
||||
);
|
||||
}
|
||||
ComPtr(output6)
|
||||
}
|
||||
|
||||
// A fresh factory sees the current display configuration; the output is found
|
||||
// by its GDI name because the outputs of a stale factory keep stale descriptions.
|
||||
// Returns both or neither: a non-null factory guarantees the output came from
|
||||
// its topology, so a caller that sees a null factory knows to enumerate again.
|
||||
unsafe fn enumerate_output6(
|
||||
device_name: &[WCHAR; 32],
|
||||
) -> (ComPtr<IDXGIFactory1>, ComPtr<IDXGIOutput6>) {
|
||||
let mut factory: *mut c_void = ptr::null_mut();
|
||||
if CreateDXGIFactory1(&IID_IDXGIFactory1, &mut factory) != S_OK {
|
||||
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
|
||||
}
|
||||
let factory = ComPtr(factory as *mut IDXGIFactory1);
|
||||
let mut adapter_index = 0;
|
||||
loop {
|
||||
let mut adapter = ptr::null_mut();
|
||||
if (*factory.0).EnumAdapters1(adapter_index, &mut adapter) != S_OK {
|
||||
break;
|
||||
}
|
||||
let adapter = ComPtr(adapter);
|
||||
adapter_index += 1;
|
||||
let mut output_index = 0;
|
||||
loop {
|
||||
let mut output = ptr::null_mut();
|
||||
if (*adapter.0).EnumOutputs(output_index, &mut output) != S_OK {
|
||||
break;
|
||||
}
|
||||
let output = ComPtr(output);
|
||||
output_index += 1;
|
||||
let mut desc: DXGI_OUTPUT_DESC = mem::zeroed();
|
||||
if (*output.0).GetDesc(&mut desc) == S_OK && wide_eq(&desc.DeviceName, device_name) {
|
||||
let output6 = query_output6(output.0 as *mut IUnknown);
|
||||
if output6.is_null() {
|
||||
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
|
||||
}
|
||||
return (factory, output6);
|
||||
}
|
||||
}
|
||||
}
|
||||
(ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()))
|
||||
}
|
||||
|
||||
fn other(msg: impl Into<String>) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Other, msg.into())
|
||||
}
|
||||
|
||||
fn check(hr: HRESULT, what: &str) -> io::Result<()> {
|
||||
if hr == S_OK {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(other(format!("{what} failed: {hr:#x}")))
|
||||
}
|
||||
}
|
||||
|
||||
// D3DCompile(pSrcData, SrcDataSize, pSourceName, pDefines, pInclude,
|
||||
// pEntrypoint, pTarget, Flags1, Flags2, ppCode, ppErrorMsgs)
|
||||
type D3DCompileFn = unsafe extern "system" fn(
|
||||
LPCVOID,
|
||||
SIZE_T,
|
||||
LPCSTR,
|
||||
*const D3D_SHADER_MACRO,
|
||||
*mut ID3DInclude,
|
||||
LPCSTR,
|
||||
LPCSTR,
|
||||
UINT,
|
||||
UINT,
|
||||
*mut *mut ID3DBlob,
|
||||
*mut *mut ID3DBlob,
|
||||
) -> HRESULT;
|
||||
|
||||
static D3D_COMPILE: OnceLock<Result<D3DCompileFn, String>> = OnceLock::new();
|
||||
|
||||
// Loaded once per process and kept: the compiler DLL is only needed on HDR
|
||||
// desktops, and an import-time link would make every install depend on it.
|
||||
fn load_d3d_compile() -> io::Result<D3DCompileFn> {
|
||||
D3D_COMPILE
|
||||
.get_or_init(|| unsafe { find_d3d_compile() })
|
||||
.clone()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Unsupported, e))
|
||||
}
|
||||
|
||||
unsafe fn find_d3d_compile() -> Result<D3DCompileFn, String> {
|
||||
let name: Vec<u16> = "d3dcompiler_47.dll\0".encode_utf16().collect();
|
||||
let module = LoadLibraryExW(name.as_ptr(), ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if module.is_null() {
|
||||
return Err("d3dcompiler_47.dll not available".into());
|
||||
}
|
||||
let f = GetProcAddress(module, b"D3DCompile\0".as_ptr() as _);
|
||||
if f.is_null() {
|
||||
return Err("D3DCompile not exported".into());
|
||||
}
|
||||
Ok(mem::transmute::<_, D3DCompileFn>(f))
|
||||
}
|
||||
|
||||
unsafe fn compile_shader(
|
||||
compile: D3DCompileFn,
|
||||
src: &str,
|
||||
target: &[u8],
|
||||
) -> io::Result<ComPtr<ID3DBlob>> {
|
||||
let mut code = ptr::null_mut();
|
||||
let mut errors = ptr::null_mut();
|
||||
let hr = compile(
|
||||
src.as_ptr() as _,
|
||||
src.len(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
ptr::null_mut(),
|
||||
b"main\0".as_ptr() as _,
|
||||
target.as_ptr() as _,
|
||||
0,
|
||||
0,
|
||||
&mut code,
|
||||
&mut errors,
|
||||
);
|
||||
let errors = ComPtr(errors);
|
||||
if hr != S_OK || code.is_null() {
|
||||
let msg = if errors.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
let bytes = std::slice::from_raw_parts(
|
||||
(*errors.0).GetBufferPointer() as *const u8,
|
||||
(*errors.0).GetBufferSize(),
|
||||
);
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
};
|
||||
if !code.is_null() {
|
||||
(*(code as *mut IUnknown)).Release();
|
||||
}
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
format!("D3DCompile failed: {hr:#x} {msg}"),
|
||||
));
|
||||
}
|
||||
Ok(ComPtr(code))
|
||||
}
|
||||
|
||||
const DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL: u32 = 11;
|
||||
const QDC_ONLY_ACTIVE_PATHS: u32 = 2;
|
||||
|
||||
#[repr(C)]
|
||||
#[allow(non_snake_case)]
|
||||
struct DISPLAYCONFIG_SDR_WHITE_LEVEL {
|
||||
header: DISPLAYCONFIG_DEVICE_INFO_HEADER,
|
||||
SDRWhiteLevel: ULONG,
|
||||
}
|
||||
|
||||
#[link(name = "user32")]
|
||||
extern "system" {
|
||||
fn GetDisplayConfigBufferSizes(
|
||||
flags: u32,
|
||||
numPathArrayElements: *mut u32,
|
||||
numModeInfoArrayElements: *mut u32,
|
||||
) -> LONG;
|
||||
fn QueryDisplayConfig(
|
||||
flags: u32,
|
||||
numPathArrayElements: *mut u32,
|
||||
pathArray: *mut DISPLAYCONFIG_PATH_INFO,
|
||||
numModeInfoArrayElements: *mut u32,
|
||||
modeInfoArray: *mut DISPLAYCONFIG_MODE_INFO,
|
||||
currentTopologyId: *mut DISPLAYCONFIG_TOPOLOGY_ID,
|
||||
) -> LONG;
|
||||
fn DisplayConfigGetDeviceInfo(requestPacket: *mut DISPLAYCONFIG_DEVICE_INFO_HEADER) -> LONG;
|
||||
}
|
||||
|
||||
/// SDR white level of the output whose GDI name is `device_name`
|
||||
/// (e.g. `\\.\DISPLAY1`), in DISPLAYCONFIG units (1000 == 80 nits). `None`
|
||||
/// when the query fails (before Windows 10 1709) or reports 0.
|
||||
fn query_sdr_white_level(device_name: &[WCHAR; 32]) -> Option<u32> {
|
||||
unsafe {
|
||||
let mut n_paths = 0u32;
|
||||
let mut n_modes = 0u32;
|
||||
if GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut n_paths, &mut n_modes) != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut paths: Vec<DISPLAYCONFIG_PATH_INFO> = vec![mem::zeroed(); n_paths as usize];
|
||||
let mut modes: Vec<DISPLAYCONFIG_MODE_INFO> = vec![mem::zeroed(); n_modes as usize];
|
||||
if QueryDisplayConfig(
|
||||
QDC_ONLY_ACTIVE_PATHS,
|
||||
&mut n_paths,
|
||||
paths.as_mut_ptr(),
|
||||
&mut n_modes,
|
||||
modes.as_mut_ptr(),
|
||||
ptr::null_mut(),
|
||||
) != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for path in &paths[..n_paths as usize] {
|
||||
let mut source: DISPLAYCONFIG_SOURCE_DEVICE_NAME = mem::zeroed();
|
||||
source.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
|
||||
source.header.size = mem::size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as _;
|
||||
source.header.adapterId = path.sourceInfo.adapterId;
|
||||
source.header.id = path.sourceInfo.id;
|
||||
if DisplayConfigGetDeviceInfo(&mut source.header) != 0
|
||||
|| !wide_eq(&source.viewGdiDeviceName, device_name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut white: DISPLAYCONFIG_SDR_WHITE_LEVEL = mem::zeroed();
|
||||
white.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
|
||||
white.header.size = mem::size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as _;
|
||||
white.header.adapterId = path.targetInfo.adapterId;
|
||||
white.header.id = path.targetInfo.id;
|
||||
if DisplayConfigGetDeviceInfo(&mut white.header) == 0 && white.SDRWhiteLevel != 0 {
|
||||
return Some(white.SDRWhiteLevel);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn wide_eq(a: &[WCHAR], b: &[WCHAR]) -> bool {
|
||||
let end = |s: &[WCHAR]| s.iter().position(|&c| c == 0).unwrap_or(s.len());
|
||||
a[..end(a)] == b[..end(b)]
|
||||
}
|
||||
+120
-4
@@ -1,18 +1,20 @@
|
||||
use std::{io, mem, ptr, slice};
|
||||
pub mod gdi;
|
||||
pub use gdi::CapturerGDI;
|
||||
pub mod hdr;
|
||||
pub mod mag;
|
||||
|
||||
use winapi::{
|
||||
shared::{
|
||||
dxgi::*,
|
||||
dxgi1_2::*,
|
||||
dxgi1_6::*,
|
||||
dxgiformat::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT},
|
||||
dxgitype::*,
|
||||
minwindef::{DWORD, FALSE, TRUE, UINT},
|
||||
ntdef::LONG,
|
||||
windef::{HMONITOR, RECT},
|
||||
winerror::*,
|
||||
// dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
|
||||
},
|
||||
um::{
|
||||
d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown, wingdi::*,
|
||||
@@ -66,6 +68,7 @@ pub struct Capturer {
|
||||
adapter_desc1: DXGI_ADAPTER_DESC1,
|
||||
rotate: Rotate,
|
||||
frame_state: FrameState,
|
||||
hdr: Option<hdr::HdrToSdr>,
|
||||
}
|
||||
|
||||
impl Capturer {
|
||||
@@ -113,7 +116,7 @@ impl Capturer {
|
||||
}
|
||||
} else {
|
||||
res = wrap_hresult(unsafe {
|
||||
let hres = (*display.inner.0).DuplicateOutput(device.0 as *mut _, &mut duplication);
|
||||
let hres = Self::duplicate_output(&display, device.0, &mut duplication);
|
||||
if hres != S_OK {
|
||||
gdi_capturer = display.create_gdi();
|
||||
println!("Fallback to GDI");
|
||||
@@ -169,7 +172,8 @@ impl Capturer {
|
||||
device,
|
||||
context,
|
||||
duplication: ComPtr(duplication),
|
||||
fastlane: desc.DesktopImageInSystemMemory == TRUE,
|
||||
fastlane: desc.DesktopImageInSystemMemory == TRUE
|
||||
&& desc.ModeDesc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
surface: ComPtr(ptr::null_mut()),
|
||||
texture: ComPtr(ptr::null_mut()),
|
||||
width: display.width() as usize,
|
||||
@@ -183,9 +187,104 @@ impl Capturer {
|
||||
adapter_desc1,
|
||||
rotate,
|
||||
frame_state: FrameState::Idle,
|
||||
hdr: None,
|
||||
})
|
||||
}
|
||||
|
||||
// Asks for the float desktop that HDR mode composes so it can be tone-mapped;
|
||||
// the legacy call would hand back DXGI's clipped BGRA8 conversion instead.
|
||||
// Only where IDXGIOutput6 (Windows 10 1703) exists, since that is what later
|
||||
// tells an HDR desktop from a WCG one; Microsoft's duplication sample gates
|
||||
// the float request the same way.
|
||||
unsafe fn duplicate_output(
|
||||
display: &Display,
|
||||
device: *mut ID3D11Device,
|
||||
duplication: &mut *mut IDXGIOutputDuplication,
|
||||
) -> HRESULT {
|
||||
if !hdr::UNAVAILABLE.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
|
||||
(*display.inner.0).QueryInterface(
|
||||
&IID_IDXGIOutput6,
|
||||
&mut output6 as *mut *mut _ as *mut *mut _,
|
||||
);
|
||||
if !output6.is_null() {
|
||||
let output6 = ComPtr(output6);
|
||||
let formats = [DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8A8_UNORM];
|
||||
let hres = (*output6.0).DuplicateOutput1(
|
||||
device as *mut _,
|
||||
0,
|
||||
formats.len() as UINT,
|
||||
formats.as_ptr(),
|
||||
duplication,
|
||||
);
|
||||
if hres == S_OK {
|
||||
return hres;
|
||||
}
|
||||
hbb_common::log::warn!(
|
||||
"HDR DuplicateOutput1 failed: hr={:#x}, fallback=DuplicateOutput",
|
||||
hres as u32
|
||||
);
|
||||
}
|
||||
}
|
||||
(*display.inner.0).DuplicateOutput(device as *mut _, duplication)
|
||||
}
|
||||
|
||||
unsafe fn tonemap(
|
||||
&mut self,
|
||||
source: *mut ID3D11Texture2D,
|
||||
desc: &D3D11_TEXTURE2D_DESC,
|
||||
) -> io::Result<*mut ID3D11Texture2D> {
|
||||
if self.hdr.is_none() {
|
||||
match hdr::HdrToSdr::new(
|
||||
self.device.0,
|
||||
self.context.0,
|
||||
self.display.inner.0,
|
||||
&self.display.desc.DeviceName,
|
||||
) {
|
||||
Ok(hdr) => self.hdr = Some(hdr),
|
||||
Err(err) => return self.abandon_tonemap(err),
|
||||
}
|
||||
}
|
||||
let converted = match self.hdr.as_mut() {
|
||||
Some(hdr) => hdr.convert(source, desc),
|
||||
None => Err(io::Error::new(io::ErrorKind::Other, "no tone-map")),
|
||||
};
|
||||
match converted {
|
||||
Ok(texture) => Ok(texture),
|
||||
Err(err) => self.abandon_tonemap(err),
|
||||
}
|
||||
}
|
||||
|
||||
// Drops the tone-map and re-duplicates the output the legacy way, so DXGI
|
||||
// hands over clipped BGRA8 (the pre-HDR behaviour). If re-duplication fails,
|
||||
// switch to GDI before returning. The caller sees WouldBlock and asks again.
|
||||
unsafe fn abandon_tonemap<T>(&mut self, err: io::Error) -> io::Result<T> {
|
||||
if hdr::is_permanent(&err) {
|
||||
hdr::UNAVAILABLE.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
hbb_common::log::error!("HDR tone-map failed, re-duplicating without it: {err}");
|
||||
self.hdr = None;
|
||||
if let Err(release_err) = self.release_frame() {
|
||||
hbb_common::log::warn!("DXGI frame cleanup failed while disabling HDR: {release_err}");
|
||||
}
|
||||
self.duplication = ComPtr(ptr::null_mut());
|
||||
let mut duplication = ptr::null_mut();
|
||||
let result = wrap_hresult(
|
||||
(*self.display.inner.0).DuplicateOutput(self.device.0 as *mut _, &mut duplication),
|
||||
);
|
||||
if let Err(err) = result {
|
||||
if self.set_gdi() {
|
||||
return Err(io::ErrorKind::WouldBlock.into());
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
self.duplication = ComPtr(duplication);
|
||||
let mut desc: DXGI_OUTDUPL_DESC = mem::zeroed();
|
||||
(*duplication).GetDesc(&mut desc);
|
||||
self.fastlane = desc.DesktopImageInSystemMemory == TRUE;
|
||||
Err(io::ErrorKind::WouldBlock.into())
|
||||
}
|
||||
|
||||
fn create_rotations(
|
||||
device: *mut ID3D11Device,
|
||||
context: *mut ID3D11DeviceContext,
|
||||
@@ -339,6 +438,9 @@ impl Capturer {
|
||||
}
|
||||
|
||||
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
|
||||
if self.duplication.0.is_null() {
|
||||
return Err(io::ErrorKind::AddrNotAvailable.into());
|
||||
}
|
||||
let mut frame = ptr::null_mut();
|
||||
#[allow(invalid_value)]
|
||||
let mut info = mem::MaybeUninit::uninit().assume_init();
|
||||
@@ -377,6 +479,12 @@ impl Capturer {
|
||||
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
|
||||
(*texture.0).GetDesc(&mut texture_desc);
|
||||
|
||||
let mut source = texture.0;
|
||||
if texture_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
|
||||
source = self.tonemap(texture.0, &texture_desc)?;
|
||||
(*source).GetDesc(&mut texture_desc);
|
||||
}
|
||||
|
||||
texture_desc.Usage = D3D11_USAGE_STAGING;
|
||||
texture_desc.BindFlags = 0;
|
||||
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
||||
@@ -397,7 +505,7 @@ impl Capturer {
|
||||
&mut surface as *mut *mut _ as *mut *mut _,
|
||||
);
|
||||
|
||||
(*self.context.0).CopyResource(readable.0 as *mut _, texture.0 as *mut _);
|
||||
(*self.context.0).CopyResource(readable.0 as *mut _, source as *mut _);
|
||||
|
||||
Ok(surface)
|
||||
}
|
||||
@@ -505,6 +613,14 @@ impl Capturer {
|
||||
let texture = ComPtr(texture);
|
||||
self.texture = texture;
|
||||
|
||||
let mut frame_desc: D3D11_TEXTURE2D_DESC = mem::zeroed();
|
||||
(*self.texture.0).GetDesc(&mut frame_desc);
|
||||
if frame_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
|
||||
let converted = self.tonemap(self.texture.0, &frame_desc)?;
|
||||
(*converted).AddRef();
|
||||
self.texture = ComPtr(converted);
|
||||
}
|
||||
|
||||
let mut final_texture = self.texture.0 as *mut c_void;
|
||||
let mut rotation = match self.display.rotation() {
|
||||
DXGI_MODE_ROTATION_ROTATE90 => 90,
|
||||
|
||||
+161
-3
@@ -1694,7 +1694,9 @@ impl Client {
|
||||
let bytes = res?;
|
||||
if let Ok(msg_in) = Message::parse_from_bytes(&bytes) {
|
||||
if let Some(message::Union::SignedId(si)) = msg_in.union {
|
||||
if let Ok((id, their_pk_b, signed_fp)) = decode_id_pk_dtls(&si.id, &sign_pk) {
|
||||
if let Ok((id, their_pk_b, signed_fp, kx_version)) =
|
||||
decode_id_pk_dtls(&si.id, &sign_pk)
|
||||
{
|
||||
if id == peer_id {
|
||||
// WebRTC only: bind the DTLS channel to the verified peer identity.
|
||||
// webrtc-rs already bound the certificate to the remote SDP, so
|
||||
@@ -1710,14 +1712,31 @@ impl Client {
|
||||
}
|
||||
let (asymmetric_value, symmetric_value, key) =
|
||||
create_symmetric_key_msg(their_pk_b);
|
||||
// A WebRTC stream is encrypted by DTLS and takes no stream
|
||||
// key of its own, split or not, so the pick says what runs: 0.
|
||||
let picked = if is_webrtc {
|
||||
0
|
||||
} else {
|
||||
hbb_common::tcp::kx_version_for(kx_version)
|
||||
};
|
||||
let mut msg_out = Message::new();
|
||||
msg_out.set_public_key(PublicKey {
|
||||
asymmetric_value,
|
||||
asymmetric_value: asymmetric_value.clone(),
|
||||
symmetric_value,
|
||||
kx_version: picked,
|
||||
..Default::default()
|
||||
});
|
||||
timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??;
|
||||
conn.set_key(key);
|
||||
conn.set_negotiated_key(
|
||||
key,
|
||||
true,
|
||||
&hbb_common::tcp::KxTranscript {
|
||||
initiator_pk: &asymmetric_value,
|
||||
responder_pk: &their_pk_b,
|
||||
advertised: kx_version,
|
||||
picked,
|
||||
},
|
||||
)?;
|
||||
} else {
|
||||
if is_webrtc {
|
||||
bail!("WebRTC handshake id mismatch (possible MITM)");
|
||||
@@ -5795,3 +5814,142 @@ mod webrtc_race_tests {
|
||||
assert!(err.contains("webrtc dead") && err.contains("relay dead"), "{}", err);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod kx_tests {
|
||||
use super::*;
|
||||
use hbb_common::{
|
||||
sodiumoxide::crypto::box_,
|
||||
tcp::{Encrypt, FramedStream, KxTranscript, KX_VERSION_LATEST},
|
||||
};
|
||||
|
||||
const PEER_ID: &str = "123456789";
|
||||
|
||||
/// What the stand-in controlled peer saw: the version the controller picked, and whether the
|
||||
/// controller's first application message decrypted.
|
||||
struct Seen {
|
||||
picked: u32,
|
||||
decrypted: bool,
|
||||
}
|
||||
|
||||
fn test_delay(time: i64) -> Message {
|
||||
let mut msg = Message::new();
|
||||
msg.set_test_delay(TestDelay {
|
||||
time,
|
||||
..Default::default()
|
||||
});
|
||||
msg
|
||||
}
|
||||
|
||||
fn delay_in(bytes: &[u8]) -> Option<i64> {
|
||||
match Message::parse_from_bytes(bytes).ok()?.union? {
|
||||
message::Union::TestDelay(t) => Some(t.time),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A stand-in controlled peer on loopback. It advertises `advertised` in its signed identity
|
||||
/// and runs the key under `run`, or under the version the controller picked when `run` is
|
||||
/// `None`, then sends one message and reads one. Returns the host, its identity as the
|
||||
/// rendezvous server would sign it, and what it saw.
|
||||
async fn controlled_stub(
|
||||
advertised: u32,
|
||||
run: Option<u32>,
|
||||
rs_sk: sign::SecretKey,
|
||||
) -> (String, Vec<u8>, oneshot::Receiver<Seen>) {
|
||||
let (sign_pk, sign_sk) = sign::gen_keypair();
|
||||
let id_pk = |pk: &[u8], kx_version| {
|
||||
IdPk {
|
||||
id: PEER_ID.to_owned(),
|
||||
pk: pk.to_vec().into(),
|
||||
kx_version,
|
||||
..Default::default()
|
||||
}
|
||||
.write_to_bytes()
|
||||
.unwrap()
|
||||
};
|
||||
let signed_id_pk = sign::sign(&id_pk(&sign_pk.0, 0), &rs_sk);
|
||||
let listener = hbb_common::tcp::new_listener("127.0.0.1:0", false)
|
||||
.await
|
||||
.unwrap();
|
||||
let host = listener.local_addr().unwrap().to_string();
|
||||
let (tx, rx) = oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let (stream, addr) = listener.accept().await.unwrap();
|
||||
let mut s = FramedStream::from(stream, addr);
|
||||
let (our_pk_b, our_sk_b) = box_::gen_keypair();
|
||||
let mut msg = Message::new();
|
||||
msg.set_signed_id(SignedId {
|
||||
id: sign::sign(&id_pk(&our_pk_b.0, advertised), &sign_sk).into(),
|
||||
..Default::default()
|
||||
});
|
||||
s.send(&msg).await.unwrap();
|
||||
let bytes = s.next().await.unwrap().unwrap();
|
||||
let Some(message::Union::PublicKey(pk)) =
|
||||
Message::parse_from_bytes(&bytes).unwrap().union
|
||||
else {
|
||||
panic!("expected the controller's public key");
|
||||
};
|
||||
let key =
|
||||
Encrypt::decode(&pk.symmetric_value, &pk.asymmetric_value, &our_sk_b).unwrap();
|
||||
let t = KxTranscript {
|
||||
initiator_pk: &pk.asymmetric_value,
|
||||
responder_pk: &our_pk_b.0,
|
||||
advertised,
|
||||
picked: run.unwrap_or(pk.kx_version),
|
||||
};
|
||||
if t.picked == 0 {
|
||||
s.set_key(key);
|
||||
} else {
|
||||
s.set_key_split(key, false, &t).unwrap();
|
||||
}
|
||||
s.send(&test_delay(2)).await.unwrap();
|
||||
let decrypted = matches!(s.next().await, Some(Ok(b)) if delay_in(&b) == Some(1));
|
||||
tx.send(Seen {
|
||||
picked: pk.kx_version,
|
||||
decrypted,
|
||||
})
|
||||
.ok();
|
||||
});
|
||||
(host, signed_id_pk, rx)
|
||||
}
|
||||
|
||||
/// The controller's handshake against the stub, then one application message each way.
|
||||
/// Returns what the stub saw and whether the stub's message decrypted on this side.
|
||||
async fn handshake(advertised: u32, run: Option<u32>) -> (Seen, bool) {
|
||||
let (rs_pk, rs_sk) = sign::gen_keypair();
|
||||
let (host, signed_id_pk, seen) = controlled_stub(advertised, run, rs_sk).await;
|
||||
let mut conn = connect_tcp(host, 3000).await.unwrap();
|
||||
let pk =
|
||||
Client::secure_connection(PEER_ID, signed_id_pk, &crate::encode64(rs_pk.0), &mut conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(pk.is_some() && conn.is_secured());
|
||||
conn.send(&test_delay(1)).await.unwrap();
|
||||
let decrypted = matches!(conn.next().await, Some(Ok(b)) if delay_in(&b) == Some(2));
|
||||
(seen.await.unwrap(), decrypted)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_new_peers_pick_version_1_and_exchange_application_data() {
|
||||
let (seen, decrypted) = handshake(KX_VERSION_LATEST, None).await;
|
||||
assert_eq!(seen.picked, 1);
|
||||
assert!(seen.decrypted && decrypted);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_a_peer_without_versions_gets_version_0() {
|
||||
let (seen, decrypted) = handshake(0, Some(0)).await;
|
||||
assert_eq!(seen.picked, 0);
|
||||
assert!(seen.decrypted && decrypted);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_a_pick_lowered_in_transit_decrypts_nothing() {
|
||||
// The controlled side takes 0 from a controller without versions, so a lowered pick is
|
||||
// caught by the keys disagreeing on the first application message, not before.
|
||||
let (seen, decrypted) = handshake(KX_VERSION_LATEST, Some(0)).await;
|
||||
assert_eq!(seen.picked, 1);
|
||||
assert!(!seen.decrypted && !decrypted);
|
||||
}
|
||||
}
|
||||
|
||||
+377
-18
@@ -59,6 +59,7 @@ pub const PLATFORM_MACOS: &str = "Mac OS";
|
||||
pub const PLATFORM_ANDROID: &str = "Android";
|
||||
|
||||
pub const TIMER_OUT: Duration = Duration::from_secs(1);
|
||||
pub(crate) const API_LOG_INTERVAL: Duration = Duration::from_secs(600);
|
||||
pub const DEFAULT_KEEP_ALIVE: i32 = 60_000;
|
||||
|
||||
const MIN_VER_MULTI_UI_SESSION: &str = "1.2.4";
|
||||
@@ -1196,6 +1197,9 @@ pub fn get_local_option(key: &str) -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
if key == "lang" && (v == "pt" || v == "br") {
|
||||
return "pt-br".to_owned();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -1244,6 +1248,23 @@ fn is_tcp_proxy_api_target(url: &str) -> bool {
|
||||
should_use_tcp_proxy_for_api_url(url, &ui_get_api_server())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn should_throttle_log(url: &str) -> bool {
|
||||
url::Url::parse(url)
|
||||
.map(|parsed| parsed.path().ends_with("/api/heartbeat"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
macro_rules! api_log {
|
||||
($level:ident, $url:expr, $interval:expr, $($arg:tt)+) => {{
|
||||
if should_throttle_log($url) {
|
||||
hbb_common::throttled_log!($interval, $level, $($arg)+);
|
||||
} else {
|
||||
log::$level!($($arg)+);
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
fn tcp_proxy_log_target(url: &str) -> String {
|
||||
url::Url::parse(url)
|
||||
.ok()
|
||||
@@ -1293,7 +1314,10 @@ async fn tcp_proxy_request(
|
||||
parsed.path().to_string()
|
||||
};
|
||||
|
||||
log::debug!(
|
||||
api_log!(
|
||||
debug,
|
||||
url,
|
||||
API_LOG_INTERVAL,
|
||||
"Sending {} {} via TCP proxy to {}",
|
||||
method,
|
||||
parsed.path(),
|
||||
@@ -1453,7 +1477,10 @@ where
|
||||
};
|
||||
|
||||
if should_fallback && can_fallback_to_raw_tcp(url) {
|
||||
log::warn!(
|
||||
api_log!(
|
||||
warn,
|
||||
url,
|
||||
API_LOG_INTERVAL,
|
||||
"HTTP {} to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
|
||||
method,
|
||||
tcp_proxy_log_target(url),
|
||||
@@ -1465,7 +1492,13 @@ where
|
||||
match tcp_fn.await {
|
||||
Ok(resp) => return Ok(resp),
|
||||
Err(tcp_err) => {
|
||||
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
|
||||
api_log!(
|
||||
warn,
|
||||
url,
|
||||
API_LOG_INTERVAL,
|
||||
"TCP proxy fallback also failed: {:?}",
|
||||
tcp_err
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1523,7 +1556,10 @@ pub async fn post_request_with_status(
|
||||
Ok((status, _)) => *status >= 500,
|
||||
};
|
||||
if should_fallback && can_fallback_to_raw_tcp(&url) {
|
||||
log::warn!(
|
||||
api_log!(
|
||||
warn,
|
||||
&url,
|
||||
API_LOG_INTERVAL,
|
||||
"HTTP POST to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
|
||||
tcp_proxy_log_target(&url),
|
||||
http_result
|
||||
@@ -1534,7 +1570,13 @@ pub async fn post_request_with_status(
|
||||
match post_request_via_tcp_proxy_status(&url, &body, header).await {
|
||||
Ok(resp) => return Ok(resp),
|
||||
Err(tcp_err) => {
|
||||
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
|
||||
api_log!(
|
||||
warn,
|
||||
&url,
|
||||
API_LOG_INTERVAL,
|
||||
"TCP proxy fallback also failed: {:?}",
|
||||
tcp_err
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1591,7 +1633,10 @@ async fn post_request_(
|
||||
Err(e) => {
|
||||
if (tls_type.is_none() || danger_accept_invalid_cert.is_none()) && e.is_request() {
|
||||
if danger_accept_invalid_cert.is_none() {
|
||||
log::warn!(
|
||||
api_log!(
|
||||
warn,
|
||||
url,
|
||||
API_LOG_INTERVAL,
|
||||
"HTTP request failed: {:?}, try again, danger accept invalid cert",
|
||||
e
|
||||
);
|
||||
@@ -1606,7 +1651,13 @@ async fn post_request_(
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
log::warn!("HTTP request failed: {:?}, try again with native-tls", e);
|
||||
api_log!(
|
||||
warn,
|
||||
url,
|
||||
API_LOG_INTERVAL,
|
||||
"HTTP request failed: {:?}, try again with native-tls",
|
||||
e
|
||||
);
|
||||
post_request_(
|
||||
url,
|
||||
tls_url,
|
||||
@@ -2100,17 +2151,46 @@ async fn key_exchange(conn: &mut Stream, key: &str, log_on_success: bool) -> Res
|
||||
}
|
||||
let their_pk_b = sign::verify(&ex.keys[0], &rs_pk)
|
||||
.map_err(|_| anyhow!("Signature mismatch in key exchange"))?;
|
||||
let (asymmetric_value, symmetric_value, key) = create_symmetric_key_msg(
|
||||
get_pk(&their_pk_b)
|
||||
.context("Wrong their public length in key exchange")?,
|
||||
);
|
||||
let their_pk_b = get_pk(&their_pk_b)
|
||||
.context("Wrong their public length in key exchange")?;
|
||||
// The signed X25519 high bit marks servers that sign their parameters.
|
||||
// X25519 ignores that bit, so old clients use the key unchanged; keep
|
||||
// the bytes as signed, since the transcript and KxParams carry them so.
|
||||
if their_pk_b[31] & 0x80 != 0 || !ex.signed_params.is_empty() {
|
||||
let params = sign::verify(&ex.signed_params, &rs_pk)
|
||||
.ok()
|
||||
.and_then(|signed| {
|
||||
let params =
|
||||
signed.strip_prefix(hbb_common::tcp::KX_PARAMS_DOMAIN)?;
|
||||
KxParams::parse_from_bytes(params).ok()
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
anyhow!("Missing or invalid signed key exchange parameters")
|
||||
})?;
|
||||
if params.pk[..] != their_pk_b[..] || params.version != ex.version {
|
||||
bail!("Key exchange version or public key does not match its signature");
|
||||
}
|
||||
}
|
||||
let (asymmetric_value, symmetric_value, key) =
|
||||
create_symmetric_key_msg(their_pk_b);
|
||||
let picked = hbb_common::tcp::kx_version_for(ex.version);
|
||||
let mut msg_out = RendezvousMessage::new();
|
||||
msg_out.set_key_exchange(KeyExchange {
|
||||
keys: vec![asymmetric_value, symmetric_value],
|
||||
keys: vec![asymmetric_value.clone(), symmetric_value],
|
||||
version: picked,
|
||||
..Default::default()
|
||||
});
|
||||
timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??;
|
||||
conn.set_key(key);
|
||||
conn.set_negotiated_key(
|
||||
key,
|
||||
true,
|
||||
&hbb_common::tcp::KxTranscript {
|
||||
initiator_pk: &asymmetric_value,
|
||||
responder_pk: &their_pk_b,
|
||||
advertised: ex.version,
|
||||
picked,
|
||||
},
|
||||
)?;
|
||||
if log_on_success {
|
||||
log::info!("Connection secured");
|
||||
}
|
||||
@@ -2170,21 +2250,23 @@ pub fn get_rs_pk(str_base64: &str) -> Option<sign::PublicKey> {
|
||||
}
|
||||
|
||||
pub fn decode_id_pk(signed: &[u8], key: &sign::PublicKey) -> ResultType<(String, [u8; 32])> {
|
||||
let (id, pk, _) = decode_id_pk_dtls(signed, key)?;
|
||||
let (id, pk, _, _) = decode_id_pk_dtls(signed, key)?;
|
||||
Ok((id, pk))
|
||||
}
|
||||
|
||||
/// Like [`decode_id_pk`] but also returns the signed DTLS certificate fingerprint (empty string
|
||||
/// for non-WebRTC peers), used to bind a WebRTC DTLS channel to the verified peer identity.
|
||||
/// for non-WebRTC peers), used to bind a WebRTC DTLS channel to the verified peer identity, and
|
||||
/// the newest key exchange version the peer speaks (0, the original scheme, for a peer from
|
||||
/// before versions).
|
||||
pub fn decode_id_pk_dtls(
|
||||
signed: &[u8],
|
||||
key: &sign::PublicKey,
|
||||
) -> ResultType<(String, [u8; 32], String)> {
|
||||
) -> ResultType<(String, [u8; 32], String, u32)> {
|
||||
let res = IdPk::parse_from_bytes(
|
||||
&sign::verify(signed, key).map_err(|_| anyhow!("Signature mismatch"))?,
|
||||
)?;
|
||||
if let Some(pk) = get_pk(&res.pk) {
|
||||
Ok((res.id, pk, res.dtls_fingerprint))
|
||||
Ok((res.id, pk, res.dtls_fingerprint, res.kx_version))
|
||||
} else {
|
||||
bail!("Wrong their public length");
|
||||
}
|
||||
@@ -3104,6 +3186,21 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_throttle_log() {
|
||||
assert!(should_throttle_log("https://example.com/api/heartbeat"));
|
||||
assert!(should_throttle_log(
|
||||
"https://example.com/api/heartbeat?token=secret"
|
||||
));
|
||||
assert!(should_throttle_log("https://example.com/prefix/api/heartbeat"));
|
||||
assert!(!should_throttle_log("https://example.com/api/heartbeat2"));
|
||||
assert!(!should_throttle_log("https://example.com/api/sysinfo"));
|
||||
assert!(!should_throttle_log(
|
||||
"https://example.com/api/sysinfo?next=/api/heartbeat"
|
||||
));
|
||||
assert!(!should_throttle_log("not a url"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_tcp_proxy_addr_normalizes_bare_ipv6_host() {
|
||||
struct RestoreCustomRendezvousServer(String);
|
||||
@@ -3318,6 +3415,26 @@ mod tests {
|
||||
(encode64(pk.0), sk)
|
||||
}
|
||||
|
||||
fn signed_key_exchange(
|
||||
pk: &box_::PublicKey,
|
||||
sk: &sign::SecretKey,
|
||||
version: u32,
|
||||
) -> KeyExchange {
|
||||
let params = KxParams {
|
||||
pk: pk.0.to_vec().into(),
|
||||
version,
|
||||
..Default::default()
|
||||
};
|
||||
let mut payload = hbb_common::tcp::KX_PARAMS_DOMAIN.to_vec();
|
||||
payload.extend_from_slice(¶ms.write_to_bytes().unwrap());
|
||||
KeyExchange {
|
||||
keys: vec![sign::sign(&pk.0, sk).into()],
|
||||
version,
|
||||
signed_params: sign::sign(&payload, sk).into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(host: &str) -> Stream {
|
||||
hbb_common::socket_client::connect_tcp(host.to_owned(), 3000)
|
||||
.await
|
||||
@@ -3379,6 +3496,248 @@ mod tests {
|
||||
assert!(conn.is_secured());
|
||||
}
|
||||
|
||||
// The stand-in does what hbbs does at version 1: advertises it and splits the exchanged key
|
||||
// over the same transcript. Neither side's unit tests can catch a client that puts a
|
||||
// different byte string into the transcript than the server does; only a frame crossing
|
||||
// between the two can.
|
||||
#[tokio::test]
|
||||
async fn test_secure_tcp_version_1_keys_match_the_server_both_ways() {
|
||||
let (key, sk) = server_key();
|
||||
let host = rendezvous_stub(move |mut s| async move {
|
||||
let (eph_pk, eph_sk) = box_::gen_keypair();
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_key_exchange(KeyExchange {
|
||||
keys: vec![sign::sign(&eph_pk.0, &sk).into()],
|
||||
version: 1,
|
||||
..Default::default()
|
||||
});
|
||||
s.send(&msg).await.unwrap();
|
||||
let reply = s.next_timeout(3000).await.unwrap().unwrap();
|
||||
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
|
||||
let Some(rendezvous_message::Union::KeyExchange(ex)) = reply.union else {
|
||||
panic!("expected the client's key exchange");
|
||||
};
|
||||
let shared =
|
||||
hbb_common::tcp::Encrypt::decode(&ex.keys[1], &ex.keys[0], &eph_sk).unwrap();
|
||||
s.set_key_split(
|
||||
shared,
|
||||
false,
|
||||
&hbb_common::tcp::KxTranscript {
|
||||
initiator_pk: &ex.keys[0],
|
||||
responder_pk: &eph_pk.0,
|
||||
advertised: 1,
|
||||
picked: ex.version,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
// Answers with the request's serial, so the client learns from its own reply that
|
||||
// the request was read under the right key.
|
||||
let request = s.next_timeout(3000).await.unwrap().unwrap();
|
||||
let request = RendezvousMessage::parse_from_bytes(&request).unwrap();
|
||||
let Some(rendezvous_message::Union::TestNatRequest(nat)) = request.union else {
|
||||
panic!("expected the client's nat request");
|
||||
};
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_test_nat_response(TestNatResponse {
|
||||
port: nat.serial,
|
||||
..Default::default()
|
||||
});
|
||||
s.send(&msg).await.unwrap();
|
||||
})
|
||||
.await;
|
||||
let mut conn = connect(&host).await;
|
||||
secure_tcp_required(&mut conn, &key).await.unwrap();
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_test_nat_request(TestNatRequest {
|
||||
serial: 7,
|
||||
..Default::default()
|
||||
});
|
||||
conn.send(&msg).await.unwrap();
|
||||
let reply = conn.next_timeout(3000).await.unwrap().unwrap();
|
||||
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
|
||||
let Some(rendezvous_message::Union::TestNatResponse(nat)) = reply.union else {
|
||||
panic!("expected the server's nat response");
|
||||
};
|
||||
assert_eq!(nat.port, 7);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_secure_tcp_legacy_and_signed_servers_exchange_application_data() {
|
||||
for (advertised, signed) in [(0, false), (1, true), (3, true)] {
|
||||
for required in [false, true] {
|
||||
let (key, sk) = server_key();
|
||||
let host = rendezvous_stub(move |mut s| async move {
|
||||
let (mut eph_pk, eph_sk) = box_::gen_keypair();
|
||||
let mut msg = RendezvousMessage::new();
|
||||
let ex = if signed {
|
||||
eph_pk.0[31] |= 0x80;
|
||||
signed_key_exchange(&eph_pk, &sk, advertised)
|
||||
} else {
|
||||
KeyExchange {
|
||||
keys: vec![sign::sign(&eph_pk.0, &sk).into()],
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
msg.set_key_exchange(ex);
|
||||
s.send(&msg).await.unwrap();
|
||||
let reply = s.next_timeout(3000).await.unwrap().unwrap();
|
||||
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
|
||||
let Some(rendezvous_message::Union::KeyExchange(ex)) = reply.union else {
|
||||
panic!("expected the client's key exchange");
|
||||
};
|
||||
assert_eq!(ex.keys.len(), 2);
|
||||
assert_eq!(ex.version, hbb_common::tcp::kx_version_for(advertised));
|
||||
let shared =
|
||||
hbb_common::tcp::Encrypt::decode(&ex.keys[1], &ex.keys[0], &eph_sk)
|
||||
.unwrap();
|
||||
if ex.version >= 1 {
|
||||
s.set_key_split(
|
||||
shared,
|
||||
false,
|
||||
&hbb_common::tcp::KxTranscript {
|
||||
initiator_pk: &ex.keys[0],
|
||||
responder_pk: &eph_pk.0,
|
||||
advertised,
|
||||
picked: ex.version,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
} else {
|
||||
s.set_key(shared);
|
||||
}
|
||||
let request = s.next_timeout(3000).await.unwrap().unwrap();
|
||||
let request = RendezvousMessage::parse_from_bytes(&request).unwrap();
|
||||
let Some(rendezvous_message::Union::TestNatRequest(nat)) = request.union else {
|
||||
panic!("expected the client's nat request");
|
||||
};
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_test_nat_response(TestNatResponse {
|
||||
port: nat.serial,
|
||||
..Default::default()
|
||||
});
|
||||
s.send(&msg).await.unwrap();
|
||||
})
|
||||
.await;
|
||||
let mut conn = connect(&host).await;
|
||||
if required {
|
||||
secure_tcp_required(&mut conn, &key).await.unwrap();
|
||||
} else {
|
||||
secure_tcp(&mut conn, &key).await.unwrap();
|
||||
}
|
||||
assert!(conn.is_secured());
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_test_nat_request(TestNatRequest {
|
||||
serial: 7,
|
||||
..Default::default()
|
||||
});
|
||||
conn.send(&msg).await.unwrap();
|
||||
let reply = conn.next_timeout(3000).await.unwrap().unwrap();
|
||||
let reply = RendezvousMessage::parse_from_bytes(&reply).unwrap();
|
||||
let Some(rendezvous_message::Union::TestNatResponse(nat)) = reply.union else {
|
||||
panic!("expected the server's nat response");
|
||||
};
|
||||
assert_eq!(nat.port, 7);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_secure_tcp_rejects_unverified_versions_before_reply() {
|
||||
let (key, sk) = server_key();
|
||||
let (mut eph_pk, _) = box_::gen_keypair();
|
||||
eph_pk.0[31] |= 0x80;
|
||||
let (other_pk, _) = box_::gen_keypair();
|
||||
let (_, other_sk) = sign::gen_keypair();
|
||||
for case in [
|
||||
"missing_signature",
|
||||
"stripped_version_and_signature",
|
||||
"cleared_marker_and_stripped_fields",
|
||||
"lowered_version",
|
||||
"raised_version",
|
||||
"replaced_public_key",
|
||||
"invalid_signature",
|
||||
"wrong_signer",
|
||||
"unstructured_payload",
|
||||
"undomained_params",
|
||||
"signed_id_pk_as_params",
|
||||
] {
|
||||
let mut ex = signed_key_exchange(&eph_pk, &sk, 1);
|
||||
match case {
|
||||
"missing_signature" => ex.signed_params = Bytes::new(),
|
||||
"stripped_version_and_signature" => {
|
||||
ex.signed_params = Bytes::new();
|
||||
ex.version = 0;
|
||||
}
|
||||
"cleared_marker_and_stripped_fields" => {
|
||||
let mut signed_pk = ex.keys[0].to_vec();
|
||||
*signed_pk.last_mut().unwrap() &= 0x7f;
|
||||
ex.keys[0] = signed_pk.into();
|
||||
ex.signed_params = Bytes::new();
|
||||
ex.version = 0;
|
||||
}
|
||||
"lowered_version" => ex.version = 0,
|
||||
"raised_version" => ex.version = 2,
|
||||
"replaced_public_key" => ex.keys[0] = sign::sign(&other_pk.0, &sk).into(),
|
||||
"invalid_signature" => {
|
||||
let mut signed = ex.signed_params.to_vec();
|
||||
signed[0] ^= 1;
|
||||
ex.signed_params = signed.into();
|
||||
}
|
||||
"wrong_signer" => {
|
||||
ex.signed_params = signed_key_exchange(&eph_pk, &other_sk, 1).signed_params;
|
||||
}
|
||||
"unstructured_payload" => {
|
||||
let mut payload = eph_pk.0.to_vec();
|
||||
payload.extend_from_slice(&1u32.to_le_bytes());
|
||||
ex.signed_params = sign::sign(&payload, &sk).into();
|
||||
}
|
||||
"undomained_params" => {
|
||||
let params = KxParams {
|
||||
pk: eph_pk.0.to_vec().into(),
|
||||
version: 1,
|
||||
..Default::default()
|
||||
};
|
||||
ex.signed_params = sign::sign(¶ms.write_to_bytes().unwrap(), &sk).into();
|
||||
}
|
||||
"signed_id_pk_as_params" => {
|
||||
// The server signs IdPk with the same key; its `id` sits where `pk` does.
|
||||
let mut pk = [0x2au8; box_::PUBLICKEYBYTES];
|
||||
pk[30] = 0xc2;
|
||||
pk[31] = 0xaa;
|
||||
let id_pk = IdPk {
|
||||
id: String::from_utf8(pk.to_vec()).unwrap(),
|
||||
pk: vec![7u8; box_::PUBLICKEYBYTES].into(),
|
||||
..Default::default()
|
||||
};
|
||||
ex.keys[0] = sign::sign(&pk, &sk).into();
|
||||
ex.version = 0;
|
||||
ex.signed_params = sign::sign(&id_pk.write_to_bytes().unwrap(), &sk).into();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
for required in [false, true] {
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_key_exchange(ex.clone());
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let host = rendezvous_stub(move |mut s| async move {
|
||||
s.send(&msg).await.unwrap();
|
||||
tx.send(s.next_timeout(3000).await.is_none()).unwrap();
|
||||
})
|
||||
.await;
|
||||
let mut conn = connect(&host).await;
|
||||
let result = if required {
|
||||
secure_tcp_required(&mut conn, &key).await
|
||||
} else {
|
||||
secure_tcp(&mut conn, &key).await
|
||||
};
|
||||
assert!(result.is_err(), "accepted {case}, required={required}");
|
||||
assert!(!conn.is_secured());
|
||||
drop(conn);
|
||||
assert!(rx.await.unwrap(), "replied to {case}, required={required}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dtls_fingerprint_travels_signed_and_binds() {
|
||||
let (pk, sk) = sign::gen_keypair();
|
||||
@@ -3395,7 +3754,7 @@ mod tests {
|
||||
&sk,
|
||||
);
|
||||
|
||||
let (id, their_pk, signed_fp) = decode_id_pk_dtls(&signed, &pk).unwrap();
|
||||
let (id, their_pk, signed_fp, _) = decode_id_pk_dtls(&signed, &pk).unwrap();
|
||||
assert_eq!(id, "123456789");
|
||||
assert_eq!(their_pk, [7u8; 32]);
|
||||
assert_eq!(signed_fp, fp);
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::{
|
||||
};
|
||||
|
||||
#[cfg(not(any(target_os = "ios")))]
|
||||
use crate::{ui_interface::get_builtin_option, Connection};
|
||||
use crate::{common::API_LOG_INTERVAL, ui_interface::get_builtin_option, Connection};
|
||||
use hbb_common::{
|
||||
config::{self, Config, LocalConfig},
|
||||
log,
|
||||
@@ -242,7 +242,11 @@ async fn start_hbbs_sync_async() {
|
||||
}
|
||||
let modified_at = LocalConfig::get_option("strategy_timestamp").parse::<i64>().unwrap_or(0);
|
||||
v["modified_at"] = json!(modified_at);
|
||||
if let Ok(s) = crate::post_request(url.clone(), v.to_string(), "").await {
|
||||
let response = crate::post_request(url.clone(), v.to_string(), "").await;
|
||||
if let Err(err) = &response {
|
||||
hbb_common::throttled_log!(API_LOG_INTERVAL, warn, "Heartbeat failed: {err:?}");
|
||||
}
|
||||
if let Ok(s) = response {
|
||||
if let Ok(mut rsp) = serde_json::from_str::<HashMap::<&str, Value>>(&s) {
|
||||
if rsp.remove("sysinfo").is_some() {
|
||||
info_uploaded.uploaded = false;
|
||||
|
||||
+59
@@ -555,9 +555,29 @@ pub enum Data {
|
||||
height: u32,
|
||||
hotx: i32,
|
||||
hoty: i32,
|
||||
/// Whether the hotspot came from the driver, or was inferred from the bitmap.
|
||||
///
|
||||
/// Absent means the producer predates the field, and the default must then be TRUE, not
|
||||
/// `bool::default()`. These messages are JSON over a unix socket between two processes
|
||||
/// that are upgraded separately: an old root service can be streaming to a freshly
|
||||
/// started `--server`, and its `{"hotx": 12, "hoty": 11}` carries no provenance. Read as
|
||||
/// `false`, the new consumer would throw that hotspot away and re-infer one from the
|
||||
/// upright bitmap, moving the cursor on a rotated display for the length of the upgrade.
|
||||
/// Defaulting to true means "no provenance available, so behave as the old protocol did"
|
||||
/// -- use the point the producer sent. It is not a claim that the value was measured; a
|
||||
/// new producer that wants re-inference says `hot_measured: false` explicitly, which
|
||||
/// serializes, so new-to-new is unaffected.
|
||||
#[serde(default = "legacy_hot_measured")]
|
||||
hot_measured: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The default for a `hot_measured` that is not on the wire at all; see the field's docs.
|
||||
#[cfg(all(target_os = "linux", feature = "drm"))]
|
||||
fn legacy_hot_measured() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
pub async fn start(postfix: &str) -> ResultType<()> {
|
||||
let mut incoming = new_listener(postfix).await?;
|
||||
@@ -2310,4 +2330,43 @@ mod test {
|
||||
fn test_select_server_uid_fails_when_multiple_servers_are_ambiguous() {
|
||||
assert!(select_server_uid_for_user_main_ipc(&[501, 502], None, false).is_err());
|
||||
}
|
||||
|
||||
/// The upgrade window: an old root service is still streaming when a new `--server` starts,
|
||||
/// and its DrmCursor carries no `hot_measured` at all. Read as `false` the consumer would
|
||||
/// discard a hotspot the producer did measure and re-infer one from the bitmap, which moves
|
||||
/// the cursor on a rotated display until the old process is replaced. `bool::default()` is
|
||||
/// the wrong default here; the right one preserves what the old protocol meant.
|
||||
#[cfg(all(target_os = "linux", feature = "drm"))]
|
||||
#[test]
|
||||
fn a_drm_cursor_without_provenance_keeps_the_hotspot_the_producer_sent() {
|
||||
// `Data` is adjacently tagged (`tag = "t", content = "c"`), so this is the real shape on
|
||||
// the socket, not a simplified one.
|
||||
let legacy =
|
||||
r#"{"t":"DrmCursor","c":{"id":7,"width":24,"height":24,"hotx":12,"hoty":11}}"#;
|
||||
let msg: Data = serde_json::from_str(legacy).expect("legacy DrmCursor must deserialize");
|
||||
match msg {
|
||||
Data::DrmCursor {
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
..
|
||||
} => {
|
||||
assert_eq!((hotx, hoty), (12, 11));
|
||||
assert!(
|
||||
hot_measured,
|
||||
"a message with no provenance field must be treated as the old protocol did, \
|
||||
i.e. use the hotspot as sent, not re-infer it"
|
||||
);
|
||||
}
|
||||
other => panic!("expected DrmCursor, got {other:?}"),
|
||||
}
|
||||
|
||||
// And a NEW producer that really wants re-inference says so, which serializes: the
|
||||
// default must not swallow an explicit false.
|
||||
let modern = r#"{"t":"DrmCursor","c":{"id":7,"width":24,"height":24,"hotx":0,"hoty":0,"hot_measured":false}}"#;
|
||||
match serde_json::from_str::<Data>(modern).expect("modern DrmCursor must deserialize") {
|
||||
Data::DrmCursor { hot_measured, .. } => assert!(!hot_measured),
|
||||
other => panic!("expected DrmCursor, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +107,7 @@ enum DrmProducerMsg {
|
||||
height: u32,
|
||||
hotx: i32,
|
||||
hoty: i32,
|
||||
hot_measured: bool,
|
||||
colors: Vec<u8>,
|
||||
},
|
||||
}
|
||||
@@ -915,6 +916,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
|
||||
height,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
colors,
|
||||
} => {
|
||||
conn.send_msg(
|
||||
@@ -924,6 +926,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
|
||||
height,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -1115,6 +1118,7 @@ fn drm_capture_worker(
|
||||
height: c.height,
|
||||
hotx: c.hotx,
|
||||
hoty: c.hoty,
|
||||
hot_measured: c.hot_measured,
|
||||
colors: c.colors,
|
||||
})
|
||||
.is_err()
|
||||
|
||||
+40
-1
@@ -34,6 +34,7 @@ mod nb;
|
||||
mod nl;
|
||||
mod pl;
|
||||
mod ptbr;
|
||||
mod pt_PT;
|
||||
mod ro;
|
||||
mod ru;
|
||||
mod sc;
|
||||
@@ -63,7 +64,8 @@ pub const LANGS: &[(&str, &str)] = &[
|
||||
("nb", "Norsk bokmål"),
|
||||
("zh-cn", "简体中文"),
|
||||
("zh-tw", "繁體中文"),
|
||||
("pt", "Português"),
|
||||
("pt-pt", "Português (Portugal)"),
|
||||
("pt-br", "Português (Brasil)"),
|
||||
("es", "Español"),
|
||||
("et", "Eesti keel"),
|
||||
("eu", "Euskara"),
|
||||
@@ -143,6 +145,21 @@ fn resolve_lang(saved_lang: &str, locale: &str, cjk_fallback: bool) -> String {
|
||||
.to_owned();
|
||||
}
|
||||
}
|
||||
if lang.is_empty() {
|
||||
// pt_PT on Linux, pt-PT on mac, pt_PT on Android.
|
||||
// Per CLDR locale inheritance, every Portuguese-speaking locale
|
||||
// besides bare "pt" and Brazil's own variants (pt-BR/pt_BR) has
|
||||
// pt-PT as its parent (Angola, Mozambique, Cape Verde, etc.),
|
||||
// so it should resolve to European Portuguese.
|
||||
if locale.starts_with("pt") {
|
||||
lang = (if locale == "pt" || locale.starts_with("pt-br") || locale.starts_with("pt_br") {
|
||||
"pt-br"
|
||||
} else {
|
||||
"pt-pt"
|
||||
})
|
||||
.to_owned();
|
||||
}
|
||||
}
|
||||
if lang.is_empty() {
|
||||
lang = locale
|
||||
.split("-")
|
||||
@@ -187,6 +204,8 @@ pub fn translate_locale(name: String, locale: &str) -> String {
|
||||
"id" => id::T.deref(),
|
||||
"br" => ptbr::T.deref(),
|
||||
"pt" => ptbr::T.deref(),
|
||||
"pt-br" => ptbr::T.deref(),
|
||||
"pt-pt" => pt_PT::T.deref(),
|
||||
"tr" => tr::T.deref(),
|
||||
"cs" => cs::T.deref(),
|
||||
"da" => da::T.deref(),
|
||||
@@ -344,4 +363,24 @@ mod test {
|
||||
assert_eq!(f("", "zh_TW", false), "zh-tw");
|
||||
assert_eq!(f("", "ja-JP", false), "ja");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_lang_detects_pt_pt_and_pt_br_from_locale() {
|
||||
use super::resolve_lang as f;
|
||||
|
||||
assert_eq!(f("", "pt-PT", false), "pt-pt");
|
||||
assert_eq!(f("", "pt_PT", false), "pt-pt");
|
||||
assert_eq!(f("", "pt-BR", false), "pt-br");
|
||||
assert_eq!(f("", "pt_BR", false), "pt-br");
|
||||
assert_eq!(f("", "pt-AO", false), "pt-pt");
|
||||
assert_eq!(f("", "pt-MZ", false), "pt-pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_lang_saved_lang_takes_precedence_over_locale() {
|
||||
use super::resolve_lang as f;
|
||||
|
||||
assert_eq!(f("pt-br", "pt-PT", false), "pt-br");
|
||||
assert_eq!(f("pt-pt", "pt-BR", false), "pt-pt");
|
||||
}
|
||||
}
|
||||
|
||||
+42
-42
@@ -4,7 +4,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Status", "Estado"),
|
||||
("Your Desktop", "Ambiente de Trabalho"),
|
||||
("desk_tip", "O seu Ambiente de Trabalho pode ser acedido com este ID e palavra-passe."),
|
||||
("Password", "Senha"),
|
||||
("Password", "Palavra-passe"),
|
||||
("Ready", "Pronto"),
|
||||
("Established", "Estabelecido"),
|
||||
("connecting_status", "A ligar à rede do RustDesk..."),
|
||||
@@ -21,7 +21,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Confirmation", "Confirmação"),
|
||||
("TCP tunneling", "Túnel TCP"),
|
||||
("Remove", "Remover"),
|
||||
("Refresh random password", "Actualizar palavra-chave"),
|
||||
("Refresh random password", "Actualizar palavra-passe"),
|
||||
("Set your own password", "Configure a sua palavra-passe"),
|
||||
("Enable keyboard/mouse", "Activar Teclado/Rato"),
|
||||
("Enable clipboard", "Activar Área de Transferência"),
|
||||
@@ -68,10 +68,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Close", "Fechar"),
|
||||
("Retry", "Tentar novamente"),
|
||||
("OK", "Confirmar"),
|
||||
("Password Required", "Palavra-chave Necessária"),
|
||||
("Please enter your password", "Por favor introduza a sua palavra-chave"),
|
||||
("Remember password", "Memorizar palavra-chave"),
|
||||
("Wrong Password", "Palavra-chave inválida"),
|
||||
("Password Required", "Palavra-passe Necessária"),
|
||||
("Please enter your password", "Por favor introduza a sua palavra-passe"),
|
||||
("Remember password", "Memorizar palavra-passe"),
|
||||
("Wrong Password", "Palavra-passe inválida"),
|
||||
("Do you want to enter again?", "Deseja tentar novamente??"),
|
||||
("Connection Error", "Erro de Ligação"),
|
||||
("Error", "Erro"),
|
||||
@@ -102,9 +102,9 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Unselect All", "Desmarcar todos"),
|
||||
("Empty Directory", "Directório Vazio"),
|
||||
("Not an empty directory", "Directório não está vazio"),
|
||||
("Are you sure you want to delete this file?", "Tem certeza que deseja apagar este ficheiro?"),
|
||||
("Are you sure you want to delete this empty directory?", "Tem certeza que deseja apagar este directório vazio?"),
|
||||
("Are you sure you want to delete the file of this directory?", "Tem certeza que deseja apagar este ficheiro deste directório?"),
|
||||
("Are you sure you want to delete this file?", "Tem a certeza que deseja apagar este ficheiro?"),
|
||||
("Are you sure you want to delete this empty directory?", "Tem a certeza que deseja apagar este diretório vazio?"),
|
||||
("Are you sure you want to delete the file of this directory?", "Tem a certeza que deseja apagar este ficheiro deste diretório?"),
|
||||
("Do this for all conflicts", "Fazer isto para todos os conflictos"),
|
||||
("This is irreversible!", "Isto é irreversível!"),
|
||||
("Deleting", "A apagar"),
|
||||
@@ -142,21 +142,21 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Failed to connect to relay server", "Falha ao ligar ao servidor de relay"),
|
||||
("Failed to connect via rendezvous server", "Falha ao ligar ao servidor de rendezvous"),
|
||||
("Failed to connect via relay server", "Falha ao ligar através do servidor de relay"),
|
||||
("Failed to make direct connection to remote desktop", "Falha ao fazer ligação directa ao desktop remoto"),
|
||||
("Set Password", "Definir palavra-chave"),
|
||||
("OS Password", "Senha do SO"),
|
||||
("Failed to make direct connection to remote desktop", "Falha ao fazer ligação directa ao ambiente de trabalho remoto"),
|
||||
("Set Password", "Definir palavra-passe"),
|
||||
("OS Password", "Palavra-Passe do SO"),
|
||||
("install_tip", "Devido ao UAC, o RustDesk não funciona correctamente em alguns casos. Para evitar o UAC, por favor clique no botão abaixo para instalar o RustDesk no sistema."),
|
||||
("Click to upgrade", "Clique para atualizar"),
|
||||
("Configure", "Configurar"),
|
||||
("config_acc", "Para controlar o seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Acessibilidade\"."),
|
||||
("config_screen", "Para aceder ao seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Gravar a Tela\"/"),
|
||||
("config_screen", "Para aceder ao seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Gravar o Ecrã\"."),
|
||||
("Installing ...", "A Instalar ..."),
|
||||
("Install", "Instalar"),
|
||||
("Installation", "Instalação"),
|
||||
("Installation Path", "Caminho da Instalação"),
|
||||
("Create start menu shortcuts", "Criar atalhos no menu iniciar"),
|
||||
("Create desktop icon", "Criar ícone no ambiente de trabalho"),
|
||||
("agreement_tip", "Ao iniciar a instalação, você concorda com o acordo de licença."),
|
||||
("agreement_tip", "Ao iniciar a instalação, está a concordar com o acordo de licença."),
|
||||
("Accept and Install", "Aceitar e Instalar"),
|
||||
("End-user license agreement", "Acordo de licença do utilizador final"),
|
||||
("Generating ...", "A Gerar ..."),
|
||||
@@ -170,13 +170,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Local Port", "Porta Local"),
|
||||
("Local Address", "Endereço local"),
|
||||
("Change Local Port", "Alterar porta local"),
|
||||
("setup_server_tip", "Para uma ligação mais rápida, por favor configure seu próprio servidor"),
|
||||
("setup_server_tip", "Para uma ligação mais rápida, por favor configure o seu próprio servidor"),
|
||||
("Too short, at least 6 characters.", "Muito curto, pelo menos 6 caracteres."),
|
||||
("The confirmation is not identical.", "A confirmação não é idêntica."),
|
||||
("Permissions", "Permissões"),
|
||||
("Accept", "Aceitar"),
|
||||
("Dismiss", "Dispensar"),
|
||||
("Disconnect", "Desconectar"),
|
||||
("Disconnect", "Desligar"),
|
||||
("Enable file copy and paste", "Permitir copiar e mover ficheiros"),
|
||||
("Connected", "Ligado"),
|
||||
("Direct and encrypted connection", "Ligação directa e encriptada"),
|
||||
@@ -184,10 +184,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Direct and unencrypted connection", "Ligação direta e não encriptada"),
|
||||
("Relayed and unencrypted connection", "Ligação via relay e não encriptada"),
|
||||
("Enter Remote ID", "Introduza o ID Remoto"),
|
||||
("Enter your password", "Introduza a sua palavra-chave"),
|
||||
("Enter your password", "Introduza a sua palavra-passe"),
|
||||
("Logging in...", "A efectuar Login..."),
|
||||
("Enable RDP session sharing", "Activar partilha de sessão RDP"),
|
||||
("Auto Login", "Login Automático (Somente válido se você activou \"Bloquear após o fim da sessão\")"),
|
||||
("Auto Login", "Login Automático (Apenas válido se tiver activado \"Bloquear após o fim da sessão\")"),
|
||||
("Enable direct IP access", "Activar Acesso IP Directo"),
|
||||
("Rename", "Renomear"),
|
||||
("Space", "Espaço"),
|
||||
@@ -197,7 +197,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Please enter the folder name", "Por favor introduza o nome do diretório"),
|
||||
("Fix it", "Reparar"),
|
||||
("Warning", "Aviso"),
|
||||
("Login screen using Wayland is not supported", "Tela de Login com Wayland não é suportada"),
|
||||
("Login screen using Wayland is not supported", "Ecrã de Início de Sessão com Wayland não é suportado"),
|
||||
("Reboot required", "Reinicialização necessária"),
|
||||
("Unsupported display server", "Servidor de display não suportado"),
|
||||
("x11 expected", "x11 em falha"),
|
||||
@@ -209,7 +209,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Enable remote configuration modification", "Habilitar modificações de configuração remotas"),
|
||||
("Run without install", "Executar sem instalar"),
|
||||
("Connect via relay", "Ligar via relay"),
|
||||
("Always connect via relay", "Sempre conectar via relay"),
|
||||
("Always connect via relay", "Ligar sempre via relay"),
|
||||
("whitelist_tip", "Somente IPs na whitelist podem me acessar"),
|
||||
("Login", "Login"),
|
||||
("Verify", "Verificar"),
|
||||
@@ -226,11 +226,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Unselect all tags", "Desselecionar todas as tags"),
|
||||
("Network error", "Erro de rede"),
|
||||
("Username missed", "Nome de utilizador em falta"),
|
||||
("Password missed", "Palavra-chave em falta"),
|
||||
("Wrong credentials", "Nome de utilizador ou palavra-chave incorrectos"),
|
||||
("Password missed", "Palavra-passe em falta"),
|
||||
("Wrong credentials", "Nome de utilizador ou palavra-passe incorrectos"),
|
||||
("The verification code is incorrect or has expired", "O código de verificação está incorreto ou expirou"),
|
||||
("Edit Tag", "Editar Tag"),
|
||||
("Forget Password", "Esquecer Palavra-chave"),
|
||||
("Forget Password", "Esquecer Palavra-passe"),
|
||||
("Favorites", "Favoritos"),
|
||||
("Add to Favorites", "Adicionar aos Favoritos"),
|
||||
("Remove from Favorites", "Remover dos Favoritos"),
|
||||
@@ -243,7 +243,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Remote ID", "ID Remoto"),
|
||||
("Paste", "Colar"),
|
||||
("Paste here?", "Colar aqui?"),
|
||||
("Are you sure to close the connection?", "Tem certeza que deseja fechar a ligação?"),
|
||||
("Are you sure to close the connection?", "Tem a certeza que deseja fechar a ligação?"),
|
||||
("Download new version", "Transferir nova versão"),
|
||||
("Touch mode", "Modo toque"),
|
||||
("Mouse mode", "Modo rato"),
|
||||
@@ -258,10 +258,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Three-Finger vertically", "Três dedos verticalmente"),
|
||||
("Mouse Wheel", "Roda do rato"),
|
||||
("Two-Finger Move", "Mover com dois dedos"),
|
||||
("Canvas Move", "Mover Tela"),
|
||||
("Canvas Move", "Mover Ecrã"),
|
||||
("Pinch to Zoom", "Clique para ampliar"),
|
||||
("Canvas Zoom", "Zoom na Tela"),
|
||||
("Reset canvas", "Reiniciar tela"),
|
||||
("Canvas Zoom", "Zoom no Ecrã"),
|
||||
("Reset canvas", "Reiniciar ecrã"),
|
||||
("No permission of file transfer", "Sem permissões de transferência de ficheiro"),
|
||||
("Note", "Nota"),
|
||||
("Connection", "Ligação"),
|
||||
@@ -276,7 +276,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Do you accept?", "Aceita?"),
|
||||
("Open System Setting", "Abrir Configurações do Sistema"),
|
||||
("How to get Android input permission?", "Como activar a permissão de entrada do Android?"),
|
||||
("android_input_permission_tip1", "Para que um dispositivo remoto controle o seu dispositivo Android via rato ou toque, você precisa permitir que o RustDesk use o serviço \"Acessibilidade\"."),
|
||||
("android_input_permission_tip1", "Para que um dispositivo remoto controle o seu dispositivo Android via rato ou toque, é necessário permitir que o RustDesk use o serviço \"Acessibilidade\"."),
|
||||
("android_input_permission_tip2", "Por favor vá para a próxima página de configuração do sistema, encontre e entre [Serviços Instalados], ACTIVE o serviço [RustDesk Input]."),
|
||||
("android_new_connection_tip", "Nova requisição de controle recebida, solicita o controle do seu dispositivo atual."),
|
||||
("android_service_will_start_tip", "Activar a Captura de Ecran irá automaticamente inicializar o serviço, permitindo que outros dispositivos solicitem uma ligação deste dispositivo."),
|
||||
@@ -307,18 +307,18 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Legacy mode", "Modo antigo"),
|
||||
("Map mode", "Modo de mapeamento"),
|
||||
("Translate mode", "Modo de tradução"),
|
||||
("Use permanent password", "Utilizar palavra-chave permanente"),
|
||||
("Use permanent password", "Utilizar palavra-passe permanente"),
|
||||
("Use both passwords", "Utilizar ambas as palavras-chave"),
|
||||
("Set permanent password", "Definir palavra-chave permanente"),
|
||||
("Set permanent password", "Definir palavra-passe permanente"),
|
||||
("Enable remote restart", "Activar reiniciar remoto"),
|
||||
("Restart remote device", "Reiniciar Dispositivo Remoto"),
|
||||
("Are you sure you want to restart", "Tem a certeza que pretende reiniciar"),
|
||||
("Restarting remote device", "A reiniciar sistema remoto"),
|
||||
("remote_restarting_tip", "O dispositivo remoto está a reiniciar, feche esta caixa de mensagem e volte a ligar com a palavra-passe permanente daqui a momentos"),
|
||||
("Copied", "Copiado"),
|
||||
("Exit Fullscreen", "Sair da tela cheia"),
|
||||
("Fullscreen", "Tela cheia"),
|
||||
("Mobile Actions", "Ações para celular"),
|
||||
("Exit Fullscreen", "Sair do Ecrã Inteiro"),
|
||||
("Fullscreen", "Ecrã Inteiro"),
|
||||
("Mobile Actions", "Ações para telemóvel"),
|
||||
("Select Monitor", "Selecionar monitor"),
|
||||
("Control Actions", "Ações de controle"),
|
||||
("Display Settings", "Configurações do visor"),
|
||||
@@ -327,10 +327,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Scroll Style", "Estilo de rolagem"),
|
||||
("Show Toolbar", "Mostrar barra de ferramentas"),
|
||||
("Hide Toolbar", "Ocultar barra de ferramentas"),
|
||||
("Direct Connection", "Conexão direta"),
|
||||
("Relay Connection", "Conexão de relé"),
|
||||
("Secure Connection", "Conexão segura"),
|
||||
("Insecure Connection", "Conexão insegura"),
|
||||
("Direct Connection", "Ligação direta"),
|
||||
("Relay Connection", "Ligação de relay"),
|
||||
("Secure Connection", "Ligação segura"),
|
||||
("Insecure Connection", "Ligação insegura"),
|
||||
("Scale original", "Escala original"),
|
||||
("Scale adaptive", "Escala adaptável"),
|
||||
("General", "Geral"),
|
||||
@@ -377,10 +377,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Full Access", "Controlo total"),
|
||||
("Screen Share", "Partilha de ecrã"),
|
||||
("ubuntu-21-04-required", "Wayland requer Ubuntu 21.04 ou versão superior."),
|
||||
("wayland-requires-higher-linux-version", "Wayland requer uma versão superior da distribuição linux. Por favor, tente o desktop X11 ou mude seu sistema operacional."),
|
||||
("wayland-requires-higher-linux-version", "Wayland requer uma versão superior da distribuição Linux. Por favor, tente o ambiente de trabalho X11 ou mude o seu sistema operativo."),
|
||||
("xdp-portal-unavailable", "A captura de ecrã do Wayland falhou. O XDG Desktop Portal poderá ter falhado ou estar indisponível. Tente reiniciá-lo com `systemctl --user restart xdg-desktop-portal`."),
|
||||
("JumpLink", "View"),
|
||||
("Please Select the screen to be shared(Operate on the peer side).", "Por favor, selecione a tela a ser compartilhada (operar no lado do peer)."),
|
||||
("Please Select the screen to be shared(Operate on the peer side).", "Por favor, selecione o ecrã a partilhar (operar no lado do par)."),
|
||||
("Show RustDesk", "Mostrar RustDesk"),
|
||||
("This PC", "Este PC"),
|
||||
("or", "ou"),
|
||||
@@ -760,11 +760,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("whitelist_cidr_tip", "A notação CIDR é suportada, por exemplo 192.168.1.0/24"),
|
||||
("Continue", "Continuar"),
|
||||
("Browser didn't open? Use the url below to sign in.", "O navegador não abriu? Utilize o URL abaixo para iniciar sessão."),
|
||||
("Lock canvas", "Bloquear tela"),
|
||||
("Lock canvas", "Bloquear ecrã"),
|
||||
("Sync clipboard between sessions", "Sincronizar área de transferência entre sessões"),
|
||||
("sync-clipboard-between-sessions-tip", "O texto ou as imagens copiados numa sessão remota também são enviados para a área de transferência das suas outras sessões ligadas."),
|
||||
("terminal-clipboard-write-tip", ""),
|
||||
("Allow terminal apps to copy to clipboard", ""),
|
||||
("terminal-clipboard-write-tip", "Uma aplicação no terminal pretende copiar texto para a área de transferência deste dispositivo. Se autorizada, esta permissão aplica-se a aplicações de terminal em todas as ligações até a desativar nas Configurações. A cópia e colagem manuais não são afetadas."),
|
||||
("Allow terminal apps to copy to clipboard", "Permitir cópia do terminal para a área de transferência"),
|
||||
("Enable", "Ativar"),
|
||||
("Reuse one connection for port forwarding", "Reutilizar uma ligação para o reencaminhamento de portas"),
|
||||
("port-forward-mux-tip", "Encaminhar todas as ligações de um reencaminhamento de portas por uma única ligação ao outro computador, em vez de ligar e iniciar sessão novamente para cada uma."),
|
||||
|
||||
+3
-3
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Lock canvas", "Bloca sa tela"),
|
||||
("Sync clipboard between sessions", "Sincroniza sa punta de billete intre is sessiones"),
|
||||
("sync-clipboard-between-sessions-tip", "Su testu o is immàgines copiadas in una sessione remota sunt imbiadas fintzas a sa punta de billete de is àteras sessiones connètidas."),
|
||||
("terminal-clipboard-write-tip", ""),
|
||||
("Allow terminal apps to copy to clipboard", ""),
|
||||
("terminal-clipboard-write-tip", "Un’aplicatzione in su terminale bolet copiare testu in sa punta de billete de custu dispositivu. Si benit frunidu, custu permissu s’àplicat a sas aplicatziones de terminale in totu sas connessiones finas a cando non nche l’istudas in sas Impostatziones. Sas operatziones de còpia e incolla manuales non benint influentzadas."),
|
||||
("Allow terminal apps to copy to clipboard", "Permite a sas aplicatziones de terminale de copiare in punta de billete"),
|
||||
("Enable", "Abìlita"),
|
||||
("Reuse one connection for port forwarding", "Torra a impreare una connessione pro s'imbiu de is portas"),
|
||||
("port-forward-mux-tip", "Totu is connessiones de un'imbiu de portas passant in una connessione ebbia a s'àteru computadore, in logu de si connètere e intrare torra pro dontzi una."),
|
||||
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk no at pòdidu carrigare unu cumponente de GStreamer netzessàriu pro registrare sa schermada ({})"),
|
||||
("Relay fallback delay in seconds", "Tardu prima de impreare su relè in segundos"),
|
||||
("relay-fallback-delay-tip", "Cantu tempus una connessione de relè giai istabilida abetat sa connessione direta WebRTC prima de èssere impreada in su postu suo. Aumenta pro dare prus tempus a una connessione direta lenta; diminuì pro colare prima a su relè in sas retes in ue non si podet fàghere una connessione direta. Lassa bòidu pro su valore predefinidu de 2.5 segundos."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Pro aviare una mutida de boghe, ativa in sa pàgina \"Cumpartzidura de ischermu\" s’elementu \"Catura de s’àudio\".")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+28
-2
@@ -276,12 +276,21 @@ async fn identity_handshake(stream: &mut Stream, secure: bool) -> ResultType<()>
|
||||
if stream.is_webrtc() && dtls_fingerprint.is_empty() {
|
||||
bail!("WebRTC local DTLS fingerprint unavailable");
|
||||
}
|
||||
// A WebRTC stream is encrypted by DTLS and takes no stream key of its own, split or
|
||||
// not, so what it advertises is what it runs: 0. Saying 1 there would have a future
|
||||
// controller that splits keys on WebRTC agree on a version this side never applies.
|
||||
let advertised = if stream.is_webrtc() {
|
||||
0
|
||||
} else {
|
||||
tcp::KX_VERSION_LATEST
|
||||
};
|
||||
msg_out.set_signed_id(SignedId {
|
||||
id: sign::sign(
|
||||
&IdPk {
|
||||
id: Config::get_id(),
|
||||
pk: Bytes::from(our_pk_b.0.to_vec()),
|
||||
dtls_fingerprint,
|
||||
kx_version: advertised,
|
||||
..Default::default()
|
||||
}
|
||||
.write_to_bytes()
|
||||
@@ -298,11 +307,28 @@ async fn identity_handshake(stream: &mut Stream, secure: bool) -> ResultType<()>
|
||||
if let Ok(msg_in) = Message::parse_from_bytes(&bytes) {
|
||||
if let Some(message::Union::PublicKey(pk)) = msg_in.union {
|
||||
if pk.asymmetric_value.len() == box_::PUBLICKEYBYTES {
|
||||
stream.set_key(tcp::Encrypt::decode(
|
||||
let key = tcp::Encrypt::decode(
|
||||
&pk.symmetric_value,
|
||||
&pk.asymmetric_value,
|
||||
&our_sk_b,
|
||||
)?);
|
||||
)?;
|
||||
if pk.kx_version > advertised {
|
||||
bail!(
|
||||
"Handshake failed: key exchange version {} not offered, {} was",
|
||||
pk.kx_version,
|
||||
advertised
|
||||
);
|
||||
}
|
||||
stream.set_negotiated_key(
|
||||
key,
|
||||
false,
|
||||
&tcp::KxTranscript {
|
||||
initiator_pk: &pk.asymmetric_value,
|
||||
responder_pk: &our_pk_b.0,
|
||||
advertised,
|
||||
picked: pk.kx_version,
|
||||
},
|
||||
)?;
|
||||
} else if pk.asymmetric_value.is_empty() {
|
||||
Config::set_key_confirmed(false);
|
||||
log::info!("Force to update pk");
|
||||
|
||||
+804
-24
@@ -53,17 +53,22 @@ impl FrameSlot {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Shared.transform` before new() stores the real value: a cursor arriving this early is held
|
||||
/// back and replayed once the session transform is in, because the producer will not resend it
|
||||
/// until the shape changes.
|
||||
/// `Shared.cursor_transform` before new() stores the real value: a cursor arriving this early is
|
||||
/// held back and replayed once the session transform is in, because the producer will not resend
|
||||
/// it until the shape changes.
|
||||
const TRANSFORM_PENDING: i32 = i32::MIN;
|
||||
|
||||
struct Shared {
|
||||
slot: Mutex<FrameSlot>,
|
||||
cv: Condvar,
|
||||
// Session transform, TRANSFORM_PENDING until new() stores it post-handshake; the receive
|
||||
// thread turns cursor bitmaps with it and defers any cursor that races the store.
|
||||
transform: std::sync::atomic::AtomicI32,
|
||||
// The output's real transform, TRANSFORM_PENDING until new() stores it post-handshake. Only
|
||||
// the cursor needs it across threads: it differs from the angle the FRAME is turned by on a
|
||||
// hardware-rotated 180 output, where the primary plane scans out upright but the compositor
|
||||
// still pre-rotates the sprite (measured on i915 + mutter: the frame arrived upright and the
|
||||
// sprite upside down). The frame's own angle is not shared - it is fixed for the session and
|
||||
// lives on the capturer that uses it. The receive thread defers any cursor that races the
|
||||
// store.
|
||||
cursor_transform: std::sync::atomic::AtomicI32,
|
||||
}
|
||||
|
||||
pub struct IpcDrmCapturer {
|
||||
@@ -177,10 +182,6 @@ fn transform_and_origin(
|
||||
.copied()
|
||||
.flatten()
|
||||
.map(|j| wl.displays[j].transform)
|
||||
// Hardware-rotated 180 scans out already upright (i915 advertises rotate-180 and
|
||||
// mutter uses it), and wl_output cannot tell hardware from software rotation, so 180
|
||||
// keeps master behavior until the plane rotation property travels the wire.
|
||||
.map(|t| if t == 90 || t == 270 { t } else { 0 })
|
||||
.unwrap_or(0);
|
||||
let origin = augment_with_wayland_geometry_from(drm, wl, &assignment)
|
||||
.get(wire_idx)
|
||||
@@ -188,6 +189,18 @@ fn transform_and_origin(
|
||||
(transform, origin)
|
||||
}
|
||||
|
||||
/// The angle the FRAME has to be turned back by. Hardware-rotated 180 scans out already upright
|
||||
/// (i915 advertises rotate-180 and mutter uses it), and wl_output cannot tell hardware from
|
||||
/// software rotation, so 180 keeps master behavior until the plane rotation property travels
|
||||
/// the wire. The cursor does not go through this: see `Shared::cursor_transform`.
|
||||
fn frame_transform(wl_transform: i32) -> i32 {
|
||||
if wl_transform == 90 || wl_transform == 270 {
|
||||
wl_transform
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes DRM_STATE: never call it while holding one of the per-display maps below.
|
||||
fn display_info_of(display: i32) -> Option<DrmDisplayInfo> {
|
||||
match &*DRM_STATE.lock().unwrap() {
|
||||
@@ -325,7 +338,7 @@ impl IpcDrmCapturer {
|
||||
ended: None,
|
||||
}),
|
||||
cv: Condvar::new(),
|
||||
transform: std::sync::atomic::AtomicI32::new(TRANSFORM_PENDING),
|
||||
cursor_transform: std::sync::atomic::AtomicI32::new(TRANSFORM_PENDING),
|
||||
});
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let (tx, rx) = std::sync::mpsc::channel::<ResultType<(Vec<DrmDisplayInfo>, usize)>>();
|
||||
@@ -350,13 +363,14 @@ impl IpcDrmCapturer {
|
||||
// clear racing the build rebuilds once instead of running a session on stale geometry.
|
||||
let snapshot_gen = scrap::wayland::display::wayland_snapshot_generation();
|
||||
let wl = scrap::wayland::display::get_displays();
|
||||
let (transform, origin) = transform_and_origin(&displays, wire_idx, &wl);
|
||||
let (wl_transform, origin) = transform_and_origin(&displays, wire_idx, &wl);
|
||||
let transform = frame_transform(wl_transform);
|
||||
// This capturer now shows that layout. If the session init's own wayland query failed it
|
||||
// saved an empty baseline, so this is the only record of what the stream is built on.
|
||||
super::display_service::note_capturer_layout(&wl.displays, snapshot_gen);
|
||||
shared
|
||||
.transform
|
||||
.store(transform, std::sync::atomic::Ordering::Release);
|
||||
.cursor_transform
|
||||
.store(wl_transform, std::sync::atomic::Ordering::Release);
|
||||
Ok((
|
||||
IpcDrmCapturer {
|
||||
shared,
|
||||
@@ -634,16 +648,18 @@ async fn recv_thread(
|
||||
|
||||
// A cursor that arrived before new() stored the session transform, held for replay. Only the
|
||||
// newest matters; the 200 ms recv timeout guarantees this is retried even on an idle wire.
|
||||
let mut pending_cursor: Option<(u64, u32, u32, i32, i32, Vec<u8>)> = None;
|
||||
let mut pending_cursor: Option<(u64, u32, u32, i32, i32, bool, Vec<u8>)> = None;
|
||||
let end_reason = loop {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
break "stopped".to_owned();
|
||||
}
|
||||
if pending_cursor.is_some() {
|
||||
let t = shared.transform.load(std::sync::atomic::Ordering::Acquire);
|
||||
let t = shared.cursor_transform.load(std::sync::atomic::Ordering::Acquire);
|
||||
if t != TRANSFORM_PENDING {
|
||||
if let Some((id, width, height, hotx, hoty, raw)) = pending_cursor.take() {
|
||||
deliver_drm_cursor(display, cursor_epoch, id, width, height, hotx, hoty, raw, t);
|
||||
if let Some((id, width, height, hotx, hoty, hot_measured, raw)) = pending_cursor.take() {
|
||||
deliver_drm_cursor(
|
||||
display, cursor_epoch, id, width, height, hotx, hoty, hot_measured, raw, t,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -745,6 +761,7 @@ async fn recv_thread(
|
||||
height,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
} => {
|
||||
// get_cursor_data() hands `colors` straight to the client, which renders
|
||||
// width*height*4 RGBA bytes: a short body would make it READ PAST THE BUFFER. A
|
||||
@@ -763,9 +780,9 @@ async fn recv_thread(
|
||||
raw.len()
|
||||
);
|
||||
}
|
||||
let t = shared.transform.load(std::sync::atomic::Ordering::Acquire);
|
||||
let t = shared.cursor_transform.load(std::sync::atomic::Ordering::Acquire);
|
||||
if t == TRANSFORM_PENDING {
|
||||
pending_cursor = Some((id, width, height, hotx, hoty, raw));
|
||||
pending_cursor = Some((id, width, height, hotx, hoty, hot_measured, raw));
|
||||
} else {
|
||||
pending_cursor = None;
|
||||
deliver_drm_cursor(
|
||||
@@ -776,6 +793,7 @@ async fn recv_thread(
|
||||
height,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
raw,
|
||||
t,
|
||||
);
|
||||
@@ -921,17 +939,34 @@ fn deliver_drm_cursor(
|
||||
height: u32,
|
||||
hotx: i32,
|
||||
hoty: i32,
|
||||
hot_measured: bool,
|
||||
raw: Vec<u8>,
|
||||
t: i32,
|
||||
) {
|
||||
let (width, height, hotx, hoty, colors) = if t == 90 || t == 270 {
|
||||
// Every non-zero angle, 180 included. Measured on i915 + mutter with the output at 180: the
|
||||
// frame arrived upright and the sprite upside down, so the compositor had pre-rotated the
|
||||
// sprite by the full transform while the plane scanned out already turned. wl_output cannot
|
||||
// say which of the two happened - the same blindness `frame_transform` defers to - so the
|
||||
// sprite is treated as pre-rotated at every angle.
|
||||
let (width, height, hotx, hoty, colors) = if t != 0 {
|
||||
let mut turned = Vec::new();
|
||||
unrotate_bgra(&raw, width as usize, height as usize, t, &mut turned);
|
||||
let (hx, hy) = unrotate_hotspot(t, width as i32, height as i32, hotx, hoty);
|
||||
(height as i32, width as i32, hx, hy, turned)
|
||||
let (dw, dh) = rotated_dims(t, width as usize, height as usize);
|
||||
// A hotspot the driver measured is a point on the scanout sprite and maps like a pixel.
|
||||
// A guessed one was guessed on the ROTATED sprite - top-left of an arrow's box - and
|
||||
// the tip of a turned arrow is some other corner, so it is guessed again on the upright
|
||||
// one. The old flow was off at every angle; what differs is the size of the error, which
|
||||
// is why only one of them got reported (see the test below).
|
||||
let (hx, hy) = if hot_measured {
|
||||
unrotate_hotspot(t, width as i32, height as i32, hotx, hoty)
|
||||
} else {
|
||||
scrap::drm_reader::infer_hotspot(&turned, dw, dh)
|
||||
};
|
||||
(dw as i32, dh as i32, hx, hy, turned)
|
||||
} else {
|
||||
(width as i32, height as i32, hotx, hoty, raw)
|
||||
};
|
||||
note_received_provenance(display, id, hot_measured);
|
||||
let id = fold_cursor_id(id, t);
|
||||
set_drm_cursor(
|
||||
display,
|
||||
@@ -947,6 +982,50 @@ fn deliver_drm_cursor(
|
||||
);
|
||||
}
|
||||
|
||||
/// Last provenance seen PER DISPLAY. Not one global: several streams run at once and their
|
||||
/// provenance can differ and still be stable -- one output publishing HOTSPOT_X/Y while another
|
||||
/// does not is a normal multi-GPU host -- and a single slot would read that as an endless
|
||||
/// alternation and log on every cursor message.
|
||||
static LAST_RECEIVED_PROVENANCE: Mutex<BTreeMap<i32, bool>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// Whether this display's provenance changed, recording the new value. Its own function so the
|
||||
/// per-display behaviour can be asserted without reading a log.
|
||||
fn provenance_is_news_for(display: i32, hot_measured: bool) -> bool {
|
||||
LAST_RECEIVED_PROVENANCE
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(display, hot_measured)
|
||||
!= Some(hot_measured)
|
||||
}
|
||||
|
||||
/// Say once per display, and again only on a change, what the producer told us about the hotspot.
|
||||
///
|
||||
/// The counterpart of the producer's own provenance line, and it exists for the case that line
|
||||
/// cannot cover: a message that arrives with no `hot_measured` field at all, where what happens is
|
||||
/// decided by the field's serde default and is otherwise invisible on a running box.
|
||||
///
|
||||
/// The hidden-cursor sentinel is skipped. It is sent with `hot_measured: false` because there is no
|
||||
/// hotspot to describe, so recording it would make every hide/show look like a provenance change.
|
||||
fn note_received_provenance(display: i32, id: u64, hot_measured: bool) {
|
||||
if id == scrap::drm_reader::HIDDEN_CURSOR_ID {
|
||||
return;
|
||||
}
|
||||
if !provenance_is_news_for(display, hot_measured) {
|
||||
return;
|
||||
}
|
||||
if hot_measured {
|
||||
log::info!(
|
||||
"drm: cursor hotspots arrive MEASURED; mapping the point the producer sent. \
|
||||
(a producer that predates the field reads as measured too, on purpose: that \
|
||||
preserves what the old protocol meant)"
|
||||
);
|
||||
} else {
|
||||
log::info!(
|
||||
"drm: cursor hotspots arrive as a GUESS; re-inferring from the upright bitmap"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn fold_cursor_id(id: u64, t: i32) -> u64 {
|
||||
if id == scrap::drm_reader::HIDDEN_CURSOR_ID {
|
||||
id
|
||||
@@ -1783,7 +1862,7 @@ mod drm_capturer_tests {
|
||||
ended: None,
|
||||
}),
|
||||
cv: Condvar::new(),
|
||||
transform: std::sync::atomic::AtomicI32::new(0),
|
||||
cursor_transform: std::sync::atomic::AtomicI32::new(0),
|
||||
}),
|
||||
stop: Arc::new(AtomicBool::new(false)),
|
||||
display: 0,
|
||||
@@ -1922,6 +2001,362 @@ mod drm_capturer_tests {
|
||||
assert_eq!(back, src);
|
||||
}
|
||||
|
||||
/// An upright arrow, tip at (0,0): a 4x6 bitmap, every pixel with x <= y/2 opaque, so the
|
||||
/// opaque box is the left 3 columns. Its top-left corner IS the tip - which is exactly why
|
||||
/// the bare-metal guess works when the sprite is upright, and only then.
|
||||
fn arrow() -> (Vec<u8>, usize, usize) {
|
||||
let (w, h) = (4usize, 6usize);
|
||||
let mut px = vec![0u8; w * h * 4];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if x <= y / 2 {
|
||||
px[(y * w + x) * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
}
|
||||
(px, w, h)
|
||||
}
|
||||
|
||||
/// An I-beam lying along x, deliberately NOT centred in its bitmap: 16x8, opaque rows 2..4 and
|
||||
/// columns 1..13, so the opaque box is (1,2)-(12,3), 12x2 - elongated, which is what Adwaita's
|
||||
/// `vertical-text` shape is. Its click point is the centre of that BOX, (6,2), while the centre
|
||||
/// of the bitmap is (7,3). The offset is the point: a real sprite sits somewhere inside a
|
||||
/// 64x64 hardware buffer (the adwaita box above is (2,6)-(21,14) in a 24x24 one), and a fixture
|
||||
/// centred in its bitmap would let an implementation that returns the bitmap centre pass a test
|
||||
/// claiming to check the box centre.
|
||||
fn ibeam_horizontal() -> (Vec<u8>, usize, usize, (i32, i32)) {
|
||||
let (w, h) = (16usize, 8usize);
|
||||
let mut px = vec![0u8; w * h * 4];
|
||||
for y in 2..4 {
|
||||
for x in 1..13 {
|
||||
px[(y * w + x) * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
(px, w, h, (6, 2))
|
||||
}
|
||||
|
||||
/// The shape at the aspect ratio that actually matters: a 20x9 opaque box, which is what the
|
||||
/// installed Adwaita `vertical-text` measures at 24 px. 2.22:1, only just past the rule's
|
||||
/// factor of two, so it pins the threshold from ABOVE: a stricter rule (say `bw > bh * 3`)
|
||||
/// leaves the 6:1 bars below centred and silently un-centres the real cursor. Placed
|
||||
/// off-centre in a 24x24 buffer like the real one, box (2,6)-(21,14), centre (11,10) - the
|
||||
/// same numbers the theme file gives, against its declared hotspot of (12,11).
|
||||
fn ibeam_theme_aspect() -> (Vec<u8>, usize, usize, (i32, i32)) {
|
||||
let (w, h) = (24usize, 24usize);
|
||||
let mut px = vec![0u8; w * h * 4];
|
||||
for y in 6..15 {
|
||||
for x in 2..22 {
|
||||
px[(y * w + x) * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
(px, w, h, (11, 10))
|
||||
}
|
||||
|
||||
/// The same shape standing up and equally off-centre: 8x16, opaque columns 2..4 and rows 1..13,
|
||||
/// box (2,1)-(3,12), centre (2,6) against a bitmap centre of (3,7). The tall case the guess
|
||||
/// already handled, kept so the symmetric rule cannot pass by breaking it.
|
||||
fn ibeam_vertical() -> (Vec<u8>, usize, usize, (i32, i32)) {
|
||||
let (w, h) = (8usize, 16usize);
|
||||
let mut px = vec![0u8; w * h * 4];
|
||||
for y in 1..13 {
|
||||
for x in 2..4 {
|
||||
px[(y * w + x) * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
(px, w, h, (2, 6))
|
||||
}
|
||||
|
||||
/// What the compositor puts in the cursor plane on an output rotated by `t`: the upright sprite
|
||||
/// rotated forward by t, which is what turning it back by (360 - t) degrees produces.
|
||||
fn as_scanned_out(upright: &[u8], w: usize, h: usize, t: i32) -> (Vec<u8>, usize, usize) {
|
||||
let mut out = Vec::new();
|
||||
unrotate_bgra(upright, w, h, (360 - t) % 360, &mut out);
|
||||
let (dw, dh) = rotated_dims(t, w, h);
|
||||
(out, dw, dh)
|
||||
}
|
||||
|
||||
// rustdesk#15886, the maintainer's physical test: the cursor looked right at 0 and 90, drawn
|
||||
// above the click point at 270, and upside down at 180. Two causes, not one. The sprite came
|
||||
// out upside down at 180 because master turned it only at 90 and 270, so a 180 sprite was
|
||||
// never turned back at all. And at every angle the hotspot was GUESSED on the sprite as
|
||||
// scanned out and only afterwards mapped as if it were a point on it: the guess picks the
|
||||
// top-left of the opaque box, and a turned arrow's tip is not in that corner - at 90 the
|
||||
// error is the arrow's WIDTH along x, small enough to pass as fine; at 270 it is its HEIGHT
|
||||
// along y, which is the one that got reported.
|
||||
//
|
||||
// The 180 entry below is about that mapping, not about what was seen: on master the clamp sent
|
||||
// 180 down the untouched branch, so the guess and the sprite were turned together and the
|
||||
// hotspot landed on the tip anyway - measured as (0,0) there, with only the sprite wrong. What
|
||||
// the loop shows is that the guess is not a point that survives being mapped, at any angle.
|
||||
// This test covers the mapping; the sprite is covered by the two below.
|
||||
#[test]
|
||||
fn a_guessed_hotspot_is_guessed_on_the_upright_sprite() {
|
||||
use scrap::drm_reader::infer_hotspot;
|
||||
let (up, w, h) = arrow();
|
||||
let tip = infer_hotspot(&up, w, h);
|
||||
assert_eq!(tip, (0, 0));
|
||||
let mut old_wrong_at = Vec::new();
|
||||
for t in [90, 180, 270] {
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
|
||||
// The old flow: guess on the scanned-out sprite, then map the point.
|
||||
let (gx, gy) = infer_hotspot(&scan, sw, sh);
|
||||
let old = unrotate_hotspot(t, sw as i32, sh as i32, gx, gy);
|
||||
// The new flow: turn the sprite back first, then guess.
|
||||
let mut turned = Vec::new();
|
||||
unrotate_bgra(&scan, sw, sh, t, &mut turned);
|
||||
let (dw, dh) = rotated_dims(t, sw, sh);
|
||||
assert_eq!(turned, up, "the sprite turns back to upright at {t}");
|
||||
assert_eq!(infer_hotspot(&turned, dw, dh), tip, "the tip is found again at {t}");
|
||||
if old != tip {
|
||||
old_wrong_at.push(t);
|
||||
}
|
||||
}
|
||||
// The old flow is wrong at every angle, not only the one that was noticed.
|
||||
assert_eq!(old_wrong_at, vec![90, 180, 270]);
|
||||
}
|
||||
|
||||
// rustdesk#16242, the maintainer's pixel-level finding: the guess only centred TALL shapes, so
|
||||
// a horizontal I-beam got the corner of its box. Before the rotation rework such a cursor
|
||||
// reached a quarter-turned output as a tall bitmap and the same rule centred it by accident, so
|
||||
// turning the sprite upright first - correct in itself - turned a nearly right hotspot into one
|
||||
// about 11 px out. Measured on the installed Adwaita `vertical-text` at 24 px: theme hotspot
|
||||
// (12, 11), opaque box 20x9, corner guess (2, 6) = 11.2 px away, centre guess (11, 10) = 1.4 px.
|
||||
//
|
||||
// The old flow is not the fix: it was right for this one shape and wrong for arrows at every
|
||||
// angle, which is what the test above pins. The fix is for the guess to centre an elongated box
|
||||
// whichever way it lies, and that is what this checks - for both orientations and at the real
|
||||
// 2.22:1 aspect of the shape that was wrong - by driving `deliver_drm_cursor` and reading the
|
||||
// published hotspot back, not by chaining the helpers itself.
|
||||
/// The upgrade window, end to end from the WIRE rather than from a struct literal.
|
||||
///
|
||||
/// An old root service can be streaming to a freshly started `--server`, and its `DrmCursor`
|
||||
/// carries no `hot_measured` at all. This takes the exact bytes such a producer puts on the
|
||||
/// socket, deserializes them the way the consumer's receive loop does, and drives the real
|
||||
/// delivery path, then reads back what was published. Staging it with two live processes is
|
||||
/// not possible with how the package is built - a `--server` from one build will not run
|
||||
/// inside the other's tree - so this is the honest form of that test, and it runs in CI
|
||||
/// instead of once on somebody's desk.
|
||||
///
|
||||
/// The transform must be non-zero: at 0 the delivery path never consults `hot_measured`, so a
|
||||
/// test at 0 could not tell the two branches apart.
|
||||
/// Two streams with different but STABLE provenance must not read as a change on every
|
||||
/// message. A single global slot did exactly that: display A measured and display B inferred,
|
||||
/// alternating forever, is a normal multi-GPU host and would have logged per cursor message -
|
||||
/// the per-frame logging this was written to avoid. And the hidden-cursor sentinel carries
|
||||
/// `hot_measured: false` because it has no hotspot, so recording it would turn every hide and
|
||||
/// show into a provenance transition.
|
||||
#[test]
|
||||
fn provenance_is_tracked_per_display_and_ignores_the_hidden_cursor() {
|
||||
let (a, b) = (9_510, 9_511);
|
||||
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&a);
|
||||
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&b);
|
||||
|
||||
// First sighting of each is news; the same value again is not.
|
||||
assert!(provenance_is_news_for(a, true));
|
||||
assert!(!provenance_is_news_for(a, true));
|
||||
assert!(provenance_is_news_for(b, false));
|
||||
assert!(!provenance_is_news_for(b, false));
|
||||
|
||||
// The interleaving that a single global slot could not survive.
|
||||
for _ in 0..4 {
|
||||
assert!(!provenance_is_news_for(a, true), "display A is stable");
|
||||
assert!(!provenance_is_news_for(b, false), "display B is stable");
|
||||
}
|
||||
|
||||
// A real change on one display is still reported, and does not disturb the other.
|
||||
assert!(provenance_is_news_for(a, false));
|
||||
assert!(!provenance_is_news_for(b, false));
|
||||
|
||||
// The hidden sentinel is not recorded at all: it would otherwise look like B flipping.
|
||||
note_received_provenance(b, scrap::drm_reader::HIDDEN_CURSOR_ID, true);
|
||||
assert!(
|
||||
!provenance_is_news_for(b, false),
|
||||
"the hidden cursor must not count as a provenance change"
|
||||
);
|
||||
|
||||
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&a);
|
||||
LAST_RECEIVED_PROVENANCE.lock().unwrap().remove(&b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_cursor_message_keeps_the_hotspot_the_old_protocol_meant() {
|
||||
use crate::ipc::Data;
|
||||
|
||||
let (up, w, h, _box_centre) = ibeam_theme_aspect();
|
||||
let t = 90;
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
|
||||
// A hotspot the old producer measured and sent as a point on the scanned-out sprite.
|
||||
let (hotx, hoty) = (3, 5);
|
||||
|
||||
// Exactly what an old producer writes: `Data` is adjacently tagged, and there is no
|
||||
// `hot_measured` key because that build has no such field.
|
||||
let legacy = format!(
|
||||
r#"{{"t":"DrmCursor","c":{{"id":11,"width":{sw},"height":{sh},"hotx":{hotx},"hoty":{hoty}}}}}"#
|
||||
);
|
||||
let (id, mw, mh, mx, my, measured) =
|
||||
match serde_json::from_str::<Data>(&legacy).expect("a legacy DrmCursor must parse") {
|
||||
Data::DrmCursor { id, width, height, hotx, hoty, hot_measured } => {
|
||||
(id, width, height, hotx, hoty, hot_measured)
|
||||
}
|
||||
other => panic!("expected DrmCursor, got {other:?}"),
|
||||
};
|
||||
assert!(measured, "no provenance on the wire must mean what the old protocol meant");
|
||||
|
||||
// The two branches must disagree here, or the assertion below proves nothing.
|
||||
let mapped = unrotate_hotspot(t, mw as i32, mh as i32, mx, my);
|
||||
let mut turned = Vec::new();
|
||||
unrotate_bgra(&scan, sw, sh, t, &mut turned);
|
||||
let (dw, dh) = rotated_dims(t, sw, sh);
|
||||
let reinferred = scrap::drm_reader::infer_hotspot(&turned, dw, dh);
|
||||
assert_ne!(
|
||||
mapped, reinferred,
|
||||
"fixture cannot discriminate: mapping and re-inferring give the same point"
|
||||
);
|
||||
|
||||
let display = 9_400;
|
||||
deliver_drm_cursor(display, 1, id, mw, mh, mx, my, measured, scan, t);
|
||||
let published = {
|
||||
let map = DRM_CURSOR.lock().unwrap();
|
||||
let (_, c) = map.get(&display).expect("the delivery path published nothing");
|
||||
(c.hotx, c.hoty)
|
||||
};
|
||||
assert_eq!(
|
||||
published, mapped,
|
||||
"a legacy message must keep the hotspot the producer sent, transformed as a point; \
|
||||
re-inferring it would move the cursor for the length of an upgrade"
|
||||
);
|
||||
|
||||
// The control: a NEW producer asking for re-inference says so explicitly, and that must
|
||||
// not be swallowed by the default.
|
||||
let modern = format!(
|
||||
r#"{{"t":"DrmCursor","c":{{"id":12,"width":{sw},"height":{sh},"hotx":{hotx},"hoty":{hoty},"hot_measured":false}}}}"#
|
||||
);
|
||||
let Data::DrmCursor { hot_measured, .. } =
|
||||
serde_json::from_str::<Data>(&modern).expect("a modern DrmCursor must parse")
|
||||
else {
|
||||
panic!("expected DrmCursor")
|
||||
};
|
||||
assert!(!hot_measured);
|
||||
let (scan2, _, _) = as_scanned_out(&up, w, h, t);
|
||||
deliver_drm_cursor(display + 1, 1, 12, sw as u32, sh as u32, hotx, hoty, false, scan2, t);
|
||||
let published2 = {
|
||||
let map = DRM_CURSOR.lock().unwrap();
|
||||
let (_, c) = map.get(&(display + 1)).expect("nothing published for the control");
|
||||
(c.hotx, c.hoty)
|
||||
};
|
||||
assert_eq!(
|
||||
published2, reinferred,
|
||||
"an explicit false must still re-infer, or the legacy default has eaten the new \
|
||||
producer's request"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ibeam_keeps_its_centre_whichever_way_it_lies() {
|
||||
use scrap::drm_reader::infer_hotspot;
|
||||
for (i, (name, (up, w, h, box_centre))) in [
|
||||
("horizontal", ibeam_horizontal()),
|
||||
("vertical", ibeam_vertical()),
|
||||
("theme-aspect", ibeam_theme_aspect()),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
// The fixture must not be centred in its own bitmap, or this test cannot tell the
|
||||
// centre of the opaque BOX - which is what the guess computes and what a cursor's
|
||||
// click point is - from the centre of the buffer the sprite happens to sit in.
|
||||
let bitmap_centre = (((w - 1) / 2) as i32, ((h - 1) / 2) as i32);
|
||||
assert_ne!(
|
||||
box_centre, bitmap_centre,
|
||||
"the {name} fixture is centred in its bitmap, so it cannot discriminate"
|
||||
);
|
||||
|
||||
// The upright guess is the centre of the opaque box, not its corner.
|
||||
let guess = infer_hotspot(&up, w, h);
|
||||
assert_eq!(guess, box_centre, "the {name} I-beam is centred, not cornered");
|
||||
|
||||
// And it is what the delivery path PUBLISHES, not just what the helper computes:
|
||||
// `deliver_drm_cursor` is where the guessed branch is chosen and where the sprite is
|
||||
// turned back, so the sprite is handed over pre-rotated exactly as the compositor
|
||||
// scans it out, and the published hotspot is read back out of DRM_CURSOR.
|
||||
for (j, t) in [0, 90, 180, 270].into_iter().enumerate() {
|
||||
let display = 9_300 + (i * 8 + j) as i32;
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
|
||||
// What the producer actually sends for a guessed hotspot: its own guess, made on
|
||||
// the sprite AS SCANNED OUT (drm_reader does exactly that). At 0 the delivery path
|
||||
// publishes it unchanged, which is why it has to be the real value and not a
|
||||
// placeholder; at every other angle the path discards it and guesses again.
|
||||
let (phx, phy) = scrap::drm_reader::infer_hotspot(&scan, sw, sh);
|
||||
deliver_drm_cursor(display, 1, 7, sw as u32, sh as u32, phx, phy, false, scan, t);
|
||||
let map = DRM_CURSOR.lock().unwrap();
|
||||
let (_, c) = map.get(&display).expect("the cursor path published nothing");
|
||||
assert_eq!(
|
||||
(c.width as usize, c.height as usize),
|
||||
(w, h),
|
||||
"the published {name} sprite is upright-sized at {t}"
|
||||
);
|
||||
assert_eq!(c.colors, up, "the published {name} sprite is upright at {t}");
|
||||
assert_eq!(
|
||||
(c.hotx, c.hoty),
|
||||
box_centre,
|
||||
"the published {name} hotspot is the box centre at {t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The arrow is untouched, and it sits exactly ON the boundary rather than safely inside
|
||||
// it: its box is 3x6, which is the factor of two itself, so it keeps its tip only because
|
||||
// the comparison is strict. That makes it the control for the other side of the threshold
|
||||
// - loosen the rule to `* 1` and this line fails, tighten it past 2.22 and the
|
||||
// theme-aspect case above fails. The two together pin where the boundary is.
|
||||
let (arrow_px, aw, ah) = arrow();
|
||||
assert_eq!(infer_hotspot(&arrow_px, aw, ah), (0, 0));
|
||||
}
|
||||
|
||||
/// NOT a general DRM/Wayland contract, and should not be read as one. This pins the behaviour
|
||||
/// MEASURED on i915 advertising rotate-180 with mutter: the primary plane scans out already
|
||||
/// upright while the compositor pre-rotates the cursor sprite, and `wl_output` cannot tell
|
||||
/// hardware rotation from compositor rotation, so the frame is left alone and the sprite is
|
||||
/// turned. Arch with KDE Plasma is still wrong at 180, which is exactly why this is scoped to
|
||||
/// what was measured rather than stated as a rule. The robust fix is to propagate the actual
|
||||
/// KMS plane rotation instead of inferring both from the `wl_output` transform; until then,
|
||||
/// changing this test means re-measuring on the compositor in question, not reasoning from it.
|
||||
#[test]
|
||||
fn a_180_output_turns_the_cursor_but_not_the_frame_on_i915_plus_mutter() {
|
||||
assert_eq!(frame_transform(180), 0);
|
||||
assert_eq!(frame_transform(90), 90);
|
||||
assert_eq!(frame_transform(270), 270);
|
||||
let (up, w, h) = arrow();
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, 180);
|
||||
let mut turned = Vec::new();
|
||||
unrotate_bgra(&scan, sw, sh, 180, &mut turned);
|
||||
assert_eq!(turned, up);
|
||||
}
|
||||
|
||||
// The two above exercise the helpers, which cannot see WHICH angle the cursor path is handed
|
||||
// or whether it turns 180 at all - the line that decides both is `if t != 0` in
|
||||
// `deliver_drm_cursor`, and reverting it to master's `t == 90 || t == 270` leaves every helper
|
||||
// assertion above still passing. So this drives the real path and reads back what it published.
|
||||
#[test]
|
||||
fn the_cursor_path_publishes_an_upright_sprite_at_every_angle() {
|
||||
let (up, w, h) = arrow();
|
||||
for (i, t) in [0, 90, 180, 270].into_iter().enumerate() {
|
||||
// A display id of its own per angle: DRM_CURSOR is process-wide and keyed by display.
|
||||
let display = 9_100 + i as i32;
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
|
||||
deliver_drm_cursor(display, 1, 7, sw as u32, sh as u32, 0, 0, false, scan, t);
|
||||
let map = DRM_CURSOR.lock().unwrap();
|
||||
let (_, c) = map.get(&display).expect("the cursor path published nothing");
|
||||
assert_eq!(
|
||||
(c.width as usize, c.height as usize),
|
||||
(w, h),
|
||||
"the published sprite is upright-sized at {t}"
|
||||
);
|
||||
assert_eq!(c.colors, up, "the published sprite is upright at {t}");
|
||||
assert_eq!((c.hotx, c.hoty), (0, 0), "the tip is the hotspot at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrotate_180_reverses_both_axes() {
|
||||
let (src, w, h) = px_frame(&[&[1, 2, 3], &[4, 5, 6]], 0);
|
||||
@@ -2390,4 +2825,349 @@ mod drm_capturer_tests {
|
||||
assert!(demote_cooldown(1) + burn < Duration::from_secs(40));
|
||||
assert!(demote_cooldown(5) + burn > Duration::from_secs(8 * 60));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// rustdesk#16242 round 2: the measurement behind the inference model.
|
||||
//
|
||||
// The question a synthetic fixture cannot answer: when the driver publishes no hotspot and
|
||||
// the sprite has to be turned upright before guessing, how far from the THEME's real click
|
||||
// point does each flow land? Both flows are driven here, per shape and per angle, against
|
||||
// the hotspot the theme author wrote into the cursor file. It reads the installed Adwaita
|
||||
// theme, so it prints instead of asserting and is ignored by default:
|
||||
//
|
||||
// cargo test --features drm --lib drm_capturer_tests::adwaita -- --ignored --nocapture
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
/// Minimal Xcursor reader. The format is a 16-byte header, a table of contents of 12-byte
|
||||
/// entries, and one chunk per (nominal size, animation frame); an image chunk is 36 bytes of
|
||||
/// header followed by width*height little-endian ARGB words, so byte 3 of each pixel is the
|
||||
/// alpha `infer_hotspot` reads. Only the FIRST frame of each nominal size is taken.
|
||||
fn xcursor_images(path: &std::path::Path) -> Vec<(u32, usize, usize, i32, i32, Vec<u8>)> {
|
||||
let b = match std::fs::read(path) {
|
||||
Ok(b) => b,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
let u32at = |o: usize| -> u32 {
|
||||
if o + 4 > b.len() {
|
||||
0
|
||||
} else {
|
||||
u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])
|
||||
}
|
||||
};
|
||||
if b.len() < 16 || &b[0..4] != b"Xcur" {
|
||||
return Vec::new();
|
||||
}
|
||||
let (hdr, ntoc) = (u32at(4) as usize, u32at(12) as usize);
|
||||
let mut out: Vec<(u32, usize, usize, i32, i32, Vec<u8>)> = Vec::new();
|
||||
for i in 0..ntoc {
|
||||
let e = hdr + i * 12;
|
||||
if u32at(e) != 0xfffd_0002 {
|
||||
continue;
|
||||
}
|
||||
let nominal = u32at(e + 4);
|
||||
if out.iter().any(|(n, ..)| *n == nominal) {
|
||||
continue;
|
||||
}
|
||||
let p = u32at(e + 8) as usize;
|
||||
let (w, h) = (u32at(p + 16) as usize, u32at(p + 20) as usize);
|
||||
let (xhot, yhot) = (u32at(p + 24) as i32, u32at(p + 28) as i32);
|
||||
let px = p + 36;
|
||||
if w == 0 || h == 0 || px.saturating_add(w * h * 4) > b.len() {
|
||||
continue;
|
||||
}
|
||||
out.push((nominal, w, h, xhot, yhot, b[px..px + w * h * 4].to_vec()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn dist(a: (i32, i32), b: (i32, i32)) -> f64 {
|
||||
let (dx, dy) = ((a.0 - b.0) as f64, (a.1 - b.1) as f64);
|
||||
(dx * dx + dy * dy).sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn adwaita_hotspot_survey() {
|
||||
let dir = std::env::var("SURVEY_DIR")
|
||||
.unwrap_or_else(|_| "/usr/share/icons/Adwaita/cursors".to_owned());
|
||||
let dir = std::path::Path::new(&dir);
|
||||
let mut names: Vec<String> = std::fs::read_dir(dir)
|
||||
.expect("no installed Adwaita cursors to measure")
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
names.sort();
|
||||
let want: u32 = std::env::var("SURVEY_SIZE")
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(24);
|
||||
let mut display = 20_000;
|
||||
println!("SURVEY size={want}");
|
||||
println!("shape,size,w,h,truth_x,truth_y,box,t,sent_x,sent_y,base_x,base_y,base_err,head_x,head_y,head_err,master_x,master_y,master_err");
|
||||
for name in &names {
|
||||
let imgs = xcursor_images(&dir.join(name));
|
||||
let Some((n, w, h, tx, ty, up)) = imgs.into_iter().find(|(n, ..)| *n == want) else {
|
||||
println!("# {name}: no {want} px image");
|
||||
continue;
|
||||
};
|
||||
// The opaque box, to tell the shapes apart afterwards.
|
||||
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
|
||||
for (i, px) in up.chunks_exact(4).take(w * h).enumerate() {
|
||||
if px[3] >= 128 {
|
||||
let (x, y) = ((i % w) as i32, (i / w) as i32);
|
||||
minx = minx.min(x);
|
||||
maxx = maxx.max(x);
|
||||
miny = miny.min(y);
|
||||
maxy = maxy.max(y);
|
||||
}
|
||||
}
|
||||
let bx = format!("{}x{}+{}+{}", maxx - minx + 1, maxy - miny + 1, minx, miny);
|
||||
for t in [0, 90, 180, 270] {
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
|
||||
// What the producer puts on the wire: the guess taken on the sprite as the plane
|
||||
// holds it, with hot_measured false.
|
||||
let sent = scrap::drm_reader::infer_hotspot(&scan, sw, sh);
|
||||
// The flow before this PR: map that point back as if it were a pixel.
|
||||
let base = unrotate_hotspot(t, sw as i32, sh as i32, sent.0, sent.1);
|
||||
// The flow in this PR, read back from the real delivery path.
|
||||
display += 1;
|
||||
deliver_drm_cursor(display, 1, 1, sw as u32, sh as u32, sent.0, sent.1, false, scan, t);
|
||||
let head = {
|
||||
let map = DRM_CURSOR.lock().unwrap();
|
||||
let (_, c) = map.get(&display).expect("nothing published");
|
||||
(c.hotx, c.hoty)
|
||||
};
|
||||
let m = master_delivered(&up, w, h, t);
|
||||
println!(
|
||||
"{name},{n},{w},{h},{tx},{ty},{bx},{t},{},{},{},{},{:.2},{},{},{:.2},{},{},{:.2}",
|
||||
sent.0, sent.1, base.0, base.1, dist(base, (tx, ty)),
|
||||
head.0, head.1, dist(head, (tx, ty)),
|
||||
m.0, m.1, dist(m, (tx, ty))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------------------
|
||||
// rustdesk#16242 round 2: the guess measured against the hotspots a THEME declares.
|
||||
//
|
||||
// Every test above builds its own sprite, so all of them compare the guess with the guess.
|
||||
// That can pin a mapping but it cannot say whether the guess is any good. These two read the
|
||||
// expected value from the cursor theme instead - the click point its author wrote into the
|
||||
// file, which is exactly what a compositor programs into HOTSPOT_X/Y when it has the
|
||||
// property to program.
|
||||
// -----------------------------------------------------------------------------------------
|
||||
|
||||
include!("drm_cursor_theme.rs");
|
||||
|
||||
/// Expand a fixture's packed alpha mask into the sprite the delivery path takes. Only alpha
|
||||
/// is set: the guess reads nothing else.
|
||||
fn theme_sprite(mask_hex: &str, w: usize, h: usize) -> Vec<u8> {
|
||||
let bytes: Vec<u8> = (0..mask_hex.len() / 2)
|
||||
.map(|i| u8::from_str_radix(&mask_hex[i * 2..i * 2 + 2], 16).expect("fixture hex"))
|
||||
.collect();
|
||||
let mut px = vec![0u8; w * h * 4];
|
||||
for i in 0..w * h {
|
||||
if bytes[i / 8] & (0x80 >> (i % 8)) != 0 {
|
||||
px[i * 4 + 3] = 255;
|
||||
}
|
||||
}
|
||||
px
|
||||
}
|
||||
|
||||
/// The guess MASTER ships, frozen. Only a TALL box is centred there: the symmetric aspect
|
||||
/// test came later, in this PR, so freezing that instead would measure this PR against its own
|
||||
/// earlier revision rather than against what is merged.
|
||||
fn master_guess(rgba: &[u8], w: usize, h: usize) -> (i32, i32) {
|
||||
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
|
||||
for (i, px) in rgba.chunks_exact(4).take(w * h).enumerate() {
|
||||
if px[3] >= 128 {
|
||||
let (x, y) = ((i % w) as i32, (i / w) as i32);
|
||||
minx = minx.min(x);
|
||||
maxx = maxx.max(x);
|
||||
miny = miny.min(y);
|
||||
maxy = maxy.max(y);
|
||||
}
|
||||
}
|
||||
if maxx < minx || maxy < miny {
|
||||
return (0, 0);
|
||||
}
|
||||
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
|
||||
if bh > bw * 2 {
|
||||
((minx + maxx) / 2, (miny + maxy) / 2)
|
||||
} else {
|
||||
(minx, miny)
|
||||
}
|
||||
}
|
||||
|
||||
/// What master DELIVERS for an upright sprite on an output turned by `t`: it guesses on the
|
||||
/// sprite as the plane holds it and then maps that point as if it were a pixel, and it does
|
||||
/// that only at 90 and 270 - 0 and 180 pass through untouched.
|
||||
fn master_delivered(up: &[u8], w: usize, h: usize, t: i32) -> (i32, i32) {
|
||||
let (scan, sw, sh) = as_scanned_out(up, w, h, t);
|
||||
let (gx, gy) = master_guess(&scan, sw, sh);
|
||||
if t == 90 || t == 270 {
|
||||
unrotate_hotspot(t, sw as i32, sh as i32, gx, gy)
|
||||
} else {
|
||||
(gx, gy)
|
||||
}
|
||||
}
|
||||
|
||||
fn away(a: (i32, i32), b: (i32, i32)) -> f64 {
|
||||
(((a.0 - b.0) as f64).powi(2) + ((a.1 - b.1) as f64).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
/// A hotspot names a point on the SHAPE, so the same sprite has to get the same click point
|
||||
/// whatever angle the output happens to sit at. This drives the real delivery path for every
|
||||
/// shape in the theme at all four angles and demands exactly that.
|
||||
///
|
||||
/// The maintainer's objection on this PR was a table of four shapes where the old flow landed
|
||||
/// closer than the new one. It did, at some angles - and 16 to 19 px out at the others, which
|
||||
/// is what the second half of this test measures: with the old flow not one of the 35 shapes
|
||||
/// keeps its hotspot across the four angles, and the point moves by 15 px on average. That
|
||||
/// number is also the control. Without it the first assertion would still pass on a revert,
|
||||
/// since a flow that is wrong the same way at every angle is consistent too.
|
||||
#[test]
|
||||
fn a_published_hotspot_does_not_move_when_the_output_turns() {
|
||||
let mut display = 21_000;
|
||||
let (mut spread_sum, mut spread_max, mut spread_zero) = (0f64, 0f64, 0usize);
|
||||
for &(name, w, h, _, _, mask) in THEME_SHAPES {
|
||||
let (w, h) = (w as usize, h as usize);
|
||||
let up = theme_sprite(mask, w, h);
|
||||
let (mut published, mut mapped) = (Vec::new(), Vec::new());
|
||||
for t in [0, 90, 180, 270] {
|
||||
let (scan, sw, sh) = as_scanned_out(&up, w, h, t);
|
||||
// What the producer puts on the wire: the guess taken on the sprite as the plane
|
||||
// holds it, with no provenance behind it.
|
||||
let sent = scrap::drm_reader::infer_hotspot(&scan, sw, sh);
|
||||
mapped.push(unrotate_hotspot(t, sw as i32, sh as i32, sent.0, sent.1));
|
||||
display += 1;
|
||||
deliver_drm_cursor(
|
||||
display, 1, 1, sw as u32, sh as u32, sent.0, sent.1, false, scan, t,
|
||||
);
|
||||
let map = DRM_CURSOR.lock().unwrap();
|
||||
let (_, c) = map.get(&display).expect("the delivery path published nothing");
|
||||
published.push((c.hotx, c.hoty));
|
||||
}
|
||||
assert!(
|
||||
published.windows(2).all(|p| p[0] == p[1]),
|
||||
"{name}: the published hotspot follows the output angle: {published:?}"
|
||||
);
|
||||
let spread = mapped
|
||||
.iter()
|
||||
.flat_map(|a| mapped.iter().map(move |b| away(*a, *b)))
|
||||
.fold(0f64, f64::max);
|
||||
spread_sum += spread;
|
||||
spread_max = spread_max.max(spread);
|
||||
if spread == 0.0 {
|
||||
spread_zero += 1;
|
||||
}
|
||||
}
|
||||
// The control, and it has to be read with the guess this PR now makes. A box centre and a
|
||||
// heavier-half extreme both map like a pixel, so for the 16 shapes that land on one the
|
||||
// old flow happens to be angle-independent too. The other 19 move, by up to 26.87 px on a
|
||||
// 24 px sprite. Without this the assertion above would also pass on a revert: a flow that
|
||||
// is wrong the same way at every angle is consistent too.
|
||||
let n = THEME_SHAPES.len();
|
||||
assert!(
|
||||
n - spread_zero >= 15,
|
||||
"the control has gone vacuous: the old flow now keeps {spread_zero} of {n} shapes \
|
||||
stable, so the assertion above no longer separates the two flows"
|
||||
);
|
||||
assert!(
|
||||
spread_sum / n as f64 > 5.0 && spread_max > 20.0,
|
||||
"the control is weak: old-flow spread mean {:.2} max {:.2} over {n} shapes",
|
||||
spread_sum / n as f64,
|
||||
spread_max
|
||||
);
|
||||
}
|
||||
|
||||
/// How far the delivered hotspot lands from the click point the theme declares, per shape,
|
||||
/// measured against MASTER and not against an earlier revision of this PR.
|
||||
///
|
||||
/// Master handles 0, 90 and 270 for the cursor (180 passes through untouched there), so the
|
||||
/// comparison is over those three angles, which is the set master actually covers.
|
||||
///
|
||||
/// Two shapes stay further out than master and they are named rather than averaged away.
|
||||
/// `help` is the honest limit of any bitmap rule: the theme puts its click point on the dot of
|
||||
/// its question mark, which is not recoverable from alpha. `alias` is 0.51 px. Everything else
|
||||
/// is equal or better, and the mean over the corpus falls from 12.08 px to 4.20.
|
||||
#[test]
|
||||
fn no_shape_lands_further_from_the_theme_than_master_except_the_two_no_bitmap_can_reach() {
|
||||
const NOT_INFERABLE: [&str; 2] = ["help", "alias"];
|
||||
let (mut sum_master, mut sum_now) = (0f64, 0f64);
|
||||
let mut regressed = Vec::new();
|
||||
for &(name, w, h, hx, hy, mask) in THEME_SHAPES {
|
||||
let (w, h) = (w as usize, h as usize);
|
||||
let up = theme_sprite(mask, w, h);
|
||||
let truth = (hx, hy);
|
||||
let angles = [0, 90, 270];
|
||||
let mut e_master = 0f64;
|
||||
let mut e_now = 0f64;
|
||||
for t in angles {
|
||||
e_master += away(master_delivered(&up, w, h, t), truth);
|
||||
// The upright inference answers the same at every angle by construction; the
|
||||
// angle-independence test above is what pins that.
|
||||
e_now += away(scrap::drm_reader::infer_hotspot(&up, w, h), truth);
|
||||
}
|
||||
let (e_master, e_now) = (e_master / angles.len() as f64, e_now / angles.len() as f64);
|
||||
sum_master += e_master;
|
||||
sum_now += e_now;
|
||||
if e_now > e_master + 0.005 && !NOT_INFERABLE.contains(&name) {
|
||||
regressed.push((name, e_master, e_now));
|
||||
}
|
||||
}
|
||||
let n = THEME_SHAPES.len() as f64;
|
||||
assert!(
|
||||
regressed.is_empty(),
|
||||
"further from the theme hotspot than master, averaged over 0/90/270: {regressed:?}"
|
||||
);
|
||||
assert!(
|
||||
sum_now / n <= 4.5 && sum_master / n >= 11.0,
|
||||
"mean error over {n} shapes: master {:.2}, this pr {:.2} (measured 12.08 and 4.20)",
|
||||
sum_master / n,
|
||||
sum_now / n
|
||||
);
|
||||
}
|
||||
|
||||
/// The two shapes the test above excuses are excused for a measured reason, not because they
|
||||
/// were in the way, and the excuse is bounded in BOTH directions it could grow: the average
|
||||
/// over the angles master handles, and the worst single angle. The worst angle is the bigger
|
||||
/// number and the one that would be felt - `help` at 270 is 8.00 px under master and 21.54
|
||||
/// here - so leaving it unbounded would let the exemption widen quietly.
|
||||
#[test]
|
||||
fn the_two_excused_shapes_are_excused_by_how_much() {
|
||||
// (shape, mean excess allowed, worst single-angle excess allowed). Measured: alias 0.51
|
||||
// mean and 8.94 at 90; help 4.73 mean and 13.54 at 270.
|
||||
for (name, mean_bound, angle_bound) in [("alias", 0.75f64, 9.5f64), ("help", 5.5, 14.5)] {
|
||||
let &(_, w, h, hx, hy, mask) = THEME_SHAPES
|
||||
.iter()
|
||||
.find(|s| s.0 == name)
|
||||
.expect("the corpus must carry the excused shapes");
|
||||
let (w, h) = (w as usize, h as usize);
|
||||
let up = theme_sprite(mask, w, h);
|
||||
let truth = (hx, hy);
|
||||
let now = away(scrap::drm_reader::infer_hotspot(&up, w, h), truth);
|
||||
let angles = [0, 90, 270];
|
||||
let mut worst = f64::MIN;
|
||||
let mut total = 0f64;
|
||||
for t in angles {
|
||||
let m = away(master_delivered(&up, w, h, t), truth);
|
||||
total += m;
|
||||
worst = worst.max(now - m);
|
||||
}
|
||||
let mean_excess = now - total / angles.len() as f64;
|
||||
assert!(
|
||||
mean_excess <= mean_bound,
|
||||
"{name} averages {mean_excess:.2} px worse than master, over the {mean_bound} \
|
||||
this excuses"
|
||||
);
|
||||
assert!(
|
||||
worst <= angle_bound,
|
||||
"{name} is {worst:.2} px worse than master at its worst angle, over the \
|
||||
{angle_bound} this excuses"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Generated from the installed cursor theme by `adwaita_hotspot_survey` (the ignored test in
|
||||
// `drm_capturer.rs`); see its doc comment for the command. adwaita-icon-theme 50.0-1, every shape
|
||||
// the theme ships as a real file, at its 24 px nominal size - the GNOME default cursor size.
|
||||
//
|
||||
// Each entry is the shape name, the hotspot the THEME declares, and the sprite's alpha mask: one
|
||||
// bit per pixel, row-major, most significant bit first, set where alpha >= 128. The mask is all
|
||||
// the hotspot guess reads, and rotating a mask is exact, so it is the whole fixture.
|
||||
//
|
||||
// The point of carrying these is that the expected value comes from the theme author, not from
|
||||
// our own heuristic: a test that compares the guess against the guess cannot say whether the
|
||||
// guess is right.
|
||||
const THEME_SHAPES: &[(&str, u32, u32, i32, i32, &str)] = &[
|
||||
("X_cursor", 24, 24, 11, 12, "00000000000000000000000000000001830003c78007ffc007ffc007ffc003ff8001ff0001ff8003ff8007ffc007ffc003ef8003c780000000000000000000000000000000000000"),
|
||||
("alias", 24, 24, 18, 5, "00000000000000000001ffc000ffc0007fc0003fc0007fc0007fc000ffc000ffc001fdc001f8c001f04001e00001e00001e00000e00000e000007000003000000000000000000000"),
|
||||
("all-resize", 24, 24, 12, 11, "001800003c00007e0000ff0001ff8003ffc007ffe00f3cf01f3cf83ffffc7ffffe7ffffe3ffffc1f3cf80f3cf007ffe003ffc001ff8000ff00007e00003c00001800000000000000"),
|
||||
("all-scroll", 24, 24, 11, 11, "00000000300000780000fc0001fe0003ff0007ff800e01c01e79e03efdf07efdf87efdf83efdf01e79e00e01c007ff8003ff0001fe0000fc00007800003000000000000000000000"),
|
||||
("cell", 24, 24, 11, 11, "0000000078000078000078000078000078000078000078000030007f03f87f87f87f87f87f03f8003000007800007800007800007800007800007800007800000000000000000000"),
|
||||
("col-resize", 24, 24, 12, 12, "0000000038000038000038000038000139000339800739c00f39e01ffff03ffff87ffffc3ffff83ffff80f39f00739e00739c0013900003800003800003800003800000000000000"),
|
||||
("context-menu", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f00001f80001fc0001fe7fe1ff7fe1ffffe1ffffe1ffffe1fe7fe1fe7fe1ff7fe1df7fe10fffe00fffe007ffe007800000000000000"),
|
||||
("copy", 24, 24, 3, 1, "0000000000000000001000001800001c00001e00001f00001f80001fc0001fe3c01ffff01ffff81ffff81ffffc1f3ffc1e3ffc1c3ffc183ffc101ff8000ff00007e0000000000000"),
|
||||
("crosshair", 24, 24, 11, 11, "0000000078000078000078000078000078000078000078000078007ffff87ffff87ffff87ffff8007800007800007800007800007800007800007800007800000000000000000000"),
|
||||
("default", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f00001f80001fc0001fe0001ff0001ff8001ffc001ffe001fe0001fe0001ff0001df00010f80000f800007800007800000000000000"),
|
||||
("e-resize", 24, 24, 19, 13, "000000000000000000000000000078001078001878001c78001e78001f781ffff81ffff81ffff81ffff81ffff8001ff8001e78001c78001878001078000078000000000000000000"),
|
||||
("ew-resize", 24, 24, 12, 12, "0000000000000000000000000000000081000181800381c00781e00ffff01ffff83ffffc1ffff81ffff80781f00381e00381c0008100000000000000000000000000000000000000"),
|
||||
("grab", 24, 24, 11, 2, "000000000000001800003c0000ff0001ff8001ffe001fff001fff001fff001fff001fff00dfff01ffff01ffff00ffff00ffff007fff007fff003fff001fff000ffe0000000000000"),
|
||||
("grabbing", 24, 24, 9, 5, "000000000000000000000000000000001f0000ff8001ffe001fff007fff00ffff00ffff00ffff00ffff007fff007fff003fff003fff001ffe0000000000000000000000000000000"),
|
||||
("help", 24, 24, 12, 21, "000000007e0001ff8003ffc007ffc007ffe00fc7e00fc7e00fc7e0000fe0003fc0003f80007f00007e00007c00007c00000000007c00007c00007c00007c00007c00000000000000"),
|
||||
("n-resize", 24, 24, 13, 6, "0000000000000000000ffff80ffff80ffff80ffff8007f00007f0000ff8001ffc003ffe007fff0003e00003e00003e00003e00003e00003e00003e00003e00000000000000000000"),
|
||||
("ne-resize", 24, 24, 15, 10, "0000000000000000000000001ffff01ffff01ffff01ffff00000f00ffef007fef003fef001fef001fef003fef007fef00ffef01fcef01f86f01f02f01e00f00c0000000000000000"),
|
||||
("nesw-resize", 24, 24, 11, 11, "00000000000000000000ffc0007fc0003fc0003fc0003fc0107fc018ffc01dffc01ff9c01ff0401fe0001fe0001fe0001ff0001ff800000000000000000000000000000000000000"),
|
||||
("no-drop", 24, 24, 3, 1, "0000000000000000001000001800001c00001e00001f00001f80001fc0001fe3c01ffff01ffff81ffff81ffffc1f3ffc1e3ffc1c3ffc183ffc101ff8000ff00007e0000000000000"),
|
||||
("not-allowed", 24, 24, 12, 12, "000000000000000000007e0001ff8003ffc007ffe00ffff00ffff01ffff81ffff81ffff81ffff81ffff81ffff80ffff00ffff007ffe003ffc001ff8000ff00000000000000000000"),
|
||||
("ns-resize", 24, 24, 12, 13, "000000000000001000003800007c0000fe0001ff0003ff8007ffc0007c00007c00007c00007c00007c00007c0007ffc003ff8001ff8001ff0000fe00007c00003800000000000000"),
|
||||
("nw-resize", 24, 24, 10, 10, "0000000000000000000000000ffff80ffff80ffff80ffff80f00000f7ff00f7fe00f7fc00f7f800f7f800f7fc00f7fe00f7ff00f73f80f61f80f40f80f0078000030000000000000"),
|
||||
("nwse-resize", 24, 24, 11, 11, "0000000000000000001ff8001ff0001ff0001fe0001fe0001ff0401ff8c01ffdc01cffc0107fc0003fc0003fc0003fc0007fc000ffc0000000000000000000000000000000000000"),
|
||||
("pointer", 24, 24, 7, 5, "00000000000000000000000000c00001e00001e00001e00001e00001ff0001ffe001fff001fff01dfff03ffff03ffff01ffff00ffff007fff003fff001fff000ffe0000000000000"),
|
||||
("progress", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f3e001fff801fffc01fffc01fffe01fffe01fffe01fffe01fffe01fffc01fffc01cff80103f00000000000000000000000000000000"),
|
||||
("row-resize", 24, 24, 12, 13, "000000001000003800007c0000fe0001ff0003ff8007ffc0007c00007c007ffffc7ffffc7ffffc007c00007c0007ffc003ff8001ff8000ff00007e00007c00003800000000000000"),
|
||||
("s-resize", 24, 24, 13, 18, "000000000000003e00003e00003e00003e00003e00003e00003e00003e0007fff003ffe001ffc000ff80007f00003e000ffff80ffff80ffff80ffff8000000000000000000000000"),
|
||||
("se-resize", 24, 24, 15, 15, "0000000000000000001e00f01f02f01f86f01fcef00ffef007fef003fef001fef001fef003fef007fef00ffef00000f01ffff01ffff01ffff01ffff0000000000000000000000000"),
|
||||
("sw-resize", 24, 24, 10, 15, "0000000000000000000f00780f40f80f61f80f73f80f7ff00f7fe00f7fc00f7f800f7f800f7fc00f7fe00f7ff00f00000ffff80ffff80ffff80ffff8000000000000000000000000"),
|
||||
("text", 24, 24, 11, 12, "00000000000003de0003fe0003fe0000700000700000700000700000700000700000700000700000700000700000700000700000700000700003fe0003fe0003fe00000000000000"),
|
||||
("vertical-text", 24, 24, 12, 11, "00000000000000000000000000000000000038001c38001c38001c3ffffc3ffffc3ffffc38001c38001c38001c000000000000000000000000000000000000000000000000000000"),
|
||||
("w-resize", 24, 24, 6, 13, "0000000000000000000000001e00001e08001e18001e38001e78001ef8001ffff81ffff81ffff81ffff81ffff81ff8001e78001e38001e18001e08001e0000000000000000000000"),
|
||||
("wait", 24, 24, 11, 11, "000000000000000000007e0001ff8003ffc007ffe00ffff00ffff01ffff81ffff81ffff81ffff81ffff81ffff80ffff00ffff007ffe003ffc001ff8000ff00000000000000000000"),
|
||||
("zoom-in", 24, 24, 11, 10, "00000000000000000000fc0003ff0007ff800fffc00fffc01fffe01fffe01fffe01fffe01fffe01fffe00fffc00fffc007ffe003ffe000fff00000f80000f8000078000000000000"),
|
||||
("zoom-out", 24, 24, 11, 10, "000000000000000000007e0001ff8003ffc007ffe007ffe00ffff00ffff00ffff00ffff00ffff00ffff007ffe007ffe003fff001fff0007ff800007c00007c00003c000000000000"),
|
||||
];
|
||||
Reference in New Issue
Block a user