Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fada664df7 | ||
|
|
9d3ae7acd2 | ||
|
|
a7f2260203 | ||
|
|
40a4aa34c8 | ||
|
|
0c18a8cbc9 | ||
|
|
4812a9815b | ||
|
|
b6b11fd9b1 | ||
|
|
d1722c5d6d | ||
|
|
0d49ead0c3 | ||
|
|
be9b96cf65 | ||
|
|
89fcf56c4e | ||
|
|
8a76628007 | ||
|
|
b5d8b979d8 | ||
|
|
44683d108b | ||
|
|
50258e21e9 | ||
|
|
47a2a3c83d | ||
|
|
17feabbcab | ||
|
|
08affc69c4 | ||
|
|
e9ddbd8f46 | ||
|
|
bb924d2939 | ||
|
|
134af545ae | ||
|
|
417e3bdd2c | ||
|
|
483cc10266 | ||
|
|
efec124c52 | ||
|
|
341193290e | ||
|
|
f299fb9906 | ||
|
|
58ff78a823 | ||
|
|
a8ae0d6d66 | ||
|
|
2e333f64a4 | ||
|
|
e424b57fca | ||
|
|
b30f781fd6 | ||
|
|
68a35e65f2 | ||
|
|
7c21b4569c | ||
|
|
c6a358afbe | ||
|
|
458ffe44c6 | ||
|
|
2e7255f083 | ||
|
|
12f61b1fda | ||
|
|
6a0eb9a1fd | ||
|
|
763d4eeb05 | ||
|
|
a5d4ef97e8 | ||
|
|
dd9b21cf86 | ||
|
|
97811acbdd | ||
|
|
7a367f7cc6 | ||
|
|
ea04f04f9d | ||
|
|
ef00ed78a7 | ||
|
|
5278fcab68 | ||
|
|
53ec874c39 | ||
|
|
04974591b8 | ||
|
|
4da167517e | ||
|
|
d4ac2c07b7 | ||
|
|
0b3a1ddd80 | ||
|
|
01e3917390 | ||
|
|
fd0fe592eb | ||
|
|
bedf64c8d3 | ||
|
|
4df7404a6c | ||
|
|
f4808b71d4 | ||
|
|
0ac2e7fb52 | ||
|
|
092a961b62 | ||
|
|
4f56d6957a | ||
|
|
f312b57909 | ||
|
|
f9c2f16857 | ||
|
|
8154c026a4 | ||
|
|
28269af9c7 | ||
|
|
20e25e743d | ||
|
|
851d2df88c | ||
|
|
be757de462 | ||
|
|
a437eb9bc6 | ||
|
|
39d4f1854b | ||
|
|
bd028ad350 | ||
|
|
b48fe17b52 | ||
|
|
82b6fc2f3b | ||
|
|
29772f6595 | ||
|
|
d0ee56d349 | ||
|
|
4515cd6463 | ||
|
|
9b5f342839 | ||
|
|
cdcb4d4b4c | ||
|
|
34c340be4e | ||
|
|
9f60bb6fc5 | ||
|
|
5d7e20103a | ||
|
|
e4b9594c5e | ||
|
|
8b716c7046 | ||
|
|
70d45051f6 | ||
|
|
bf1ebe5be2 | ||
|
|
3c7c13d79d | ||
|
|
e54f21e10c | ||
|
|
e82dd12350 | ||
|
|
d5311574be | ||
|
|
0843447c41 | ||
|
|
67e0a1f582 | ||
|
|
91c9fccbb0 | ||
|
|
c4221469d8 | ||
|
|
978e2e28b9 |
@@ -374,6 +374,12 @@ jobs:
|
||||
|
||||
- name: Add MSBuild to PATH
|
||||
uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # v2
|
||||
with:
|
||||
# Select the MSBuild process architecture; -p:Platform sets the MSI target.
|
||||
# Native ARM64 tools give the compiler more address space for PCH files
|
||||
# (C3859/C1076 were reported by HostX86\arm64\CL.exe).
|
||||
# Keep the action's default x86 MSBuild for the existing x64 MSI job.
|
||||
msbuild-architecture: ${{ matrix.job.arch == 'aarch64' && 'arm64' || 'x86' }}
|
||||
|
||||
- name: Build msi
|
||||
# Builds the MSI for the matrix arch. res/msi (WiX v4 + native CustomActions) carries
|
||||
@@ -492,11 +498,20 @@ jobs:
|
||||
version: ${{ env.LLVM_VERSION }}
|
||||
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 # v1
|
||||
with:
|
||||
toolchain: nightly-2023-10-13-${{ matrix.job.target }} # must use nightly here, because of abi_thiscall feature required
|
||||
targets: ${{ matrix.job.target }}
|
||||
components: "rustfmt"
|
||||
shell: bash
|
||||
run: |
|
||||
# Sciter's abi_thiscall feature requires nightly Rust.
|
||||
# Use an i686 host toolchain so build scripts can load the 32-bit LLVM installed above.
|
||||
# Since rustup 1.29.1, i686 toolchains on x64 Windows require --force-non-host
|
||||
# for both installation and default selection, even though WOW64 can run them.
|
||||
# See https://github.com/rust-lang/rustup/pull/4935.
|
||||
# Alternatively, an x64 compiler could use cargo build --target i686-pc-windows-msvc.
|
||||
# This requires 64-bit LLVM for host build scripts and updated packaging paths,
|
||||
# and has not been manually verified for RustDesk.
|
||||
rustup toolchain install nightly-2023-10-13-${{ matrix.job.target }} \
|
||||
--target ${{ matrix.job.target }} --component rustfmt \
|
||||
--profile minimal --no-self-update --force-non-host
|
||||
rustup default nightly-2023-10-13-${{ matrix.job.target }} --force-non-host
|
||||
|
||||
- uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
|
||||
with:
|
||||
@@ -856,6 +871,11 @@ jobs:
|
||||
name: bridge-artifact
|
||||
path: ./
|
||||
|
||||
- name: Test cursor sizing
|
||||
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
||||
working-directory: flutter
|
||||
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
|
||||
|
||||
- name: Setup vcpkg with Github Actions binary cache
|
||||
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
||||
with:
|
||||
@@ -2026,6 +2046,52 @@ 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 "rustdesk cursor_pos_tests" \
|
||||
cargo test --locked --lib --features drm cursor_pos_tests
|
||||
run_drm_tests "rustdesk peer_abs_sample_tests" \
|
||||
cargo test --locked --lib --features drm peer_abs_sample_tests
|
||||
run_drm_tests "rustdesk input_map_tests" \
|
||||
cargo test --locked --lib --features drm input_map_tests
|
||||
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
|
||||
run_drm_tests "scrap plane_rotation_tests" \
|
||||
cargo test --locked -p scrap --features drm plane_rotation_tests
|
||||
cargo build --locked --lib --features "$FEATURES" --release
|
||||
rm -rf target/release/deps target/release/build
|
||||
rm -rf ~/.cargo
|
||||
@@ -2386,7 +2452,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'
|
||||
|
||||
@@ -48,6 +48,20 @@ workspace member. `base::config::keys` re-exports the handful of keys
|
||||
* Do not add dependencies unless needed.
|
||||
* Keep code simple and idiomatic.
|
||||
|
||||
### Logging
|
||||
|
||||
* `debug` and above are written to the log file. A log call that can fire
|
||||
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
|
||||
peer controls) must not use `debug` or higher unthrottled.
|
||||
* For such a site, pick one:
|
||||
|
||||
* `log::trace!` when the event is expected and the line only helps while
|
||||
actively debugging;
|
||||
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
|
||||
that should still show up in a user's log. It keeps one line per interval
|
||||
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
|
||||
directly only when the decision drives more than one log call.
|
||||
|
||||
## Tokio Rules
|
||||
|
||||
* Assume a Tokio runtime already exists.
|
||||
@@ -127,12 +141,36 @@ Before considering any implementation complete, perform a minimization pass over
|
||||
* Before finalizing, explicitly report the regression surface: list the existing files and existing runtime paths whose behavior changed, and explain why each change is unavoidable.
|
||||
* During review, treat an unnecessarily modified legacy path as a review finding even if tests pass and the rewritten behavior appears equivalent.
|
||||
|
||||
### Corner cases raised in review
|
||||
|
||||
A refactor added to cover a corner case rarely converges. Each new counter, timestamp, cache or eviction/expiry rule interacts with state that existing code relies on, and the next review round finds the problems it introduced.
|
||||
|
||||
* A corner case is still worth fixing when the fix is easy and low-risk: a local change of a few lines that adds no state and changes no existing lookup, such as moving a check or refusing bad input earlier.
|
||||
* When the only fix needs new state, a new lifecycle rule or a restructure, and the code already fails cleanly there or behaves as master does, document it as a known limit in the PR instead. Anything beyond the easy fix needs the maintainer's explicit go-ahead first.
|
||||
* Before adding state that reorders, expires or reuses existing data, list every lookup that reads that data and check each one still holds.
|
||||
* Prefer a clean failure, where the operation reports an error, over machinery that tries to make a rare case succeed.
|
||||
* A severity label from any reviewer (P1, Critical, Major) is not a triage result. Apply the next rule by consequence, not by label.
|
||||
* A corner case whose fix needs new state is fixed only when it crashes, loses data, weakens security, or a user has reported it. A rare cosmetic or layout glitch (e.g. rotation during an active drag, a feature that is off by default) is a known limit: reply once, list it under "Known limits" in the PR body, and leave the code alone.
|
||||
* When a finding is about behavior an earlier commit of this same PR introduced, fix it by removing or simplifying that commit, not by adding a layer on top.
|
||||
* Judge growth across all rounds, not per round. If review follow-ups have grown the non-test diff by more than half of the first fix, or added a new kind of state (handles into another component, cross-component references, deferred / post-frame callbacks, timers, caches, flags), stop and ask the maintainer before pushing.
|
||||
* When keeping the user's preferred state is hard in a rare case, fall back to a deterministic default computed from the current inputs. Do not coordinate mutable state across components or frames to preserve the preference.
|
||||
|
||||
## Tests
|
||||
|
||||
* A fix gets regression tests for the reported behavior only: they fail on master and pass with the fix. One to three tests is normal.
|
||||
* Assert what the user sees or what the API returns. Do not test private state, the order an algorithm runs its steps in, or each corner case raised in review.
|
||||
* Do not add test infrastructure (browser runners, golden/screenshot harnesses, new mock layers, test-only hooks in production code) for a bug fix unless the maintainer asks.
|
||||
* If the test diff is more than twice the fix, cut it back to the tests that pin the reported behavior. A state that needs long setup to reach is usually too rare to fix.
|
||||
* When the number of tests needed to describe the behavior keeps growing, the implementation is too complex: simplify it instead of adding tests.
|
||||
|
||||
## Reviewing a PR
|
||||
|
||||
* Review only what the diff introduces. Verify ownership with `gh pr diff` before reporting a finding — if the offending lines are untouched context, it is a pre-existing problem, not this PR's.
|
||||
* List pre-existing problems in a separate section at the end, or leave out the ones that are not fatal. Never mix them into the findings the author has to fix.
|
||||
* Before re-reviewing, read the author's reply comments. Do not re-raise items they declined on scope grounds.
|
||||
* State a finding's consequence exactly: distinguish "the value is lost" from "the shortcut is inert but the value still saves".
|
||||
* Do not report a rare corner case as blocking when fixing it needs new state; mark it as a known limit the author may leave unfixed.
|
||||
* Treat growth across review rounds as a finding: if the latest commits add more state than the original fix, say so instead of asking for more handling.
|
||||
|
||||
## Localization (`src/lang/*.rs`)
|
||||
|
||||
|
||||
Generated
+37
-50
@@ -985,9 +985,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.10.1"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
||||
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
dependencies = [
|
||||
"serde 1.0.228",
|
||||
]
|
||||
@@ -1305,7 +1305,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "clipboard-master"
|
||||
version = "4.0.0-beta.6"
|
||||
source = "git+https://github.com/rustdesk-org/clipboard-master#7762d74e38db37cfeb6ded88c964b9cdbddfb6db"
|
||||
source = "git+https://github.com/rustdesk-org/clipboard-master#522fafb65edfe7939cf63fa797f916569ecab595"
|
||||
dependencies = [
|
||||
"objc",
|
||||
"objc-foundation",
|
||||
@@ -1717,7 +1717,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "cpal"
|
||||
version = "0.15.3"
|
||||
source = "git+https://github.com/rustdesk-org/cpal?branch=osx-screencapturekit#69ad2578adc9200093fc81cdfbdad63dbc4274f9"
|
||||
source = "git+https://github.com/rustdesk-org/cpal?branch=osx-screencapturekit#96d4da121b7d949677ac5b6887413a9185fd7f39"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"cidre",
|
||||
@@ -1791,9 +1791,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.18"
|
||||
version = "0.9.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
|
||||
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
@@ -4121,8 +4121,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "interceptor"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ac0781c825d602095113772e389ef0607afcb869ae0e68a590d8e0799cdcef8"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -6496,9 +6495,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.13"
|
||||
version = "0.11.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
|
||||
checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.3.2",
|
||||
@@ -6773,7 +6772,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rdev"
|
||||
version = "0.5.0-2"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#23e24dd6b35452a495dae0ae6d99395e9755ab0f"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
|
||||
dependencies = [
|
||||
"cocoa 0.24.1",
|
||||
"core-foundation 0.9.4",
|
||||
@@ -7008,8 +7007,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rtcp"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e9689528bf3a9eb311fd938d05516dd546412f9ce4fffc8acfc1db27cc3dbf72"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"thiserror 1.0.61",
|
||||
@@ -7019,8 +7017,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rtp"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c54733451a67d76caf9caa07a7a2cec6871ea9dda92a7847f98063d459200f4b"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"memchr",
|
||||
@@ -7139,6 +7136,7 @@ dependencies = [
|
||||
"lazy_static",
|
||||
"libpulse-binding",
|
||||
"libpulse-simple-binding",
|
||||
"libsamplerate-sys",
|
||||
"libxdo-sys",
|
||||
"mac_address",
|
||||
"magnum-opus",
|
||||
@@ -7198,6 +7196,7 @@ dependencies = [
|
||||
"wol-rs",
|
||||
"x11-clipboard 0.8.1",
|
||||
"x11rb 0.12.0",
|
||||
"xxhash-rust",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
@@ -7465,8 +7464,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sdp"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cd277015eada44a0bb810a4b84d3bf6e810573fa62fb442f457edf6a1087a69"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"rand 0.8.5",
|
||||
"substring",
|
||||
@@ -8038,8 +8036,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "stun"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dbc2bab375524093c143dc362a03fb6a1fb79e938391cdb21665688f88a088a"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"crc",
|
||||
@@ -8613,9 +8610,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.26.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
|
||||
version = "0.29.0"
|
||||
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=c241b11b03de4881faf1ecd2fe6e867c92f3013b#c241b11b03de4881faf1ecd2fe6e867c92f3013b"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
@@ -8898,9 +8894,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.26.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
|
||||
version = "0.29.0"
|
||||
source = "git+https://github.com/rustdesk-org/tungstenite-rs?rev=efce47e5364f00a63302cf07ab1fb13ded478914#efce47e5364f00a63302cf07ab1fb13ded478914"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
@@ -8914,15 +8909,13 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
"sha1",
|
||||
"thiserror 2.0.17",
|
||||
"utf-8",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "turn"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f5aea1116456e1da71c45586b87c72e3b43164fbf435eb93ff6aa475416a9a4"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
@@ -9145,12 +9138,6 @@ dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf-8"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||
|
||||
[[package]]
|
||||
name = "utf16string"
|
||||
version = "0.2.0"
|
||||
@@ -9585,8 +9572,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24bab7195998d605c862772f90a452ba655b90a2f463c850ac032038890e367a"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -9629,8 +9615,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-data"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e97b932854da633a767eff0cc805425a2222fc6481e96f463e57b015d949d1d"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"log",
|
||||
@@ -9644,8 +9629,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-dtls"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ccbe4d9049390ab52695c3646c1395c877e16c15fb05d3bda8eee0c7351711c"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
@@ -9681,12 +9665,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-ice"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb51bde0d790f109a15bfe4d04f1b56fb51d567da231643cb3f21bb74d678997"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
"crc",
|
||||
"ipnet",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
@@ -9706,8 +9690,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-mdns"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "979cc85259c53b7b620803509d10d35e2546fa505d228850cbe3f08765ea6ea8"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"log",
|
||||
"socket2 0.5.10",
|
||||
@@ -9719,8 +9702,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-media"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80041211deccda758a3e19aa93d6b10bc1d37c9183b519054b40a83691d13810"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
@@ -9732,7 +9714,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-sctp"
|
||||
version = "0.12.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=db3b07a9dd8f195916c89c2e62a8911402b11d27#db3b07a9dd8f195916c89c2e62a8911402b11d27"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -9749,8 +9731,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-srtp"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01e773f79b09b057ffbda6b03fe7b43403b012a240cf8d05d630674c3723b5bb"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"aes",
|
||||
@@ -9772,7 +9753,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc-util"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=db3b07a9dd8f195916c89c2e62a8911402b11d27#db3b07a9dd8f195916c89c2e62a8911402b11d27"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bitflags 1.3.2",
|
||||
@@ -10826,6 +10807,12 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
|
||||
|
||||
[[package]]
|
||||
name = "xxhash-rust"
|
||||
version = "0.8.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
|
||||
|
||||
[[package]]
|
||||
name = "yasna"
|
||||
version = "0.5.2"
|
||||
|
||||
+26
-6
@@ -22,7 +22,7 @@ path = "src/service.rs"
|
||||
|
||||
[features]
|
||||
inline = []
|
||||
use_samplerate = ["samplerate"]
|
||||
use_samplerate = ["samplerate", "libsamplerate-sys"]
|
||||
use_rubato = ["rubato"]
|
||||
use_dasp = ["dasp"]
|
||||
flutter = ["flutter_rust_bridge"]
|
||||
@@ -40,6 +40,7 @@ drm-wake = ["drm"]
|
||||
linux-pkg-config = ["magnum-opus/linux-pkg-config", "scrap/linux-pkg-config"]
|
||||
unix-file-copy-paste = [
|
||||
"dep:x11-clipboard",
|
||||
"dep:x11rb",
|
||||
"dep:percent-encoding",
|
||||
"dep:once_cell",
|
||||
"clipboard/unix-file-copy-paste",
|
||||
@@ -62,11 +63,13 @@ lazy_static = "1.4"
|
||||
sha2 = "0.10"
|
||||
repng = "0.2"
|
||||
zstd = "0.13"
|
||||
xxhash-rust = { version = "0.8", features = ["xxh3"] }
|
||||
parity-tokio-ipc = { git = "https://github.com/rustdesk-org/parity-tokio-ipc" }
|
||||
magnum-opus = { git = "https://github.com/rustdesk-org/magnum-opus" }
|
||||
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
|
||||
rubato = { version = "0.12", optional = true }
|
||||
samplerate = { version = "0.2", optional = true }
|
||||
libsamplerate-sys = { version = "0.1.12", optional = true }
|
||||
uuid = { version = "1.3", features = ["v4"] }
|
||||
num_cpus = "1.15"
|
||||
bytes = { version = "1.4", features = ["serde"] }
|
||||
@@ -191,7 +194,7 @@ evdev = { git="https://github.com/rustdesk-org/evdev" }
|
||||
dbus = "0.9"
|
||||
dbus-crossroads = "0.5"
|
||||
x11-clipboard = {git="https://github.com/clslaid/x11-clipboard", branch = "feat/store-batch", optional = true}
|
||||
x11rb = {version = "0.12", features = ["all-extensions"]}
|
||||
x11rb = {version = "0.12", features = ["all-extensions"], optional = true}
|
||||
percent-encoding = {version = "2.3", optional = true}
|
||||
once_cell = {version = "1.18", optional = true}
|
||||
nix = { version = "0.29", features = ["term", "process"]}
|
||||
@@ -216,9 +219,21 @@ exclude = ["vdi/host"]
|
||||
# This allows building and running on systems without libxdo installed (e.g., Wayland-only)
|
||||
[patch.crates-io]
|
||||
libxdo-sys = { path = "libs/libxdo-sys-stub" }
|
||||
# Upstream reserves a frame's whole declared length as soon as its header is in, so a header alone
|
||||
# buys an allocation the size it names, bounded only by max_frame_size. This fork grows the read
|
||||
# buffer one read_buffer_size chunk at a time as the bytes actually arrive. Patched rather than
|
||||
# depended on directly, so tokio-tungstenite's own tungstenite resolves to the same copy.
|
||||
tungstenite = { git = "https://github.com/rustdesk-org/tungstenite-rs", rev = "efce47e5364f00a63302cf07ab1fb13ded478914" }
|
||||
# One branch off upstream v0.13.0, the tag whose crate versions match this stack.
|
||||
# webrtc-util: reads the Windows adapter list's IPv6 addresses as host-order u16 groups, so every
|
||||
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows.
|
||||
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows;
|
||||
# and names every Windows adapter "" with no mask, so ICE cannot tell one adapter's addresses
|
||||
# from another's; and lays the adapter struct out in nested parts, whose padding on x64 shifts
|
||||
# every field after OperStatus, Ipv6IfIndex first.
|
||||
# webrtc-ice: best effort, one IPv6 host candidate per interface and prefix - the one the OS
|
||||
# sends from when that is one of the group's, else all of them - since the stable address beside
|
||||
# the temporary one is an identifier that outlives every rotation and that nothing else this
|
||||
# machine sends out ever shows.
|
||||
# webrtc-sctp: RFC 4960's 1s RTO floor makes a single loss cost 1-3s on a link whose RTT is 24-64ms,
|
||||
# and fast retransmit cannot cover a request/response exchange; INITIAL_MTU 1228 also fragments on
|
||||
# IPv6; and its AIMD pins a lossy long-haul link to MSS/(RTT*sqrt(p)), so a switch sends without
|
||||
@@ -228,10 +243,15 @@ libxdo-sys = { path = "libs/libxdo-sys-stub" }
|
||||
# RTT at KCP's RTO floors, and bundles of small chunks stay within the MTU. A T3-rtx resends
|
||||
# everything outstanding when it packs into four packets and otherwise probes with one and lets
|
||||
# the SACK settle the rest (F-RTO), timed from the latest send, so a stall no longer resends the
|
||||
# whole backlog behind itself while a short lost tail still comes back at once.
|
||||
# whole backlog behind itself while a short lost tail still comes back at once. A DATA chunk
|
||||
# received again is listed in the SACK, which never happened - the sender widens its reordering
|
||||
# window on that - and the SACK keeps to the MTU too, the lowest gap blocks first.
|
||||
# Pinned by rev, not branch: a fork branch can be rewritten out from under the lockfile.
|
||||
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "db3b07a9dd8f195916c89c2e62a8911402b11d27" }
|
||||
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "db3b07a9dd8f195916c89c2e62a8911402b11d27" }
|
||||
# webrtc: SettingEngine cannot reach the ICE agent's max_binding_requests, which decides how
|
||||
# long the answerer keeps checking a pair that has not answered yet.
|
||||
webrtc = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
|
||||
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
|
||||
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
|
||||
|
||||
[package.metadata.winres]
|
||||
LegalCopyright = "Copyright © 2026 Purslane Tech Pte. Ltd. All rights reserved."
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM debian:bullseye-slim
|
||||
FROM debian:trixie-slim
|
||||
|
||||
WORKDIR /
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -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.8.
|
||||
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
|
||||
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
|
||||
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
|
||||
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 для настільних і мобільних платформ
|
||||
|
||||
## Знімки екрана
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
Applicazione open source per desktop remoto, l'alternativa open source a TeamViewer.
|
||||
Codice sorgente: https://github.com/rustdesk/rustdesk
|
||||
Documentazione: https://rustdesk.com/docs/it/client/android/
|
||||
|
||||
Per consentire a un dispositivo remoto di controllare il tuo Android tramite mouse o tocco, devi permettere a RustDesk di utilizzare il servizio "Accessibilità". RustDesk utilizza l'API AccessibilityService per implementare il controllo remoto su Android.
|
||||
|
||||
Oltre al controllo remoto, puoi anche trasferire facilmente file tra dispositivi Android e PC con RustDesk.
|
||||
|
||||
Hai il controllo totale dei tuoi dati, senza preoccupazioni per la sicurezza. Puoi usare il nostro server rendezvous/relay, optare per l'hosting autonomo, o scrivere il tuo server rendezvous/relay. Il server auto-ospitato è gratuito e open source: https://github.com/rustdesk/rustdesk-server
|
||||
|
||||
Scarica e installa la versione per desktop da: https://rustdesk.com — potrai quindi accedere e controllare il tuo computer dal cellulare, o controllare il tuo cellulare dal computer.
|
||||
@@ -0,0 +1 @@
|
||||
App open source per desktop remoto, alternativa a TeamViewer.
|
||||
@@ -51,6 +51,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
private var minBufferSize = 0
|
||||
private var audioRecordStat = false
|
||||
private var audioThread: Thread? = null
|
||||
private var playbackCapturePending = false
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
fun createAudioRecorder(inVoiceCall: Boolean, mediaProjection: MediaProjection?): Boolean {
|
||||
@@ -193,6 +194,17 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
return audioRecorder?.audioSource == MediaRecorder.AudioSource.VOICE_COMMUNICATION
|
||||
}
|
||||
|
||||
fun getVoiceCallStartError(): String {
|
||||
return if (ActivityCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.RECORD_AUDIO
|
||||
) != PackageManager.PERMISSION_GRANTED) {
|
||||
"To start a voice call, enable \"Audio capture\" on the \"Screen share\" page."
|
||||
} else {
|
||||
"Failed to start voice call."
|
||||
}
|
||||
}
|
||||
|
||||
fun onVoiceCallStarted(mediaProjection: MediaProjection?): Boolean {
|
||||
if (!isSupportVoiceCall()) {
|
||||
return false
|
||||
@@ -220,6 +232,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
if (it.getAudioSource() == MediaRecorder.AudioSource.VOICE_COMMUNICATION) {
|
||||
return true
|
||||
}
|
||||
playbackCapturePending = true
|
||||
}
|
||||
audioRecordStat = false
|
||||
audioThread?.join()
|
||||
@@ -234,11 +247,10 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
fun switchOutVoiceCall(mediaProjection: MediaProjection?): Boolean {
|
||||
audioRecorder?.let {
|
||||
if (it.getAudioSource() != MediaRecorder.AudioSource.VOICE_COMMUNICATION) {
|
||||
return true
|
||||
}
|
||||
if (!isVoiceCallActive() && !playbackCapturePending) {
|
||||
return true
|
||||
}
|
||||
playbackCapturePending = true
|
||||
audioRecordStat = false
|
||||
audioThread?.join()
|
||||
|
||||
@@ -246,7 +258,11 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
Log.e(logTag, "createAudioRecorder fail")
|
||||
return false
|
||||
}
|
||||
return startAudioRecorder()
|
||||
val started = startAudioRecorder()
|
||||
if (started) {
|
||||
playbackCapturePending = false
|
||||
}
|
||||
return started
|
||||
}
|
||||
|
||||
fun tryReleaseAudio() {
|
||||
@@ -256,6 +272,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
audioRecordStat = false
|
||||
audioThread?.join()
|
||||
audioThread = null
|
||||
playbackCapturePending = false
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
|
||||
@@ -969,7 +969,7 @@ class MainActivity : FlutterActivity() {
|
||||
flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to "Failed to start voice call."))
|
||||
"text" to audioRecordHandle.getVoiceCallStartError()))
|
||||
} else {
|
||||
Log.d(logTag, "onVoiceCallStarted success")
|
||||
}
|
||||
|
||||
@@ -153,19 +153,13 @@ class MainService : Service() {
|
||||
} else {
|
||||
if (!switchOutVoiceCall()) {
|
||||
Log.e(logTag, "switchOutVoiceCall fail")
|
||||
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to "Failed to switch out voice call."))
|
||||
showVoiceCallError("Failed to switch out voice call.")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!switchToVoiceCall()) {
|
||||
Log.e(logTag, "switchToVoiceCall fail")
|
||||
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to "Failed to switch to voice call."))
|
||||
showVoiceCallError(audioRecordHandle.getVoiceCallStartError())
|
||||
}
|
||||
}
|
||||
} catch (e: JSONException) {
|
||||
@@ -507,6 +501,15 @@ class MainService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun showVoiceCallError(message: String) {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to message))
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun startMicrophoneCapture(startAudio: () -> Boolean): Boolean {
|
||||
if (!setMicrophoneForegroundService(true)) {
|
||||
|
||||
+8
-1
@@ -2,6 +2,7 @@ package com.carriez.flutter_hbb
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.media.projection.MediaProjectionConfig
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
@@ -19,7 +20,13 @@ class PermissionRequestTransparentActivity: Activity() {
|
||||
ACT_REQUEST_MEDIA_PROJECTION -> {
|
||||
val mediaProjectionManager =
|
||||
getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
val intent = mediaProjectionManager.createScreenCaptureIntent()
|
||||
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
mediaProjectionManager.createScreenCaptureIntent(
|
||||
MediaProjectionConfig.createConfigForDefaultDisplay()
|
||||
)
|
||||
} else {
|
||||
mediaProjectionManager.createScreenCaptureIntent()
|
||||
}
|
||||
startActivityForResult(intent, REQ_REQUEST_MEDIA_PROJECTION)
|
||||
}
|
||||
else -> finish()
|
||||
|
||||
@@ -126,6 +126,8 @@ const String kOptionEnableBlockInput = "enable-block-input";
|
||||
const String kOptionEnablePrivacyMode = "enable-privacy-mode";
|
||||
const String kOptionEnablePermChangeInAcceptWindow =
|
||||
"enable-perm-change-in-accept-window";
|
||||
const String kOptionHideElevateButtonInAcceptWindow =
|
||||
"hide-elevate-button-in-accept-window";
|
||||
const String kOptionAllowRemoteConfigModification =
|
||||
"allow-remote-config-modification";
|
||||
const String kOptionVerificationMethod = "verification-method";
|
||||
@@ -178,6 +180,7 @@ const String kOptionEnableIpv6Punch = "enable-ipv6-punch";
|
||||
const String kOptionAllowSyncClipboardBetweenSessions =
|
||||
"allow-sync-clipboard-between-sessions";
|
||||
const String kOptionEnableWebrtc = "enable-webrtc";
|
||||
const String kOptionRelayFallbackDelay = "relay-fallback-delay";
|
||||
const String kOptionEnableTrustedDevices = "enable-trusted-devices";
|
||||
const String kOptionShowVirtualMouse = "show-virtual-mouse";
|
||||
const String kOptionVirtualMouseScale = "virtual-mouse-scale";
|
||||
|
||||
@@ -591,13 +591,7 @@ class _GeneralState extends State<_General> {
|
||||
isServer: false,
|
||||
),
|
||||
],
|
||||
if (!incomingOnly)
|
||||
_OptionCheckBox(
|
||||
context,
|
||||
'Enable WebRTC P2P connection',
|
||||
kOptionEnableWebrtc,
|
||||
isServer: false,
|
||||
),
|
||||
if (!incomingOnly) ...webrtcOptions(context),
|
||||
if (!isWeb && !incomingOnly)
|
||||
Tooltip(
|
||||
message: translate('sync-clipboard-between-sessions-tip'),
|
||||
@@ -887,6 +881,85 @@ class _GeneralState extends State<_General> {
|
||||
).marginOnly(left: _kContentHMargin);
|
||||
});
|
||||
}
|
||||
|
||||
// How long an already-connected relay is held back to give the direct WebRTC
|
||||
// attempt a chance to win. It only means anything while WebRTC is on, so it
|
||||
// follows the checkbox as an indented sub-option and is hidden outright when
|
||||
// the box is clear — the shape `directIp` uses for its port.
|
||||
List<Widget> webrtcOptions(BuildContext context) {
|
||||
final stored = bind.mainGetLocalOption(key: kOptionRelayFallbackDelay);
|
||||
final controller = TextEditingController(text: stored);
|
||||
// What the field holds against what is saved. Apply is offered only while
|
||||
// the two differ, so an untouched field shows no button at all, and neither
|
||||
// does one typed back to its saved value or cleared when nothing was saved
|
||||
// — the state an "edited" flag alone would still call dirty.
|
||||
final typed = RxString(stored);
|
||||
final saved = RxString(stored);
|
||||
return [
|
||||
_OptionCheckBox(
|
||||
context,
|
||||
'Enable WebRTC P2P connection',
|
||||
kOptionEnableWebrtc,
|
||||
isServer: false,
|
||||
update: (_) => setState(() {}),
|
||||
),
|
||||
() {
|
||||
final enabled = mainGetLocalBoolOptionSync(kOptionEnableWebrtc);
|
||||
final isOptFixed = isOptionFixed(kOptionRelayFallbackDelay);
|
||||
return Offstage(
|
||||
offstage: !enabled,
|
||||
child: Tooltip(
|
||||
message: translate('relay-fallback-delay-tip'),
|
||||
child: _SubLabeledWidget(
|
||||
context,
|
||||
'Relay fallback delay in seconds',
|
||||
Row(children: [
|
||||
SizedBox(
|
||||
width: 95,
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
enabled: enabled && !isOptFixed,
|
||||
onChanged: (v) => typed.value = v,
|
||||
inputFormatters: [
|
||||
// Seconds, at most one decimal. Clearing the field is
|
||||
// allowed and restores the built-in default.
|
||||
FilteringTextInputFormatter.allow(
|
||||
RegExp(r'^([0-9]|[1-9][0-9])(\.[0-9]?)?$')),
|
||||
],
|
||||
decoration: const InputDecoration(
|
||||
hintText: '2.5',
|
||||
contentPadding:
|
||||
EdgeInsets.symmetric(vertical: 12, horizontal: 12),
|
||||
),
|
||||
).workaroundFreezeLinuxMint().marginOnly(right: 15),
|
||||
),
|
||||
Obx(() => Offstage(
|
||||
offstage: typed.value.trim() == saved.value.trim(),
|
||||
child: ElevatedButton(
|
||||
onPressed: enabled &&
|
||||
!isOptFixed &&
|
||||
!typed.value.trim().endsWith('.') &&
|
||||
double.tryParse(typed.value.trim()) != 0
|
||||
? () async {
|
||||
final v = controller.text.trim();
|
||||
await bind.mainSetLocalOption(
|
||||
key: kOptionRelayFallbackDelay, value: v);
|
||||
if (controller.text != v) controller.text = v;
|
||||
typed.value = v;
|
||||
saved.value = v;
|
||||
}
|
||||
: null,
|
||||
child: Text(translate('Apply')),
|
||||
),
|
||||
))
|
||||
]),
|
||||
enabled: enabled && !isOptFixed,
|
||||
),
|
||||
),
|
||||
);
|
||||
}(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
enum _AccessMode {
|
||||
|
||||
@@ -1005,8 +1005,8 @@ class _RemotePageState extends State<RemotePage>
|
||||
bool get wantKeepAlive => true;
|
||||
}
|
||||
|
||||
/// A widget that tracks the view size and updates CanvasModel.updateViewStyle()
|
||||
/// and InputModel.updateImageWidgetSize() only when size actually changes.
|
||||
/// Tracks view size and DPR to update CanvasModel.updateViewStyle()
|
||||
/// and InputModel.updateImageWidgetSize() only when either changes.
|
||||
/// This avoids scheduling post-frame callbacks on every LayoutBuilder rebuild.
|
||||
class _ViewStyleUpdater extends StatefulWidget {
|
||||
final CanvasModel canvasModel;
|
||||
@@ -1026,10 +1026,12 @@ class _ViewStyleUpdater extends StatefulWidget {
|
||||
|
||||
class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
|
||||
Size? _lastSize;
|
||||
double? _lastDevicePixelRatio;
|
||||
bool _callbackScheduled = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final maxWidth = constraints.maxWidth;
|
||||
@@ -1039,8 +1041,9 @@ class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
|
||||
return widget.child;
|
||||
}
|
||||
final newSize = Size(maxWidth, maxHeight);
|
||||
if (_lastSize != newSize) {
|
||||
if (_lastSize != newSize || _lastDevicePixelRatio != devicePixelRatio) {
|
||||
_lastSize = newSize;
|
||||
_lastDevicePixelRatio = devicePixelRatio;
|
||||
// Schedule the update for after the current frame to avoid setState during build.
|
||||
// Use _callbackScheduled flag to prevent accumulating multiple callbacks
|
||||
// when size changes rapidly before any callback executes.
|
||||
@@ -1088,6 +1091,7 @@ class ImagePaint extends StatefulWidget {
|
||||
|
||||
class _ImagePaintState extends State<ImagePaint> {
|
||||
bool _lastRemoteCursorMoved = false;
|
||||
final _cursorDisplayScale = 1.0.obs;
|
||||
|
||||
String get id => widget.id;
|
||||
RxBool get zoomCursor => widget.zoomCursor;
|
||||
@@ -1101,47 +1105,19 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
final m = Provider.of<ImageModel>(context);
|
||||
var c = Provider.of<CanvasModel>(context);
|
||||
final s = c.scale;
|
||||
// CanvasModel caches the DPR and only refreshes it when the view style
|
||||
// changes, so read it live to follow the window across monitors.
|
||||
// Read the live DPR while the canvas's post-frame update is pending.
|
||||
final dpr = MediaQuery.devicePixelRatioOf(context);
|
||||
|
||||
bool isViewScaled() =>
|
||||
c.viewStyle.style == kRemoteViewStyleAdaptive ||
|
||||
c.viewStyle.style == kRemoteViewStyleCustom;
|
||||
bool isViewOriginal() => c.viewStyle.style == kRemoteViewStyleOriginal;
|
||||
|
||||
mouseRegion({child}) => Obx(() {
|
||||
double getCursorScale() {
|
||||
final cursor = Provider.of<CursorModel>(context);
|
||||
// Predefined artwork must not inherit the cached remote bitmap's DPI.
|
||||
final cache = keyboardEnabled.isTrue
|
||||
? cursor.cache ?? preDefaultCursor.cache
|
||||
: preForbiddenCursor.cache;
|
||||
final peerDpr = cache?.pixelRatio ?? 0;
|
||||
if (isViewScaled() && zoomCursor.isFalse && peerDpr > 0 &&
|
||||
(!isWeb || widget.ffi.ffiModel.pi.platform == kPeerPlatformMacOS)) {
|
||||
// Normalize to logical size; Windows takes physical pixels here.
|
||||
// Web normalizes only macOS's optional Retina image, preserving
|
||||
// the existing unzoomed sizing policy for other hosts.
|
||||
return (isWindows ? dpr : 1.0) / peerDpr;
|
||||
}
|
||||
// Without density, preserve the legacy unzoomed size. Controller
|
||||
// DPR alone cannot determine the remote bitmap's logical size.
|
||||
final imageScale = isViewScaled() && zoomCursor.isTrue
|
||||
? _cursorImageScale(widget.ffi, cursor, useLocalPointer: true)
|
||||
: s;
|
||||
var cursorScale = 1.0;
|
||||
if (isWindows) {
|
||||
// debug win10
|
||||
if (zoomCursor.value && isViewScaled()) {
|
||||
cursorScale = imageScale * dpr;
|
||||
}
|
||||
var c = Provider.of<CanvasModel>(context);
|
||||
if (isDesktop) {
|
||||
return _getDesktopCursorScale(c, dpr);
|
||||
} else {
|
||||
if (zoomCursor.value || isViewOriginal()) {
|
||||
cursorScale = imageScale;
|
||||
}
|
||||
return zoomCursor.value || isViewOriginal() ? s : 1.0;
|
||||
}
|
||||
return cursorScale;
|
||||
}
|
||||
|
||||
return MouseRegion(
|
||||
@@ -1171,7 +1147,6 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
child: child);
|
||||
});
|
||||
if (c.imageOverflow.isTrue && c.scrollStyle != ScrollStyle.scrollauto) {
|
||||
_syncScrollAfterLayout(c);
|
||||
final paintWidth = c.getDisplayWidth() * s;
|
||||
final paintHeight = c.getDisplayHeight() * s;
|
||||
final paintSize = Size(paintWidth, paintHeight);
|
||||
@@ -1216,25 +1191,70 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
}
|
||||
}
|
||||
|
||||
// Layout can change scroll metrics without notification. Compare against this
|
||||
// build's fractions: a delayed refresh may already have changed the model.
|
||||
void _syncScrollAfterLayout(CanvasModel canvas) {
|
||||
// Both supported scrollbar view styles also paint from scroll fractions.
|
||||
if (canvas.scrollStyle != ScrollStyle.scrolledge &&
|
||||
canvas.viewStyle.style != kRemoteViewStyleCustom &&
|
||||
canvas.viewStyle.style != kRemoteViewStyleOriginal) return;
|
||||
final renderedScroll = (canvas.scrollX, canvas.scrollY);
|
||||
SchedulerBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
canvas.updateScrollAfterLayout(renderedScroll);
|
||||
});
|
||||
/// Matches desktop cursors to the rendered image and native pixel units.
|
||||
///
|
||||
/// Windows cursor pixels are physical; NSCursor/GdkCursor use logical pixels.
|
||||
/// Unzoomed Adaptive/Custom views preserve macOS cursors' point dimensions.
|
||||
double _getDesktopCursorScale(CanvasModel c, double dpr) {
|
||||
final peer = widget.ffi.ffiModel;
|
||||
if (!zoomCursor.value &&
|
||||
peer.pi.platform == kPeerPlatformMacOS &&
|
||||
(c.viewStyle.style == kRemoteViewStyleAdaptive ||
|
||||
c.viewStyle.style == kRemoteViewStyleCustom)) {
|
||||
return isWindows ? dpr : 1.0;
|
||||
}
|
||||
if (peer.isPeerLinux && peer.pi.currentDisplay == kAllDisplayValue) {
|
||||
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
|
||||
// Remove the host output's density without applying canvas zoom.
|
||||
final scale = 1.0 / _cursorDisplayScale.value;
|
||||
return isWindows ? scale : scale / dpr;
|
||||
}
|
||||
final scale = c.scale / _cursorDisplayScale.value;
|
||||
return isWindows ? scale * dpr : scale;
|
||||
}
|
||||
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
|
||||
// Original and unzoomed views do not apply canvas zoom.
|
||||
final scale = _getCursorScaleForDisplay(1.0);
|
||||
return isWindows ? scale : scale / dpr;
|
||||
}
|
||||
final scale = _getCursorScaleForDisplay(c.scale);
|
||||
return isWindows ? scale * dpr : scale;
|
||||
}
|
||||
|
||||
double _getCursorScaleForDisplay(double scale) {
|
||||
final peer = widget.ffi.ffiModel;
|
||||
// All Displays can mix densities; no single display scale applies.
|
||||
if (peer.pi.currentDisplay == kAllDisplayValue) return scale;
|
||||
final displays = peer.pi.getCurDisplays();
|
||||
if (displays.isEmpty) return scale;
|
||||
if (peer.pi.platform == kPeerPlatformMacOS) {
|
||||
// macOS sends NSImage.size in points (src/platform/macos.rs:640,682),
|
||||
// while HiDPI screen frames use backing pixels (libs/scrap/src/quartz/display.rs:37).
|
||||
return scale * displays.first.scale;
|
||||
}
|
||||
if (!peer.isPeerLinux) return scale;
|
||||
// Match rendering when a Wayland host
|
||||
// with multiple outputs reports a display scale > 1.
|
||||
// A single-output host keeps scale at 1.0 to preserve physical uinput
|
||||
// coordinates, even with OS scaling enabled. This counts host outputs,
|
||||
// not the selected displays.length.
|
||||
// See src/server/display_service.rs:650 (update_sync_displays) and
|
||||
// src/server/drm_capturer.rs:1523 (DRM's matching convention).
|
||||
return scale / displays.first.scale;
|
||||
}
|
||||
|
||||
Widget _buildScrollbarNonTextureRender(
|
||||
ImageModel m, Size imageSize, double s) {
|
||||
double sizeScale = s;
|
||||
if (widget.ffi.ffiModel.isPeerLinux) {
|
||||
final displays = widget.ffi.ffiModel.pi.getCurDisplays();
|
||||
if (displays.isNotEmpty) {
|
||||
sizeScale = s / displays[0].scale;
|
||||
}
|
||||
}
|
||||
return CustomPaint(
|
||||
size: imageSize,
|
||||
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: s),
|
||||
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: sizeScale),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1279,11 +1299,14 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
top: (displays[i].y - rect.top) * s + offset.dy,
|
||||
width: displays[i].width * sizeScale,
|
||||
height: displays[i].height * sizeScale,
|
||||
child: Obx(() => Texture(
|
||||
textureId: textureId.value,
|
||||
filterQuality:
|
||||
isViewOriginal ? FilterQuality.none : FilterQuality.low,
|
||||
)),
|
||||
child: _trackCursorDisplay(
|
||||
Obx(() => Texture(
|
||||
textureId: textureId.value,
|
||||
filterQuality:
|
||||
isViewOriginal ? FilterQuality.none : FilterQuality.low,
|
||||
)),
|
||||
displays[i],
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1294,6 +1317,20 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _trackCursorDisplay(Widget child, Display display) {
|
||||
final peer = widget.ffi.ffiModel;
|
||||
if (!isDesktop ||
|
||||
!peer.isPeerLinux ||
|
||||
peer.pi.currentDisplay != kAllDisplayValue) {
|
||||
return child;
|
||||
}
|
||||
return MouseRegion(
|
||||
onEnter: (_) => _cursorDisplayScale.value = display.scale,
|
||||
onHover: (_) => _cursorDisplayScale.value = display.scale,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
MouseCursor _buildCustomCursor(BuildContext context, double scale) {
|
||||
final cursor = Provider.of<CursorModel>(context);
|
||||
final cache = cursor.cache ?? preDefaultCursor.cache;
|
||||
@@ -1421,119 +1458,43 @@ class CursorPaint extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
final imageOffset = _softwareImageOffset(c);
|
||||
double cx = imageOffset?.dx ?? c.x;
|
||||
double cy = imageOffset?.dy ?? c.y;
|
||||
if (c.imageOverflow.isTrue && c.scrollStyle != ScrollStyle.scrollauto) {
|
||||
double cx = c.x;
|
||||
double cy = c.y;
|
||||
if (c.viewStyle.style == kRemoteViewStyleOriginal &&
|
||||
c.scrollStyle == ScrollStyle.scrollbar) {
|
||||
final rect = c.parent.target!.ffiModel.rect;
|
||||
if (rect == null) {
|
||||
// unreachable!
|
||||
debugPrint('unreachable! The displays rect is null.');
|
||||
return Container();
|
||||
}
|
||||
// Scrollbar and edge scrolling share a layout that ignores canvas pan offsets.
|
||||
final imageWidth = rect.width * c.scale;
|
||||
final imageHeight = rect.height * c.scale;
|
||||
// Match the video's integer centering on each fitting axis, even if a
|
||||
// detached scroll controller left a stale fraction before layout sync.
|
||||
cx = c.size.width < imageWidth
|
||||
? -imageWidth * c.scrollX
|
||||
: ((c.size.width - imageWidth) ~/ 2).toDouble();
|
||||
cy = c.size.height < imageHeight
|
||||
? -imageHeight * c.scrollY
|
||||
: ((c.size.height - imageHeight) ~/ 2).toDouble();
|
||||
if (cx < 0) {
|
||||
final imageWidth = rect.width * c.scale;
|
||||
cx = -imageWidth * c.scrollX;
|
||||
}
|
||||
if (cy < 0) {
|
||||
final imageHeight = rect.height * c.scale;
|
||||
cy = -imageHeight * c.scrollY;
|
||||
}
|
||||
}
|
||||
|
||||
final image = m.image ?? preDefaultCursor.image;
|
||||
// Match native registration's logical minimum for density-aware scaled views.
|
||||
final logicalMinimum = (m.cache?.pixelRatio ?? 0) > 0 &&
|
||||
c.viewStyle.style != kRemoteViewStyleOriginal;
|
||||
final nativePixels = isWindows && !logicalMinimum
|
||||
? MediaQuery.devicePixelRatioOf(context) : 1.0;
|
||||
// Show remote cursor follows the image scale, independently of Zoom cursor.
|
||||
double scale = _cursorImageScale(c.parent.target!, m);
|
||||
if (image != null && (logicalMinimum || scale * nativePixels != 1.0)) {
|
||||
final sx = kMinCursorSize / (image.width * nativePixels);
|
||||
final sy = kMinCursorSize / (image.height * nativePixels);
|
||||
// Match native resizing: a thin axis must not enlarge the whole cursor.
|
||||
final minimumScale = sx < sy ? sx : sy;
|
||||
if (scale < minimumScale) scale = minimumScale;
|
||||
double x = (m.x - hotx) * c.scale + cx;
|
||||
double y = (m.y - hoty) * c.scale + cy;
|
||||
double scale = 1.0;
|
||||
final isViewOriginal = c.viewStyle.style == kRemoteViewStyleOriginal;
|
||||
if (zoomCursor.value || isViewOriginal) {
|
||||
x = m.x - hotx + cx / c.scale;
|
||||
y = m.y - hoty + cy / c.scale;
|
||||
scale = c.scale;
|
||||
}
|
||||
// Anchor the hotspot to the video position even when the minimum size
|
||||
// makes the artwork scale differ from the video scale.
|
||||
final x = (m.x * c.scale + cx) / scale - hotx;
|
||||
final y = (m.y * c.scale + cy) / scale - hoty;
|
||||
|
||||
return CustomPaint(
|
||||
painter: ImagePainter(
|
||||
image: image,
|
||||
image: m.image ?? preDefaultCursor.image,
|
||||
x: x,
|
||||
y: y,
|
||||
scale: scale,
|
||||
useIntegerPosition: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Match video-origin rounding: source pixels for software, logical pixels
|
||||
/// for Linux textures. The caller handles scrolling and unrounded origins.
|
||||
/// Keep cursor positions and hotspots fractional.
|
||||
Offset? _softwareImageOffset(CanvasModel canvas) {
|
||||
if (canvas.imageOverflow.isTrue &&
|
||||
canvas.scrollStyle != ScrollStyle.scrollauto) {
|
||||
return null;
|
||||
}
|
||||
final ffi = canvas.parent.target!;
|
||||
final peer = ffi.ffiModel;
|
||||
if (ffi.imageModel.useTextureRender || peer.pi.forceTextureRender) {
|
||||
// Match Linux's texture origin without rounding the cursor or hotspot.
|
||||
return isLinux
|
||||
? Offset(canvas.x.toInt().toDouble(), canvas.y.toInt().toDouble())
|
||||
: null;
|
||||
}
|
||||
var scale = canvas.scale;
|
||||
final displays = peer.pi.getCurDisplays();
|
||||
if (peer.isPeerLinux && displays.isNotEmpty) scale /= displays[0].scale;
|
||||
// Match the origin used by _buildScrollAutoNonTextureRender's ImagePainter.
|
||||
return Offset(
|
||||
(canvas.x / scale).toInt() * scale, (canvas.y / scale).toInt() * scale);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Logical pixels per cursor bitmap pixel, matching the video renderer.
|
||||
/// Linux display geometry, not cursor density, determines this ratio.
|
||||
/// Native mixed-display cursors use mapped local input; overlays use the host
|
||||
/// position. Callers apply minimum size, controller DPR and hotspot offsets.
|
||||
double _cursorImageScale(FFI ffi, CursorModel cursor,
|
||||
{bool useLocalPointer = false}) {
|
||||
final canvas = ffi.canvasModel;
|
||||
final peer = ffi.ffiModel;
|
||||
if (!peer.isPeerLinux) return canvas.scale;
|
||||
if (canvas.imageOverflow.isTrue &&
|
||||
canvas.scrollStyle != ScrollStyle.scrollauto &&
|
||||
!ffi.imageModel.useTextureRender &&
|
||||
!peer.pi.forceTextureRender) {
|
||||
return canvas.scale; // The nontexture scrollbar also paints physical pixels.
|
||||
}
|
||||
final displays = peer.pi.getCurDisplays();
|
||||
if (displays.length == 1) return canvas.scale / displays.first.scale;
|
||||
final rect = peer.rect;
|
||||
if (rect != null) {
|
||||
// Mapped local input is already in host desktop coordinates. CursorModel's
|
||||
// position is relative to rect, so restore its origin for display lookup.
|
||||
// Before the first local movement, both paths use the host position.
|
||||
final position =
|
||||
(useLocalPointer ? ffi.inputModel.remotePointerPosition.value : null) ??
|
||||
Offset(cursor.x + rect.left, cursor.y + rect.top);
|
||||
for (final display in displays) {
|
||||
// Display origins are desktop coordinates; dimensions are physical pixels.
|
||||
// Convert the dimensions so these bounds use the same units as position.
|
||||
if (Rect.fromLTWH(display.x, display.y, display.width / display.scale,
|
||||
display.height / display.scale).contains(position)) {
|
||||
return canvas.scale / display.scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
return canvas.scale;
|
||||
}
|
||||
|
||||
@@ -1073,7 +1073,10 @@ class _CmControlPanel extends StatelessWidget {
|
||||
final model = Provider.of<ServerModel>(context);
|
||||
final showElevation = canElevate &&
|
||||
model.showElevation &&
|
||||
client.type_() == ClientType.remote;
|
||||
client.type_() == ClientType.remote &&
|
||||
bind.mainGetBuildinOption(
|
||||
key: kOptionHideElevateButtonInAcceptWindow) !=
|
||||
'Y';
|
||||
final showAccept = model.approveMode != 'password';
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
|
||||
@@ -175,7 +175,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
||||
// `on_voice_call_closed` should be called when the connection is ended.
|
||||
// The inner logic of `on_voice_call_closed` will check if the voice call is active.
|
||||
// Only one client is considered here for now.
|
||||
gFFI.chatModel.onVoiceCallClosed("End connetion");
|
||||
gFFI.chatModel.onVoiceCallClosed("End connection");
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -141,7 +141,7 @@ class _ViewCameraPageState extends State<ViewCameraPage>
|
||||
// `on_voice_call_closed` should be called when the connection is ended.
|
||||
// The inner logic of `on_voice_call_closed` will check if the voice call is active.
|
||||
// Only one client is considered here for now.
|
||||
gFFI.chatModel.onVoiceCallClosed("End connetion");
|
||||
gFFI.chatModel.onVoiceCallClosed("End connection");
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -449,11 +449,6 @@ class InputModel {
|
||||
final isPhysicalMouse = false.obs;
|
||||
int _lastButtons = 0;
|
||||
Offset lastMousePos = Offset.zero;
|
||||
// Latest local pointer position mapped to absolute remote desktop coordinates.
|
||||
// Used to select the native cursor's display scale in Linux All Displays mode,
|
||||
// without waiting for a host position update. Keep it separate from the
|
||||
// host-reported position used to paint the remote cursor.
|
||||
final remotePointerPosition = Rxn<Offset>();
|
||||
int _lastWheelTsUs = 0;
|
||||
|
||||
// Wheel acceleration thresholds.
|
||||
@@ -1959,7 +1954,7 @@ class InputModel {
|
||||
canvasModel.updateLocalCursor(x, y);
|
||||
}
|
||||
|
||||
final point = _handlePointerDevicePos(
|
||||
return _handlePointerDevicePos(
|
||||
kind,
|
||||
x,
|
||||
y,
|
||||
@@ -1970,20 +1965,6 @@ class InputModel {
|
||||
onExit: onExit,
|
||||
buttons: buttons,
|
||||
);
|
||||
_rememberRemotePointer(point, isMove);
|
||||
return point;
|
||||
}
|
||||
|
||||
void _rememberRemotePointer(Point? point, bool isMove) {
|
||||
final peer = parent.target!.ffiModel;
|
||||
if (point == null ||
|
||||
!isMove ||
|
||||
!(isDesktop || isWebDesktop) ||
|
||||
peer.pi.currentDisplay != kAllDisplayValue ||
|
||||
!peer.isPeerLinux) {
|
||||
return;
|
||||
}
|
||||
remotePointerPosition.value = Offset(point.x.toDouble(), point.y.toDouble());
|
||||
}
|
||||
|
||||
bool _isInCurrentWindow(double x, double y) {
|
||||
|
||||
+391
-190
@@ -58,7 +58,8 @@ const _restartReconnectSilentDelaySecs = 5;
|
||||
class CachedPeerData {
|
||||
Map<String, dynamic> updatePrivacyMode = {};
|
||||
Map<String, dynamic> peerInfo = {};
|
||||
List<Map<String, dynamic>> cursorDataList = [];
|
||||
// No shapes: the core keeps them for the session, and the window a tab moves to asks it
|
||||
// for the one in use.
|
||||
Map<String, dynamic> lastCursorId = {};
|
||||
Map<String, bool> permissions = {};
|
||||
|
||||
@@ -73,7 +74,6 @@ class CachedPeerData {
|
||||
return jsonEncode({
|
||||
'updatePrivacyMode': updatePrivacyMode,
|
||||
'peerInfo': peerInfo,
|
||||
'cursorDataList': cursorDataList,
|
||||
'lastCursorId': lastCursorId,
|
||||
'permissions': permissions,
|
||||
'secure': secure,
|
||||
@@ -88,9 +88,6 @@ class CachedPeerData {
|
||||
final data = CachedPeerData();
|
||||
data.updatePrivacyMode = map['updatePrivacyMode'];
|
||||
data.peerInfo = map['peerInfo'];
|
||||
for (final cursorData in map['cursorDataList']) {
|
||||
data.cursorDataList.add(cursorData);
|
||||
}
|
||||
data.lastCursorId = map['lastCursorId'];
|
||||
map['permissions'].forEach((key, value) {
|
||||
data.permissions[key] = value;
|
||||
@@ -166,6 +163,7 @@ class FfiModel with ChangeNotifier {
|
||||
bool get isPeerMobile => isPeerAndroid;
|
||||
|
||||
bool get isPeerLinux => _pi.platform == kPeerPlatformLinux;
|
||||
bool get isPeerWindows => _pi.platform == kPeerPlatformWindows;
|
||||
|
||||
bool get viewOnly => _viewOnly;
|
||||
bool get showMyCursor => _showMyCursor;
|
||||
@@ -322,10 +320,6 @@ class FfiModel with ChangeNotifier {
|
||||
updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
|
||||
setConnectionType(peerId, data.secure, data.direct, data.streamType);
|
||||
await handlePeerInfo(data.peerInfo, peerId, true);
|
||||
for (final element in data.cursorDataList) {
|
||||
updateLastCursorId(element);
|
||||
await handleCursorData(element);
|
||||
}
|
||||
if (data.lastCursorId.isNotEmpty) {
|
||||
updateLastCursorId(data.lastCursorId);
|
||||
handleCursorId(data.lastCursorId);
|
||||
@@ -355,9 +349,6 @@ class FfiModel with ChangeNotifier {
|
||||
} else if (name == 'switch_display') {
|
||||
// switch display is kept for backward compatibility
|
||||
handleSwitchDisplay(evt, sessionId, peerId);
|
||||
} else if (name == 'cursor_data') {
|
||||
updateLastCursorId(evt);
|
||||
await handleCursorData(evt);
|
||||
} else if (name == 'cursor_id') {
|
||||
updateLastCursorId(evt);
|
||||
handleCursorId(evt);
|
||||
@@ -1436,9 +1427,9 @@ class FfiModel with ChangeNotifier {
|
||||
}
|
||||
// After reconnecting, restore the last selected monitor once the canvas is ready.
|
||||
// Switching earlier can offset the view if the monitor sizes differ.
|
||||
final last = lastUserDisplay;
|
||||
// New monitor windows keep their selection in currentDisplay.
|
||||
final last = lastUserDisplay ?? _pi.currentDisplay;
|
||||
pendingMonitorRestore = (!isCache &&
|
||||
last != null &&
|
||||
last != currentDisplay &&
|
||||
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
|
||||
sessionId: sessionId) !=
|
||||
@@ -1661,9 +1652,14 @@ class FfiModel with ChangeNotifier {
|
||||
parent.target?.cursorModel.updateCursorId(evt);
|
||||
}
|
||||
|
||||
handleCursorData(Map<String, dynamic> evt) async {
|
||||
cachedPeerData.cursorDataList.add(evt);
|
||||
await parent.target?.cursorModel.updateCursorData(evt);
|
||||
/// A shape arriving is the shape in use, as a cursor_id is.
|
||||
handleCursorData(String id, int hotx, int hoty, int width, int height,
|
||||
Uint8List colors) async {
|
||||
// The replay selects this last, whatever the order the shapes are replayed in.
|
||||
cachedPeerData.lastCursorId = {'id': id};
|
||||
parent.target?.cursorModel.id = id;
|
||||
await parent.target?.cursorModel
|
||||
.updateCursorData(id, hotx, hoty, width, height, colors);
|
||||
}
|
||||
|
||||
/// Handle the peer info synchronization event based on [evt].
|
||||
@@ -2401,7 +2397,9 @@ class CanvasModel with ChangeNotifier {
|
||||
// ViewStyle fields and is not captured by the equality check. Therefore, we must
|
||||
// allow updates to proceed when style == kRemoteViewStyleCustom, even if the
|
||||
// rest of the ViewStyle fields are unchanged.
|
||||
if (_lastViewStyle == viewStyle && style != kRemoteViewStyleCustom) {
|
||||
if (_lastViewStyle == viewStyle &&
|
||||
_devicePixelRatio == ui.window.devicePixelRatio &&
|
||||
style != kRemoteViewStyleCustom) {
|
||||
return;
|
||||
}
|
||||
if (_lastViewStyle.style != viewStyle.style) {
|
||||
@@ -2461,6 +2459,8 @@ class CanvasModel with ChangeNotifier {
|
||||
_resetScroll();
|
||||
|
||||
Future.delayed(duration, () async {
|
||||
// Layout updates scroll extents and detaches scrollbars no longer needed.
|
||||
await SchedulerBinding.instance.endOfFrame;
|
||||
updateScrollPercent();
|
||||
});
|
||||
}
|
||||
@@ -2472,7 +2472,8 @@ class CanvasModel with ChangeNotifier {
|
||||
style != null ? ScrollStyle.fromString(style) : ScrollStyle.scrollauto;
|
||||
|
||||
if (_scrollStyle != ScrollStyle.scrollauto) {
|
||||
_resetScroll();
|
||||
// Scrollbar and Scroll Edge share controllers and retain their positions.
|
||||
updateScrollPercent();
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
@@ -2696,20 +2697,10 @@ class CanvasModel with ChangeNotifier {
|
||||
|
||||
setScrollPercent(scrollPixelPercent.x, scrollPixelPercent.y);
|
||||
pushScrollPositionToUI(scrollPixel.x, scrollPixel.y);
|
||||
// A no-op jump emits no notification to refresh the actual scroll fractions.
|
||||
updateScrollPercent();
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void updateScrollAfterLayout((double, double) renderedScroll) {
|
||||
updateScrollPercent();
|
||||
// A delayed refresh may already have changed the model without repainting.
|
||||
if (renderedScroll != (_scrollX, _scrollY)) {
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
panX(double dx) {
|
||||
_x += dx;
|
||||
if (isMobile) {
|
||||
@@ -2860,27 +2851,15 @@ class CanvasModel with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
// Bound integer cache keys and raster allocation: 4096 squared RGBA is 64 MiB.
|
||||
const _maxCursorRasterSize = 4096;
|
||||
|
||||
bool _validCursorRasterSize(double width, double height,
|
||||
{double rasterScale = 1}) =>
|
||||
width.isFinite && height.isFinite && rasterScale.isFinite &&
|
||||
width > 0 && height > 0 && rasterScale > 0 &&
|
||||
width.ceilToDouble() * rasterScale <= _maxCursorRasterSize &&
|
||||
height.ceilToDouble() * rasterScale <= _maxCursorRasterSize;
|
||||
|
||||
// Scale the host's bitmap and hotspot together. Incorrect source geometry
|
||||
// must be fixed in host capture, independently of the client's sizing policy.
|
||||
// data for cursor
|
||||
class CursorData {
|
||||
// At most 1 MiB of RGBA, including Linux's square cursor padding: twice the largest
|
||||
// accessibility cursor, beyond which a cursor is shown smaller rather than larger.
|
||||
static const _maxRasterSize = 512;
|
||||
|
||||
final String peerId;
|
||||
final String id;
|
||||
final img2.Image image;
|
||||
// Borrowed from CursorModel/PredefinedCursor, which own its lifetime.
|
||||
// The plugin clones the handle before starting asynchronous encoding.
|
||||
final ui.Image nativeImage;
|
||||
// Zero preserves legacy sizing for capture backends without density metadata.
|
||||
final double pixelRatio;
|
||||
img2.Image? _image;
|
||||
double scale;
|
||||
Uint8List? data;
|
||||
final double hotxOrigin;
|
||||
@@ -2889,95 +2868,146 @@ class CursorData {
|
||||
double hoty;
|
||||
final int width;
|
||||
final int height;
|
||||
int _rasterWidth;
|
||||
int _rasterHeight;
|
||||
bool _scaleLimitReported = false;
|
||||
|
||||
int get rasterWidth => _rasterWidth;
|
||||
int get rasterHeight => _rasterHeight;
|
||||
|
||||
img2.Image get image => _image!;
|
||||
|
||||
/// False for a shape not in use; only the shape in use keeps pixels, for a new raster.
|
||||
bool get hasPixels => _image != null;
|
||||
|
||||
void releasePixels() {
|
||||
_image = null;
|
||||
data = null;
|
||||
}
|
||||
|
||||
CursorData({
|
||||
required this.peerId,
|
||||
required this.id,
|
||||
required this.image,
|
||||
required this.nativeImage,
|
||||
this.pixelRatio = 0,
|
||||
required img2.Image image,
|
||||
required this.scale,
|
||||
required this.data,
|
||||
required this.hotxOrigin,
|
||||
required this.hotyOrigin,
|
||||
required this.width,
|
||||
required this.height,
|
||||
}) : hotx = hotxOrigin * scale,
|
||||
}) : _image = image,
|
||||
_rasterWidth = (width * scale).ceil(),
|
||||
_rasterHeight = (height * scale).ceil(),
|
||||
hotx = hotxOrigin * scale,
|
||||
hoty = hotyOrigin * scale;
|
||||
|
||||
int _doubleToInt(double v) => (v * 10e6).round().toInt();
|
||||
|
||||
// Keep the minimum-size policy here. Native callers let the plugin rasterize
|
||||
// the original ui.Image; Web keeps the encoded-image resizing path.
|
||||
double? _validatedScale(double scale,
|
||||
{required bool useLegacyMinimum, required double rasterScale}) {
|
||||
if (!scale.isFinite || scale <= 0) {
|
||||
debugPrint('Rejected cursor $id: invalid scale $scale');
|
||||
return null;
|
||||
double _limitScale(double requestedScale) {
|
||||
final valid = requestedScale.isFinite && requestedScale > 0;
|
||||
// Invalid requests retain the last valid raster and hotspot.
|
||||
final limitedScale = valid
|
||||
? min(requestedScale, _maxRasterSize / max(width, height))
|
||||
: scale;
|
||||
final limited = !valid || limitedScale != requestedScale;
|
||||
if (limited && !_scaleLimitReported) {
|
||||
debugPrint(
|
||||
'Cursor $id: rejected scale $requestedScale for ${width}x$height; '
|
||||
'using $limitedScale (maximum raster side $_maxRasterSize).');
|
||||
}
|
||||
// Preserve unscaled legacy artwork, but never enlarge a thin cursor just
|
||||
// to make its short edge reach the visibility minimum.
|
||||
if (!useLegacyMinimum || scale != 1.0) {
|
||||
_scaleLimitReported = limited;
|
||||
return limitedScale;
|
||||
}
|
||||
|
||||
double _checkUpdateScale(double scale) {
|
||||
scale = _limitScale(scale);
|
||||
if (scale != 1.0) {
|
||||
// A thin cursor must not grow just to make its short edge reach the minimum.
|
||||
scale = max(scale, kMinCursorSize / max(width, height));
|
||||
}
|
||||
|
||||
if (!_validCursorRasterSize(width * scale, height * scale,
|
||||
rasterScale: rasterScale)) {
|
||||
debugPrint('Rejected cursor $id: raster ${width * scale}x${height * scale} '
|
||||
'at pixel ratio $rasterScale exceeds $_maxCursorRasterSize');
|
||||
return null;
|
||||
final targetWidth = (width * scale).ceil();
|
||||
final targetHeight = (height * scale).ceil();
|
||||
if ((_rasterWidth != targetWidth || _rasterHeight != targetHeight) &&
|
||||
!hasPixels) {
|
||||
// Nothing to make this raster from; buildCursorOfCache asks for the pixels unless its
|
||||
// native cursor was made before.
|
||||
data = null;
|
||||
return scale;
|
||||
}
|
||||
return scale;
|
||||
}
|
||||
|
||||
double _checkUpdateScale(double scale, {required bool resizeImage}) {
|
||||
double oldScale = this.scale;
|
||||
// Web's long-edge minimum can round a thin axis below one raster pixel.
|
||||
final webWidth = max(1, (width * scale).round());
|
||||
final webHeight = max(1, (height * scale).round());
|
||||
if (resizeImage && _doubleToInt(oldScale) != _doubleToInt(scale)) {
|
||||
if (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
|
||||
if (isWindows) {
|
||||
data = img2
|
||||
.copyResize(
|
||||
image,
|
||||
width: (width * scale).toInt(),
|
||||
height: (height * scale).toInt(),
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
interpolation: img2.Interpolation.average,
|
||||
)
|
||||
.getBytes(order: img2.ChannelOrder.bgra);
|
||||
} else if (isDesktop && scale < 1.0 && !image.hasPalette) {
|
||||
data = Uint8List.fromList(
|
||||
img2.encodePng(_resizeWithAlpha(targetWidth, targetHeight)));
|
||||
} else {
|
||||
data = Uint8List.fromList(
|
||||
img2.encodePng(
|
||||
img2.copyResize(
|
||||
image,
|
||||
width: isWeb ? webWidth : (width * scale).toInt(),
|
||||
height: isWeb ? webHeight : (height * scale).toInt(),
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
interpolation: img2.Interpolation.average,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
_rasterWidth = targetWidth;
|
||||
_rasterHeight = targetHeight;
|
||||
}
|
||||
|
||||
this.scale = scale;
|
||||
hotx = hotxOrigin * scale;
|
||||
hoty = hotyOrigin * scale;
|
||||
if (isWeb) {
|
||||
// CSS hotspots must follow the actual rounded PNG dimensions.
|
||||
hotx = hotxOrigin * webWidth / width;
|
||||
hoty = hotyOrigin * webHeight / height;
|
||||
}
|
||||
hotx = hotxOrigin * _rasterWidth / width;
|
||||
hoty = hotyOrigin * _rasterHeight / height;
|
||||
return scale;
|
||||
}
|
||||
|
||||
String? updateGetKey(double scale,
|
||||
{bool resizeImage = true, bool useLegacyMinimum = true,
|
||||
double rasterScale = 1}) {
|
||||
final effectiveScale = _validatedScale(scale,
|
||||
useLegacyMinimum: useLegacyMinimum, rasterScale: rasterScale);
|
||||
if (effectiveScale == null) return null;
|
||||
_checkUpdateScale(effectiveScale, resizeImage: resizeImage);
|
||||
return '${peerId}_${id}_${_doubleToInt(width * effectiveScale)}_${_doubleToInt(height * effectiveScale)}';
|
||||
img2.Image _resizeWithAlpha(int targetWidth, int targetHeight) {
|
||||
final resized =
|
||||
img2.Image.fromResized(image, width: targetWidth, height: targetHeight);
|
||||
final dx = image.width / targetWidth;
|
||||
final dy = image.height / targetHeight;
|
||||
// Use the average filter's sample area, but weight RGB by alpha so
|
||||
// transparent pixels do not darken visible edges in the straight-alpha PNG.
|
||||
for (final pixel in resized) {
|
||||
final x = (pixel.x * dx).toInt();
|
||||
final y = (pixel.y * dy).toInt();
|
||||
final sampleWidth = ((pixel.x + 1) * dx).toInt() - x;
|
||||
final sampleHeight = ((pixel.y + 1) * dy).toInt() - y;
|
||||
final samples = image.getRange(x, y, sampleWidth, sampleHeight);
|
||||
num r = 0;
|
||||
num g = 0;
|
||||
num b = 0;
|
||||
num a = 0;
|
||||
while (samples.moveNext()) {
|
||||
final sample = samples.current;
|
||||
r += sample.r * sample.a;
|
||||
g += sample.g * sample.a;
|
||||
b += sample.b * sample.a;
|
||||
a += sample.a;
|
||||
}
|
||||
if (a == 0) {
|
||||
pixel.setRgba(0, 0, 0, 0);
|
||||
continue;
|
||||
}
|
||||
pixel.setRgba(r / a, g / a, b / a, a / (sampleWidth * sampleHeight));
|
||||
}
|
||||
return resized;
|
||||
}
|
||||
|
||||
String updateGetKey(double scale) {
|
||||
scale = _checkUpdateScale(scale);
|
||||
// The raster asked for, not the one made last: a shape without pixels keeps the native
|
||||
// cursors of every raster it was shown at.
|
||||
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${(width * scale).ceil()}_${(height * scale).ceil()}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3017,8 +3047,7 @@ class PredefinedCursor {
|
||||
CursorData? get cache => _cache;
|
||||
|
||||
init() {
|
||||
final pngBytes = base64Decode(png);
|
||||
_image2 = img2.decodePng(pngBytes);
|
||||
_image2 = img2.decodePng(base64Decode(png));
|
||||
if (_image2 != null) {
|
||||
// The png type of forbidden cursor image is `PngColorType.indexed`.
|
||||
if (id == kPreForbiddenCursorId) {
|
||||
@@ -3026,20 +3055,17 @@ class PredefinedCursor {
|
||||
}
|
||||
|
||||
() async {
|
||||
final defaultImg = _image2!;
|
||||
// This function is called only one time, no need to care about the performance.
|
||||
Uint8List data = defaultImg.getBytes(order: img2.ChannelOrder.rgba);
|
||||
_image?.dispose();
|
||||
// Native registration uses this ui.Image. The RGBA bytes from img2 are
|
||||
// straight alpha, but PixelFormat.rgba8888 requires premultiplied alpha.
|
||||
// Decode the PNG directly to preserve translucent cursor colors.
|
||||
final codec = await ui.instantiateImageCodec(pngBytes);
|
||||
final ui.Image nativeImage;
|
||||
try {
|
||||
nativeImage = (await codec.getNextFrame()).image;
|
||||
} finally {
|
||||
codec.dispose();
|
||||
_image = await img.decodeImageFromPixels(
|
||||
data, defaultImg.width, defaultImg.height, ui.PixelFormat.rgba8888);
|
||||
if (_image == null) {
|
||||
print("decodeImageFromPixels failed, pre-defined cursor $id");
|
||||
return;
|
||||
}
|
||||
_image = nativeImage;
|
||||
double scale = 1.0;
|
||||
final Uint8List data;
|
||||
if (isWindows) {
|
||||
data = _image2!.getBytes(order: img2.ChannelOrder.bgra);
|
||||
} else {
|
||||
@@ -3050,7 +3076,6 @@ class PredefinedCursor {
|
||||
peerId: '',
|
||||
id: id,
|
||||
image: _image2!.clone(),
|
||||
nativeImage: nativeImage,
|
||||
scale: scale,
|
||||
data: data,
|
||||
hotxOrigin:
|
||||
@@ -3153,7 +3178,16 @@ class CursorModel with ChangeNotifier {
|
||||
|
||||
get lastIsBlocked => _lastIsBlocked;
|
||||
|
||||
ui.Image? get image => _image;
|
||||
/// The image of the shape in use, or the one shown before until it is back: a switch falls
|
||||
/// back to the default cursor only for a shape the core cannot give. Asks the core for the
|
||||
/// shape in use when it was let go.
|
||||
ui.Image? get image {
|
||||
if (_images[_id] == null && _cacheMap.containsKey(_id)) {
|
||||
restorePixels(_id);
|
||||
}
|
||||
return _image;
|
||||
}
|
||||
|
||||
CursorData? get cache => _cache;
|
||||
|
||||
double get x => _x - _displayOriginX;
|
||||
@@ -3166,7 +3200,10 @@ class CursorModel with ChangeNotifier {
|
||||
double get hotx => _hotx;
|
||||
double get hoty => _hoty;
|
||||
|
||||
set id(String id) => _id = id;
|
||||
set id(String id) {
|
||||
if (_id != id) _unavailable = null;
|
||||
_id = id;
|
||||
}
|
||||
|
||||
bool get isPeerControlProtected =>
|
||||
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
|
||||
@@ -3181,7 +3218,12 @@ class CursorModel with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
CursorModel(this.parent);
|
||||
CursorModel(this.parent) {
|
||||
// Made now, not when first drawn: nothing draws again when their decode lands, so the first
|
||||
// build that needs one would show the shape before in its place.
|
||||
preDefaultCursor.cache;
|
||||
preForbiddenCursor.cache;
|
||||
}
|
||||
|
||||
Set<String> get cachedKeys => _cacheKeys;
|
||||
addKey(String key) => _cacheKeys.add(key);
|
||||
@@ -3480,103 +3522,84 @@ class CursorModel with ChangeNotifier {
|
||||
_images.clear();
|
||||
}
|
||||
|
||||
updateCursorData(Map<String, dynamic> evt) async {
|
||||
final id = evt['id'];
|
||||
final hotx = double.parse(evt['hotx']);
|
||||
final hoty = double.parse(evt['hoty']);
|
||||
final width = int.parse(evt['width']);
|
||||
final height = int.parse(evt['height']);
|
||||
// Rust validates native packets; Web receives them directly from JavaScript.
|
||||
if (isWeb && !_validCursorRasterSize(width.toDouble(), height.toDouble())) {
|
||||
debugPrint('Rejected cursor $id: invalid source size ${width}x$height');
|
||||
return;
|
||||
}
|
||||
final pixelRatio = double.tryParse(evt['scale'] ?? '0');
|
||||
if (pixelRatio == null ||
|
||||
(isWeb && (!pixelRatio.isFinite || pixelRatio < 0 ||
|
||||
(pixelRatio > 0 &&
|
||||
!_validCursorRasterSize(width / pixelRatio, height / pixelRatio))))) {
|
||||
debugPrint('Rejected cursor $id: invalid pixel ratio ${evt['scale']}');
|
||||
return;
|
||||
}
|
||||
List<dynamic> colors = json.decode(evt['colors']);
|
||||
const bytesPerPixel = 4;
|
||||
if (isWeb && colors.length != width * height * bytesPerPixel) {
|
||||
debugPrint('Rejected cursor $id: invalid RGBA length ${colors.length}');
|
||||
return;
|
||||
}
|
||||
final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
|
||||
final ui.Image? image;
|
||||
final platform = parent.target?.ffiModel.pi.platform;
|
||||
if (!isWeb &&
|
||||
(platform == kPeerPlatformMacOS || platform == kPeerPlatformWindows)) {
|
||||
image = await _decodeStraightAlphaCursor(rgba, width, height);
|
||||
} else {
|
||||
image = await img.decodeImageFromPixels(
|
||||
rgba, width, height, ui.PixelFormat.rgba8888);
|
||||
}
|
||||
/// Its image is kept with the ones used last, see [_imageLimit]; a shape that does not decode
|
||||
/// is marked as one the core cannot give.
|
||||
Future<void> updateCursorData(String id, int hotxInt, int hotyInt, int width,
|
||||
int height, Uint8List rgba) async {
|
||||
final generation = _generation;
|
||||
if (_unavailable == id) _unavailable = null;
|
||||
final hotx = hotxInt.toDouble();
|
||||
final hoty = hotyInt.toDouble();
|
||||
final image = await img.decodeImageFromPixels(
|
||||
rgba, width, height, ui.PixelFormat.rgba8888);
|
||||
if (image == null) {
|
||||
// It did not decode; painting must not ask for it on every frame.
|
||||
_markUnavailable(generation, id);
|
||||
return;
|
||||
}
|
||||
if (await _updateCache(rgba, image, id, hotx, hoty, width, height,
|
||||
pixelRatio: pixelRatio)) {
|
||||
_images[id]?.item1.dispose();
|
||||
_images[id] = Tuple3(image, hotx, hoty);
|
||||
} else {
|
||||
if (!await _updateCache(
|
||||
generation, rgba, image, id, hotx, hoty, width, height)) {
|
||||
// Not kept, or the session was cleared while it decoded.
|
||||
image.dispose();
|
||||
_markUnavailable(generation, id);
|
||||
return;
|
||||
}
|
||||
final old = _images.remove(id);
|
||||
_images[id] = Tuple3(image, hotx, hoty);
|
||||
if (old != null) {
|
||||
if (identical(old.item1, _image)) _image = image;
|
||||
old.item1.dispose();
|
||||
}
|
||||
|
||||
// Update last cursor data.
|
||||
// Do not use the previous `image` and `id`, because `_id` may be changed.
|
||||
_updateCurData();
|
||||
}
|
||||
|
||||
Future<ui.Image?> _decodeStraightAlphaCursor(
|
||||
Uint8List rgba, int width, int height) async {
|
||||
// macOS and Win32 capture send straight alpha; XFixes/DRM are premultiplied.
|
||||
// Convert a copy for native ui.Image, preserving the wire and PNG cache colors.
|
||||
final source = img2.Image.fromBytes(
|
||||
width: width, height: height, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
|
||||
for (final pixel in source) {
|
||||
final opacity = pixel.a / pixel.maxChannelValue;
|
||||
pixel.r = (pixel.r * opacity).round();
|
||||
pixel.g = (pixel.g * opacity).round();
|
||||
pixel.b = (pixel.b * opacity).round();
|
||||
}
|
||||
return img.decodeImageFromPixels(
|
||||
source.getBytes(), width, height, ui.PixelFormat.rgba8888);
|
||||
final cache = _cacheMap[id];
|
||||
if (id != _id && cache != null) _switchedAway(cache);
|
||||
}
|
||||
|
||||
Future<bool> _updateCache(
|
||||
int generation,
|
||||
Uint8List rgba,
|
||||
ui.Image image,
|
||||
String id,
|
||||
double hotx,
|
||||
double hoty,
|
||||
int w,
|
||||
int h, {
|
||||
required double pixelRatio,
|
||||
}) async {
|
||||
int h,
|
||||
) async {
|
||||
Uint8List? data;
|
||||
img2.Image imgOrigin = img2.Image.fromBytes(
|
||||
width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
|
||||
width: w,
|
||||
height: h,
|
||||
bytes: rgba.buffer,
|
||||
bytesOffset: rgba.offsetInBytes,
|
||||
order: img2.ChannelOrder.rgba);
|
||||
if (isWindows) {
|
||||
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
|
||||
} else {
|
||||
ByteData? imgBytes =
|
||||
await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
if (imgBytes == null) {
|
||||
debugPrint('Unable to encode cursor $id as PNG');
|
||||
return false;
|
||||
}
|
||||
data = imgBytes.buffer.asUint8List();
|
||||
if (isDesktop &&
|
||||
(parent.target?.ffiModel.isPeerLinux == true ||
|
||||
parent.target?.ffiModel.isPeerWindows == true)) {
|
||||
// PNG decoding supplies straight alpha for Linux/Windows cursor resizing.
|
||||
final decoded = img2.decodePng(data);
|
||||
if (decoded == null) {
|
||||
debugPrint('Unable to decode cursor $id PNG for resizing');
|
||||
return false;
|
||||
}
|
||||
imgOrigin = decoded;
|
||||
}
|
||||
}
|
||||
final cache = CursorData(
|
||||
peerId: peerId,
|
||||
id: id,
|
||||
image: imgOrigin,
|
||||
nativeImage: image,
|
||||
pixelRatio: pixelRatio,
|
||||
scale: 1.0,
|
||||
data: data,
|
||||
hotxOrigin: hotx,
|
||||
@@ -3584,34 +3607,200 @@ class CursorModel with ChangeNotifier {
|
||||
width: w,
|
||||
height: h,
|
||||
);
|
||||
if (generation != _generation) {
|
||||
return false;
|
||||
}
|
||||
_cacheMap[id] = cache;
|
||||
return true;
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
Iterable<String> get shapeIds => _images.keys;
|
||||
|
||||
@visibleForTesting
|
||||
CursorData? cachedShape(String id) => _cacheMap[id];
|
||||
|
||||
final _restoring = <String>{};
|
||||
|
||||
// Tabs in a window share its engine's native cursors, predefined ones included.
|
||||
static int _nextKeyScope = 0;
|
||||
final int _keyScope = _nextKeyScope++;
|
||||
|
||||
String nativeKey(CursorData cache, double scale) {
|
||||
final key = '${_keyScope}_${cache.updateGetKey(scale)}';
|
||||
// A native cursor at another raster does not hold the pixels this one is made from.
|
||||
if (!_cacheKeys.contains(key)) _nativeIds.remove(cache.id);
|
||||
return key;
|
||||
}
|
||||
|
||||
// Native cursors stay for the session, one per raster of each shape, and only [clear]
|
||||
// deletes them, as before; unlike the painted images they have no LRU, for now. A delete
|
||||
// frees nothing on Windows: the engine's `deleteCustomCursor/windows` releases the HCURSOR
|
||||
// with `DeleteObject`, which does not take a cursor. Measured on Windows with 500 cursors
|
||||
// made by `CreateIconIndirect`, as the engine makes them: `DeleteObject` failed all 500 and
|
||||
// left 500 USER objects alive, while `DestroyCursor` or `DestroyIcon` freed all 500. Each
|
||||
// delete leaks its handle until the process exits, and making the cursor again for a raster
|
||||
// or a shape shown once more leaks another, so an LRU would leak more than keeping them.
|
||||
//
|
||||
// Fixing the engine is not cheap. x64 runs our fork, rustdesk/engine, on Flutter 3.24; the
|
||||
// fix is one more patch to rebuild, publish, and carry across every Flutter upgrade. arm64
|
||||
// runs the stock engine of a newer Flutter, which has the same code: fixing it means
|
||||
// porting the fork to that version and building and publishing an arm64 engine as well, or
|
||||
// an upstream fix and waiting for it to reach stable. Once both engines destroy cursors, an
|
||||
// LRU like the painted images' can come back. Content ids keep the count to the shapes the
|
||||
// peer really shows, a few dozen to a couple of hundred.
|
||||
|
||||
/// The shape in use keeps its pixels, so a new raster is made from them at once; the others
|
||||
/// keep none once their native cursor holds them.
|
||||
void registered(CursorData cache, String key) {
|
||||
_nativeIds.add(cache.id);
|
||||
_awaitingNative.remove(cache.id);
|
||||
if (cache.id != _id && identical(_cacheMap[cache.id], cache)) {
|
||||
cache.releasePixels();
|
||||
}
|
||||
}
|
||||
|
||||
// The shapes a native cursor holds, and those keeping their pixels until one does, oldest
|
||||
// first: one decoded after the peer moved on must still get a native cursor when shown
|
||||
// again, rather than be decoded again every time it comes back.
|
||||
final _nativeIds = <String>{};
|
||||
final _awaitingNative = <String>{};
|
||||
|
||||
void _switchedAway(CursorData cache) {
|
||||
_awaitingNative.remove(cache.id);
|
||||
// Mobile only paints the cursor, from its image.
|
||||
if (isMobile || _nativeIds.contains(cache.id)) {
|
||||
cache.releasePixels();
|
||||
return;
|
||||
}
|
||||
_awaitingNative.add(cache.id);
|
||||
while (_awaitingNative.length > kRecentShapes) {
|
||||
final oldest = _awaitingNative.first;
|
||||
_awaitingNative.remove(oldest);
|
||||
if (oldest != _id) _cacheMap[oldest]?.releasePixels();
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer's shapes used last that keep a painted image, and the most that keep their pixels
|
||||
/// waiting for a native cursor; the core rebuilds the others. An animated cursor is a shape per
|
||||
/// frame, 18 for the Windows busy cursor and 23 for KDE's, and a cycle longer than this limit
|
||||
/// would rebuild every frame.
|
||||
static const kRecentShapes = 64;
|
||||
|
||||
/// The native cursor of the shape shown last, shown on while the shape in use is made.
|
||||
String? shownKey;
|
||||
|
||||
void shown(CursorData cache, String key) {
|
||||
// The forbidden cursor shows only while input is off; it is no stand-in for a shape.
|
||||
if (cache.id != kPreForbiddenCursorId) shownKey = key;
|
||||
}
|
||||
|
||||
/// Whether the desktop paints the peer's cursor over the remote image.
|
||||
@protected
|
||||
bool get showsRemoteCursor {
|
||||
final tag = ShowRemoteCursorState.tag(parent.target?.id ?? '');
|
||||
return Get.isRegistered<RxBool>(tag: tag) &&
|
||||
Get.find<RxBool>(tag: tag).value;
|
||||
}
|
||||
|
||||
// Painted images kept: mobile always paints the cursor, a desktop only when it shows the
|
||||
// remote cursor, and otherwise the native cursors show the shapes.
|
||||
int get _imageLimit => isMobile || showsRemoteCursor ? kRecentShapes : 1;
|
||||
|
||||
// `_images` is in order of use. The image painted is kept, whoever's it is.
|
||||
void _evictImages() {
|
||||
var excess = _images.length - _imageLimit;
|
||||
_images.removeWhere((id, shape) {
|
||||
if (excess <= 0 || id == _id || identical(shape.item1, _image)) {
|
||||
return false;
|
||||
}
|
||||
excess--;
|
||||
shape.item1.dispose();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// The core keeps every shape the peer sent, compressed; see `Session::cursor_shapes`.
|
||||
@protected
|
||||
Future<CursorShape?> fetchCursorShape(String id) {
|
||||
final ffi = parent.target;
|
||||
if (ffi == null) return Future.value(null);
|
||||
return bind.sessionGetCursorShape(sessionId: ffi.sessionId, id: id);
|
||||
}
|
||||
|
||||
// The shape the core could not give, not asked for again while it is the one in use. One
|
||||
// is enough: only the shape in use is asked for on every frame, and the peer's ids must not
|
||||
// accumulate here.
|
||||
String? _unavailable;
|
||||
// Counts session clears, so that a decode finishing after one keeps nothing.
|
||||
int _generation = 0;
|
||||
|
||||
/// Decodes the shape in use again from the core, for a raster its native cursor lacks, for
|
||||
/// painting it, or for a window a tab moved to.
|
||||
void restorePixels(String id) {
|
||||
if (id != _id || _unavailable == id || !_restoring.add(id)) return;
|
||||
final generation = _generation;
|
||||
() async {
|
||||
try {
|
||||
// A throw becomes an error the await hands over later, not during the build that may
|
||||
// have asked: a failure tells the listeners.
|
||||
final shape = await Future.sync(() => fetchCursorShape(id));
|
||||
if (generation != _generation) {
|
||||
return;
|
||||
} else if (shape == null) {
|
||||
_markUnavailable(generation, id);
|
||||
debugPrint('Cursor $id is not kept by the core');
|
||||
} else {
|
||||
// Decoded even if the peer moved on: an animation comes back to it.
|
||||
await updateCursorData(id, shape.hotx, shape.hoty, shape.width,
|
||||
shape.height, shape.colors);
|
||||
}
|
||||
} catch (e) {
|
||||
_markUnavailable(generation, id);
|
||||
debugPrint('Failed to fetch cursor $id: $e');
|
||||
} finally {
|
||||
_restoring.remove(id);
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
void _markUnavailable(int generation, String id) {
|
||||
if (generation != _generation || id != _id) return;
|
||||
_unavailable = id;
|
||||
_updateCurData();
|
||||
}
|
||||
|
||||
bool _updateCurData() {
|
||||
_cache = _cacheMap[_id];
|
||||
final tmp = _images[_id];
|
||||
final previous = _cache;
|
||||
final cache = _cacheMap[_id];
|
||||
// A shape not decoded yet leaves the one shown before in place until it is; one the core
|
||||
// cannot give leaves none, so the default cursor shows, as for a shape never sent.
|
||||
if (cache != null || _unavailable == _id) _cache = cache;
|
||||
if (previous != null && !identical(previous, _cache)) {
|
||||
_switchedAway(previous);
|
||||
}
|
||||
final tmp = _images.remove(_id);
|
||||
if (tmp != null) {
|
||||
_images[_id] = tmp;
|
||||
_image = tmp.item1;
|
||||
_hotx = tmp.item2;
|
||||
_hoty = tmp.item3;
|
||||
try {
|
||||
// may throw exception, because the listener maybe already dispose
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint(
|
||||
'WARNING: updateCursorId $_id, without notifyListeners(). $e');
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
} else if (_unavailable == _id) {
|
||||
_image = null;
|
||||
}
|
||||
_evictImages();
|
||||
try {
|
||||
// may throw exception, because the listener maybe already dispose
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('WARNING: updateCursorId $_id, without notifyListeners(). $e');
|
||||
}
|
||||
return tmp != null || cache != null;
|
||||
}
|
||||
|
||||
updateCursorId(Map<String, dynamic> evt) {
|
||||
if (!_updateCurData()) {
|
||||
debugPrint(
|
||||
'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
|
||||
restorePixels(_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3664,6 +3853,10 @@ class CursorModel with ChangeNotifier {
|
||||
_clearCache();
|
||||
_cache = null;
|
||||
_cacheMap.clear();
|
||||
_nativeIds.clear();
|
||||
_awaitingNative.clear();
|
||||
_unavailable = null;
|
||||
_generation++;
|
||||
}
|
||||
|
||||
_clearCache() {
|
||||
@@ -3672,6 +3865,8 @@ class CursorModel with ChangeNotifier {
|
||||
debugPrint("deleting cursor with key $k");
|
||||
deleteCustomCursor(k);
|
||||
}
|
||||
_cacheKeys.clear();
|
||||
shownKey = null;
|
||||
resetSystemCursor();
|
||||
}
|
||||
|
||||
@@ -3707,9 +3902,11 @@ class QualityMonitorModel with ChangeNotifier {
|
||||
bool get show => _show;
|
||||
QualityMonitorData get data => _data;
|
||||
|
||||
// Only a WebRTC session names its transport here: web has no session tab
|
||||
// to show it on, and WebRTC is the one path that can be direct or TURN.
|
||||
// Only a WebRTC session on the web names its transport here: web has no
|
||||
// session tab to show it on (the desktop tab's tooltip already does), and
|
||||
// WebRTC is the one path that can be direct or TURN.
|
||||
String? get webrtcTransport {
|
||||
if (!isWeb) return null;
|
||||
final ffiModel = parent.target?.ffiModel;
|
||||
if (ffiModel == null) return null;
|
||||
final streamType = ffiModel.cachedPeerData.streamType;
|
||||
@@ -4009,6 +4206,7 @@ class FFI {
|
||||
}
|
||||
|
||||
if (isWeb) {
|
||||
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
|
||||
platformFFI.setRgbaCallback((int display, Uint8List data) {
|
||||
onEvent2UIRgba();
|
||||
imageModel.onRgba(display, data);
|
||||
@@ -4091,6 +4289,9 @@ class FFI {
|
||||
} else {
|
||||
platformFFI.nextRgba(sessionId, display);
|
||||
}
|
||||
} else if (message is EventToUI_Cursor) {
|
||||
await ffiModel.handleCursorData(message.id, message.hotx,
|
||||
message.hoty, message.width, message.height, message.colors);
|
||||
} else if (message is EventToUI_Texture) {
|
||||
final display = message.field0;
|
||||
final gpuTexture = message.field1;
|
||||
|
||||
@@ -285,6 +285,10 @@ class PlatformFFI {
|
||||
|
||||
void setRgbaCallback(void Function(int, Uint8List) fun) async {}
|
||||
|
||||
// web only
|
||||
void setCursorDataCallback(
|
||||
void Function(String, int, int, int, int, Uint8List) fun) async {}
|
||||
|
||||
// web only, decoded WebCodecs frames arriving as ready-made images
|
||||
void setVideoFrameCallback(
|
||||
Future<void> Function(int, ui.Image, bool Function()) fun) {}
|
||||
|
||||
@@ -9,6 +9,7 @@ import 'platform_model.dart';
|
||||
import 'rustdesk_terminal.dart';
|
||||
import 'terminal_copy_shortcut.dart';
|
||||
import 'terminal_mouse_drag_reporter.dart';
|
||||
import 'terminal_scroll_controller.dart';
|
||||
|
||||
part 'terminal_mouse_handler_input.dart';
|
||||
part 'terminal_web_clipboard_gesture.dart';
|
||||
@@ -55,7 +56,7 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
static const _scrollDown = 1;
|
||||
|
||||
final _terminalViewKey = GlobalKey<TerminalViewState>();
|
||||
final _scrollController = ScrollController();
|
||||
late final _scrollController = TerminalScrollController(() => widget.terminal);
|
||||
final _mouseDrag = TerminalMouseDragReporter();
|
||||
late final WheelButtonFixMouseHandler _mouseHandler;
|
||||
TerminalMouseHandler? _previousMouseHandler;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:xterm/xterm.dart';
|
||||
|
||||
class TerminalScrollController extends ScrollController {
|
||||
TerminalScrollController(this.terminal);
|
||||
|
||||
final Terminal Function() terminal;
|
||||
|
||||
@override
|
||||
ScrollPosition createScrollPosition(ScrollPhysics physics,
|
||||
ScrollContext context, ScrollPosition? oldPosition) {
|
||||
return super.createScrollPosition(
|
||||
_TerminalScrollPhysics(terminal, parent: physics),
|
||||
context,
|
||||
oldPosition,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TerminalScrollPhysics extends ScrollPhysics {
|
||||
const _TerminalScrollPhysics(this.terminal, {super.parent});
|
||||
|
||||
final Terminal Function() terminal;
|
||||
|
||||
@override
|
||||
_TerminalScrollPhysics applyTo(ScrollPhysics? ancestor) =>
|
||||
_TerminalScrollPhysics(terminal, parent: buildParent(ancestor));
|
||||
|
||||
@override
|
||||
bool shouldAcceptUserOffset(ScrollMetrics position) {
|
||||
// A retained main-screen offset can make this inner scrollable win the
|
||||
// trackpad gesture, starving xterm's outer alternate-screen scroll handler.
|
||||
if (terminal().isUsingAltBuffer) return false;
|
||||
return super.shouldAcceptUserOffset(position);
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,17 @@ class PlatformFFI {
|
||||
};
|
||||
}
|
||||
|
||||
// The web core calls this with a shape's pixels as bytes, as it calls onRgba for a frame.
|
||||
void setCursorDataCallback(
|
||||
void Function(String, int, int, int, int, Uint8List) fun) {
|
||||
context["onCursorData"] = (String id, int hotx, int hoty, int width,
|
||||
int height, Uint8List? rgba) {
|
||||
if (rgba != null) {
|
||||
fun(id, hotx, hoty, width, height, rgba);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
late final WebVideoFrameQueue<JSObject, ui.Image> _videoFrameQueue;
|
||||
|
||||
// Zero-readback video path: the JS decoder hands decoded VideoFrames here
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter_custom_cursor/cursor_manager.dart'
|
||||
as custom_cursor_manager;
|
||||
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart' show WidgetsBinding;
|
||||
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/common.dart' show isLinux;
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
deleteCustomCursor(String key) =>
|
||||
custom_cursor_manager.CursorManager.instance.deleteCursor(key);
|
||||
@@ -20,51 +16,63 @@ resetSystemCursor() {}
|
||||
MouseCursor buildCursorOfCache(
|
||||
CursorModel cursor, double scale, CursorData? cache) {
|
||||
if (cache == null) {
|
||||
return MouseCursor.defer;
|
||||
return _shownCursor(cursor);
|
||||
} else {
|
||||
// Include the live DPR so moving between monitors rebuilds the native
|
||||
// bitmap even when the remote view scale has not changed.
|
||||
final dpr = WidgetsBinding
|
||||
.instance.platformDispatcher.views.single.devicePixelRatio;
|
||||
// Keep Original and older peers' pixel units and scale-1 behavior.
|
||||
// Resizing uses a long-edge minimum regardless of source density.
|
||||
final legacyMinimum = cache.pixelRatio == 0 ||
|
||||
cursor.parent.target?.canvasModel.viewStyle.style == kRemoteViewStyleOriginal;
|
||||
// The minimum is logical, while Windows callers pass a physical scale.
|
||||
final effectiveScale = !legacyMinimum && isWindows
|
||||
? math.max(scale, kMinCursorSize * dpr / math.max(cache.width, cache.height))
|
||||
: scale;
|
||||
final cacheKey = cache.updateGetKey(effectiveScale, resizeImage: false,
|
||||
useLegacyMinimum: legacyMinimum,
|
||||
rasterScale: isWindows ? 1 : (isLinux ? dpr.ceilToDouble() : dpr));
|
||||
if (cacheKey == null) return MouseCursor.defer;
|
||||
final key = '${cacheKey}_$dpr';
|
||||
final key = cursor.nativeKey(cache, scale);
|
||||
if (!cursor.cachedKeys.contains(key)) {
|
||||
// data should be checked here, because it may be changed after `updateGetKey()`
|
||||
final data = cache.data;
|
||||
if (data == null) {
|
||||
cursor.restorePixels(cache.id);
|
||||
return _shownCursor(cursor);
|
||||
}
|
||||
// Square canvases avoid clipping or stray edge pixels on Linux.
|
||||
final width = isLinux && cache.rasterWidth < cache.rasterHeight
|
||||
? cache.rasterHeight
|
||||
: cache.rasterWidth;
|
||||
final height = isLinux ? width : cache.rasterHeight;
|
||||
debugPrint(
|
||||
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
|
||||
unawaited(custom_cursor_manager.CursorManager.instance
|
||||
.registerCursorImage(
|
||||
name: key,
|
||||
image: cache.nativeImage,
|
||||
hotSpot: Offset(cache.hotxOrigin, cache.hotyOrigin),
|
||||
// Windows callers already express scale in physical pixels.
|
||||
// The plugin takes logical scale and applies DPR during rasterization.
|
||||
scale: isWindows ? cache.scale / dpr : cache.scale,
|
||||
devicePixelRatio: dpr,
|
||||
)
|
||||
.then<void>((_) {}, onError: (Object error, StackTrace stack) {
|
||||
cursor.cachedKeys.remove(key);
|
||||
FlutterError.reportError(FlutterErrorDetails(
|
||||
exception: error,
|
||||
stack: stack,
|
||||
library: 'native cursor',
|
||||
context: ErrorDescription('registering cursor $key')));
|
||||
}));
|
||||
// [Safety]
|
||||
// It's ok to call async registerCursor in current synchronous context,
|
||||
// because activating the cursor is also an async call and will always
|
||||
// be executed after this.
|
||||
custom_cursor_manager.CursorManager.instance
|
||||
.registerCursor(custom_cursor_manager.CursorData()
|
||||
..name = key
|
||||
..buffer =
|
||||
width == cache.rasterWidth && height == cache.rasterHeight
|
||||
? data
|
||||
: _padCursor(data, width)
|
||||
..width = width
|
||||
..height = height
|
||||
..hotX = cache.hotx
|
||||
..hotY = cache.hoty);
|
||||
cursor.addKey(key);
|
||||
cursor.registered(cache, key);
|
||||
}
|
||||
return FlutterCustomMemoryImageCursor(
|
||||
key: key,
|
||||
registrationToken: custom_cursor_manager.CursorManager.instance
|
||||
.registrationTokenFor(key));
|
||||
cursor.shown(cache, key);
|
||||
return FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
}
|
||||
|
||||
// The last shape's cursor stays while the one in use is made, rather than the system one.
|
||||
MouseCursor _shownCursor(CursorModel cursor) {
|
||||
final key = cursor.shownKey;
|
||||
return key == null
|
||||
? MouseCursor.defer
|
||||
: FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
|
||||
Uint8List _padCursor(Uint8List data, int size) {
|
||||
final bitmap = img.decodePng(data);
|
||||
if (bitmap == null) {
|
||||
throw const FormatException('Invalid native cursor PNG');
|
||||
}
|
||||
final padded = img.copyExpandCanvas(bitmap,
|
||||
newWidth: size,
|
||||
newHeight: size,
|
||||
position: img.ExpandCanvasPosition.topLeft,
|
||||
toImage: img.Image(width: size, height: size, numChannels: 4));
|
||||
return Uint8List.fromList(img.encodePng(padded));
|
||||
}
|
||||
|
||||
@@ -96,14 +96,12 @@ class ImagePainter extends CustomPainter {
|
||||
required this.x,
|
||||
required this.y,
|
||||
required this.scale,
|
||||
this.useIntegerPosition = true,
|
||||
});
|
||||
|
||||
ui.Image? image;
|
||||
double x;
|
||||
double y;
|
||||
double scale;
|
||||
final bool useIntegerPosition;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
@@ -124,10 +122,8 @@ class ImagePainter extends CustomPainter {
|
||||
if (isWeb) {
|
||||
paint.filterQuality = FilterQuality.high;
|
||||
}
|
||||
final position = useIntegerPosition
|
||||
? Offset(x.toInt().toDouble(), y.toInt().toDouble())
|
||||
: Offset(x, y);
|
||||
canvas.drawImage(image!, position, paint);
|
||||
canvas.drawImage(
|
||||
image!, Offset(x.toInt().toDouble(), y.toInt().toDouble()), paint);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -26,6 +26,14 @@ sealed class EventToUI {
|
||||
int field0,
|
||||
bool field1,
|
||||
) = EventToUI_Texture;
|
||||
const factory EventToUI.cursor({
|
||||
required String id,
|
||||
required int hotx,
|
||||
required int hoty,
|
||||
required int width,
|
||||
required int height,
|
||||
required Uint8List colors,
|
||||
}) = EventToUI_Cursor;
|
||||
}
|
||||
|
||||
class EventToUI_Event implements EventToUI {
|
||||
@@ -50,7 +58,60 @@ class EventToUI_Texture implements EventToUI {
|
||||
bool get field1 => f1;
|
||||
}
|
||||
|
||||
class EventToUI_Cursor implements EventToUI {
|
||||
const EventToUI_Cursor({
|
||||
required this.id,
|
||||
required this.hotx,
|
||||
required this.hoty,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.colors,
|
||||
});
|
||||
final String id;
|
||||
final int hotx;
|
||||
final int hoty;
|
||||
final int width;
|
||||
final int height;
|
||||
final Uint8List colors;
|
||||
}
|
||||
|
||||
class CursorShape {
|
||||
final int hotx;
|
||||
final int hoty;
|
||||
final int width;
|
||||
final int height;
|
||||
final Uint8List colors;
|
||||
|
||||
const CursorShape({
|
||||
required this.hotx,
|
||||
required this.hoty,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.colors,
|
||||
});
|
||||
}
|
||||
|
||||
class RustdeskImpl {
|
||||
// The core answers through the callback, before callMethod returns.
|
||||
Future<CursorShape?> sessionGetCursorShape(
|
||||
{required UuidValue sessionId, required String id, dynamic hint}) {
|
||||
final completer = Completer<CursorShape?>();
|
||||
js.context.callMethod('getCursorShape', [
|
||||
id,
|
||||
(int hotx, int hoty, int width, int height, Uint8List? colors) {
|
||||
completer.complete(colors == null
|
||||
? null
|
||||
: CursorShape(
|
||||
hotx: hotx,
|
||||
hoty: hoty,
|
||||
width: width,
|
||||
height: height,
|
||||
colors: colors));
|
||||
}
|
||||
]);
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
Future<void> stopGlobalEventStream({required String appType, dynamic hint}) {
|
||||
throw UnimplementedError("stopGlobalEventStream");
|
||||
}
|
||||
@@ -901,7 +962,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.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:js' as js;
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -53,9 +52,8 @@ class CursorManager {
|
||||
'cursor',
|
||||
jsonEncode({
|
||||
'url': cursorData.url,
|
||||
// Rounding must keep the hotspot inside even a one-pixel raster.
|
||||
'hotx': cursorData.hotX.round().clamp(0, cursorData.width - 1),
|
||||
'hoty': cursorData.hotY.round().clamp(0, cursorData.height - 1),
|
||||
'hotx': cursorData.hotX.toInt(),
|
||||
'hoty': cursorData.hotY.toInt(),
|
||||
})
|
||||
]);
|
||||
}
|
||||
@@ -104,29 +102,37 @@ resetSystemCursor() => CursorManager.instance.resetSystemCursor();
|
||||
MouseCursor buildCursorOfCache(
|
||||
model.CursorModel cursor, double scale, model.CursorData? cache) {
|
||||
if (cache == null) {
|
||||
return MouseCursor.defer;
|
||||
return _shownCursor(cursor);
|
||||
} else {
|
||||
// A short-edge minimum can enlarge thin artwork beyond CSS cursor limits.
|
||||
// Keep unzoomed images unchanged and use the long edge when resizing.
|
||||
final key = cache.updateGetKey(scale, useLegacyMinimum: scale == 1.0);
|
||||
if (key == null) return MouseCursor.defer;
|
||||
final key = cursor.nativeKey(cache, scale);
|
||||
if (!cursor.cachedKeys.contains(key)) {
|
||||
// data should be checked here, because it may be changed after `updateGetKey()`
|
||||
final data = cache.data;
|
||||
if (data == null) {
|
||||
return MouseCursor.defer;
|
||||
cursor.restorePixels(cache.id);
|
||||
return _shownCursor(cursor);
|
||||
}
|
||||
debugPrint(
|
||||
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
|
||||
CursorManager.instance.registerCursor(CursorData(
|
||||
key: key,
|
||||
url: 'data:image/rgba;base64,${base64Encode(data)}',
|
||||
width: max(1, (cache.width * cache.scale).round()),
|
||||
height: max(1, (cache.height * cache.scale).round()),
|
||||
width: (cache.width * cache.scale).toInt(),
|
||||
height: (cache.height * cache.scale).toInt(),
|
||||
hotX: cache.hotx,
|
||||
hotY: cache.hoty));
|
||||
cursor.addKey(key);
|
||||
cursor.registered(cache, key);
|
||||
}
|
||||
cursor.shown(cache, key);
|
||||
return FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
}
|
||||
|
||||
// The last shape's cursor stays while the one in use is made, rather than the system one.
|
||||
MouseCursor _shownCursor(model.CursorModel cursor) {
|
||||
final key = cursor.shownKey;
|
||||
return key == null
|
||||
? MouseCursor.defer
|
||||
: FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
|
||||
@@ -339,8 +339,8 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "."
|
||||
ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
|
||||
resolved-ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
|
||||
ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
|
||||
resolved-ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
|
||||
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
|
||||
source: git
|
||||
version: "0.1.0"
|
||||
@@ -522,9 +522,9 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "."
|
||||
ref: "ad940aaac3aada70958df2de761adda1a71aa2c4"
|
||||
resolved-ref: "ad940aaac3aada70958df2de761adda1a71aa2c4"
|
||||
url: "https://github.com/fufesou/flutter_custom_cursor"
|
||||
ref: db63b785c38153603e9fb84b50d3ec46f0d7e05e
|
||||
resolved-ref: db63b785c38153603e9fb84b50d3ec46f0d7e05e
|
||||
url: "https://github.com/rustdesk-org/flutter_custom_cursor"
|
||||
source: git
|
||||
version: "0.0.3"
|
||||
flutter_gpu_texture_renderer:
|
||||
|
||||
@@ -58,12 +58,12 @@ dependencies:
|
||||
desktop_multi_window:
|
||||
git:
|
||||
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
|
||||
ref: 8b774a66671cbb9bcb2631af6ac28f9bdd469ce3
|
||||
ref: cddc2e64f8fefce4f80db87b20bcda2dd019bed6
|
||||
freezed_annotation: ^2.0.3
|
||||
flutter_custom_cursor:
|
||||
git:
|
||||
url: https://github.com/fufesou/flutter_custom_cursor
|
||||
ref: ad940aaac3aada70958df2de761adda1a71aa2c4
|
||||
url: https://github.com/rustdesk-org/flutter_custom_cursor
|
||||
ref: db63b785c38153603e9fb84b50d3ec46f0d7e05e
|
||||
window_size:
|
||||
git:
|
||||
url: https://github.com/21pages/flutter-desktop-embedding.git
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
// A file of its own: nothing else in this isolate has made the default cursor before the model.
|
||||
|
||||
/// A core that keeps no shape.
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
||||
@override
|
||||
Future<CursorShape?> fetchCursorShape(String id) => Future.value(null);
|
||||
@override
|
||||
bool get showsRemoteCursor => false;
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI() {
|
||||
ffiModel = FfiModel(WeakReference(this));
|
||||
cursorModel = _Cursor(this);
|
||||
}
|
||||
@override
|
||||
final SessionID sessionId = const Uuid().v4obj();
|
||||
@override
|
||||
late final FfiModel ffiModel;
|
||||
@override
|
||||
late final CursorModel cursorModel;
|
||||
}
|
||||
|
||||
String? _key(MouseCursor cursor) =>
|
||||
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final channel = Platform.isWindows
|
||||
? SystemChannels.mouseCursor
|
||||
: const MethodChannel('flutter_custom_cursor');
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
|
||||
(call) async => (call.arguments as Map<dynamic, dynamic>)['name']);
|
||||
|
||||
test('a shape the core cannot give shows the default cursor at once',
|
||||
() async {
|
||||
final ffi = _FFI();
|
||||
final cursor = ffi.cursorModel;
|
||||
final pixels = Uint8List.fromList(List.generate(8 * 8 * 4, (i) => i % 256));
|
||||
await ffi.ffiModel.handleCursorData('1', 0, 0, 8, 8, pixels);
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
final evt = {'id': '2'};
|
||||
ffi.ffiModel.updateLastCursorId(evt);
|
||||
ffi.ffiModel.handleCursorId(evt);
|
||||
// Not a wait for the default cursor itself: asking for it would make it.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
expect(cursor.cache, isNull);
|
||||
final built = _key(buildCursorOfCache(
|
||||
cursor, 1.0, cursor.cache ?? preDefaultCursor.cache));
|
||||
expect(built, isNot(shown));
|
||||
expect(built, contains('_${kPreDefaultCursorId}_'));
|
||||
cursor.disposeImages();
|
||||
});
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_custom_cursor/cursor_manager.dart' show CursorManager;
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/common.dart' as common;
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
void main() {
|
||||
_rasterBoundsTests();
|
||||
final registrations = <Map<dynamic, dynamic>>[];
|
||||
captureNativeCursors(registrations);
|
||||
for (final style in [kRemoteViewStyleAdaptive, kRemoteViewStyleCustom]) {
|
||||
for (final (density, width, dpr) in [
|
||||
(null, 4, 1.0),
|
||||
('0', 4, 2.0),
|
||||
(null, 32, 2.0),
|
||||
('0', 32, 1.0),
|
||||
]) {
|
||||
testWidgets(
|
||||
'legacy $style density=$density ${width}x32 DPR=$dpr',
|
||||
(tester) => tester.runAsync(() => checkDensity(
|
||||
tester, (style, density), registrations,
|
||||
sourceSize: Size(width.toDouble(), 32), dpr: dpr)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _rasterBoundsTests() {
|
||||
for (final (width, height, scale, legacy, rasterScale) in [
|
||||
(32, 32, 1e300, false, 1.0),
|
||||
(32, 32, 100.0, false, 2.0),
|
||||
]) {
|
||||
test('rejects raster ${width}x$height scale=$scale before key creation',
|
||||
() async {
|
||||
final image = await createTestImage(width: width, height: height);
|
||||
addTearDown(image.dispose);
|
||||
final data = CursorData(
|
||||
peerId: 'bounds',
|
||||
id: 'bounds',
|
||||
image: img.Image(width: width, height: height, numChannels: 4),
|
||||
nativeImage: image,
|
||||
scale: 1,
|
||||
data: null,
|
||||
hotxOrigin: 0,
|
||||
hotyOrigin: 0,
|
||||
width: width,
|
||||
height: height);
|
||||
final initial = data.updateGetKey(1, resizeImage: false);
|
||||
expect(
|
||||
data.updateGetKey(scale,
|
||||
resizeImage: false,
|
||||
useLegacyMinimum: legacy,
|
||||
rasterScale: rasterScale),
|
||||
isNull);
|
||||
expect(data.scale, 1);
|
||||
expect(data.updateGetKey(1, resizeImage: false), initial);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> checkDensity(WidgetTester tester, (String, String?) input,
|
||||
List<Map<dynamic, dynamic>> registrations,
|
||||
{Size sourceSize = const Size(32, 32), double dpr = 1}) async {
|
||||
final (style, density) = input;
|
||||
final id = '$style-$density';
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final canvas = CursorTestCanvas(dpr, style: style, scale: 0.5);
|
||||
final ffi = CursorTestFFI(canvas)..ffiModel.pi.platform = kPeerPlatformMacOS;
|
||||
final cursor = CursorModel(WeakReference(ffi))..id = id;
|
||||
addTearDown(() async {
|
||||
expect(cursor.parent.target, same(ffi));
|
||||
for (final key in cursor.cachedKeys) {
|
||||
await deleteCustomCursor(key);
|
||||
}
|
||||
cursor.disposeImages();
|
||||
cursor.dispose();
|
||||
canvas.dispose();
|
||||
});
|
||||
await cursor.updateCursorData(_cursorEvent(id, density, size: sourceSize));
|
||||
expect(cursor.cache!.pixelRatio, 0);
|
||||
await _paintCursor(tester, ffi, cursor);
|
||||
expect(tester.takeException(), isNull);
|
||||
for (final key in cursor.cachedKeys) {
|
||||
await CursorManager.instance.ensureCursorRegistered(key);
|
||||
}
|
||||
expect(registrations, hasLength(1));
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
expect(cursor.cache!.scale, 1.0);
|
||||
_expectLegacyRaster(registrations.single, sourceSize, dpr);
|
||||
}
|
||||
|
||||
Future<void> _paintCursor(
|
||||
WidgetTester tester, CursorTestFFI ffi, CursorModel cursor) async {
|
||||
await tester.pumpWidget(MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: ffi.canvasModel.devicePixelRatio),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ImageModel>(create: (_) => CursorTestImage()),
|
||||
ChangeNotifierProvider<CanvasModel>.value(value: ffi.canvasModel),
|
||||
ChangeNotifierProvider<CursorModel>.value(value: cursor),
|
||||
],
|
||||
child: ImagePaint(
|
||||
ffi: ffi,
|
||||
id: 'density-review',
|
||||
zoomCursor: false.obs,
|
||||
cursorOverImage: true.obs,
|
||||
keyboardEnabled: true.obs,
|
||||
remoteCursorMoved: false.obs)),
|
||||
));
|
||||
}
|
||||
|
||||
void _expectLegacyRaster(Map<dynamic, dynamic> args, Size size, double dpr) {
|
||||
// Base unzoomed sizing is logical on macOS/GTK, physical on Windows.
|
||||
final rasterScale = common.isWindows ? 1.0 : dpr;
|
||||
final width = (size.width * rasterScale).toInt();
|
||||
final height = (size.height * rasterScale).toInt();
|
||||
final bufferWidth = common.isLinux ? size.longestSide * rasterScale : width;
|
||||
expect((args['width'], args['height']), (bufferWidth, height));
|
||||
expect((args['hotX'], args['hotY']),
|
||||
((size.width ~/ 2) * rasterScale, (size.height ~/ 2) * rasterScale));
|
||||
expect(args['imagePixelRatio'], dpr);
|
||||
final decoded = decodeNativeCursorRaster(args);
|
||||
expect((decoded.width, decoded.height), (bufferWidth, height));
|
||||
expect(decoded.getPixel(width - 1, height - 1).a, 255);
|
||||
if (bufferWidth > width) expect(decoded.getPixel(width, 0).a, 0);
|
||||
}
|
||||
|
||||
Map<String, String> _cursorEvent(String id, String? density,
|
||||
{Size size = const Size(32, 32)}) =>
|
||||
{
|
||||
'id': id,
|
||||
'width': '${size.width.toInt()}',
|
||||
'height': '${size.height.toInt()}',
|
||||
'hotx': '${size.width ~/ 2}',
|
||||
'hoty': '${size.height ~/ 2}',
|
||||
if (density != null) 'scale': density,
|
||||
'colors': jsonEncode(
|
||||
List<int>.filled((size.width * size.height * 4).toInt(), 255)),
|
||||
};
|
||||
@@ -1,236 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_custom_cursor/cursor_manager.dart' show CursorManager;
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(this.cache, this._ffi) : super(WeakReference(_ffi));
|
||||
|
||||
final FFI _ffi;
|
||||
@override
|
||||
WeakReference<FFI> get parent => WeakReference(_ffi);
|
||||
|
||||
@override
|
||||
CursorData cache;
|
||||
@override
|
||||
double get hotx => cache.hotxOrigin;
|
||||
@override
|
||||
double get hoty => cache.hotyOrigin;
|
||||
}
|
||||
|
||||
class _LinuxDisplay extends Display {
|
||||
@override
|
||||
double get scale => 2;
|
||||
}
|
||||
|
||||
Future<CursorData> _data(int density, String id,
|
||||
{(int, int) source = (9, 18)}) async {
|
||||
final bitmapDensity = density == 0 ? 1 : density;
|
||||
final image = await createTestImage(
|
||||
width: source.$1 * bitmapDensity, height: source.$2 * bitmapDensity);
|
||||
return CursorData(
|
||||
peerId: 'dpi-policy',
|
||||
id: id,
|
||||
image: img.Image(width: image.width, height: image.height, numChannels: 4),
|
||||
nativeImage: image,
|
||||
scale: 1,
|
||||
data: Uint8List.fromList([1, 2]),
|
||||
hotxOrigin: (source.$1 ~/ 2) * bitmapDensity.toDouble(),
|
||||
hotyOrigin: (source.$2 ~/ 2) * bitmapDensity.toDouble(),
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
pixelRatio: density.toDouble(),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final view = binding.platformDispatcher.views.single;
|
||||
final windows = Platform.isWindows;
|
||||
final registrations = <Map<dynamic, dynamic>>[];
|
||||
captureNativeCursors(registrations);
|
||||
tearDown(view.resetDevicePixelRatio);
|
||||
for (final forbidden in [false, true]) {
|
||||
test('predefined cursor forbidden=$forbidden preserves native RGBA', () {
|
||||
view.devicePixelRatio = 1;
|
||||
return _checkPredefinedCursor(
|
||||
forbidden ? preForbiddenCursor : preDefaultCursor, registrations);
|
||||
});
|
||||
}
|
||||
for (final testCase in [
|
||||
(kRemoteViewStyleAdaptive, false, 0, 0.25, 1.0),
|
||||
(kRemoteViewStyleCustom, false, 0, 0.25, 1.0),
|
||||
(kRemoteViewStyleAdaptive, false, 1, 0.25, windows ? 2.0 : 1.0),
|
||||
(kRemoteViewStyleAdaptive, false, 2, 0.25, windows ? 1.0 : 0.5),
|
||||
(kRemoteViewStyleCustom, false, 2, 0.25, windows ? 1.0 : 0.5),
|
||||
(kRemoteViewStyleAdaptive, true, 2, 0.25, windows ? 2 / 3 : 1 / 3),
|
||||
(kRemoteViewStyleCustom, true, 2, 0.25, windows ? 2 / 3 : 1 / 3),
|
||||
(kRemoteViewStyleOriginal, false, 1, 0.5, windows ? 1.0 : 2 / 3),
|
||||
(kRemoteViewStyleOriginal, false, 2, 0.5, windows ? 1.0 : 0.5),
|
||||
]) {
|
||||
testWidgets(
|
||||
'${testCase.$1} zoom=${testCase.$2} peerDPR=${testCase.$3}',
|
||||
(tester) => tester
|
||||
.runAsync(() => _checkPolicy(tester, testCase, registrations)));
|
||||
}
|
||||
test('live DPR changes invalidate a cached native cursor',
|
||||
() => _checkDprChange(view, registrations));
|
||||
for (final style in [kRemoteViewStyleAdaptive, kRemoteViewStyleCustom]) {
|
||||
final dpr = style == kRemoteViewStyleAdaptive ? 1.0 : 2.0;
|
||||
final source = style == kRemoteViewStyleAdaptive ? (64, 4) : (4, 64);
|
||||
testWidgets('$style unknown-density thin cursor preserves zoom', (tester) =>
|
||||
tester.runAsync(() => _checkPolicy(tester,
|
||||
(style, true, 0, 0.5, windows ? 0.5 * dpr : 0.5), registrations,
|
||||
dpr: dpr, source: source)));
|
||||
testWidgets('$style forbidden cursor ignores remote DPR', (tester) =>
|
||||
tester.runAsync(() => _checkPolicy(tester,
|
||||
(style, false, 2, 0.25, 0.5), registrations, dpr: 1)));
|
||||
testWidgets('Linux $style zoom follows video pixels', (tester) => tester.runAsync(
|
||||
() => _checkPolicy(tester, (style, true, 2, 1.0, windows ? 1.0 : 0.5),
|
||||
registrations, linux: true)));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkPolicy(
|
||||
WidgetTester tester,
|
||||
(String, bool, int, double, double) testCase,
|
||||
List<Map<dynamic, dynamic>> registrations,
|
||||
{bool linux = false, double dpr = 2, (int, int) source = (9, 18)}) async {
|
||||
final (style, zoom, density, viewScale, expectedScale) = testCase;
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
final data = await _data(density, '$style-$zoom-$density', source: source);
|
||||
final originalBytes = data.data;
|
||||
// A stale cached DPR must not affect the cursor when the window moves.
|
||||
final canvas = CursorTestCanvas(1, style: style, scale: viewScale);
|
||||
final ffi = CursorTestFFI(canvas);
|
||||
ffi.ffiModel.isPeerLinux = linux;
|
||||
if (linux) ffi.ffiModel.pi.displays.add(_LinuxDisplay());
|
||||
final cursor = _Cursor(data, ffi);
|
||||
final keyboardEnabled = true.obs;
|
||||
await tester.pumpWidget(MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: dpr),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ImageModel>(create: (_) => CursorTestImage()),
|
||||
ChangeNotifierProvider<CanvasModel>.value(value: canvas),
|
||||
ChangeNotifierProvider<CursorModel>.value(value: cursor),
|
||||
],
|
||||
child: ImagePaint(
|
||||
ffi: ffi,
|
||||
id: 'dpi-policy',
|
||||
zoomCursor: zoom.obs,
|
||||
cursorOverImage: true.obs,
|
||||
keyboardEnabled: keyboardEnabled,
|
||||
remoteCursorMoved: false.obs,
|
||||
)),
|
||||
));
|
||||
final revoke = !zoom && style != kRemoteViewStyleOriginal;
|
||||
if (revoke) {
|
||||
await Future.wait(cursor.cachedKeys
|
||||
.map(CursorManager.instance.ensureCursorRegistered));
|
||||
keyboardEnabled.value = false;
|
||||
await tester.pump();
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
for (final key in cursor.cachedKeys) {
|
||||
await deleteCustomCursor(key);
|
||||
}
|
||||
data.nativeImage.dispose();
|
||||
cursor.dispose();
|
||||
canvas.dispose();
|
||||
expect(data.scale, closeTo(expectedScale, 1e-9));
|
||||
expect(data.hotx, closeTo(data.hotxOrigin * expectedScale, 1e-9));
|
||||
expect(data.hoty, closeTo(data.hotyOrigin * expectedScale, 1e-9));
|
||||
expect(data.data, same(originalBytes));
|
||||
if (zoom && density == 0) {
|
||||
final args = registrations.single;
|
||||
final rasterScale = expectedScale * (Platform.isWindows ? 1 : dpr);
|
||||
final width = source.$1 * rasterScale;
|
||||
final height = source.$2 * rasterScale;
|
||||
expect((args['width'], args['height']),
|
||||
(Platform.isLinux && height > width ? height : width, height));
|
||||
expect((args['hotX'], args['hotY']),
|
||||
((source.$1 ~/ 2) * rasterScale, (source.$2 ~/ 2) * rasterScale));
|
||||
}
|
||||
if (revoke) {
|
||||
final args = registrations.last;
|
||||
expect(args['name'], contains('_${kPreForbiddenCursorId}_'));
|
||||
final rasterSize = 32 * (Platform.isWindows ? 1 : dpr);
|
||||
expect((args['width'], args['height']), (rasterSize, rasterSize));
|
||||
expect((args['hotX'], args['hotY']), (0.0, 0.0));
|
||||
}
|
||||
if (style == kRemoteViewStyleAdaptive && !zoom && density > 0) {
|
||||
final args = registrations.first;
|
||||
expect((args['width'], args['height']), ((Platform.isLinux ? 18 : 9) * dpr, 18 * dpr));
|
||||
expect((args['hotX'], args['hotY']), (4 * dpr, 9 * dpr));
|
||||
expect(args['imagePixelRatio'], dpr);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkDprChange(
|
||||
TestFlutterView view, List<Map<dynamic, dynamic>> registrations) async {
|
||||
// Keep the scale above the minimum so only DPR invalidates the cache.
|
||||
final data = await _data(2, 'dpr-cache');
|
||||
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 1);
|
||||
final cursor = _Cursor(data, CursorTestFFI(canvas));
|
||||
for (final dpr in [2.0, 1.0]) {
|
||||
view.devicePixelRatio = dpr;
|
||||
buildCursorOfCache(cursor, 1, data);
|
||||
await deleteCustomCursor(cursor.cachedKeys.last);
|
||||
}
|
||||
expect(registrations, hasLength(2));
|
||||
expect(registrations[0]['name'], isNot(registrations[1]['name']));
|
||||
data.nativeImage.dispose();
|
||||
cursor.dispose();
|
||||
canvas.dispose();
|
||||
}
|
||||
|
||||
Future<void> _checkPredefinedCursor(PredefinedCursor predefined,
|
||||
List<Map<dynamic, dynamic>> registrations) async {
|
||||
await Future.doWhile(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
return predefined.cache == null;
|
||||
}).timeout(const Duration(seconds: 5));
|
||||
final cache = predefined.cache!;
|
||||
final original = img
|
||||
.decodePng(base64Decode(predefined.png))!
|
||||
.convert(format: img.Format.uint8, numChannels: 4);
|
||||
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 1);
|
||||
final cursor = _Cursor(cache, CursorTestFFI(canvas));
|
||||
buildCursorOfCache(cursor, 1, cache);
|
||||
await deleteCustomCursor(cursor.cachedKeys.single);
|
||||
cursor.dispose();
|
||||
canvas.dispose();
|
||||
|
||||
final args = registrations.single;
|
||||
final decoded = decodeNativeCursorRaster(args);
|
||||
expect((decoded.width, decoded.height), (original.width, original.height));
|
||||
expect(args['imagePixelRatio'], 1.0);
|
||||
expect((args['hotX'], args['hotY']), (cache.hotxOrigin, cache.hotyOrigin));
|
||||
expect(cache.image.getBytes(), original.getBytes());
|
||||
// Actual bundled pixels cover transparent, opaque and translucent colors.
|
||||
for (final (x, y) in [(0, 0), (1, 8), (13, 22), (16, 16)]) {
|
||||
final expected = original.getPixel(x, y);
|
||||
final actual = decoded.getPixel(x, y);
|
||||
expect(actual.a, expected.a);
|
||||
for (final (got, want) in [
|
||||
(actual.r, expected.r),
|
||||
(actual.g, expected.g),
|
||||
(actual.b, expected.b)
|
||||
]) {
|
||||
expect(got, closeTo(want, 1), reason: '${predefined.id} at ($x, $y)');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_custom_cursor/cursor_manager.dart' as cursor_manager;
|
||||
import 'package:flutter_hbb/common/shared_state.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/desktop_render_texture.dart';
|
||||
import 'package:flutter_hbb/models/input_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
const _viewport = Size(1920, 540);
|
||||
const _id = 'local-display-review';
|
||||
const _side = 64;
|
||||
const _hotspot = Offset(8, 12);
|
||||
|
||||
class _Display extends Display {
|
||||
_Display(this.density, double left, int w, int h) {
|
||||
x = left;
|
||||
width = w;
|
||||
height = h;
|
||||
}
|
||||
final double density;
|
||||
@override
|
||||
double get scale => density;
|
||||
}
|
||||
|
||||
class _Peer extends Fake implements FfiModel {
|
||||
_Peer() {
|
||||
pi.platform = kPeerPlatformLinux;
|
||||
pi.currentDisplay = kAllDisplayValue;
|
||||
pi.displays.assignAll([
|
||||
_Display(2, 0, 3840, 2160),
|
||||
_Display(1, 1920, 1920, 1080),
|
||||
]);
|
||||
}
|
||||
@override
|
||||
final pi = PeerInfo();
|
||||
@override
|
||||
bool get isPeerLinux => true;
|
||||
@override
|
||||
bool get keyboard => true;
|
||||
@override
|
||||
bool get viewOnly => false;
|
||||
@override
|
||||
Rect get rect => const Rect.fromLTWH(0, 0, 3840, 1080);
|
||||
}
|
||||
|
||||
class _Texture extends Fake implements TextureModel {
|
||||
final ids = <int, RxInt>{};
|
||||
@override
|
||||
RxInt getTextureId(int display) =>
|
||||
ids.putIfAbsent(display, () => display.obs);
|
||||
}
|
||||
|
||||
class _Canvas extends CanvasModel {
|
||||
_Canvas(FFI ffi, String style)
|
||||
: viewStyle = ViewStyle(
|
||||
style: style,
|
||||
width: 1920,
|
||||
height: 540,
|
||||
displayWidth: 3840,
|
||||
displayHeight: 1080),
|
||||
super(WeakReference(ffi)) {
|
||||
id = _id;
|
||||
}
|
||||
@override
|
||||
double get scale => 0.5;
|
||||
@override
|
||||
Size get size => _viewport;
|
||||
@override
|
||||
bool get cursorEmbedded => false;
|
||||
@override
|
||||
final ViewStyle viewStyle;
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI(String style) {
|
||||
canvasModel = _Canvas(this, style);
|
||||
cursorModel = CursorModel(WeakReference(this));
|
||||
inputModel = InputModel(WeakReference(this));
|
||||
}
|
||||
@override
|
||||
final sessionId = Uuid().v4obj();
|
||||
@override
|
||||
String get id => _id;
|
||||
@override
|
||||
final ffiModel = _Peer();
|
||||
@override
|
||||
final imageModel = CursorTestImage(useTextureRender: true);
|
||||
@override
|
||||
final textureModel = _Texture();
|
||||
@override
|
||||
late final CanvasModel canvasModel;
|
||||
@override
|
||||
late final CursorModel cursorModel;
|
||||
@override
|
||||
late final InputModel inputModel;
|
||||
Offset? mappedPosition;
|
||||
}
|
||||
|
||||
Future<void> _shape(_FFI ffi, String id) async {
|
||||
ffi.cursorModel.id = id;
|
||||
await ffi.cursorModel.updateCursorData({
|
||||
'id': id,
|
||||
'width': '$_side',
|
||||
'height': '$_side',
|
||||
'scale': '2',
|
||||
'hotx': '${_hotspot.dx}',
|
||||
'hoty': '${_hotspot.dy}',
|
||||
'colors': jsonEncode(List.generate(_side * _side * 4, (_) => 255)),
|
||||
});
|
||||
}
|
||||
|
||||
Widget _widget(_FFI ffi, double dpr) => Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: dpr),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ImageModel>.value(value: ffi.imageModel),
|
||||
ChangeNotifierProvider<CanvasModel>.value(value: ffi.canvasModel),
|
||||
ChangeNotifierProvider<CursorModel>.value(value: ffi.cursorModel),
|
||||
],
|
||||
child: ImagePaint(
|
||||
ffi: ffi,
|
||||
id: _id,
|
||||
zoomCursor: true.obs,
|
||||
cursorOverImage: true.obs,
|
||||
keyboardEnabled: true.obs,
|
||||
remoteCursorMoved: RemoteCursorMovedState.find(_id),
|
||||
listenerBuilder: (child) => Listener(
|
||||
child: child,
|
||||
onPointerHover: (e) {
|
||||
final point = ffi.inputModel.handlePointerDevicePos(
|
||||
kPointerEventKindMouse,
|
||||
e.position.dx,
|
||||
e.position.dy,
|
||||
true,
|
||||
kMouseEventTypeDefault,
|
||||
moveCanvas: false);
|
||||
if (point != null) {
|
||||
ffi.mappedPosition =
|
||||
Offset(point.x.toDouble(), point.y.toDouble());
|
||||
}
|
||||
})))));
|
||||
|
||||
Future<void> _settle(WidgetTester tester, _FFI ffi) async {
|
||||
await tester.pump();
|
||||
for (final key in ffi.cursorModel.cachedKeys) {
|
||||
await cursor_manager.CursorManager.instance.ensureCursorRegistered(key);
|
||||
}
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
final registrations = <Map<dynamic, dynamic>>[];
|
||||
final activations = <String>[];
|
||||
captureNativeCursors(registrations, activations: activations);
|
||||
setUp(() => RemoteCursorMovedState.init(_id));
|
||||
tearDown(() => RemoteCursorMovedState.delete(_id));
|
||||
for (final (style, dpr) in [
|
||||
(kRemoteViewStyleAdaptive, 1.0),
|
||||
(kRemoteViewStyleCustom, 2.0),
|
||||
]) {
|
||||
for (final mode in ['movement', 'shape refresh', 'host position control']) {
|
||||
testWidgets(
|
||||
'mixed displays: $style DPR=$dpr $mode',
|
||||
(tester) => tester.runAsync(
|
||||
() => _checkMovement(tester, (style, dpr, mode), (registrations, activations))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkMovement(
|
||||
WidgetTester tester,
|
||||
(String, double, String) testCase,
|
||||
(List<Map<dynamic, dynamic>>, List<String>) calls) async {
|
||||
final (style, dpr, mode) = testCase;
|
||||
final (registrations, activations) = calls;
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
tester.view.physicalSize = _viewport * dpr;
|
||||
addTearDown(tester.view.reset);
|
||||
final ffi = _FFI(style);
|
||||
addTearDown(() => _dispose(ffi));
|
||||
await _shape(ffi, '$style-$dpr-$mode-1');
|
||||
await ffi.cursorModel.updateCursorPosition({'x': '100', 'y': '100'}, _id);
|
||||
ffi.canvasModel.updateLocalCursor(50, 50);
|
||||
await tester.pumpWidget(_widget(ffi, dpr));
|
||||
await _settle(tester, ffi);
|
||||
expect(registrations.last['width'], 16 * dpr);
|
||||
await _moveToB(tester, ffi, (mode, activations));
|
||||
final args = registrations.last;
|
||||
expect((args['width'], args['height']), (32 * dpr, 32 * dpr));
|
||||
expect((args['hotX'], args['hotY']), (4 * dpr, 6 * dpr));
|
||||
}
|
||||
|
||||
Future<void> _moveToB(WidgetTester tester, _FFI ffi, (String, List<String>) testCase) async {
|
||||
final (mode, activations) = testCase;
|
||||
final mouse = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
|
||||
await mouse.addPointer(location: const Offset(50, 50));
|
||||
await _settle(tester, ffi);
|
||||
final before = activations.length;
|
||||
for (final x in [60.0, 70.0, 80.0]) {
|
||||
await mouse.moveTo(Offset(x, 50));
|
||||
await _settle(tester, ffi);
|
||||
expect(activations.length, before);
|
||||
}
|
||||
await mouse.moveTo(
|
||||
Offset(1100 + CanvasModel.leftToEdge, 50 + CanvasModel.topToEdge));
|
||||
await _settle(tester, ffi);
|
||||
expect(activations.length, before + 1);
|
||||
expect(ffi.mappedPosition, const Offset(2200, 100));
|
||||
expect(ffi.cursorModel.offset, const Offset(100, 100));
|
||||
if (mode == 'shape refresh') {
|
||||
await _shape(ffi, '$mode-2');
|
||||
} else if (mode == 'host position control') {
|
||||
await ffi.cursorModel.updateCursorPosition({'x': '2200', 'y': '100'}, _id);
|
||||
ffi.canvasModel.updateLocalCursor(1100, 50);
|
||||
}
|
||||
await _settle(tester, ffi);
|
||||
final after = activations.length;
|
||||
expect(after, before + (mode == 'shape refresh' ? 2 : 1));
|
||||
for (final x in [1110.0, 1120.0, 1130.0]) {
|
||||
await mouse.moveTo(Offset(x, 50));
|
||||
await _settle(tester, ffi);
|
||||
expect(activations.length, after);
|
||||
}
|
||||
final displayB = tester.widgetList<Positioned>(find.byType(Positioned)).last;
|
||||
expect(displayB.width! / 1920, 0.5);
|
||||
await mouse.removePointer();
|
||||
}
|
||||
|
||||
Future<void> _dispose(_FFI ffi) async {
|
||||
for (final key in ffi.cursorModel.cachedKeys) {
|
||||
await deleteCustomCursor(key);
|
||||
}
|
||||
ffi.cursorModel.disposeImages();
|
||||
ffi.cursorModel.dispose();
|
||||
ffi.canvasModel.dispose();
|
||||
ffi.imageModel.dispose();
|
||||
// Relative mode is never started and this fixture has no Rust session.
|
||||
ffi.inputModel.disposeSideButtonTracking();
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
const _side = 32;
|
||||
const _hotspot = Offset(7, 9);
|
||||
const _colors = [
|
||||
[64, 32, 16, 128],
|
||||
[240, 100, 20, 255],
|
||||
[0, 0, 0, 0],
|
||||
[0, 0, 0, 128],
|
||||
];
|
||||
final _stripeWidth = _side ~/ _colors.length;
|
||||
|
||||
class _Canvas extends Fake implements CanvasModel {
|
||||
@override
|
||||
final viewStyle = ViewStyle(
|
||||
style: kRemoteViewStyleAdaptive,
|
||||
width: 200,
|
||||
height: 160,
|
||||
displayWidth: 200,
|
||||
displayHeight: 160);
|
||||
}
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final view = binding.platformDispatcher.views.single;
|
||||
final registrations = <Map<dynamic, dynamic>>[];
|
||||
captureNativeCursors(registrations);
|
||||
tearDown(view.resetDevicePixelRatio);
|
||||
for (final testCase in <(String, String?, List<int>)>[
|
||||
(kPeerPlatformMacOS, null, [64, 32, 16, 128]),
|
||||
(kPeerPlatformWindows, '0', [64, 32, 16, 128]),
|
||||
(kPeerPlatformLinux, '0', [32, 16, 8, 128]),
|
||||
]) {
|
||||
for (final dpr in [1.0, 2.0]) {
|
||||
test(
|
||||
'native ${testCase.$1} scale=${testCase.$2} DPR=$dpr preserves alpha',
|
||||
() {
|
||||
view.devicePixelRatio = dpr;
|
||||
return _checkCursor(testCase, dpr, registrations);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkCursor((String, String?, List<int>) testCase, double dpr,
|
||||
List<Map<dynamic, dynamic>> registrations) async {
|
||||
final (platform, density, color) = testCase;
|
||||
final ffi = CursorTestFFI(_Canvas())..ffiModel.pi.platform = platform;
|
||||
final cursor = CursorModel(WeakReference(ffi))..id = '$testCase-$dpr';
|
||||
addTearDown(() {
|
||||
cursor.disposeImages();
|
||||
cursor.dispose();
|
||||
});
|
||||
final palette = [color, ..._colors.skip(1)];
|
||||
final rgba = [
|
||||
for (var y = 0; y < _side; y++)
|
||||
for (var x = 0; x < _side; x++) ...palette[x ~/ _stripeWidth]
|
||||
];
|
||||
await cursor.updateCursorData({
|
||||
'id': '$testCase-$dpr',
|
||||
'width': '$_side',
|
||||
'height': '$_side',
|
||||
'hotx': '${_hotspot.dx}',
|
||||
'hoty': '${_hotspot.dy}',
|
||||
if (density != null) 'scale': density,
|
||||
'colors': jsonEncode(rgba),
|
||||
});
|
||||
final cache = cursor.cache!;
|
||||
buildCursorOfCache(cursor, Platform.isWindows ? dpr : 1, cache);
|
||||
await deleteCustomCursor(cursor.cachedKeys.single);
|
||||
expect(cache.image.getBytes(), rgba); // Keep the original byte-cache source.
|
||||
_checkRegistration(registrations.single, dpr);
|
||||
// The same ui.Image also supplies the painted remote cursor.
|
||||
final straight = await cache.nativeImage
|
||||
.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
|
||||
_checkColors(img.Image.fromBytes(
|
||||
width: _side,
|
||||
height: _side,
|
||||
bytes: straight!.buffer,
|
||||
bytesOffset: straight.offsetInBytes,
|
||||
order: img.ChannelOrder.rgba));
|
||||
// Real sessions own FFI strongly throughout asynchronous cursor decoding.
|
||||
expect(cursor.parent.target, same(ffi));
|
||||
}
|
||||
|
||||
void _checkRegistration(Map<dynamic, dynamic> args, double dpr) {
|
||||
final decoded = decodeNativeCursorRaster(args);
|
||||
expect((decoded.width, decoded.height), (_side * dpr, _side * dpr));
|
||||
expect((args['hotX'], args['hotY']), (_hotspot.dx * dpr, _hotspot.dy * dpr));
|
||||
_checkColors(decoded);
|
||||
}
|
||||
|
||||
void _checkColors(img.Image bitmap) {
|
||||
for (var stripe = 0; stripe < _colors.length; stripe++) {
|
||||
final pixel = bitmap.getPixel(
|
||||
((stripe + 0.5) * bitmap.width / _colors.length).floor(),
|
||||
bitmap.height ~/ 2);
|
||||
final expected = _colors[stripe];
|
||||
expect(pixel.a, expected.last);
|
||||
for (final (actual, wanted) in [
|
||||
(pixel.r, expected[0]),
|
||||
(pixel.g, expected[1]),
|
||||
(pixel.b, expected[2])
|
||||
]) {
|
||||
expect(actual, closeTo(wanted, 1), reason: 'RGBA stripe $stripe');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/utils/image.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
const _hotspot = Offset(4, 9);
|
||||
const _remotePosition = Offset(100.25, 80.75);
|
||||
const _canvasOffset = Offset(15.125, -10.25);
|
||||
const _viewport = Size(200, 160);
|
||||
|
||||
class _CursorModel extends ChangeNotifier implements CursorModel {
|
||||
_CursorModel(this.image, this.position, this.density, {this.hotspot = _hotspot});
|
||||
|
||||
final Offset position;
|
||||
final double density;
|
||||
final Offset hotspot;
|
||||
@override
|
||||
CursorData get cache => _Density(density);
|
||||
|
||||
@override
|
||||
final ui.Image image;
|
||||
@override
|
||||
double get hotx => hotspot.dx;
|
||||
@override
|
||||
double get hoty => hotspot.dy;
|
||||
@override
|
||||
double get x => position.dx;
|
||||
@override
|
||||
double get y => position.dy;
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _Density extends Fake implements CursorData {
|
||||
_Density(this.pixelRatio);
|
||||
@override
|
||||
final double pixelRatio;
|
||||
}
|
||||
|
||||
class _ImageModel extends ChangeNotifier implements ImageModel {
|
||||
_ImageModel(this.useTextureRender);
|
||||
|
||||
@override
|
||||
final bool useTextureRender;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _Display extends Display {
|
||||
_Display(this.scale, double left) {
|
||||
x = left;
|
||||
width = 3840;
|
||||
height = 2160;
|
||||
}
|
||||
|
||||
@override
|
||||
final double scale;
|
||||
}
|
||||
|
||||
class _Peer extends Fake implements FfiModel {
|
||||
@override
|
||||
final pi = PeerInfo()
|
||||
..displays.add(Display()
|
||||
..width = _viewport.width.toInt()
|
||||
..height = _viewport.height.toInt());
|
||||
@override
|
||||
bool isPeerLinux = false;
|
||||
@override
|
||||
Rect rect = Offset.zero & _viewport;
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI(bool useTexture) : imageModel = _ImageModel(useTexture);
|
||||
|
||||
@override
|
||||
final ImageModel imageModel;
|
||||
@override
|
||||
final _Peer ffiModel = _Peer();
|
||||
@override
|
||||
final textureModel = CursorTestTexture();
|
||||
@override
|
||||
late CanvasModel canvasModel;
|
||||
}
|
||||
|
||||
class _CanvasModel extends ChangeNotifier implements CanvasModel {
|
||||
_CanvasModel(String style, this.scale, bool useTexture)
|
||||
: _ffi = _FFI(useTexture),
|
||||
viewStyle = ViewStyle(
|
||||
style: style,
|
||||
width: _viewport.width,
|
||||
height: _viewport.height,
|
||||
displayWidth: _viewport.width.toInt(),
|
||||
displayHeight: _viewport.height.toInt(),
|
||||
) {
|
||||
_ffi.canvasModel = this;
|
||||
}
|
||||
|
||||
final _FFI _ffi;
|
||||
@override
|
||||
WeakReference<FFI> get parent => WeakReference(_ffi);
|
||||
@override
|
||||
final imageOverflow = false.obs;
|
||||
@override
|
||||
final ViewStyle viewStyle;
|
||||
@override
|
||||
double get x => _canvasOffset.dx;
|
||||
@override
|
||||
double get y => _canvasOffset.dy;
|
||||
@override
|
||||
final double scale;
|
||||
@override
|
||||
ScrollStyle get scrollStyle => ScrollStyle.scrollauto;
|
||||
@override
|
||||
Size get size => _viewport;
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _ScrollbarCanvasModel extends _CanvasModel {
|
||||
_ScrollbarCanvasModel(String style, {Size? frame, double scale = 2})
|
||||
: super(style, scale, true) {
|
||||
imageOverflow.value = true;
|
||||
if (frame != null) _ffi.ffiModel.rect = Offset.zero & frame;
|
||||
}
|
||||
|
||||
@override
|
||||
ScrollStyle get scrollStyle => ScrollStyle.scrollbar;
|
||||
@override
|
||||
double get scrollX => _ffi.ffiModel.rect.width * scale > size.width ? 0.1 : 0;
|
||||
@override
|
||||
double get scrollY => _ffi.ffiModel.rect.height * scale > size.height ? 0.2 : 0;
|
||||
}
|
||||
|
||||
Future<ImagePainter> _paintCursor(WidgetTester tester, CanvasModel canvas,
|
||||
{double dpr = 2, bool zoom = true, (int, int) source = (48, 64),
|
||||
Offset position = _remotePosition, double density = 0,
|
||||
Offset hotspot = _hotspot}) async {
|
||||
final image = (await tester
|
||||
.runAsync(() => createTestImage(width: source.$1, height: source.$2)))!;
|
||||
addTearDown(image.dispose);
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
tester.view.physicalSize = _viewport * dpr;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr,
|
||||
child: MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: dpr),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ImageModel>.value(value: canvas.parent.target!.imageModel),
|
||||
ChangeNotifierProvider<CursorModel>(create: (_) => _CursorModel(image, position, density, hotspot: hotspot)),
|
||||
ChangeNotifierProvider<CanvasModel>(create: (_) => canvas),
|
||||
],
|
||||
child: Stack(fit: StackFit.expand, children: [
|
||||
// Measure the video's origin instead of copying its rounding policy.
|
||||
if (canvas.parent.target!.imageModel.useTextureRender &&
|
||||
canvas.scrollStyle == ScrollStyle.scrollauto)
|
||||
ImagePaint(ffi: canvas.parent.target!, id: 'cursor-test',
|
||||
zoomCursor: zoom.obs, cursorOverImage: false.obs,
|
||||
keyboardEnabled: true.obs, remoteCursorMoved: false.obs),
|
||||
CursorPaint(id: 'cursor-test', zoomCursor: zoom.obs),
|
||||
]),
|
||||
),
|
||||
)));
|
||||
final painter = tester.widget<CustomPaint>(find.byType(CustomPaint)).painter!
|
||||
as ImagePainter;
|
||||
expect(painter.image, same(image));
|
||||
return painter;
|
||||
}
|
||||
|
||||
void _linuxDisplayTests() {
|
||||
for (final (texture, displayScale, allDisplays) in [
|
||||
(false, 2.0, false), (true, 2.0, false), (true, 2.0, true),
|
||||
(false, 1.0, false), (true, 1.0, false),
|
||||
]) {
|
||||
testWidgets('Linux scale=$displayScale texture=$texture all=$allDisplays',
|
||||
(tester) async {
|
||||
final canvas = _CanvasModel(kRemoteViewStyleCustom, 2, texture);
|
||||
final peer = canvas._ffi.ffiModel;
|
||||
peer.isPeerLinux = true;
|
||||
// The first output's physical extent overlaps the second in logical
|
||||
// coordinates. Selection must use logical extents and the union origin.
|
||||
peer.pi.displays.assignAll([
|
||||
if (displayScale > 1) _Display(4, -960), _Display(displayScale, 0),
|
||||
]);
|
||||
peer.pi.currentDisplay = allDisplays ? kAllDisplayValue
|
||||
: peer.pi.displays.length - 1;
|
||||
peer.rect = Rect.fromLTWH(allDisplays ? -960 : 0, 0, 3840, 2160);
|
||||
final painter = await _paintCursor(tester, canvas,
|
||||
dpr: 1, zoom: false, source: (64, 64), density: 2,
|
||||
position: allDisplays ? _remotePosition + const Offset(960, 0)
|
||||
: _remotePosition);
|
||||
final pixelScale = 2 / displayScale;
|
||||
expect(painter.scale, pixelScale);
|
||||
final origin = texture ? tester.getTopLeft(find.byType(Texture).first)
|
||||
: Offset((_canvasOffset.dx / pixelScale).toInt() * pixelScale,
|
||||
(_canvasOffset.dy / pixelScale).toInt() * pixelScale);
|
||||
final position = allDisplays
|
||||
? _remotePosition + const Offset(960, 0) : _remotePosition;
|
||||
expect((Offset(painter.x, painter.y) + _hotspot) * painter.scale,
|
||||
position * 2 + origin);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
_linuxDisplayTests();
|
||||
final minimumScale = Platform.isWindows ? 1 / 3 : 2 / 3;
|
||||
for (final (style, zoom, dpr, source, canvasScale, scale, texture, density) in [
|
||||
(kRemoteViewStyleAdaptive, false, 2.0, (48, 64), 0.375, 0.375, true, 0.0),
|
||||
(kRemoteViewStyleOriginal, false, 2.0, (48, 64), 0.5, 0.5, true, 0.0),
|
||||
(kRemoteViewStyleCustom, false, 2.0, (48, 64), 0.25, 0.25, false, 0.0),
|
||||
(kRemoteViewStyleCustom, true, 2.0, (48, 64), 2.0, 2.0, false, 0.0),
|
||||
(kRemoteViewStyleAdaptive, false, 2.25, (48, 48), 0.375, 0.375, false, 0.0),
|
||||
(kRemoteViewStyleAdaptive, true, 2.0, (9, 18), 0.1, minimumScale, true, 0.0),
|
||||
(kRemoteViewStyleAdaptive, true, 1.0, (64, 4), 0.5, 0.5, true, 0.0),
|
||||
(kRemoteViewStyleCustom, true, 2.0, (4, 64), 0.5, 0.5, true, 0.0),
|
||||
(kRemoteViewStyleAdaptive, true, 1.0, (48, 64), 0.05, 0.1875, true, 2.0),
|
||||
(kRemoteViewStyleAdaptive, true, 2.0, (48, 64), 0.05, 0.1875, true, 2.0),
|
||||
(kRemoteViewStyleCustom, true, 1.0, (48, 64), 0.05, 0.1875, true, 2.0),
|
||||
(kRemoteViewStyleCustom, true, 2.0, (48, 64), 0.05, 0.1875, true, 2.0),
|
||||
(kRemoteViewStyleCustom, true, 2.0, (8, 10), 1.0, 1.2, true, 2.0),
|
||||
(kRemoteViewStyleOriginal, true, 1.0, (48, 64), 0.05, 0.1875, true, 2.0),
|
||||
(kRemoteViewStyleOriginal, true, 2.0, (48, 64), 0.05,
|
||||
Platform.isWindows ? 0.09375 : 0.1875, true, 2.0),
|
||||
]) {
|
||||
testWidgets(
|
||||
'$style zoom=$zoom dpr=$dpr source=$source texture=$texture density=$density keeps remote geometry',
|
||||
(tester) async {
|
||||
final sourceHotspot = source.$1 <= _hotspot.dx || source.$2 <= _hotspot.dy
|
||||
? Offset(source.$1 / 2, source.$2 / 2) : _hotspot;
|
||||
final painter = await _paintCursor(
|
||||
tester, _CanvasModel(style, canvasScale, texture),
|
||||
dpr: dpr, zoom: zoom, source: source, density: density,
|
||||
hotspot: sourceHotspot);
|
||||
expect(painter.scale, scale);
|
||||
var imageOrigin = texture
|
||||
? tester.getTopLeft(find.byType(Texture).first) : _canvasOffset;
|
||||
if (!texture) {
|
||||
final background = CursorTestDraw();
|
||||
ImagePainter(
|
||||
image: painter.image,
|
||||
x: _canvasOffset.dx / canvasScale,
|
||||
y: _canvasOffset.dy / canvasScale,
|
||||
scale: canvasScale,
|
||||
).paint(background, _viewport);
|
||||
imageOrigin = background.position!;
|
||||
}
|
||||
final target = _remotePosition * canvasScale + imageOrigin;
|
||||
final hotspot = (Offset(painter.x, painter.y) + sourceHotspot) * scale;
|
||||
expect(hotspot.dx, closeTo(target.dx, 1e-9));
|
||||
expect(hotspot.dy, closeTo(target.dy, 1e-9));
|
||||
final canvas = CursorTestDraw();
|
||||
painter.paint(canvas, _viewport);
|
||||
final position = canvas.position! + sourceHotspot * canvas.factor;
|
||||
expect(position.dx, closeTo(target.dx, 1e-9));
|
||||
expect(position.dy, closeTo(target.dy, 1e-9));
|
||||
});
|
||||
}
|
||||
for (final style in [kRemoteViewStyleOriginal, kRemoteViewStyleCustom]) {
|
||||
for (final (frame, scale, offset) in [
|
||||
(_viewport, 2.0, const Offset(-40, -64)),
|
||||
(const Size(199, 320), 1.0, const Offset(0, -64)),
|
||||
(const Size(198, 320), 1.0, const Offset(1, -64)),
|
||||
(const Size(400, 159), 1.0, const Offset(-40, 0)),
|
||||
(const Size(400, 158), 1.0, const Offset(-40, 1)),
|
||||
]) {
|
||||
testWidgets('$style frame=$frame painted cursor follows scrollbar layout',
|
||||
(tester) async {
|
||||
final painter = await _paintCursor(
|
||||
tester, _ScrollbarCanvasModel(style, frame: frame, scale: scale));
|
||||
final target = _remotePosition * scale + offset;
|
||||
expect((Offset(painter.x, painter.y) + _hotspot) * painter.scale, target);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
/// Stands in for the core, which keeps every shape the peer sent.
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
||||
final core = <String, CursorShape>{};
|
||||
final fetched = <String>[];
|
||||
// While set, a fetch answers only when [answerFetches] is called.
|
||||
bool holdFetches = false;
|
||||
// While set, a fetch throws before it returns a future.
|
||||
bool throwAtOnce = false;
|
||||
final _held = <Completer<CursorShape?>, String>{};
|
||||
@override
|
||||
Future<CursorShape?> fetchCursorShape(String id) {
|
||||
fetched.add(id);
|
||||
if (throwAtOnce) throw StateError('no core');
|
||||
if (!holdFetches) return Future.value(core[id]);
|
||||
final answer = Completer<CursorShape?>();
|
||||
_held[answer] = id;
|
||||
return answer.future;
|
||||
}
|
||||
|
||||
void answerFetches() {
|
||||
final held = Map.of(_held);
|
||||
_held.clear();
|
||||
held.forEach((answer, id) => answer.complete(core[id]));
|
||||
}
|
||||
|
||||
void failFetches() {
|
||||
final held = Map.of(_held);
|
||||
_held.clear();
|
||||
held.forEach((answer, _) => answer.completeError(StateError('failed')));
|
||||
}
|
||||
|
||||
bool showRemoteCursor = false;
|
||||
@override
|
||||
bool get showsRemoteCursor => showRemoteCursor;
|
||||
}
|
||||
|
||||
String? _key(MouseCursor cursor) =>
|
||||
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI() {
|
||||
ffiModel = FfiModel(WeakReference(this));
|
||||
cursorModel = _Cursor(this);
|
||||
}
|
||||
@override
|
||||
final SessionID sessionId = const Uuid().v4obj();
|
||||
@override
|
||||
late final FfiModel ffiModel;
|
||||
@override
|
||||
late final CursorModel cursorModel;
|
||||
_Cursor get cursor => cursorModel as _Cursor;
|
||||
}
|
||||
|
||||
Uint8List _pixels(int size, int seed) =>
|
||||
Uint8List.fromList(List.generate(size * size * 4, (i) => (i + seed) % 256));
|
||||
|
||||
/// A shape as the core delivers it, and keeps it.
|
||||
Future<void> _feed(_FFI ffi, String id, {int size = 8, int seed = 0}) {
|
||||
final pixels = _pixels(size, seed);
|
||||
ffi.cursor.core[id] =
|
||||
CursorShape(hotx: 0, hoty: 0, width: size, height: size, colors: pixels);
|
||||
return ffi.ffiModel.handleCursorData(id, 0, 0, size, size, pixels);
|
||||
}
|
||||
|
||||
void _select(_FFI ffi, String id) {
|
||||
final evt = {'id': id};
|
||||
ffi.ffiModel.updateLastCursorId(evt);
|
||||
ffi.ffiModel.handleCursorId(evt);
|
||||
}
|
||||
|
||||
Future<void> _settle() async {
|
||||
for (var i = 0; i < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final channel = Platform.isWindows
|
||||
? SystemChannels.mouseCursor
|
||||
: const MethodChannel('flutter_custom_cursor');
|
||||
final registered = <String>[];
|
||||
final deleted = <String>[];
|
||||
late _FFI ffi;
|
||||
setUp(() {
|
||||
registered.clear();
|
||||
deleted.clear();
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
|
||||
(call) async {
|
||||
final args = call.arguments as Map<dynamic, dynamic>;
|
||||
if (call.method.startsWith('createCustomCursor')) {
|
||||
registered.add(args['name'] as String);
|
||||
return args['name'];
|
||||
}
|
||||
if (call.method.startsWith('deleteCustomCursor')) {
|
||||
deleted.add(args['name'] as String);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
ffi = _FFI();
|
||||
});
|
||||
tearDown(() {
|
||||
ffi.cursorModel.disposeImages();
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);
|
||||
});
|
||||
|
||||
test(
|
||||
'only the shape in use keeps an image, and a shape its native cursor holds '
|
||||
'keeps no pixels', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var round = 0; round < 3; round++) {
|
||||
for (final (id, seed) in [('1', 1), ('2', 2), ('3', 3)]) {
|
||||
await _feed(ffi, id, seed: seed);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
}
|
||||
expect(ffi.cursorModel.shapeIds, ['3']);
|
||||
for (final id in ['1', '2']) {
|
||||
expect(ffi.cursorModel.cachedShape(id)!.hasPixels, isFalse);
|
||||
expect(ffi.cursorModel.cachedShape(id)!.data, isNull);
|
||||
}
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
});
|
||||
|
||||
test('the shape in use keeps its pixels, and a new raster is made at once',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
expect(cursor.cache!.hasPixels, isTrue);
|
||||
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
|
||||
isNot(MouseCursor.defer));
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'nothing had to be decoded');
|
||||
expect(registered.length, 2);
|
||||
expect((cursor.cache!.rasterWidth, cursor.cache!.rasterHeight), (16, 16));
|
||||
|
||||
await _feed(ffi, '2');
|
||||
expect(cursor.cachedShape('1')!.hasPixels, isFalse,
|
||||
reason: 'switched away from, a shape keeps no pixels');
|
||||
_select(ffi, '1');
|
||||
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
|
||||
isNot(MouseCursor.defer));
|
||||
await _settle();
|
||||
expect(registered.length, 2, reason: 'its native cursor is still there');
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
});
|
||||
|
||||
test('native cursors stay for the session, every raster of every shape',
|
||||
() async {
|
||||
// A delete frees nothing on Windows, so none is deleted before the session ends.
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; i < 100; i++) {
|
||||
await _feed(ffi, '$i', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(deleted, isEmpty);
|
||||
expect(cursor.cachedKeys.length, 100);
|
||||
|
||||
_select(ffi, '0');
|
||||
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)),
|
||||
cursor.nativeKey(cursor.cache!, 1.0));
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'its cursor is still there');
|
||||
expect(registered.length, 100);
|
||||
});
|
||||
|
||||
test(
|
||||
'a raster made before is found again after the shape was switched away from',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, 'A', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
final first = registered.single;
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, 'B');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
final count = registered.length;
|
||||
|
||||
_select(ffi, 'A'); // its pixels went; its cursors at both rasters stay
|
||||
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), first);
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
expect(registered.length, count);
|
||||
});
|
||||
|
||||
test('a new raster of a shape without pixels keeps the cursor shown before',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, '2', size: 32);
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
await _settle();
|
||||
_select(ffi, '1'); // its native cursor held its pixels, so they went
|
||||
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)),
|
||||
cursor.nativeKey(cursor.cache!, 0.5));
|
||||
});
|
||||
|
||||
test('shapes that keep decoding late still get their native cursors',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, 'arrow');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
// A and B arrive, each decoding only after the peer moved on.
|
||||
for (final (id, seed) in [('A', 1), ('B', 2)]) {
|
||||
final pixels = _pixels(8, seed);
|
||||
ffi.cursor.core[id] =
|
||||
CursorShape(hotx: 0, hoty: 0, width: 8, height: 8, colors: pixels);
|
||||
final decoding = ffi.ffiModel.handleCursorData(id, 0, 0, 8, 8, pixels);
|
||||
_select(ffi, 'arrow');
|
||||
await decoding;
|
||||
}
|
||||
// Each fetch answers only after the next switch.
|
||||
ffi.cursor.holdFetches = true;
|
||||
for (var i = 0; i < 6; i++) {
|
||||
_select(ffi, i.isEven ? 'A' : 'B');
|
||||
ffi.cursor.answerFetches();
|
||||
await _settle();
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(registered.where((key) => key.contains('_A_')), isNotEmpty);
|
||||
expect(registered.where((key) => key.contains('_B_')), isNotEmpty);
|
||||
});
|
||||
|
||||
test('a zoom still gets native cursors for shapes that keep decoding late',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
// An animation whose frames have native cursors at 1.0 only.
|
||||
for (final (id, seed) in [('A', 1), ('B', 2)]) {
|
||||
await _feed(ffi, id, size: 32, seed: seed);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
// At 0.5 each frame is fetched again, and each fetch answers after the next switch.
|
||||
ffi.cursor.holdFetches = true;
|
||||
for (var i = 0; i < 6; i++) {
|
||||
_select(ffi, i.isEven ? 'A' : 'B');
|
||||
ffi.cursor.answerFetches();
|
||||
await _settle();
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(
|
||||
registered
|
||||
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
|
||||
isNotEmpty);
|
||||
expect(
|
||||
registered
|
||||
.where((key) => key.contains('_B_') && key.endsWith('_16_16')),
|
||||
isNotEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'a raster still missing keeps a late restore, whatever was shown meanwhile',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, 'A', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, 'B');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
|
||||
_select(ffi, 'A');
|
||||
ffi.cursor.holdFetches = true;
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache); // no cursor at 0.5: fetched
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache); // 1.0 has one meanwhile
|
||||
_select(ffi, 'B');
|
||||
ffi.cursor.answerFetches();
|
||||
await _settle();
|
||||
ffi.cursor.fetched.clear();
|
||||
|
||||
_select(ffi, 'A');
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache);
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty,
|
||||
reason: 'its pixels waited for the cursor at 0.5');
|
||||
expect(
|
||||
registered
|
||||
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
|
||||
isNotEmpty);
|
||||
});
|
||||
|
||||
test('shapes waiting for a native cursor keep their pixels, within the limit',
|
||||
() async {
|
||||
const max = CursorModel.kRecentShapes;
|
||||
for (var i = 0; i <= max + 1; i++) {
|
||||
await _feed(ffi, '$i');
|
||||
}
|
||||
expect(ffi.cursorModel.cachedShape('0')!.hasPixels, isFalse,
|
||||
reason: 'the one waiting longest is let go');
|
||||
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue);
|
||||
expect(ffi.cursorModel.cachedShape('$max')!.hasPixels, isTrue);
|
||||
});
|
||||
|
||||
test('two animated cursors and the everyday set keep their native cursors',
|
||||
() async {
|
||||
// Each frame is a shape of its own: 18 for the Windows busy cursor, 23 for
|
||||
// KDE Breeze's wait and progress cursors on X11.
|
||||
const frames = 23;
|
||||
const statics = 12;
|
||||
final cursor = ffi.cursorModel;
|
||||
final shapes = [
|
||||
for (var i = 0; i < statics; i++) 's$i',
|
||||
for (var i = 0; i < frames; i++) 'wait$i',
|
||||
for (var i = 0; i < frames; i++) 'progress$i',
|
||||
];
|
||||
for (var i = 0; i < shapes.length; i++) {
|
||||
await _feed(ffi, shapes[i], seed: i);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
ffi.cursor.fetched.clear();
|
||||
for (final id in shapes) {
|
||||
_select(ffi, id);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(ffi.cursor.fetched, isEmpty,
|
||||
reason: 'every shape kept its native cursor');
|
||||
expect(registered.length, shapes.length);
|
||||
expect(deleted, isEmpty);
|
||||
});
|
||||
|
||||
test('a shape painted again is decoded again, the last one shown meanwhile',
|
||||
() async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
_select(ffi, '1');
|
||||
expect(ffi.cursorModel.image?.width, 8, reason: 'shape 2 until 1 is back');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
expect(ffi.cursorModel.image?.width, 16);
|
||||
expect(ffi.cursorModel.shapeIds, ['1']);
|
||||
});
|
||||
|
||||
test('a shape the core gives but that does not decode is asked for once',
|
||||
() async {
|
||||
await _feed(ffi, '1');
|
||||
await _feed(ffi, '2');
|
||||
ffi.cursor.core['1'] = CursorShape(
|
||||
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
|
||||
_select(ffi, '1');
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ffi.cursorModel.image;
|
||||
await _settle();
|
||||
}
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
});
|
||||
|
||||
test('a shape switched away from while it decoded is asked for again',
|
||||
() async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
_select(ffi, '1');
|
||||
ffi.cursorModel.image; // asks the core
|
||||
// The core has answered and the shape is decoding when the peer moves on.
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
_select(ffi, '2');
|
||||
await _settle();
|
||||
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue,
|
||||
reason:
|
||||
'decoded after the peer moved on, it waits for its native cursor');
|
||||
_select(ffi, '1');
|
||||
ffi.cursorModel.image;
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1', '1']);
|
||||
expect(ffi.cursorModel.image?.width, 16);
|
||||
});
|
||||
|
||||
test('a shape decoded after the session was cleared is not kept', () async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
_select(ffi, '1');
|
||||
ffi.cursorModel.image; // asks the core
|
||||
ffi.cursorModel.clear();
|
||||
await _settle();
|
||||
expect(ffi.cursorModel.shapeIds, isEmpty);
|
||||
expect(ffi.cursorModel.cache, isNull);
|
||||
});
|
||||
|
||||
test('a shape the core does not have is asked for once', () async {
|
||||
await _feed(ffi, '1');
|
||||
await _feed(ffi, '2');
|
||||
ffi.cursor.core.remove('1');
|
||||
_select(ffi, '1');
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ffi.cursorModel.image;
|
||||
await _settle();
|
||||
}
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
});
|
||||
|
||||
test('a shape the core lacks is remembered only while it is in use',
|
||||
() async {
|
||||
await _feed(ffi, '1');
|
||||
for (var i = 0; i < 1000; i++) {
|
||||
_select(ffi, 'missing$i');
|
||||
ffi.cursorModel.image;
|
||||
}
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched.length, 1000, reason: 'each is asked for once');
|
||||
_select(ffi, 'missing0');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched.length, 1001,
|
||||
reason: 'nothing is kept for a shape no longer in use');
|
||||
});
|
||||
|
||||
test('a shape the core lacks is asked for again after another was in use',
|
||||
() async {
|
||||
await _feed(ffi, '1');
|
||||
_select(ffi, 'missing0');
|
||||
await _settle();
|
||||
_select(ffi, '1');
|
||||
_select(ffi, 'missing0');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['missing0', 'missing0']);
|
||||
});
|
||||
|
||||
test('a moved tab carries the id in use, and its window asks the core',
|
||||
() async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
await _feed(ffi, '1', size: 16);
|
||||
final carried = ffi.ffiModel.cachedPeerData.toString();
|
||||
expect(carried, isNot(contains('colors')));
|
||||
expect(CachedPeerData.fromString(carried)!.lastCursorId['id'], '1',
|
||||
reason: 'a shape arriving is the shape in use');
|
||||
|
||||
final moved = _FFI();
|
||||
addTearDown(moved.cursorModel.disposeImages);
|
||||
moved.cursor.core.addAll(ffi.cursor.core);
|
||||
_select(moved, '1');
|
||||
await _settle();
|
||||
expect(moved.cursor.fetched, ['1']);
|
||||
expect(moved.cursorModel.cache?.id, '1');
|
||||
expect(moved.cursorModel.image?.width, 16);
|
||||
});
|
||||
|
||||
test('a shape keeps a native cursor for each raster it was shown at',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1', size: 32);
|
||||
for (final scale in [1.0, 0.5, 1.0, 0.5]) {
|
||||
buildCursorOfCache(cursor, scale, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(registered.length, 2, reason: 'a raster returned to is reused');
|
||||
expect(deleted, isEmpty);
|
||||
expect(cursor.cachedKeys, registered.toSet());
|
||||
});
|
||||
|
||||
test('a cleared session forgets the native cursors it deleted', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
cursor.clear();
|
||||
await _settle();
|
||||
expect(deleted, registered);
|
||||
expect(cursor.cachedKeys, isEmpty);
|
||||
});
|
||||
|
||||
test('a tab closing does not delete the cursors of another tab', () async {
|
||||
final other = _FFI();
|
||||
addTearDown(other.cursorModel.disposeImages);
|
||||
while (preDefaultCursor.cache == null) {
|
||||
await _settle();
|
||||
}
|
||||
buildCursorOfCache(ffi.cursorModel, 1.0, preDefaultCursor.cache);
|
||||
buildCursorOfCache(other.cursorModel, 1.0, preDefaultCursor.cache);
|
||||
await _settle();
|
||||
expect(registered.toSet().length, 2, reason: 'each tab has its own');
|
||||
|
||||
ffi.cursorModel.clear();
|
||||
await _settle();
|
||||
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
|
||||
});
|
||||
|
||||
test('a shape given as a view into a larger buffer is read from the view',
|
||||
() async {
|
||||
final pixels = _pixels(8, 3);
|
||||
final padded = Uint8List(16 + pixels.length)
|
||||
..setRange(16, 16 + pixels.length, pixels);
|
||||
await ffi.ffiModel
|
||||
.handleCursorData('1', 0, 0, 8, 8, Uint8List.sublistView(padded, 16));
|
||||
final p = ffi.cursorModel.cache!.image.getPixel(0, 0);
|
||||
expect([p.r, p.g, p.b, p.a], [3, 4, 5, 6]);
|
||||
});
|
||||
|
||||
test('a shape still decoding leaves the one shown before in place', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
await _settle();
|
||||
_select(ffi, '2'); // its shape has not decoded yet
|
||||
expect(cursor.cache?.id, '1');
|
||||
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), shown);
|
||||
expect(cursor.image, isNotNull);
|
||||
await _feed(ffi, '2');
|
||||
expect(cursor.cache?.id, '2');
|
||||
});
|
||||
|
||||
for (final how in ['does not have', 'cannot decode']) {
|
||||
test('a shape the core $how leaves the default cursor, not the one before',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
if (how == 'cannot decode') {
|
||||
ffi.cursor.core['2'] = CursorShape(
|
||||
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
|
||||
}
|
||||
_select(ffi, '2');
|
||||
expect(cursor.cache?.id, '1', reason: 'kept while the shape may come');
|
||||
var notified = 0;
|
||||
cursor.addListener(() => notified++);
|
||||
await _settle();
|
||||
expect(cursor.cache, isNull,
|
||||
reason: 'the desktop shows preDefaultCursor');
|
||||
expect(cursor.image, isNull, reason: 'and so does a painted cursor');
|
||||
expect(notified, greaterThan(0));
|
||||
});
|
||||
}
|
||||
|
||||
test('a shape sent that does not decode leaves the default cursor', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
ffi.cursor.core['2'] = CursorShape(
|
||||
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
|
||||
await ffi.ffiModel.handleCursorData('2', 0, 0, 8, 8, Uint8List(3));
|
||||
expect(cursor.cache, isNull);
|
||||
expect(cursor.image, isNull);
|
||||
_select(ffi, '2');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'it is not asked for either');
|
||||
});
|
||||
|
||||
test('a fetch failing after the session was cleared marks nothing in it',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
ffi.cursor.holdFetches = true;
|
||||
_select(ffi, '1'); // not decoded here yet, so it is asked for
|
||||
cursor.clear();
|
||||
ffi.cursor.failFetches();
|
||||
await _settle();
|
||||
ffi.cursor.holdFetches = false;
|
||||
_select(ffi, '1'); // the same id, now in the new session
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1', '1']);
|
||||
});
|
||||
|
||||
test('a fetch that throws at once tells the listeners after the build',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
ffi.cursor.throwAtOnce = true;
|
||||
cursor.id = '2';
|
||||
var notified = 0;
|
||||
cursor.addListener(() => notified++);
|
||||
cursor.restorePixels('2');
|
||||
expect(notified, 0, reason: 'a build may be what asked');
|
||||
await _settle();
|
||||
expect(notified, greaterThan(0));
|
||||
expect(cursor.cache, isNull);
|
||||
});
|
||||
|
||||
test('a raster still being made falls back to a shape, not the forbidden one',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; preForbiddenCursor.cache == null && i < 100; i++) {
|
||||
await _settle();
|
||||
}
|
||||
expect(preForbiddenCursor.cache, isNotNull);
|
||||
await _feed(ffi, '1', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, '2', size: 32);
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
await _settle();
|
||||
buildCursorOfCache(cursor, 1.0, preForbiddenCursor.cache); // input disabled
|
||||
_select(ffi, '1'); // its native cursor held its pixels, so they went
|
||||
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
|
||||
});
|
||||
|
||||
group('a painted cursor', () {
|
||||
void painted(String how) {
|
||||
if (how == 'mobile') {
|
||||
final was = isMobile;
|
||||
isMobile = true;
|
||||
addTearDown(() => isMobile = was);
|
||||
} else {
|
||||
ffi.cursor.showRemoteCursor = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (final how in ['mobile', 'remote cursor shown']) {
|
||||
test('keeps the images of two animations and the everyday set ($how)',
|
||||
() async {
|
||||
painted(how);
|
||||
final cursor = ffi.cursorModel;
|
||||
final shapes = [
|
||||
for (var i = 0; i < 12; i++) 's$i',
|
||||
for (var i = 0; i < 23; i++) 'wait$i',
|
||||
for (var i = 0; i < 23; i++) 'progress$i',
|
||||
];
|
||||
for (var i = 0; i < shapes.length; i++) {
|
||||
await _feed(ffi, shapes[i], seed: i);
|
||||
}
|
||||
for (final id in shapes) {
|
||||
_select(ffi, id);
|
||||
expect(cursor.shapeIds.last, id, reason: 'its image is at hand');
|
||||
}
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
test('keeps the images used last, and decodes the others again', () async {
|
||||
painted('mobile');
|
||||
const max = CursorModel.kRecentShapes;
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; i <= max; i++) {
|
||||
await _feed(ffi, '$i');
|
||||
}
|
||||
expect(cursor.shapeIds.length, max);
|
||||
_select(ffi, '$max');
|
||||
_select(ffi, '1');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'shape 1 was used lately');
|
||||
_select(ffi, '0');
|
||||
expect(cursor.image, isNotNull, reason: 'shape 1 until 0 is back');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['0']);
|
||||
expect(cursor.shapeIds.length, max);
|
||||
});
|
||||
|
||||
test('keeps a shape that finished decoding after the peer moved on',
|
||||
() async {
|
||||
painted('mobile');
|
||||
const max = CursorModel.kRecentShapes;
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; i <= max; i++) {
|
||||
await _feed(ffi, '$i');
|
||||
}
|
||||
_select(ffi, '0');
|
||||
cursor.image; // let go, so it is asked for
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
_select(ffi, '1');
|
||||
await _settle();
|
||||
_select(ffi, '0');
|
||||
cursor.image;
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['0'], reason: 'the late one was kept');
|
||||
expect(cursor.shapeIds.last, '0');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,294 +0,0 @@
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/utils/image.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:vector_math/vector_math.dart' show Vector2;
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
const _viewport = Size(200, 160);
|
||||
const _hotspot = Offset(4, 9);
|
||||
const _scrollDeltas = [80.0, -20.0, 1000.0, 1000.0, -1000.0, -1000.0, 80.0, 0.0];
|
||||
const _fittingViewports = [
|
||||
Size(500, 160), // Fit horizontally while vertical scrolling remains.
|
||||
Size(200, 400), // Fit vertically while horizontal scrolling remains.
|
||||
Size(400, 160), // Exact fit also detaches the controller.
|
||||
Size(200, 320),
|
||||
];
|
||||
|
||||
class _Peer extends Fake implements FfiModel {
|
||||
_Peer(ui.Image frame)
|
||||
: rect = Rect.fromLTWH(
|
||||
0, 0, frame.width.toDouble(), frame.height.toDouble()) {
|
||||
pi.displays.add(Display()
|
||||
..width = frame.width
|
||||
..height = frame.height);
|
||||
}
|
||||
@override
|
||||
final pi = PeerInfo();
|
||||
@override
|
||||
final Rect rect;
|
||||
@override
|
||||
bool get isPeerLinux => false;
|
||||
}
|
||||
|
||||
class _Image extends ImageModel {
|
||||
_Image(FFI ffi, this.image, this.useTextureRender)
|
||||
: super(WeakReference(ffi));
|
||||
@override
|
||||
final ui.Image image;
|
||||
@override
|
||||
final bool useTextureRender;
|
||||
}
|
||||
|
||||
class _ScrollCanvas extends CanvasModel {
|
||||
_ScrollCanvas(FFI ffi, String style, this.scrollStyle)
|
||||
: viewStyle = ViewStyle(
|
||||
style: style,
|
||||
width: _viewport.width,
|
||||
height: _viewport.height,
|
||||
displayWidth: ffi.ffiModel.rect!.width.toInt(),
|
||||
displayHeight: ffi.ffiModel.rect!.height.toInt()),
|
||||
super(WeakReference(ffi)) {
|
||||
resetOffset();
|
||||
imageOverflow.value = true;
|
||||
}
|
||||
Size viewport = _viewport;
|
||||
double imageScale = 1;
|
||||
@override
|
||||
Size get size => viewport;
|
||||
@override
|
||||
double get scale => imageScale;
|
||||
@override
|
||||
double get x => (size.width - getDisplayWidth() * scale) / 2;
|
||||
@override
|
||||
double get y => (size.height - getDisplayHeight() * scale) / 2;
|
||||
@override
|
||||
final ScrollStyle scrollStyle;
|
||||
@override
|
||||
final ViewStyle viewStyle;
|
||||
|
||||
void relayout(Size viewport, double dpr) {
|
||||
this.viewport = viewport;
|
||||
imageScale = 1 / dpr;
|
||||
imageOverflow.value = viewport.width < getDisplayWidth() * scale ||
|
||||
viewport.height < getDisplayHeight() * scale;
|
||||
setScrollPercent(0, 0);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(FFI ffi, this.image, this.position) : super(WeakReference(ffi));
|
||||
final Offset position;
|
||||
@override
|
||||
final ui.Image image;
|
||||
@override
|
||||
double get hotx => _hotspot.dx;
|
||||
@override
|
||||
double get hoty => _hotspot.dy;
|
||||
@override
|
||||
double get x => position.dx;
|
||||
@override
|
||||
double get y => position.dy;
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI(ui.Image frame, ui.Image cursor,
|
||||
{required bool texture, required (String, ScrollStyle) style, required Offset position})
|
||||
: ffiModel = _Peer(frame) {
|
||||
imageModel = _Image(this, frame, texture);
|
||||
canvasModel = _ScrollCanvas(this, style.$1, style.$2);
|
||||
cursorModel = _Cursor(this, cursor, position);
|
||||
}
|
||||
@override
|
||||
final sessionId = Uuid().v4obj();
|
||||
@override
|
||||
final _Peer ffiModel;
|
||||
@override
|
||||
late final ImageModel imageModel;
|
||||
@override
|
||||
late final CanvasModel canvasModel;
|
||||
@override
|
||||
late final CursorModel cursorModel;
|
||||
@override
|
||||
final textureModel = CursorTestTexture();
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final style in [(kRemoteViewStyleOriginal, ScrollStyle.scrolledge),
|
||||
(kRemoteViewStyleOriginal, ScrollStyle.scrollbar),
|
||||
(kRemoteViewStyleCustom, ScrollStyle.scrolledge),
|
||||
(kRemoteViewStyleCustom, ScrollStyle.scrollbar)]) {
|
||||
for (final texture in [false, true]) {
|
||||
for (final (frame, dpr) in [
|
||||
(const Size(199, 320), 1.0),
|
||||
(const Size(198, 320), 2.0),
|
||||
(const Size(400, 159), 2.0),
|
||||
(const Size(400, 158), 1.0),
|
||||
]) {
|
||||
testWidgets(
|
||||
'Scroll $style texture=$texture frame=$frame DPR=$dpr',
|
||||
(tester) => tester
|
||||
.runAsync(() => _check(tester, (style, texture, frame, dpr))));
|
||||
}
|
||||
for (final refreshBeforeLayout in [true, false]) {
|
||||
testWidgets(
|
||||
'Scroll relayout $style texture=$texture early=$refreshBeforeLayout',
|
||||
(tester) => tester.runAsync(() =>
|
||||
_checkRelayout(tester, (style, texture, refreshBeforeLayout))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _check(
|
||||
WidgetTester tester, ((String, ScrollStyle), bool, Size, double) testCase) async {
|
||||
final (style, texture, frame, dpr) = testCase;
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
tester.view.physicalSize = _viewport * dpr;
|
||||
addTearDown(tester.view.reset);
|
||||
final vertical = frame.height > _viewport.height;
|
||||
final pointer =
|
||||
vertical ? const Offset(50.25, 200.75) : const Offset(240.25, 50.75);
|
||||
final video = await createTestImage(
|
||||
width: frame.width.toInt(), height: frame.height.toInt());
|
||||
final cursor = await createTestImage(width: 48, height: 64);
|
||||
final ffi =
|
||||
_FFI(video, cursor, texture: texture, style: style, position: pointer);
|
||||
addTearDown(() {
|
||||
ffi.canvasModel.scrollHorizontal.dispose();
|
||||
ffi.canvasModel.scrollVertical.dispose();
|
||||
ffi.canvasModel.dispose();
|
||||
ffi.imageModel.dispose();
|
||||
ffi.cursorModel.dispose();
|
||||
video.dispose();
|
||||
cursor.dispose();
|
||||
});
|
||||
await _mount(tester, ffi, dpr);
|
||||
final videoWidget = texture ? find.byType(Texture) : _paintOf(video);
|
||||
final scrolling = vertical
|
||||
? ffi.canvasModel.scrollVertical
|
||||
: ffi.canvasModel.scrollHorizontal;
|
||||
for (final distance in _scrollDeltas) {
|
||||
// Drive the real scroll controllers; canvas pan offsets are not the video origin.
|
||||
ffi.canvasModel.performEdgeScroll(
|
||||
vertical ? Vector2(0, distance) : Vector2(distance, 0));
|
||||
expect(vertical ? ffi.canvasModel.scrollY : ffi.canvasModel.scrollX,
|
||||
closeTo(scrolling.offset / (vertical ? frame.height : frame.width), 1e-9));
|
||||
await tester.pump();
|
||||
_expectAlignment(tester, ffi, videoWidget);
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
}
|
||||
|
||||
Future<void> _checkRelayout(
|
||||
WidgetTester tester, ((String, ScrollStyle), bool, bool) testCase) async {
|
||||
final (style, texture, refreshBeforeLayout) = testCase;
|
||||
tester.view.devicePixelRatio = 1;
|
||||
tester.view.physicalSize = _viewport;
|
||||
addTearDown(tester.view.reset);
|
||||
final video = await createTestImage(width: 400, height: 320);
|
||||
final cursor = await createTestImage(width: 48, height: 64);
|
||||
final ffi = _FFI(video, cursor,
|
||||
texture: texture, style: style, position: const Offset(150.25, 120.75));
|
||||
final canvas = ffi.canvasModel as _ScrollCanvas;
|
||||
addTearDown(() {
|
||||
canvas.scrollHorizontal.dispose();
|
||||
canvas.scrollVertical.dispose();
|
||||
canvas.dispose();
|
||||
ffi.imageModel.dispose();
|
||||
ffi.cursorModel.dispose();
|
||||
video.dispose();
|
||||
cursor.dispose();
|
||||
});
|
||||
await _mount(tester, ffi, 1);
|
||||
final videoWidget = texture ? find.byType(Texture) : _paintOf(video);
|
||||
for (final (viewport, dpr) in [
|
||||
for (final viewport in _fittingViewports)
|
||||
...[(viewport, 1.0), (_viewport, 1.0)],
|
||||
(const Size(160, 120), 2.0),
|
||||
(const Size(195, 155), 2.0), // Clamp both existing scroll positions.
|
||||
(const Size(240, 155), 2.0), // Detach the horizontal scroll controller.
|
||||
(const Size(240, 200), 2.0), // No scrolling remains.
|
||||
(_viewport, 1.0),
|
||||
]) {
|
||||
canvas.performEdgeScroll(Vector2(20, 20));
|
||||
await tester.pump();
|
||||
_expectAlignment(tester, ffi, videoWidget);
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
tester.view.physicalSize = viewport * dpr;
|
||||
canvas.relayout(viewport, dpr);
|
||||
// A settings refresh may run before layout or after the first cursor build.
|
||||
if (refreshBeforeLayout) {
|
||||
canvas.updateScrollPercent();
|
||||
} else {
|
||||
tester.binding.addPostFrameCallback((_) => canvas.updateScrollPercent());
|
||||
}
|
||||
await _mount(tester, ffi, dpr);
|
||||
await tester.pumpAndSettle(const Duration(milliseconds: 16),
|
||||
EnginePhase.sendSemanticsUpdate, const Duration(seconds: 1));
|
||||
_expectAlignment(tester, ffi, videoWidget);
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
}
|
||||
|
||||
void _expectAlignment(WidgetTester tester, FFI ffi, Finder videoWidget) {
|
||||
final cursor = ffi.cursorModel;
|
||||
final cursorWidget = _paintOf(cursor.image!);
|
||||
final painter =
|
||||
tester.widget<CustomPaint>(cursorWidget).painter! as ImagePainter;
|
||||
final output = CursorTestDraw();
|
||||
painter.paint(output, ffi.canvasModel.size);
|
||||
final hotspot = tester.getTopLeft(cursorWidget) +
|
||||
output.position! +
|
||||
_hotspot * output.factor;
|
||||
var videoOrigin = tester.getTopLeft(videoWidget);
|
||||
final video = tester.widget(videoWidget);
|
||||
if (video is CustomPaint) {
|
||||
final drawnVideo = CursorTestDraw();
|
||||
video.painter!.paint(drawnVideo, ffi.canvasModel.size);
|
||||
videoOrigin += drawnVideo.position!;
|
||||
}
|
||||
final target =
|
||||
videoOrigin + Offset(cursor.x, cursor.y) * ffi.canvasModel.scale;
|
||||
expect(hotspot.dx, closeTo(target.dx, 1e-9));
|
||||
expect(hotspot.dy, closeTo(target.dy, 1e-9));
|
||||
}
|
||||
|
||||
Finder _paintOf(ui.Image image) => find.byWidgetPredicate((widget) =>
|
||||
widget is CustomPaint &&
|
||||
widget.painter is ImagePainter &&
|
||||
identical((widget.painter as ImagePainter).image, image));
|
||||
|
||||
Future<void> _mount(WidgetTester tester, FFI ffi, double dpr) =>
|
||||
tester.pumpWidget(Directionality(
|
||||
textDirection: TextDirection.ltr,
|
||||
child: MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: dpr),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ImageModel>.value(
|
||||
value: ffi.imageModel),
|
||||
ChangeNotifierProvider<CanvasModel>.value(
|
||||
value: ffi.canvasModel),
|
||||
ChangeNotifierProvider<CursorModel>.value(
|
||||
value: ffi.cursorModel),
|
||||
],
|
||||
child: Stack(fit: StackFit.expand, children: [
|
||||
ImagePaint(
|
||||
ffi: ffi,
|
||||
id: 'scroll-edge-test',
|
||||
zoomCursor: false.obs,
|
||||
cursorOverImage: false.obs,
|
||||
keyboardEnabled: true.obs,
|
||||
remoteCursorMoved: false.obs),
|
||||
CursorPaint(id: 'scroll-edge-test', zoomCursor: false.obs),
|
||||
])))));
|
||||
@@ -0,0 +1,368 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/input_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_hbb/utils/image.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
class _Canvas extends ChangeNotifier implements CanvasModel {
|
||||
_Canvas(String style)
|
||||
: viewStyle = ViewStyle(
|
||||
style: style,
|
||||
width: 200,
|
||||
height: 160,
|
||||
displayWidth: 400,
|
||||
displayHeight: 320);
|
||||
@override
|
||||
final ViewStyle viewStyle;
|
||||
@override
|
||||
final devicePixelRatio = 1.0;
|
||||
@override
|
||||
double scale = 0.25;
|
||||
@override
|
||||
final imageOverflow = false.obs;
|
||||
@override
|
||||
bool get cursorEmbedded => false;
|
||||
@override
|
||||
Size get size => const Size(200, 160);
|
||||
@override
|
||||
double get x => 0;
|
||||
@override
|
||||
double get y => 0;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _Image extends ChangeNotifier implements ImageModel {
|
||||
@override
|
||||
bool get useTextureRender => false;
|
||||
@override
|
||||
ui.Image? get image => null;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _Input extends Fake implements InputModel {
|
||||
@override
|
||||
final relativeMouseMode = false.obs;
|
||||
}
|
||||
|
||||
class _Display extends Display {
|
||||
@override
|
||||
double scale = 1.0;
|
||||
}
|
||||
|
||||
class _Peer extends Fake implements FfiModel {
|
||||
@override
|
||||
final pi = PeerInfo();
|
||||
@override
|
||||
bool get isPeerLinux => pi.platform == kPeerPlatformLinux;
|
||||
@override
|
||||
bool get isPeerWindows => pi.platform == kPeerPlatformWindows;
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI(this.canvasModel);
|
||||
@override
|
||||
final CanvasModel canvasModel;
|
||||
@override
|
||||
final ffiModel = _Peer();
|
||||
@override
|
||||
final inputModel = _Input();
|
||||
@override
|
||||
var id = '';
|
||||
}
|
||||
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(this.cache, FFI ffi) : super(WeakReference(ffi));
|
||||
@override
|
||||
final CursorData cache;
|
||||
}
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final channel = Platform.isWindows
|
||||
? SystemChannels.mouseCursor
|
||||
: const MethodChannel('flutter_custom_cursor');
|
||||
final registrations = <Map<dynamic, dynamic>>[];
|
||||
setUp(() {
|
||||
registrations.clear();
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
|
||||
(call) async {
|
||||
if (!call.method.startsWith('createCustomCursor')) return null;
|
||||
final args = call.arguments as Map<dynamic, dynamic>;
|
||||
registrations.add(args);
|
||||
return args['name'];
|
||||
});
|
||||
});
|
||||
tearDown(() =>
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
|
||||
for (final scenario in [
|
||||
((4, 64), 0.5, (2, 32)),
|
||||
((64, 4), 0.5, (32, 2)),
|
||||
((1, 64), 0.25, (1, 16)),
|
||||
((8, 8), 0.5, (12, 12)),
|
||||
((4, 64), 1.0, (4, 64)),
|
||||
((1, 512), 10.0, (1, 512)),
|
||||
]) {
|
||||
test('native cursor size $scenario',
|
||||
() => _checkSize(scenario, registrations));
|
||||
}
|
||||
test('native raster boundaries rebuild buffers and distinguish cache keys',
|
||||
() => _checkRasterTransitions(registrations));
|
||||
test('cursor resize limits preserve the last valid raster', () async {
|
||||
for (final size in [(30, 20), (20, 30)]) {
|
||||
await _checkResizeLimits(size, registrations);
|
||||
registrations.clear();
|
||||
}
|
||||
});
|
||||
for (final pattern in [
|
||||
([128, 0, 0, 128], 128),
|
||||
([255, 0, 0, 255, 0, 0, 0, 0], 127),
|
||||
]) {
|
||||
test('Windows peer cursor alpha survives resizing $pattern',
|
||||
() => _checkWindowsPeerAlpha(pattern, registrations));
|
||||
}
|
||||
for (final style in [
|
||||
kRemoteViewStyleOriginal,
|
||||
kRemoteViewStyleAdaptive,
|
||||
kRemoteViewStyleCustom
|
||||
]) {
|
||||
for (final zoom in [false, true]) {
|
||||
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
|
||||
(tester) => _checkView(tester, (style, zoom), registrations));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CursorData _data((int, int) size, {Offset hotspot = Offset.zero}) {
|
||||
final image = img.Image(width: size.$1, height: size.$2, numChannels: 4);
|
||||
for (final pixel in image) {
|
||||
pixel.setRgba(64, 32, 16, 255);
|
||||
}
|
||||
image.getPixel(0, 0).setRgba(255, 0, 0, 128);
|
||||
return CursorData(
|
||||
peerId: 'size',
|
||||
id: '$size',
|
||||
image: image,
|
||||
scale: 1,
|
||||
data: Platform.isWindows
|
||||
? image.getBytes(order: img.ChannelOrder.bgra)
|
||||
: Uint8List.fromList(img.encodePng(image)),
|
||||
hotxOrigin: hotspot.dx,
|
||||
hotyOrigin: hotspot.dy,
|
||||
width: size.$1,
|
||||
height: size.$2);
|
||||
}
|
||||
|
||||
Future<void> _dispose(CursorModel cursor) async {
|
||||
for (final key in cursor.cachedKeys) {
|
||||
await deleteCustomCursor(key);
|
||||
}
|
||||
cursor.dispose();
|
||||
}
|
||||
|
||||
Future<void> _checkWindowsPeerAlpha(
|
||||
(List<int>, int) pattern, List<Map<dynamic, dynamic>> registrations) async {
|
||||
const sourceSize = 64;
|
||||
const dpr = 2.0;
|
||||
const channels = 4;
|
||||
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
||||
ffi.ffiModel.pi.platform = kPeerPlatformWindows;
|
||||
final cursor = CursorModel(WeakReference<FFI>(ffi))..id = 'alpha';
|
||||
addTearDown(() => _dispose(cursor));
|
||||
addTearDown(cursor.disposeImages);
|
||||
addTearDown(ffi.canvasModel.dispose);
|
||||
await cursor.updateCursorData(
|
||||
'alpha',
|
||||
0,
|
||||
0,
|
||||
sourceSize,
|
||||
sourceSize,
|
||||
Uint8List.fromList(List.generate(sourceSize * sourceSize * channels,
|
||||
(i) => pattern.$1[i % pattern.$1.length])));
|
||||
buildCursorOfCache(cursor, 1.0 / dpr, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final args = registrations.single;
|
||||
final targetSize = (sourceSize / dpr).ceil();
|
||||
_expectSize(args, (targetSize, targetSize));
|
||||
final bytes = args['buffer'] as Uint8List;
|
||||
if (Platform.isWindows) {
|
||||
expect(bytes.sublist(0, channels), [0, 0, pattern.$2, pattern.$2]);
|
||||
} else {
|
||||
final pixel = img.decodePng(bytes)!.getPixel(0, 0);
|
||||
expect([pixel.r, pixel.g, pixel.b, pixel.a], [255, 0, 0, pattern.$2]);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkSize(((int, int), double, (int, int)) scenario,
|
||||
List<Map<dynamic, dynamic>> registrations) async {
|
||||
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
||||
final cursor = _Cursor(_data(scenario.$1), ffi);
|
||||
addTearDown(() => _dispose(cursor));
|
||||
addTearDown(ffi.canvasModel.dispose);
|
||||
buildCursorOfCache(cursor, scenario.$2, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final (width, height) = scenario.$3;
|
||||
expect(
|
||||
(cursor.cache.rasterWidth, cursor.cache.rasterHeight), (width, height));
|
||||
final args = registrations.single;
|
||||
final padded = Platform.isLinux && width != height;
|
||||
final side = width > height ? width : height;
|
||||
_expectSize(args, (padded ? side : width, padded ? side : height));
|
||||
if (padded) {
|
||||
final bitmap = img.decodePng(args['buffer'] as Uint8List)!;
|
||||
final artwork =
|
||||
img.copyCrop(bitmap, x: 0, y: 0, width: width, height: height);
|
||||
expect(artwork.getBytes(), img.decodePng(cursor.cache.data!)!.getBytes());
|
||||
expect(bitmap.where((p) => p.x >= width || p.y >= height).map((p) => p.a),
|
||||
everyElement(0));
|
||||
}
|
||||
}
|
||||
|
||||
void _expectSize(Map<dynamic, dynamic> args, (int, int) expected) {
|
||||
expect((args['width'], args['height']), expected);
|
||||
final bytes = args['buffer'] as Uint8List;
|
||||
if (Platform.isWindows) {
|
||||
const channels = 4;
|
||||
expect(bytes.length, expected.$1 * expected.$2 * channels);
|
||||
} else {
|
||||
final bitmap = img.decodePng(bytes)!;
|
||||
expect((bitmap.width, bitmap.height), expected);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkRasterTransitions(
|
||||
List<Map<dynamic, dynamic>> registrations) async {
|
||||
const delta = 3e-8;
|
||||
const scaleAboveOne = (2.25 / 1.75) / 2.25 * 1.75;
|
||||
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
||||
final cursor = _Cursor(_data((64, 64)), ffi);
|
||||
addTearDown(() => _dispose(cursor));
|
||||
addTearDown(ffi.canvasModel.dispose);
|
||||
for (final (scale, expected) in [
|
||||
(scaleAboveOne, (65, 65)),
|
||||
(0.5 - delta, (32, 32)),
|
||||
(0.5 + delta, (33, 33)),
|
||||
(1.0, (64, 64)),
|
||||
(scaleAboveOne, (65, 65)),
|
||||
(1.0, (64, 64)),
|
||||
]) {
|
||||
buildCursorOfCache(cursor, scale, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final key = cursor.nativeKey(cursor.cache, scale);
|
||||
_expectSize(
|
||||
registrations.singleWhere((args) => args['name'] == key), expected);
|
||||
}
|
||||
expect(registrations.length, 4);
|
||||
}
|
||||
|
||||
Future<void> _checkResizeLimits(
|
||||
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
|
||||
const maxSide = 512;
|
||||
const sourceLongEdge = 30;
|
||||
const validScale = maxSide / sourceLongEdge;
|
||||
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
||||
const hotspot = Offset(4, 7);
|
||||
final cursor = _Cursor(_data(size, hotspot: hotspot), ffi);
|
||||
addTearDown(() => _dispose(cursor));
|
||||
addTearDown(ffi.canvasModel.dispose);
|
||||
buildCursorOfCache(cursor, validScale, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final raster = ((size.$1 * validScale).ceil(), (size.$2 * validScale).ceil());
|
||||
final expectedHotspot =
|
||||
(hotspot.dx * raster.$1 / size.$1, hotspot.dy * raster.$2 / size.$2);
|
||||
_expectSize(
|
||||
registrations.single, Platform.isLinux ? (maxSide, maxSide) : raster);
|
||||
expect((registrations.single['hotX'], registrations.single['hotY']),
|
||||
expectedHotspot);
|
||||
// Fail on a small allocation before reaching unsafe sizes without the guard.
|
||||
for (final scale in [
|
||||
(maxSide + 1) / sourceLongEdge,
|
||||
double.maxFinite,
|
||||
double.infinity,
|
||||
double.nan,
|
||||
0.0,
|
||||
-1.0,
|
||||
]) {
|
||||
buildCursorOfCache(cursor, scale, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(cursor.cache.scale, validScale);
|
||||
expect((cursor.cache.rasterWidth, cursor.cache.rasterHeight), raster);
|
||||
expect((cursor.cache.hotx, cursor.cache.hoty), expectedHotspot);
|
||||
}
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(cursor.cache.scale, 1.0);
|
||||
_expectSize(registrations.last,
|
||||
Platform.isLinux ? (sourceLongEdge, sourceLongEdge) : size);
|
||||
}
|
||||
|
||||
const _viewCases = [
|
||||
(1.0, kPeerPlatformMacOS, 2.0),
|
||||
(1.25, kPeerPlatformLinux, 2.0),
|
||||
(2.0, kPeerPlatformMacOS, 1.0),
|
||||
];
|
||||
|
||||
Future<void> _checkView(WidgetTester tester, (String, bool) mode,
|
||||
List<Map<dynamic, dynamic>> registrations) async {
|
||||
const sourceSize = 64, customScale = 4.0;
|
||||
final canvas = _Canvas(mode.$1);
|
||||
final ffi = _FFI(canvas);
|
||||
final display = _Display();
|
||||
ffi.ffiModel.pi.displays.addAll([Display(), display]);
|
||||
ffi.ffiModel.pi.currentDisplay = 1;
|
||||
final cursor = _Cursor(_data((sourceSize, sourceSize)), ffi);
|
||||
addTearDown(() => _dispose(cursor));
|
||||
addTearDown(canvas.dispose);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
for (final (dpr, peer, peerScale) in _viewCases) {
|
||||
ffi.ffiModel.pi.platform = peer;
|
||||
display.scale = peerScale;
|
||||
canvas.scale = mode.$1 == kRemoteViewStyleCustom
|
||||
? customScale / dpr
|
||||
: mode.$1 == kRemoteViewStyleOriginal
|
||||
? 1.0 / dpr
|
||||
: canvas.viewStyle.scale;
|
||||
tester.view.devicePixelRatio = dpr;
|
||||
await tester.pumpWidget(MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: dpr),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<ImageModel>(create: (_) => _Image()),
|
||||
ChangeNotifierProvider<CanvasModel>.value(value: canvas),
|
||||
ChangeNotifierProvider<CursorModel>.value(value: cursor),
|
||||
],
|
||||
child: ImagePaint(
|
||||
ffi: ffi,
|
||||
id: 'size',
|
||||
zoomCursor: mode.$2.obs,
|
||||
cursorOverImage: true.obs,
|
||||
keyboardEnabled: true.obs,
|
||||
remoteCursorMoved: false.obs,
|
||||
),
|
||||
),
|
||||
));
|
||||
final video = tester.widget<CustomPaint>(find.byType(CustomPaint)).painter
|
||||
as ImagePainter;
|
||||
final scale = video.scale * (mode.$2 ? 1.0 : 1.0 / (canvas.scale * dpr));
|
||||
final size = sourceSize * (peer == kPeerPlatformMacOS ? peerScale : 1.0);
|
||||
final w = peer == kPeerPlatformMacOS &&
|
||||
!mode.$2 &&
|
||||
mode.$1 != kRemoteViewStyleOriginal
|
||||
? (sourceSize * (Platform.isWindows ? dpr : 1.0)).ceil()
|
||||
: (size * scale * (Platform.isWindows ? dpr : 1.0)).ceil();
|
||||
final key = cursor.nativeKey(cursor.cache, cursor.cache.scale);
|
||||
_expectSize(registrations.singleWhere((v) => v['name'] == key), (w, w));
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hbb/common.dart' as common;
|
||||
import 'package:flutter_hbb/models/desktop_render_texture.dart';
|
||||
import 'package:flutter_hbb/models/input_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
|
||||
class CursorTestImage extends ChangeNotifier implements ImageModel {
|
||||
CursorTestImage({this.useTextureRender = false});
|
||||
@override
|
||||
final bool useTextureRender;
|
||||
@override
|
||||
ui.Image? get image => null;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class CursorTestCanvas extends ChangeNotifier implements CanvasModel {
|
||||
CursorTestCanvas(this.devicePixelRatio,
|
||||
{required this.style, required this.scale});
|
||||
|
||||
final String style;
|
||||
@override
|
||||
final double devicePixelRatio;
|
||||
@override
|
||||
final imageOverflow = false.obs;
|
||||
@override
|
||||
late final viewStyle = ViewStyle(
|
||||
style: style,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
displayWidth: 400,
|
||||
displayHeight: 320,
|
||||
);
|
||||
@override
|
||||
bool get cursorEmbedded => false;
|
||||
@override
|
||||
ScrollStyle get scrollStyle => ScrollStyle.scrollauto;
|
||||
@override
|
||||
Size get size => const Size(200, 160);
|
||||
@override
|
||||
final double scale;
|
||||
@override
|
||||
double get x => 0;
|
||||
@override
|
||||
double get y => 0;
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
class _Input extends Fake implements InputModel {
|
||||
@override
|
||||
final relativeMouseMode = false.obs;
|
||||
}
|
||||
|
||||
class CursorTestPeer extends Fake implements FfiModel {
|
||||
@override
|
||||
final pi = PeerInfo();
|
||||
@override
|
||||
bool isPeerLinux = false;
|
||||
}
|
||||
|
||||
class CursorTestFFI extends Fake implements FFI {
|
||||
CursorTestFFI(this.canvasModel);
|
||||
@override
|
||||
final CanvasModel canvasModel;
|
||||
@override
|
||||
final inputModel = _Input();
|
||||
@override
|
||||
final CursorTestPeer ffiModel = CursorTestPeer();
|
||||
}
|
||||
|
||||
void captureNativeCursors(List<Map<dynamic, dynamic>> registrations,
|
||||
{List<String>? activations}) {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final channel = common.isWindows
|
||||
? SystemChannels.mouseCursor
|
||||
: const MethodChannel('flutter_custom_cursor');
|
||||
setUp(() {
|
||||
registrations.clear();
|
||||
activations?.clear();
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
|
||||
(call) async {
|
||||
if (call.method.startsWith('setCustomCursor')) {
|
||||
activations?.add(call.arguments['name'] as String);
|
||||
}
|
||||
if (!call.method.startsWith('createCustomCursor')) return null;
|
||||
final args = call.arguments as Map<dynamic, dynamic>;
|
||||
registrations.add(args);
|
||||
return args['name'];
|
||||
});
|
||||
});
|
||||
tearDown(() =>
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
|
||||
}
|
||||
|
||||
img.Image decodeNativeCursorRaster(Map<dynamic, dynamic> args) {
|
||||
final bytes = args['buffer'] as Uint8List;
|
||||
return common.isWindows
|
||||
? img.Image.fromBytes(
|
||||
width: args['width'] as int,
|
||||
height: args['height'] as int,
|
||||
bytes: bytes.buffer,
|
||||
bytesOffset: bytes.offsetInBytes,
|
||||
order: img.ChannelOrder.bgra)
|
||||
: img.decodePng(bytes)!;
|
||||
}
|
||||
|
||||
class CursorTestTexture extends Fake implements TextureModel {
|
||||
@override
|
||||
RxInt getTextureId(int display) => 0.obs;
|
||||
}
|
||||
|
||||
class CursorTestDraw extends Fake implements Canvas {
|
||||
double factor = 1;
|
||||
Offset? position;
|
||||
@override
|
||||
void scale(double sx, [double? sy]) => factor *= sx;
|
||||
@override
|
||||
void drawImage(ui.Image image, Offset offset, Paint paint) =>
|
||||
position = offset * factor;
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
// The test drives the cursor lifecycle normally owned by MouseTracker.
|
||||
// ignore_for_file: invalid_use_of_protected_member
|
||||
|
||||
@TestOn('browser')
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:js' as js;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
|
||||
import 'package:flutter_hbb/models/model.dart' as model;
|
||||
import 'package:flutter_hbb/web/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import 'cursor_test_utils.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
_alphaTests();
|
||||
_thinCursorTests();
|
||||
_sourceValidationTests();
|
||||
for (final style in [kRemoteViewStyleAdaptive, kRemoteViewStyleCustom]) {
|
||||
for (final dpr in [1.0, 2.0]) {
|
||||
for (final (platform, density) in [
|
||||
(kPeerPlatformMacOS, null), (kPeerPlatformMacOS, 0.0),
|
||||
(kPeerPlatformMacOS, 1.0), (kPeerPlatformMacOS, 2.0),
|
||||
(kPeerPlatformLinux, 2.0), (kPeerPlatformWindows, 2.0),
|
||||
]) {
|
||||
testWidgets('Web $style zoom off DPR $dpr $platform density=$density',
|
||||
(tester) => tester.runAsync(() => _checkPolicy(tester, style, dpr,
|
||||
pixelRatio: density, platform: platform)));
|
||||
}
|
||||
}
|
||||
}
|
||||
test('Web cursor aligns CSS hotspots with rounded PNG dimensions', () async {
|
||||
final registered = _captureCursor();
|
||||
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 0.5);
|
||||
addTearDown(canvas.dispose);
|
||||
final ffi = CursorTestFFI(canvas);
|
||||
for (final (hotspot, scale, side, expected) in [
|
||||
((7.0, 7.0), 633 / 1600, 19, (3, 3)),
|
||||
((21.0, 23.0), 633 / 1600, 19, (8, 9)),
|
||||
((22.0, 22.0), 633 / 1600, 19, (9, 9)),
|
||||
((21.0, 23.0), 0.05, 12, (5, 6)),
|
||||
((21.0, 23.0), 0.5, 24, (11, 12)),
|
||||
((7.0, 7.0), 1.0, 48, (7, 7)),
|
||||
]) {
|
||||
final cursor = await _loadCursor(ffi, '$hotspot-$scale',
|
||||
hotspot: hotspot, pixelRatio: null);
|
||||
final session =
|
||||
buildCursorOfCache(cursor, scale, cursor.cache).createSession(1);
|
||||
await session.activate();
|
||||
final uri = Uri.parse(registered['url'] as String);
|
||||
final bitmap = img.decodePng(uri.data!.contentAsBytes())!;
|
||||
expect((bitmap.width, bitmap.height), (side, side));
|
||||
expect((registered['hotx'], registered['hoty']), expected);
|
||||
session.dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _sourceValidationTests() {
|
||||
const side = 48;
|
||||
const sourceLimit = 4096;
|
||||
const bytes = side * side * 4;
|
||||
for (final density in [null, 4.0]) {
|
||||
test('Web rejects invalid cursor sources and recovers, density=$density', () async {
|
||||
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 1);
|
||||
addTearDown(canvas.dispose);
|
||||
final cursor = await _loadCursor(CursorTestFFI(canvas), 'source-$density',
|
||||
source: (side, side), pixelRatio: density);
|
||||
final cache = cursor.cache;
|
||||
final image = cursor.image;
|
||||
final event = {
|
||||
'id': 'source-$density', 'width': '$side', 'height': '$side',
|
||||
'hotx': '7', 'hoty': '9',
|
||||
if (density != null) 'scale': '$density',
|
||||
'colors': jsonEncode(List<int>.filled(bytes, 255)),
|
||||
};
|
||||
// Invalid JSON proves geometry is checked before decoding or allocation.
|
||||
const invalidPixels = 'must not decode an invalid source size';
|
||||
for (final invalid in [
|
||||
{'colors': '[1,2,3,4]'},
|
||||
{'colors': jsonEncode(List<int>.filled(bytes + 1, 255))},
|
||||
{'width': '0', 'colors': invalidPixels},
|
||||
{'height': '-1', 'colors': invalidPixels},
|
||||
{'width': '${sourceLimit * 4}', 'height': '${sourceLimit * 4}',
|
||||
'colors': invalidPixels},
|
||||
{'scale': '1e-300'},
|
||||
{'scale': '0.001'},
|
||||
]) {
|
||||
await cursor.updateCursorData({...event, ...invalid});
|
||||
expect(cursor.cache, same(cache));
|
||||
expect(cursor.image, same(image));
|
||||
expect((cursor.hotx, cursor.hoty), (7, 9));
|
||||
}
|
||||
await cursor.updateCursorData(event);
|
||||
expect(cursor.cache, isNot(same(cache)));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _thinCursorTests() {
|
||||
for (final style in [kRemoteViewStyleAdaptive, kRemoteViewStyleCustom]) {
|
||||
for (final zoom in [false, true]) {
|
||||
testWidgets('ImagePaint Web $style thin cursor zoom=$zoom', (tester) =>
|
||||
tester.runAsync(() => _checkPolicy(tester, style, 1,
|
||||
zoom: zoom, source: (64, 4), hotspot: (32, 2),
|
||||
expectedSize: zoom ? (32, 2) : (64, 4),
|
||||
expectedHotspot: zoom ? (16, 1) : (32, 2))));
|
||||
}
|
||||
}
|
||||
test('Web thin cursors keep a raster pixel and an in-bounds hotspot', () async {
|
||||
final registered = _captureCursor();
|
||||
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 0.5);
|
||||
addTearDown(canvas.dispose);
|
||||
final ffi = CursorTestFFI(canvas);
|
||||
for (final (source, hotspot, scale, size, expected) in [
|
||||
((4, 64), (2.0, 32.0), 0.5, (2, 32), (1, 16)),
|
||||
((2, 128), (1.0, 64.0), 0.01, (1, 12), (0, 6)),
|
||||
((128, 2), (64.0, 1.0), 0.01, (12, 1), (6, 0)),
|
||||
]) {
|
||||
final cursor = await _loadCursor(ffi, '$source',
|
||||
source: source, hotspot: hotspot);
|
||||
for (final factor in [1.0, scale, 1.0]) {
|
||||
final session =
|
||||
buildCursorOfCache(cursor, factor, cursor.cache).createSession(1);
|
||||
await session.activate();
|
||||
session.dispose();
|
||||
final png = img.decodePng(Uri.parse(registered['url']).data!.contentAsBytes())!;
|
||||
expect((png.width, png.height), factor == 1 ? source : size);
|
||||
expect((registered['hotx'], registered['hoty']),
|
||||
factor == 1 ? (hotspot.$1, hotspot.$2) : expected);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<model.CursorModel> _loadCursor(model.FFI ffi, String id,
|
||||
{List<int> pixel = const [255, 255, 255, 255],
|
||||
(int, int) source = (48, 48),
|
||||
(double, double) hotspot = (7, 9),
|
||||
double? pixelRatio = 1}) async {
|
||||
final cursor = model.CursorModel(WeakReference(ffi))..id = id;
|
||||
await cursor.updateCursorData({
|
||||
'id': id,
|
||||
'width': '${source.$1}',
|
||||
'height': '${source.$2}',
|
||||
'hotx': '${hotspot.$1}',
|
||||
'hoty': '${hotspot.$2}',
|
||||
if (pixelRatio != null) 'scale': '$pixelRatio',
|
||||
'colors': jsonEncode([for (var i = 0; i < source.$1 * source.$2; i++) ...pixel]),
|
||||
});
|
||||
addTearDown(() async {
|
||||
// Keep the session owner alive across asynchronous image decoding.
|
||||
expect(cursor.parent.target, same(ffi));
|
||||
for (final key in cursor.cachedKeys) {
|
||||
await deleteCustomCursor(key);
|
||||
}
|
||||
cursor.disposeImages();
|
||||
cursor.dispose();
|
||||
});
|
||||
return cursor;
|
||||
}
|
||||
|
||||
Map<String, dynamic> _captureCursor() {
|
||||
final originals = {
|
||||
for (final key in ['isMobile', 'getByName', 'setByName'])
|
||||
key: js.context[key]
|
||||
};
|
||||
js.context['isMobile'] = js.allowInterop(() => false);
|
||||
js.context['getByName'] = js.allowInterop((String name, String value) => '');
|
||||
final registered = <String, dynamic>{};
|
||||
js.context['setByName'] = js.allowInterop((String name, String value) {
|
||||
if (name == 'cursor') {
|
||||
registered
|
||||
..clear()
|
||||
..addAll(jsonDecode(value));
|
||||
}
|
||||
});
|
||||
addTearDown(() {
|
||||
for (final entry in originals.entries) {
|
||||
js.context[entry.key] = entry.value;
|
||||
}
|
||||
});
|
||||
return registered;
|
||||
}
|
||||
|
||||
Future<void> _checkPolicy(WidgetTester tester, String style, double dpr,
|
||||
{bool zoom = false, (int, int) source = (48, 48),
|
||||
(double, double) hotspot = (7, 9), (int, int) expectedSize = (48, 48),
|
||||
(int, int) expectedHotspot = (7, 9), double? pixelRatio = 1,
|
||||
String platform = kPeerPlatformMacOS}) async {
|
||||
final registered = _captureCursor();
|
||||
final canvas = CursorTestCanvas(1, style: style, scale: 0.5);
|
||||
addTearDown(canvas.dispose);
|
||||
final ffi = CursorTestFFI(canvas);
|
||||
ffi.ffiModel.pi.platform = platform;
|
||||
// Retina export changes the bitmap too; varying metadata alone misses this boundary.
|
||||
final density = platform == kPeerPlatformMacOS && pixelRatio == 2 ? 2 : 1;
|
||||
final cursor = await _loadCursor(ffi, '$style-$dpr-$zoom-$source-$platform-$pixelRatio',
|
||||
source: (source.$1 * density, source.$2 * density), pixelRatio: pixelRatio,
|
||||
hotspot: (hotspot.$1 * density, hotspot.$2 * density));
|
||||
await tester.pumpWidget(MediaQuery(
|
||||
data: MediaQueryData(devicePixelRatio: dpr),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<model.ImageModel>(create: (_) => CursorTestImage()),
|
||||
ChangeNotifierProvider<model.CanvasModel>.value(value: canvas),
|
||||
ChangeNotifierProvider<model.CursorModel>.value(value: cursor),
|
||||
],
|
||||
child: ImagePaint(
|
||||
ffi: ffi,
|
||||
id: 'web-cursor-test',
|
||||
zoomCursor: zoom.obs,
|
||||
cursorOverImage: true.obs,
|
||||
keyboardEnabled: true.obs,
|
||||
remoteCursorMoved: false.obs)),
|
||||
));
|
||||
final session = tester
|
||||
.widget<MouseRegion>(find.byType(MouseRegion))
|
||||
.cursor
|
||||
.createSession(1);
|
||||
await session.activate();
|
||||
session.dispose();
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
final png =
|
||||
img.decodePng(Uri.parse(registered['url']).data!.contentAsBytes())!;
|
||||
expect((png.width, png.height), expectedSize);
|
||||
expect((registered['hotx'], registered['hoty']), expectedHotspot);
|
||||
}
|
||||
|
||||
void _alphaTests() {
|
||||
for (final (density, pixel) in [
|
||||
(1.0, [255, 255, 255, 128]),
|
||||
(2.0, [255, 128, 64, 128]),
|
||||
(1.0, [255, 128, 64, 112]),
|
||||
(1.0, [0, 0, 0, 0]),
|
||||
(1.0, [255, 255, 255, 255]),
|
||||
// Old macOS hosts send straight alpha without density metadata.
|
||||
(0.0, [255, 128, 64, 128]),
|
||||
(null, [80, 40, 20, 128]),
|
||||
]) {
|
||||
test('Web macOS cursor density $density preserves RGBA $pixel',
|
||||
() => _checkAlpha(density, pixel));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _checkAlpha(double? density, List<int> pixel) async {
|
||||
final registered = _captureCursor();
|
||||
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 0.5);
|
||||
addTearDown(canvas.dispose);
|
||||
final ffi = CursorTestFFI(canvas)..ffiModel.pi.platform = kPeerPlatformMacOS;
|
||||
final cursor = await _loadCursor(ffi, 'alpha-$density-$pixel',
|
||||
pixel: pixel, pixelRatio: density);
|
||||
// Cover both the painted remote cursor and the initial CSS cursor PNG.
|
||||
final straight = await cursor.image!
|
||||
.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
|
||||
expect(straight!.buffer.asUint8List(0, 4), pixel);
|
||||
for (final scale in [1.0, 0.5, 1.0]) {
|
||||
final session =
|
||||
buildCursorOfCache(cursor, scale, cursor.cache).createSession(1);
|
||||
await session.activate();
|
||||
session.dispose();
|
||||
final png =
|
||||
img.decodePng(Uri.parse(registered['url']).data!.contentAsBytes())!;
|
||||
final color = png.getPixel(png.width ~/ 2, png.height ~/ 2);
|
||||
expect([color.r, color.g, color.b, color.a], pixel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
final _sessionId = UuidValue('00000000-0000-0000-0000-000000000000');
|
||||
|
||||
class _FakeFFI implements FFI {
|
||||
@override
|
||||
UuidValue get sessionId => _sessionId;
|
||||
|
||||
@override
|
||||
late final FfiModel ffiModel = FfiModel(WeakReference(this));
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('the quality monitor names the WebRTC transport only on web', () {
|
||||
final ffi = _FakeFFI();
|
||||
ffi.ffiModel.cachedPeerData.streamType = 'WebRTC';
|
||||
final model = QualityMonitorModel(WeakReference(ffi));
|
||||
// Off the web the session tab's tooltip already names the transport.
|
||||
expect(isWeb, isFalse);
|
||||
expect(model.webrtcTransport, isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/models/terminal_mouse_handler.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:xterm/xterm.dart';
|
||||
|
||||
const _captureMouse = '\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?1003h';
|
||||
|
||||
void main() {
|
||||
late Terminal terminal;
|
||||
late TerminalController controller;
|
||||
late List<String> output;
|
||||
|
||||
setUp(() {
|
||||
output = [];
|
||||
terminal = Terminal()..onOutput = output.add;
|
||||
controller = TerminalController();
|
||||
});
|
||||
|
||||
Future<TerminalViewState> mount(WidgetTester tester) async {
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 30, top: 50),
|
||||
child: SizedBox(
|
||||
width: 400,
|
||||
height: 120,
|
||||
child: TerminalMouseInteraction(terminal, controller: controller),
|
||||
),
|
||||
),
|
||||
),
|
||||
));
|
||||
terminal.write(List.generate(80, (i) => 'line $i\r\n').join());
|
||||
await tester.pump();
|
||||
final view = tester.state<TerminalViewState>(find.byType(TerminalView));
|
||||
expect(view.widget.scrollController!.offset, greaterThan(0));
|
||||
return view;
|
||||
}
|
||||
|
||||
Future<void> scrollTrackpad(
|
||||
WidgetTester tester, Offset point, double distance) async {
|
||||
final pointer = TestPointer(2, PointerDeviceKind.trackpad);
|
||||
await tester.sendEventToBinding(pointer.panZoomStart(point));
|
||||
await tester.sendEventToBinding(
|
||||
pointer.panZoomUpdate(point, pan: Offset(0, distance)));
|
||||
await tester.sendEventToBinding(
|
||||
pointer.panZoomUpdate(point, pan: Offset(0, distance * 2)));
|
||||
await tester.sendEventToBinding(pointer.panZoomEnd());
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
for (final trackpad in [false, true]) {
|
||||
final device = trackpad ? 'trackpad' : 'wheel';
|
||||
testWidgets('alternate screen reports $device after main-screen history',
|
||||
(tester) async {
|
||||
final view = await mount(tester);
|
||||
terminal.write('\x1b[?1049h$_captureMouse');
|
||||
await tester.pump();
|
||||
final render = view.renderTerminal;
|
||||
final point = render.localToGlobal(
|
||||
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
|
||||
if (trackpad) {
|
||||
await scrollTrackpad(tester, point, render.lineHeight * 3);
|
||||
} else {
|
||||
await tester.sendEventToBinding(PointerScrollEvent(
|
||||
position: point,
|
||||
scrollDelta: Offset(0, -render.lineHeight * 3),
|
||||
));
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
expect(output, isNotEmpty);
|
||||
expect(output, everyElement('\x1b[<64;3;2M'));
|
||||
expect(view.widget.scrollController!.offset, 0);
|
||||
expect(controller.selection, isNull);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
}
|
||||
|
||||
testWidgets('trackpad scrolling keeps subsequent drag coordinates aligned',
|
||||
(tester) async {
|
||||
final view = await mount(tester);
|
||||
terminal.write('\x1b[?1049h$_captureMouse');
|
||||
await tester.pump();
|
||||
final render = view.renderTerminal;
|
||||
final start = render.localToGlobal(
|
||||
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
|
||||
final end = render.localToGlobal(
|
||||
Offset(render.cellSize.width * 6.5, render.lineHeight * 2.5));
|
||||
await scrollTrackpad(tester, start, render.lineHeight * 3);
|
||||
output.clear();
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
await mouse.down(start);
|
||||
await mouse.moveTo(end);
|
||||
await mouse.up();
|
||||
await tester.pump(kDoubleTapTimeout);
|
||||
|
||||
expect(output, ['\x1b[<0;3;2M', '\x1b[<32;7;3M', '\x1b[<0;7;3m']);
|
||||
expect(controller.selection, isNull);
|
||||
expect(controller.suspendedPointerInputs, isFalse);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets('leaving alternate screen restores local trackpad scrollback',
|
||||
(tester) async {
|
||||
final view = await mount(tester);
|
||||
terminal.write('\x1b[?1049h$_captureMouse');
|
||||
await tester.pump();
|
||||
terminal.write('\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1006l\x1b[?1049l');
|
||||
await tester.pump();
|
||||
final before = view.widget.scrollController!.offset;
|
||||
await scrollTrackpad(
|
||||
tester, view.renderTerminal.localToGlobal(const Offset(40, 40)), 48);
|
||||
|
||||
expect(output, isEmpty);
|
||||
expect(view.widget.scrollController!.offset, lessThan(before));
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets('alternate screen without mouse capture still simulates arrows',
|
||||
(tester) async {
|
||||
final view = await mount(tester);
|
||||
terminal.write('\x1b[?1049h');
|
||||
await tester.pump();
|
||||
await scrollTrackpad(
|
||||
tester, view.renderTerminal.localToGlobal(const Offset(40, 40)), -48);
|
||||
|
||||
expect(output, isNotEmpty);
|
||||
expect(output, everyElement('\x1b[B'));
|
||||
expect(view.widget.scrollController!.offset, 0);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
}
|
||||
@@ -59,19 +59,22 @@ constexpr UINT kForceRedrawMaxTries = 25;
|
||||
// per call (each nudge re-enters the 100ms resize wait).
|
||||
constexpr UINT kForceRedrawCheapTries = 2;
|
||||
|
||||
// Re-enters the embedder's OnWindowSizeChanged by nudging the Flutter child
|
||||
// window by 1px and back: this resets the resize target and resends the window
|
||||
// metrics. Same as BaseFlutterWindow::ForceChildRefresh() on the
|
||||
// rustdesk_desktop_multi_window side.
|
||||
// A nonzero intermediate width can time out before Flutter resizes its surface.
|
||||
// Restoring the old width then leaves that intermediate resize pending. Zero
|
||||
// width resends metrics without creating a new resize target, as in the plugin.
|
||||
void ForceChildRefresh(HWND child) {
|
||||
if (!child) {
|
||||
return;
|
||||
}
|
||||
// FancyZones can queue a hide before the Flutter view is reparented.
|
||||
if ((GetWindowLongPtr(child, GWL_STYLE) & WS_VISIBLE) == 0) {
|
||||
ShowWindow(child, SW_SHOWNA);
|
||||
}
|
||||
RECT rect;
|
||||
GetWindowRect(child, &rect);
|
||||
LONG width = rect.right - rect.left;
|
||||
LONG height = rect.bottom - rect.top;
|
||||
SetWindowPos(child, nullptr, 0, 0, width + 1, height,
|
||||
SetWindowPos(child, nullptr, 0, 0, 0, height,
|
||||
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
|
||||
SetWindowPos(child, nullptr, 0, 0, width, height,
|
||||
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
|
||||
|
||||
@@ -104,6 +104,14 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||
}
|
||||
if (!allow_multiple_instances) {
|
||||
if (!command_line_arguments.empty()) {
|
||||
// The process launched by the browser owns the foreground permission.
|
||||
// Transfer it to the existing RustDesk process before dispatching the
|
||||
// URI so that it can bring an existing session to the foreground.
|
||||
DWORD pid = 0;
|
||||
::GetWindowThreadProcessId(hwnd, &pid);
|
||||
if (pid != 0) {
|
||||
::AllowSetForegroundWindow(pid);
|
||||
}
|
||||
// Dispatch command line arguments
|
||||
DispatchToUniLinksDesktop(hwnd);
|
||||
} else {
|
||||
|
||||
@@ -310,16 +310,14 @@ message KeyEvent {
|
||||
}
|
||||
|
||||
message CursorData {
|
||||
// A string in JS: a Windows peer before 1.5.0 sends its cursor handle, sign-extended above
|
||||
// 2^53 when its top bit is set, which a JS number cannot hold.
|
||||
uint64 id = 1 [jstype = JS_STRING];
|
||||
sint32 hotx = 2;
|
||||
sint32 hoty = 3;
|
||||
int32 width = 4;
|
||||
int32 height = 5;
|
||||
bytes colors = 6;
|
||||
// Physical bitmap pixels per remote logical pixel; 0 means unknown density.
|
||||
double scale = 7;
|
||||
// Optional physical image. Legacy receivers keep using the logical-sized fields above.
|
||||
CursorData high_resolution = 8;
|
||||
}
|
||||
|
||||
message CursorPosition {
|
||||
@@ -709,6 +707,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; }
|
||||
@@ -860,6 +861,12 @@ message Misc {
|
||||
DisplayResolution change_display_resolution = 36;
|
||||
MessageQuery message_query = 37;
|
||||
int32 follow_current_display = 38;
|
||||
// Since 1.5.0: send the CursorData of this id again. No controller sends this yet; it is
|
||||
// here so a controller can one day bound its own shape store and ask for the shape the
|
||||
// peer just selected. The peer answers with what it holds then: a shape its cache dropped
|
||||
// is rebuilt, and held again, the next time it is shown, before any connection names it
|
||||
// by id again, so the shape just selected is always there to give.
|
||||
uint64 request_cursor_data = 39;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1003,7 +1010,7 @@ message Message {
|
||||
AudioFrame audio_frame = 11;
|
||||
CursorData cursor_data = 12;
|
||||
CursorPosition cursor_position = 13;
|
||||
uint64 cursor_id = 14 [jstype = JS_STRING];
|
||||
uint64 cursor_id = 14 [jstype = JS_STRING]; // as CursorData.id
|
||||
KeyEvent key_event = 15;
|
||||
Clipboard clipboard = 16;
|
||||
FileAction file_action = 17;
|
||||
|
||||
@@ -48,6 +48,8 @@ pub const OPTION_ENABLE_RECORD_SESSION: &str = "enable-record-session";
|
||||
pub const OPTION_ENABLE_BLOCK_INPUT: &str = "enable-block-input";
|
||||
pub const OPTION_ENABLE_PRIVACY_MODE: &str = "enable-privacy-mode";
|
||||
pub const OPTION_ENABLE_PERM_CHANGE_IN_ACCEPT_WINDOW: &str = "enable-perm-change-in-accept-window";
|
||||
pub const OPTION_HIDE_ELEVATE_BUTTON_IN_ACCEPT_WINDOW: &str =
|
||||
"hide-elevate-button-in-accept-window";
|
||||
pub const OPTION_ALLOW_SCOPE_VIOLATION_CLOSE: &str = "allow-scope-violation-close";
|
||||
pub const OPTION_ALLOW_SCOPE_VIOLATION_ALARM: &str = "allow-scope-violation-alarm";
|
||||
pub const OPTION_ALLOW_REMOTE_CONFIG_MODIFICATION: &str = "allow-remote-config-modification";
|
||||
@@ -129,6 +131,7 @@ pub const OPTION_ENABLE_UDP_PUNCH: &str = "enable-udp-punch";
|
||||
pub const OPTION_ENABLE_IPV6_PUNCH: &str = "enable-ipv6-punch";
|
||||
pub const OPTION_ENABLE_PORT_FORWARD_MUX: &str = "enable-port-forward-mux";
|
||||
pub const OPTION_ENABLE_WEBRTC: &str = "enable-webrtc";
|
||||
pub const OPTION_RELAY_FALLBACK_DELAY: &str = "relay-fallback-delay";
|
||||
pub const OPTION_ALLOW_KCP_CC: &str = "allow-kcp-congestion-control";
|
||||
pub const OPTION_HIDE_USERNAME_ON_CARD: &str = "hide-username-on-card";
|
||||
pub const OPTION_HIDE_HELP_CARDS: &str = "hide-help-cards";
|
||||
@@ -258,6 +261,7 @@ pub const KEYS_LOCAL_SETTINGS: &[&str] = &[
|
||||
OPTION_ENABLE_IPV6_PUNCH,
|
||||
OPTION_ENABLE_PORT_FORWARD_MUX,
|
||||
OPTION_ENABLE_WEBRTC,
|
||||
OPTION_RELAY_FALLBACK_DELAY,
|
||||
OPTION_TOUCH_MODE,
|
||||
OPTION_SHOW_VIRTUAL_MOUSE,
|
||||
OPTION_SHOW_VIRTUAL_JOYSTICK,
|
||||
@@ -364,6 +368,7 @@ pub const KEYS_BUILDIN_SETTINGS: &[&str] = &[
|
||||
OPTION_DISABLE_UNLOCK_PIN,
|
||||
OPTION_USE_RAW_TCP_FOR_API,
|
||||
OPTION_ENABLE_PERM_CHANGE_IN_ACCEPT_WINDOW,
|
||||
OPTION_HIDE_ELEVATE_BUTTON_IN_ACCEPT_WINDOW,
|
||||
OPTION_ALLOW_COMMAND_LINE_SETTINGS_WHEN_SETTINGS_DISABLED,
|
||||
];
|
||||
|
||||
|
||||
@@ -320,9 +320,6 @@ pub struct WaylandDisplayInfo {
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub logical_size: Option<(i32, i32)>,
|
||||
// wl_output.scale is independent of desktop coordinates. Older probes omit it.
|
||||
#[serde(default)]
|
||||
pub scale_factor: i32,
|
||||
pub refresh_rate: i32,
|
||||
/// Output rotation in degrees (0/90/180/270), from `wl_output.geometry`. The mode keeps its
|
||||
/// unrotated dimensions and `logical_size` arrives already swapped, so without this field a
|
||||
@@ -453,7 +450,6 @@ fn collect_wayland_displays(conn: &Connection) -> ResultType<Vec<WaylandDisplayI
|
||||
width,
|
||||
height,
|
||||
logical_size,
|
||||
scale_factor: info.scale_factor,
|
||||
refresh_rate,
|
||||
transform,
|
||||
});
|
||||
@@ -546,11 +542,9 @@ mod tests {
|
||||
let old = r#"{"name":"HDMI-1","x":0,"y":0,"width":1920,"height":1080,"logical_size":null,"refresh_rate":60}"#;
|
||||
let info: WaylandDisplayInfo = serde_json::from_str(old).unwrap();
|
||||
assert_eq!(info.transform, 0);
|
||||
assert_eq!(info.scale_factor, 0);
|
||||
let roundtrip: WaylandDisplayInfo =
|
||||
serde_json::from_str(&serde_json::to_string(&info).unwrap()).unwrap();
|
||||
assert_eq!(roundtrip.transform, 0);
|
||||
assert_eq!(roundtrip.scale_factor, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -48,6 +48,19 @@ pub struct FileDescription {
|
||||
pub creation_time: SystemTime,
|
||||
pub size: u64,
|
||||
pub perm: u16,
|
||||
/// `file_list_id()` of the list this file came from, sent back in file contents requests
|
||||
#[serde(default)]
|
||||
pub clip_data_id: i32,
|
||||
}
|
||||
|
||||
/// Identifies a file list by its descriptor PDU, which both peers hold, so file contents
|
||||
/// requests can name the list they read from. FNV-1a, same as `wf_cliprdr_file_list_id()`.
|
||||
pub fn file_list_id(file_descriptor_pdu: &[u8]) -> i32 {
|
||||
file_descriptor_pdu
|
||||
.iter()
|
||||
.fold(0x811c_9dc5_u32, |id, byte| {
|
||||
(id ^ *byte as u32).wrapping_mul(0x0100_0193)
|
||||
}) as i32
|
||||
}
|
||||
|
||||
pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
|
||||
@@ -69,6 +82,7 @@ impl FileDescription {
|
||||
fn parse_file_descriptor(
|
||||
bytes: &mut Bytes,
|
||||
conn_id: i32,
|
||||
clip_data_id: i32,
|
||||
) -> Result<FileDescription, CliprdrError> {
|
||||
let flags = bytes.get_u32_le();
|
||||
// skip reserved 32 bytes
|
||||
@@ -126,12 +140,13 @@ impl FileDescription {
|
||||
// cannot set as is...
|
||||
} else if normal {
|
||||
PERM_RWX
|
||||
} else if directory {
|
||||
// Windows ignores read-only and hidden on a directory; without `x` it cannot be entered.
|
||||
PERM_RWX
|
||||
} else if readonly {
|
||||
PERM_READ
|
||||
} else if hidden {
|
||||
PERM_SELF_RO
|
||||
} else if directory {
|
||||
PERM_RWX
|
||||
} else {
|
||||
PERM_RW
|
||||
};
|
||||
@@ -154,8 +169,11 @@ impl FileDescription {
|
||||
|
||||
let valid_write_time = flags & FLAGS_FD_LAST_WRITE != 0;
|
||||
let last_modified = if valid_write_time && last_write_time >= LDAP_EPOCH_DELTA {
|
||||
let last_write_time = (last_write_time - LDAP_EPOCH_DELTA) * 100;
|
||||
let last_write_time = Duration::from_nanos(last_write_time);
|
||||
let last_write_time = last_write_time - LDAP_EPOCH_DELTA;
|
||||
let last_write_time = Duration::new(
|
||||
last_write_time / 10_000_000,
|
||||
(last_write_time % 10_000_000) as u32 * 100,
|
||||
);
|
||||
SystemTime::UNIX_EPOCH + last_write_time
|
||||
} else {
|
||||
SystemTime::UNIX_EPOCH
|
||||
@@ -175,6 +193,7 @@ impl FileDescription {
|
||||
creation_time: last_modified,
|
||||
size,
|
||||
perm,
|
||||
clip_data_id,
|
||||
};
|
||||
|
||||
Ok(desc)
|
||||
@@ -186,6 +205,7 @@ impl FileDescription {
|
||||
file_descriptor_pdu: Vec<u8>,
|
||||
conn_id: i32,
|
||||
) -> Result<Vec<Self>, CliprdrError> {
|
||||
let clip_data_id = file_list_id(&file_descriptor_pdu);
|
||||
let mut data = Bytes::from(file_descriptor_pdu);
|
||||
if data.remaining() < 4 {
|
||||
return Err(CliprdrError::InvalidRequest {
|
||||
@@ -206,7 +226,7 @@ impl FileDescription {
|
||||
|
||||
let mut files = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
|
||||
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
|
||||
files.push(desc);
|
||||
}
|
||||
|
||||
@@ -222,6 +242,7 @@ mod tests {
|
||||
const PDU_HEADER_SIZE: usize = size_of::<u32>();
|
||||
const DESCRIPTOR_SIZE: usize = 592;
|
||||
const ATTRIBUTES_OFFSET: usize = PDU_HEADER_SIZE + 36;
|
||||
const LAST_WRITE_TIME_OFFSET: usize = PDU_HEADER_SIZE + 56;
|
||||
const NAME_OFFSET: usize = PDU_HEADER_SIZE + 72;
|
||||
const FILE_NAME_CODE_UNITS: usize = 260;
|
||||
const INVALID_UTF16_UNIT: u16 = 0xdc00;
|
||||
@@ -282,6 +303,22 @@ mod tests {
|
||||
assert_eq!(files[0].name, PathBuf::from("file.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_list_id_is_fnv1a() {
|
||||
// Reference vectors; the Windows side computes the same id in C.
|
||||
assert_eq!(file_list_id(b"") as u32, 0x811c_9dc5);
|
||||
assert_eq!(file_list_id(b"a") as u32, 0xe40c_292c);
|
||||
assert_eq!(file_list_id(b"foobar") as u32, 0xbf9c_f968);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsed_files_carry_their_list_id() {
|
||||
let pdu = descriptor_pdu("file.txt");
|
||||
let id = file_list_id(&pdu);
|
||||
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
|
||||
assert_eq!(files[0].clip_data_id, id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_terminated_file_name() {
|
||||
let name = "a".repeat(FILE_NAME_CODE_UNITS);
|
||||
@@ -290,4 +327,57 @@ mod tests {
|
||||
Err(CliprdrError::InvalidRequest { .. })
|
||||
));
|
||||
}
|
||||
|
||||
fn parse_perm(attributes: u32) -> u16 {
|
||||
let mut pdu = descriptor_pdu("folder");
|
||||
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
|
||||
.copy_from_slice(&attributes.to_le_bytes());
|
||||
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].perm
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_directories_stay_searchable() {
|
||||
const FILE_ATTRIBUTE_READONLY: u32 = 0x01;
|
||||
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x02;
|
||||
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
|
||||
for attributes in [
|
||||
FILE_ATTRIBUTE_DIRECTORY,
|
||||
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_READONLY,
|
||||
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN,
|
||||
] {
|
||||
assert_eq!(
|
||||
parse_perm(attributes),
|
||||
PERM_RWX,
|
||||
"attributes {attributes:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_last_write_time(filetime: u64) -> SystemTime {
|
||||
let mut pdu = descriptor_pdu("file.txt");
|
||||
pdu[PDU_HEADER_SIZE..PDU_HEADER_SIZE + size_of::<u32>()]
|
||||
.copy_from_slice(&(FLAGS_FD_ATTRIBUTES | FLAGS_FD_LAST_WRITE).to_le_bytes());
|
||||
pdu[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + size_of::<u64>()]
|
||||
.copy_from_slice(&filetime.to_le_bytes());
|
||||
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].last_modified
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_last_write_time_from_windows_filetime() {
|
||||
// 2023-11-14 22:13:20 UTC
|
||||
assert_eq!(
|
||||
parse_last_write_time(133_444_736_000_000_000),
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000)
|
||||
);
|
||||
// 3000-01-01 00:00:00 UTC
|
||||
assert_eq!(
|
||||
parse_last_write_time(441_481_536_000_000_000),
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000)
|
||||
);
|
||||
// 1969-12-31 23:59:59 UTC falls back to the Unix epoch.
|
||||
assert_eq!(
|
||||
parse_last_write_time(116_444_736_000_000_000 - 10_000_000),
|
||||
SystemTime::UNIX_EPOCH
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,8 +549,8 @@ impl FuseServer {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested,
|
||||
have_clip_data_id: false,
|
||||
clip_data_id: 0,
|
||||
have_clip_data_id: true,
|
||||
clip_data_id: node.clip_data_id,
|
||||
};
|
||||
|
||||
send_data(node.conn_id, request.clone()).map_err(|e| {
|
||||
@@ -611,6 +611,9 @@ struct FuseNode {
|
||||
/// connection id
|
||||
pub conn_id: i32,
|
||||
|
||||
/// id of the peer's file list this node came from
|
||||
pub clip_data_id: i32,
|
||||
|
||||
/// file index in peer's file list
|
||||
/// NOTE:
|
||||
/// it is NOT the same as inode, this is the index in the file list
|
||||
@@ -634,6 +637,7 @@ impl FuseNode {
|
||||
pub fn from_description(inode: Inode, desc: FileDescription) -> Self {
|
||||
Self {
|
||||
conn_id: desc.conn_id,
|
||||
clip_data_id: desc.clip_data_id,
|
||||
index: inode as usize - 2,
|
||||
name: desc
|
||||
.name
|
||||
@@ -650,6 +654,7 @@ impl FuseNode {
|
||||
pub fn new_root() -> Self {
|
||||
Self {
|
||||
conn_id: 0,
|
||||
clip_data_id: 0,
|
||||
index: 0,
|
||||
name: String::from("/"),
|
||||
parent: None,
|
||||
@@ -898,6 +903,7 @@ mod fuse_test {
|
||||
|
||||
size: 0,
|
||||
perm: 0,
|
||||
clip_data_id: 0,
|
||||
}
|
||||
}
|
||||
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
|
||||
|
||||
@@ -160,12 +160,12 @@ impl LocalFile {
|
||||
| archive_flag
|
||||
| normal_flag;
|
||||
|
||||
let win32_time = self
|
||||
let win32_time = (self
|
||||
.last_write_time
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos() as u64
|
||||
/ 100
|
||||
.as_nanos()
|
||||
/ 100) as u64
|
||||
+ LDAP_EPOCH_DELTA;
|
||||
|
||||
let size_high = (self.size >> 32) as u32;
|
||||
@@ -323,6 +323,7 @@ mod file_list_test {
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use hbb_common::bytes::{BufMut, BytesMut};
|
||||
@@ -490,4 +491,46 @@ mod file_list_test {
|
||||
std::fs::remove_file(file_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const LAST_WRITE_TIME_OFFSET: usize = 56;
|
||||
|
||||
fn file_with_last_write_time(last_write_time: SystemTime) -> LocalFile {
|
||||
let mut file = generate_tree("").remove(1);
|
||||
file.last_write_time = last_write_time;
|
||||
file
|
||||
}
|
||||
|
||||
fn encoded_last_write_time(last_write_time: SystemTime) -> Result<u64, CliprdrError> {
|
||||
let descriptor = file_with_last_write_time(last_write_time).as_bin()?;
|
||||
let field = &descriptor[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + 8];
|
||||
Ok(u64::from_le_bytes(field.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_last_write_time_as_windows_filetime() -> Result<(), CliprdrError> {
|
||||
// 2023-11-14 22:13:20 UTC
|
||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
|
||||
assert_eq!(encoded_last_write_time(time)?, 133_444_736_000_000_000);
|
||||
// 3000-01-01 00:00:00 UTC
|
||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000);
|
||||
assert_eq!(encoded_last_write_time(time)?, 441_481_536_000_000_000);
|
||||
// Times before 1970 are sent as 1970-01-01 00:00:00 UTC.
|
||||
let time = SystemTime::UNIX_EPOCH - Duration::from_secs(1);
|
||||
assert_eq!(encoded_last_write_time(time)?, 116_444_736_000_000_000);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_write_time_round_trips() -> Result<(), CliprdrError> {
|
||||
let file = file_with_last_write_time(
|
||||
SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_700),
|
||||
);
|
||||
let mut pdu = BytesMut::with_capacity(4 + FILE_DESCRIPTOR_SIZE);
|
||||
pdu.put_u32_le(1);
|
||||
pdu.put(file.as_bin()?.as_slice());
|
||||
|
||||
let parsed = FileDescription::parse_file_descriptors(pdu.to_vec(), 0)?;
|
||||
assert_eq!(parsed[0].last_modified, file.last_write_time);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ use crate::{
|
||||
};
|
||||
use base::fs::join_validated_path;
|
||||
use hbb_common::{allow_err, log, tokio::time::Instant};
|
||||
use objc2::rc::Id;
|
||||
use objc2_foundation::NSProgress;
|
||||
use std::{
|
||||
cmp::min,
|
||||
fs::{File, FileTimes, OpenOptions},
|
||||
@@ -15,7 +17,7 @@ use std::{
|
||||
Arc, Mutex,
|
||||
},
|
||||
thread,
|
||||
time::{Duration, SystemTime},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
const RECV_RETRY_TIMES: usize = 3;
|
||||
@@ -23,15 +25,16 @@ const RECV_RETRY_TIMES: usize = 3;
|
||||
const DOWNLOAD_EXTENSION: &str = "rddownload";
|
||||
const RECEIVE_WAIT_TIMEOUT: Duration = Duration::from_millis(5_000);
|
||||
|
||||
// https://stackoverflow.com/a/15112784/1926020
|
||||
// "1984-01-24 08:00:00 +0000"
|
||||
const TIMESTAMP_FOR_FILE_PROGRESS_COMPLETED: u64 = 443779200;
|
||||
const ATTR_PROGRESS_FRACTION_COMPLETED: &str = "com.apple.progress.fractionCompleted";
|
||||
|
||||
fn create_new_file(path: impl AsRef<Path>) -> std::io::Result<File> {
|
||||
OpenOptions::new().write(true).create_new(true).open(path)
|
||||
}
|
||||
|
||||
fn finder_progress_byte_count(bytes: u64) -> Result<i64, CliprdrError> {
|
||||
i64::try_from(bytes).map_err(|_| CliprdrError::InvalidRequest {
|
||||
description: format!("File progress byte count exceeds i64::MAX: {bytes}"),
|
||||
})
|
||||
}
|
||||
|
||||
pub struct FileContentsResponse {
|
||||
pub conn_id: i32,
|
||||
pub msg_flags: i32,
|
||||
@@ -53,6 +56,7 @@ struct PasteTaskProgress {
|
||||
download_file_path: String,
|
||||
download_file_current_size: u64,
|
||||
file_handle: Option<BufWriter<File>>,
|
||||
finder_progress: Option<Id<NSProgress>>,
|
||||
error: Option<CliprdrError>,
|
||||
is_canceled: bool,
|
||||
}
|
||||
@@ -116,6 +120,7 @@ impl PasteTask {
|
||||
download_file_path: "".to_owned(),
|
||||
download_file_current_size: 0,
|
||||
file_handle: None,
|
||||
finder_progress: None,
|
||||
error: None,
|
||||
is_canceled: false,
|
||||
},
|
||||
@@ -318,7 +323,7 @@ impl PasteTaskHandle {
|
||||
} else {
|
||||
self.progress.offset += size;
|
||||
self.progress.download_file_current_size += size;
|
||||
self.update_progress_completed(None);
|
||||
self.update_progress_completed(None)?;
|
||||
}
|
||||
if self.progress.file_handle.is_none() {
|
||||
self.progress.list_index = self.files.len() as i32;
|
||||
@@ -329,44 +334,52 @@ impl PasteTaskHandle {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_progress_completed(&self) {
|
||||
if let Some(file) = self.progress.file_handle.as_ref() {
|
||||
let creation_time =
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(TIMESTAMP_FOR_FILE_PROGRESS_COMPLETED);
|
||||
file.get_ref()
|
||||
.set_times(FileTimes::new().set_created(creation_time))
|
||||
.ok();
|
||||
xattr::set(
|
||||
&self.progress.download_file_path,
|
||||
ATTR_PROGRESS_FRACTION_COMPLETED,
|
||||
"0.0".as_bytes(),
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
fn start_progress_completed(&mut self) -> Result<(), CliprdrError> {
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2_foundation::{
|
||||
NSProgressFileOperationKindDownloading, NSProgressKindFile, NSString, NSURL,
|
||||
};
|
||||
|
||||
let total_bytes = finder_progress_byte_count(self.progress.download_file_size)?;
|
||||
// Finder can retain the legacy timestamp/xattr indicator after a single-chunk transfer.
|
||||
autoreleasepool(|_| unsafe {
|
||||
let progress = NSProgress::discreteProgressWithTotalUnitCount(total_bytes);
|
||||
let url =
|
||||
NSURL::fileURLWithPath(&NSString::from_str(&self.progress.download_file_path));
|
||||
progress.setKind(Some(NSProgressKindFile));
|
||||
progress.setFileOperationKind(Some(NSProgressFileOperationKindDownloading));
|
||||
progress.setFileURL(Some(&url));
|
||||
progress.setCancellable(false);
|
||||
progress.setPausable(false);
|
||||
progress.publish();
|
||||
self.progress.finder_progress = Some(progress);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_progress_completed(&mut self, fraction_completed: Option<f64>) {
|
||||
let fraction_completed = fraction_completed.unwrap_or_else(|| {
|
||||
let current_size = self.progress.download_file_current_size as f64;
|
||||
let total_size = self.progress.download_file_size as f64;
|
||||
if total_size > 0.0 {
|
||||
current_size / total_size
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
});
|
||||
xattr::set(
|
||||
&self.progress.download_file_path,
|
||||
ATTR_PROGRESS_FRACTION_COMPLETED,
|
||||
&fraction_completed.to_string().as_bytes(),
|
||||
)
|
||||
.ok();
|
||||
fn update_progress_completed(
|
||||
&mut self,
|
||||
completed_bytes: Option<u64>,
|
||||
) -> Result<(), CliprdrError> {
|
||||
use objc2::rc::autoreleasepool;
|
||||
|
||||
let completed_bytes = finder_progress_byte_count(
|
||||
completed_bytes.unwrap_or(self.progress.download_file_current_size),
|
||||
)?;
|
||||
if let Some(progress) = self.progress.finder_progress.as_ref() {
|
||||
autoreleasepool(|_| unsafe {
|
||||
progress.setCompletedUnitCount(completed_bytes);
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn remove_progress_completed(path: &str) {
|
||||
if !path.is_empty() {
|
||||
xattr::remove(path, ATTR_PROGRESS_FRACTION_COMPLETED).ok();
|
||||
fn remove_progress_completed(&mut self) {
|
||||
use objc2::rc::autoreleasepool;
|
||||
|
||||
if let Some(progress) = self.progress.finder_progress.take() {
|
||||
autoreleasepool(|_| unsafe { progress.unpublish() });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,7 +429,7 @@ impl PasteTaskHandle {
|
||||
self.progress.download_file_path = download_file_path;
|
||||
self.progress.download_file_current_size = 0;
|
||||
self.progress.file_handle = Some(writer);
|
||||
self.start_progress_completed();
|
||||
self.start_progress_completed()?;
|
||||
}
|
||||
Err(e) => {
|
||||
self.progress.error = Some(CliprdrError::FileError {
|
||||
@@ -522,14 +535,12 @@ impl PasteTaskHandle {
|
||||
}
|
||||
|
||||
fn on_cancelled(&mut self) {
|
||||
self.remove_progress_completed();
|
||||
self.progress.file_handle = None;
|
||||
std::fs::remove_file(&self.progress.download_file_path).ok();
|
||||
}
|
||||
|
||||
fn on_done(&mut self) -> Result<(), CliprdrError> {
|
||||
self.update_progress_completed(Some(1.0));
|
||||
Self::remove_progress_completed(&self.progress.download_file_path);
|
||||
|
||||
let Some(file) = self.progress.file_handle.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -542,6 +553,11 @@ impl PasteTaskHandle {
|
||||
log::error!("Failed to flush file: {:?}", e);
|
||||
}
|
||||
self.progress.file_handle = None;
|
||||
// Updating or unpublishing after rename can leave stale Finder/Dock progress.
|
||||
// https://crbug.com/40217637
|
||||
// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/download/download_status_updater_mac.mm
|
||||
self.update_progress_completed(Some(self.progress.download_file_size))?;
|
||||
self.remove_progress_completed();
|
||||
|
||||
let Some(file_desc) = self.files.get(self.progress.download_file_index as usize) else {
|
||||
// unreachable
|
||||
@@ -617,6 +633,7 @@ impl PasteTaskHandle {
|
||||
};
|
||||
let cb_requested = min(BLOCK_SIZE as u64, file.size - self.progress.offset);
|
||||
let conn_id = file.conn_id;
|
||||
let clip_data_id = file.clip_data_id;
|
||||
|
||||
let (n_position_high, n_position_low) = (
|
||||
(self.progress.offset >> 32) as i32,
|
||||
@@ -629,8 +646,8 @@ impl PasteTaskHandle {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested: cb_requested as _,
|
||||
have_clip_data_id: false,
|
||||
clip_data_id: 0,
|
||||
have_clip_data_id: true,
|
||||
clip_data_id,
|
||||
};
|
||||
allow_err!(send_data(conn_id, request));
|
||||
self.progress.last_sent_time = Instant::now();
|
||||
@@ -669,10 +686,16 @@ impl PasteTaskHandle {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PasteTaskHandle {
|
||||
fn drop(&mut self) {
|
||||
self.remove_progress_completed();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::{os::unix::fs::symlink, time::SystemTime};
|
||||
|
||||
struct TestDirectory(PathBuf);
|
||||
|
||||
@@ -703,6 +726,7 @@ mod tests {
|
||||
creation_time: SystemTime::UNIX_EPOCH,
|
||||
size,
|
||||
perm: 0,
|
||||
clip_data_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -719,6 +743,7 @@ mod tests {
|
||||
download_file_path: String::new(),
|
||||
download_file_current_size: 0,
|
||||
file_handle: None,
|
||||
finder_progress: None,
|
||||
error: None,
|
||||
is_canceled: false,
|
||||
},
|
||||
@@ -727,6 +752,75 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finder_progress_completes_single_response_transfer() {
|
||||
let (_temp, target, _) = test_directories();
|
||||
let data = b"single response";
|
||||
let file = file_description("small.txt", FileType::File, data.len() as u64);
|
||||
let mut task = paste_task_handle(target.clone(), vec![file]);
|
||||
task.update_next(0).unwrap();
|
||||
let download_path = PathBuf::from(&task.progress.download_file_path);
|
||||
let progress = task.progress.finder_progress.as_ref().unwrap().clone();
|
||||
assert_eq!(unsafe { progress.completedUnitCount() }, 0);
|
||||
|
||||
task.handle_file_contents_response(FileContentsResponse {
|
||||
conn_id: 0,
|
||||
msg_flags: 1,
|
||||
stream_id: 0,
|
||||
requested_data: data.to_vec(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
unsafe {
|
||||
assert_eq!(progress.totalUnitCount(), data.len() as i64);
|
||||
assert_eq!(progress.completedUnitCount(), progress.totalUnitCount());
|
||||
assert!(progress.isFinished());
|
||||
}
|
||||
assert!(task.progress.finder_progress.is_none());
|
||||
assert!(task.progress.file_handle.is_none());
|
||||
assert!(task.is_finished());
|
||||
assert!(task.progress.error.is_none());
|
||||
assert!(!download_path.exists());
|
||||
assert_eq!(std::fs::read(target.join("small.txt")).unwrap(), data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finder_progress_reports_bytes_below_one_percent() {
|
||||
let (_temp, target, _) = test_directories();
|
||||
let size = u32::MAX as u64 + 1;
|
||||
let file = file_description("large.bin", FileType::File, size);
|
||||
let mut task = paste_task_handle(target, vec![file]);
|
||||
task.update_next(0).unwrap();
|
||||
task.handle_file_contents_response(FileContentsResponse {
|
||||
conn_id: 0,
|
||||
msg_flags: 1,
|
||||
stream_id: 0,
|
||||
requested_data: vec![1],
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let progress = task.progress.finder_progress.as_ref().unwrap();
|
||||
unsafe {
|
||||
assert_eq!(progress.totalUnitCount(), size as i64);
|
||||
assert_eq!(progress.completedUnitCount(), 1);
|
||||
}
|
||||
task.on_cancelled();
|
||||
assert!(task.progress.finder_progress.is_none());
|
||||
assert!(!Path::new(&task.progress.download_file_path).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finder_progress_rejects_unrepresentable_byte_count() {
|
||||
let (_temp, target, _) = test_directories();
|
||||
let file = file_description("large.bin", FileType::File, i64::MAX as u64 + 1);
|
||||
let mut task = paste_task_handle(target.clone(), vec![file]);
|
||||
let error = task.update_next(0).expect_err("byte count must not wrap");
|
||||
assert!(matches!(&error, CliprdrError::InvalidRequest { .. }));
|
||||
task.on_error(error);
|
||||
assert!(task.progress.finder_progress.is_none());
|
||||
assert!(std::fs::read_dir(target).unwrap().next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_all_paths_before_creating_files() {
|
||||
let (_temp, target, outside) = test_directories();
|
||||
|
||||
@@ -40,7 +40,8 @@ pub(super) const FILE_NAME_FIELD_SIZE: usize = FILE_NAME_CODE_UNITS * std::mem::
|
||||
|
||||
// begin of epoch used by microsoft
|
||||
// 1601-01-01 00:00:00 + LDAP_EPOCH_DELTA*(100 ns) = 1970-01-01 00:00:00
|
||||
const LDAP_EPOCH_DELTA: u64 = 116444772610000000;
|
||||
// 134_774 days (369 years, 89 leap days) * 86_400 s * 10_000_000 per s
|
||||
const LDAP_EPOCH_DELTA: u64 = 116_444_736_000_000_000;
|
||||
|
||||
lazy_static! {
|
||||
static ref REMOTE_FORMAT_MAP: DashMap<i32, String> = DashMap::from_iter(
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
use super::local_file::LocalFile;
|
||||
use crate::{platform::unix::local_file::construct_file_list, ClipboardFile, CliprdrError};
|
||||
use crate::{
|
||||
platform::unix::{
|
||||
filetype::file_list_id,
|
||||
local_file::{construct_file_list, LocalFile},
|
||||
},
|
||||
ClipboardFile, CliprdrError,
|
||||
};
|
||||
use hbb_common::{
|
||||
bytes::{BufMut, BytesMut},
|
||||
log,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::{path::PathBuf, sync::Arc, time::SystemTime, usize};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
sync::{atomic::Ordering, Arc},
|
||||
time::SystemTime,
|
||||
usize,
|
||||
};
|
||||
|
||||
// Our clients request at most this much per range: macOS 4 MiB, FUSE less, and Windows
|
||||
// splits larger reads (WF_CLIPRDR_MAX_RANGE_READ). A larger read is refused, not shortened:
|
||||
// a short response reads as end of file to IStream callers on Windows.
|
||||
const MAX_RANGE_READ: u64 = 16 * 1024 * 1024;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
// local files are cached, this value should not be changed when copying files
|
||||
@@ -13,8 +29,18 @@ lazy_static::lazy_static! {
|
||||
// We need to keep the file list in the same order as the remote side.
|
||||
// We may add a `FileId` field to `CliprdrFileContentsRequest` in the future.
|
||||
static ref CLIP_FILES: Arc<Mutex<ClipFiles>> = Default::default();
|
||||
// Lists replaced by a newer copy after a peer was sent them, oldest first. The peer's
|
||||
// streams keep reading the list they came from. Lock after `CLIP_FILES`.
|
||||
static ref RETIRED_CLIP_FILES: Mutex<VecDeque<ClipFiles>> = Default::default();
|
||||
}
|
||||
|
||||
const MAX_RETIRED_CLIP_FILES: usize = 4;
|
||||
|
||||
// The first descriptor's `clsid`, inside the 32 reserved bytes every peer skips. A random
|
||||
// nonce there makes each copy's list id distinct, even when two copies have identical
|
||||
// names, sizes and times (the same file in two folders).
|
||||
const LIST_NONCE: std::ops::Range<usize> = 8..24;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum FileContentsRequest {
|
||||
Size {
|
||||
@@ -62,6 +88,10 @@ struct ClipFiles {
|
||||
file_list: Vec<LocalFile>,
|
||||
first_file_index: usize,
|
||||
files_pdu: Vec<u8>,
|
||||
// `file_list_id(files_pdu)`, which peers send back as `clip_data_id`.
|
||||
id: i32,
|
||||
// Connections that were sent `files_pdu`.
|
||||
served_to: Vec<i32>,
|
||||
}
|
||||
|
||||
impl ClipFiles {
|
||||
@@ -71,6 +101,8 @@ impl ClipFiles {
|
||||
self.file_list.clear();
|
||||
self.first_file_index = usize::MAX;
|
||||
self.files_pdu.clear();
|
||||
self.id = 0;
|
||||
self.served_to.clear();
|
||||
}
|
||||
|
||||
fn sync_files(
|
||||
@@ -100,9 +132,54 @@ impl ClipFiles {
|
||||
data.put(file.as_bin()?.as_slice());
|
||||
}
|
||||
self.files_pdu = data.to_vec();
|
||||
if let Some(nonce) = self.files_pdu.get_mut(LIST_NONCE) {
|
||||
nonce.copy_from_slice(&rand::random::<[u8; 16]>());
|
||||
}
|
||||
self.id = file_list_id(&self.files_pdu);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Close files that are not being read, such as the preloaded next file; `read_exact_at`
|
||||
// reopens them on the next read. A file part-way through keeps its handle and offset, so
|
||||
// its remaining bytes come from the same file even if its path is replaced meanwhile.
|
||||
fn release_handles(&mut self) {
|
||||
for file in self.file_list.iter_mut() {
|
||||
if file.offset.load(Ordering::Relaxed) == 0 {
|
||||
file.handle = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A retired list's file is reopened by path once its handle was closed, and the path may now
|
||||
// name a replacement. Check size and modified time on the handle the read will use, and refuse
|
||||
// a file that no longer matches the list.
|
||||
fn check_retired_file(&mut self, request: &FileContentsRequest) -> Result<(), CliprdrError> {
|
||||
let FileContentsRequest::Range { file_idx, .. } = request else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(file) = self.file_list.get_mut(*file_idx) else {
|
||||
return Ok(());
|
||||
};
|
||||
if file.is_dir {
|
||||
return Ok(());
|
||||
}
|
||||
file.load_handle()?;
|
||||
let unchanged = file
|
||||
.handle
|
||||
.as_ref()
|
||||
.and_then(|handle| handle.get_ref().metadata().ok())
|
||||
.map_or(false, |md| {
|
||||
md.len() == file.size && md.modified().ok() == Some(file.last_write_time)
|
||||
});
|
||||
if unchanged {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CliprdrError::InvalidRequest {
|
||||
description: format!("file {} changed since its list was sent", file.name),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn get_files_for_audit(&self, request: &FileContentsRequest) -> Option<ClipboardFile> {
|
||||
if let FileContentsRequest::Range {
|
||||
file_idx, offset, ..
|
||||
@@ -213,12 +290,21 @@ impl ClipFiles {
|
||||
),
|
||||
});
|
||||
}
|
||||
let read_size = if offset + length > file.size {
|
||||
let read_size = if length > file.size - offset {
|
||||
file.size - offset
|
||||
} else {
|
||||
length
|
||||
};
|
||||
|
||||
if read_size > MAX_RANGE_READ {
|
||||
return Err(CliprdrError::InvalidRequest {
|
||||
description: format!(
|
||||
"file contents request of {} bytes exceeds the {} byte limit, conn: {}",
|
||||
read_size, MAX_RANGE_READ, conn_id
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let mut buf = vec![0u8; read_size as usize];
|
||||
|
||||
file.read_exact_at(&mut buf, offset)?;
|
||||
@@ -238,7 +324,10 @@ impl ClipFiles {
|
||||
// hot reload next file
|
||||
for next_file in self.file_list.iter_mut().skip(file_idx + 1) {
|
||||
if !next_file.is_dir {
|
||||
next_file.load_handle()?;
|
||||
// Best-effort: if it still cannot be opened, its own request reports that.
|
||||
if let Err(e) = next_file.load_handle() {
|
||||
log::trace!("failed to preload the next file: {:?}", e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -249,6 +338,44 @@ impl ClipFiles {
|
||||
#[inline]
|
||||
pub fn clear_files() {
|
||||
CLIP_FILES.lock().clear();
|
||||
RETIRED_CLIP_FILES.lock().clear();
|
||||
}
|
||||
|
||||
// The list a request reads from: the one its `clip_data_id` names, else the one last sent to
|
||||
// the connection. A named list that is gone yields `None`. A peer that sends no id and was
|
||||
// never sent a list reads the current one, as before.
|
||||
fn select_clip_files<'a>(
|
||||
current: &'a mut ClipFiles,
|
||||
retired: &'a mut VecDeque<ClipFiles>,
|
||||
conn_id: i32,
|
||||
clip_data_id: Option<i32>,
|
||||
) -> Option<&'a mut ClipFiles> {
|
||||
match clip_data_id {
|
||||
Some(id) if current.id == id => Some(current),
|
||||
Some(id) => retired
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|files| files.id == id && files.served_to.contains(&conn_id)),
|
||||
None if current.served_to.contains(&conn_id) => Some(current),
|
||||
None => retired
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|files| files.served_to.contains(&conn_id))
|
||||
.or(Some(current)),
|
||||
}
|
||||
}
|
||||
|
||||
// Keep a list a peer was sent, so its streams do not read the new copy at the same indexes.
|
||||
fn retire_if_served(mut replaced: ClipFiles) {
|
||||
if replaced.served_to.is_empty() {
|
||||
return;
|
||||
}
|
||||
replaced.release_handles();
|
||||
let mut retired = RETIRED_CLIP_FILES.lock();
|
||||
if retired.len() == MAX_RETIRED_CLIP_FILES {
|
||||
retired.pop_front();
|
||||
}
|
||||
retired.push_back(replaced);
|
||||
}
|
||||
|
||||
pub fn read_file_contents(
|
||||
@@ -259,6 +386,7 @@ pub fn read_file_contents(
|
||||
n_position_low: i32,
|
||||
n_position_high: i32,
|
||||
cb_requested: i32,
|
||||
clip_data_id: Option<i32>,
|
||||
) -> Vec<Result<ClipboardFile, CliprdrError>> {
|
||||
let fcr = if dw_flags == 0x1 {
|
||||
FileContentsRequest::Size {
|
||||
@@ -266,8 +394,11 @@ pub fn read_file_contents(
|
||||
file_idx: list_index as usize,
|
||||
}
|
||||
} else if dw_flags == 0x2 {
|
||||
let offset = (n_position_high as u64) << 32 | n_position_low as u64;
|
||||
let length = cb_requested as u64;
|
||||
// nPositionLow and cbRequested are UINT32s carried in i32 fields. Sign-extending
|
||||
// them rejects offsets whose low word is >= 2 GiB and turns a negative length
|
||||
// into a near-u64::MAX read.
|
||||
let offset = (n_position_high as u64) << 32 | n_position_low as u32 as u64;
|
||||
let length = cb_requested as u32 as u64;
|
||||
|
||||
FileContentsRequest::Range {
|
||||
stream_id,
|
||||
@@ -281,7 +412,23 @@ pub fn read_file_contents(
|
||||
})];
|
||||
};
|
||||
|
||||
let mut clip_files = CLIP_FILES.lock();
|
||||
let mut current = CLIP_FILES.lock();
|
||||
let mut retired = RETIRED_CLIP_FILES.lock();
|
||||
let current_ptr: *const ClipFiles = &*current;
|
||||
let Some(clip_files) = select_clip_files(&mut current, &mut retired, conn_id, clip_data_id)
|
||||
else {
|
||||
return vec![Err(CliprdrError::InvalidRequest {
|
||||
description: format!(
|
||||
"file list {:?} is not available to conn: {}",
|
||||
clip_data_id, conn_id
|
||||
),
|
||||
})];
|
||||
};
|
||||
if !std::ptr::eq(&*clip_files, current_ptr) {
|
||||
if let Err(e) = clip_files.check_retired_file(&fcr) {
|
||||
return vec![Err(e)];
|
||||
}
|
||||
}
|
||||
let mut res = vec![];
|
||||
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
|
||||
res.push(Ok(files_res));
|
||||
@@ -301,12 +448,21 @@ pub fn sync_files(files: &[String]) -> Result<(), CliprdrError> {
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
files_lock.sync_files(files, current)?;
|
||||
files_lock.build_file_list_pdu()
|
||||
// Build aside, so a failure leaves the current list in place.
|
||||
let mut next = ClipFiles::default();
|
||||
next.sync_files(files, current)?;
|
||||
next.build_file_list_pdu()?;
|
||||
let replaced = std::mem::replace(&mut *files_lock, next);
|
||||
retire_if_served(replaced);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_file_list_pdu() -> Vec<u8> {
|
||||
CLIP_FILES.lock().files_pdu.clone()
|
||||
pub fn get_file_list_pdu(conn_id: i32) -> Vec<u8> {
|
||||
let mut clip_files = CLIP_FILES.lock();
|
||||
if !clip_files.files_pdu.is_empty() && !clip_files.served_to.contains(&conn_id) {
|
||||
clip_files.served_to.push(conn_id);
|
||||
}
|
||||
clip_files.files_pdu.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -343,6 +499,30 @@ mod sig_test {
|
||||
p.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
// Tests that drive the global CLIP_FILES must not interleave.
|
||||
static CLIP_FILES_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn lock_clip_files() -> std::sync::MutexGuard<'static, ()> {
|
||||
CLIP_FILES_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
// Sparse, so a multi-GiB file costs no disk space.
|
||||
fn write_at(path: &PathBuf, offset: u64, data: &[u8]) {
|
||||
use std::io::{Seek, SeekFrom, Write};
|
||||
let mut f = fs::File::create(path).unwrap();
|
||||
f.seek(SeekFrom::Start(offset)).unwrap();
|
||||
f.write_all(data).unwrap();
|
||||
}
|
||||
|
||||
fn range_data(res: Vec<Result<ClipboardFile, CliprdrError>>) -> Vec<u8> {
|
||||
match res.into_iter().last() {
|
||||
Some(Ok(ClipboardFile::FileContentsResponse { requested_data, .. })) => requested_data,
|
||||
other => panic!("unexpected response: {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_missing_path_is_default() {
|
||||
let tmp = TmpDir::new("missing");
|
||||
@@ -393,7 +573,8 @@ mod sig_test {
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
|
||||
// reset first (this is the only test that touches the global).
|
||||
// reset first.
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
|
||||
sync_files(&files).unwrap();
|
||||
@@ -415,4 +596,420 @@ mod sig_test {
|
||||
|
||||
clear_files(); // leave the global clean for other tests
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_huge_length_is_clamped() {
|
||||
let tmp = TmpDir::new("range");
|
||||
let file = tmp.join("data.bin");
|
||||
fs::write(&file, b"0123456789").unwrap();
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
let mut clip = ClipFiles::default();
|
||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
||||
let file_idx = clip.first_file_index;
|
||||
|
||||
// offset + length used to wrap to 0, skip the clamp and ask for a u64::MAX buffer.
|
||||
let resp = clip
|
||||
.serve_file_contents(
|
||||
0,
|
||||
FileContentsRequest::Range {
|
||||
stream_id: 0,
|
||||
file_idx,
|
||||
offset: 1,
|
||||
length: u64::MAX,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match resp {
|
||||
ClipboardFile::FileContentsResponse { requested_data, .. } => {
|
||||
assert_eq!(requested_data, b"123456789");
|
||||
}
|
||||
_ => panic!("unexpected response"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_decodes_wire_fields_as_u32() {
|
||||
let tmp = TmpDir::new("decode");
|
||||
let small = tmp.join("small.bin");
|
||||
fs::write(&small, b"0123456789").unwrap();
|
||||
let large = tmp.join("large.bin");
|
||||
write_at(&large, 0x8000_0000, b"tail");
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&small), path_str(&large)]).unwrap();
|
||||
let small_idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
let large_idx = small_idx + 1;
|
||||
|
||||
// A negative cbRequested is a UINT32 length, clamped to the rest of the file.
|
||||
let res = read_file_contents(0, 0, small_idx, 0x2, 1, 0, -1, None);
|
||||
assert_eq!(range_data(res), b"123456789");
|
||||
|
||||
// An nPositionLow with bit 31 set is an offset past 2 GiB, not a huge one.
|
||||
let res = read_file_contents(0, 0, large_idx, 0x2, 0x8000_0000u32 as i32, 0, 4, None);
|
||||
assert_eq!(range_data(res), b"tail");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_over_limit_is_rejected() {
|
||||
let tmp = TmpDir::new("limit");
|
||||
let file = tmp.join("big.bin");
|
||||
let size = MAX_RANGE_READ + 1;
|
||||
write_at(&file, size - 1, b"x");
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
let mut clip = ClipFiles::default();
|
||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
||||
let file_idx = clip.first_file_index;
|
||||
|
||||
let res = clip.serve_file_contents(
|
||||
0,
|
||||
FileContentsRequest::Range {
|
||||
stream_id: 0,
|
||||
file_idx,
|
||||
offset: 0,
|
||||
length: u32::MAX as u64,
|
||||
},
|
||||
);
|
||||
assert!(matches!(res, Err(CliprdrError::InvalidRequest { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_copy_during_transfer_keeps_serving_the_sent_list() {
|
||||
let tmp = TmpDir::new("recopy_in_flight");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
get_file_list_pdu(1);
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
let read = |offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, None));
|
||||
assert_eq!(read(0), b"AAAA");
|
||||
|
||||
// Copying another file on this side must not redirect the peer's stream.
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
assert_eq!(read(4), b"AAAA");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_keeps_its_list_after_a_second_paste() {
|
||||
let tmp = TmpDir::new("repaste_in_flight");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
|
||||
// The peer copies the second file on this side and pastes it while the first
|
||||
// transfer is still reading.
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
let second_id = file_list_id(&get_file_list_pdu(1));
|
||||
assert_ne!(first_id, second_id);
|
||||
|
||||
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
|
||||
assert_eq!(read(first_id), b"AAAA");
|
||||
assert_eq!(read(second_id), b"BBBB");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_list_must_have_been_sent_to_the_conn() {
|
||||
let tmp = TmpDir::new("foreign_list");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
|
||||
let refused = |conn_id, id| {
|
||||
matches!(
|
||||
read_file_contents(conn_id, 7, idx, 0x2, 0, 0, 4, Some(id)).last(),
|
||||
Some(Err(CliprdrError::InvalidRequest { .. }))
|
||||
)
|
||||
};
|
||||
// Retired list, asked for by a connection it was never sent to.
|
||||
assert!(refused(2, first_id));
|
||||
// A list id this side never sent.
|
||||
assert!(refused(1, first_id ^ 1));
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_recopy_keeps_the_current_list() {
|
||||
let tmp = TmpDir::new("failed_recopy");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let missing = tmp.join("missing.bin");
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let pdu = get_file_list_pdu(1);
|
||||
|
||||
assert!(sync_files(&[path_str(&missing)]).is_err());
|
||||
assert_eq!(get_file_list_pdu(1), pdu);
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
fn file_index(path: &PathBuf) -> i32 {
|
||||
let files = CLIP_FILES.lock();
|
||||
files
|
||||
.file_list
|
||||
.iter()
|
||||
.position(|f| &f.path == path)
|
||||
.unwrap() as i32
|
||||
}
|
||||
|
||||
// Replaces `path` the way editors save: write aside, then rename over it.
|
||||
fn replace_atomically(path: &PathBuf, data: &[u8]) {
|
||||
let aside = path.with_extension("new");
|
||||
fs::write(&aside, data).unwrap();
|
||||
fs::rename(&aside, path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retired_list_closes_only_files_not_being_read() {
|
||||
let tmp = TmpDir::new("retired_handles");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAABBBB").unwrap();
|
||||
let next = tmp.join("next.bin");
|
||||
fs::write(&next, b"CCCCDDDD").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&next)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, next_idx) = (file_index(&first), file_index(&next));
|
||||
let read =
|
||||
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
|
||||
// Leaves `first` open at offset 4, and preloads `next`.
|
||||
assert_eq!(read(first_idx, 0), b"AAAA");
|
||||
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
{
|
||||
let retired = RETIRED_CLIP_FILES.lock();
|
||||
let open = |idx: i32| retired[0].file_list[idx as usize].handle.is_some();
|
||||
assert!(open(first_idx));
|
||||
assert!(!open(next_idx));
|
||||
}
|
||||
assert_eq!(read(first_idx, 4), b"BBBB");
|
||||
assert_eq!(read(next_idx, 0), b"CCCC");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_being_read_keep_their_content_when_their_paths_are_replaced() {
|
||||
let tmp = TmpDir::new("replaced_paths");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"1111aaaa").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"2222bbbb").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
|
||||
let read =
|
||||
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
|
||||
// Two files part-way through at once.
|
||||
assert_eq!(read(first_idx, 0), b"1111");
|
||||
assert_eq!(read(second_idx, 0), b"2222");
|
||||
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
replace_atomically(&first, b"3333cccc");
|
||||
replace_atomically(&second, b"4444dddd");
|
||||
|
||||
assert_eq!(read(first_idx, 4), b"aaaa");
|
||||
assert_eq!(read(second_idx, 4), b"bbbb");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_file_metadata_in_another_folder_is_another_list() {
|
||||
let tmp = TmpDir::new("same_metadata");
|
||||
let (dir_a, dir_b) = (tmp.join("a"), tmp.join("b"));
|
||||
fs::create_dir_all(&dir_a).unwrap();
|
||||
fs::create_dir_all(&dir_b).unwrap();
|
||||
let (first, second) = (dir_a.join("report.bin"), dir_b.join("report.bin"));
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
// Same name, size and mtime: the descriptors differ only by the nonce.
|
||||
let mtime = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
for path in [&first, &second] {
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_modified(mtime)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
let second_id = file_list_id(&get_file_list_pdu(1));
|
||||
assert_ne!(first_id, second_id);
|
||||
|
||||
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
|
||||
assert_eq!(read(first_id), b"AAAA");
|
||||
assert_eq!(read(second_id), b"BBBB");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retired_list_refuses_a_file_replaced_before_its_read() {
|
||||
let tmp = TmpDir::new("replaced_unread");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
|
||||
let read = |idx, offset| read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id));
|
||||
assert_eq!(range_data(read(first_idx, 0)), b"AAAA");
|
||||
|
||||
// Retiring closes `second`, which has not been read yet; it is then replaced.
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
replace_atomically(&second, b"CCCCCCCCCC");
|
||||
|
||||
assert!(matches!(
|
||||
read(second_idx, 0).last(),
|
||||
Some(Err(CliprdrError::InvalidRequest { .. }))
|
||||
));
|
||||
// The file part-way through is unaffected.
|
||||
assert_eq!(range_data(read(first_idx, 4)), b"AAAA");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
fn list_files(selection: &[&PathBuf]) -> ClipFiles {
|
||||
let files: Vec<String> = selection.iter().map(|p| path_str(p)).collect();
|
||||
let mut clip = ClipFiles::default();
|
||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
||||
clip
|
||||
}
|
||||
|
||||
fn read_head(clip: &mut ClipFiles, file_idx: usize) -> Result<Vec<u8>, CliprdrError> {
|
||||
let request = FileContentsRequest::Range {
|
||||
stream_id: 0,
|
||||
file_idx,
|
||||
offset: 0,
|
||||
length: 4,
|
||||
};
|
||||
match clip.serve_file_contents(0, request)? {
|
||||
ClipboardFile::FileContentsResponse { requested_data, .. } => Ok(requested_data),
|
||||
other => panic!("unexpected response: {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
// Preloading the file after the requested one is best-effort: a file that can no longer
|
||||
// be opened fails its own requests, not those of the file before it.
|
||||
fn assert_only_its_own_requests_fail(clip: &mut ClipFiles, broken: &PathBuf) {
|
||||
let first_idx = clip.first_file_index;
|
||||
let broken_idx = clip
|
||||
.file_list
|
||||
.iter()
|
||||
.position(|f| &f.path == broken)
|
||||
.unwrap();
|
||||
let size = FileContentsRequest::Size {
|
||||
stream_id: 0,
|
||||
file_idx: first_idx,
|
||||
};
|
||||
clip.serve_file_contents(0, size).unwrap();
|
||||
assert_eq!(read_head(clip, first_idx).unwrap(), b"AAAA");
|
||||
assert!(matches!(
|
||||
read_head(clip, broken_idx),
|
||||
Err(CliprdrError::FileError { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_next_file_fails_only_its_own_requests() {
|
||||
let tmp = TmpDir::new("next_deleted");
|
||||
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
let mut clip = list_files(&[&first, &second]);
|
||||
|
||||
fs::remove_file(&second).unwrap();
|
||||
assert_only_its_own_requests_fail(&mut clip, &second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_next_file_fails_only_its_own_requests() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = TmpDir::new("next_unreadable");
|
||||
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
let mut clip = list_files(&[&first, &second]);
|
||||
|
||||
fs::set_permissions(&second, fs::Permissions::from_mode(0o000)).unwrap();
|
||||
// Root opens it regardless of its mode.
|
||||
if fs::File::open(&second).is_ok() {
|
||||
return;
|
||||
}
|
||||
assert_only_its_own_requests_fail(&mut clip, &second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_next_file_is_preloaded_past_a_directory() {
|
||||
let tmp = TmpDir::new("next_preloaded");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let dir = tmp.join("dir");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
let inner = dir.join("inner.bin");
|
||||
fs::write(&inner, b"BBBBBBBB").unwrap();
|
||||
// Listed as first.bin, dir, dir/inner.bin.
|
||||
let mut clip = list_files(&[&first, &dir]);
|
||||
let first_idx = clip.first_file_index;
|
||||
let inner_idx = clip.file_list.len() - 1;
|
||||
assert_eq!(clip.file_list[inner_idx].path, inner);
|
||||
|
||||
assert_eq!(read_head(&mut clip, first_idx).unwrap(), b"AAAA");
|
||||
assert!(clip.file_list[inner_idx].handle.is_some());
|
||||
// The last file has no next file to preload.
|
||||
assert_eq!(read_head(&mut clip, inner_idx).unwrap(), b"BBBB");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,12 @@
|
||||
/* File clipboard redirection always advertises the descriptor and contents formats. */
|
||||
#define WF_CLIPRDR_FILE_FORMAT_COUNT 2u
|
||||
#define WF_CLIPRDR_COM_LPT_PREFIX_LENGTH 3u
|
||||
/* File lists kept after they were sent, so a transfer still in flight keeps reading its own
|
||||
* files after a later copy or paste replaces them. */
|
||||
#define WF_CLIPRDR_SERVED_FILE_LISTS 4u
|
||||
/* Largest range served in one request, here and by the unix file server (MAX_RANGE_READ in
|
||||
* serv_files.rs). Larger IStream reads are split into requests of this size. */
|
||||
#define WF_CLIPRDR_MAX_RANGE_READ (16u * 1024u * 1024u)
|
||||
static const WCHAR WF_CLIPRDR_SUPERSCRIPT_DIGITS[] = L"\x00B9\x00B2\x00B3";
|
||||
static const WCHAR WF_CLIPRDR_INVALID_FILE_NAME_CHARS[] = L"<>:\"|?*";
|
||||
|
||||
@@ -213,6 +219,21 @@ static BOOL wf_cliprdr_bounded_strlen(const char *value, size_t max_len, size_t
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/* Identifies a file list by its FILEGROUPDESCRIPTORW bytes, which both peers hold, and is
|
||||
* carried as FileContentsRequest.clipDataId. FNV-1a, same as `file_list_id()` on unix. */
|
||||
static UINT32 wf_cliprdr_file_list_id(const BYTE *data, SIZE_T size)
|
||||
{
|
||||
UINT32 id = 2166136261u;
|
||||
SIZE_T i;
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
{
|
||||
id ^= data[i];
|
||||
id *= 16777619u;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard Formats
|
||||
*/
|
||||
@@ -358,6 +379,7 @@ struct _CliprdrStream
|
||||
void *m_pData;
|
||||
UINT32 m_connID;
|
||||
UINT32 m_streamId; // unique CLIPRDR streamId; avoids leaking a heap pointer
|
||||
UINT32 m_clipDataId; // id of the file list this stream was created from
|
||||
};
|
||||
typedef struct _CliprdrStream CliprdrStream;
|
||||
|
||||
@@ -377,6 +399,21 @@ struct _CliprdrDataObject
|
||||
};
|
||||
typedef struct _CliprdrDataObject CliprdrDataObject;
|
||||
|
||||
struct wf_served_file_list
|
||||
{
|
||||
UINT32 id;
|
||||
UINT32 *connIDs; // connections the list was sent to
|
||||
size_t nConnIDs;
|
||||
UINT64 last_served; // served_file_list_seq when last sent; the lowest is evicted first
|
||||
size_t nFiles;
|
||||
size_t first_file_index;
|
||||
WCHAR **file_names;
|
||||
UINT64 *file_sizes;
|
||||
BYTE *descriptors; // the FILEGROUPDESCRIPTORW sent, nonce included
|
||||
SIZE_T descriptorsSize;
|
||||
};
|
||||
typedef struct wf_served_file_list wfServedFileList;
|
||||
|
||||
struct wf_clipboard
|
||||
{
|
||||
// wfContext* wfc;
|
||||
@@ -424,6 +461,10 @@ struct wf_clipboard
|
||||
WCHAR **file_names;
|
||||
size_t first_file_index;
|
||||
FILEDESCRIPTORW **fileDescriptor;
|
||||
DWORD file_list_seq; // clipboard sequence number the file list was read at
|
||||
UINT32 file_list_id; // wf_cliprdr_file_list_id() of the file list, 0 while none is valid
|
||||
wfServedFileList served_file_lists[WF_CLIPRDR_SERVED_FILE_LISTS];
|
||||
UINT64 served_file_list_seq;
|
||||
|
||||
BOOL legacyApi;
|
||||
HMODULE hUser32;
|
||||
@@ -451,8 +492,8 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
|
||||
static UINT cliprdr_send_lock(wfClipboard *clipboard);
|
||||
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
|
||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
||||
ULONG index, UINT32 flag, DWORD positionhigh,
|
||||
DWORD positionlow, ULONG request);
|
||||
UINT32 clipDataId, ULONG index, UINT32 flag,
|
||||
DWORD positionhigh, DWORD positionlow, ULONG request);
|
||||
|
||||
static BOOL is_file_descriptor_from_remote();
|
||||
static BOOL is_set_by_instance(wfClipboard *clipboard);
|
||||
@@ -464,6 +505,7 @@ static HRESULT CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC *pFormatEtc,
|
||||
static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC *instance);
|
||||
|
||||
static void CliprdrStream_Delete(CliprdrStream *instance);
|
||||
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead);
|
||||
|
||||
static BOOL try_open_clipboard(HWND hwnd)
|
||||
{
|
||||
@@ -550,7 +592,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
|
||||
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
|
||||
return S_FALSE;
|
||||
|
||||
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId, instance->m_lIndex,
|
||||
if (cb > WF_CLIPRDR_MAX_RANGE_READ)
|
||||
return wf_cliprdr_stream_read_split(This, (BYTE *)pv, cb, pcbRead);
|
||||
|
||||
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
||||
instance->m_clipDataId, instance->m_lIndex,
|
||||
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
|
||||
instance->m_lOffset.LowPart, cb);
|
||||
|
||||
@@ -591,6 +637,26 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
ULONG total = 0;
|
||||
ULONG chunk;
|
||||
ULONG n;
|
||||
|
||||
while (total < cb && hr == S_OK)
|
||||
{
|
||||
chunk = cb - total < WF_CLIPRDR_MAX_RANGE_READ ? cb - total : WF_CLIPRDR_MAX_RANGE_READ;
|
||||
n = 0;
|
||||
hr = CliprdrStream_Read(This, pv + total, chunk, &n);
|
||||
total += n;
|
||||
}
|
||||
*pcbRead = total;
|
||||
if (FAILED(hr))
|
||||
return hr;
|
||||
return total < cb ? S_FALSE : S_OK;
|
||||
}
|
||||
|
||||
static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream *This, const void *pv, ULONG cb,
|
||||
ULONG *pcbWritten)
|
||||
{
|
||||
@@ -736,7 +802,8 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Clone(IStream *This, IStream **pp
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc)
|
||||
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc,
|
||||
UINT32 clipDataId)
|
||||
{
|
||||
IStream *iStream = NULL;
|
||||
BOOL success = FALSE;
|
||||
@@ -779,6 +846,7 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
|
||||
instance->m_lOffset.QuadPart = 0;
|
||||
instance->m_connID = connID;
|
||||
instance->m_streamId = (UINT32)InterlockedIncrement(&clipboard->req_f_stream_id_seq);
|
||||
instance->m_clipDataId = clipDataId;
|
||||
|
||||
if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES)
|
||||
{
|
||||
@@ -790,8 +858,8 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
|
||||
{
|
||||
/* get content size of this stream */
|
||||
if (cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
||||
instance->m_lIndex, FILECONTENTS_SIZE, 0, 0,
|
||||
8) == CHANNEL_RC_OK)
|
||||
instance->m_clipDataId, instance->m_lIndex,
|
||||
FILECONTENTS_SIZE, 0, 0, 8) == CHANNEL_RC_OK)
|
||||
{
|
||||
success = TRUE;
|
||||
}
|
||||
@@ -1007,6 +1075,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
|
||||
IStream **streams = NULL;
|
||||
UINT stream_count = 0;
|
||||
SIZE_T hmem_size;
|
||||
UINT32 clipDataId;
|
||||
// DWORD remote_format_id = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat);
|
||||
// FIXME: origin code may be failed here???
|
||||
if (cliprdr_send_data_request(instance->m_connID, clipboard, instance->m_pFormatEtc[idx].cfFormat) != 0)
|
||||
@@ -1053,10 +1122,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
|
||||
return wf_cliprdr_fail_locked_file_descriptor_data(
|
||||
clipboard, pMedium, instance, NULL, 0, E_OUTOFMEMORY);
|
||||
|
||||
clipDataId = wf_cliprdr_file_list_id((const BYTE *)dsc, hmem_size);
|
||||
for (i = 0; i < stream_count; i++)
|
||||
{
|
||||
streams[i] =
|
||||
(IStream *)CliprdrStream_New(instance->m_connID, i, clipboard, &dsc->fgd[i]);
|
||||
streams[i] = (IStream *)CliprdrStream_New(instance->m_connID, i, clipboard,
|
||||
&dsc->fgd[i], clipDataId);
|
||||
if (!streams[i])
|
||||
{
|
||||
return wf_cliprdr_fail_locked_file_descriptor_data(
|
||||
@@ -1996,9 +2066,9 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
|
||||
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
|
||||
}
|
||||
|
||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId, ULONG index,
|
||||
UINT32 flag, DWORD positionhigh, DWORD positionlow,
|
||||
ULONG nreq)
|
||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
||||
UINT32 clipDataId, ULONG index, UINT32 flag,
|
||||
DWORD positionhigh, DWORD positionlow, ULONG nreq)
|
||||
{
|
||||
UINT rc;
|
||||
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
|
||||
@@ -2023,7 +2093,8 @@ static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 con
|
||||
fileContentsRequest.nPositionLow = positionlow;
|
||||
fileContentsRequest.nPositionHigh = positionhigh;
|
||||
fileContentsRequest.cbRequested = nreq;
|
||||
fileContentsRequest.clipDataId = 0;
|
||||
fileContentsRequest.haveClipDataId = TRUE;
|
||||
fileContentsRequest.clipDataId = clipDataId;
|
||||
fileContentsRequest.msgFlags = 0;
|
||||
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
|
||||
if (rc != ERROR_SUCCESS)
|
||||
@@ -2424,6 +2495,242 @@ error:
|
||||
return res;
|
||||
}
|
||||
|
||||
static void wf_cliprdr_free_served_file_list(wfServedFileList *list)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (list->file_names)
|
||||
{
|
||||
for (i = 0; i < list->nFiles; i++)
|
||||
free(list->file_names[i]);
|
||||
free(list->file_names);
|
||||
}
|
||||
free(list->file_sizes);
|
||||
free(list->connIDs);
|
||||
free(list->descriptors);
|
||||
ZeroMemory(list, sizeof(*list));
|
||||
}
|
||||
|
||||
static BOOL wf_cliprdr_served_to(const wfServedFileList *list, UINT32 connID)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < list->nConnIDs; i++)
|
||||
{
|
||||
if (list->connIDs[i] == connID)
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static void wf_cliprdr_forget_served_file_lists(wfClipboard *clipboard)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
wf_cliprdr_free_served_file_list(&clipboard->served_file_lists[i]);
|
||||
}
|
||||
|
||||
/* Whether a kept list has the current file_names and the same descriptors as dsc, apart
|
||||
* from the nonce in fgd[0].clsid. */
|
||||
static BOOL wf_cliprdr_is_same_file_list(wfClipboard *clipboard, const wfServedFileList *list,
|
||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
||||
{
|
||||
SIZE_T nonce_start = offsetof(FILEGROUPDESCRIPTORW, fgd) + offsetof(FILEDESCRIPTORW, clsid);
|
||||
SIZE_T nonce_end = nonce_start + sizeof(CLSID);
|
||||
size_t i;
|
||||
|
||||
if (!list->file_names || list->nFiles != clipboard->nFiles ||
|
||||
list->descriptorsSize != size || size < nonce_end)
|
||||
return FALSE;
|
||||
for (i = 0; i < list->nFiles; i++)
|
||||
{
|
||||
if (!clipboard->file_names[i] || wcscmp(list->file_names[i], clipboard->file_names[i]) != 0)
|
||||
return FALSE;
|
||||
}
|
||||
return memcmp(list->descriptors, dsc, nonce_start) == 0 &&
|
||||
memcmp(list->descriptors + nonce_end, (const BYTE *)dsc + nonce_end,
|
||||
size - nonce_end) == 0;
|
||||
}
|
||||
|
||||
/* Puts a nonce in fgd[0].clsid, which peers ignore without FD_CLSID. The list id hashes it,
|
||||
* so each copy gets its own id even when two copies have identical names, sizes and times
|
||||
* (the same file in two folders). Re-sending unchanged files keeps their nonce, and id. */
|
||||
static void wf_cliprdr_stamp_file_list(wfClipboard *clipboard, FILEGROUPDESCRIPTORW *dsc,
|
||||
SIZE_T size)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (wf_cliprdr_is_same_file_list(clipboard, &clipboard->served_file_lists[i], dsc, size))
|
||||
{
|
||||
dsc->fgd[0].clsid =
|
||||
((const FILEGROUPDESCRIPTORW *)clipboard->served_file_lists[i].descriptors)
|
||||
->fgd[0]
|
||||
.clsid;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (FAILED(CoCreateGuid(&dsc->fgd[0].clsid)))
|
||||
ZeroMemory(&dsc->fgd[0].clsid, sizeof(CLSID));
|
||||
}
|
||||
|
||||
static BOOL wf_cliprdr_copy_file_list(wfClipboard *clipboard, wfServedFileList *list,
|
||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
list->file_names = (WCHAR **)calloc(clipboard->nFiles, sizeof(WCHAR *));
|
||||
list->file_sizes = (UINT64 *)calloc(clipboard->nFiles, sizeof(UINT64));
|
||||
list->descriptors = (BYTE *)malloc(size);
|
||||
if (!list->file_names || !list->file_sizes || !list->descriptors)
|
||||
return FALSE;
|
||||
CopyMemory(list->descriptors, dsc, size);
|
||||
list->descriptorsSize = size;
|
||||
list->nFiles = clipboard->nFiles;
|
||||
for (i = 0; i < clipboard->nFiles; i++)
|
||||
{
|
||||
if (!clipboard->file_names[i] ||
|
||||
!(list->file_names[i] = _wcsdup(clipboard->file_names[i])))
|
||||
return FALSE;
|
||||
if (clipboard->fileDescriptor[i])
|
||||
list->file_sizes[i] = ((UINT64)clipboard->fileDescriptor[i]->nFileSizeHigh << 32) |
|
||||
clipboard->fileDescriptor[i]->nFileSizeLow;
|
||||
}
|
||||
list->id = clipboard->file_list_id;
|
||||
list->first_file_index = clipboard->first_file_index;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/* One slot per list, shared by every connection it was sent to. A full table evicts the list
|
||||
* sent least recently, so a list a transfer has just started on is kept. */
|
||||
static void wf_cliprdr_remember_served_file_list(wfClipboard *clipboard, UINT32 connID,
|
||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
||||
{
|
||||
wfServedFileList *list = NULL;
|
||||
UINT32 *connIDs;
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (clipboard->served_file_lists[i].file_names &&
|
||||
clipboard->served_file_lists[i].id == clipboard->file_list_id)
|
||||
{
|
||||
list = &clipboard->served_file_lists[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!list)
|
||||
{
|
||||
// An empty slot has last_served 0, so it is taken first.
|
||||
list = &clipboard->served_file_lists[0];
|
||||
for (i = 1; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (clipboard->served_file_lists[i].last_served < list->last_served)
|
||||
list = &clipboard->served_file_lists[i];
|
||||
}
|
||||
wf_cliprdr_free_served_file_list(list);
|
||||
if (!wf_cliprdr_copy_file_list(clipboard, list, dsc, size))
|
||||
{
|
||||
wf_cliprdr_free_served_file_list(list);
|
||||
return;
|
||||
}
|
||||
}
|
||||
list->last_served = ++clipboard->served_file_list_seq;
|
||||
|
||||
if (wf_cliprdr_served_to(list, connID))
|
||||
return;
|
||||
connIDs = (UINT32 *)realloc(list->connIDs, (list->nConnIDs + 1) * sizeof(UINT32));
|
||||
if (!connIDs)
|
||||
return;
|
||||
connIDs[list->nConnIDs++] = connID;
|
||||
list->connIDs = connIDs;
|
||||
}
|
||||
|
||||
/* Reads like wf_cliprdr_get_file_contents, but only from the file the list was sent with: a
|
||||
* different size or last-write time means the path now names another file, and the read fails
|
||||
* rather than continuing a transfer with its bytes. */
|
||||
static BOOL wf_cliprdr_get_served_file_contents(const WCHAR *file_name, const FILEDESCRIPTORW *dsc,
|
||||
BYTE *buffer, DWORD positionLow, DWORD positionHigh,
|
||||
DWORD nRequested, DWORD *puSize)
|
||||
{
|
||||
BOOL res = FALSE;
|
||||
HANDLE hFile;
|
||||
LARGE_INTEGER size;
|
||||
LARGE_INTEGER position;
|
||||
FILETIME lastWrite;
|
||||
DWORD nGet;
|
||||
|
||||
hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
|
||||
if (hFile == INVALID_HANDLE_VALUE)
|
||||
return FALSE;
|
||||
|
||||
if (GetFileSizeEx(hFile, &size) &&
|
||||
(UINT64)size.QuadPart == (((UINT64)dsc->nFileSizeHigh << 32) | dsc->nFileSizeLow) &&
|
||||
(!(dsc->dwFlags & FD_WRITESTIME) ||
|
||||
(GetFileTime(hFile, NULL, NULL, &lastWrite) &&
|
||||
CompareFileTime(&lastWrite, &dsc->ftLastWriteTime) == 0)))
|
||||
{
|
||||
position.LowPart = positionLow;
|
||||
position.HighPart = (LONG)positionHigh;
|
||||
if (SetFilePointerEx(hFile, position, NULL, FILE_BEGIN) &&
|
||||
ReadFile(hFile, buffer, nRequested, &nGet, NULL))
|
||||
{
|
||||
*puSize = nGet;
|
||||
res = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
CloseHandle(hFile);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Serves a request by path from the file list it names, if that list was sent to the same
|
||||
* connection. An unknown list fails the request rather than falling back to other files. */
|
||||
static BOOL wf_cliprdr_read_served_file_list(wfClipboard *clipboard,
|
||||
const CLIPRDR_FILE_CONTENTS_REQUEST *request,
|
||||
BYTE *data, UINT32 cbRequested, DWORD *puSize)
|
||||
{
|
||||
wfServedFileList *list = NULL;
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (clipboard->served_file_lists[i].file_names &&
|
||||
clipboard->served_file_lists[i].id == request->clipDataId &&
|
||||
wf_cliprdr_served_to(&clipboard->served_file_lists[i], request->connID))
|
||||
{
|
||||
list = &clipboard->served_file_lists[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!list || request->listIndex >= list->nFiles)
|
||||
return FALSE;
|
||||
|
||||
if (request->dwFlags == FILECONTENTS_SIZE)
|
||||
{
|
||||
CopyMemory(data, &list->file_sizes[request->listIndex], sizeof(UINT64));
|
||||
*puSize = sizeof(UINT64);
|
||||
return TRUE;
|
||||
}
|
||||
if (request->dwFlags != FILECONTENTS_RANGE)
|
||||
return FALSE;
|
||||
|
||||
if (clipboard->context->HandleClipboardFiles &&
|
||||
request->listIndex == (UINT32)list->first_file_index &&
|
||||
request->nPositionLow == 0 && request->nPositionHigh == 0)
|
||||
{
|
||||
clipboard->context->HandleClipboardFiles(request->connID, list->nFiles, list->file_names);
|
||||
}
|
||||
return wf_cliprdr_get_served_file_contents(
|
||||
list->file_names[request->listIndex],
|
||||
&((const FILEGROUPDESCRIPTORW *)list->descriptors)->fgd[request->listIndex], data,
|
||||
request->nPositionLow, request->nPositionHigh, cbRequested, puSize);
|
||||
}
|
||||
|
||||
/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */
|
||||
static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t pathLen)
|
||||
{
|
||||
@@ -3028,6 +3335,8 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
|
||||
STGMEDIUM stg_medium;
|
||||
DROPFILES *dropFiles;
|
||||
FILEGROUPDESCRIPTORW *groupDsc;
|
||||
clipboard->file_list_seq = GetClipboardSequenceNumber();
|
||||
clipboard->file_list_id = 0;
|
||||
result = OleGetClipboard(&dataObj);
|
||||
|
||||
if (FAILED(result))
|
||||
@@ -3164,6 +3473,10 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
|
||||
|
||||
buff = groupDsc;
|
||||
rc = ERROR_SUCCESS;
|
||||
wf_cliprdr_stamp_file_list(clipboard, groupDsc, size);
|
||||
clipboard->file_list_id = wf_cliprdr_file_list_id((const BYTE *)groupDsc, size);
|
||||
wf_cliprdr_remember_served_file_list(clipboard, formatDataRequest->connID, groupDsc,
|
||||
size);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -3376,6 +3689,18 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
||||
return ERROR_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
// Refuse an unknown request type, or a range over the cap, before allocating for it. Clients
|
||||
// of this version split larger reads; an older Windows client reading more in one
|
||||
// IStream::Read fails, as with unix owners.
|
||||
if ((fileContentsRequest->dwFlags != FILECONTENTS_SIZE &&
|
||||
fileContentsRequest->dwFlags != FILECONTENTS_RANGE) ||
|
||||
(fileContentsRequest->dwFlags == FILECONTENTS_RANGE &&
|
||||
fileContentsRequest->cbRequested > WF_CLIPRDR_MAX_RANGE_READ))
|
||||
{
|
||||
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
|
||||
goto exit;
|
||||
}
|
||||
|
||||
// If the clipboard is set by the instance, or the file descriptor is from remote,
|
||||
// we should not process the request.
|
||||
// Because this may be the following cases:
|
||||
@@ -3401,6 +3726,22 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
||||
goto exit;
|
||||
}
|
||||
|
||||
// A stream whose list is no longer the current one reads by path from the list it came from.
|
||||
// Only lists sent to this connection are served.
|
||||
if (fileContentsRequest->haveClipDataId &&
|
||||
fileContentsRequest->clipDataId != clipboard->file_list_id)
|
||||
{
|
||||
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
|
||||
cbRequested = fileContentsRequest->dwFlags == FILECONTENTS_SIZE
|
||||
? sizeof(UINT64)
|
||||
: fileContentsRequest->cbRequested;
|
||||
pData = (BYTE *)calloc(1, cbRequested);
|
||||
if (pData && wf_cliprdr_read_served_file_list(clipboard, fileContentsRequest, pData,
|
||||
cbRequested, &uSize))
|
||||
rc = CHANNEL_RC_OK;
|
||||
goto exit;
|
||||
}
|
||||
|
||||
cbRequested = fileContentsRequest->cbRequested;
|
||||
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
|
||||
cbRequested = sizeof(UINT64);
|
||||
@@ -3430,7 +3771,13 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
||||
vFormatEtc.lindex = fileContentsRequest->listIndex;
|
||||
vFormatEtc.ptd = NULL;
|
||||
|
||||
if ((uStreamIdStc != fileContentsRequest->streamId) ||
|
||||
if (GetClipboardSequenceNumber() != clipboard->file_list_seq)
|
||||
{
|
||||
// The clipboard changed after the peer got its file list. The live FileContents
|
||||
// belongs to the new copy, so reading it would splice another file into this one.
|
||||
bIsStreamFile = FALSE;
|
||||
}
|
||||
else if ((uStreamIdStc != fileContentsRequest->streamId) ||
|
||||
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
|
||||
{
|
||||
LPENUMFORMATETC pEnumFormatEtc;
|
||||
@@ -3842,6 +4189,7 @@ BOOL wf_cliprdr_uninit(wfClipboard *clipboard, CliprdrClientContext *cliprdr)
|
||||
CloseHandle(clipboard->req_fevent);
|
||||
|
||||
clear_file_array(clipboard);
|
||||
wf_cliprdr_forget_served_file_lists(clipboard);
|
||||
clear_format_map(clipboard);
|
||||
free(clipboard->format_mappings);
|
||||
return TRUE;
|
||||
|
||||
@@ -39,6 +39,17 @@ fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) -> DWORD {
|
||||
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
|
||||
}
|
||||
|
||||
// `v` comes from the remote peer unchecked, so scale in i64 to avoid overflow, and clamp to
|
||||
// the 0..=65535 range MOUSEEVENTF_ABSOLUTE takes.
|
||||
// `extent` is 0 when the virtual screen metrics are unavailable.
|
||||
fn to_absolute(v: i32, origin: i32, extent: i32) -> Option<i32> {
|
||||
if extent <= 0 {
|
||||
return None;
|
||||
}
|
||||
let abs = (v as i64 - origin as i64) * 65535 / extent as i64;
|
||||
Some(abs.clamp(0, 65535) as i32)
|
||||
}
|
||||
|
||||
fn keybd_event(mut flags: u32, vk: u16, scan: u16) -> DWORD {
|
||||
let mut scan = scan;
|
||||
unsafe {
|
||||
@@ -126,13 +137,28 @@ impl MouseControllable for Enigo {
|
||||
}
|
||||
|
||||
fn mouse_move_to(&mut self, x: i32, y: i32) {
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let (Some(dx), Some(dy)) = (to_absolute(x, left, width), to_absolute(y, top, height))
|
||||
else {
|
||||
hbb_common::throttled_log!(
|
||||
std::time::Duration::from_secs(60),
|
||||
warn,
|
||||
"mouse_move_to skipped: virtual screen size unavailable"
|
||||
);
|
||||
return;
|
||||
};
|
||||
mouse_event(
|
||||
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
|
||||
0,
|
||||
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535
|
||||
/ unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
|
||||
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535
|
||||
/ unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
|
||||
dx,
|
||||
dy,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
Submodule libs/hbb_common updated: 29cf7cbe4d...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.8). 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,7 +30,275 @@ 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>,
|
||||
/// Cursor plane position (CRTC_X/CRTC_Y), in this reader's scanout pixels.
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
}
|
||||
|
||||
/// 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).
|
||||
@@ -101,6 +370,16 @@ 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,
|
||||
/// The plane rotation read right after the last successful grab, before any copy: libdrmtap
|
||||
/// reads the property when asked, so a read after the copies could describe the next frame.
|
||||
last_plane_rotation: Option<u32>,
|
||||
}
|
||||
|
||||
impl DrmReader {
|
||||
@@ -134,9 +413,11 @@ impl DrmReader {
|
||||
return None;
|
||||
}
|
||||
Some(DrmReader {
|
||||
last_provenance: -1,
|
||||
lib,
|
||||
ctx,
|
||||
buf: Vec::new(),
|
||||
last_plane_rotation: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -160,6 +441,7 @@ impl DrmReader {
|
||||
format!("drmtap_grab_mapped failed: errno {errno}"),
|
||||
));
|
||||
}
|
||||
self.last_plane_rotation = self.read_plane_rotation();
|
||||
if frame.data.is_null() || frame.width == 0 || frame.height == 0 {
|
||||
(self.lib.frame_release)(self.ctx, &mut frame);
|
||||
return Err(io::ErrorKind::WouldBlock.into());
|
||||
@@ -254,6 +536,23 @@ impl DrmReader {
|
||||
.map(|s| s.to_owned())
|
||||
}
|
||||
|
||||
/// The DRM `rotation` bitmask of the plane the last successful grab read from, as it was right
|
||||
/// after that grab. A plane without the property answers rotate-0: it cannot have turned
|
||||
/// anything, so the compositor drew the scanout already turned and the whole output transform
|
||||
/// is still to be undone. `None` only when the library cannot say: it predates the call
|
||||
/// (0.5.8), no plane is bound, or the property set could not be read.
|
||||
pub fn plane_rotation(&self) -> Option<u32> {
|
||||
self.last_plane_rotation
|
||||
}
|
||||
|
||||
fn read_plane_rotation(&mut self) -> Option<u32> {
|
||||
let f = self.lib.plane_rotation?;
|
||||
let mut rotation: u32 = 0;
|
||||
// SAFETY: self.ctx is a live context and `rotation` outlives the call.
|
||||
let rc = unsafe { f(self.ctx, &mut rotation) };
|
||||
plane_rotation_answer(rc, rotation)
|
||||
}
|
||||
|
||||
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
|
||||
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
|
||||
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
|
||||
@@ -285,6 +584,7 @@ impl DrmReader {
|
||||
format!("drmtap_grab_desc failed: errno {errno}"),
|
||||
));
|
||||
}
|
||||
self.last_plane_rotation = self.read_plane_rotation();
|
||||
// `desc.dma_buf_fd` is the canonical fd (what split_capture.c sends); `frame` owns it too and `frame_release` closes the library's copy.
|
||||
let raw_fd = if desc.dma_buf_fd >= 0 {
|
||||
desc.dma_buf_fd
|
||||
@@ -363,7 +663,10 @@ impl DrmReader {
|
||||
height: 1,
|
||||
hotx: 0,
|
||||
hoty: 0,
|
||||
hot_measured: false,
|
||||
colors: vec![0, 0, 0, 0],
|
||||
x: 0,
|
||||
y: 0,
|
||||
})
|
||||
} else if !c.pixels.is_null()
|
||||
&& c.width > 0
|
||||
@@ -376,54 +679,48 @@ 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,
|
||||
x: c.x,
|
||||
y: c.y,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
@@ -475,3 +772,333 @@ 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// DRM_MODE_ROTATE_0: the `rotation` bitmask of a plane that turned nothing.
|
||||
const DRM_MODE_ROTATE_0: u32 = 1 << 0;
|
||||
|
||||
/// What a `drmtap_plane_rotation` return means to the consumer. Success is the mask. `-ENOTSUP`
|
||||
/// (the plane has no `rotation` property) is rotate-0, not "unknown": such a plane cannot have
|
||||
/// turned the scanout, so the frame arrives turned by the whole output transform, which is the
|
||||
/// virtio-gpu and vmwgfx case this exists for. Anything else (`-ENOENT` with no plane bound, a
|
||||
/// failed property read) is `None`, and the consumer keeps its pre-0.5.8 rule.
|
||||
fn plane_rotation_answer(rc: c_int, rotation: u32) -> Option<u32> {
|
||||
if rc == 0 {
|
||||
Some(rotation)
|
||||
} else if rc == -hbb_common::libc::ENOTSUP {
|
||||
Some(DRM_MODE_ROTATE_0)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod plane_rotation_tests {
|
||||
use super::*;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
|
||||
|
||||
#[test]
|
||||
fn a_plane_without_the_property_turned_nothing() {
|
||||
assert_eq!(plane_rotation_answer(0, 0x4), Some(0x4));
|
||||
assert_eq!(plane_rotation_answer(0, 0x1), Some(0x1));
|
||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::ENOTSUP, 0), Some(0x1));
|
||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::ENOENT, 0), None);
|
||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::EINVAL, 0), None);
|
||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::EIO, 7), None);
|
||||
}
|
||||
|
||||
// What the plane answers whenever it is asked. The fake release turns it, the way a compositor
|
||||
// may once the frame is out, so a read taken after the release or outside the grab sees 0x1.
|
||||
static PLANE: AtomicU32 = AtomicU32::new(0x1);
|
||||
static FD: AtomicI32 = AtomicI32::new(-1);
|
||||
static PIXELS: [u8; 16] = [0; 16];
|
||||
|
||||
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, rotation: *mut u32) -> c_int {
|
||||
*rotation = PLANE.load(Ordering::SeqCst);
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {
|
||||
PLANE.store(0x1, Ordering::SeqCst);
|
||||
}
|
||||
unsafe extern "C" fn grab_mapped(_: *mut drmtap_ctx, f: *mut drmtap_frame_info) -> c_int {
|
||||
(*f).data = PIXELS.as_ptr() as *mut _;
|
||||
(*f).width = 2;
|
||||
(*f).height = 2;
|
||||
(*f).stride = 8;
|
||||
(*f).format = DRM_FORMAT_XRGB8888;
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn grab_desc(
|
||||
_: *mut drmtap_ctx,
|
||||
d: *mut drmtap_dmabuf_desc,
|
||||
_: *mut drmtap_frame_info,
|
||||
) -> c_int {
|
||||
(*d).dma_buf_fd = FD.load(Ordering::SeqCst);
|
||||
(*d).width = 2;
|
||||
(*d).height = 2;
|
||||
(*d).num_planes = 1;
|
||||
(*d).pitches[0] = 8;
|
||||
0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_keeps_the_rotation_its_plane_had_when_it_was_grabbed() {
|
||||
let lib: &'static DrmtapLib = Box::leak(Box::new(DrmtapLib::fake(
|
||||
grab_mapped,
|
||||
frame_release,
|
||||
grab_desc,
|
||||
plane_rotation,
|
||||
)));
|
||||
let mut r = DrmReader {
|
||||
lib,
|
||||
ctx: std::ptr::null_mut(),
|
||||
buf: Vec::new(),
|
||||
last_provenance: -1,
|
||||
last_plane_rotation: None,
|
||||
};
|
||||
PLANE.store(0x4, Ordering::SeqCst);
|
||||
r.grab().expect("the fake grab succeeds");
|
||||
assert_eq!(r.plane_rotation(), Some(0x4), "cpu grab");
|
||||
let (fd, _peer) = std::os::unix::net::UnixStream::pair().unwrap();
|
||||
FD.store(fd.as_raw_fd(), Ordering::SeqCst);
|
||||
PLANE.store(0x8, Ordering::SeqCst);
|
||||
r.grab_desc().expect("the fake export succeeds");
|
||||
assert_eq!(r.plane_rotation(), Some(0x8), "dma-buf export");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 =
|
||||
@@ -134,6 +140,12 @@ type FnGrabDesc =
|
||||
type FnOpenRender = unsafe extern "C" fn(*const c_char) -> *mut drmtap_ctx;
|
||||
// libdrmtap >= 0.4.15; returns a ctx-owned string, or NULL if it has none.
|
||||
type FnRenderNode = unsafe extern "C" fn(*mut drmtap_ctx) -> *const c_char;
|
||||
/// `drmtap_plane_rotation`, added in libdrmtap 0.5.8: the DRM `rotation` bitmask the primary
|
||||
/// plane scans out with, read now (0x1 = 0, 0x2 = 90, 0x4 = 180, 0x8 = 270, plus 0x10/0x20 for
|
||||
/// a reflection). 0 with `*rotation` set; `-ENOTSUP` when the plane has no such property, which
|
||||
/// means the compositor can only have rotated in software; `-ENOENT` with no plane bound;
|
||||
/// `-EINVAL` on a null argument.
|
||||
type FnPlaneRotation = unsafe extern "C" fn(*mut drmtap_ctx, *mut u32) -> c_int;
|
||||
type FnConvertDmabuf =
|
||||
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
|
||||
|
||||
@@ -148,13 +160,72 @@ 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,
|
||||
pub render_node: Option<FnRenderNode>,
|
||||
/// Optional: it only exists from libdrmtap 0.5.8. Absent means the library cannot say whether
|
||||
/// the plane rotated the scanout, and the consumer keeps the pre-0.5.8 rule for that case.
|
||||
pub plane_rotation: Option<FnPlaneRotation>,
|
||||
pub version: (c_int, c_int, c_int),
|
||||
}
|
||||
|
||||
/// A library whose capture entry points are the given fakes and whose others do nothing, for the
|
||||
/// tests of the reader.
|
||||
#[cfg(test)]
|
||||
impl DrmtapLib {
|
||||
pub(crate) fn fake(
|
||||
grab_mapped: FnGrabMapped,
|
||||
frame_release: FnFrameRelease,
|
||||
grab_desc: FnGrabDesc,
|
||||
plane_rotation: FnPlaneRotation,
|
||||
) -> Self {
|
||||
unsafe extern "C" fn open(_: *const drmtap_config) -> *mut drmtap_ctx {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
unsafe extern "C" fn close(_: *mut drmtap_ctx) {}
|
||||
unsafe extern "C" fn list_displays(_: *mut drmtap_ctx, _: *mut drmtap_display, _: c_int) -> c_int {
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn get_cursor(_: *mut drmtap_ctx, _: *mut drmtap_cursor_info) -> c_int {
|
||||
-1
|
||||
}
|
||||
unsafe extern "C" fn cursor_release(_: *mut drmtap_ctx, _: *mut drmtap_cursor_info) {}
|
||||
unsafe extern "C" fn open_render(_: *const c_char) -> *mut drmtap_ctx {
|
||||
std::ptr::null_mut()
|
||||
}
|
||||
unsafe extern "C" fn convert_dmabuf(
|
||||
_: *mut drmtap_ctx,
|
||||
_: *const drmtap_dmabuf_desc,
|
||||
_: *mut drmtap_frame_info,
|
||||
) -> c_int {
|
||||
-1
|
||||
}
|
||||
DrmtapLib {
|
||||
_lib: hbb_common::libloading::os::unix::Library::this().into(),
|
||||
open,
|
||||
close,
|
||||
list_displays,
|
||||
list_devices: None,
|
||||
grab_mapped,
|
||||
frame_release,
|
||||
get_cursor,
|
||||
cursor_release,
|
||||
cursor_hotspot_valid: None,
|
||||
grab_desc,
|
||||
open_render,
|
||||
convert_dmabuf,
|
||||
render_node: None,
|
||||
plane_rotation: Some(plane_rotation),
|
||||
version: (0, 5, 8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the resolved fn pointers are plain C entry points with no interior mutability;
|
||||
// libdrmtap contexts are used single-threaded by the caller. The Library handle is never moved out.
|
||||
unsafe impl Send for DrmtapLib {}
|
||||
@@ -278,6 +349,10 @@ 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);
|
||||
let plane_rotation: Option<FnPlaneRotation> =
|
||||
lib.get(b"drmtap_plane_rotation").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 +384,26 @@ 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)."
|
||||
);
|
||||
}
|
||||
if (minor, patch) >= (5, 8) && plane_rotation.is_none() {
|
||||
log::warn!(
|
||||
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
|
||||
drmtap_plane_rotation: it is a stale or pre-release build. Check what the \
|
||||
soname symlink points at. A 180-degree output rotated by the compositor in \
|
||||
software will be captured upside down."
|
||||
);
|
||||
}
|
||||
Some(DrmtapLib {
|
||||
_lib: lib,
|
||||
open,
|
||||
@@ -319,10 +414,12 @@ impl DrmtapLib {
|
||||
frame_release,
|
||||
get_cursor,
|
||||
cursor_release,
|
||||
cursor_hotspot_valid,
|
||||
grab_desc,
|
||||
open_render,
|
||||
convert_dmabuf,
|
||||
render_node,
|
||||
plane_rotation,
|
||||
version: (major, minor, patch),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
}
|
||||
+170
-15
@@ -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::*,
|
||||
@@ -41,6 +43,13 @@ impl<T> Drop for ComPtr<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum FrameState {
|
||||
Idle,
|
||||
Acquired,
|
||||
Mapped,
|
||||
}
|
||||
|
||||
pub struct Capturer {
|
||||
device: ComPtr<ID3D11Device>,
|
||||
display: Display,
|
||||
@@ -58,6 +67,8 @@ pub struct Capturer {
|
||||
output_texture: bool,
|
||||
adapter_desc1: DXGI_ADAPTER_DESC1,
|
||||
rotate: Rotate,
|
||||
frame_state: FrameState,
|
||||
hdr: Option<hdr::HdrToSdr>,
|
||||
}
|
||||
|
||||
impl Capturer {
|
||||
@@ -105,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");
|
||||
@@ -161,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,
|
||||
@@ -174,9 +186,105 @@ impl Capturer {
|
||||
output_texture: false,
|
||||
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,
|
||||
@@ -330,11 +438,15 @@ 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();
|
||||
|
||||
wrap_hresult((*self.duplication.0).AcquireNextFrame(timeout, &mut info, &mut frame))?;
|
||||
self.frame_state = FrameState::Acquired;
|
||||
let frame = ComPtr(frame);
|
||||
|
||||
if *info.LastPresentTime.QuadPart() == 0 {
|
||||
@@ -345,9 +457,11 @@ impl Capturer {
|
||||
let mut rect = mem::MaybeUninit::uninit().assume_init();
|
||||
if self.fastlane {
|
||||
wrap_hresult((*self.duplication.0).MapDesktopSurface(&mut rect))?;
|
||||
self.frame_state = FrameState::Mapped;
|
||||
} else {
|
||||
self.surface = ComPtr(self.ohgodwhat(frame.0)?);
|
||||
wrap_hresult((*self.surface.0).Map(&mut rect, DXGI_MAP_READ))?;
|
||||
self.frame_state = FrameState::Mapped;
|
||||
}
|
||||
Ok((rect.pBits, rect.Pitch))
|
||||
}
|
||||
@@ -365,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;
|
||||
@@ -385,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)
|
||||
}
|
||||
@@ -424,7 +544,7 @@ impl Capturer {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.unmap();
|
||||
self.release_frame()?;
|
||||
let r = self.load_frame(timeout)?;
|
||||
let rotate = match self.display.rotation() {
|
||||
DXGI_MODE_ROTATION_IDENTITY | DXGI_MODE_ROTATION_UNSPECIFIED => kRotate0,
|
||||
@@ -472,12 +592,13 @@ impl Capturer {
|
||||
if self.duplication.0.is_null() {
|
||||
return Err(std::io::ErrorKind::AddrNotAvailable.into());
|
||||
}
|
||||
(*self.duplication.0).ReleaseFrame();
|
||||
self.release_frame()?;
|
||||
let mut frame = ptr::null_mut();
|
||||
#[allow(invalid_value)]
|
||||
let mut info = mem::MaybeUninit::uninit().assume_init();
|
||||
|
||||
wrap_hresult((*self.duplication.0).AcquireNextFrame(timeout, &mut info, &mut frame))?;
|
||||
self.frame_state = FrameState::Acquired;
|
||||
let frame = ComPtr(frame);
|
||||
|
||||
if info.AccumulatedFrames == 0 || *info.LastPresentTime.QuadPart() == 0 {
|
||||
@@ -492,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,
|
||||
@@ -574,16 +703,42 @@ impl Capturer {
|
||||
}
|
||||
}
|
||||
|
||||
fn unmap(&self) {
|
||||
fn release_frame(&mut self) -> io::Result<()> {
|
||||
if self.duplication.is_null() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut first_error = None;
|
||||
// Unmap before ReleaseFrame invalidates the desktop surface; use the same
|
||||
// order for staging surfaces. Cleanup advances Mapped -> Acquired -> Idle,
|
||||
// while Idle is a no-op. Advance state even on errors to avoid retrying
|
||||
// cleanup, but still attempt ReleaseFrame if unmapping fails.
|
||||
unsafe {
|
||||
(*self.duplication.0).ReleaseFrame();
|
||||
if self.fastlane {
|
||||
(*self.duplication.0).UnMapDesktopSurface();
|
||||
} else {
|
||||
if !self.surface.is_null() {
|
||||
(*self.surface.0).Unmap();
|
||||
if self.frame_state == FrameState::Mapped {
|
||||
let result = if self.fastlane {
|
||||
wrap_hresult((*self.duplication.0).UnMapDesktopSurface())
|
||||
} else if !self.surface.is_null() {
|
||||
wrap_hresult((*self.surface.0).Unmap())
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
self.frame_state = FrameState::Acquired;
|
||||
if let Err(err) = result {
|
||||
first_error = Some(err);
|
||||
}
|
||||
}
|
||||
if self.frame_state == FrameState::Acquired {
|
||||
let result = wrap_hresult((*self.duplication.0).ReleaseFrame());
|
||||
self.frame_state = FrameState::Idle;
|
||||
if first_error.is_none() {
|
||||
if let Err(err) = result {
|
||||
first_error = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match first_error {
|
||||
Some(err) => Err(err),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,8 +754,8 @@ impl Capturer {
|
||||
|
||||
impl Drop for Capturer {
|
||||
fn drop(&mut self) {
|
||||
if !self.duplication.is_null() {
|
||||
self.unmap();
|
||||
if let Err(err) = self.release_frame() {
|
||||
eprintln!("DXGI frame cleanup failed: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,25 +248,6 @@ pub fn wayland_failure_stamped() -> bool {
|
||||
LAST_FAILED_LOOKUP.lock().unwrap().is_some()
|
||||
}
|
||||
|
||||
#[cfg(feature = "drm")]
|
||||
pub enum CachedDisplays {
|
||||
Busy,
|
||||
Ready(Option<Arc<Displays>>),
|
||||
}
|
||||
|
||||
/// Cursor polls must neither wait for discovery nor mistake contention for missing metadata.
|
||||
#[cfg(feature = "drm")]
|
||||
pub fn get_cached_displays() -> CachedDisplays {
|
||||
match DISPLAYS.try_lock() {
|
||||
Ok(cache) => CachedDisplays::Ready(cache.clone()),
|
||||
Err(std::sync::TryLockError::WouldBlock) => CachedDisplays::Busy,
|
||||
Err(err) => {
|
||||
warn!("Failed to read cached Wayland displays: {}", err);
|
||||
CachedDisplays::Ready(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_displays() -> Arc<Displays> {
|
||||
let mut lock = DISPLAYS.lock().unwrap();
|
||||
match lock.as_ref() {
|
||||
@@ -356,17 +337,6 @@ pub fn get_layout_for_uinput_live() -> Option<((i32, i32, i32, i32), Vec<Display
|
||||
}
|
||||
match enumerate_displays() {
|
||||
Ok(displays) => {
|
||||
#[cfg(feature = "drm")]
|
||||
{
|
||||
// Output density can change without moving any desktop-coordinate rectangle.
|
||||
let mut cache = DISPLAYS.lock().unwrap();
|
||||
if let Some(updated) = cache
|
||||
.as_deref()
|
||||
.and_then(|cached| updated_cursor_scales(cached, &displays))
|
||||
{
|
||||
*cache = Some(Arc::new(updated));
|
||||
}
|
||||
}
|
||||
desktop_rect_of(&displays).map(|rect| (rect, logical_rects_of(&displays)))
|
||||
}
|
||||
Err(_err) => {
|
||||
@@ -377,30 +347,6 @@ pub fn get_layout_for_uinput_live() -> Option<((i32, i32, i32, i32), Vec<Display
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "drm")]
|
||||
fn updated_cursor_scales(cached: &Displays, live: &[WaylandDisplayInfo]) -> Option<Displays> {
|
||||
let mut displays = cached.displays.clone();
|
||||
let mut changed = false;
|
||||
for output in &mut displays {
|
||||
// Geometry changes retain the existing layout invalidation/rebuild path.
|
||||
let Some(current) = live.iter().find(|d| {
|
||||
d.name == output.name
|
||||
&& (d.x, d.y) == (output.x, output.y)
|
||||
&& (d.width, d.height) == (output.width, output.height)
|
||||
&& d.transform == output.transform
|
||||
&& d.logical_size == output.logical_size
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
changed |= output.scale_factor != current.scale_factor;
|
||||
output.scale_factor = current.scale_factor;
|
||||
}
|
||||
changed.then_some(Displays {
|
||||
primary: cached.primary,
|
||||
displays,
|
||||
})
|
||||
}
|
||||
|
||||
fn desktop_rect_of(displays: &[WaylandDisplayInfo]) -> Option<(i32, i32, i32, i32)> {
|
||||
if displays.is_empty() {
|
||||
return None;
|
||||
@@ -570,27 +516,6 @@ fn map_axis(v: i32, base_origin: i32, base_extent: i32, live_origin: i32, live_e
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(feature = "drm")]
|
||||
#[test]
|
||||
fn cursor_metadata_does_not_wait_for_display_discovery() {
|
||||
let cache = DISPLAYS.lock().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
tx.send(matches!(get_cached_displays(), CachedDisplays::Busy))
|
||||
.unwrap();
|
||||
});
|
||||
// Discovery owns this lock until it completes or times out.
|
||||
let result = rx.recv_timeout(Duration::from_secs(1));
|
||||
drop(cache);
|
||||
reader.join().unwrap();
|
||||
assert!(result.unwrap());
|
||||
|
||||
clear_wayland_displays_cache();
|
||||
for _ in 0..100 {
|
||||
assert!(matches!(get_cached_displays(), CachedDisplays::Ready(None)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lookup_backoff_boundaries() {
|
||||
// Future `now`s sidestep Instant subtraction, which can panic near boot.
|
||||
@@ -639,7 +564,6 @@ mod tests {
|
||||
width,
|
||||
height,
|
||||
logical_size,
|
||||
scale_factor: 1,
|
||||
refresh_rate: 60,
|
||||
transform: 0,
|
||||
}
|
||||
@@ -650,33 +574,6 @@ mod tests {
|
||||
assert_eq!(desktop_rect_of(&[]), None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "drm")]
|
||||
#[test]
|
||||
fn output_scale_refresh_preserves_layout_and_existing_snapshots() {
|
||||
let mut output = display(0, 0, 2560, 1600, Some((2560, 1600)));
|
||||
output.name = "eDP-1".into();
|
||||
output.scale_factor = 3;
|
||||
let cached = Displays {
|
||||
primary: 0,
|
||||
displays: vec![output.clone()],
|
||||
};
|
||||
output.scale_factor = 2;
|
||||
let updated = updated_cursor_scales(&cached, &[output.clone()]).unwrap();
|
||||
assert_eq!(updated.displays[0].scale_factor, 2);
|
||||
assert_eq!(cached.displays[0].scale_factor, 3);
|
||||
assert_eq!(updated.primary, cached.primary);
|
||||
assert_eq!(
|
||||
logical_rects_of(&updated.displays),
|
||||
logical_rects_of(&cached.displays)
|
||||
);
|
||||
assert!(updated_cursor_scales(&updated, &[output.clone()]).is_none());
|
||||
output.name = "HDMI-1".into();
|
||||
assert!(updated_cursor_scales(&cached, &[output.clone()]).is_none());
|
||||
output.name = "eDP-1".into();
|
||||
output.logical_size = Some((1280, 800));
|
||||
assert!(updated_cursor_scales(&cached, &[output]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_desktop_rect_single_display_uses_physical_size() {
|
||||
let displays = [display(0, 0, 2880, 1800, Some((1859, 1162)))];
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ if [ "$1" = configure ]; then
|
||||
if [ "systemd" == "$INITSYS" ]; then
|
||||
|
||||
if [ -e /etc/systemd/system/rustdesk.service ]; then
|
||||
rm /etc/systemd/system/rustdesk.service /usr/lib/systemd/system/rustdesk.service /usr/lib/systemd/user/rustdesk.service >/dev/null 2>&1
|
||||
rm -f /etc/systemd/system/rustdesk.service /usr/lib/systemd/system/rustdesk.service /usr/lib/systemd/user/rustdesk.service >/dev/null 2>&1
|
||||
fi
|
||||
mkdir -p /usr/lib/systemd/system/
|
||||
cp /usr/share/rustdesk/files/systemd/rustdesk.service /usr/lib/systemd/system/rustdesk.service
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# FFmpeg 7.1.1 includes the HEVC WPP slice-thread deadlock fix:
|
||||
# https://github.com/FFmpeg/FFmpeg/commit/79c47dfd25f101b6842bbec8c6ffef8d5077c3ae
|
||||
vcpkg_from_github(
|
||||
OUT_SOURCE_PATH SOURCE_PATH
|
||||
REPO ffmpeg/ffmpeg
|
||||
REF "n${VERSION}"
|
||||
SHA512 3b273769ef1a1b63aed0691eef317a760f8c83b1d0e1c232b67bbee26db60b4864aafbc88df0e86d6bebf07185bbd057f33e2d5258fde6d97763b9994cd48b6f
|
||||
SHA512 6b9a5ee501be41d6abc7579a106263b31f787321cbc45dedee97abf992bf8236cdb2394571dd256a74154f4a20018d429ae7e7f0409611ddc4d6f529d924d175
|
||||
HEAD_REF master
|
||||
PATCHES
|
||||
0001-create-lib-libraries.patch
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"name": "ffmpeg",
|
||||
"version": "7.1",
|
||||
"port-version": 1,
|
||||
"version": "7.1.1",
|
||||
"description": [
|
||||
"a library to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created.",
|
||||
"FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created. It supports the most obscure ancient formats up to the cutting edge. No matter if they were designed by some standards committee, the community or a corporation. It is also highly portable: FFmpeg compiles, runs, and passes our testing infrastructure FATE across Linux, Mac OS X, Microsoft Windows, the BSDs, Solaris, etc. under a wide variety of build environments, machine architectures, and configurations."
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
use hbb_common::thiserror;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod allocation_tests;
|
||||
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
mod sinc;
|
||||
|
||||
const INTERPOLATION_MARGIN_FRAMES: usize = 2;
|
||||
const PENDING_PACKET_CAPACITY: usize = 2;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct AudioResamplerConfig {
|
||||
pub input_rate: u32,
|
||||
pub output_rate: u32,
|
||||
pub channels: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub(crate) enum AudioResamplerError {
|
||||
#[error(
|
||||
"invalid audio resampler configuration: input_rate={}, output_rate={}, channels={}",
|
||||
.0.input_rate, .0.output_rate, .0.channels
|
||||
)]
|
||||
InvalidConfig(AudioResamplerConfig),
|
||||
#[error("invalid resampler output frame size: {output_frames}")]
|
||||
InvalidOutputFrameSize { output_frames: usize },
|
||||
#[error("audio resampler input length {samples} is not divisible by channel count {channels}")]
|
||||
IncompleteFrame { samples: usize, channels: usize },
|
||||
#[error("audio resampler output capacity overflow")]
|
||||
CapacityOverflow,
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
#[error("audio resampler backend failed: {0}")]
|
||||
Backend(String),
|
||||
}
|
||||
|
||||
pub(crate) struct FixedFrameAudioResampler {
|
||||
resampler: AudioResampler,
|
||||
output_samples: usize,
|
||||
pending_samples: Vec<f32>,
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
// SAFETY: libsamplerate's src_new state owns heap data and has no thread affinity.
|
||||
// This wrapper never exposes or shares that state; processing requires &mut self.
|
||||
unsafe impl Send for FixedFrameAudioResampler {}
|
||||
|
||||
impl FixedFrameAudioResampler {
|
||||
pub(crate) fn new(
|
||||
config: AudioResamplerConfig,
|
||||
output_frames: usize,
|
||||
) -> Result<Self, AudioResamplerError> {
|
||||
if output_frames == 0 {
|
||||
return Err(AudioResamplerError::InvalidOutputFrameSize { output_frames });
|
||||
}
|
||||
let channels = validate_config(config)?;
|
||||
let output_samples = output_frames
|
||||
.checked_mul(channels)
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?;
|
||||
let input_frames = output_frames
|
||||
.checked_mul(config.input_rate as usize)
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?
|
||||
.div_ceil(config.output_rate as usize);
|
||||
let capacity = output_samples
|
||||
.checked_mul(PENDING_PACKET_CAPACITY)
|
||||
.and_then(|samples| samples.checked_add(channels * INTERPOLATION_MARGIN_FRAMES))
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?;
|
||||
let mut resampler = AudioResampler::new(config)?;
|
||||
resampler.reserve_input(input_frames)?;
|
||||
Ok(Self {
|
||||
resampler,
|
||||
output_samples,
|
||||
pending_samples: Vec::with_capacity(capacity),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn process_with(
|
||||
&mut self,
|
||||
input: &[f32],
|
||||
mut on_packet: impl FnMut(&[f32]),
|
||||
) -> Result<(), AudioResamplerError> {
|
||||
self.resampler
|
||||
.process_into(input, &mut self.pending_samples)?;
|
||||
let complete_samples =
|
||||
self.pending_samples.len() / self.output_samples * self.output_samples;
|
||||
for packet in self.pending_samples[..complete_samples].chunks_exact(self.output_samples) {
|
||||
on_packet(packet);
|
||||
}
|
||||
self.pending_samples.drain(..complete_samples);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn process(&mut self, input: &[f32]) -> Result<Vec<Vec<f32>>, AudioResamplerError> {
|
||||
let mut packets = Vec::new();
|
||||
self.process_with(input, |packet| packets.push(packet.to_owned()))?;
|
||||
Ok(packets)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AudioResampler {
|
||||
#[cfg(not(all(feature = "use_samplerate", not(feature = "use_dasp"))))]
|
||||
backend: StreamingLinearAudioResampler,
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
backend: sinc::SincAudioResampler,
|
||||
}
|
||||
|
||||
impl AudioResampler {
|
||||
pub(crate) fn new(config: AudioResamplerConfig) -> Result<Self, AudioResamplerError> {
|
||||
Ok(Self {
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
backend: sinc::SincAudioResampler::new(config)?,
|
||||
#[cfg(not(all(feature = "use_samplerate", not(feature = "use_dasp"))))]
|
||||
backend: StreamingLinearAudioResampler::new(config)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn process(&mut self, input: &[f32]) -> Result<Vec<f32>, AudioResamplerError> {
|
||||
let mut output = Vec::new();
|
||||
self.process_into(input, &mut output)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
// Append samples so capture can retain an incomplete output packet in the same buffer.
|
||||
fn process_into(
|
||||
&mut self,
|
||||
input: &[f32],
|
||||
output: &mut Vec<f32>,
|
||||
) -> Result<(), AudioResamplerError> {
|
||||
self.backend.process_into(input, output)
|
||||
}
|
||||
|
||||
fn reserve_input(&mut self, _frames: usize) -> Result<(), AudioResamplerError> {
|
||||
#[cfg(not(all(feature = "use_samplerate", not(feature = "use_dasp"))))]
|
||||
{
|
||||
let capacity = _frames
|
||||
.checked_add(INTERPOLATION_MARGIN_FRAMES)
|
||||
.and_then(|frames| frames.checked_mul(self.backend.channels))
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?;
|
||||
self.backend.buffered_samples.reserve(capacity);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(feature = "use_samplerate", not(feature = "use_dasp"))))]
|
||||
struct StreamingLinearAudioResampler {
|
||||
config: AudioResamplerConfig,
|
||||
channels: usize,
|
||||
buffered_samples: Vec<f32>,
|
||||
next_position: u64,
|
||||
}
|
||||
|
||||
#[cfg(not(all(feature = "use_samplerate", not(feature = "use_dasp"))))]
|
||||
impl StreamingLinearAudioResampler {
|
||||
fn new(config: AudioResamplerConfig) -> Result<Self, AudioResamplerError> {
|
||||
Ok(Self {
|
||||
config,
|
||||
channels: validate_config(config)?,
|
||||
buffered_samples: Vec::new(),
|
||||
next_position: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn process_into(
|
||||
&mut self,
|
||||
input: &[f32],
|
||||
output: &mut Vec<f32>,
|
||||
) -> Result<(), AudioResamplerError> {
|
||||
validate_input(input, self.channels)?;
|
||||
let capacity = self.output_capacity(input.len())?;
|
||||
output.reserve(capacity);
|
||||
self.buffered_samples.extend_from_slice(input);
|
||||
while self.write_next_frame(output) {
|
||||
self.next_position += self.config.input_rate as u64;
|
||||
}
|
||||
self.discard_consumed_frames();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn output_capacity(&self, input_samples: usize) -> Result<usize, AudioResamplerError> {
|
||||
let input_frames = input_samples / self.channels;
|
||||
let scaled_frames = input_frames
|
||||
.checked_mul(self.config.output_rate as usize)
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?
|
||||
/ self.config.input_rate as usize;
|
||||
scaled_frames
|
||||
.checked_add(INTERPOLATION_MARGIN_FRAMES)
|
||||
.and_then(|frames| frames.checked_mul(self.channels))
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)
|
||||
}
|
||||
|
||||
fn write_next_frame(&self, output: &mut Vec<f32>) -> bool {
|
||||
let output_rate = self.config.output_rate as u64;
|
||||
let frame_count = self.buffered_samples.len() / self.channels;
|
||||
let frame = (self.next_position / output_rate) as usize;
|
||||
let fraction = self.next_position % output_rate;
|
||||
if frame >= frame_count || (fraction != 0 && frame + 1 >= frame_count) {
|
||||
return false;
|
||||
}
|
||||
let weight = fraction as f32 / output_rate as f32;
|
||||
for channel in 0..self.channels {
|
||||
let current = self.buffered_samples[frame * self.channels + channel];
|
||||
let next_frame = frame + usize::from(fraction != 0);
|
||||
let next = self.buffered_samples[next_frame * self.channels + channel];
|
||||
output.push(current + (next - current) * weight);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn discard_consumed_frames(&mut self) {
|
||||
let output_rate = self.config.output_rate as u64;
|
||||
let available_frames = self.buffered_samples.len() / self.channels;
|
||||
let consumed_frames = ((self.next_position / output_rate) as usize).min(available_frames);
|
||||
self.buffered_samples
|
||||
.drain(0..consumed_frames * self.channels);
|
||||
self.next_position -= consumed_frames as u64 * output_rate;
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_config(config: AudioResamplerConfig) -> Result<usize, AudioResamplerError> {
|
||||
if config.input_rate == 0 || config.output_rate == 0 || config.channels == 0 {
|
||||
return Err(AudioResamplerError::InvalidConfig(config));
|
||||
}
|
||||
Ok(config.channels as usize)
|
||||
}
|
||||
|
||||
fn validate_input(input: &[f32], channels: usize) -> Result<(), AudioResamplerError> {
|
||||
if input.len() % channels != 0 {
|
||||
return Err(AudioResamplerError::IncompleteFrame {
|
||||
samples: input.len(),
|
||||
channels,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(all(feature = "use_samplerate", not(feature = "use_dasp")))))]
|
||||
mod tests;
|
||||
|
||||
#[cfg(all(test, feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
mod samplerate_tests;
|
||||
@@ -0,0 +1,142 @@
|
||||
use super::{AudioResamplerConfig, FixedFrameAudioResampler};
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
|
||||
struct CountingAllocator;
|
||||
|
||||
thread_local! {
|
||||
static ALLOCATIONS: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
}
|
||||
|
||||
fn record_allocation() {
|
||||
let _ = ALLOCATIONS.try_with(|count| {
|
||||
if let Some(value) = count.get() {
|
||||
count.set(Some(value + 1));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for CountingAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
record_allocation();
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
|
||||
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
||||
record_allocation();
|
||||
unsafe { System.alloc_zeroed(layout) }
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
record_allocation();
|
||||
unsafe { System.realloc(ptr, layout, size) }
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
unsafe { System.dealloc(ptr, layout) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CountingAllocator = CountingAllocator;
|
||||
|
||||
pub(crate) fn assert_no_allocations(process: impl FnOnce()) {
|
||||
struct ResetCounter;
|
||||
impl Drop for ResetCounter {
|
||||
fn drop(&mut self) {
|
||||
ALLOCATIONS.with(|count| count.set(None));
|
||||
}
|
||||
}
|
||||
|
||||
ALLOCATIONS.with(|count| assert!(count.replace(Some(0)).is_none()));
|
||||
let reset = ResetCounter;
|
||||
process();
|
||||
let allocations = ALLOCATIONS.with(|count| count.get().unwrap());
|
||||
drop(reset);
|
||||
assert_eq!(
|
||||
allocations, 0,
|
||||
"PCM processing allocated on the capture thread"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_resampling_reuses_buffers() {
|
||||
const PACKETS_PER_SECOND: usize = 100;
|
||||
const PACKET_COUNT: usize = 100;
|
||||
const MAX_STARTUP_DELAY_PACKETS: usize = 1;
|
||||
const SIGNAL_LEVEL: f32 = 0.25;
|
||||
const RATE_PAIRS: [(u32, u32); 6] = [
|
||||
(32_000, 24_000),
|
||||
(44_100, 24_000),
|
||||
(44_100, 48_000),
|
||||
(48_000, 24_000),
|
||||
(96_000, 48_000),
|
||||
(192_000, 48_000),
|
||||
];
|
||||
|
||||
for (input_rate, output_rate) in RATE_PAIRS {
|
||||
for channels in [1, 2, 4, 6, 8] {
|
||||
let config = AudioResamplerConfig {
|
||||
input_rate,
|
||||
output_rate,
|
||||
channels,
|
||||
};
|
||||
let input =
|
||||
vec![SIGNAL_LEVEL; input_rate as usize / PACKETS_PER_SECOND * channels as usize];
|
||||
let frames = output_rate as usize / PACKETS_PER_SECOND;
|
||||
let mut resampler = FixedFrameAudioResampler::new(config, frames).unwrap();
|
||||
let mut packets = 0;
|
||||
let mut energy = 0.0;
|
||||
assert_no_allocations(|| {
|
||||
for _ in 0..PACKET_COUNT {
|
||||
resampler
|
||||
.process_with(&input, |packet| {
|
||||
assert_eq!(packet.len(), frames * channels as usize);
|
||||
energy += packet.iter().map(|sample| sample * sample).sum::<f32>();
|
||||
packets += 1;
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
assert!((PACKET_COUNT - MAX_STARTUP_DELAY_PACKETS..=PACKET_COUNT).contains(&packets));
|
||||
assert!(energy > SIGNAL_LEVEL);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
#[test]
|
||||
fn sinc_output_matches_the_existing_backend() {
|
||||
use super::AudioResampler;
|
||||
|
||||
const INPUT_FRAMES: usize = 2_048;
|
||||
const CHUNK_FRAMES: usize = 73;
|
||||
const SIGNAL_STEP: f32 = 0.07;
|
||||
for (input_rate, output_rate) in [(44_100, 24_000), (44_100, 48_000), (96_000, 48_000)] {
|
||||
for channels in [1, 2, 4, 6, 8] {
|
||||
let config = AudioResamplerConfig {
|
||||
input_rate,
|
||||
output_rate,
|
||||
channels,
|
||||
};
|
||||
let input: Vec<_> = (0..INPUT_FRAMES * channels as usize)
|
||||
.map(|sample| (sample as f32 * SIGNAL_STEP).sin())
|
||||
.collect();
|
||||
let mut actual = AudioResampler::new(config).unwrap();
|
||||
let expected = samplerate::Samplerate::new(
|
||||
samplerate::ConverterType::SincBestQuality,
|
||||
input_rate,
|
||||
output_rate,
|
||||
channels as usize,
|
||||
)
|
||||
.unwrap();
|
||||
for chunk in input.chunks(CHUNK_FRAMES * channels as usize) {
|
||||
assert_eq!(
|
||||
actual.process(chunk).unwrap(),
|
||||
expected.process(chunk).unwrap()
|
||||
);
|
||||
assert_eq!(actual.process(&[]).unwrap(), expected.process(&[]).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
use super::{AudioResampler, AudioResamplerConfig, AudioResamplerError, FixedFrameAudioResampler};
|
||||
|
||||
const INPUT_RATE: u32 = 44_100;
|
||||
const OUTPUT_RATE: u32 = 48_000;
|
||||
const CHANNELS: u16 = 2;
|
||||
const INPUT_PACKET_FRAMES: usize = INPUT_RATE as usize / PACKETS_PER_SECOND;
|
||||
const OUTPUT_PACKET_FRAMES: usize = OUTPUT_RATE as usize / PACKETS_PER_SECOND;
|
||||
const PACKET_COUNT: usize = 20;
|
||||
const PACKETS_PER_SECOND: usize = 100;
|
||||
const MIN_CONTINUITY_PACKETS: usize = 2;
|
||||
const TONE_FREQUENCY_HZ: f32 = 997.0;
|
||||
const TONE_AMPLITUDE: f32 = 0.5;
|
||||
const MAX_BOUNDARY_RESIDUAL: f32 = 0.02;
|
||||
const INCOMPLETE_SAMPLE_COUNT: usize = 1;
|
||||
const DOWNSAMPLE_RATE: u32 = 24_000;
|
||||
const REJECTED_TONE_HZ: f64 = 18_000.0;
|
||||
const MAX_ALIAS_RMS: f64 = 0.01;
|
||||
const MIN_PASSBAND_RMS: f64 = 0.3;
|
||||
|
||||
fn stereo_tone(frames: usize) -> Vec<f32> {
|
||||
(0..frames)
|
||||
.flat_map(|frame| {
|
||||
let phase =
|
||||
std::f32::consts::TAU * TONE_FREQUENCY_HZ * frame as f32 / INPUT_RATE as f32;
|
||||
let sample = TONE_AMPLITUDE * phase.sin();
|
||||
[sample, sample]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn maximum_boundary_residual(packets: &[Vec<f32>]) -> f32 {
|
||||
packets.windows(2).fold(0.0, |maximum, pair| {
|
||||
let previous = &pair[0];
|
||||
let current = &pair[1];
|
||||
let last = previous.len() - CHANNELS as usize;
|
||||
let penultimate = last - CHANNELS as usize;
|
||||
(0..CHANNELS as usize).fold(maximum, |maximum, channel| {
|
||||
let predicted = previous[last + channel]
|
||||
+ (previous[last + channel] - previous[penultimate + channel]);
|
||||
maximum.max((current[channel] - predicted).abs())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn stereo_config() -> AudioResamplerConfig {
|
||||
AudioResamplerConfig {
|
||||
input_rate: INPUT_RATE,
|
||||
output_rate: OUTPUT_RATE,
|
||||
channels: CHANNELS,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_capture_resampler_preserves_pending_audio() {
|
||||
let input = stereo_tone(INPUT_PACKET_FRAMES * PACKET_COUNT);
|
||||
let packet_samples = INPUT_PACKET_FRAMES * CHANNELS as usize;
|
||||
let mut expected_resampler =
|
||||
FixedFrameAudioResampler::new(stereo_config(), OUTPUT_PACKET_FRAMES).unwrap();
|
||||
let expected: Vec<_> = input
|
||||
.chunks(packet_samples)
|
||||
.flat_map(|packet| expected_resampler.process(packet).unwrap())
|
||||
.collect();
|
||||
let mut moved_resampler =
|
||||
FixedFrameAudioResampler::new(stereo_config(), OUTPUT_PACKET_FRAMES).unwrap();
|
||||
let mut output = moved_resampler.process(&input[..packet_samples]).unwrap();
|
||||
let remaining = std::thread::spawn(move || {
|
||||
input[packet_samples..]
|
||||
.chunks(packet_samples)
|
||||
.flat_map(|packet| moved_resampler.process(packet).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
output.extend(remaining);
|
||||
|
||||
assert!(output.len() >= MIN_CONTINUITY_PACKETS);
|
||||
assert!(output
|
||||
.iter()
|
||||
.all(|packet| packet.len() == OUTPUT_PACKET_FRAMES * CHANNELS as usize));
|
||||
assert!(maximum_boundary_residual(&output) <= MAX_BOUNDARY_RESIDUAL);
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
fn downsampled_rms(input: &[f32]) -> f64 {
|
||||
let config = AudioResamplerConfig {
|
||||
output_rate: DOWNSAMPLE_RATE,
|
||||
..stereo_config()
|
||||
};
|
||||
let output_frames = DOWNSAMPLE_RATE as usize / PACKETS_PER_SECOND;
|
||||
let mut resampler = FixedFrameAudioResampler::new(config, output_frames).unwrap();
|
||||
let output: Vec<f32> = input
|
||||
.chunks(INPUT_PACKET_FRAMES * CHANNELS as usize)
|
||||
.flat_map(|packet| resampler.process(packet).unwrap().into_iter().flatten())
|
||||
.collect();
|
||||
|
||||
assert!(output.len() >= output_frames * CHANNELS as usize * MIN_CONTINUITY_PACKETS);
|
||||
let mean_square = output
|
||||
.iter()
|
||||
.map(|sample| f64::from(*sample).powi(2))
|
||||
.sum::<f64>()
|
||||
/ output.len() as f64;
|
||||
mean_square.sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_downsampling_filters_out_of_band_audio() {
|
||||
let input: Vec<_> = (0..INPUT_PACKET_FRAMES * PACKET_COUNT)
|
||||
.flat_map(|frame| {
|
||||
let phase =
|
||||
std::f64::consts::TAU * REJECTED_TONE_HZ * frame as f64 / f64::from(INPUT_RATE);
|
||||
let sample = (f64::from(TONE_AMPLITUDE) * phase.sin()) as f32;
|
||||
[sample, sample]
|
||||
})
|
||||
.collect();
|
||||
let rms = downsampled_rms(&input);
|
||||
assert!(
|
||||
rms < MAX_ALIAS_RMS,
|
||||
"out-of-band output RMS {rms} exceeded {MAX_ALIAS_RMS}"
|
||||
);
|
||||
|
||||
let input = stereo_tone(INPUT_PACKET_FRAMES * PACKET_COUNT);
|
||||
let rms = downsampled_rms(&input);
|
||||
assert!(
|
||||
rms > MIN_PASSBAND_RMS,
|
||||
"in-band output RMS {rms} fell below {MIN_PASSBAND_RMS}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samplerate_backend_preserves_streaming_continuity() {
|
||||
let input = stereo_tone(INPUT_PACKET_FRAMES * PACKET_COUNT);
|
||||
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
|
||||
let packets: Vec<_> = input
|
||||
.chunks(INPUT_PACKET_FRAMES * CHANNELS as usize)
|
||||
.map(|packet| resampler.process(packet).unwrap())
|
||||
.filter(|packet| !packet.is_empty())
|
||||
.collect();
|
||||
|
||||
assert!(packets.len() >= MIN_CONTINUITY_PACKETS);
|
||||
assert!(packets
|
||||
.iter()
|
||||
.all(|packet| packet.len() % CHANNELS as usize == 0));
|
||||
assert!(maximum_boundary_residual(&packets) <= MAX_BOUNDARY_RESIDUAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samplerate_backend_reports_incomplete_frame_context() {
|
||||
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
resampler.process(&[0.0]).unwrap_err(),
|
||||
AudioResamplerError::IncompleteFrame {
|
||||
samples: INCOMPLETE_SAMPLE_COUNT,
|
||||
channels: CHANNELS as usize,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use super::{AudioResamplerConfig, AudioResamplerError};
|
||||
use libsamplerate_sys as sys;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
const OUTPUT_MARGIN_FRAMES: usize = 1;
|
||||
|
||||
pub(super) struct SincAudioResampler {
|
||||
state: NonNull<sys::SRC_STATE>,
|
||||
config: AudioResamplerConfig,
|
||||
}
|
||||
|
||||
impl SincAudioResampler {
|
||||
pub(super) fn new(config: AudioResamplerConfig) -> Result<Self, AudioResamplerError> {
|
||||
super::validate_config(config)?;
|
||||
let ratio = f64::from(config.output_rate) / f64::from(config.input_rate);
|
||||
if unsafe { sys::src_is_valid_ratio(ratio) } == 0 {
|
||||
return Err(backend_error(
|
||||
config,
|
||||
samplerate::ErrorCode::BadSrcRatio as _,
|
||||
));
|
||||
}
|
||||
let mut error = 0;
|
||||
// SAFETY: src_new allocates independent state; this owner releases it in Drop.
|
||||
let state = unsafe {
|
||||
sys::src_new(
|
||||
sys::SRC_SINC_BEST_QUALITY as _,
|
||||
config.channels.into(),
|
||||
&mut error,
|
||||
)
|
||||
};
|
||||
let state = NonNull::new(state).ok_or_else(|| backend_error(config, error))?;
|
||||
Ok(Self { state, config })
|
||||
}
|
||||
|
||||
pub(super) fn process_into(
|
||||
&mut self,
|
||||
input: &[f32],
|
||||
output: &mut Vec<f32>,
|
||||
) -> Result<(), AudioResamplerError> {
|
||||
super::validate_input(input, self.config.channels as usize)?;
|
||||
let mut consumed = 0;
|
||||
loop {
|
||||
let (used, generated) = self.process_block(&input[consumed..], output)?;
|
||||
consumed += used;
|
||||
if consumed == input.len() {
|
||||
return Ok(());
|
||||
}
|
||||
if used == 0 && generated == 0 {
|
||||
return Err(AudioResamplerError::Backend(
|
||||
"libsamplerate made no progress while input remained".to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_block(
|
||||
&mut self,
|
||||
input: &[f32],
|
||||
output: &mut Vec<f32>,
|
||||
) -> Result<(usize, usize), AudioResamplerError> {
|
||||
let channels = self.config.channels as usize;
|
||||
let input_frames = input.len() / channels;
|
||||
let output_frames = input_frames
|
||||
.checked_mul(self.config.output_rate as usize)
|
||||
.map(|frames| frames / self.config.input_rate as usize)
|
||||
.and_then(|frames| frames.checked_add(OUTPUT_MARGIN_FRAMES))
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?;
|
||||
let start = output.len();
|
||||
let end = output_frames
|
||||
.checked_mul(channels)
|
||||
.and_then(|samples| start.checked_add(samples))
|
||||
.ok_or(AudioResamplerError::CapacityOverflow)?;
|
||||
let mut data = sys::SRC_DATA {
|
||||
data_in: input.as_ptr(),
|
||||
input_frames: input_frames
|
||||
.try_into()
|
||||
.map_err(|_| AudioResamplerError::CapacityOverflow)?,
|
||||
output_frames: output_frames
|
||||
.try_into()
|
||||
.map_err(|_| AudioResamplerError::CapacityOverflow)?,
|
||||
src_ratio: f64::from(self.config.output_rate) / f64::from(self.config.input_rate),
|
||||
..Default::default()
|
||||
};
|
||||
output.resize(end, 0.0);
|
||||
data.data_out = output[start..].as_mut_ptr();
|
||||
// SAFETY: state is exclusively owned; disjoint slices cover the declared frame counts.
|
||||
let error = unsafe { sys::src_process(self.state.as_ptr(), &mut data) };
|
||||
let generated = data.output_frames_gen as usize * channels;
|
||||
output.truncate(start + generated);
|
||||
if error != 0 {
|
||||
return Err(backend_error(self.config, error));
|
||||
}
|
||||
Ok((data.input_frames_used as usize * channels, generated))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SincAudioResampler {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: this owner holds the only handle returned by src_new.
|
||||
unsafe { sys::src_delete(self.state.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
fn backend_error(config: AudioResamplerConfig, code: i32) -> AudioResamplerError {
|
||||
AudioResamplerError::Backend(format!(
|
||||
"input_rate={}, output_rate={}, channels={}: {:?}",
|
||||
config.input_rate,
|
||||
config.output_rate,
|
||||
config.channels,
|
||||
samplerate::Error::from_int(code)
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
use super::{AudioResampler, AudioResamplerConfig, FixedFrameAudioResampler};
|
||||
|
||||
const INPUT_RATE: u32 = 24_000;
|
||||
const OUTPUT_RATE: u32 = 48_000;
|
||||
const CHANNELS: u16 = 2;
|
||||
const CHUNK_FRAMES: usize = 240;
|
||||
const CHUNK_COUNT: usize = 4;
|
||||
const TONE_FREQUENCY_HZ: f32 = 997.0;
|
||||
const TONE_AMPLITUDE: f32 = 0.5;
|
||||
const MAX_BOUNDARY_RESIDUAL: f32 = 0.02;
|
||||
const LOOK_AHEAD_OUTPUT_FRAMES: usize = 1;
|
||||
const UNEVEN_CHUNK_FRAMES: usize = 73;
|
||||
const MONO_CHANNELS: u16 = 1;
|
||||
const UNIT_RATE: u32 = 1;
|
||||
const DOUBLE_RATE: u32 = 2;
|
||||
const FIRST_DOWNSAMPLE_PACKET: [f32; 3] = [0.0, 1.0, 2.0];
|
||||
const SECOND_DOWNSAMPLE_PACKET: [f32; 4] = [3.0, 4.0, 5.0, 6.0];
|
||||
const EXPECTED_DOWNSAMPLED_OUTPUT: [f32; 4] = [0.0, 2.0, 4.0, 6.0];
|
||||
const PACKETS_PER_SECOND: usize = 100;
|
||||
const OUTPUT_PACKET_FRAMES: usize = OUTPUT_RATE as usize / PACKETS_PER_SECOND;
|
||||
const RATE_44_1_KHZ: u32 = 44_100;
|
||||
const FLOAT_TOLERANCE: f32 = 0.000_001;
|
||||
const MIN_CONTINUITY_PACKETS: usize = 2;
|
||||
|
||||
fn stereo_tone_at_rate(frames: usize, sample_rate: u32) -> Vec<f32> {
|
||||
(0..frames)
|
||||
.flat_map(|frame| {
|
||||
let phase =
|
||||
std::f32::consts::TAU * TONE_FREQUENCY_HZ * frame as f32 / sample_rate as f32;
|
||||
let sample = TONE_AMPLITUDE * phase.sin();
|
||||
[sample, sample]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn stereo_tone(frames: usize) -> Vec<f32> {
|
||||
stereo_tone_at_rate(frames, INPUT_RATE)
|
||||
}
|
||||
|
||||
fn maximum_tone_prediction_residual(sample_rate: u32) -> f32 {
|
||||
let half_step = std::f32::consts::PI * TONE_FREQUENCY_HZ / sample_rate as f32;
|
||||
4.0 * TONE_AMPLITUDE * half_step.sin().powi(2)
|
||||
}
|
||||
|
||||
fn maximum_boundary_residual(chunks: &[Vec<f32>]) -> f32 {
|
||||
chunks.windows(2).fold(0.0, |maximum, pair| {
|
||||
let previous = &pair[0];
|
||||
let current = &pair[1];
|
||||
let last = previous.len() - CHANNELS as usize;
|
||||
let penultimate = last - CHANNELS as usize;
|
||||
(0..CHANNELS as usize).fold(maximum, |maximum, channel| {
|
||||
let predicted = previous[last + channel]
|
||||
+ (previous[last + channel] - previous[penultimate + channel]);
|
||||
maximum.max((current[channel] - predicted).abs())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn stereo_config() -> AudioResamplerConfig {
|
||||
AudioResamplerConfig {
|
||||
input_rate: INPUT_RATE,
|
||||
output_rate: OUTPUT_RATE,
|
||||
channels: CHANNELS,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_decoded_packet_continuity_and_output_ratio() {
|
||||
let input = stereo_tone(CHUNK_FRAMES * CHUNK_COUNT);
|
||||
let mut whole_resampler = AudioResampler::new(stereo_config()).unwrap();
|
||||
let whole_output = whole_resampler.process(&input).unwrap();
|
||||
let expected_frames = CHUNK_FRAMES * CHUNK_COUNT * OUTPUT_RATE as usize / INPUT_RATE as usize
|
||||
- LOOK_AHEAD_OUTPUT_FRAMES;
|
||||
|
||||
for chunk_frames in [CHUNK_FRAMES, UNEVEN_CHUNK_FRAMES] {
|
||||
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
|
||||
let output: Vec<_> = input
|
||||
.chunks(chunk_frames * CHANNELS as usize)
|
||||
.map(|chunk| resampler.process(chunk).unwrap())
|
||||
.collect();
|
||||
let residual = maximum_boundary_residual(&output);
|
||||
assert!(
|
||||
residual <= MAX_BOUNDARY_RESIDUAL,
|
||||
"packet boundary residual {residual} exceeded {MAX_BOUNDARY_RESIDUAL}, chunk_frames={chunk_frames}"
|
||||
);
|
||||
let output_frames = output.iter().map(Vec::len).sum::<usize>() / CHANNELS as usize;
|
||||
assert_eq!(output_frames, expected_frames);
|
||||
assert_eq!(output.concat(), whole_output, "chunk_frames={chunk_frames}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_incomplete_interleaved_frames() {
|
||||
let mut resampler = AudioResampler::new(stereo_config()).unwrap();
|
||||
|
||||
assert!(resampler.process(&[TONE_AMPLITUDE]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolates_mono_samples() {
|
||||
let config = AudioResamplerConfig {
|
||||
input_rate: UNIT_RATE,
|
||||
output_rate: DOUBLE_RATE,
|
||||
channels: MONO_CHANNELS,
|
||||
};
|
||||
let mut resampler = AudioResampler::new(config).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
resampler.process(&[0.0, 1.0, 2.0]).unwrap(),
|
||||
[0.0, 0.5, 1.0, 1.5, 2.0]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_zero_rate_configuration() {
|
||||
let config = AudioResamplerConfig {
|
||||
input_rate: 0,
|
||||
output_rate: OUTPUT_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
|
||||
assert!(AudioResampler::new(config).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn downsamples_across_packet_boundaries() {
|
||||
let config = AudioResamplerConfig {
|
||||
input_rate: DOUBLE_RATE,
|
||||
output_rate: UNIT_RATE,
|
||||
channels: MONO_CHANNELS,
|
||||
};
|
||||
let mut resampler = AudioResampler::new(config).unwrap();
|
||||
let mut output = resampler.process(&FIRST_DOWNSAMPLE_PACKET).unwrap();
|
||||
output.extend(resampler.process(&SECOND_DOWNSAMPLE_PACKET).unwrap());
|
||||
|
||||
assert_eq!(output, EXPECTED_DOWNSAMPLED_OUTPUT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_resampler_emits_only_complete_continuous_frames() {
|
||||
let input = stereo_tone(CHUNK_FRAMES * CHUNK_COUNT);
|
||||
let mut resampler =
|
||||
FixedFrameAudioResampler::new(stereo_config(), OUTPUT_PACKET_FRAMES).unwrap();
|
||||
let output: Vec<_> = input
|
||||
.chunks(CHUNK_FRAMES * CHANNELS as usize)
|
||||
.flat_map(|chunk| resampler.process(chunk).unwrap())
|
||||
.collect();
|
||||
|
||||
assert!(output.len() >= MIN_CONTINUITY_PACKETS);
|
||||
assert!(output
|
||||
.iter()
|
||||
.all(|packet| packet.len() == OUTPUT_PACKET_FRAMES * CHANNELS as usize));
|
||||
assert!(maximum_boundary_residual(&output) <= MAX_BOUNDARY_RESIDUAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sender_downsampling_preserves_packet_continuity() {
|
||||
let input_packet_frames = RATE_44_1_KHZ as usize / PACKETS_PER_SECOND;
|
||||
let input = stereo_tone_at_rate(input_packet_frames * CHUNK_COUNT, RATE_44_1_KHZ);
|
||||
let config = AudioResamplerConfig {
|
||||
input_rate: RATE_44_1_KHZ,
|
||||
output_rate: INPUT_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
let mut resampler =
|
||||
FixedFrameAudioResampler::new(config, INPUT_RATE as usize / PACKETS_PER_SECOND).unwrap();
|
||||
let packets: Vec<_> = input
|
||||
.chunks(input_packet_frames * CHANNELS as usize)
|
||||
.flat_map(|packet| resampler.process(packet).unwrap())
|
||||
.collect();
|
||||
let residual = maximum_boundary_residual(&packets);
|
||||
|
||||
assert_eq!(packets.len(), CHUNK_COUNT);
|
||||
assert!(
|
||||
residual <= maximum_tone_prediction_residual(INPUT_RATE) + FLOAT_TOLERANCE,
|
||||
"sender packet boundary residual {residual} exceeded the tone curvature"
|
||||
);
|
||||
}
|
||||
+519
-135
@@ -1,9 +1,7 @@
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
use crate::clipboard::clipboard_listener;
|
||||
use crate::clipboard::clipboard_listener::{self, ClipboardEvent};
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
use clipboard_master::CallbackResult;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
use cpal::{
|
||||
traits::{DeviceTrait, HostTrait, StreamTrait},
|
||||
@@ -30,9 +28,10 @@ use uuid::Uuid;
|
||||
use crate::{
|
||||
check_port,
|
||||
common::input::{MOUSE_BUTTON_LEFT, MOUSE_BUTTON_RIGHT, MOUSE_TYPE_DOWN, MOUSE_TYPE_UP},
|
||||
create_symmetric_key_msg, decode_id_pk, decode_id_pk_dtls, get_rs_pk, is_keyboard_mode_supported,
|
||||
create_symmetric_key_msg, decode_id_pk, decode_id_pk_dtls, dtls_fingerprint_bound, get_rs_pk,
|
||||
is_keyboard_mode_supported,
|
||||
kcp_stream::KcpStream,
|
||||
secure_tcp,
|
||||
secure_tcp, secure_tcp_required,
|
||||
ui_interface::{get_builtin_option, resolve_avatar_url, use_texture_render},
|
||||
ui_session_interface::{InvokeUiSession, Session},
|
||||
};
|
||||
@@ -56,7 +55,7 @@ use hbb_common::{
|
||||
rand,
|
||||
rendezvous_proto::*,
|
||||
sha2::{Digest, Sha256},
|
||||
socket_client::{connect_tcp, connect_tcp_local, ipv4_to_ipv6, new_direct_udp_for},
|
||||
socket_client::{connect_tcp, connect_tcp_local, ipv4_to_ipv6, new_direct_udp_for_unverified},
|
||||
sodiumoxide::{base64, crypto::sign},
|
||||
timeout,
|
||||
tokio::{
|
||||
@@ -93,6 +92,13 @@ use crate::ui_session_interface::SessionPermissionConfig;
|
||||
|
||||
pub use super::lang::*;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
mod audio_playback;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod audio_playback_recovery;
|
||||
#[cfg(all(test, not(target_os = "linux")))]
|
||||
#[path = "client/tests/audio_state_tests.rs"]
|
||||
mod audio_state_tests;
|
||||
pub mod file_trait;
|
||||
pub mod helper;
|
||||
pub mod io_loop;
|
||||
@@ -482,7 +488,7 @@ impl Client {
|
||||
// no need to care about multiple rendezvous servers case, since it is acutally not used any more.
|
||||
// Shared state for UDP NAT test result
|
||||
if crate::get_udp_punch_enabled() && !interface.is_force_relay() {
|
||||
if let Ok((socket, addr)) = new_direct_udp_for(&rendezvous_server).await {
|
||||
if let Ok((socket, addr)) = new_direct_udp_for_unverified(&rendezvous_server).await {
|
||||
let udp_port = Arc::new(Mutex::new(0));
|
||||
let up_cloned = udp_port.clone();
|
||||
let socket_cloned = socket.clone();
|
||||
@@ -569,7 +575,7 @@ impl Client {
|
||||
return race_transports_prefer_webrtc(
|
||||
preferred_fut,
|
||||
vec![fallback_fut],
|
||||
Self::WEBRTC_PREFER_WINDOW_MS,
|
||||
Self::relay_fallback_delay_ms(),
|
||||
|result| result.0 .1,
|
||||
)
|
||||
.await;
|
||||
@@ -610,11 +616,27 @@ impl Client {
|
||||
/// ones that traverse NAT.
|
||||
const MAX_PENDING_WEBRTC_ICE: usize = 64;
|
||||
|
||||
/// Prefer-P2P window: how long a WebRTC attempt outranks an already-established relay
|
||||
/// result, and the floor for a punch-path WebRTC attempt whose race timeout is tuned for a
|
||||
/// raw TCP SYN. Long enough for candidate trickle + ICE checks + DTLS on high-latency
|
||||
/// links; short enough that UDP-blocked networks settle on relay without a noticeable wait.
|
||||
const WEBRTC_PREFER_WINDOW_MS: u64 = 2500;
|
||||
/// Default relay fallback delay: how long an already-established relay result is held back
|
||||
/// while a WebRTC attempt is still in flight, and the floor for a punch-path WebRTC attempt
|
||||
/// whose race timeout is tuned for a raw TCP SYN. Long enough for candidate trickle + ICE
|
||||
/// checks + DTLS on high-latency links; short enough that UDP-blocked networks settle on
|
||||
/// relay without a noticeable wait. The same role RFC 8305 calls a connection attempt delay.
|
||||
const RELAY_FALLBACK_DELAY_MS: u64 = 2500;
|
||||
|
||||
/// The delay as the user configured it, falling back to `RELAY_FALLBACK_DELAY_MS`. The
|
||||
/// settings field holds seconds, which is what a user reasons about; everything here is
|
||||
/// milliseconds. Unparseable, zero or negative all mean "unset", so clearing the field
|
||||
/// restores the default instead of collapsing the delay and handing every race to the
|
||||
/// relay.
|
||||
fn relay_fallback_delay_ms() -> u64 {
|
||||
match LocalConfig::get_option(keys::OPTION_RELAY_FALLBACK_DELAY)
|
||||
.trim()
|
||||
.parse::<f64>()
|
||||
{
|
||||
Ok(secs) if secs.is_finite() && secs > 0.0 => (secs * 1000.0).round() as u64,
|
||||
_ => Self::RELAY_FALLBACK_DELAY_MS,
|
||||
}
|
||||
}
|
||||
|
||||
/// UDP-NAT-test wait when the TCP clock is implausible (see TCP_RTT_PLAUSIBLE_MIN). The
|
||||
/// normal bound is `rtt / 2`: the test has been running since before the TCP connect, so on
|
||||
@@ -809,7 +831,7 @@ impl Client {
|
||||
}
|
||||
log::info!("rendezvous server: {}", rendezvous_server);
|
||||
let mut socket = socket?;
|
||||
let my_addr = socket.local_addr();
|
||||
let mut my_addr = socket.local_addr();
|
||||
let mut signed_id_pk = Vec::new();
|
||||
let mut relay_server = "".to_owned();
|
||||
let mut peer_addr = Config::get_any_listen_addr(true);
|
||||
@@ -825,12 +847,44 @@ impl Client {
|
||||
};
|
||||
|
||||
let switch_code = interface.get_switch_code();
|
||||
if !key.is_empty() && (!token.is_empty() || !switch_code.is_empty()) {
|
||||
let legacy_secure = !key.is_empty() && (!token.is_empty() || !switch_code.is_empty());
|
||||
let carries_offer = webrtc_offerer.as_ref().and_then(|g| g.stream()).is_some();
|
||||
// Counted from before the key exchange, so the exchange spends the UDP NAT test's own
|
||||
// wait rather than replacing it: the test runs beside both.
|
||||
let udp_nat_wait_from = Instant::now();
|
||||
let mut exchanged = false;
|
||||
if carries_offer {
|
||||
// An offer puts both sides' ICE candidates, every interface address of both
|
||||
// machines, on this socket, so it goes out only once the server's key exchange has
|
||||
// encrypted it. When the server does not complete one, an hbbs from before the
|
||||
// exchange, the offer is dropped and this becomes a punch without WebRTC, on a fresh
|
||||
// socket since the failed exchange may have consumed a message on this one. Degrade
|
||||
// to no WebRTC, never to WebRTC signalling in the clear.
|
||||
match secure_tcp_required(&mut socket, &key).await {
|
||||
Ok(()) => exchanged = true,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"WebRTC signalling to {} cannot be encrypted, punching without WebRTC: {}",
|
||||
rendezvous_server,
|
||||
err
|
||||
);
|
||||
webrtc_offerer = None;
|
||||
socket = connect_tcp(&*rendezvous_server, CONNECT_TIMEOUT).await?;
|
||||
my_addr = socket.local_addr();
|
||||
}
|
||||
}
|
||||
}
|
||||
if !exchanged && legacy_secure {
|
||||
secure_tcp(&mut socket, &key)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to secure tcp: {}", e))?;
|
||||
} else if let Some(udp) = udp.1.as_ref() {
|
||||
let tm = Instant::now();
|
||||
}
|
||||
// A token or switch code has always taken this socket straight to the punch without
|
||||
// waiting for the UDP NAT test. The WebRTC exchange does not replace that wait, it only
|
||||
// spends part of the same budget, so what is left of it is waited out here and a result
|
||||
// that has already arrived is taken at once.
|
||||
if let Some(udp) = udp.1.as_ref().filter(|_| !legacy_secure) {
|
||||
let tm = udp_nat_wait_from;
|
||||
// rtt is the TCP connect time. When it is too short to be a real WAN round trip it
|
||||
// says nothing about the UDP path (a TUN VPN or the LAN gateway answered the
|
||||
// handshake, not the server), so fall back to the flat grace; otherwise trust it.
|
||||
@@ -1114,7 +1168,7 @@ impl Client {
|
||||
race_transports_prefer_webrtc(
|
||||
webrtc_fut,
|
||||
connect_futures,
|
||||
Self::WEBRTC_PREFER_WINDOW_MS,
|
||||
Self::relay_fallback_delay_ms(),
|
||||
|result| result.3,
|
||||
)
|
||||
.await
|
||||
@@ -1442,7 +1496,7 @@ impl Client {
|
||||
// so a viable P2P path is not abandoned before it can complete; TCP/UDP keep the
|
||||
// tighter timeout, so a working direct connection still wins immediately, and the
|
||||
// relay fallback only waits the extra time when direct attempts all failed.
|
||||
let webrtc_timeout = connect_timeout.max(Self::WEBRTC_PREFER_WINDOW_MS);
|
||||
let webrtc_timeout = connect_timeout.max(Self::relay_fallback_delay_ms());
|
||||
async move {
|
||||
raced.wait_connected(webrtc_timeout).await?;
|
||||
// Resolve the pair here: a TURN win is relayed, not direct, and must be held
|
||||
@@ -1460,7 +1514,7 @@ impl Client {
|
||||
race_transports_prefer_webrtc(
|
||||
webrtc_fut,
|
||||
direct_futures,
|
||||
Self::WEBRTC_PREFER_WINDOW_MS,
|
||||
Self::relay_fallback_delay_ms(),
|
||||
|r| r.3,
|
||||
)
|
||||
.await
|
||||
@@ -1638,7 +1692,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
|
||||
@@ -1648,20 +1704,37 @@ impl Client {
|
||||
let actual_fp = conn.dtls_fingerprint(false).await.ok_or_else(
|
||||
|| anyhow!("WebRTC DTLS fingerprint unavailable"),
|
||||
)?;
|
||||
if signed_fp.is_empty() || signed_fp != actual_fp {
|
||||
if !dtls_fingerprint_bound(&signed_fp, &actual_fp) {
|
||||
bail!("WebRTC DTLS fingerprint not bound to peer identity (possible MITM)");
|
||||
}
|
||||
}
|
||||
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)");
|
||||
@@ -1867,14 +1940,19 @@ impl Client {
|
||||
break;
|
||||
}
|
||||
match rx_cb_result.recv_timeout(Duration::from_millis(CLIPBOARD_INTERVAL)) {
|
||||
Ok(CallbackResult::Next) => {
|
||||
handler.check_clipboard();
|
||||
Ok(ClipboardEvent::Changed) => {
|
||||
handler.check_clipboard(true);
|
||||
}
|
||||
Ok(CallbackResult::Stop) => {
|
||||
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
|
||||
Ok(ClipboardEvent::InitialSelection) => {
|
||||
// Preserve file startup sync without bypassing text initial-sync settings.
|
||||
handler.check_clipboard(false);
|
||||
}
|
||||
Ok(ClipboardEvent::Stop) => {
|
||||
log::debug!("Clipboard listener stopped");
|
||||
break;
|
||||
}
|
||||
Ok(CallbackResult::StopWithError(err)) => {
|
||||
Ok(ClipboardEvent::StopWithError(err)) => {
|
||||
log::error!("Clipboard listener stopped with error: {}", err);
|
||||
break;
|
||||
}
|
||||
@@ -1976,16 +2054,16 @@ impl ClientClipboardHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_clipboard(&mut self) {
|
||||
fn check_clipboard(&mut self, check_text: bool) {
|
||||
if CLIPBOARD_STATE.lock().unwrap().running {
|
||||
#[cfg(feature = "unix-file-copy-paste")]
|
||||
if let Some(urls) = check_clipboard_files(&mut self.ctx, ClipboardSide::Client, false) {
|
||||
if !urls.is_empty() {
|
||||
#[cfg(target_os = "macos")]
|
||||
if crate::clipboard::is_file_url_set_by_rustdesk(&urls) {
|
||||
return;
|
||||
}
|
||||
if self.is_file_required() {
|
||||
if self.is_file_required() {
|
||||
if let Some(urls) = check_clipboard_files(&mut self.ctx, ClipboardSide::Client, false) {
|
||||
if !urls.is_empty() {
|
||||
#[cfg(target_os = "macos")]
|
||||
if crate::clipboard::is_file_url_set_by_rustdesk(&urls) {
|
||||
return;
|
||||
}
|
||||
match clipboard::platform::unix::serv_files::sync_files(&urls) {
|
||||
Ok(()) => {
|
||||
let msg = crate::clipboard_file::clip_2_msg(
|
||||
@@ -2002,8 +2080,8 @@ impl ClientClipboardHandler {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(msg) = check_clipboard(&mut self.ctx, ClipboardSide::Client, false) {
|
||||
if self.is_text_required() {
|
||||
if check_text && self.is_text_required() {
|
||||
if let Some(msg) = check_clipboard(&mut self.ctx, ClipboardSide::Client, false) {
|
||||
self.send_msg(msg, false);
|
||||
}
|
||||
}
|
||||
@@ -2053,6 +2131,8 @@ pub struct AudioHandler {
|
||||
simple: Option<psimple::Simple>,
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
audio_buffer: AudioBuffer,
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
audio_resampler: Option<crate::audio_resampler::AudioResampler>,
|
||||
sample_rate: (u32, u32),
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
audio_stream: Option<Box<dyn StreamTrait>>,
|
||||
@@ -2060,7 +2140,57 @@ pub struct AudioHandler {
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
device_channel: u16,
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
ready: Arc<std::sync::Mutex<bool>>,
|
||||
playback_status: Arc<audio_playback::AudioPlaybackStatus>,
|
||||
#[cfg(target_os = "windows")]
|
||||
playback_recovery: audio_playback_recovery::PlaybackRecovery,
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
#[derive(Clone, Copy)]
|
||||
struct DecodedAudioConfig {
|
||||
sample_rate: u32,
|
||||
input_channels: u16,
|
||||
output_channels: u16,
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn create_audio_resampler(
|
||||
input_rate: u32,
|
||||
output_rate: u32,
|
||||
channels: u16,
|
||||
) -> ResultType<Option<crate::audio_resampler::AudioResampler>> {
|
||||
if input_rate == output_rate {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(crate::audio_resampler::AudioResampler::new(
|
||||
crate::audio_resampler::AudioResamplerConfig {
|
||||
input_rate,
|
||||
output_rate,
|
||||
channels,
|
||||
},
|
||||
)?))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn prepare_decoded_audio(
|
||||
input: &[f32],
|
||||
resampler: Option<&mut crate::audio_resampler::AudioResampler>,
|
||||
config: DecodedAudioConfig,
|
||||
) -> Result<Vec<f32>, crate::audio_resampler::AudioResamplerError> {
|
||||
let mut output = match resampler {
|
||||
Some(resampler) => resampler.process(input)?,
|
||||
None => input.to_owned(),
|
||||
};
|
||||
if config.input_channels != config.output_channels {
|
||||
output = crate::audio_rechannel(
|
||||
output,
|
||||
config.sample_rate,
|
||||
config.sample_rate,
|
||||
config.input_channels,
|
||||
config.output_channels,
|
||||
);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
@@ -2068,6 +2198,7 @@ struct AudioBuffer(
|
||||
pub Arc<std::sync::Mutex<ringbuf::HeapRb<f32>>>,
|
||||
usize,
|
||||
[usize; 30],
|
||||
Arc<std::sync::atomic::AtomicUsize>,
|
||||
);
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
@@ -2079,6 +2210,7 @@ impl Default for AudioBuffer {
|
||||
)),
|
||||
48000 * 2,
|
||||
[0; 30],
|
||||
Arc::new(std::sync::atomic::AtomicUsize::new(0)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2153,27 +2285,38 @@ impl AudioBuffer {
|
||||
let skip = (cap * max / (30 * N) + 1) & (!1);
|
||||
if (having > skip * 3) && (skip > 0) {
|
||||
lock.skip(skip);
|
||||
log::info!("skip {skip}, based {max} {zero}");
|
||||
let generation = self.signal_discontinuity();
|
||||
drop(lock);
|
||||
log::info!("skip {skip}, based {max} {zero}, generation={generation}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The caller must hold the PCM buffer lock while signaling the discard.
|
||||
fn signal_discontinuity(&self) -> usize {
|
||||
self.3
|
||||
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
.wrapping_add(1)
|
||||
}
|
||||
|
||||
/// append pcm to audio buffer, if buffered data
|
||||
/// exceeds AUDIO_BUFFER_MS, only AUDIO_BUFFER_MS
|
||||
/// will be kept.
|
||||
fn append_pcm2(&self, buffer: &[f32]) -> usize {
|
||||
let mut lock = self.0.lock().unwrap();
|
||||
let cap = lock.capacity();
|
||||
if buffer.len() > cap {
|
||||
lock.push_slice_overwrite(buffer);
|
||||
return cap;
|
||||
}
|
||||
|
||||
let having = lock.occupied_len() + buffer.len();
|
||||
if having > cap {
|
||||
lock.skip(having - cap);
|
||||
}
|
||||
lock.push_slice_overwrite(buffer);
|
||||
lock.occupied_len()
|
||||
let discard = (having > cap).then(|| (having - cap, self.signal_discontinuity()));
|
||||
let occupied = lock.occupied_len();
|
||||
drop(lock);
|
||||
if let Some((discarded, generation)) = discard {
|
||||
hbb_common::throttled_log!(
|
||||
audio_playback::AUDIO_PLAYBACK_LOG_INTERVAL,
|
||||
debug,
|
||||
"Audio buffer capacity discard: samples={discarded}, generation={generation}"
|
||||
);
|
||||
}
|
||||
occupied
|
||||
}
|
||||
|
||||
/// append pcm to audio buffer, trying to drop data
|
||||
@@ -2185,6 +2328,41 @@ impl AudioBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_os = "linux")))]
|
||||
mod audio_buffer_discontinuity_tests {
|
||||
use super::AudioBuffer;
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc, Mutex,
|
||||
};
|
||||
|
||||
const BUFFER_CAPACITY: usize = 4;
|
||||
const BUFFER_LEVELS: usize = 30;
|
||||
const FIRST_INPUT: [f32; 2] = [0.1, 0.2];
|
||||
const OVERFLOWING_INPUT: [f32; 3] = [0.3, 0.4, 0.5];
|
||||
const OVERSIZED_INPUT: [f32; 5] = [0.6, 0.7, 0.8, 0.9, 1.0];
|
||||
|
||||
#[test]
|
||||
fn capacity_discards_signal_discontinuities() {
|
||||
let audio_buffer = AudioBuffer(
|
||||
Arc::new(Mutex::new(ringbuf::HeapRb::new(BUFFER_CAPACITY))),
|
||||
BUFFER_CAPACITY,
|
||||
[0; BUFFER_LEVELS],
|
||||
Arc::new(AtomicUsize::new(0)),
|
||||
);
|
||||
|
||||
assert_eq!(audio_buffer.append_pcm2(&FIRST_INPUT), FIRST_INPUT.len());
|
||||
assert_eq!(audio_buffer.3.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(
|
||||
audio_buffer.append_pcm2(&OVERFLOWING_INPUT),
|
||||
BUFFER_CAPACITY
|
||||
);
|
||||
assert_eq!(audio_buffer.3.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(audio_buffer.append_pcm2(&OVERSIZED_INPUT), BUFFER_CAPACITY);
|
||||
assert_eq!(audio_buffer.3.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioHandler {
|
||||
#[cfg(target_os = "linux")]
|
||||
fn start_audio(&mut self, format0: AudioFormat) -> ResultType<()> {
|
||||
@@ -2231,13 +2409,16 @@ impl AudioHandler {
|
||||
log::info!("Remote input format: {:?}", format0);
|
||||
#[allow(unused_mut)]
|
||||
let mut config: StreamConfig = config.into();
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
{
|
||||
// this makes ios audio output not work
|
||||
// this makes ios and android audio output not work
|
||||
config.buffer_size = cpal::BufferSize::Fixed(64);
|
||||
}
|
||||
|
||||
self.sample_rate = (format0.sample_rate, config.sample_rate.0);
|
||||
let audio_resampler = create_audio_resampler(
|
||||
format0.sample_rate, config.sample_rate.0, format0.channels as _,
|
||||
)?;
|
||||
let mut build_output_stream = |config: StreamConfig| match sample_format {
|
||||
cpal::SampleFormat::I8 => self.build_output_stream::<i8>(&config, &device),
|
||||
cpal::SampleFormat::I16 => self.build_output_stream::<i16>(&config, &device),
|
||||
@@ -2262,22 +2443,61 @@ impl AudioHandler {
|
||||
} else {
|
||||
build_output_stream(config)?;
|
||||
}
|
||||
self.audio_resampler = audio_resampler;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle audio format and create an audio decoder.
|
||||
pub fn handle_format(&mut self, f: AudioFormat) {
|
||||
self.handle_format_with_start(f, Self::start_audio);
|
||||
}
|
||||
|
||||
fn handle_format_with_start(
|
||||
&mut self,
|
||||
f: AudioFormat,
|
||||
start: impl FnOnce(&mut Self, AudioFormat) -> ResultType<()>,
|
||||
) {
|
||||
if !is_supported_audio_channel_count(f.channels) {
|
||||
log::error!("Unsupported audio channel count: {}", f.channels);
|
||||
return;
|
||||
}
|
||||
match AudioDecoder::new(f.sample_rate, if f.channels > 1 { Stereo } else { Mono }) {
|
||||
Ok(d) => {
|
||||
#[cfg(target_os = "windows")]
|
||||
let playback_failed = self.cancel_pending_playback();
|
||||
#[cfg(target_os = "linux")]
|
||||
let keep_existing_stream = self.simple.is_some()
|
||||
&& self.sample_rate.0 == f.sample_rate
|
||||
&& u32::from(self.channels) == f.channels;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let keep_existing_stream = self.audio_stream.is_some()
|
||||
&& self.sample_rate.0 == f.sample_rate
|
||||
&& u32::from(self.channels) == f.channels;
|
||||
let buffer = vec![0.; f.sample_rate as usize * f.channels as usize];
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let mut previous = std::mem::take(self);
|
||||
#[cfg(target_os = "windows")]
|
||||
self.prepare_playback(&f);
|
||||
self.audio_decoder = Some((d, buffer));
|
||||
self.channels = f.channels as _;
|
||||
allow_err!(self.start_audio(f));
|
||||
let result = start(self, f);
|
||||
#[cfg(target_os = "windows")]
|
||||
let keep_existing_stream = keep_existing_stream
|
||||
&& !playback_failed
|
||||
&& !previous.playback_recovery.report_pending();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
if result.is_err() && keep_existing_stream {
|
||||
// The restarted capture has new Opus history even when output startup fails.
|
||||
previous.audio_decoder = self.audio_decoder.take();
|
||||
*self = previous;
|
||||
self.handle_audio_start_result(result, true);
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
self.finish_playback_replacement(result, keep_existing_stream.then_some(previous));
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
self.handle_audio_start_result(result, keep_existing_stream);
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Failed to create audio decoder: {}", err);
|
||||
@@ -2285,52 +2505,73 @@ impl AudioHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_audio_start_result(&mut self, result: ResultType<()>, keep_existing_stream: bool) {
|
||||
if let Err(error) = result {
|
||||
if keep_existing_stream {
|
||||
log::error!(
|
||||
"Failed to replace audio playback stream; keeping the existing compatible stream: {error:#}"
|
||||
);
|
||||
} else {
|
||||
*self = Self::default();
|
||||
log::error!("Failed to start audio playback: {error:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle audio frame and play it.
|
||||
#[inline]
|
||||
pub fn handle_frame(&mut self, frame: AudioFrame) {
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
if self.audio_stream.is_none() || !self.ready.lock().unwrap().clone() {
|
||||
self.playback_status.report_errors();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
if self.audio_stream.is_none()
|
||||
|| !self
|
||||
.playback_status
|
||||
.ready
|
||||
.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
if self.simple.is_none() {
|
||||
log::debug!("PulseAudio simple binding does not exists");
|
||||
log::trace!("PulseAudio simple binding does not exists");
|
||||
return;
|
||||
}
|
||||
self.audio_decoder.as_mut().map(|(d, buffer)| {
|
||||
if let Ok(n) = d.decode_float(&frame.data, buffer, false) {
|
||||
let channels = self.channels;
|
||||
let n = n * (channels as usize);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let sample_rate0 = self.sample_rate.0;
|
||||
let sample_rate = self.sample_rate.1;
|
||||
let mut buffer = buffer[0..n].to_owned();
|
||||
if sample_rate != sample_rate0 {
|
||||
buffer = crate::audio_resample(
|
||||
&buffer[0..n],
|
||||
sample_rate0,
|
||||
sample_rate,
|
||||
channels,
|
||||
);
|
||||
}
|
||||
if self.channels != self.device_channel {
|
||||
buffer = crate::audio_rechannel(
|
||||
buffer,
|
||||
sample_rate,
|
||||
sample_rate,
|
||||
self.channels,
|
||||
self.device_channel,
|
||||
);
|
||||
}
|
||||
self.audio_buffer.append_pcm(&buffer);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let data_u8 =
|
||||
unsafe { std::slice::from_raw_parts::<u8>(buffer.as_ptr() as _, n * 4) };
|
||||
self.simple.as_mut().map(|x| x.write(data_u8));
|
||||
let decoded_frames = match d.decode_float(&frame.data, buffer, false) {
|
||||
Ok(decoded_frames) => decoded_frames,
|
||||
Err(error) => {
|
||||
log::warn!("Failed to decode audio frame: {error:?}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let channels = self.channels;
|
||||
let n = decoded_frames * channels as usize;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let config = DecodedAudioConfig {
|
||||
sample_rate: self.sample_rate.1,
|
||||
input_channels: self.channels,
|
||||
output_channels: self.device_channel,
|
||||
};
|
||||
let buffer = match prepare_decoded_audio(
|
||||
&buffer[0..n],
|
||||
self.audio_resampler.as_mut(),
|
||||
config,
|
||||
) {
|
||||
Ok(output) => output,
|
||||
Err(error) => {
|
||||
log::error!("Failed to resample decoded audio: {error:#}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.audio_buffer.append_pcm(&buffer);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let data_u8 =
|
||||
unsafe { std::slice::from_raw_parts::<u8>(buffer.as_ptr() as _, n * 4) };
|
||||
self.simple.as_mut().map(|x| x.write(data_u8));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2343,6 +2584,9 @@ impl AudioHandler {
|
||||
device: &Device,
|
||||
) -> ResultType<()> {
|
||||
self.device_channel = config.channels;
|
||||
#[cfg(target_os = "windows")]
|
||||
let err_fn = self.playback_recovery.new_error_callback();
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let err_fn = move |err| {
|
||||
// too many errors, will improve later
|
||||
log::trace!("an error occurred on stream: {}", err);
|
||||
@@ -2350,63 +2594,28 @@ impl AudioHandler {
|
||||
self.audio_buffer
|
||||
.resize(config.sample_rate.0 as _, config.channels as _);
|
||||
let audio_buffer = self.audio_buffer.0.clone();
|
||||
let ready = self.ready.clone();
|
||||
let discontinuity_generation = self.audio_buffer.3.clone();
|
||||
let mut playback_writer = audio_playback::AudioPlaybackWriter::new(
|
||||
audio_playback::AudioPlaybackConfig {
|
||||
sample_rate: config.sample_rate.0,
|
||||
channels: config.channels as usize,
|
||||
},
|
||||
audio_buffer,
|
||||
discontinuity_generation,
|
||||
)?;
|
||||
let playback_status = playback_writer.status.clone();
|
||||
let timeout = None;
|
||||
let stream = device.build_output_stream(
|
||||
config,
|
||||
move |data: &mut [T], info: &cpal::OutputCallbackInfo| {
|
||||
if !*ready.lock().unwrap() {
|
||||
*ready.lock().unwrap() = true;
|
||||
}
|
||||
|
||||
let mut n = data.len();
|
||||
let mut lock = audio_buffer.lock().unwrap();
|
||||
let mut having = lock.occupied_len();
|
||||
// android two timestamps, one from zero, another not
|
||||
#[cfg(not(target_os = "android"))]
|
||||
if having < n {
|
||||
let tms = info.timestamp();
|
||||
let how_long = tms
|
||||
.playback
|
||||
.duration_since(&tms.callback)
|
||||
.unwrap_or(Duration::from_millis(0));
|
||||
|
||||
// must long enough to fight back scheuler delay
|
||||
if how_long > Duration::from_millis(6) && how_long < Duration::from_millis(3000)
|
||||
{
|
||||
drop(lock);
|
||||
std::thread::sleep(how_long.div_f32(1.2));
|
||||
lock = audio_buffer.lock().unwrap();
|
||||
having = lock.occupied_len();
|
||||
}
|
||||
|
||||
if having < n {
|
||||
n = having;
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "android")]
|
||||
if having < n {
|
||||
n = having;
|
||||
}
|
||||
let mut elems = vec![0.0f32; n];
|
||||
if n > 0 {
|
||||
lock.pop_slice(&mut elems);
|
||||
}
|
||||
drop(lock);
|
||||
|
||||
let mut input = elems.into_iter();
|
||||
for sample in data.iter_mut() {
|
||||
*sample = match input.next() {
|
||||
Some(x) => T::from_sample(x),
|
||||
_ => T::from_sample(0.),
|
||||
};
|
||||
}
|
||||
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
|
||||
playback_writer.write_output(data);
|
||||
},
|
||||
err_fn,
|
||||
timeout,
|
||||
)?;
|
||||
stream.play()?;
|
||||
self.audio_stream = Some(Box::new(stream));
|
||||
self.playback_status = playback_status;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2426,6 +2635,27 @@ mod audio_format_tests {
|
||||
assert!(!is_supported_audio_channel_count(0));
|
||||
assert!(!is_supported_audio_channel_count(u32::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_audio_start_discards_format_state() {
|
||||
use super::{anyhow, AudioDecoder, AudioHandler, Stereo};
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const CHANNELS: u16 = 2;
|
||||
let decoder = AudioDecoder::new(SAMPLE_RATE, Stereo).unwrap();
|
||||
let mut handler = AudioHandler {
|
||||
audio_decoder: Some((decoder, Vec::new())),
|
||||
sample_rate: (SAMPLE_RATE, SAMPLE_RATE),
|
||||
channels: CHANNELS,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
handler.handle_audio_start_result(Err(anyhow!("Injected playback startup failure")), false);
|
||||
|
||||
assert!(handler.audio_decoder.is_none());
|
||||
assert_eq!(handler.channels, 0);
|
||||
assert_eq!(handler.sample_rate, (0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Video handler for the [`Client`].
|
||||
@@ -3929,7 +4159,11 @@ pub fn start_audio_thread() -> MediaSender {
|
||||
std::thread::spawn(move || {
|
||||
let mut audio_handler = AudioHandler::default();
|
||||
loop {
|
||||
if let Ok(data) = audio_receiver.recv() {
|
||||
#[cfg(target_os = "windows")]
|
||||
let received = audio_handler.receive_audio(&audio_receiver);
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let received = audio_receiver.recv();
|
||||
if let Ok(data) = received {
|
||||
match data {
|
||||
MediaData::AudioFrame(af) => {
|
||||
audio_handler.handle_frame(*af);
|
||||
@@ -4742,6 +4976,8 @@ pub enum Data {
|
||||
RejectInsecureConnection,
|
||||
Login((String, String, String, bool)),
|
||||
Message(Message),
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
InitialClipboard(usize, Option<Message>),
|
||||
SendFiles((i32, JobType, String, String, i32, bool, bool)),
|
||||
RemoveDirAll((i32, String, bool, bool)),
|
||||
ConfirmDeleteFiles((i32, i32)),
|
||||
@@ -5138,6 +5374,15 @@ pub mod peer_online {
|
||||
match msg_in.union {
|
||||
Some(rendezvous_message::Union::OnlineResponse(online_response)) => {
|
||||
let states = online_response.states;
|
||||
// One bit per ID, rounded up to whole bytes:
|
||||
// 0 IDs -> 0 bytes; 1..=8 -> 1; 9..=16 -> 2; 17..=24 -> 3.
|
||||
let required_len = ids.len().div_ceil(u8::BITS as usize);
|
||||
if states.len() < required_len {
|
||||
bail!(
|
||||
"Invalid online response: expected at least {required_len} state bytes, got {}",
|
||||
states.len()
|
||||
);
|
||||
}
|
||||
let mut onlines = Vec::new();
|
||||
let mut offlines = Vec::new();
|
||||
for i in 0..ids.len() {
|
||||
@@ -5583,3 +5828,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
use hbb_common::{log, log_throttle::LogThrottle, thiserror};
|
||||
use ringbuf::{ring_buffer::RbBase, Rb};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
TryLockError,
|
||||
};
|
||||
|
||||
pub(super) const UNDERRUN_DECLICK_MS: usize = 5;
|
||||
pub(super) const AUDIO_PLAYBACK_LOG_INTERVAL: std::time::Duration =
|
||||
std::time::Duration::from_secs(5);
|
||||
const MILLISECONDS_PER_SECOND: usize = 1_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct AudioPlaybackConfig {
|
||||
pub sample_rate: u32,
|
||||
pub channels: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub(super) enum AudioPlaybackError {
|
||||
#[error(
|
||||
"invalid audio playback configuration: sample_rate={}, channels={}",
|
||||
.0.sample_rate, .0.channels
|
||||
)]
|
||||
InvalidConfig(AudioPlaybackConfig),
|
||||
#[error("audio playback frame has {samples} samples for {channels} channels")]
|
||||
IncompleteFrame { samples: usize, channels: usize },
|
||||
#[error("audio playback transition frame count overflow")]
|
||||
FrameCountOverflow,
|
||||
}
|
||||
|
||||
pub(super) struct AudioPlaybackRecovery {
|
||||
channels: usize,
|
||||
transition_frames: usize,
|
||||
transition_frame: usize,
|
||||
had_input: bool,
|
||||
transition_start: Vec<f32>,
|
||||
output_frame: Vec<f32>,
|
||||
}
|
||||
|
||||
pub(super) struct AudioPlaybackStatus {
|
||||
pub(super) ready: AtomicBool,
|
||||
contentions: AtomicUsize,
|
||||
contention_log_throttle: LogThrottle,
|
||||
buffer_poisoned: AtomicBool,
|
||||
}
|
||||
|
||||
impl Default for AudioPlaybackStatus {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
ready: AtomicBool::new(false),
|
||||
contentions: AtomicUsize::new(0),
|
||||
contention_log_throttle: LogThrottle::new(AUDIO_PLAYBACK_LOG_INTERVAL),
|
||||
buffer_poisoned: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioPlaybackStatus {
|
||||
pub(super) fn report_errors(&self) {
|
||||
if self.contentions.load(Ordering::Relaxed) != 0
|
||||
&& self.contention_log_throttle.due().is_some()
|
||||
{
|
||||
let contentions = self.contentions.swap(0, Ordering::Relaxed);
|
||||
log::debug!("Audio playback PCM buffer contention: callbacks={contentions}");
|
||||
}
|
||||
if self.buffer_poisoned.swap(false, Ordering::Relaxed) {
|
||||
log::error!("Audio playback stopped reading a poisoned PCM buffer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct AudioPlaybackWriter {
|
||||
audio_buffer: std::sync::Arc<std::sync::Mutex<ringbuf::HeapRb<f32>>>,
|
||||
discontinuity_generation: std::sync::Arc<AtomicUsize>,
|
||||
observed_discontinuity_generation: usize,
|
||||
buffered_input: Vec<f32>,
|
||||
recovery: AudioPlaybackRecovery,
|
||||
pub(super) status: std::sync::Arc<AudioPlaybackStatus>,
|
||||
buffer_failed: bool,
|
||||
}
|
||||
|
||||
impl AudioPlaybackWriter {
|
||||
pub(super) fn new(
|
||||
config: AudioPlaybackConfig,
|
||||
audio_buffer: std::sync::Arc<std::sync::Mutex<ringbuf::HeapRb<f32>>>,
|
||||
discontinuity_generation: std::sync::Arc<AtomicUsize>,
|
||||
) -> Result<Self, AudioPlaybackError> {
|
||||
let recovery = AudioPlaybackRecovery::new(config)?;
|
||||
let buffer_capacity = audio_buffer.lock().unwrap().capacity();
|
||||
let observed_discontinuity_generation = discontinuity_generation.load(Ordering::Relaxed);
|
||||
Ok(Self {
|
||||
audio_buffer,
|
||||
discontinuity_generation,
|
||||
observed_discontinuity_generation,
|
||||
buffered_input: vec![0.0; buffer_capacity],
|
||||
recovery,
|
||||
status: Default::default(),
|
||||
buffer_failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_buffer(&mut self, requested_samples: usize) -> usize {
|
||||
if self.buffer_failed {
|
||||
return 0;
|
||||
}
|
||||
let mut buffer = match self.audio_buffer.try_lock() {
|
||||
Ok(buffer) => buffer,
|
||||
Err(TryLockError::WouldBlock) => {
|
||||
// Keep queued PCM and its generation for the next successful read.
|
||||
self.status.contentions.fetch_add(1, Ordering::Relaxed);
|
||||
return 0;
|
||||
}
|
||||
Err(TryLockError::Poisoned(_)) => {
|
||||
self.buffer_failed = true;
|
||||
self.status.ready.store(false, Ordering::Release);
|
||||
self.status.buffer_poisoned.store(true, Ordering::Relaxed);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
let generation = self.discontinuity_generation.load(Ordering::Relaxed);
|
||||
let channels = self.recovery.channels;
|
||||
let samples = buffer.occupied_len().min(requested_samples) / channels * channels;
|
||||
buffer.pop_slice(&mut self.buffered_input[..samples]);
|
||||
drop(buffer);
|
||||
if generation != self.observed_discontinuity_generation {
|
||||
self.recovery.begin_discontinuity();
|
||||
self.observed_discontinuity_generation = generation;
|
||||
}
|
||||
samples
|
||||
}
|
||||
|
||||
pub(super) fn write_output<T>(&mut self, output: &mut [T])
|
||||
where
|
||||
T: cpal::Sample + cpal::FromSample<f32>,
|
||||
{
|
||||
self.status
|
||||
.ready
|
||||
.store(!self.buffer_failed, Ordering::Release);
|
||||
let requested_samples = output.len().min(self.buffered_input.len());
|
||||
let channel_count = self.recovery.channels;
|
||||
let available_samples = self.read_buffer(requested_samples);
|
||||
let available_frames = available_samples / channel_count;
|
||||
for (frame_index, output_frame) in output.chunks_mut(channel_count).enumerate() {
|
||||
let input = if frame_index < available_frames {
|
||||
let start = frame_index * channel_count;
|
||||
Some(&self.buffered_input[start..start + channel_count])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match self.recovery.process_frame(input) {
|
||||
Ok(recovered) => {
|
||||
for (output, sample) in output_frame.iter_mut().zip(recovered) {
|
||||
*output = T::from_sample(*sample);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Failed to recover audio underflow: {error}");
|
||||
output_frame.fill(T::from_sample(0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioPlaybackRecovery {
|
||||
pub(super) fn new(config: AudioPlaybackConfig) -> Result<Self, AudioPlaybackError> {
|
||||
if config.sample_rate == 0 || config.channels == 0 {
|
||||
return Err(AudioPlaybackError::InvalidConfig(config));
|
||||
}
|
||||
let transition_frames = (config.sample_rate as usize)
|
||||
.checked_mul(UNDERRUN_DECLICK_MS)
|
||||
.ok_or(AudioPlaybackError::FrameCountOverflow)?
|
||||
/ MILLISECONDS_PER_SECOND;
|
||||
if transition_frames == 0 {
|
||||
return Err(AudioPlaybackError::InvalidConfig(config));
|
||||
}
|
||||
Ok(Self {
|
||||
channels: config.channels,
|
||||
transition_frames,
|
||||
transition_frame: transition_frames,
|
||||
had_input: false,
|
||||
transition_start: vec![0.0; config.channels],
|
||||
output_frame: vec![0.0; config.channels],
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn process_frame(
|
||||
&mut self,
|
||||
input: Option<&[f32]>,
|
||||
) -> Result<&[f32], AudioPlaybackError> {
|
||||
if input.is_some_and(|frame| frame.len() != self.channels) {
|
||||
return Err(AudioPlaybackError::IncompleteFrame {
|
||||
samples: input.map_or(0, <[f32]>::len),
|
||||
channels: self.channels,
|
||||
});
|
||||
}
|
||||
self.begin_transition(input.is_some());
|
||||
let target_weight = self.advance_transition();
|
||||
for channel in 0..self.channels {
|
||||
let target = input.map_or(0.0, |frame| frame[channel]);
|
||||
self.output_frame[channel] =
|
||||
self.transition_start[channel] * (1.0 - target_weight) + target * target_weight;
|
||||
}
|
||||
Ok(&self.output_frame)
|
||||
}
|
||||
|
||||
pub(super) fn begin_discontinuity(&mut self) {
|
||||
self.transition_start.copy_from_slice(&self.output_frame);
|
||||
self.transition_frame = 0;
|
||||
}
|
||||
|
||||
fn begin_transition(&mut self, has_input: bool) {
|
||||
if has_input == self.had_input {
|
||||
return;
|
||||
}
|
||||
self.transition_start.copy_from_slice(&self.output_frame);
|
||||
self.transition_frame = 0;
|
||||
self.had_input = has_input;
|
||||
}
|
||||
|
||||
fn advance_transition(&mut self) -> f32 {
|
||||
if self.transition_frame >= self.transition_frames {
|
||||
return 1.0;
|
||||
}
|
||||
self.transition_frame += 1;
|
||||
self.transition_frame as f32 / self.transition_frames as f32
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "audio_playback_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,184 @@
|
||||
use super::{AudioDecoder, AudioFormat, AudioHandler, MediaData, Mono, Stereo};
|
||||
use cpal::StreamError;
|
||||
use crossbeam_queue::SegQueue;
|
||||
use hbb_common::{log, tokio::time::Instant, ResultType};
|
||||
use std::{
|
||||
sync::{atomic::Ordering, mpsc, Arc},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
const RECOVERY_INTERVAL: Duration = Duration::from_secs(1);
|
||||
pub(super) const STARTUP_CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
// The pinned WASAPI backend reports this warning but keeps its worker running.
|
||||
const PRIORITY_WARNING_PREFIX: &str = "SetThreadPriority failed: ";
|
||||
|
||||
#[path = "audio_playback_startup.rs"]
|
||||
mod startup;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlaybackRecovery {
|
||||
pub(super) errors: Arc<SegQueue<StreamError>>,
|
||||
format: Option<AudioFormat>,
|
||||
pub(super) retry_at: Option<Instant>,
|
||||
restart_not_before: Option<Instant>,
|
||||
awaiting_callback: bool,
|
||||
startup_deadline: Option<Instant>,
|
||||
pending_output: Option<Box<AudioHandler>>,
|
||||
}
|
||||
|
||||
impl PlaybackRecovery {
|
||||
pub(super) fn new_error_callback(&mut self) -> impl FnMut(StreamError) + Send + 'static {
|
||||
self.errors = Default::default();
|
||||
let errors = self.errors.clone();
|
||||
move |error| errors.push(error)
|
||||
}
|
||||
|
||||
pub(super) fn report_pending(&self) -> bool {
|
||||
let mut failed = false;
|
||||
while let Some(error) = self.errors.pop() {
|
||||
if matches!(&error, StreamError::BackendSpecific { err }
|
||||
if err.description.starts_with(PRIORITY_WARNING_PREFIX))
|
||||
{
|
||||
log::warn!("Audio playback nonterminal priority warning: {error}");
|
||||
} else {
|
||||
log::error!("Audio playback stream failed: {error}");
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
failed
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioHandler {
|
||||
fn clear_playback_stream(&mut self) {
|
||||
// Dropping CPAL may join its worker; run this on the owner, not its callback.
|
||||
self.audio_stream = None;
|
||||
self.playback_recovery.report_pending();
|
||||
self.playback_status.report_errors();
|
||||
let recovery = std::mem::take(self).playback_recovery;
|
||||
self.playback_recovery.format = recovery.format;
|
||||
self.playback_recovery.retry_at = recovery.retry_at;
|
||||
self.playback_recovery.restart_not_before = recovery.restart_not_before;
|
||||
}
|
||||
|
||||
pub(super) fn prepare_playback(&mut self, format: &AudioFormat) {
|
||||
self.clear_playback_stream();
|
||||
self.playback_recovery.format = Some(format.clone());
|
||||
self.playback_recovery.retry_at = None;
|
||||
self.playback_recovery.restart_not_before = None;
|
||||
}
|
||||
|
||||
pub(super) fn finish_playback_start(&mut self, result: ResultType<()>) {
|
||||
let now = Instant::now();
|
||||
let retry_at = now + RECOVERY_INTERVAL;
|
||||
self.playback_recovery.restart_not_before = Some(retry_at);
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.playback_recovery.retry_at = None;
|
||||
self.playback_recovery.awaiting_callback = true;
|
||||
self.playback_recovery.startup_deadline = Some(now + STARTUP_CONFIRMATION_TIMEOUT);
|
||||
log::info!("Audio playback stream opened; waiting for output callback");
|
||||
}
|
||||
Err(error) => {
|
||||
self.clear_playback_stream();
|
||||
self.playback_recovery.retry_at = Some(retry_at);
|
||||
log::error!(
|
||||
"Audio playback start failed: {error:#}; retrying in {RECOVERY_INTERVAL:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn playback_start_timed_out(&mut self, now: Instant) -> bool {
|
||||
if !self.playback_recovery.awaiting_callback
|
||||
|| self.playback_status.ready.load(Ordering::Acquire)
|
||||
|| !self
|
||||
.playback_recovery
|
||||
.startup_deadline
|
||||
.is_some_and(|due| now >= due)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.playback_recovery.awaiting_callback = false;
|
||||
self.playback_recovery.startup_deadline = None;
|
||||
log::error!("Audio playback start timed out waiting for output callback");
|
||||
true
|
||||
}
|
||||
|
||||
fn restart_playback(&mut self, format: AudioFormat) -> ResultType<()> {
|
||||
let channels = if format.channels > 1 { Stereo } else { Mono };
|
||||
let decoder = AudioDecoder::new(format.sample_rate, channels)?;
|
||||
let buffer = vec![0.; format.sample_rate as usize * format.channels as usize];
|
||||
let channel_count = format.channels as _;
|
||||
self.start_audio(format)?;
|
||||
self.channels = channel_count;
|
||||
self.audio_decoder = Some((decoder, buffer));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn recover_playback_with(
|
||||
&mut self,
|
||||
now: Instant,
|
||||
restart: impl FnOnce(&mut Self, AudioFormat) -> ResultType<()>,
|
||||
) {
|
||||
let failed = self.resolve_pending_playback(now).unwrap_or_else(|| {
|
||||
self.playback_recovery.report_pending() || self.playback_start_timed_out(now)
|
||||
});
|
||||
if failed {
|
||||
self.clear_playback_stream();
|
||||
self.playback_recovery.retry_at = Some(
|
||||
self.playback_recovery
|
||||
.restart_not_before
|
||||
.map_or(now, |due| due.max(now)),
|
||||
);
|
||||
}
|
||||
if self.playback_recovery.awaiting_callback
|
||||
&& self.playback_status.ready.load(Ordering::Acquire)
|
||||
{
|
||||
self.playback_recovery.awaiting_callback = false;
|
||||
self.playback_recovery.startup_deadline = None;
|
||||
log::info!("Audio playback output callback started");
|
||||
}
|
||||
if !self
|
||||
.playback_recovery
|
||||
.retry_at
|
||||
.is_some_and(|due| now >= due)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(format) = self.playback_recovery.format.clone() else {
|
||||
return;
|
||||
};
|
||||
log::info!("Recreating audio playback on the current default output device");
|
||||
let result = restart(self, format);
|
||||
self.finish_playback_start(result);
|
||||
}
|
||||
|
||||
pub(super) fn receive_audio(
|
||||
&mut self,
|
||||
receiver: &mpsc::Receiver<MediaData>,
|
||||
) -> Result<MediaData, mpsc::RecvError> {
|
||||
receive_with_recovery(receiver, RECOVERY_INTERVAL, || {
|
||||
self.recover_playback_with(Instant::now(), Self::restart_playback);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn receive_with_recovery(
|
||||
receiver: &mpsc::Receiver<MediaData>,
|
||||
interval: Duration,
|
||||
mut recover: impl FnMut(),
|
||||
) -> Result<MediaData, mpsc::RecvError> {
|
||||
loop {
|
||||
match receiver.recv_timeout(interval) {
|
||||
Ok(data) => {
|
||||
if !matches!(data, MediaData::AudioFormat(_)) {
|
||||
recover();
|
||||
}
|
||||
return Ok(data);
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => recover(),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => return Err(mpsc::RecvError),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use super::{AudioHandler, Instant, Ordering, ResultType};
|
||||
use hbb_common::log;
|
||||
|
||||
impl AudioHandler {
|
||||
pub(in crate::client) fn cancel_pending_playback(&mut self) -> bool {
|
||||
// Format messages bypass recovery; retain a usable candidate before superseding it.
|
||||
let failed = self
|
||||
.resolve_pending_playback(Instant::now())
|
||||
.unwrap_or(false);
|
||||
if let Some(mut pending) = self.playback_recovery.pending_output.take() {
|
||||
pending.audio_stream = None;
|
||||
pending.playback_recovery.report_pending();
|
||||
pending.playback_status.report_errors();
|
||||
}
|
||||
failed
|
||||
}
|
||||
|
||||
pub(in crate::client) fn finish_playback_replacement(
|
||||
&mut self,
|
||||
result: ResultType<()>,
|
||||
previous: Option<Self>,
|
||||
) {
|
||||
self.finish_playback_start(result);
|
||||
let Some(mut previous) = previous else {
|
||||
return;
|
||||
};
|
||||
previous.audio_decoder = self.audio_decoder.take();
|
||||
let candidate = std::mem::replace(self, previous);
|
||||
self.playback_recovery.pending_output = Some(Box::new(candidate));
|
||||
log::info!("Audio playback replacement pending; continuing on the compatible output");
|
||||
self.recover_playback_with(Instant::now(), Self::restart_playback);
|
||||
}
|
||||
|
||||
pub(super) fn resolve_pending_playback(&mut self, now: Instant) -> Option<bool> {
|
||||
let mut candidate = self.playback_recovery.pending_output.take()?;
|
||||
let candidate_failed =
|
||||
candidate.playback_recovery.report_pending() || candidate.playback_start_timed_out(now);
|
||||
let previous_failed =
|
||||
self.playback_recovery.report_pending() || self.playback_start_timed_out(now);
|
||||
if candidate_failed {
|
||||
self.playback_recovery.restart_not_before =
|
||||
candidate.playback_recovery.restart_not_before;
|
||||
candidate.audio_stream = None;
|
||||
candidate.playback_recovery.report_pending();
|
||||
candidate.playback_status.report_errors();
|
||||
if !previous_failed {
|
||||
log::error!("Audio playback replacement failed before startup confirmation; keeping the existing compatible stream");
|
||||
}
|
||||
return Some(previous_failed);
|
||||
}
|
||||
if candidate.playback_status.ready.load(Ordering::Acquire) || previous_failed {
|
||||
candidate.audio_decoder = self.audio_decoder.take();
|
||||
self.audio_stream = None;
|
||||
self.playback_recovery.report_pending();
|
||||
self.playback_status.report_errors();
|
||||
*self = *candidate;
|
||||
return Some(false);
|
||||
}
|
||||
self.playback_recovery.pending_output = Some(candidate);
|
||||
// A second active-queue read could discard a healthy pending candidate.
|
||||
Some(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
use super::{
|
||||
AudioPlaybackConfig, AudioPlaybackError, AudioPlaybackRecovery, AudioPlaybackStatus,
|
||||
AudioPlaybackWriter,
|
||||
};
|
||||
use ringbuf::{ring_buffer::RbBase, Rb};
|
||||
use std::{
|
||||
sync::{atomic::Ordering, mpsc, Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
const SAMPLE_RATE: u32 = 48_000;
|
||||
const CHANNELS: usize = 2;
|
||||
const ACTIVE_FRAME: [f32; CHANNELS] = [0.8, -0.8];
|
||||
const OPPOSITE_ACTIVE_FRAME: [f32; CHANNELS] = [-0.8, 0.8];
|
||||
const ACTIVE_FRAMES: usize = 300;
|
||||
const SILENT_FRAMES: usize = 300;
|
||||
const TRANSITION_FRAMES: usize =
|
||||
SAMPLE_RATE as usize * super::UNDERRUN_DECLICK_MS / super::MILLISECONDS_PER_SECOND;
|
||||
const MAX_SAMPLE_STEP: f32 = 0.01;
|
||||
|
||||
#[test]
|
||||
fn writing_audio_observes_discard_and_releases_buffer_lock() {
|
||||
const INPUT: [f32; 4] = [0.1, 0.2, 0.3, 0.4];
|
||||
const GENERATION: usize = 7;
|
||||
let buffer = Arc::new(Mutex::new(ringbuf::HeapRb::new(INPUT.len())));
|
||||
let generation = Arc::new(super::AtomicUsize::new(0));
|
||||
let config = AudioPlaybackConfig {
|
||||
sample_rate: SAMPLE_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
let mut writer = AudioPlaybackWriter::new(config, buffer.clone(), generation.clone()).unwrap();
|
||||
{
|
||||
let mut buffer = buffer.lock().unwrap();
|
||||
buffer.push_slice(&INPUT);
|
||||
generation.store(GENERATION, Ordering::Relaxed);
|
||||
}
|
||||
let mut output = [0.0_f32; INPUT.len()];
|
||||
|
||||
writer.write_output(&mut output);
|
||||
|
||||
assert_eq!(writer.buffered_input, INPUT);
|
||||
assert_eq!(writer.observed_discontinuity_generation, GENERATION);
|
||||
assert_eq!(buffer.try_lock().unwrap().occupied_len(), 0);
|
||||
}
|
||||
|
||||
fn maximum_sample_step(samples: &[f32]) -> f32 {
|
||||
samples
|
||||
.windows(CHANNELS + 1)
|
||||
.map(|window| (window[CHANNELS] - window[0]).abs())
|
||||
.fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooths_underflow_and_explicit_audio_discontinuities() {
|
||||
for explicit_discontinuity in [false, true] {
|
||||
let config = AudioPlaybackConfig {
|
||||
sample_rate: SAMPLE_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
let mut recovery = AudioPlaybackRecovery::new(config).unwrap();
|
||||
let mut output = Vec::new();
|
||||
for _ in 0..ACTIVE_FRAMES {
|
||||
output.extend_from_slice(recovery.process_frame(Some(&ACTIVE_FRAME)).unwrap());
|
||||
}
|
||||
let transition_end = TRANSITION_FRAMES * CHANNELS;
|
||||
assert_eq!(
|
||||
&output[transition_end - CHANNELS..transition_end],
|
||||
ACTIVE_FRAME.as_slice(),
|
||||
"explicit_discontinuity={explicit_discontinuity}"
|
||||
);
|
||||
let resumed_frame = if explicit_discontinuity {
|
||||
recovery.begin_discontinuity();
|
||||
&OPPOSITE_ACTIVE_FRAME
|
||||
} else {
|
||||
for _ in 0..SILENT_FRAMES {
|
||||
output.extend_from_slice(recovery.process_frame(None).unwrap());
|
||||
}
|
||||
&ACTIVE_FRAME
|
||||
};
|
||||
for _ in 0..ACTIVE_FRAMES {
|
||||
output.extend_from_slice(recovery.process_frame(Some(resumed_frame)).unwrap());
|
||||
}
|
||||
let maximum = maximum_sample_step(&output);
|
||||
assert!(
|
||||
maximum <= MAX_SAMPLE_STEP,
|
||||
"step {maximum} exceeded {MAX_SAMPLE_STEP}, explicit={explicit_discontinuity}"
|
||||
);
|
||||
assert_eq!(
|
||||
&output[output.len() - CHANNELS..],
|
||||
resumed_frame,
|
||||
"explicit_discontinuity={explicit_discontinuity}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_configuration_and_frame_size() {
|
||||
let invalid_config = AudioPlaybackConfig {
|
||||
sample_rate: 0,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
assert_eq!(
|
||||
AudioPlaybackRecovery::new(invalid_config).err(),
|
||||
Some(AudioPlaybackError::InvalidConfig(invalid_config))
|
||||
);
|
||||
|
||||
let config = AudioPlaybackConfig {
|
||||
sample_rate: SAMPLE_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
let mut recovery = AudioPlaybackRecovery::new(config).unwrap();
|
||||
assert_eq!(
|
||||
recovery.process_frame(Some(&[0.5])).err(),
|
||||
Some(AudioPlaybackError::IncompleteFrame {
|
||||
samples: 1,
|
||||
channels: CHANNELS,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const CALLBACK_SAMPLES: usize = 64;
|
||||
const CALLBACK_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const DISCARD_GENERATION: usize = 1;
|
||||
|
||||
fn write_while_buffer_is_locked(
|
||||
mut writer: AudioPlaybackWriter,
|
||||
buffer: &Arc<Mutex<ringbuf::HeapRb<f32>>>,
|
||||
generation: &Arc<super::AtomicUsize>,
|
||||
) -> (AudioPlaybackWriter, [f32; CALLBACK_SAMPLES]) {
|
||||
let mut guard = buffer.lock().unwrap();
|
||||
let queued = OPPOSITE_ACTIVE_FRAME.repeat(ACTIVE_FRAMES);
|
||||
guard.push_slice(&queued);
|
||||
generation.store(DISCARD_GENERATION, Ordering::Relaxed);
|
||||
let (completed_tx, completed_rx) = mpsc::channel();
|
||||
let callback = std::thread::spawn(move || {
|
||||
let mut output = [0.0; CALLBACK_SAMPLES];
|
||||
crate::audio_resampler::allocation_tests::assert_no_allocations(|| {
|
||||
writer.write_output(&mut output);
|
||||
});
|
||||
completed_tx.send((writer, output)).unwrap();
|
||||
});
|
||||
let completed = completed_rx.recv_timeout(CALLBACK_TIMEOUT);
|
||||
let retained = guard.occupied_len();
|
||||
drop(guard);
|
||||
callback.join().unwrap();
|
||||
let result = completed.expect("playback callback waited for the buffer owner");
|
||||
assert_eq!(retained, queued.len());
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playback_contention_preserves_queued_audio_and_recovers_after_release() {
|
||||
let samples = ACTIVE_FRAMES * CHANNELS;
|
||||
let buffer = Arc::new(Mutex::new(ringbuf::HeapRb::new(samples)));
|
||||
let generation = Arc::new(super::AtomicUsize::new(0));
|
||||
let config = AudioPlaybackConfig {
|
||||
sample_rate: SAMPLE_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
let mut writer = AudioPlaybackWriter::new(config, buffer.clone(), generation.clone()).unwrap();
|
||||
buffer
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push_slice(&ACTIVE_FRAME.repeat(ACTIVE_FRAMES));
|
||||
let mut output = vec![0.0; samples];
|
||||
writer.write_output(&mut output);
|
||||
assert_eq!(&output[samples - CHANNELS..], &ACTIVE_FRAME);
|
||||
|
||||
let (mut writer, gap) = write_while_buffer_is_locked(writer, &buffer, &generation);
|
||||
|
||||
assert_eq!(writer.status.contentions.load(Ordering::Relaxed), 1);
|
||||
assert!(writer.status.ready.load(Ordering::Acquire));
|
||||
assert_eq!(writer.observed_discontinuity_generation, 0);
|
||||
assert!(maximum_sample_step(&gap) <= MAX_SAMPLE_STEP);
|
||||
assert!(gap[0] > 0.0 && gap[0] < ACTIVE_FRAME[0]);
|
||||
assert_eq!(gap[1], -gap[0]);
|
||||
assert!(gap[CALLBACK_SAMPLES - CHANNELS] > 0.0);
|
||||
writer.write_output(&mut output);
|
||||
let mut transition = gap[gap.len() - CHANNELS..].to_vec();
|
||||
transition.extend_from_slice(&output[..TRANSITION_FRAMES * CHANNELS]);
|
||||
assert!(maximum_sample_step(&transition) <= MAX_SAMPLE_STEP);
|
||||
assert_eq!(
|
||||
writer.buffered_input,
|
||||
OPPOSITE_ACTIVE_FRAME.repeat(ACTIVE_FRAMES)
|
||||
);
|
||||
assert_eq!(writer.observed_discontinuity_generation, DISCARD_GENERATION);
|
||||
assert_eq!(&output[samples - CHANNELS..], &OPPOSITE_ACTIVE_FRAME);
|
||||
assert_eq!(buffer.lock().unwrap().occupied_len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poisoned_playback_buffer_reports_once_without_panicking_in_the_callback() {
|
||||
let buffer = Arc::new(Mutex::new(ringbuf::HeapRb::new(CALLBACK_SAMPLES)));
|
||||
let config = AudioPlaybackConfig {
|
||||
sample_rate: SAMPLE_RATE,
|
||||
channels: CHANNELS,
|
||||
};
|
||||
let mut writer =
|
||||
AudioPlaybackWriter::new(config, buffer.clone(), Arc::new(super::AtomicUsize::new(0)))
|
||||
.unwrap();
|
||||
assert!(std::thread::spawn(move || {
|
||||
let _guard = buffer.lock().unwrap();
|
||||
panic!("Injected PCM buffer failure");
|
||||
})
|
||||
.join()
|
||||
.is_err());
|
||||
let mut output = [ACTIVE_FRAME[0]; CALLBACK_SAMPLES];
|
||||
|
||||
crate::audio_resampler::allocation_tests::assert_no_allocations(|| {
|
||||
writer.write_output(&mut output);
|
||||
});
|
||||
|
||||
assert_eq!(output, [0.0; CALLBACK_SAMPLES]);
|
||||
assert!(!writer.status.ready.load(Ordering::Acquire));
|
||||
assert!(writer.status.buffer_poisoned.load(Ordering::Relaxed));
|
||||
writer.status.report_errors();
|
||||
writer.write_output(&mut output);
|
||||
assert!(!writer.status.buffer_poisoned.load(Ordering::Relaxed));
|
||||
assert_eq!(writer.status.contentions.load(Ordering::Relaxed), 0);
|
||||
assert!(!writer.status.ready.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contention_counts_accumulate_until_the_next_report() {
|
||||
let status = AudioPlaybackStatus::default();
|
||||
status.report_errors();
|
||||
status.contentions.fetch_add(1, Ordering::Relaxed);
|
||||
status.report_errors();
|
||||
assert_eq!(status.contentions.load(Ordering::Relaxed), 0);
|
||||
|
||||
let mut total = 0;
|
||||
for callbacks in [3, 7, 2] {
|
||||
total += callbacks;
|
||||
status.contentions.fetch_add(callbacks, Ordering::Relaxed);
|
||||
status.report_errors();
|
||||
assert_eq!(status.contentions.load(Ordering::Relaxed), total);
|
||||
}
|
||||
status.buffer_poisoned.store(true, Ordering::Relaxed);
|
||||
status.report_errors();
|
||||
assert!(!status.buffer_poisoned.load(Ordering::Relaxed));
|
||||
assert_eq!(status.contentions.load(Ordering::Relaxed), total);
|
||||
|
||||
std::thread::sleep(super::AUDIO_PLAYBACK_LOG_INTERVAL);
|
||||
status.report_errors();
|
||||
assert_eq!(status.contentions.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contention_reporting_is_independent_between_playbacks() {
|
||||
let first = AudioPlaybackStatus::default();
|
||||
let second = AudioPlaybackStatus::default();
|
||||
for status in [&first, &second] {
|
||||
status.contentions.fetch_add(1, Ordering::Relaxed);
|
||||
status.report_errors();
|
||||
assert_eq!(status.contentions.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
for status in [&first, &second] {
|
||||
status.contentions.fetch_add(1, Ordering::Relaxed);
|
||||
status.report_errors();
|
||||
assert_eq!(status.contentions.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
}
|
||||
+534
-46
@@ -1,5 +1,5 @@
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
use crate::clipboard::{update_clipboard, ClipboardSide};
|
||||
use crate::clipboard::{clipboard_listener, update_clipboard, ClipboardSide};
|
||||
#[cfg(not(any(target_os = "ios")))]
|
||||
use crate::{audio_service, clipboard::CLIPBOARD_INTERVAL, ConnInner, CLIENT_SERVER};
|
||||
use crate::{
|
||||
@@ -61,7 +61,7 @@ use hbb_common::{
|
||||
use hbb_common::{tokio::sync::Mutex as TokioMutex, ResultType};
|
||||
use scrap::CodecFormat;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
collections::{HashMap, HashSet},
|
||||
ffi::c_void,
|
||||
num::NonZeroI64,
|
||||
path::PathBuf,
|
||||
@@ -84,7 +84,12 @@ pub struct Remote<T: InvokeUiSession> {
|
||||
remove_jobs: HashMap<i32, RemoveJob>,
|
||||
timer: crate::RustDeskInterval,
|
||||
last_update_jobs_status: (Instant, HashMap<i32, u64>),
|
||||
// Set after PeerInfo for this round, not when the transport connects.
|
||||
is_connected: bool,
|
||||
// Whether the scheduled initial snapshot may still be sent.
|
||||
// The connection loop clears this when handling its result or a live clipboard update.
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
initial_clipboard_pending: bool,
|
||||
first_frame: bool,
|
||||
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
|
||||
client_conn_id: i32, // used for file clipboard
|
||||
@@ -96,6 +101,7 @@ pub struct Remote<T: InvokeUiSession> {
|
||||
chroma: Arc<RwLock<Option<Chroma>>>,
|
||||
last_record_state: bool,
|
||||
sent_close_reason: bool,
|
||||
cursor_dedupe: CursorDedupe,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -132,6 +138,8 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
timer: crate::rustdesk_interval(time::interval(SEC30)),
|
||||
last_update_jobs_status: (Instant::now(), Default::default()),
|
||||
is_connected: false,
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
initial_clipboard_pending: false,
|
||||
first_frame: false,
|
||||
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
|
||||
client_conn_id: 0,
|
||||
@@ -145,6 +153,7 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
chroma: Default::default(),
|
||||
last_record_state: false,
|
||||
sent_close_reason: false,
|
||||
cursor_dedupe: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,6 +441,11 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
if self.handler.is_default() && _set_disconnected_ok {
|
||||
// Other sessions may keep the listener running after this one disconnects.
|
||||
#[cfg(feature = "flutter")]
|
||||
crate::flutter::update_text_clipboard_required();
|
||||
#[cfg(all(feature = "flutter", feature = "unix-file-copy-paste"))]
|
||||
crate::flutter::update_file_clipboard_required();
|
||||
Client::try_stop_clipboard();
|
||||
}
|
||||
|
||||
@@ -445,7 +459,7 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
|
||||
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
|
||||
async fn handle_local_clipboard_msg(
|
||||
&self,
|
||||
&mut self,
|
||||
peer: &mut Stream,
|
||||
msg: Option<clipboard::ClipboardFile>,
|
||||
) {
|
||||
@@ -458,6 +472,10 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
} => {
|
||||
self.handler.msgbox(&r#type, &title, &text, "");
|
||||
}
|
||||
// File-data responses bypass is_stopping_allowed, but still require login.
|
||||
_ if !self.is_connected => {
|
||||
log::debug!("Discarding local file clipboard message before login");
|
||||
}
|
||||
_ => {
|
||||
let is_stopping_allowed = clip.is_stopping_allowed();
|
||||
let server_file_transfer_enabled =
|
||||
@@ -466,9 +484,7 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
self.handler.lc.read().unwrap().enable_file_copy_paste.v;
|
||||
let view_only = self.handler.lc.read().unwrap().view_only.v;
|
||||
let stop = is_stopping_allowed
|
||||
&& (view_only
|
||||
|| !self.is_connected
|
||||
|| !(server_file_transfer_enabled && file_transfer_enabled));
|
||||
&& (view_only || !(server_file_transfer_enabled && file_transfer_enabled));
|
||||
log::debug!(
|
||||
"Process clipboard message from system, view_only: {}, stop: {}, is_stopping_allowed: {}, server_file_transfer_enabled: {}, file_transfer_enabled: {}",
|
||||
view_only, stop, is_stopping_allowed, server_file_transfer_enabled, file_transfer_enabled
|
||||
@@ -485,6 +501,10 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
// to-do: Show msgbox with "Don't show again" option
|
||||
};
|
||||
log::debug!("Send system clipboard message to remote");
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
if matches!(&clip, clipboard::ClipboardFile::FormatList { .. }) {
|
||||
self.initial_clipboard_pending = false;
|
||||
}
|
||||
let msg = crate::clipboard_file::clip_2_msg(clip);
|
||||
allow_err!(peer.send(&msg).await);
|
||||
}
|
||||
@@ -598,6 +618,9 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
} else {
|
||||
log::debug!("Failed to record local audio channel: {}", err);
|
||||
}
|
||||
// Both arms fall through with nothing else in this loop blocking, so
|
||||
// without a pause the thread spun a core for the whole voice call.
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -622,6 +645,82 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
self.sent_close_reason = true;
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
fn start_initial_clipboard_sync(&mut self) {
|
||||
let peer_info = {
|
||||
let lc = self.handler.lc.read().unwrap();
|
||||
lc.peer_info
|
||||
.as_ref()
|
||||
.map(|pi| (pi.version.clone(), pi.platform.clone()))
|
||||
};
|
||||
let Some((peer_version, peer_platform)) = peer_info else {
|
||||
log::error!("Cannot start initial clipboard sync without peer information");
|
||||
return;
|
||||
};
|
||||
|
||||
self.initial_clipboard_pending = true;
|
||||
let sender = self.sender.clone();
|
||||
let permission_config = self.handler.get_permission_config();
|
||||
// Clipboard access and encoding must not block the connection loop.
|
||||
let read_clipboard = move || {
|
||||
// Capture after readiness, before reading; later changes invalidate this snapshot.
|
||||
let generation = clipboard_listener::current_generation();
|
||||
let msg_out = if permission_config.is_text_clipboard_required() {
|
||||
crate::clipboard::get_current_clipboard_msg(
|
||||
&peer_version,
|
||||
&peer_platform,
|
||||
crate::clipboard::ClipboardSide::Client,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let msg_out = msg_out.filter(|_| permission_config.is_text_clipboard_required());
|
||||
// Empty or failed reads must also finish the pending initial-sync attempt.
|
||||
if let Err(err) = sender.send(Data::InitialClipboard(generation, msg_out)) {
|
||||
log::debug!("Failed to send initial clipboard result: {}", err);
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
self.spawn_initial_clipboard_read_after_ready(read_clipboard);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
tokio::task::spawn_blocking(read_clipboard);
|
||||
}
|
||||
|
||||
// Linux listener creation returns before X11/Wayland has subscribed to changes.
|
||||
// Capture after readiness so changes during the read can invalidate the snapshot.
|
||||
// A separate task keeps a stalled backend from blocking the connection loop.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn spawn_initial_clipboard_read_after_ready(&self, read_clipboard: impl FnOnce() + Send + 'static) {
|
||||
// Initial-sync wait budget, not a protocol-defined startup deadline.
|
||||
const CLIPBOARD_READY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
let sender = self.sender.clone();
|
||||
tokio::spawn(async move {
|
||||
let ready = tokio::select! {
|
||||
result = time::timeout(CLIPBOARD_READY_TIMEOUT, clipboard_listener::wait_for_ready()) => {
|
||||
match result {
|
||||
Ok(ready) => ready,
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
_ = sender.closed() => return,
|
||||
};
|
||||
if let Err(err) = ready {
|
||||
log::error!(
|
||||
"Failed to wait for clipboard listener readiness (limit {:?}): {}",
|
||||
CLIPBOARD_READY_TIMEOUT,
|
||||
err,
|
||||
);
|
||||
let generation = clipboard_listener::current_generation();
|
||||
if let Err(err) = sender.send(Data::InitialClipboard(generation, None)) {
|
||||
log::debug!("Failed to send initial clipboard result: {}", err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
tokio::task::spawn_blocking(read_clipboard);
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle_msg_from_ui(&mut self, data: Data, peer: &mut Stream) -> bool {
|
||||
match data {
|
||||
Data::Close => {
|
||||
@@ -637,8 +736,56 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
Data::ToggleClipboardFile => {
|
||||
self.check_clipboard_file_context();
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
Data::InitialClipboard(generation, msg) => {
|
||||
// A live update supersedes any initial snapshot still being prepared.
|
||||
if !self.initial_clipboard_pending {
|
||||
return true;
|
||||
}
|
||||
self.initial_clipboard_pending = false;
|
||||
if !self.handler.is_text_clipboard_required() {
|
||||
return true;
|
||||
}
|
||||
if generation != clipboard_listener::current_generation() {
|
||||
// A clipboard change or listener restart can invalidate the snapshot
|
||||
// without sending a live update that supersedes it.
|
||||
drop(msg);
|
||||
self.start_initial_clipboard_sync();
|
||||
return true;
|
||||
}
|
||||
if let Some(msg) = msg {
|
||||
allow_err!(peer.send(&msg).await);
|
||||
}
|
||||
}
|
||||
Data::Message(msg) => {
|
||||
// The Flutter clipboard broadcast is process-wide, so a clipboard can reach this
|
||||
// round's queue before the round has logged in; it is dropped here, on the round
|
||||
// itself.
|
||||
#[cfg(feature = "flutter")]
|
||||
if !self.is_connected
|
||||
&& matches!(
|
||||
msg.union.as_ref(),
|
||||
Some(message::Union::Clipboard(_))
|
||||
| Some(message::Union::MultiClipboards(_))
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match &msg.union {
|
||||
Some(message::Union::Cliprdr(_)) if !self.is_connected => {
|
||||
log::debug!("Discarding outgoing file clipboard message before login");
|
||||
return true;
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
Some(message::Union::Clipboard(_)) | Some(message::Union::MultiClipboards(_)) => {
|
||||
self.initial_clipboard_pending = false;
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
Some(message::Union::Cliprdr(clip))
|
||||
if matches!(clip.union.as_ref(), Some(cliprdr::Union::FormatList(_))) =>
|
||||
{
|
||||
self.initial_clipboard_pending = false;
|
||||
}
|
||||
Some(message::Union::Misc(misc)) => match misc.union {
|
||||
Some(misc::Union::RefreshVideo(_)) => {
|
||||
self.video_threads.iter().for_each(|(_, v)| {
|
||||
@@ -1451,6 +1598,14 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
#[cfg(all(target_os = "windows", not(feature = "flutter")))]
|
||||
self.check_clipboard_file_context();
|
||||
if self.handler.is_default() {
|
||||
// Startup notifications must see the current sessions' clipboard requirements.
|
||||
#[cfg(feature = "flutter")]
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
crate::flutter::update_text_clipboard_required();
|
||||
|
||||
#[cfg(all(feature = "flutter", feature = "unix-file-copy-paste"))]
|
||||
crate::flutter::update_file_clipboard_required();
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
let rx = Client::try_start_clipboard(None);
|
||||
@@ -1472,31 +1627,18 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
timeout(CLIPBOARD_INTERVAL, rx.recv()).await.ok();
|
||||
}
|
||||
|
||||
// `is_connected`` becomes true after the first PeerInfo.
|
||||
// Reconnects create a new Remote. Refreshes after a generation change
|
||||
// use a separate entry point and are not blocked by this guard.
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
if self.handler.lc.read().unwrap().sync_init_clipboard.v {
|
||||
if let Some(msg_out) = crate::clipboard::get_current_clipboard_msg(
|
||||
&peer_version,
|
||||
&peer_platform,
|
||||
crate::clipboard::ClipboardSide::Client,
|
||||
) {
|
||||
let sender = self.sender.clone();
|
||||
let permission_config = self.handler.get_permission_config();
|
||||
tokio::spawn(async move {
|
||||
if permission_config.is_text_clipboard_required() {
|
||||
sender.send(Data::Message(msg_out)).ok();
|
||||
}
|
||||
});
|
||||
}
|
||||
if !self.is_connected
|
||||
&& self.handler.is_text_clipboard_required()
|
||||
&& self.handler.lc.read().unwrap().sync_init_clipboard.v
|
||||
{
|
||||
self.start_initial_clipboard_sync();
|
||||
}
|
||||
// to-do: Android, is `sync_init_clipboard` really needed?
|
||||
// https://github.com/rustdesk/rustdesk/discussions/9010
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
crate::flutter::update_text_clipboard_required();
|
||||
|
||||
#[cfg(all(feature = "flutter", feature = "unix-file-copy-paste"))]
|
||||
crate::flutter::update_file_clipboard_required();
|
||||
}
|
||||
|
||||
if self.handler.is_file_transfer() {
|
||||
@@ -1507,11 +1649,29 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Some(message::Union::CursorData(cd)) if self.dedupes_cursors() => {
|
||||
self.set_cursor_data_by_content(cd);
|
||||
}
|
||||
Some(message::Union::CursorId(id)) if self.dedupes_cursors() => {
|
||||
self.handler
|
||||
.set_cursor_id(self.cursor_dedupe.id(id).to_string());
|
||||
}
|
||||
Some(message::Union::CursorData(cd)) => {
|
||||
let id = cd.id;
|
||||
#[cfg(feature = "flutter")]
|
||||
let compressed = cd.colors.clone();
|
||||
match decode_cursor_data(cd) {
|
||||
Ok(cd) => self.handler.set_cursor_data(cd),
|
||||
Err(err) => log::warn!("Rejected cursor {id}: {err}"),
|
||||
Ok(cd) => {
|
||||
#[cfg(feature = "flutter")]
|
||||
self.keep_cursor_shape(cursor_shape(id, &cd, &compressed));
|
||||
self.handler.set_cursor_data(cd)
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("Rejected cursor {id}: {err}");
|
||||
// The peer shows it now: selected, the UI treats it as a shape it
|
||||
// lacks, as it will when the peer selects it again.
|
||||
self.handler.set_cursor_id(id.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(message::Union::CursorId(id)) => {
|
||||
@@ -1539,7 +1699,10 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
crate::flutter::send_clipboard_msg_to_other_sessions(msg, session_id);
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
update_clipboard(vec![cb], ClipboardSide::Client);
|
||||
{
|
||||
self.initial_clipboard_pending = false;
|
||||
update_clipboard(vec![cb], ClipboardSide::Client);
|
||||
}
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
let content = if cb.compress {
|
||||
@@ -1574,7 +1737,10 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
crate::flutter::send_clipboard_msg_to_other_sessions(msg, session_id);
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
update_clipboard(_mcb.clipboards, ClipboardSide::Client);
|
||||
{
|
||||
self.initial_clipboard_pending = false;
|
||||
update_clipboard(_mcb.clipboards, ClipboardSide::Client);
|
||||
}
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
if let Some(cb) = _mcb
|
||||
@@ -2401,6 +2567,10 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
|
||||
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
|
||||
async fn handle_cliprdr_msg(&mut self, clip: base::message_proto::Cliprdr, _peer: &mut Stream) {
|
||||
if !self.is_connected {
|
||||
log::debug!("Discarding incoming file clipboard message before login");
|
||||
return;
|
||||
}
|
||||
log::debug!("handling cliprdr msg from server peer");
|
||||
#[cfg(feature = "flutter")]
|
||||
if let Some(base::message_proto::cliprdr::Union::FormatList(_)) = &clip.union {
|
||||
@@ -2432,6 +2602,9 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
if matches!(&clip, clipboard::ClipboardFile::FormatList { .. }) {
|
||||
self.initial_clipboard_pending = false;
|
||||
}
|
||||
let _ = ContextSend::proc(|context| -> ResultType<()> {
|
||||
context
|
||||
.server_clip_file(self.client_conn_id, clip)
|
||||
@@ -2440,6 +2613,10 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
}
|
||||
#[cfg(feature = "unix-file-copy-paste")]
|
||||
if crate::is_support_file_copy_paste_num(self.handler.lc.read().unwrap().version) {
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
if matches!(&clip, clipboard::ClipboardFile::FormatList { .. }) {
|
||||
self.initial_clipboard_pending = false;
|
||||
}
|
||||
let mut out_msgs = vec![];
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -2544,21 +2721,80 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
msg.set_misc(misc);
|
||||
self.sender.send(Data::Message(msg)).ok();
|
||||
}
|
||||
|
||||
/// A shape that decoded, for the UI to ask for again; see `Session::cursor_shapes`.
|
||||
#[cfg(feature = "flutter")]
|
||||
fn keep_cursor_shape(&self, shape: CursorData) {
|
||||
self.handler
|
||||
.cursor_shapes
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(shape.id, shape);
|
||||
}
|
||||
|
||||
fn dedupes_cursors(&self) -> bool {
|
||||
!crate::is_peer_naming_cursors_by_content(self.handler.lc.read().unwrap().version)
|
||||
}
|
||||
|
||||
/// A shape the UI already has, under whatever handle, is only selected.
|
||||
fn set_cursor_data_by_content(&mut self, cd: CursorData) {
|
||||
let peer_id = cd.id;
|
||||
let id = CursorDedupe::name(&cd);
|
||||
if self.cursor_dedupe.has_decoded(id) {
|
||||
self.cursor_dedupe.record(peer_id, id);
|
||||
self.handler.set_cursor_id(id.to_string());
|
||||
return;
|
||||
}
|
||||
#[cfg(feature = "flutter")]
|
||||
let compressed = cd.colors.clone();
|
||||
match decode_cursor_data(cd) {
|
||||
Ok(mut cd) => {
|
||||
cd.id = id;
|
||||
self.cursor_dedupe.record(peer_id, id);
|
||||
#[cfg(feature = "flutter")]
|
||||
self.keep_cursor_shape(cursor_shape(id, &cd, &compressed));
|
||||
self.handler.set_cursor_data(cd);
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("Rejected cursor {peer_id}: {err}");
|
||||
self.handler
|
||||
.set_cursor_id(self.cursor_dedupe.rejected(peer_id, id).to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape that decoded, still compressed, under the id the UI knows it by. Copied once it
|
||||
/// decoded: the message's colors may be a slice of a larger received buffer, which a clone
|
||||
/// would keep alive.
|
||||
#[cfg(any(feature = "flutter", test))]
|
||||
fn cursor_shape(id: u64, cd: &CursorData, compressed: &[u8]) -> CursorData {
|
||||
CursorData {
|
||||
id,
|
||||
hotx: cd.hotx,
|
||||
hoty: cd.hoty,
|
||||
width: cd.width,
|
||||
height: cd.height,
|
||||
colors: compressed.to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGBA of a shape kept by `Session::cursor_shapes`, for the UI to draw it again.
|
||||
#[cfg(any(feature = "flutter", test))]
|
||||
pub(crate) fn kept_cursor_rgba(shape: CursorData) -> hbb_common::ResultType<CursorData> {
|
||||
decode_cursor_data(shape)
|
||||
}
|
||||
|
||||
// Both UI handlers receive validated, uncompressed RGBA from the receive loop.
|
||||
fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
|
||||
use hbb_common::{anyhow::anyhow, bail};
|
||||
|
||||
const MAX_CURSOR_SIZE: i32 = 4096;
|
||||
// Limit decoded cursor data to 1 MiB before JSON serialization.
|
||||
const MAX_CURSOR_SIZE: i32 = 512;
|
||||
const RGBA_CHANNELS: usize = 4;
|
||||
|
||||
let mut cd = data;
|
||||
// Sciter keeps the legacy outer image; Flutter uses the physical variant.
|
||||
#[cfg(feature = "flutter")]
|
||||
if let Some(physical) = cd.high_resolution.take() {
|
||||
cd = physical;
|
||||
}
|
||||
if !(1..=MAX_CURSOR_SIZE).contains(&cd.width) || !(1..=MAX_CURSOR_SIZE).contains(&cd.height) {
|
||||
bail!("invalid source size {}x{}", cd.width, cd.height);
|
||||
}
|
||||
@@ -2569,19 +2805,17 @@ fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
|
||||
cd.hoty
|
||||
);
|
||||
}
|
||||
// Zero preserves legacy sizing; positive density must bound the logical image too.
|
||||
if !cd.scale.is_finite()
|
||||
|| cd.scale < 0.0
|
||||
|| (cd.scale > 0.0
|
||||
&& (f64::from(cd.width) / cd.scale > f64::from(MAX_CURSOR_SIZE)
|
||||
|| f64::from(cd.height) / cd.scale > f64::from(MAX_CURSOR_SIZE)))
|
||||
{
|
||||
bail!("invalid cursor density {}", cd.scale);
|
||||
}
|
||||
let expected = (cd.width as usize)
|
||||
.checked_mul(cd.height as usize)
|
||||
.and_then(|pixels| pixels.checked_mul(RGBA_CHANNELS))
|
||||
.ok_or_else(|| anyhow!("cursor RGBA size overflow"))?;
|
||||
let max_compressed_size = zstd::zstd_safe::compress_bound(expected);
|
||||
if cd.colors.len() > max_compressed_size {
|
||||
bail!(
|
||||
"compressed cursor data too large: {} bytes (limit {max_compressed_size})",
|
||||
cd.colors.len()
|
||||
);
|
||||
}
|
||||
let colors = zstd::bulk::decompress(&cd.colors, expected)?;
|
||||
if colors.len() != expected {
|
||||
bail!(
|
||||
@@ -2593,6 +2827,49 @@ fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
|
||||
Ok(cd)
|
||||
}
|
||||
|
||||
/// Gives the UI one id per shape for a peer that names shapes by handle, so the UI decodes and
|
||||
/// keeps a shape once however many handles it arrives under. Nothing is dropped for the
|
||||
/// connection: the peer sends a shape once and may select any handle it named again.
|
||||
#[derive(Default)]
|
||||
struct CursorDedupe {
|
||||
ids: HashMap<u64, u64>,
|
||||
// The shapes given to the UI, by content id: whether one that arrives needs decoding.
|
||||
decoded: HashSet<u64>,
|
||||
}
|
||||
|
||||
impl CursorDedupe {
|
||||
/// Hashes the compressed colors: one peer compresses the same pixels to the same bytes, and
|
||||
/// a shape seen before is then never decompressed again.
|
||||
fn name(cd: &CursorData) -> u64 {
|
||||
crate::cursor_content_id(cd.width, cd.height, cd.hotx, cd.hoty, &cd.colors)
|
||||
}
|
||||
|
||||
fn id(&self, peer_id: u64) -> u64 {
|
||||
self.ids.get(&peer_id).copied().unwrap_or(peer_id)
|
||||
}
|
||||
|
||||
fn has_decoded(&self, id: u64) -> bool {
|
||||
self.decoded.contains(&id)
|
||||
}
|
||||
|
||||
/// Names the handle once its shape decoded, now or before.
|
||||
fn record(&mut self, peer_id: u64, id: u64) {
|
||||
self.ids.insert(peer_id, id);
|
||||
self.decoded.insert(id);
|
||||
}
|
||||
|
||||
/// Names a known handle by the content of a shape that did not decode, which is never
|
||||
/// marked decoded: the UI has no shape under it, now or when the handle is selected again,
|
||||
/// and the shape the handle named before is not shown in its place. A handle never seen is
|
||||
/// not filed, so what a peer sends that does not decode takes no room.
|
||||
fn rejected(&mut self, peer_id: u64, id: u64) -> u64 {
|
||||
if let Some(named) = self.ids.get_mut(&peer_id) {
|
||||
*named = id;
|
||||
}
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
struct RemoveJob {
|
||||
files: Vec<FileEntry>,
|
||||
path: String,
|
||||
@@ -2646,3 +2923,214 @@ impl Drop for VideoThread {
|
||||
*self.discard_queue.write().unwrap() = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(feature = "flutter")]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::flutter::FlutterHandler;
|
||||
|
||||
/// A round's `Remote` over a loopback pair, before any login: what it sends to `peer`
|
||||
/// arrives at `far`.
|
||||
async fn remote_and_peer() -> (Remote<FlutterHandler>, Stream, Stream) {
|
||||
let listener = hbb_common::tcp::new_listener("127.0.0.1:0", false)
|
||||
.await
|
||||
.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (peer, accepted) = tokio::join!(
|
||||
hbb_common::socket_client::connect_tcp(addr.to_string(), 3000),
|
||||
listener.accept()
|
||||
);
|
||||
let (accepted, far_addr) = accepted.unwrap();
|
||||
let far = Stream::Tcp(hbb_common::tcp::FramedStream::from(accepted, far_addr));
|
||||
let (sender, receiver) = mpsc::unbounded_channel::<Data>();
|
||||
let remote = Remote::new(Session::<FlutterHandler>::default(), receiver, sender);
|
||||
(remote, peer.unwrap(), far)
|
||||
}
|
||||
|
||||
async fn arrives(far: &mut Stream) -> bool {
|
||||
matches!(hbb_common::timeout(300, far.next()).await, Ok(Some(Ok(_))))
|
||||
}
|
||||
|
||||
fn clipboard() -> Data {
|
||||
let mut msg = Message::new();
|
||||
msg.set_clipboard(Clipboard {
|
||||
content: b"copied while this login was pending".to_vec().into(),
|
||||
..Default::default()
|
||||
});
|
||||
Data::Message(msg)
|
||||
}
|
||||
|
||||
fn auth_2fa() -> Data {
|
||||
let mut msg = Message::new();
|
||||
msg.set_auth_2fa(Auth2FA {
|
||||
code: "123456".to_owned(),
|
||||
..Default::default()
|
||||
});
|
||||
Data::Message(msg)
|
||||
}
|
||||
|
||||
// A clipboard queued before this round's login stays here; what the login itself sends
|
||||
// through the same queue does not.
|
||||
#[tokio::test]
|
||||
async fn a_clipboard_queued_before_this_rounds_login_is_dropped() {
|
||||
let (mut remote, mut peer, mut far) = remote_and_peer().await;
|
||||
assert!(!remote.is_connected);
|
||||
assert!(remote.handle_msg_from_ui(clipboard(), &mut peer).await);
|
||||
assert!(
|
||||
!arrives(&mut far).await,
|
||||
"a clipboard went out before the login"
|
||||
);
|
||||
assert!(remote.handle_msg_from_ui(auth_2fa(), &mut peer).await);
|
||||
assert!(arrives(&mut far).await, "the 2FA code was held back");
|
||||
|
||||
remote.is_connected = true;
|
||||
assert!(remote.handle_msg_from_ui(clipboard(), &mut peer).await);
|
||||
assert!(
|
||||
arrives(&mut far).await,
|
||||
"a clipboard after the login was held back"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_dedupe_tests {
|
||||
use super::*;
|
||||
|
||||
fn shape(id: u64, hotx: i32, colors: &[u8]) -> CursorData {
|
||||
CursorData {
|
||||
id,
|
||||
hotx,
|
||||
width: 2,
|
||||
height: 2,
|
||||
colors: colors.to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_sent_under_a_new_handle_keeps_its_id() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
let first = CursorDedupe::name(&shape(1, 0, b"arrow"));
|
||||
assert!(!dedupe.has_decoded(first));
|
||||
dedupe.record(1, first);
|
||||
|
||||
let again = CursorDedupe::name(&shape(2, 0, b"arrow"));
|
||||
assert_eq!(again, first);
|
||||
assert!(dedupe.has_decoded(again));
|
||||
dedupe.record(2, again);
|
||||
assert_eq!(dedupe.id(2), first);
|
||||
assert_eq!(dedupe.id(1), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hotspot_is_part_of_the_shape() {
|
||||
let a = CursorDedupe::name(&shape(1, 0, b"arrow"));
|
||||
let b = CursorDedupe::name(&shape(2, 1, b"arrow"));
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reused_handle_names_its_latest_shape() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
dedupe.record(1, CursorDedupe::name(&shape(1, 0, b"arrow")));
|
||||
let beam = CursorDedupe::name(&shape(1, 0, b"beam"));
|
||||
dedupe.record(1, beam);
|
||||
assert_eq!(dedupe.id(1), beam);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_shape_names_its_handle_and_is_never_decoded() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
let arrow = CursorDedupe::name(&shape(7, 0, b"arrow"));
|
||||
dedupe.record(7, arrow);
|
||||
let beam = CursorDedupe::name(&shape(8, 0, b"beam"));
|
||||
dedupe.record(8, beam);
|
||||
let broken = CursorDedupe::name(&shape(7, 0, b"broken"));
|
||||
assert_eq!(
|
||||
dedupe.rejected(7, broken),
|
||||
broken,
|
||||
"not the shape it named before"
|
||||
);
|
||||
assert_eq!(
|
||||
dedupe.id(7),
|
||||
broken,
|
||||
"nor when the handle is selected again"
|
||||
);
|
||||
assert_eq!(dedupe.id(8), beam, "another handle keeps its shape");
|
||||
assert!(!dedupe.has_decoded(broken));
|
||||
assert!(
|
||||
dedupe.has_decoded(arrow),
|
||||
"kept for a handle that brings it again"
|
||||
);
|
||||
dedupe.record(7, arrow);
|
||||
assert_eq!(dedupe.id(7), arrow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_rejected_under_handles_never_seen_files_nothing() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
let broken = CursorDedupe::name(&shape(0, 0, b"broken"));
|
||||
for handle in 0..1000 {
|
||||
assert_eq!(dedupe.rejected(handle, broken), broken);
|
||||
}
|
||||
assert!(dedupe.ids.is_empty());
|
||||
assert!(!dedupe.has_decoded(broken));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_the_peer_never_sent_is_passed_on() {
|
||||
assert_eq!(CursorDedupe::default().id(7), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peers_from_1_5_0_name_cursors_by_content() {
|
||||
use hbb_common::get_version_number as v;
|
||||
assert!(!crate::is_peer_naming_cursors_by_content(v("1.4.9")));
|
||||
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.0")));
|
||||
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.1")));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod kept_cursor_tests {
|
||||
use super::*;
|
||||
|
||||
fn compressed(width: i32, height: i32) -> CursorData {
|
||||
let rgba = vec![7u8; (width * height * 4) as usize];
|
||||
CursorData {
|
||||
id: 1,
|
||||
width,
|
||||
height,
|
||||
colors: hbb_common::compress::compress(&rgba).into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_shape_is_a_copy_under_the_ui_id() {
|
||||
let mut cd = compressed(4, 4);
|
||||
cd.hotx = 1;
|
||||
let kept = cursor_shape(42, &cd, &cd.colors);
|
||||
assert_eq!(kept.id, 42);
|
||||
assert_eq!((kept.hotx, kept.width, kept.height), (1, 4, 4));
|
||||
assert_eq!(kept.colors, cd.colors);
|
||||
assert_ne!(
|
||||
kept.colors.as_ptr(),
|
||||
cd.colors.as_ptr(),
|
||||
"not a view of the received buffer"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_shape_is_checked_again_when_it_is_read() {
|
||||
assert_eq!(kept_cursor_rgba(compressed(4, 4)).unwrap().colors.len(), 64);
|
||||
assert!(
|
||||
kept_cursor_rgba(compressed(513, 1)).is_err(),
|
||||
"over the size cap"
|
||||
);
|
||||
let mut bomb = compressed(4, 4);
|
||||
bomb.colors = hbb_common::compress::compress(&vec![0u8; 1 << 20]).into();
|
||||
assert!(kept_cursor_rgba(bomb).is_err(), "more pixels than its size");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
use super::*;
|
||||
use crate::client::{
|
||||
audio_playback::AudioPlaybackStatus, audio_playback_recovery::STARTUP_CONFIRMATION_TIMEOUT,
|
||||
};
|
||||
use cpal::StreamError;
|
||||
use crossbeam_queue::SegQueue;
|
||||
use hbb_common::tokio::time::Instant;
|
||||
use std::time::Duration;
|
||||
|
||||
const AFTER_COOLDOWN: Duration = Duration::from_secs(2);
|
||||
|
||||
type PendingOutput = (
|
||||
Arc<AtomicBool>,
|
||||
Arc<AudioPlaybackStatus>,
|
||||
Arc<SegQueue<StreamError>>,
|
||||
);
|
||||
|
||||
fn install_output(handler: &mut AudioHandler, dropped: Arc<AtomicBool>) {
|
||||
handler.sample_rate = (INPUT_RATE, OUTPUT_RATE);
|
||||
handler.device_channel = CHANNELS;
|
||||
handler.audio_stream = Some(Box::new(TrackedAudioStream(dropped)));
|
||||
handler.playback_status.ready.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
fn recovery_handler() -> (AudioHandler, Arc<AtomicBool>) {
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let mut handler = AudioHandler::default();
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), |candidate, _| {
|
||||
install_output(candidate, dropped.clone());
|
||||
Ok(())
|
||||
});
|
||||
(handler, dropped)
|
||||
}
|
||||
|
||||
fn begin_pending(handler: &mut AudioHandler) -> PendingOutput {
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let mut state = None;
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), |candidate, _| {
|
||||
install_output(candidate, dropped.clone());
|
||||
candidate
|
||||
.playback_status
|
||||
.ready
|
||||
.store(false, Ordering::Release);
|
||||
state = Some((
|
||||
candidate.playback_status.clone(),
|
||||
candidate.playback_recovery.errors.clone(),
|
||||
));
|
||||
Ok(())
|
||||
});
|
||||
let (status, errors) = state.unwrap();
|
||||
(dropped, status, errors)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unconfirmed_start_retries_without_callback_or_error() {
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let mut handler = AudioHandler::default();
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), |candidate, _| {
|
||||
install_output(candidate, dropped.clone());
|
||||
candidate
|
||||
.playback_status
|
||||
.ready
|
||||
.store(false, Ordering::Release);
|
||||
Ok(())
|
||||
});
|
||||
handler.recover_playback_with(Instant::now(), |_, _| {
|
||||
panic!("Startup confirmation deadline has not elapsed")
|
||||
});
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
let expired = Instant::now() + STARTUP_CONFIRMATION_TIMEOUT;
|
||||
let mut attempts = 0;
|
||||
handler.recover_playback_with(expired, |candidate, requested| {
|
||||
attempts += 1;
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert_eq!(requested, format(INPUT_RATE, CHANNELS));
|
||||
install_output(candidate, Arc::new(AtomicBool::new(false)));
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(attempts, 1);
|
||||
handler.recover_playback_with(expired + STARTUP_CONFIRMATION_TIMEOUT, |_, _| {
|
||||
panic!("Confirmed output must not be reopened")
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn already_terminal_candidate_cannot_replace_compatible_output() {
|
||||
let (mut handler, dropped) = recovery_handler();
|
||||
let candidate_dropped = Arc::new(AtomicBool::new(false));
|
||||
let old_buffer = handler.audio_buffer.0.clone();
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), |candidate, _| {
|
||||
install_output(candidate, candidate_dropped.clone());
|
||||
candidate
|
||||
.playback_recovery
|
||||
.errors
|
||||
.push(StreamError::DeviceNotAvailable);
|
||||
Ok(())
|
||||
});
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
assert!(candidate_dropped.load(Ordering::SeqCst));
|
||||
assert!(Arc::ptr_eq(&old_buffer, &handler.audio_buffer.0));
|
||||
handler.recover_playback_with(Instant::now() + AFTER_COOLDOWN, |_, _| {
|
||||
panic!("Compatible active output must not be reopened")
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_output_keeps_playing_and_transfers_decoder_history_on_commit() {
|
||||
let (mut handler, old_dropped) = recovery_handler();
|
||||
let old_buffer = handler.audio_buffer.0.clone();
|
||||
let (_, status, _) = begin_pending(&mut handler);
|
||||
let frame = audio_frame();
|
||||
let (mut reference, mut expected) = decoder(INPUT_RATE);
|
||||
reference
|
||||
.decode_float(&frame.data, &mut expected, false)
|
||||
.unwrap();
|
||||
handler.handle_frame(frame.clone());
|
||||
assert!(Arc::ptr_eq(&old_buffer, &handler.audio_buffer.0));
|
||||
assert!(!drain_audio(&handler).is_empty());
|
||||
status.ready.store(true, Ordering::Release);
|
||||
handler.recover_playback_with(Instant::now(), |_, _| panic!("Candidate already exists"));
|
||||
assert!(old_dropped.load(Ordering::SeqCst));
|
||||
assert!(Arc::ptr_eq(&status, &handler.playback_status));
|
||||
let samples = reference
|
||||
.decode_float(&frame.data, &mut expected, false)
|
||||
.unwrap()
|
||||
* CHANNELS as usize;
|
||||
handler.handle_frame(frame);
|
||||
assert_eq!(
|
||||
&handler.audio_decoder.as_ref().unwrap().1[..samples],
|
||||
&expected[..samples]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rollback_keeps_the_restarted_decoders_accumulated_history() {
|
||||
let (mut handler, old_dropped) = recovery_handler();
|
||||
let frame = audio_frame();
|
||||
handler.handle_frame(frame.clone());
|
||||
let (candidate_dropped, _, errors) = begin_pending(&mut handler);
|
||||
let (mut reference, mut expected) = decoder(INPUT_RATE);
|
||||
handler.handle_frame(frame.clone());
|
||||
reference
|
||||
.decode_float(&frame.data, &mut expected, false)
|
||||
.unwrap();
|
||||
errors.push(StreamError::DeviceNotAvailable);
|
||||
handler.recover_playback_with(Instant::now(), |_, _| panic!("Old output still works"));
|
||||
let samples = reference
|
||||
.decode_float(&frame.data, &mut expected, false)
|
||||
.unwrap()
|
||||
* CHANNELS as usize;
|
||||
handler.handle_frame(frame);
|
||||
assert!(!old_dropped.load(Ordering::SeqCst));
|
||||
assert!(candidate_dropped.load(Ordering::SeqCst));
|
||||
assert_eq!(
|
||||
&handler.audio_decoder.as_ref().unwrap().1[..samples],
|
||||
&expected[..samples]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_compatible_format_retires_only_the_pending_attempt() {
|
||||
let (mut handler, old_dropped) = recovery_handler();
|
||||
let (first_dropped, _, first_errors) = begin_pending(&mut handler);
|
||||
let (second_dropped, second_status, _) = begin_pending(&mut handler);
|
||||
assert!(first_dropped.load(Ordering::SeqCst));
|
||||
assert!(!old_dropped.load(Ordering::SeqCst));
|
||||
first_errors.push(StreamError::DeviceNotAvailable);
|
||||
second_status.ready.store(true, Ordering::Release);
|
||||
handler.recover_playback_with(Instant::now(), |_, _| {
|
||||
panic!("Retired attempt affected current output")
|
||||
});
|
||||
assert!(old_dropped.load(Ordering::SeqCst));
|
||||
assert!(!second_dropped.load(Ordering::SeqCst));
|
||||
assert!(Arc::ptr_eq(&second_status, &handler.playback_status));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_outputs_failing_retains_format_and_paces_recovery() {
|
||||
let (mut handler, old_dropped) = recovery_handler();
|
||||
let old_errors = handler.playback_recovery.errors.clone();
|
||||
let (candidate_dropped, _, errors) = begin_pending(&mut handler);
|
||||
old_errors.push(StreamError::DeviceNotAvailable);
|
||||
errors.push(StreamError::DeviceNotAvailable);
|
||||
handler.recover_playback_with(Instant::now(), |_, _| panic!("Retry must be paced"));
|
||||
assert!(old_dropped.load(Ordering::SeqCst));
|
||||
assert!(candidate_dropped.load(Ordering::SeqCst));
|
||||
assert!(handler.audio_stream.is_none());
|
||||
let due = handler.playback_recovery.retry_at.unwrap();
|
||||
let mut attempts = 0;
|
||||
handler.recover_playback_with(due, |_, requested| {
|
||||
attempts += 1;
|
||||
assert_eq!(requested, format(INPUT_RATE, CHANNELS));
|
||||
Ok(())
|
||||
});
|
||||
assert_eq!(attempts, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superseding_format_keeps_ready_candidate_when_active_output_failed() {
|
||||
let (mut handler, old_dropped) = recovery_handler();
|
||||
let old_errors = handler.playback_recovery.errors.clone();
|
||||
let (candidate_dropped, candidate_status, _) = begin_pending(&mut handler);
|
||||
candidate_status.ready.store(true, Ordering::Release);
|
||||
old_errors.push(StreamError::DeviceNotAvailable);
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), failed_output);
|
||||
assert!(!candidate_dropped.load(Ordering::SeqCst));
|
||||
assert!(old_dropped.load(Ordering::SeqCst));
|
||||
assert!(Arc::ptr_eq(&candidate_status, &handler.playback_status));
|
||||
assert!(handler.audio_decoder.is_some());
|
||||
assert!(handler.playback_recovery.retry_at.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superseding_format_preserves_failure_when_both_outputs_failed() {
|
||||
let (mut handler, old_dropped) = recovery_handler();
|
||||
let old_errors = handler.playback_recovery.errors.clone();
|
||||
let (candidate_dropped, status, errors) = begin_pending(&mut handler);
|
||||
status.ready.store(true, Ordering::Release);
|
||||
old_errors.push(StreamError::DeviceNotAvailable);
|
||||
errors.push(StreamError::DeviceNotAvailable);
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), failed_output);
|
||||
assert!(candidate_dropped.load(Ordering::SeqCst));
|
||||
assert!(old_dropped.load(Ordering::SeqCst));
|
||||
assert!(handler.audio_stream.is_none());
|
||||
assert!(handler.playback_recovery.retry_at.is_some());
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
use super::{create_audio_resampler, AudioDecoder, AudioFormat, AudioFrame, AudioHandler, Stereo};
|
||||
use cpal::traits::StreamTrait;
|
||||
use hbb_common::{anyhow::anyhow, ResultType};
|
||||
use magnum_opus::{Application::LowDelay, Encoder};
|
||||
use ringbuf::Rb;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
const INPUT_RATE: u32 = 24_000;
|
||||
const OUTPUT_RATE: u32 = 48_000;
|
||||
const CHANNELS: u16 = 2;
|
||||
const PACKETS_PER_SECOND: usize = 100;
|
||||
const MAX_PACKET_BYTES: usize = 4_096;
|
||||
const SAMPLE_VALUE: f32 = 0.25;
|
||||
const MONO_CHANNELS: u16 = 1;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[path = "audio_playback_recovery_tests.rs"]
|
||||
mod recovery_tests;
|
||||
|
||||
struct TrackedAudioStream(Arc<AtomicBool>);
|
||||
|
||||
impl StreamTrait for TrackedAudioStream {
|
||||
fn play(&self) -> Result<(), cpal::PlayStreamError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pause(&self) -> Result<(), cpal::PauseStreamError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TrackedAudioStream {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn decoder(sample_rate: u32) -> (AudioDecoder, Vec<f32>) {
|
||||
(
|
||||
AudioDecoder::new(sample_rate, Stereo).unwrap(),
|
||||
vec![0.0; sample_rate as usize * CHANNELS as usize],
|
||||
)
|
||||
}
|
||||
|
||||
fn active_handler(input_rate: u32) -> (AudioHandler, Arc<AtomicBool>) {
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let handler = AudioHandler {
|
||||
audio_decoder: Some(decoder(input_rate)),
|
||||
audio_resampler: create_audio_resampler(input_rate, OUTPUT_RATE, CHANNELS).unwrap(),
|
||||
sample_rate: (input_rate, OUTPUT_RATE),
|
||||
audio_stream: Some(Box::new(TrackedAudioStream(dropped.clone()))),
|
||||
channels: CHANNELS,
|
||||
device_channel: CHANNELS,
|
||||
..Default::default()
|
||||
};
|
||||
handler.playback_status.ready.store(true, Ordering::Release);
|
||||
(handler, dropped)
|
||||
}
|
||||
|
||||
fn audio_frame() -> AudioFrame {
|
||||
let samples = OUTPUT_RATE as usize / PACKETS_PER_SECOND * CHANNELS as usize;
|
||||
let mut encoder = Encoder::new(OUTPUT_RATE, Stereo, LowDelay).unwrap();
|
||||
AudioFrame {
|
||||
data: encoder
|
||||
.encode_vec_float(&vec![SAMPLE_VALUE; samples], MAX_PACKET_BYTES)
|
||||
.unwrap()
|
||||
.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn failed_output(candidate: &mut AudioHandler, _: AudioFormat) -> ResultType<()> {
|
||||
candidate.sample_rate = (INPUT_RATE, INPUT_RATE);
|
||||
candidate.device_channel = MONO_CHANNELS;
|
||||
candidate
|
||||
.audio_buffer
|
||||
.resize(INPUT_RATE as _, MONO_CHANNELS as _);
|
||||
candidate
|
||||
.playback_status
|
||||
.ready
|
||||
.store(false, Ordering::Release);
|
||||
Err(anyhow!("Injected playback failure"))
|
||||
}
|
||||
|
||||
fn format(sample_rate: u32, channels: u16) -> AudioFormat {
|
||||
AudioFormat {
|
||||
sample_rate,
|
||||
channels: u32::from(channels),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_format_failure_preserves_playback_and_resampler_history() {
|
||||
let (mut handler, dropped) = active_handler(INPUT_RATE);
|
||||
let (mut reference, _) = active_handler(INPUT_RATE);
|
||||
let (mut retained_decoder, _) = active_handler(INPUT_RATE);
|
||||
retained_decoder.handle_frame(audio_frame());
|
||||
retained_decoder.handle_frame(audio_frame());
|
||||
handler.handle_frame(audio_frame());
|
||||
reference.handle_frame(audio_frame());
|
||||
let buffer = handler.audio_buffer.0.clone();
|
||||
let status = handler.playback_status.clone();
|
||||
|
||||
handler.handle_format_with_start(format(INPUT_RATE, CHANNELS), failed_output);
|
||||
reference.audio_decoder = Some(decoder(INPUT_RATE));
|
||||
handler.handle_frame(audio_frame());
|
||||
reference.handle_frame(audio_frame());
|
||||
|
||||
assert!(!dropped.load(Ordering::SeqCst));
|
||||
assert!(Arc::ptr_eq(&buffer, &handler.audio_buffer.0));
|
||||
assert!(Arc::ptr_eq(&status, &handler.playback_status));
|
||||
assert_eq!(handler.sample_rate, (INPUT_RATE, OUTPUT_RATE));
|
||||
assert_eq!(handler.device_channel, CHANNELS);
|
||||
assert!(handler.playback_status.ready.load(Ordering::Acquire));
|
||||
let expected = drain_audio(&reference);
|
||||
let actual = drain_audio(&handler);
|
||||
assert!(!actual.is_empty());
|
||||
assert_ne!(drain_audio(&retained_decoder), expected);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
fn drain_audio(handler: &AudioHandler) -> Vec<f32> {
|
||||
handler.audio_buffer.0.lock().unwrap().pop_iter().collect()
|
||||
}
|
||||
+107
-16
@@ -34,8 +34,6 @@ const CLIPBOARD_FORMAT_EXCEL_XML_SPREADSHEET: &'static str = "XML Spreadsheet";
|
||||
#[cfg(not(target_os = "android"))]
|
||||
lazy_static::lazy_static! {
|
||||
static ref ARBOARD_MTX: Arc<Mutex<()>> = Arc::new(Mutex::new(()));
|
||||
// cache the clipboard msg
|
||||
static ref LAST_MULTI_CLIPBOARDS: Arc<Mutex<MultiClipboards>> = Arc::new(Mutex::new(MultiClipboards::new()));
|
||||
// For updating in server and getting content in cm.
|
||||
// Clipboard on Linux is "server--clients" mode.
|
||||
// The clipboard content is owned by the server and passed to the clients when requested.
|
||||
@@ -79,8 +77,7 @@ pub fn check_clipboard(
|
||||
side: ClipboardSide,
|
||||
force: bool,
|
||||
) -> Option<Message> {
|
||||
let (msg, clipboards) = read_clipboard_message(ctx, side, force)?;
|
||||
*LAST_MULTI_CLIPBOARDS.lock().unwrap() = clipboards;
|
||||
let (msg, _) = read_clipboard_message(ctx, side, force)?;
|
||||
Some(msg)
|
||||
}
|
||||
|
||||
@@ -564,18 +561,25 @@ pub fn get_current_clipboard_msg(
|
||||
peer_platform: &str,
|
||||
side: ClipboardSide,
|
||||
) -> Option<Message> {
|
||||
let mut multi_clipboards = LAST_MULTI_CLIPBOARDS.lock().unwrap();
|
||||
if multi_clipboards.clipboards.is_empty() {
|
||||
let mut ctx = ClipboardContext::new().ok()?;
|
||||
*multi_clipboards = proto::create_multi_clipboards(ctx.get(side, true).ok()?);
|
||||
// Clipboard changes can be skipped while synchronization is disabled.
|
||||
#[cfg(target_os = "linux")]
|
||||
if !clipboard_listener::is_ready() {
|
||||
log::error!("Cannot read initial clipboard before the listener is ready");
|
||||
return None;
|
||||
}
|
||||
let ctx = match ClipboardContext::new() {
|
||||
Ok(ctx) => ctx,
|
||||
Err(err) => {
|
||||
log::error!("Failed to create clipboard context for initial sync: {}", err);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let (msg, multi_clipboards) = read_clipboard_message(&mut Some(ctx), side, true)?;
|
||||
if multi_clipboards.clipboards.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if is_support_multi_clipboard(peer_version, peer_platform) {
|
||||
let mut msg = Message::new();
|
||||
msg.set_multi_clipboards(multi_clipboards.clone());
|
||||
Some(msg)
|
||||
} else {
|
||||
// Find the first text clipboard and send it.
|
||||
@@ -888,10 +892,13 @@ pub fn get_clipboards_msg(client: bool) -> Option<Message> {
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub mod clipboard_listener {
|
||||
use clipboard_master::{CallbackResult, ClipboardHandler, Master, Shutdown};
|
||||
#[cfg(target_os = "linux")]
|
||||
use hbb_common::tokio::sync::watch;
|
||||
use hbb_common::{bail, log, ResultType};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
sync::mpsc::{channel, Sender},
|
||||
sync::{Arc, Mutex},
|
||||
thread::JoinHandle,
|
||||
@@ -901,15 +908,83 @@ pub mod clipboard_listener {
|
||||
pub static ref CLIPBOARD_LISTENER: Arc<Mutex<ClipboardListener>> = Default::default();
|
||||
}
|
||||
|
||||
static CLIPBOARD_GENERATION: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
pub enum ClipboardEvent {
|
||||
Changed,
|
||||
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
|
||||
InitialSelection,
|
||||
Stop,
|
||||
StopWithError(io::Error),
|
||||
}
|
||||
|
||||
pub fn current_generation() -> usize {
|
||||
CLIPBOARD_GENERATION.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn is_ready() -> bool {
|
||||
let listener = CLIPBOARD_LISTENER.lock().unwrap();
|
||||
let ready = listener
|
||||
.ready
|
||||
.as_ref()
|
||||
.map(|ready| *ready.borrow())
|
||||
.unwrap_or(false);
|
||||
ready
|
||||
&& listener
|
||||
.handle
|
||||
.as_ref()
|
||||
.map(|(_, h)| !h.is_finished())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub async fn wait_for_ready() -> ResultType<()> {
|
||||
let Some(mut ready) = CLIPBOARD_LISTENER.lock().unwrap().ready.clone() else {
|
||||
bail!("Clipboard listener has not started");
|
||||
};
|
||||
let is_ready = *ready.borrow_and_update();
|
||||
if !is_ready {
|
||||
ready.changed().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Handler {
|
||||
subscribers: Arc<Mutex<HashMap<String, Sender<CallbackResult>>>>,
|
||||
subscribers: Arc<Mutex<HashMap<String, Sender<ClipboardEvent>>>>,
|
||||
#[cfg(target_os = "linux")]
|
||||
ready: Option<watch::Sender<bool>>,
|
||||
}
|
||||
|
||||
impl ClipboardHandler for Handler {
|
||||
#[cfg(target_os = "linux")]
|
||||
fn on_clipboard_ready(&mut self) {
|
||||
// A restart must invalidate older snapshots, including on X11 or an empty selection.
|
||||
CLIPBOARD_GENERATION.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(tx) = self.ready.take() {
|
||||
if let Err(err) = tx.send(true) {
|
||||
log::debug!("Failed to report clipboard listener readiness: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_clipboard_change(&mut self) -> CallbackResult {
|
||||
// Empty or unsupported contents still invalidate an initial snapshot.
|
||||
CLIPBOARD_GENERATION.fetch_add(1, Ordering::SeqCst);
|
||||
let sub_lock = self.subscribers.lock().unwrap();
|
||||
for tx in sub_lock.values() {
|
||||
tx.send(CallbackResult::Next).ok();
|
||||
tx.send(ClipboardEvent::Changed).ok();
|
||||
}
|
||||
CallbackResult::Next
|
||||
}
|
||||
|
||||
fn on_clipboard_initial_selection(&mut self) -> CallbackResult {
|
||||
// Only client file sync consumes this event; text initial sync is per session.
|
||||
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
|
||||
for tx in self.subscribers.lock().unwrap().values() {
|
||||
if let Err(err) = tx.send(ClipboardEvent::InitialSelection) {
|
||||
log::debug!("Failed to notify initial clipboard selection: {}", err);
|
||||
}
|
||||
}
|
||||
CallbackResult::Next
|
||||
}
|
||||
@@ -918,23 +993,30 @@ pub mod clipboard_listener {
|
||||
let msg = format!("Clipboard listener error: {}", error);
|
||||
let sub_lock = self.subscribers.lock().unwrap();
|
||||
for tx in sub_lock.values() {
|
||||
tx.send(CallbackResult::StopWithError(io::Error::new(
|
||||
tx.send(ClipboardEvent::StopWithError(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
msg.clone(),
|
||||
)))
|
||||
.ok();
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
if self.ready.is_some() {
|
||||
// Subscribers must receive the error before a failed startup stops.
|
||||
return CallbackResult::StopWithError(error);
|
||||
}
|
||||
CallbackResult::Next
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ClipboardListener {
|
||||
subscribers: Arc<Mutex<HashMap<String, Sender<CallbackResult>>>>,
|
||||
subscribers: Arc<Mutex<HashMap<String, Sender<ClipboardEvent>>>>,
|
||||
handle: Option<(Shutdown, JoinHandle<()>)>,
|
||||
#[cfg(target_os = "linux")]
|
||||
ready: Option<watch::Receiver<bool>>,
|
||||
}
|
||||
|
||||
pub fn subscribe(name: String, tx: Sender<CallbackResult>) -> ResultType<()> {
|
||||
pub fn subscribe(name: String, tx: Sender<ClipboardEvent>) -> ResultType<()> {
|
||||
log::info!("Subscribe clipboard listener: {}", &name);
|
||||
let mut listener_lock = CLIPBOARD_LISTENER.lock().unwrap();
|
||||
listener_lock
|
||||
@@ -946,8 +1028,12 @@ pub mod clipboard_listener {
|
||||
cleanup_stale_listener(&mut listener_lock);
|
||||
if listener_lock.handle.is_none() {
|
||||
log::info!("Start clipboard listener thread");
|
||||
#[cfg(target_os = "linux")]
|
||||
let (tx_ready, rx_ready) = watch::channel(false);
|
||||
let handler = Handler {
|
||||
subscribers: listener_lock.subscribers.clone(),
|
||||
#[cfg(target_os = "linux")]
|
||||
ready: Some(tx_ready),
|
||||
};
|
||||
let (tx_start_res, rx_start_res) = channel();
|
||||
let h = start_clipboard_master_thread(handler, tx_start_res);
|
||||
@@ -962,6 +1048,11 @@ pub mod clipboard_listener {
|
||||
}
|
||||
};
|
||||
listener_lock.handle = Some((shutdown, h));
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// Initial-sync tasks await backend readiness without blocking the connection loop.
|
||||
listener_lock.ready = Some(rx_ready);
|
||||
}
|
||||
log::info!("Clipboard listener thread started");
|
||||
}
|
||||
|
||||
@@ -993,7 +1084,7 @@ pub mod clipboard_listener {
|
||||
let is_empty = {
|
||||
let mut sub_lock = listener_lock.subscribers.lock().unwrap();
|
||||
if let Some(tx) = sub_lock.remove(name) {
|
||||
tx.send(CallbackResult::Stop).ok();
|
||||
tx.send(ClipboardEvent::Stop).ok();
|
||||
}
|
||||
sub_lock.is_empty()
|
||||
};
|
||||
|
||||
+66
-3
@@ -224,6 +224,13 @@ pub fn msg_2_clip(msg: Cliprdr) -> Option<ClipboardFile> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_file_data_request(msg: &Cliprdr) -> bool {
|
||||
matches!(
|
||||
msg.union,
|
||||
Some(cliprdr::Union::FormatDataRequest(_)) | Some(cliprdr::Union::FileContentsRequest(_))
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "unix-file-copy-paste")]
|
||||
pub mod unix_file_clip {
|
||||
use super::*;
|
||||
@@ -314,7 +321,7 @@ pub mod unix_file_clip {
|
||||
requested_format_id: _requested_format_id,
|
||||
} => {
|
||||
log::debug!("requested format id: {}", _requested_format_id);
|
||||
let format_data = serv_files::get_file_list_pdu();
|
||||
let format_data = serv_files::get_file_list_pdu(conn_id);
|
||||
if !format_data.is_empty() {
|
||||
return vec![clip_2_msg(ClipboardFile::FormatDataResponse {
|
||||
msg_flags: 1,
|
||||
@@ -365,7 +372,8 @@ pub mod unix_file_clip {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested,
|
||||
..
|
||||
have_clip_data_id,
|
||||
clip_data_id,
|
||||
} => {
|
||||
log::debug!("file contents request: stream_id: {}, list_index: {}, dw_flags: {}, n_position_low: {}, n_position_high: {}, cb_requested: {}", stream_id, list_index, dw_flags, n_position_low, n_position_high, cb_requested);
|
||||
return serv_files::read_file_contents(
|
||||
@@ -376,12 +384,18 @@ pub mod unix_file_clip {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested,
|
||||
have_clip_data_id.then_some(clip_data_id),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|res| match res {
|
||||
Ok(data) => clip_2_msg(data),
|
||||
Err(e) => {
|
||||
log::error!("failed to read file contents: {:?}", e);
|
||||
hbb_common::throttled_log!(
|
||||
std::time::Duration::from_secs(5),
|
||||
error,
|
||||
"failed to read file contents: {:?}",
|
||||
e
|
||||
);
|
||||
resp_file_contents_fail(stream_id)
|
||||
}
|
||||
})
|
||||
@@ -433,3 +447,52 @@ pub mod unix_file_clip {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn is_request(clip: ClipboardFile) -> bool {
|
||||
match clip_2_msg(clip).union {
|
||||
Some(message::Union::Cliprdr(msg)) => is_file_data_request(&msg),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_file_data_request() {
|
||||
assert!(is_request(ClipboardFile::FormatDataRequest {
|
||||
requested_format_id: 0,
|
||||
}));
|
||||
assert!(is_request(ClipboardFile::FileContentsRequest {
|
||||
stream_id: 0,
|
||||
list_index: 0,
|
||||
dw_flags: 0,
|
||||
n_position_low: 0,
|
||||
n_position_high: 0,
|
||||
cb_requested: 0,
|
||||
have_clip_data_id: false,
|
||||
clip_data_id: 0,
|
||||
}));
|
||||
|
||||
// Messages that carry the peer's own clipboard files must stay allowed.
|
||||
assert!(!is_request(ClipboardFile::MonitorReady));
|
||||
assert!(!is_request(ClipboardFile::FormatList {
|
||||
format_list: vec![],
|
||||
}));
|
||||
assert!(!is_request(ClipboardFile::FormatListResponse {
|
||||
msg_flags: 0
|
||||
}));
|
||||
assert!(!is_request(ClipboardFile::FormatDataResponse {
|
||||
msg_flags: 0,
|
||||
format_data: vec![],
|
||||
}));
|
||||
assert!(!is_request(ClipboardFile::FileContentsResponse {
|
||||
msg_flags: 0,
|
||||
stream_id: 0,
|
||||
requested_data: vec![],
|
||||
}));
|
||||
assert!(!is_request(ClipboardFile::TryEmpty));
|
||||
assert!(!is_request(ClipboardFile::Files { files: vec![] }));
|
||||
}
|
||||
}
|
||||
|
||||
+604
-52
@@ -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";
|
||||
@@ -148,6 +149,24 @@ pub fn is_support_multi_ui_session_num(ver: i64) -> bool {
|
||||
ver >= hbb_common::get_version_number(MIN_VER_MULTI_UI_SESSION)
|
||||
}
|
||||
|
||||
/// Peers from the 1.5.0 release name a cursor by `cursor_content_id`; older ones by the
|
||||
/// platform handle, which apps mint anew for the same shape.
|
||||
#[inline]
|
||||
pub fn is_peer_naming_cursors_by_content(ver: i64) -> bool {
|
||||
ver >= hbb_common::get_version_number("1.5.0")
|
||||
}
|
||||
|
||||
/// One id per cursor look, however many handles a platform gives it. Held to 53 bits: the web
|
||||
/// client decodes a u64 into a JS number and drops the whole message when it does not fit.
|
||||
pub fn cursor_content_id(width: i32, height: i32, hotx: i32, hoty: i32, colors: &[u8]) -> u64 {
|
||||
let mut hasher = xxhash_rust::xxh3::Xxh3::new();
|
||||
for v in [width, height, hotx, hoty] {
|
||||
hasher.update(&v.to_le_bytes());
|
||||
}
|
||||
hasher.update(colors);
|
||||
hasher.digest() & ((1 << 53) - 1)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "unix-file-copy-paste")]
|
||||
pub fn is_support_file_copy_paste(ver: &str) -> bool {
|
||||
@@ -408,6 +427,11 @@ pub fn resample_channels(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "use_dasp", feature = "use_samplerate"))]
|
||||
compile_error!(
|
||||
"features `use_dasp` and `use_samplerate` are mutually exclusive; disable default features before selecting `use_samplerate`"
|
||||
);
|
||||
|
||||
#[cfg(feature = "use_dasp")]
|
||||
pub fn audio_resample(
|
||||
data: &[f32],
|
||||
@@ -444,7 +468,7 @@ pub fn audio_resample(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "use_samplerate")]
|
||||
#[cfg(all(feature = "use_samplerate", not(feature = "use_dasp")))]
|
||||
pub fn audio_resample(
|
||||
data: &[f32],
|
||||
sample_rate0: u32,
|
||||
@@ -1191,6 +1215,9 @@ pub fn get_local_option(key: &str) -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
if key == "lang" && (v == "pt" || v == "br") {
|
||||
return "pt-br".to_owned();
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -1239,6 +1266,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()
|
||||
@@ -1288,7 +1332,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(),
|
||||
@@ -1448,7 +1495,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),
|
||||
@@ -1460,7 +1510,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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1518,7 +1574,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
|
||||
@@ -1529,7 +1588,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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1586,7 +1651,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
|
||||
);
|
||||
@@ -1601,7 +1669,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,
|
||||
@@ -2074,6 +2148,13 @@ async fn secure_tcp_impl(conn: &mut Stream, key: &str, log_on_success: bool) ->
|
||||
if use_ws() {
|
||||
return Ok(());
|
||||
}
|
||||
key_exchange(conn, key, log_on_success).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// The server's key exchange on `conn`. `Ok(true)` once the stream is encrypted. `Ok(false)`
|
||||
/// when the server sent something else first, nothing parseable, or closed: `secure_tcp`
|
||||
/// tolerates that for servers from before the exchange, `secure_tcp_required` does not.
|
||||
async fn key_exchange(conn: &mut Stream, key: &str, log_on_success: bool) -> ResultType<bool> {
|
||||
let rs_pk = get_rs_pk(key);
|
||||
let Some(rs_pk) = rs_pk else {
|
||||
bail!("Handshake failed: invalid public key from rendezvous server");
|
||||
@@ -2088,20 +2169,50 @@ async fn secure_tcp_impl(conn: &mut Stream, key: &str, log_on_success: bool) ->
|
||||
}
|
||||
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");
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -2109,7 +2220,7 @@ async fn secure_tcp_impl(conn: &mut Stream, key: &str, log_on_success: bool) ->
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub async fn secure_tcp(conn: &mut Stream, key: &str) -> ResultType<()> {
|
||||
@@ -2120,6 +2231,22 @@ async fn secure_tcp_silent(conn: &mut Stream, key: &str) -> ResultType<()> {
|
||||
secure_tcp_impl(conn, key, false).await
|
||||
}
|
||||
|
||||
/// Like [`secure_tcp`], but returns only once the server's key exchange has actually encrypted
|
||||
/// the stream; a server that answers with anything else, or with nothing, is an error, so the
|
||||
/// caller can withhold what it was about to send instead of sending it in the clear.
|
||||
/// `secure_tcp` keeps tolerating such a server, which the paths from before the exchange depend
|
||||
/// on. WebSocket is treated as `secure_tcp` treats it, as a transport that is encrypted already.
|
||||
pub async fn secure_tcp_required(conn: &mut Stream, key: &str) -> ResultType<()> {
|
||||
if use_ws() {
|
||||
return Ok(());
|
||||
}
|
||||
if key_exchange(conn, key, true).await? {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("the rendezvous server did not complete the key exchange");
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_pk(pk: &[u8]) -> Option<[u8; 32]> {
|
||||
if pk.len() == 32 {
|
||||
@@ -2141,26 +2268,35 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the DTLS fingerprint a WebRTC peer signed into its identity is the one of the channel
|
||||
/// actually negotiated. An empty signed value binds nothing: on a WebRTC channel it is either a
|
||||
/// peer that could not sign one or a rendezvous/relay that stripped it, and both fail closed.
|
||||
pub fn dtls_fingerprint_bound(signed_fp: &str, actual_fp: &str) -> bool {
|
||||
!signed_fp.is_empty() && signed_fp == actual_fp
|
||||
}
|
||||
|
||||
pub fn create_symmetric_key_msg(their_pk_b: [u8; 32]) -> (Bytes, Bytes, secretbox::Key) {
|
||||
let their_pk_b = box_::PublicKey(their_pk_b);
|
||||
let (our_pk_b, out_sk_b) = box_::gen_keypair();
|
||||
@@ -2492,45 +2628,42 @@ async fn stun_ipv6_test(stun_server: String) -> ResultType<(SocketAddr, String)>
|
||||
})
|
||||
}
|
||||
|
||||
/// A global address to ask the kernel for a route to; libwebrtc's QueryDefaultLocalAddress asks
|
||||
/// for the same one. Nothing is ever sent to it.
|
||||
const IPV6_ROUTE_PROBE: std::net::Ipv6Addr =
|
||||
std::net::Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888);
|
||||
/// The public IPv6 address the STUN servers report is looked for in the background, and for no
|
||||
/// longer than this: a probe that outlived the minute could write an earlier network's address
|
||||
/// over a later probe's.
|
||||
const STUN_IPV6_TIMEOUT_MS: u64 = 5_000;
|
||||
|
||||
async fn test_bind_ipv6() -> ResultType<SocketAddr> {
|
||||
use hbb_common::futures::future::FutureExt;
|
||||
let local_addr = SocketAddr::from(([0u16; 8], 0)); // [::]:0
|
||||
let socket = UdpSocket::bind(local_addr).await?;
|
||||
// Nothing is sent - `connect` only makes the kernel pick a route and a source address - so any
|
||||
// resolvable target answers equally and the whole cost is DNS. Race the lookups rather than
|
||||
// walk them: this is awaited inline on the connection path, not every STUN host publishes a
|
||||
// AAAA, and one resolver that hangs must not decide whether this host has v6.
|
||||
let lookups = hbb_common::webrtc::WebRTCStream::default_stun_servers()
|
||||
.into_iter()
|
||||
.map(|stun| {
|
||||
(async move {
|
||||
let addr = tokio::net::lookup_host(&stun)
|
||||
.await?
|
||||
.find(|x| x.is_ipv6())
|
||||
.ok_or_else(|| {
|
||||
anyhow!("Failed to resolve STUN ipv6 server address: {}", stun)
|
||||
})?;
|
||||
Ok::<SocketAddr, hbb_common::anyhow::Error>(addr)
|
||||
})
|
||||
.boxed()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let (addr, _) = hbb_common::futures::future::select_ok(lookups).await?;
|
||||
socket.connect(addr).await?;
|
||||
// Nothing is sent - `connect` only makes the kernel pick a route and a source address - so
|
||||
// the target can be any global address, and given as a number it is: this is awaited on the
|
||||
// connection path, and resolving a STUN host's name first was the one thing on it that
|
||||
// could wait on the network - for as long as the resolver takes, when there is none.
|
||||
socket
|
||||
.connect(SocketAddr::from((IPV6_ROUTE_PROBE, 53)))
|
||||
.await?;
|
||||
Ok(socket.local_addr()?)
|
||||
}
|
||||
|
||||
pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
|
||||
if PUBLIC_IPV6_ADDR
|
||||
.lock()
|
||||
.unwrap()
|
||||
.1
|
||||
.map(|x| x.elapsed().as_secs() < 60)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return None;
|
||||
// One look and one claim of the minute, under one lock: two connections arriving
|
||||
// together would otherwise both find it over and both probe.
|
||||
let mut cached = PUBLIC_IPV6_ADDR.lock().unwrap();
|
||||
if cached
|
||||
.1
|
||||
.map(|x| x.elapsed().as_secs() < 60)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
cached.1 = Some(Instant::now());
|
||||
}
|
||||
PUBLIC_IPV6_ADDR.lock().unwrap().1 = Some(Instant::now());
|
||||
|
||||
match test_bind_ipv6().await {
|
||||
Ok(mut addr) => {
|
||||
@@ -2587,8 +2720,8 @@ pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
|
||||
.map(|stun| stun_ipv6_test(stun).boxed())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
match select_ok(tests).await {
|
||||
Ok(res) => {
|
||||
match hbb_common::timeout(STUN_IPV6_TIMEOUT_MS, select_ok(tests)).await {
|
||||
Ok(Ok(res)) => {
|
||||
let mut addr = res.0 .0;
|
||||
addr.set_port(0); // Set port to 0 to avoid conflicts
|
||||
PUBLIC_IPV6_ADDR.lock().unwrap().0 = Some(addr);
|
||||
@@ -2598,9 +2731,12 @@ pub async fn test_ipv6() -> Option<tokio::task::JoinHandle<()>> {
|
||||
addr
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
Ok(Err(e)) => {
|
||||
log::error!("Failed to get public IPv6 address: {}", e);
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!("No STUN server answered for IPv6 within {STUN_IPV6_TIMEOUT_MS}ms");
|
||||
}
|
||||
};
|
||||
}))
|
||||
}
|
||||
@@ -2818,6 +2954,16 @@ mod tests {
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn a_cursor_content_id_fits_a_web_client_number() {
|
||||
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
|
||||
for colors in [&b"arrow"[..], b"beam", b"hand", b""] {
|
||||
for hotx in 0..64 {
|
||||
assert!(cursor_content_id(32, 32, hotx, 0, colors) <= MAX_SAFE_INTEGER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_timestamp_secs() -> u128 {
|
||||
(std::time::SystemTime::UNIX_EPOCH
|
||||
@@ -3068,6 +3214,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);
|
||||
@@ -3258,4 +3419,395 @@ mod tests {
|
||||
assert_eq!(combined_mask & MOUSE_TYPE_MASK, MOUSE_TYPE_DOWN);
|
||||
assert_eq!(combined_mask >> 3, MOUSE_BUTTON_LEFT | MOUSE_BUTTON_RIGHT);
|
||||
}
|
||||
|
||||
/// A stand-in rendezvous server on loopback: accepts one connection and hands it to `serve`.
|
||||
async fn rendezvous_stub<F, Fut>(serve: F) -> String
|
||||
where
|
||||
F: FnOnce(hbb_common::tcp::FramedStream) -> Fut + Send + 'static,
|
||||
Fut: std::future::Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let listener = hbb_common::tcp::new_listener("127.0.0.1:0", false)
|
||||
.await
|
||||
.unwrap();
|
||||
let host = listener.local_addr().unwrap().to_string();
|
||||
tokio::spawn(async move {
|
||||
if let Ok((stream, addr)) = listener.accept().await {
|
||||
serve(hbb_common::tcp::FramedStream::from(stream, addr)).await;
|
||||
}
|
||||
});
|
||||
host
|
||||
}
|
||||
|
||||
fn server_key() -> (String, sign::SecretKey) {
|
||||
let (pk, sk) = sign::gen_keypair();
|
||||
(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
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_secure_tcp_required_refuses_a_server_without_the_exchange() {
|
||||
let (key, _) = server_key();
|
||||
// A server from before the exchange answers the first message with something else.
|
||||
let serve = |mut s: hbb_common::tcp::FramedStream| async move {
|
||||
let mut msg = RendezvousMessage::new();
|
||||
msg.set_register_peer_response(RegisterPeerResponse::new());
|
||||
s.send(&msg).await.unwrap();
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
};
|
||||
let host = rendezvous_stub(serve).await;
|
||||
let mut conn = connect(&host).await;
|
||||
assert!(secure_tcp_required(&mut conn, &key).await.is_err());
|
||||
assert!(!conn.is_secured());
|
||||
// The legacy call tolerates the same server, and the stream stays in the clear.
|
||||
let host = rendezvous_stub(serve).await;
|
||||
let mut conn = connect(&host).await;
|
||||
secure_tcp(&mut conn, &key).await.unwrap();
|
||||
assert!(!conn.is_secured());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_secure_tcp_required_refuses_a_closed_connection() {
|
||||
let (key, _) = server_key();
|
||||
let host = rendezvous_stub(|s| async move { drop(s) }).await;
|
||||
let mut conn = connect(&host).await;
|
||||
assert!(secure_tcp_required(&mut conn, &key).await.is_err());
|
||||
assert!(!conn.is_secured());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_secure_tcp_required_accepts_a_completed_exchange() {
|
||||
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()],
|
||||
..Default::default()
|
||||
});
|
||||
s.send(&msg).await.unwrap();
|
||||
// The client's reply must decode to a key with the ephemeral secret half.
|
||||
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");
|
||||
};
|
||||
hbb_common::tcp::Encrypt::decode(&ex.keys[1], &ex.keys[0], &eph_sk).unwrap();
|
||||
})
|
||||
.await;
|
||||
let mut conn = connect(&host).await;
|
||||
secure_tcp_required(&mut conn, &key).await.unwrap();
|
||||
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();
|
||||
let fp = "sha-256 0A:1B:2C";
|
||||
let signed = sign::sign(
|
||||
&IdPk {
|
||||
id: "123456789".to_owned(),
|
||||
pk: Bytes::from(vec![7u8; 32]),
|
||||
dtls_fingerprint: fp.to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
.write_to_bytes()
|
||||
.unwrap(),
|
||||
&sk,
|
||||
);
|
||||
|
||||
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);
|
||||
assert!(dtls_fingerprint_bound(&signed_fp, fp));
|
||||
assert!(!dtls_fingerprint_bound(&signed_fp, "sha-256 0A:1B:2D"));
|
||||
assert!(!dtls_fingerprint_bound("", ""));
|
||||
|
||||
// The fingerprint is under the signature: a blob verified with another key yields
|
||||
// nothing, and one whose payload was edited in transit fails verification.
|
||||
let (other_pk, _) = sign::gen_keypair();
|
||||
assert!(decode_id_pk_dtls(&signed, &other_pk).is_err());
|
||||
let mut tampered = signed.clone();
|
||||
let last = tampered.len() - 1;
|
||||
tampered[last] ^= 1;
|
||||
assert!(decode_id_pk_dtls(&tampered, &pk).is_err());
|
||||
|
||||
// `decode_id_pk` is the same blob minus the fingerprint, so the field is invisible to
|
||||
// non-WebRTC handshakes.
|
||||
assert_eq!(decode_id_pk(&signed, &pk).unwrap(), (id, their_pk));
|
||||
}
|
||||
|
||||
// The route probe is awaited on the connection path, so whatever it finds - an address, or
|
||||
// no IPv6 route on this machine - it finds without waiting on the network.
|
||||
#[tokio::test]
|
||||
async fn test_ipv6_route_probe_does_not_wait_on_the_network() {
|
||||
assert!(hbb_common::timeout(1_000, test_bind_ipv6()).await.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
+18
-2
@@ -1,6 +1,9 @@
|
||||
use hbb_common::{
|
||||
bail,
|
||||
base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _},
|
||||
base64::{
|
||||
engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD},
|
||||
Engine as _,
|
||||
},
|
||||
sodiumoxide::crypto::sign,
|
||||
ResultType,
|
||||
};
|
||||
@@ -25,7 +28,9 @@ fn get_custom_server_from_config_string(s: &str) -> ResultType<CustomServer> {
|
||||
12, 46, 129, 83, 17, 84, 193, 119, 197, 130, 103,
|
||||
];
|
||||
let pk = sign::PublicKey(*PK);
|
||||
let data = URL_SAFE_NO_PAD.decode(tmp)?;
|
||||
let data = URL_SAFE_NO_PAD
|
||||
.decode(&tmp)
|
||||
.or_else(|_| URL_SAFE.decode(&tmp))?;
|
||||
if let Ok(lic) = serde_json::from_slice::<CustomServer>(&data) {
|
||||
return Ok(lic);
|
||||
}
|
||||
@@ -215,5 +220,16 @@ mod test {
|
||||
assert_eq!(
|
||||
get_custom_server_from_string("rustdesk-licensed--0nI900VsFHZVBVdIlncwpHS4V0bOZ0dtVldrpVO4JHdCp0YV5WdzUGZzdnYRVjI6ISeltmIsISMuEjLx4SMiojI0N3boJye--.exe")
|
||||
.unwrap(), lic);
|
||||
// padded base64 (one '=' after reversal) is accepted, wrong padding is not
|
||||
assert_eq!(
|
||||
get_custom_server_from_string("rustdesk-licensed-=0nI900VsFHZVBVdIlncwpHS4V0bOZ0dtVldrpVO4JHdCp0YV5WdzUGZzdnYRVjI6ISeltmIsISMuEjLx4SMiojI0N3boJye.exe")
|
||||
.unwrap(), lic);
|
||||
assert!(
|
||||
get_custom_server_from_string("rustdesk-licensed-==0nI900VsFHZVBVdIlncwpHS4V0bOZ0dtVldrpVO4JHdCp0YV5WdzUGZzdnYRVjI6ISeltmIsISMuEjLx4SMiojI0N3boJye.exe")
|
||||
.is_err());
|
||||
// bare string as passed to `--config`
|
||||
assert_eq!(
|
||||
get_custom_server_from_string("=0nI900VsFHZVBVdIlncwpHS4V0bOZ0dtVldrpVO4JHdCp0YV5WdzUGZzdnYRVjI6ISeltmIsISMuEjLx4SMiojI0N3boJye.exe")
|
||||
.unwrap(), lic);
|
||||
}
|
||||
}
|
||||
|
||||
+26
-17
@@ -105,6 +105,16 @@ fn load_plugin_in_app_path(dll_name: &str) -> Result<Library, LibError> {
|
||||
#[cfg(not(windows))]
|
||||
#[no_mangle]
|
||||
pub extern "C" fn rustdesk_core_main() -> bool {
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
use hbb_common::libc;
|
||||
|
||||
// Native runners bypass Rust's startup, which normally ignores SIGPIPE.
|
||||
if unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) } == libc::SIG_ERR {
|
||||
eprintln!("Failed to ignore SIGPIPE: {}", std::io::Error::last_os_error());
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
if crate::core_main::core_main().is_some() {
|
||||
return true;
|
||||
@@ -641,24 +651,21 @@ impl FlutterHandler {
|
||||
}
|
||||
|
||||
impl InvokeUiSession for FlutterHandler {
|
||||
// On the event stream, so that it keeps its order with the cursor_id events around it.
|
||||
fn set_cursor_data(&self, cd: CursorData) {
|
||||
let colors = &cd.colors;
|
||||
self.push_event(
|
||||
"cursor_data",
|
||||
&[
|
||||
("id", &cd.id.to_string()),
|
||||
("hotx", &cd.hotx.to_string()),
|
||||
("hoty", &cd.hoty.to_string()),
|
||||
("width", &cd.width.to_string()),
|
||||
("height", &cd.height.to_string()),
|
||||
("scale", &cd.scale.to_string()),
|
||||
(
|
||||
"colors",
|
||||
&serde_json::ser::to_string(&colors).unwrap_or("".to_owned()),
|
||||
),
|
||||
],
|
||||
&[],
|
||||
);
|
||||
let colors = cd.colors.to_vec();
|
||||
for session in self.session_handlers.read().unwrap().values() {
|
||||
if let Some(stream) = &session.event_stream {
|
||||
stream.add(EventToUI::Cursor {
|
||||
id: cd.id.to_string(),
|
||||
hotx: cd.hotx,
|
||||
hoty: cd.hoty,
|
||||
width: cd.width,
|
||||
height: cd.height,
|
||||
colors: colors.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_cursor_id(&self, id: String) {
|
||||
@@ -1408,6 +1415,7 @@ fn try_send_close_event(event_stream: &Option<StreamSink<EventToUI>>) {
|
||||
pub fn update_text_clipboard_required() {
|
||||
let is_required = sessions::get_sessions()
|
||||
.iter()
|
||||
.filter(|s| s.connection_round_state.lock().unwrap().is_connected())
|
||||
.any(|s| s.is_default() && s.is_text_clipboard_required());
|
||||
#[cfg(target_os = "android")]
|
||||
let _ = scrap::android::ffi::call_clipboard_manager_enable_client_clipboard(is_required);
|
||||
@@ -1418,6 +1426,7 @@ pub fn update_text_clipboard_required() {
|
||||
pub fn update_file_clipboard_required() {
|
||||
let is_required = sessions::get_sessions()
|
||||
.iter()
|
||||
.filter(|s| s.connection_round_state.lock().unwrap().is_connected())
|
||||
.any(|s| s.is_default() && s.is_file_clipboard_required());
|
||||
Client::set_is_file_clipboard_required(is_required);
|
||||
}
|
||||
|
||||
@@ -97,6 +97,16 @@ pub enum EventToUI {
|
||||
Event(String),
|
||||
Rgba(usize),
|
||||
Texture(usize, bool), // (display, gpu_texture)
|
||||
// A shape's RGBA as bytes: as text it was four times the size and parsed on the UI thread.
|
||||
// The id stays text, since the peer's ids can exceed Dart's int.
|
||||
Cursor {
|
||||
id: String,
|
||||
hotx: i32,
|
||||
hoty: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
colors: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn host_stop_system_key_propagate(_stopped: bool) {
|
||||
@@ -201,6 +211,34 @@ pub fn session_start_with_displays(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// A cursor shape the core keeps, as RGBA, for a window that has to draw it again.
|
||||
pub struct CursorShape {
|
||||
pub hotx: i32,
|
||||
pub hoty: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub colors: Vec<u8>,
|
||||
}
|
||||
|
||||
pub fn session_get_cursor_shape(session_id: SessionID, id: String) -> Option<CursorShape> {
|
||||
let id = id.parse::<u64>().ok()?;
|
||||
let session = sessions::get_session_by_session_id(&session_id)?;
|
||||
let shape = session.cursor_shapes.read().unwrap().get(&id).cloned()?;
|
||||
match crate::client::io_loop::kept_cursor_rgba(shape) {
|
||||
Ok(cd) => Some(CursorShape {
|
||||
hotx: cd.hotx,
|
||||
hoty: cd.hoty,
|
||||
width: cd.width,
|
||||
height: cd.height,
|
||||
colors: cd.colors.to_vec(),
|
||||
}),
|
||||
Err(err) => {
|
||||
log::warn!("Kept cursor {id} failed to decode: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn session_get_remember(session_id: SessionID) -> Option<bool> {
|
||||
if let Some(session) = sessions::get_session_by_session_id(&session_id) {
|
||||
Some(session.get_remember())
|
||||
|
||||
@@ -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;
|
||||
|
||||
+142
-2
@@ -540,7 +540,17 @@ pub enum Data {
|
||||
/// Service -> client: a frame header; the packed BGRA pixels follow via `send_raw()`.
|
||||
/// CPU-fallback path (no render node, or no transferable dma-buf): pixels cross the wire.
|
||||
#[cfg(all(target_os = "linux", feature = "drm"))]
|
||||
DrmFrame { width: u32, height: u32 },
|
||||
DrmFrame {
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// See `DmabufDesc::plane_rotation`; absent from a producer older than this field.
|
||||
#[serde(default)]
|
||||
plane_rotation: Option<u32>,
|
||||
/// See `DmabufDesc::cursor_pos`: the cursor plane position read right after this frame,
|
||||
/// or `None` when the cursor is hidden, the read failed or the producer predates the field.
|
||||
#[serde(default)]
|
||||
cursor_pos: Option<(i32, i32)>,
|
||||
},
|
||||
/// Service -> client: a zero-copy dma-buf frame descriptor. The scanout fd is NOT a field; when
|
||||
/// `desc.has_fd` it rides an SCM_RIGHTS ancillary message on the same `DrmConn::send_msg`, and
|
||||
/// there is NO trailing `send_raw()` body. The unprivileged `--server` imports the fd and does
|
||||
@@ -555,9 +565,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?;
|
||||
@@ -1497,7 +1527,13 @@ pub async fn start_pa() {
|
||||
None, // Use default buffering attributes
|
||||
) {
|
||||
Ok(s) => loop {
|
||||
if let Ok(_) = s.read(&mut buf) {
|
||||
// A dead pulse handle fails every read at once, so ignoring the
|
||||
// error left nothing pacing this loop and it burned a core.
|
||||
if let Err(err) = s.read(&mut buf) {
|
||||
log::error!("Failed to read audio data:{}", err);
|
||||
break;
|
||||
}
|
||||
{
|
||||
let out =
|
||||
if buf.iter().filter(|x| **x != 0).next().is_none() {
|
||||
vec![]
|
||||
@@ -2304,4 +2340,108 @@ 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:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame from a producer that predates the plane rotation reads as `None`, in the cpu frame
|
||||
/// header and in the dma-buf descriptor: the root service and the `--server` are upgraded
|
||||
/// separately, and `None` keeps the previous rule.
|
||||
#[cfg(all(target_os = "linux", feature = "drm"))]
|
||||
#[test]
|
||||
fn a_frame_without_a_plane_rotation_reads_as_none() {
|
||||
let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#;
|
||||
match serde_json::from_str::<Data>(legacy).expect("legacy DrmFrame must deserialize") {
|
||||
Data::DrmFrame { plane_rotation, .. } => assert_eq!(plane_rotation, None),
|
||||
other => panic!("expected DrmFrame, got {other:?}"),
|
||||
}
|
||||
let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"plane_rotation":4}}"#;
|
||||
match serde_json::from_str::<Data>(modern).expect("modern DrmFrame must deserialize") {
|
||||
Data::DrmFrame { plane_rotation, .. } => assert_eq!(plane_rotation, Some(4)),
|
||||
other => panic!("expected DrmFrame, got {other:?}"),
|
||||
}
|
||||
let desc = DmabufDesc {
|
||||
buffer_id: 0,
|
||||
width: 4,
|
||||
height: 4,
|
||||
format: 0,
|
||||
modifier: 0,
|
||||
fb_id: 0,
|
||||
num_planes: 1,
|
||||
offsets: [0; 4],
|
||||
pitches: [16, 0, 0, 0],
|
||||
hdr_eotf: 0,
|
||||
hdr_max_nits: 0,
|
||||
has_fd: false,
|
||||
plane_rotation: Some(4),
|
||||
cursor_pos: None,
|
||||
};
|
||||
let mut value = serde_json::to_value(&desc).unwrap();
|
||||
assert!(value.as_object_mut().unwrap().remove("plane_rotation").is_some());
|
||||
let legacy: DmabufDesc =
|
||||
serde_json::from_value(value).expect("legacy DmabufDesc must deserialize");
|
||||
assert_eq!(legacy.plane_rotation, None);
|
||||
}
|
||||
|
||||
/// A frame header from a producer that predates the cursor plane position reads as `None`;
|
||||
/// a producer that sends one is read back exactly. A pin, not a gate: the consumer only ever
|
||||
/// measures against `Some`.
|
||||
#[cfg(all(target_os = "linux", feature = "drm"))]
|
||||
#[test]
|
||||
fn a_drm_frame_without_a_cursor_position_reads_as_none() {
|
||||
let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#;
|
||||
match serde_json::from_str::<Data>(legacy).expect("legacy DrmFrame must deserialize") {
|
||||
Data::DrmFrame {
|
||||
width,
|
||||
height,
|
||||
cursor_pos,
|
||||
..
|
||||
} => {
|
||||
assert_eq!((width, height), (8, 8));
|
||||
assert_eq!(cursor_pos, None);
|
||||
}
|
||||
other => panic!("expected DrmFrame, got {other:?}"),
|
||||
}
|
||||
let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"cursor_pos":[3,4]}}"#;
|
||||
match serde_json::from_str::<Data>(modern).expect("modern DrmFrame must deserialize") {
|
||||
Data::DrmFrame { cursor_pos, .. } => assert_eq!(cursor_pos, Some((3, 4))),
|
||||
other => panic!("expected DrmFrame, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+191
-15
@@ -45,6 +45,21 @@ pub struct DmabufDesc {
|
||||
pub hdr_max_nits: u32,
|
||||
/// True: the fd rides this message's SCM_RIGHTS cmsg. False: import-once cache hit for `fb_id`.
|
||||
pub has_fd: bool,
|
||||
/// The DRM `rotation` bitmask the primary plane scanned this frame out with, from
|
||||
/// `drmtap_plane_rotation()` (libdrmtap 0.5.8); a plane without the property is reported as
|
||||
/// rotate-0. `None` when the library cannot say (older than 0.5.8, nothing bound, or the
|
||||
/// property set unreadable). A frame from a plane that rotated in hardware is already
|
||||
/// upright; one from a plane that did not is turned by the output transform. See
|
||||
/// `frame_transform`.
|
||||
#[serde(default)]
|
||||
pub plane_rotation: Option<u32>,
|
||||
/// Cursor plane position read right after this frame was grabbed, in scanout pixels of the
|
||||
/// display this stream shows, so a few ms newer than the frame. `None` means the cursor is
|
||||
/// hidden, the read failed or was rejected, or the producer predates this field. It rides
|
||||
/// the frame instead of a stream of its own so it cannot queue and cannot backpressure the
|
||||
/// capture worker; the consumer only acts on a position that held still for several frames.
|
||||
#[serde(default)]
|
||||
pub cursor_pos: Option<(i32, i32)>,
|
||||
}
|
||||
|
||||
pub(crate) fn drm_ipc_path() -> String {
|
||||
@@ -100,6 +115,11 @@ enum DrmProducerMsg {
|
||||
width: u32,
|
||||
height: u32,
|
||||
data: Bytes,
|
||||
/// See `DmabufDesc::plane_rotation`.
|
||||
plane_rotation: Option<u32>,
|
||||
/// See `DmabufDesc::cursor_pos`. The dmabuf path carries it inside the descriptor; this
|
||||
/// one has no descriptor, so it travels beside the pixels.
|
||||
cursor_pos: Option<(i32, i32)>,
|
||||
},
|
||||
Cursor {
|
||||
id: u64,
|
||||
@@ -107,10 +127,112 @@ enum DrmProducerMsg {
|
||||
height: u32,
|
||||
hotx: i32,
|
||||
hoty: i32,
|
||||
hot_measured: bool,
|
||||
colors: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Put this tick's cursor plane position on the frame it was read next to. The hidden sentinel
|
||||
/// carries no position; a shape message is left alone.
|
||||
fn stamp_cursor_pos(msg: &mut DrmProducerMsg, c: Option<&scrap::drm_reader::CursorSnapshot>) {
|
||||
let pos = c.and_then(|c| (c.id != scrap::drm_reader::HIDDEN_CURSOR_ID).then_some((c.x, c.y)));
|
||||
match msg {
|
||||
DrmProducerMsg::Frame { desc, .. } => desc.cursor_pos = pos,
|
||||
DrmProducerMsg::FrameCpu { cursor_pos, .. } => *cursor_pos = pos,
|
||||
DrmProducerMsg::Displays(_) | DrmProducerMsg::Cursor { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_pos_tests {
|
||||
use super::*;
|
||||
|
||||
fn desc() -> DmabufDesc {
|
||||
DmabufDesc {
|
||||
buffer_id: 0,
|
||||
width: 4,
|
||||
height: 4,
|
||||
format: 0,
|
||||
modifier: 0,
|
||||
fb_id: 0,
|
||||
num_planes: 1,
|
||||
offsets: [0; 4],
|
||||
pitches: [16, 0, 0, 0],
|
||||
hdr_eotf: 0,
|
||||
hdr_max_nits: 0,
|
||||
has_fd: false,
|
||||
plane_rotation: None,
|
||||
cursor_pos: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(id: u64) -> scrap::drm_reader::CursorSnapshot {
|
||||
scrap::drm_reader::CursorSnapshot {
|
||||
id,
|
||||
width: 2,
|
||||
height: 2,
|
||||
hotx: 0,
|
||||
hoty: 0,
|
||||
hot_measured: false,
|
||||
colors: vec![0; 16],
|
||||
x: 10,
|
||||
y: 20,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plane_position_rides_both_frame_kinds_and_a_hidden_cursor_rides_as_none() {
|
||||
let visible = snapshot(7);
|
||||
let hidden = snapshot(scrap::drm_reader::HIDDEN_CURSOR_ID);
|
||||
|
||||
let mut frame = DrmProducerMsg::Frame { desc: desc(), fd: None };
|
||||
stamp_cursor_pos(&mut frame, Some(&visible));
|
||||
assert!(matches!(&frame, DrmProducerMsg::Frame { desc, .. } if desc.cursor_pos == Some((10, 20))));
|
||||
stamp_cursor_pos(&mut frame, Some(&hidden));
|
||||
assert!(matches!(&frame, DrmProducerMsg::Frame { desc, .. } if desc.cursor_pos.is_none()));
|
||||
|
||||
let mut cpu = DrmProducerMsg::FrameCpu {
|
||||
width: 4,
|
||||
height: 4,
|
||||
data: Bytes::new(),
|
||||
plane_rotation: None,
|
||||
cursor_pos: None,
|
||||
};
|
||||
stamp_cursor_pos(&mut cpu, Some(&visible));
|
||||
assert!(matches!(&cpu, DrmProducerMsg::FrameCpu { cursor_pos: Some((10, 20)), .. }));
|
||||
stamp_cursor_pos(&mut cpu, None);
|
||||
assert!(matches!(&cpu, DrmProducerMsg::FrameCpu { cursor_pos: None, .. }));
|
||||
|
||||
let mut shape = DrmProducerMsg::Cursor {
|
||||
id: 7,
|
||||
width: 2,
|
||||
height: 2,
|
||||
hotx: 1,
|
||||
hoty: 1,
|
||||
hot_measured: false,
|
||||
colors: vec![0; 16],
|
||||
};
|
||||
stamp_cursor_pos(&mut shape, Some(&visible));
|
||||
assert!(matches!(&shape, DrmProducerMsg::Cursor { hotx: 1, hoty: 1, .. }));
|
||||
}
|
||||
|
||||
// A producer that predates the field: the descriptor arrives without it and reads as None.
|
||||
#[test]
|
||||
fn a_descriptor_without_a_cursor_position_reads_as_none() {
|
||||
let mut v = serde_json::to_value(desc()).unwrap();
|
||||
v.as_object_mut().unwrap().remove("cursor_pos").expect("the field is serialized");
|
||||
let d: DmabufDesc = serde_json::from_value(v).expect("a legacy descriptor must deserialize");
|
||||
assert_eq!(d.cursor_pos, None);
|
||||
let d: DmabufDesc = serde_json::from_value(serde_json::to_value(DmabufDesc {
|
||||
cursor_pos: Some((3, 4)),
|
||||
..desc()
|
||||
})
|
||||
.unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(d.cursor_pos, Some((3, 4)));
|
||||
}
|
||||
}
|
||||
|
||||
struct DrmStopGuard(std::sync::Arc<std::sync::atomic::AtomicBool>);
|
||||
impl Drop for DrmStopGuard {
|
||||
fn drop(&mut self) {
|
||||
@@ -915,6 +1037,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
|
||||
height,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
colors,
|
||||
} => {
|
||||
conn.send_msg(
|
||||
@@ -924,6 +1047,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
|
||||
height,
|
||||
hotx,
|
||||
hoty,
|
||||
hot_measured,
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -957,8 +1081,19 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
plane_rotation,
|
||||
cursor_pos,
|
||||
}) => {
|
||||
conn.send_msg(&Data::DrmFrame { width, height }, None).await?;
|
||||
conn.send_msg(
|
||||
&Data::DrmFrame {
|
||||
width,
|
||||
height,
|
||||
plane_rotation,
|
||||
cursor_pos,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
conn.send_raw(data).await?;
|
||||
credit -= 1; // one frame in flight until the consumer acks it
|
||||
}
|
||||
@@ -1027,12 +1162,13 @@ fn drm_capture_worker(
|
||||
let mut stalled: u32 = 0;
|
||||
let mut logged_first = false;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
let grabbed: Option<std::io::Result<DrmProducerMsg>> = if frames_gated.load(Ordering::Relaxed)
|
||||
let mut grabbed: Option<std::io::Result<DrmProducerMsg>> = if frames_gated.load(Ordering::Relaxed)
|
||||
{
|
||||
// `stalled` is left untouched because the device is healthy -- the task bounds this
|
||||
// state itself (CREDIT_STALL) since our watchdog cannot advance.
|
||||
None
|
||||
} else if use_dmabuf {
|
||||
// Read right after the grab: the library answers for the plane that grab read from.
|
||||
Some(match reader.grab_desc() {
|
||||
Ok((fd, d)) => Ok(DrmProducerMsg::Frame {
|
||||
desc: DmabufDesc {
|
||||
@@ -1048,21 +1184,38 @@ fn drm_capture_worker(
|
||||
hdr_eotf: d.hdr_eotf,
|
||||
hdr_max_nits: d.hdr_max_nits,
|
||||
has_fd: true, // every exported frame carries its fd; see the send below
|
||||
plane_rotation: reader.plane_rotation(),
|
||||
cursor_pos: None, // stamped below, from the one cursor read of this tick
|
||||
},
|
||||
fd: Some(fd),
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
})
|
||||
} else {
|
||||
Some(match reader.grab() {
|
||||
Ok((buf, w, h)) => Ok(DrmProducerMsg::FrameCpu {
|
||||
width: w as u32,
|
||||
height: h as u32,
|
||||
data: Bytes::copy_from_slice(buf),
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
})
|
||||
// The mapped buffer borrows the reader: copy it out, then take the rotation the grab
|
||||
// recorded.
|
||||
let copied = reader
|
||||
.grab()
|
||||
.map(|(buf, w, h)| (Bytes::copy_from_slice(buf), w as u32, h as u32));
|
||||
Some(copied.map(|(data, width, height)| DrmProducerMsg::FrameCpu {
|
||||
width,
|
||||
height,
|
||||
data,
|
||||
plane_rotation: reader.plane_rotation(),
|
||||
cursor_pos: None,
|
||||
}))
|
||||
};
|
||||
// ONE cursor read per tick, and none on a stalled or failed grab: the plane position rides
|
||||
// the frame it was read next to, and the shape ships when it changes. The position is a
|
||||
// few ms newer than the frame; the consumer only measures a plane that held still for
|
||||
// several frames, so that skew never reaches a measurement.
|
||||
let cursor = match &grabbed {
|
||||
Some(Err(_)) => None,
|
||||
_ => reader.cursor(),
|
||||
};
|
||||
if let Some(Ok(msg)) = grabbed.as_mut() {
|
||||
stamp_cursor_pos(msg, cursor.as_ref());
|
||||
}
|
||||
match grabbed {
|
||||
None => {}
|
||||
Some(Ok(msg)) => {
|
||||
@@ -1105,7 +1258,7 @@ fn drm_capture_worker(
|
||||
}
|
||||
|
||||
// Ship the cursor shape only when it changes (id is a content hash or the hidden sentinel).
|
||||
if let Some(c) = reader.cursor() {
|
||||
if let Some(c) = cursor {
|
||||
if c.id != last_cursor_id {
|
||||
last_cursor_id = c.id;
|
||||
if frame_tx
|
||||
@@ -1115,6 +1268,7 @@ fn drm_capture_worker(
|
||||
height: c.height,
|
||||
hotx: c.hotx,
|
||||
hoty: c.hoty,
|
||||
hot_measured: c.hot_measured,
|
||||
colors: c.colors,
|
||||
})
|
||||
.is_err()
|
||||
@@ -1534,7 +1688,15 @@ mod drm_conn_tests {
|
||||
let (a, b) = tokio::net::UnixStream::pair().unwrap();
|
||||
let mut tx = DrmConn::new(a);
|
||||
let mut rx = DrmConn::new(b);
|
||||
tx.send_msg(&Data::DrmFrame { width: 1920, height: 1080 }, None)
|
||||
tx.send_msg(
|
||||
&Data::DrmFrame {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
plane_rotation: None,
|
||||
cursor_pos: None,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (data, fd) = rx.recv_msg().await.unwrap();
|
||||
@@ -1542,7 +1704,9 @@ mod drm_conn_tests {
|
||||
data,
|
||||
Data::DrmFrame {
|
||||
width: 1920,
|
||||
height: 1080
|
||||
height: 1080,
|
||||
plane_rotation: None,
|
||||
cursor_pos: None
|
||||
}
|
||||
));
|
||||
assert!(fd.is_none(), "no fd was sent, none must be reported");
|
||||
@@ -1554,7 +1718,15 @@ mod drm_conn_tests {
|
||||
let mut tx = DrmConn::new(a);
|
||||
let mut rx = DrmConn::new(b);
|
||||
let (rd, wr) = pipe();
|
||||
tx.send_msg(&Data::DrmFrame { width: 4, height: 4 }, Some(rd.as_fd()))
|
||||
tx.send_msg(
|
||||
&Data::DrmFrame {
|
||||
width: 4,
|
||||
height: 4,
|
||||
plane_rotation: None,
|
||||
cursor_pos: None,
|
||||
},
|
||||
Some(rd.as_fd()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_data, fd) = rx.recv_msg().await.unwrap();
|
||||
@@ -1668,6 +1840,8 @@ mod drm_conn_tests {
|
||||
let payload = serde_json::to_vec(&Data::DrmFrame {
|
||||
width: 8,
|
||||
height: 8,
|
||||
plane_rotation: None,
|
||||
cursor_pos: None,
|
||||
})
|
||||
.unwrap();
|
||||
let prefix = (payload.len() as u32).to_be_bytes();
|
||||
@@ -1679,7 +1853,9 @@ mod drm_conn_tests {
|
||||
data,
|
||||
Data::DrmFrame {
|
||||
width: 8,
|
||||
height: 8
|
||||
height: 8,
|
||||
plane_rotation: None,
|
||||
cursor_pos: None
|
||||
}
|
||||
));
|
||||
let kept = fd.expect("the first surplus fd must be kept");
|
||||
|
||||
+43
-4
@@ -33,7 +33,8 @@ mod lv;
|
||||
mod nb;
|
||||
mod nl;
|
||||
mod pl;
|
||||
mod ptbr;
|
||||
mod pt_BR;
|
||||
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("-")
|
||||
@@ -185,8 +202,10 @@ pub fn translate_locale(name: String, locale: &str) -> String {
|
||||
"ru" => ru::T.deref(),
|
||||
"eo" => eo::T.deref(),
|
||||
"id" => id::T.deref(),
|
||||
"br" => ptbr::T.deref(),
|
||||
"pt" => ptbr::T.deref(),
|
||||
"br" => pt_BR::T.deref(),
|
||||
"pt" => pt_BR::T.deref(),
|
||||
"pt-br" => pt_BR::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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -778,5 +778,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("The screen sharing request ended without completing on the remote device", "انتهى طلب مشاركة الشاشة على الجهاز البعيد دون أن يكتمل"),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", "تعذّر على RustDesk الحصول على شاشة قابلة للاستخدام من XDG Desktop Portal، قد تكون مكتبة PipeWire قديمة جدًا"),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "تعذّر على RustDesk تحميل مكوّن GStreamer اللازم لالتقاط الشاشة ({})"),
|
||||
("Relay fallback delay in seconds", "مهلة التراجع إلى الترحيل بالثواني"),
|
||||
("relay-fallback-delay-tip", "المدة التي ينتظرها اتصال الترحيل القائم بالفعل الاتصالَ المباشر عبر WebRTC قبل أن يُستخدم بدلًا منه. زِدها لمنح الاتصال المباشر البطيء فرصة أكبر للفوز؛ وقلّلها للاستقرار على الترحيل أسرع في الشبكات التي يتعذر فيها الاتصال المباشر. اتركها فارغة للقيمة الافتراضية 2.5 ثانية."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -770,5 +770,16 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("port-forward-mux-tip", "Port yönləndirmə xəritələnməsinin hər əlaqəsini qarşı tərəfə açılan tək əlaqə üzərindən daşıyır, hər biri üçün yenidən qoşulub giriş etmək əvəzinə."),
|
||||
("Enable WebRTC P2P connection", "WebRTC P2P əlaqəsini aktivləşdir"),
|
||||
("Enable TCP hole punching", "TCP deşik açmanı aktivləşdir"),
|
||||
("The screen sharing request was declined on the remote device", ""),
|
||||
("The screen sharing request timed out on the remote device", ""),
|
||||
("RustDesk cannot reach the desktop session on the remote device, check that a desktop session is running and that RustDesk can use it", ""),
|
||||
("The desktop portal on the remote device is missing a capability needed for screen sharing or remote control, its backend may not be installed", ""),
|
||||
("Screen sharing was approved on the remote device, but the PipeWire connection could not be opened", ""),
|
||||
("The screen sharing request ended without completing on the remote device", ""),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", ""),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", ""),
|
||||
("Relay fallback delay in seconds", "Ötürücüyə keçid gecikməsi, saniyə"),
|
||||
("relay-fallback-delay-tip", "Artıq qurulmuş ötürücü bağlantı birbaşa WebRTC bağlantısını nə qədər gözləyir, sonra onun əvəzinə istifadə olunur. Yavaş birbaşa bağlantıya daha çox vaxt vermək üçün artırın; birbaşa bağlantının mümkün olmadığı şəbəkələrdə ötürücüyə daha tez keçmək üçün azaldın. Standart 2.5 saniyə üçün boş buraxın."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -778,5 +778,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("The screen sharing request ended without completing on the remote device", "Запыт на абагульванне экрана на аддаленай прыладзе завяршыўся, не будучы выкананым"),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", "RustDesk не змог атрымаць прыдатны экран ад XDG Desktop Portal, магчыма бібліятэка PipeWire занадта старая"),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk не змог загрузіць кампанент GStreamer, патрэбны для захопу экрана ({})"),
|
||||
("Relay fallback delay in seconds", "Затрымка пераходу на рэтранслятар у секундах"),
|
||||
("relay-fallback-delay-tip", "Колькі часу ўжо ўсталяванае злучэнне праз рэтранслятар чакае прамога злучэння WebRTC, перш чым будзе выкарыстана замест яго. Павялічце, каб даць павольнаму прамому злучэнню больш часу; паменшыце, каб хутчэй пераходзіць на рэтранслятар у сетках, дзе прамое злучэнне немагчымае. Пакіньце пустым для значэння па змаўчанні 2.5 секунды."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -778,5 +778,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("The screen sharing request ended without completing on the remote device", "Заявката за споделяне на екрана на отдалеченото устройство приключи, без да бъде изпълнена"),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", "RustDesk не можа да получи използваем екран от XDG Desktop Portal, библиотеката PipeWire може да е твърде стара"),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk не можа да зареди компонент на GStreamer, необходим за заснемане на екрана ({})"),
|
||||
("Relay fallback delay in seconds", "Забавяне преди преминаване към препредаване в секунди"),
|
||||
("relay-fallback-delay-tip", "Колко време вече установената връзка чрез препредаване изчаква директната WebRTC връзка, преди да бъде използвана вместо нея. Увеличете, за да дадете повече време на бавна директна връзка; намалете, за да се премине по-бързо към препредаване в мрежи, където директна връзка е невъзможна. Оставете празно за стойността по подразбиране 2.5 секунди."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -778,5 +778,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("The screen sharing request ended without completing on the remote device", "La sol·licitud de compartició de pantalla al dispositiu remot ha acabat sense completar-se"),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", "El RustDesk no ha pogut obtenir cap pantalla utilitzable de l'XDG Desktop Portal; la biblioteca PipeWire pot ser massa antiga"),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "El RustDesk no ha pogut carregar un component del GStreamer necessari per capturar la pantalla ({})"),
|
||||
("Relay fallback delay in seconds", "Retard abans de recórrer al relé en segons"),
|
||||
("relay-fallback-delay-tip", "Quant de temps espera una connexió de relé ja establerta la connexió directa WebRTC abans d'utilitzar-se en lloc seu. Augmenteu-lo per donar més temps a una connexió directa lenta; reduïu-lo per passar abans al relé en xarxes on no es pot fer una connexió directa. Deixeu-lo buit per al valor predeterminat de 2.5 segons."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
+4
-1
@@ -763,7 +763,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("Lock canvas", "锁定画布"),
|
||||
("Sync clipboard between sessions", "在会话间同步剪贴板"),
|
||||
("sync-clipboard-between-sessions-tip", "在一个远程会话中复制的文本或图片也会发送到其他已连接会话的剪贴板。"),
|
||||
("terminal-clipboard-write-tip", ""),
|
||||
("terminal-clipboard-write-tip", "终端中的一个应用希望将文本复制到此设备的剪贴板。如果授权,此权限将适用于所有连接中的终端应用,直到您在设置中关闭为止。手动复制和粘贴不受影响。"),
|
||||
("Allow terminal apps to copy to clipboard", "允许终端应用复制到剪贴板"),
|
||||
("Enable", "启用"),
|
||||
("Reuse one connection for port forwarding", "端口转发复用同一条连接"),
|
||||
@@ -778,5 +778,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("The screen sharing request ended without completing on the remote device", "远程设备上的屏幕共享请求已结束,但未完成"),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", "RustDesk 无法从 XDG Desktop Portal 获取可用的屏幕,PipeWire 库可能过旧"),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk 无法加载屏幕捕获所需的 GStreamer 组件 ({})"),
|
||||
("Relay fallback delay in seconds", "回落到中继前的等待时间(秒)"),
|
||||
("relay-fallback-delay-tip", "已经建立的中继连接会等待直连的 WebRTC 多久,超过这个时间就改用中继。调大可以让较慢的直连有更多机会胜出;调小则在无法直连的网络上更快回落到中继。留空表示使用默认值 2.5 秒。"),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "开始语音通话前请在\"仅共享屏幕\"页面启用\"音频录制\"。")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
@@ -778,5 +778,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
||||
("The screen sharing request ended without completing on the remote device", "Žádost o sdílení obrazovky na vzdáleném zařízení skončila, aniž by byla dokončena"),
|
||||
("RustDesk could not obtain a usable screen from the XDG Desktop Portal, the PipeWire library may be too old", "RustDesk nezískal z XDG Desktop Portal použitelnou obrazovku, knihovna PipeWire může být příliš stará"),
|
||||
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk nemohl načíst komponentu GStreameru potřebnou k zachycení obrazovky ({})"),
|
||||
("Relay fallback delay in seconds", "Prodleva před přepnutím na přenos v sekundách"),
|
||||
("relay-fallback-delay-tip", "Jak dlouho již navázané spojení přes přenos čeká na přímé spojení WebRTC, než bude použito místo něj. Zvyšte, aby pomalé přímé spojení mělo více času uspět; snižte, aby se v sítích, kde přímé spojení není možné, dříve přešlo na přenos. Ponechte prázdné pro výchozí hodnotu 2.5 sekundy."),
|
||||
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
|
||||
].iter().cloned().collect();
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user