Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9343affe0b | ||
|
|
7c830e76c6 |
@@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
app_path=$1
|
||||
identity=$2
|
||||
entitlements=$3
|
||||
|
||||
sign_args=(--force --options runtime --sign "$identity")
|
||||
if [[ "$identity" != "-" ]]; then
|
||||
sign_args+=(--timestamp)
|
||||
fi
|
||||
|
||||
frameworks_path="$app_path/Contents/Frameworks"
|
||||
if [[ -d "$frameworks_path" ]]; then
|
||||
while IFS= read -r -d '' code; do
|
||||
if file -b "$code" | grep -q 'Mach-O'; then
|
||||
codesign "${sign_args[@]}" "$code"
|
||||
fi
|
||||
done < <(find "$frameworks_path" -type f -print0)
|
||||
|
||||
while IFS= read -r -d '' framework; do
|
||||
codesign "${sign_args[@]}" "$framework"
|
||||
done < <(find "$frameworks_path" -depth -type d -name '*.framework' -print0)
|
||||
fi
|
||||
|
||||
service_path="$app_path/Contents/MacOS/service"
|
||||
if [[ -f "$service_path" ]]; then
|
||||
codesign "${sign_args[@]}" "$service_path"
|
||||
fi
|
||||
|
||||
codesign "${sign_args[@]}" --generate-entitlement-der \
|
||||
--entitlements "$entitlements" "$app_path"
|
||||
codesign --verify --deep --strict --verbose=2 "$app_path"
|
||||
|
||||
actual_entitlements=$(codesign -d --entitlements :- "$app_path" 2>/dev/null)
|
||||
audio_input=$(plutil -extract 'com\.apple\.security\.device\.audio-input' raw - \
|
||||
<<<"$actual_entitlements")
|
||||
if [[ "$audio_input" != "true" ]]; then
|
||||
echo "Missing com.apple.security.device.audio-input entitlement" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -31,7 +31,7 @@ env:
|
||||
# engine is 3.44. Every other platform stays on FLUTTER_VERSION (3.24.5) until Windows 7
|
||||
# support is restored after the upstream-wide Flutter bump. The arm64 job patches the few
|
||||
# 3.44-only source/pubspec changes on the fly (see "Patch RustDesk sources for Flutter 3.44").
|
||||
FLUTTER_WINDOWS_ARM_VERSION: "3.44.9"
|
||||
FLUTTER_WINDOWS_ARM_VERSION: "3.44.8"
|
||||
# for arm64 linux because official Dart SDK does not work
|
||||
FLUTTER_ELINUX_VERSION: "3.16.9"
|
||||
TAG_NAME: "${{ inputs.upload-tag }}"
|
||||
@@ -43,9 +43,8 @@ env:
|
||||
# https://github.com/rustdesk/rustdesk/actions/runs/14414119794/job/40427970174
|
||||
# 2. Update the `VCPKG_COMMIT_ID` in `ci.yml` and `playground.yml`.
|
||||
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
|
||||
VCPKG_CMAKE_VERSION: "4.3.0"
|
||||
ARMV7_VCPKG_COMMIT_ID: "6f29f12e82a8293156836ad81cc9bf5af41fe836" # 2025.01.13, got "/opt/artifacts/vcpkg/vcpkg: No such file or directory" with latest version
|
||||
VERSION: "1.5.0"
|
||||
VERSION: "1.4.9"
|
||||
NDK_VERSION: "r28c"
|
||||
#signing keys env variable checks
|
||||
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
||||
@@ -374,12 +373,6 @@ 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
|
||||
@@ -396,54 +389,6 @@ jobs:
|
||||
mv $msi.FullName ../../SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.msi
|
||||
sha256sum ../../SignOutput/rustdesk-*.msi
|
||||
|
||||
- name: Build pre-built MSI template
|
||||
# Two things this works around: preprocess.py rewrites res/msi in place, so the
|
||||
# tree is reset around this second variant; and it locates the app as
|
||||
# <app-name>.exe inside the dist, so the dist copy is renamed to match.
|
||||
#
|
||||
# The placeholder is chosen to keep this template as close to the shipped msi as
|
||||
# possible: eight characters like "RustDesk", and a valid 8.3 name, so WiX
|
||||
# derives no short name for it. A longer placeholder would get one, and a patch
|
||||
# cannot rewrite a truncated placeholder, leaving short names pointing at it.
|
||||
#
|
||||
# It still has to be unique, which is why "RustDesk" itself cannot be used:
|
||||
# it also names payload that must never be renamed, such as librustdesk.dll
|
||||
# and drivers\RustDeskPrinterDriver.
|
||||
#
|
||||
#
|
||||
# Building the arm64 template on the native arm64 runner makes the ARM
|
||||
# package available: the build agents are x64 and cannot run
|
||||
# preprocess.py against an ARM exe.
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
run: |
|
||||
git checkout -- res/msi
|
||||
cp -r ./rustdesk ./rustdesk-msi-template
|
||||
mv ./rustdesk-msi-template/rustdesk.exe ./rustdesk-msi-template/RDAPPNAM.exe
|
||||
Set-Content -Path ./rustdesk-msi-template/custom.txt -Value 'placeholder' -NoNewline
|
||||
$assets = './rustdesk-msi-template/data/flutter_assets/assets'
|
||||
New-Item -ItemType Directory -Force -Path $assets | Out-Null
|
||||
foreach ($a in 'icon.ico','icon.png','logo.png','logo_light.png','logo_dark.png') {
|
||||
Set-Content -Path "$assets/$a" -Value 'placeholder' -NoNewline
|
||||
}
|
||||
pushd ./res/msi
|
||||
python preprocess.py --arp --template --revision-version 0 -d ../../rustdesk-msi-template --app-name RDAPPNAM
|
||||
$msiPlatform = if ('${{ matrix.job.arch }}' -eq 'aarch64') { 'ARM64' } else { 'x64' }
|
||||
msbuild msi.sln -t:clean -p:Configuration=Release -p:Platform=$msiPlatform
|
||||
msbuild msi.sln -p:Configuration=Release -p:Platform=$msiPlatform /p:TargetVersion=Windows10
|
||||
$msi = Get-ChildItem ./Package/bin/*/Release/en-us/Package.msi | Select-Object -First 1
|
||||
popd
|
||||
mkdir ./msi-template
|
||||
mv $msi.FullName ./msi-template/rustdesk-template-${{ matrix.job.arch }}.msi
|
||||
git checkout -- res/msi
|
||||
rm -r -fo ./rustdesk-msi-template
|
||||
|
||||
- name: Upload unsigned msi template
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: rustdesk-unsigned-msi-template-${{ matrix.job.arch }}
|
||||
path: ./msi-template
|
||||
|
||||
- name: Sign rustdesk self-extracted file
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.SIGN_BASE_URL != '-2'
|
||||
shell: bash
|
||||
@@ -498,20 +443,11 @@ jobs:
|
||||
version: ${{ env.LLVM_VERSION }}
|
||||
|
||||
- name: Install Rust toolchain
|
||||
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: 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"
|
||||
|
||||
- uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
|
||||
with:
|
||||
@@ -871,11 +807,6 @@ 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:
|
||||
@@ -946,11 +877,7 @@ jobs:
|
||||
security unlock-keychain -p ${{ secrets.MACOS_P12_PASSWORD }} rustdesk.keychain
|
||||
# start sign the rustdesk.app and dmg
|
||||
rm -rf *.dmg || true
|
||||
# the identity secret carries its own shell quoting, so expand it inline like the dmg codesign below
|
||||
bash ./.github/scripts/sign-macos-app.sh \
|
||||
./flutter/build/macos/Build/Products/Release/RustDesk.app \
|
||||
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
|
||||
./flutter/macos/Runner/Release.entitlements
|
||||
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict ./flutter/build/macos/Build/Products/Release/RustDesk.app -vvv
|
||||
create-dmg --icon "RustDesk.app" 200 190 --hide-extension "RustDesk.app" --window-size 800 400 --app-drop-link 600 185 rustdesk-${{ env.VERSION }}.dmg ./flutter/build/macos/Build/Products/Release/RustDesk.app
|
||||
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict rustdesk-${{ env.VERSION }}.dmg -vvv
|
||||
# notarize the rustdesk-${{ env.VERSION }}.dmg
|
||||
@@ -998,33 +925,15 @@ jobs:
|
||||
name: rustdesk-unsigned-windows-x86_64
|
||||
path: ./windows-x86_64/
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: rustdesk-unsigned-windows-aarch64
|
||||
path: ./windows-aarch64/
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: rustdesk-unsigned-windows-x86
|
||||
path: ./windows-x86/
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: rustdesk-unsigned-msi-template-x86_64
|
||||
path: ./msi-template/
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: rustdesk-unsigned-msi-template-aarch64
|
||||
path: ./msi-template/
|
||||
|
||||
- name: Combine unsigned app
|
||||
run: |
|
||||
tar czf rustdesk-${{ env.VERSION }}-unsigned.tar.gz *.dmg windows-x86_64 windows-aarch64 windows-x86 msi-template
|
||||
tar czf rustdesk-${{ env.VERSION }}-unsigned.tar.gz *.dmg windows-x86_64 windows-x86
|
||||
|
||||
- name: Publish unsigned app
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
@@ -1561,6 +1470,7 @@ jobs:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set Swap Space
|
||||
if: ${{ matrix.job.arch == 'x86_64' }}
|
||||
uses: pierotofy/set-swap-space@49819abfb41bd9b44fb781159c033dba90353a7c # v1.0
|
||||
with:
|
||||
swap-size-gb: 12
|
||||
@@ -1595,15 +1505,6 @@ jobs:
|
||||
name: bridge-artifact
|
||||
path: ./
|
||||
|
||||
# vcpkg 2026.07.29's SPDX scripts require CMake 4.3+, but this ARM64 runner selects CMake 3.31.
|
||||
- name: Install CMake for vcpkg on Linux ARM64
|
||||
if: matrix.job.arch == 'aarch64' && env.UPLOAD_ARTIFACT == 'true'
|
||||
run: |
|
||||
python3 -m pip install --user "cmake==${VCPKG_CMAKE_VERSION}"
|
||||
user_base="$(python3 -m site --user-base)"
|
||||
"${user_base}/bin/cmake" --version
|
||||
echo "${user_base}/bin" >> "${GITHUB_PATH}"
|
||||
|
||||
- name: Setup vcpkg with Github Actions binary cache
|
||||
if: matrix.job.arch == 'x86_64' || env.UPLOAD_ARTIFACT == 'true'
|
||||
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
||||
@@ -2046,52 +1947,6 @@ 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
|
||||
@@ -2220,12 +2075,6 @@ jobs:
|
||||
echo "Modified vcpkg.json for armv7 build:"
|
||||
grep -A 2 -B 2 '"baseline"' vcpkg.json
|
||||
|
||||
- name: Set Swap Space
|
||||
if: matrix.job.arch == 'armv7'
|
||||
uses: pierotofy/set-swap-space@49819abfb41bd9b44fb781159c033dba90353a7c # v1.0
|
||||
with:
|
||||
swap-size-gb: 12
|
||||
|
||||
- name: Free Space
|
||||
run: |
|
||||
df -h
|
||||
@@ -2370,16 +2219,6 @@ jobs:
|
||||
# build rustdesk
|
||||
python3 ./res/inline-sciter.py
|
||||
export CARGO_INCREMENTAL=0
|
||||
# armv7 is the only 32-bit target in this job that links the whole binary, and the
|
||||
# release profile uses fat LTO with codegen-units=1. LLVM then merges every module
|
||||
# into a single unit and runs past the ~3GB address space a 32-bit process gets,
|
||||
# aborting rustc with "Rust cannot catch foreign exceptions" (a C++ bad_alloc from
|
||||
# LLVM unwinding into rustc's Rust frames). Thin LTO keeps peak memory bounded and
|
||||
# still allows cross-crate inlining; 64-bit targets keep fat LTO untouched.
|
||||
if [ "${{ matrix.job.arch }}" = "armv7" ]; then
|
||||
export CARGO_PROFILE_RELEASE_LTO=thin
|
||||
export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16
|
||||
fi
|
||||
cargo build --locked --features inline${{ matrix.job.extra_features }} --release --bins --jobs 1
|
||||
# make debian package
|
||||
mkdir -p ./Release
|
||||
@@ -2452,9 +2291,7 @@ 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'
|
||||
|
||||
@@ -17,7 +17,7 @@ env:
|
||||
TAG_NAME: "nightly"
|
||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
|
||||
VERSION: "1.5.0"
|
||||
VERSION: "1.4.9"
|
||||
NDK_VERSION: "r26d"
|
||||
#signing keys env variable checks
|
||||
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
||||
@@ -283,7 +283,7 @@ jobs:
|
||||
nasm \
|
||||
yasm \
|
||||
ninja-build \
|
||||
openjdk-17-jdk-headless \
|
||||
openjdk-11-jdk-headless \
|
||||
pkg-config \
|
||||
tree \
|
||||
wget
|
||||
@@ -365,9 +365,9 @@ jobs:
|
||||
- name: Build rustdesk
|
||||
shell: bash
|
||||
env:
|
||||
JAVA_HOME: /usr/lib/jvm/java-17-openjdk-amd64
|
||||
JAVA_HOME: /usr/lib/jvm/java-11-openjdk-amd64
|
||||
run: |
|
||||
export PATH=/usr/lib/jvm/java-17-openjdk-amd64/bin:$PATH
|
||||
export PATH=/usr/lib/jvm/java-11-openjdk-amd64/bin:$PATH
|
||||
# temporary use debug sign config
|
||||
sed -i "s/signingConfigs.release/signingConfigs.debug/g" ./flutter/android/app/build.gradle
|
||||
case ${{ matrix.job.target }} in
|
||||
|
||||
@@ -33,10 +33,6 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
# The root workspace lists libs/hbb_common as a member; without the
|
||||
# submodule its manifest is missing and cargo cannot load the workspace.
|
||||
submodules: recursive
|
||||
|
||||
- name: Update webpki-roots in all lockfiles
|
||||
id: update
|
||||
|
||||
@@ -8,24 +8,18 @@
|
||||
* `src/platform/` platform-specific code
|
||||
* `src/ui/` legacy Sciter UI (deprecated)
|
||||
* `flutter/` current UI
|
||||
* `libs/hbb_common/` shared with the server: rendezvous proto, sockets, `Config` core
|
||||
* `libs/base/` (crate `base`) client-only: option keys, message proto, file transfer, platform code
|
||||
* `libs/hbb_common/` config / proto / shared utils
|
||||
* `libs/scrap/` screen capture
|
||||
* `libs/enigo/` input control
|
||||
* `libs/clipboard/` clipboard
|
||||
* `libs/base/src/config/keys.rs` the single import path for all options
|
||||
* `libs/hbb_common/src/config.rs` all options
|
||||
|
||||
### Key Components
|
||||
- **Remote Desktop Protocol**: Custom protocol implemented in `src/rendezvous_mediator.rs` for communicating with rustdesk-server
|
||||
- **Screen Capture**: Platform-specific screen capture in `libs/scrap/`
|
||||
- **Input Handling**: Cross-platform input simulation in `libs/enigo/`
|
||||
- **Audio/Video Services**: Real-time audio/video streaming in `src/server/`
|
||||
- **File Transfer**: Secure file transfer implementation in `libs/base/src/fs.rs`
|
||||
|
||||
`hbb_common` is a git submodule shared with the server, so changing it costs a
|
||||
round-trip. Put client-only code in `libs/base` instead; it is a normal
|
||||
workspace member. `base::config::keys` re-exports the handful of keys
|
||||
`hbb_common` still reads, so callers get the whole set from that one path.
|
||||
- **File Transfer**: Secure file transfer implementation in `libs/hbb_common/`
|
||||
|
||||
### UI Architecture
|
||||
- **Legacy UI**: Sciter-based (deprecated) - files in `src/ui/`
|
||||
@@ -48,20 +42,6 @@ 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.
|
||||
@@ -81,34 +61,6 @@ workspace member. `base::config::keys` re-exports the handful of keys
|
||||
* Do not make formatting-only changes.
|
||||
* Keep naming/style consistent with nearby code.
|
||||
|
||||
### Imports
|
||||
|
||||
* One `use` per crate. Everything a file takes from the same crate goes in a
|
||||
single braced block, not one statement per item:
|
||||
|
||||
```rust
|
||||
// no
|
||||
use base::fs;
|
||||
use base::message_proto::*;
|
||||
|
||||
// yes
|
||||
use base::{fs, message_proto::*};
|
||||
```
|
||||
|
||||
* The only reason to split is a `#[cfg(...)]` that does not apply to the whole
|
||||
block -- an attribute binds to one item, so a differently-gated import has to
|
||||
stand on its own. A `pub use` re-export likewise cannot join a plain `use`.
|
||||
|
||||
```rust
|
||||
#[cfg(not(feature = "flutter"))]
|
||||
use base::fs;
|
||||
use base::message_proto::*;
|
||||
```
|
||||
|
||||
* When splitting an existing `use` because some of its items moved to another
|
||||
crate, fold each side into that crate's existing block rather than leaving a
|
||||
second statement behind.
|
||||
|
||||
### Comments
|
||||
|
||||
* Avoid comments unless they explain a non-obvious reason, constraint, or workaround.
|
||||
@@ -122,55 +74,12 @@ workspace member. `base::config::keys` re-exports the handful of keys
|
||||
* Accept a little duplication over a restructure. A new function that repeats a few lines of an existing one is a better diff than reshaping the original so both can share it.
|
||||
* Put new logic in self-contained functions in the module it belongs to (platform-specific logic in `src/platform/`, with `use` inside the function body to avoid churning shared import blocks). Call sites in shared files (`src/tray.rs`, `src/core_main.rs`, `src/server/connection.rs`, …) should be thin one-line hooks.
|
||||
|
||||
### Scope check before touching shared code
|
||||
|
||||
* Before changing a shared trait, a shared struct, or the signature of a widely used function, check whether the bug or feature is specific to one path. If it is, keep the change inside that path unless that is impossible, and say in the PR why it was.
|
||||
* If an unrelated caller needs `Default::default()`, `None`, or another placeholder solely to satisfy a signature you changed, the diff is too broad: stop and redesign.
|
||||
* The expected shape of a fix is a new function in the feature's own module, plus at most a new field or a thin hook in the shared code it needs. Feature-specific state belongs beside the feature's existing state, not in a new abstraction every caller has to learn.
|
||||
|
||||
### Mandatory regression-surface check
|
||||
|
||||
Before considering any implementation complete, perform a minimization pass over the final diff.
|
||||
|
||||
* Inspect every modified existing file and every modified existing code path. Each must be strictly necessary for the requested change. Revert changes that are merely cleanup, refactoring, consistency improvements, or fixes for pre-existing issues.
|
||||
* For new features, preserve the existing implementation path when the feature is disabled or unsupported whenever practical. `feature off` should run the old code, not a rewritten equivalent.
|
||||
* Do not route existing behavior through a new abstraction merely to share code with the new feature. Prefer a parallel new function or a small amount of duplication over changing a proven existing path.
|
||||
* Keep new implementation logic in new or feature-specific modules. Changes to shared/core files should normally be thin hooks, capability checks, or protocol plumbing.
|
||||
* Do not fix unrelated pre-existing bugs in the same PR. Put them in a separate change unless they directly block correctness or security of the requested work.
|
||||
* For submodule bumps, inspect the exact commit range and ensure unrelated changes are not being pulled into the parent PR.
|
||||
* 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`)
|
||||
|
||||
@@ -179,7 +88,6 @@ Each file is a `HashMap<key, translation>`. Layout:
|
||||
* `template.rs` is the master list of every key. **Never edit it** as part of translation work.
|
||||
* `en.rs` holds only the keys whose English display text differs from the key itself.
|
||||
* Every other file (`de.rs`, `fr.rs`, …) carries the full key set; an untranslated entry has an empty value: `("key", "")`.
|
||||
* `it.rs` is maintained by hand by its translator. Never fill or change its entries; when adding new keys, append them to it with `""` and leave the translation to the maintainer.
|
||||
|
||||
### Finding the English source for a key
|
||||
|
||||
@@ -201,4 +109,4 @@ Then translate that source into the file's target language (infer the language f
|
||||
|
||||
* New English-text keys use sentence case, not Title Case: `Use ID whitelisting`, **not** `Use ID Whitelisting`. Acronyms (ID, IP, 2FA…) stay uppercase. Legacy Title-Case keys (e.g. `Use IP Whitelisting`) stay as-is — do not rename them.
|
||||
* Since the key itself is the English display text, a sentence-case key usually needs **no** `en.rs` entry; add one only when the display text must differ from the key (e.g. `*_tip` keys).
|
||||
* Append each new key to `template.rs` (with `""`) and to every `src/lang/*.rs` file (translated, or `""` if unsure; always `""` for `it.rs`), at the end of the list.
|
||||
* Append each new key to `template.rs` (with `""`) and to every `src/lang/*.rs` file (translated, or `""` if unsure), at the end of the list.
|
||||
|
||||
Generated
+271
-151
@@ -648,30 +648,6 @@ dependencies = [
|
||||
"rustc-demangle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"backtrace",
|
||||
"bytes",
|
||||
"filetime",
|
||||
"hbb_common",
|
||||
"lazy_static",
|
||||
"libc",
|
||||
"log",
|
||||
"osascript",
|
||||
"protobuf",
|
||||
"protobuf-codegen",
|
||||
"serde 1.0.228",
|
||||
"serde_derive",
|
||||
"serde_json 1.0.118",
|
||||
"smithay-client-toolkit 0.20.0",
|
||||
"tokio",
|
||||
"users",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base16ct"
|
||||
version = "0.2.0"
|
||||
@@ -777,6 +753,24 @@ dependencies = [
|
||||
"syn 2.0.98",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.71.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
|
||||
dependencies = [
|
||||
"bitflags 2.9.1",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools 0.12.1",
|
||||
"proc-macro2 1.0.93",
|
||||
"quote 1.0.36",
|
||||
"regex",
|
||||
"rustc-hash 2.1.1",
|
||||
"shlex",
|
||||
"syn 2.0.98",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.72.1"
|
||||
@@ -985,9 +979,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.11.1"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
||||
dependencies = [
|
||||
"serde 1.0.228",
|
||||
]
|
||||
@@ -1167,6 +1161,30 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.0",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20poly1305"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"chacha20",
|
||||
"cipher",
|
||||
"poly1305",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.41"
|
||||
@@ -1216,6 +1234,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1275,7 +1294,6 @@ checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
|
||||
name = "clipboard"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base",
|
||||
"cacao",
|
||||
"cc",
|
||||
"dashmap 5.5.3",
|
||||
@@ -1305,7 +1323,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "clipboard-master"
|
||||
version = "4.0.0-beta.6"
|
||||
source = "git+https://github.com/rustdesk-org/clipboard-master#522fafb65edfe7939cf63fa797f916569ecab595"
|
||||
source = "git+https://github.com/rustdesk-org/clipboard-master#7762d74e38db37cfeb6ded88c964b9cdbddfb6db"
|
||||
dependencies = [
|
||||
"objc",
|
||||
"objc-foundation",
|
||||
@@ -1717,7 +1735,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "cpal"
|
||||
version = "0.15.3"
|
||||
source = "git+https://github.com/rustdesk-org/cpal?branch=osx-screencapturekit#96d4da121b7d949677ac5b6887413a9185fd7f39"
|
||||
source = "git+https://github.com/rustdesk-org/cpal?branch=osx-screencapturekit#6b374bcaed076750ca8fce6da518ab39b882e14a"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"cidre",
|
||||
@@ -1791,9 +1809,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.20"
|
||||
version = "0.9.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
|
||||
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
@@ -2306,7 +2324,7 @@ version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
|
||||
dependencies = [
|
||||
"libloading 0.7.4",
|
||||
"libloading 0.8.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2424,6 +2442,42 @@ dependencies = [
|
||||
"linux-raw-sys 0.6.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtls"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f531dd7c181beaf3cebab3716afa4d0d41ab888be85232583f56bbaf07ca208a"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
"bincode",
|
||||
"byteorder",
|
||||
"cbc",
|
||||
"ccm",
|
||||
"chacha20poly1305",
|
||||
"der-parser",
|
||||
"hmac",
|
||||
"log",
|
||||
"p256",
|
||||
"p384",
|
||||
"portable-atomic",
|
||||
"rand 0.9.2",
|
||||
"rand_core 0.6.4",
|
||||
"rcgen",
|
||||
"ring",
|
||||
"rustls",
|
||||
"sec1",
|
||||
"serde 1.0.228",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"thiserror 1.0.61",
|
||||
"tokio",
|
||||
"webrtc-util",
|
||||
"x25519-dalek",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtoa"
|
||||
version = "0.4.8"
|
||||
@@ -2502,7 +2556,6 @@ dependencies = [
|
||||
name = "enigo"
|
||||
version = "0.0.14"
|
||||
dependencies = [
|
||||
"base",
|
||||
"core-graphics 0.22.3",
|
||||
"hbb_common",
|
||||
"libxdo-sys",
|
||||
@@ -2810,7 +2863,7 @@ dependencies = [
|
||||
"is-terminal",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"nu-ansi-term",
|
||||
"nu-ansi-term 0.49.0",
|
||||
"regex",
|
||||
"thiserror 1.0.61",
|
||||
]
|
||||
@@ -3690,6 +3743,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-recursion",
|
||||
"backtrace",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
@@ -3700,6 +3754,7 @@ dependencies = [
|
||||
"dirs-next",
|
||||
"dlopen",
|
||||
"env_logger 0.11.6",
|
||||
"filetime",
|
||||
"flexi_logger",
|
||||
"futures",
|
||||
"futures-util",
|
||||
@@ -3710,7 +3765,7 @@ dependencies = [
|
||||
"log",
|
||||
"mac_address",
|
||||
"machine-uid",
|
||||
"percent-encoding",
|
||||
"osascript",
|
||||
"protobuf",
|
||||
"protobuf-codegen",
|
||||
"rand 0.8.5",
|
||||
@@ -3722,6 +3777,7 @@ dependencies = [
|
||||
"serde_derive",
|
||||
"serde_json 1.0.118",
|
||||
"sha2",
|
||||
"smithay-client-toolkit 0.20.0",
|
||||
"socket2 0.3.19",
|
||||
"sodiumoxide",
|
||||
"sysinfo",
|
||||
@@ -3740,6 +3796,7 @@ dependencies = [
|
||||
"webpki-roots 1.0.9",
|
||||
"webrtc",
|
||||
"whoami",
|
||||
"winapi 0.3.9",
|
||||
"x11 2.21.0",
|
||||
"zstd",
|
||||
]
|
||||
@@ -4120,14 +4177,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "interceptor"
|
||||
version = "0.14.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ea51375727680dc15f06e8ad90fa31df75d79dd030100e8ad60eef1c27fe2c98"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"futures",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"rtcp",
|
||||
"rtp",
|
||||
"thiserror 1.0.61",
|
||||
@@ -4163,6 +4222,16 @@ version = "2.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
|
||||
|
||||
[[package]]
|
||||
name = "iri-string"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"serde 1.0.228",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is-terminal"
|
||||
version = "0.4.16"
|
||||
@@ -4269,11 +4338,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "kcp-sys"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/rustdesk-org/kcp-sys?branch=rustdesk-patches#938eda3e5e9757a612385503af7a6cb1189b2cdd"
|
||||
source = "git+https://github.com/rustdesk-org/kcp-sys#32a6c09fc6223f54aea83981a6aa8995931d29be"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"auto_impl",
|
||||
"bindgen 0.72.1",
|
||||
"bindgen 0.71.1",
|
||||
"bitflags 2.9.1",
|
||||
"bytes",
|
||||
"cc",
|
||||
@@ -4284,6 +4353,8 @@ dependencies = [
|
||||
"thiserror 2.0.17",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"zerocopy 0.7.34",
|
||||
]
|
||||
|
||||
@@ -4417,7 +4488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.0",
|
||||
"windows-targets 0.48.5",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5139,6 +5210,16 @@ dependencies = [
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.46.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
|
||||
dependencies = [
|
||||
"overload",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.49.0"
|
||||
@@ -5802,6 +5883,12 @@ dependencies = [
|
||||
"serde_json 1.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "overload"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
|
||||
|
||||
[[package]]
|
||||
name = "owned_ttf_parser"
|
||||
version = "0.25.1"
|
||||
@@ -6190,6 +6277,17 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
"opaque-debug",
|
||||
"universal-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polyval"
|
||||
version = "0.6.2"
|
||||
@@ -6485,9 +6583,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.15"
|
||||
version = "0.11.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
|
||||
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.3.2",
|
||||
@@ -6762,7 +6860,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rdev"
|
||||
version = "0.5.0-2"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#23e24dd6b35452a495dae0ae6d99395e9755ab0f"
|
||||
dependencies = [
|
||||
"cocoa 0.24.1",
|
||||
"core-foundation 0.9.4",
|
||||
@@ -6891,10 +6989,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.28"
|
||||
version = "0.12.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
@@ -6923,6 +7022,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
@@ -6994,8 +7094,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rtcp"
|
||||
version = "0.13.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81d30d1c4091644431c22acf9f8be6191b56805e0e977f15ca7104b4a6d6eaec"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"thiserror 1.0.61",
|
||||
@@ -7004,13 +7105,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rtp"
|
||||
version = "0.13.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f126f38ea84c02480e32e547c1459a939052f74fb92117ac3eef23fdac6b023"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"memchr",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"serde 1.0.228",
|
||||
"thiserror 1.0.61",
|
||||
"webrtc-util",
|
||||
@@ -7075,14 +7177,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustdesk"
|
||||
version = "1.5.0"
|
||||
version = "1.4.9"
|
||||
dependencies = [
|
||||
"android-wakelock",
|
||||
"android_logger",
|
||||
"arboard",
|
||||
"async-process",
|
||||
"async-trait",
|
||||
"base",
|
||||
"bytemuck",
|
||||
"bytes",
|
||||
"cc",
|
||||
@@ -7124,7 +7225,6 @@ dependencies = [
|
||||
"lazy_static",
|
||||
"libpulse-binding",
|
||||
"libpulse-simple-binding",
|
||||
"libsamplerate-sys",
|
||||
"libxdo-sys",
|
||||
"mac_address",
|
||||
"magnum-opus",
|
||||
@@ -7167,7 +7267,6 @@ dependencies = [
|
||||
"terminfo",
|
||||
"termios 0.3.3",
|
||||
"tiny-skia",
|
||||
"tokio",
|
||||
"totp-rs",
|
||||
"tray-icon",
|
||||
"ttf-parser",
|
||||
@@ -7175,7 +7274,6 @@ dependencies = [
|
||||
"uuid",
|
||||
"virtual_display",
|
||||
"wallpaper",
|
||||
"wayland-client",
|
||||
"winapi 0.3.9",
|
||||
"windows 0.61.1",
|
||||
"windows-service",
|
||||
@@ -7185,14 +7283,11 @@ dependencies = [
|
||||
"wol-rs",
|
||||
"x11-clipboard 0.8.1",
|
||||
"x11rb 0.12.0",
|
||||
"xkbcommon-dl",
|
||||
"xxhash-rust",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustdesk-portable-packer"
|
||||
version = "1.5.0"
|
||||
version = "1.4.9"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"dirs 5.0.1",
|
||||
@@ -7408,7 +7503,6 @@ name = "scrap"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"android_logger",
|
||||
"base",
|
||||
"bindgen 0.72.1",
|
||||
"block",
|
||||
"cfg-if 1.0.0",
|
||||
@@ -7453,10 +7547,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sdp"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32c374dceda16965d541c8800ce9cc4e1c14acfd661ddf7952feeedc3411e5c6"
|
||||
dependencies = [
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"substring",
|
||||
"thiserror 1.0.61",
|
||||
"url",
|
||||
@@ -7686,6 +7781,15 @@ dependencies = [
|
||||
"tzdb 0.5.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shared_library"
|
||||
version = "0.1.9"
|
||||
@@ -8025,14 +8129,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "stun"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a512c5d501e3e3b5a4bb3e8e31462d56d54a66b95a28b8596e14422bf21c32b"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"crc",
|
||||
"lazy_static",
|
||||
"md-5",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"ring",
|
||||
"subtle",
|
||||
"thiserror 1.0.61",
|
||||
@@ -8414,6 +8519,16 @@ dependencies = [
|
||||
"syn 2.0.98",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.0",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "threadpool"
|
||||
version = "1.8.1"
|
||||
@@ -8600,8 +8715,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.29.0"
|
||||
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=c241b11b03de4881faf1ecd2fe6e867c92f3013b#c241b11b03de4881faf1ecd2fe6e867c92f3013b"
|
||||
version = "0.26.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
@@ -8734,25 +8850,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.6.11"
|
||||
version = "0.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"bitflags 2.9.1",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"iri-string",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8797,6 +8908,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"valuable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-log"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
|
||||
dependencies = [
|
||||
"nu-ansi-term 0.46.0",
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8889,8 +9026,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.29.0"
|
||||
source = "git+https://github.com/rustdesk-org/tungstenite-rs?rev=efce47e5364f00a63302cf07ab1fb13ded478914#efce47e5364f00a63302cf07ab1fb13ded478914"
|
||||
version = "0.26.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
@@ -8904,13 +9042,15 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
"sha1",
|
||||
"thiserror 2.0.17",
|
||||
"utf-8",
|
||||
"webpki-roots 0.26.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "turn"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ed995882f66ab94238de77c62e5e778389698ab700afa4696f4754da8f457cb"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
@@ -8918,7 +9058,7 @@ dependencies = [
|
||||
"log",
|
||||
"md-5",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"ring",
|
||||
"stun",
|
||||
"thiserror 1.0.61",
|
||||
@@ -9044,6 +9184,12 @@ dependencies = [
|
||||
"unic-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-bidi"
|
||||
version = "0.3.15"
|
||||
@@ -9133,6 +9279,12 @@ 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"
|
||||
@@ -9183,6 +9335,12 @@ dependencies = [
|
||||
"bindgen 0.65.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "valuable"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
@@ -9566,25 +9724,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webrtc"
|
||||
version = "0.13.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08fd686c0920ac08f3a57eacc48e31f0e4ca1ffefba4478784606f78c14e83ad"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"cfg-if 1.0.0",
|
||||
"dtls",
|
||||
"hex",
|
||||
"interceptor",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"rcgen",
|
||||
"regex",
|
||||
"ring",
|
||||
"rtcp",
|
||||
"rtp",
|
||||
"rustls",
|
||||
"sdp",
|
||||
"serde 1.0.228",
|
||||
"serde_json 1.0.118",
|
||||
@@ -9592,13 +9750,12 @@ dependencies = [
|
||||
"smol_str",
|
||||
"stun",
|
||||
"thiserror 1.0.61",
|
||||
"time 0.3.36",
|
||||
"tokio",
|
||||
"turn",
|
||||
"unicase",
|
||||
"url",
|
||||
"waitgroup",
|
||||
"webrtc-data",
|
||||
"webrtc-dtls",
|
||||
"webrtc-ice",
|
||||
"webrtc-mdns",
|
||||
"webrtc-media",
|
||||
@@ -9609,8 +9766,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-data"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "062a5438d63bb0756a221693d76cc0dd6119affee1dfdfe57abe3a2a8c8b3eea"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"log",
|
||||
@@ -9621,54 +9779,18 @@ dependencies = [
|
||||
"webrtc-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-dtls"
|
||||
version = "0.12.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
"bincode",
|
||||
"byteorder",
|
||||
"cbc",
|
||||
"ccm",
|
||||
"der-parser",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"log",
|
||||
"p256",
|
||||
"p384",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand_core 0.6.4",
|
||||
"rcgen",
|
||||
"ring",
|
||||
"rustls",
|
||||
"sec1",
|
||||
"serde 1.0.228",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"thiserror 1.0.61",
|
||||
"tokio",
|
||||
"webrtc-util",
|
||||
"x25519-dalek",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-ice"
|
||||
version = "0.13.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cb13fd1a373e68addc4bba0c8ca058627518e54342583d024bdcbb8ae5d97d"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
"crc",
|
||||
"ipnet",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"serde 1.0.228",
|
||||
"serde_json 1.0.118",
|
||||
"stun",
|
||||
@@ -9684,8 +9806,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-mdns"
|
||||
version = "0.9.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a17279a067e75df72ce923fdeb7f04cd808f6f5aa4910dc6bcb4fbe66b396ace"
|
||||
dependencies = [
|
||||
"log",
|
||||
"socket2 0.5.10",
|
||||
@@ -9696,20 +9819,22 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-media"
|
||||
version = "0.10.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94a84c910fec0848fd5a0d8a5651e0ddbdedaf25a7d3ae3f0b15f71ac73a1773"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"rtp",
|
||||
"thiserror 1.0.61",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-sctp"
|
||||
version = "0.12.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f985465467d8910c1f8ac4382cd64f83b1f6a1a75021a82b221546f6fb3b856f"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -9717,7 +9842,7 @@ dependencies = [
|
||||
"crc",
|
||||
"log",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"thiserror 1.0.61",
|
||||
"tokio",
|
||||
"webrtc-util",
|
||||
@@ -9725,8 +9850,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-srtp"
|
||||
version = "0.15.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66d8cdc33413f1d0192670a80ce93d17cb78d57fe3a2414be30d6f6dff121123"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"aes",
|
||||
@@ -9747,19 +9873,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webrtc-util"
|
||||
version = "0.11.0"
|
||||
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1c0c7e0c8f280f2bbfae442701465777ac07adaf46ce0c5863cd58e13fe472a"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bitflags 1.3.2",
|
||||
"bytes",
|
||||
"ipnet",
|
||||
"lazy_static",
|
||||
"libc",
|
||||
"log",
|
||||
"nix 0.26.4",
|
||||
"portable-atomic",
|
||||
"rand 0.8.5",
|
||||
"rand 0.9.2",
|
||||
"thiserror 1.0.61",
|
||||
"tokio",
|
||||
"winapi 0.3.9",
|
||||
@@ -10802,12 +10928,6 @@ 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"
|
||||
|
||||
+5
-45
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rustdesk"
|
||||
version = "1.5.0"
|
||||
version = "1.4.9"
|
||||
authors = ["rustdesk <info@rustdesk.com>"]
|
||||
edition = "2021"
|
||||
build= "build.rs"
|
||||
@@ -22,7 +22,7 @@ path = "src/service.rs"
|
||||
|
||||
[features]
|
||||
inline = []
|
||||
use_samplerate = ["samplerate", "libsamplerate-sys"]
|
||||
use_samplerate = ["samplerate"]
|
||||
use_rubato = ["rubato"]
|
||||
use_dasp = ["dasp"]
|
||||
flutter = ["flutter_rust_bridge"]
|
||||
@@ -52,8 +52,7 @@ screencapturekit = ["cpal/screencapturekit"]
|
||||
[dependencies]
|
||||
async-trait = "0.1"
|
||||
scrap = { path = "libs/scrap", features = ["wayland"] }
|
||||
hbb_common = { path = "libs/hbb_common", features = ["webrtc"] }
|
||||
base = { path = "libs/base" }
|
||||
hbb_common = { path = "libs/hbb_common" }
|
||||
serde_derive = "1.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
@@ -62,14 +61,11 @@ cfg-if = "1.0"
|
||||
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"] }
|
||||
@@ -87,7 +83,7 @@ fon = "0.6"
|
||||
shutdown_hooks = "0.1"
|
||||
totp-rs = { version = "5.4", default-features = false, features = ["gen_secret", "otpauth"] }
|
||||
stunclient = "0.4"
|
||||
kcp-sys= { git = "https://github.com/rustdesk-org/kcp-sys", branch = "rustdesk-patches" }
|
||||
kcp-sys= { git = "https://github.com/rustdesk-org/kcp-sys"}
|
||||
reqwest = { version = "0.12", features = ["blocking", "socks", "json", "native-tls", "rustls-tls", "rustls-tls-native-roots", "gzip", "zstd"], default-features=false }
|
||||
|
||||
[target.'cfg(not(target_os = "linux"))'.dependencies]
|
||||
@@ -202,8 +198,6 @@ gtk = "0.18"
|
||||
termios = "0.3"
|
||||
terminfo = "0.8"
|
||||
winit = "0.30"
|
||||
wayland-client = "0.31"
|
||||
xkbcommon-dl = { version = "0.4", features = ["x11"] }
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
|
||||
openssl = { version = "0.10", features = ["vendored"] }
|
||||
@@ -214,46 +208,13 @@ jni = "0.21"
|
||||
android-wakelock = { git = "https://github.com/rustdesk-org/android-wakelock" }
|
||||
|
||||
[workspace]
|
||||
members = ["libs/scrap", "libs/hbb_common", "libs/base", "libs/enigo", "libs/clipboard", "libs/virtual_display", "libs/virtual_display/dylib", "libs/portable", "libs/remote_printer"]
|
||||
members = ["libs/scrap", "libs/hbb_common", "libs/enigo", "libs/clipboard", "libs/virtual_display", "libs/virtual_display/dylib", "libs/portable", "libs/remote_printer"]
|
||||
exclude = ["vdi/host"]
|
||||
|
||||
# Patch libxdo-sys to use a stub implementation that doesn't require libxdo
|
||||
# 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;
|
||||
# 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
|
||||
# a congestion window, as KCP does - on by default, `allow-webrtc-congestion-control` opts back in.
|
||||
# Sending that way, a reordering window keeps a chunk that is merely late from being resent on a
|
||||
# path that jitters, every DATA chunk asks for its SACK at once so a lost tail is back within an
|
||||
# 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. 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: 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."
|
||||
@@ -273,7 +234,6 @@ os-version = "0.2"
|
||||
[dev-dependencies]
|
||||
hound = "3.5"
|
||||
docopt = "1.1"
|
||||
tokio = { version = "1.44", features = ["test-util"] }
|
||||
|
||||
[package.metadata.bundle]
|
||||
name = "RustDesk"
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM debian:trixie-slim
|
||||
FROM debian:bullseye-slim
|
||||
|
||||
WORKDIR /
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -158,8 +158,7 @@ Please ensure that you run these commands from the root of the RustDesk reposito
|
||||
|
||||
## File Structure
|
||||
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, config, tcp/udp wrapper, and some other utility functions shared with the server
|
||||
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, fs functions for file transfer, keyboard and platform code used only by this app
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: video codec, config, tcp/udp wrapper, protobuf, fs functions for file transfer, and some other utility functions
|
||||
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: screen capture
|
||||
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: platform specific keyboard/mouse control
|
||||
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: file copy and paste implementation for Windows, Linux, macOS.
|
||||
|
||||
@@ -18,7 +18,7 @@ AppDir:
|
||||
id: rustdesk
|
||||
name: rustdesk
|
||||
icon: rustdesk
|
||||
version: 1.5.0
|
||||
version: 1.4.9
|
||||
exec: usr/share/rustdesk/rustdesk
|
||||
exec_args: $@
|
||||
apt:
|
||||
|
||||
@@ -18,7 +18,7 @@ AppDir:
|
||||
id: rustdesk
|
||||
name: rustdesk
|
||||
icon: rustdesk
|
||||
version: 1.5.0
|
||||
version: 1.4.9
|
||||
exec: usr/share/rustdesk/rustdesk
|
||||
exec_args: $@
|
||||
apt:
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
--- 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;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/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.8.
|
||||
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.4.
|
||||
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
|
||||
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
|
||||
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
|
||||
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,10 +489,8 @@ 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. The helper check rides along for the same reason, and it matters
|
||||
# more here than anywhere: this is the branch the packaging workflow takes.
|
||||
# already trustworthy.
|
||||
_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:
|
||||
@@ -523,22 +521,8 @@ 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')):
|
||||
# -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')
|
||||
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release')
|
||||
# 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
|
||||
@@ -549,31 +533,9 @@ 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
|
||||
@@ -901,10 +863,8 @@ 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. A bundle produced before the helper was disabled is caught here too,
|
||||
# which is the point: it must not be repackaged into a deb.
|
||||
# without a word.
|
||||
_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,15 +43,6 @@ fn build_manifest() {
|
||||
}
|
||||
}
|
||||
|
||||
// bionic only exports getifaddrs()/freeifaddrs() from API 24, while the jniLibs
|
||||
// are built against the API 21 sysroot (flutter/ndk_*.sh). webrtc-util calls
|
||||
// them, so without this the android link fails on undefined symbols.
|
||||
fn build_android_ifaddrs() {
|
||||
let file = "src/platform/android_ifaddrs.c";
|
||||
cc::Build::new().file(file).compile("android_ifaddrs");
|
||||
println!("cargo:rerun-if-changed={}", file);
|
||||
}
|
||||
|
||||
fn install_android_deps() {
|
||||
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
|
||||
if target_os != "android" {
|
||||
@@ -98,8 +89,5 @@ fn main() {
|
||||
build_mac();
|
||||
println!("cargo:rustc-link-lib=framework=ApplicationServices");
|
||||
}
|
||||
if target_os == "android" {
|
||||
build_android_ifaddrs();
|
||||
}
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
|
||||
+35
-43
@@ -1,45 +1,39 @@
|
||||
<p align="center">
|
||||
<img src="../res/logo-header.svg" alt="RustDesk - Ваш віддалений робочий стіл"><br>
|
||||
<a href="#кроки-для-збірки">Збірка</a> •
|
||||
<img src="../res/logo-header.svg" alt="RustDesk - Ваша віддалена стільниця"><br>
|
||||
<a href="#публічні-сервери">Сервери</a> •
|
||||
<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>] | [<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>
|
||||
[<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>
|
||||
</p>
|
||||
|
||||
> [!CAUTION]
|
||||
> **Застереження щодо неналежного використання:** <br>
|
||||
> Розробники RustDesk не схвалюють і не підтримують неетичне або незаконне використання цього програмного забезпечення. Неналежне використання, зокрема несанкціонований доступ, керування або втручання в приватність, суворо суперечить нашим правилам. Автори не несуть відповідальності за неналежне використання застосунку.
|
||||
Спілкування з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
|
||||
Спілкуйтеся з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
|
||||
[](https://rustdesk.com/pricing.html)
|
||||
|
||||
RustDesk — ще одне рішення для віддаленого робочого столу, написане на Rust. Працює одразу після запуску й не потребує налаштування. Ви повністю контролюєте свої дані та їхню безпеку. Можна використовувати наш rendezvous/relay-сервер, [налаштувати власний](https://rustdesk.com/server) або [написати власний rendezvous/relay-сервер](https://github.com/rustdesk/rustdesk-server-demo).
|
||||
Ще один застосунок для віддаленого керування стільницею, написаний на Rust. Працює з коробки, не потребує налаштування. Ви повністю контролюєте свої дані, не турбуючись про безпеку. Ви можете використовувати наш сервер ретрансляції, [налаштувати свій власний](https://rustdesk.com/server), або [написати свій власний сервер ретрансляції](https://github.com/rustdesk/rustdesk-server-demo).
|
||||
|
||||

|
||||
|
||||
RustDesk вітає внески від усіх охочих. Дивіться [CONTRIBUTING.md](CONTRIBUTING.md), щоб дізнатися, з чого почати.
|
||||
RustDesk вітає внесок кожного. Ознайомтеся з [CONTRIBUTING.md](CONTRIBUTING.md), щоб отримати допомогу на початковому етапі.
|
||||
|
||||
[**FAQ**](https://github.com/rustdesk/rustdesk/wiki/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://f-droid.org/badge/get-it-on.png"
|
||||
[<img src="https://fdroid.gitlab.io/artwork/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, оскільки з ним простіше почати. Для збірки версії на Flutter дивіться наш [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml).
|
||||
Стільничні версії використовують Flutter чи Sciter (застаріле) для графічного інтерфейсу. Ця інструкція лише для Sciter, оскільки він є більш простим та дружнім для початківців. Перегляньте [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) для збірки версії на Flutter.
|
||||
|
||||
Динамічну бібліотеку 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) |
|
||||
@@ -47,14 +41,14 @@ RustDesk вітає внески від усіх охочих. Дивіться
|
||||
|
||||
## Кроки для збірки
|
||||
|
||||
- Підготуйте середовище розробки 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/)
|
||||
|
||||
@@ -116,7 +110,7 @@ cd
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
source $HOME/.cargo/env
|
||||
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
|
||||
git clone 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
|
||||
@@ -126,56 +120,54 @@ 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
|
||||
```
|
||||
|
||||
Перша збірка може тривати довше, доки залежності не буде кешовано. Наступні збірки виконуватимуться швидше. Якщо потрібно передати додаткові аргументи команді збірки, додайте їх після `rustdesk-builder` у кінці команди `docker run`. Наприклад, для оптимізованої release-збірки додайте `--release`. Отриманий виконуваний файл буде доступний у каталозі `target` вашої системи та його можна запустити так:
|
||||
Зверніть увагу, що перша збірка може зайняти більше часу, перш ніж залежності будуть кешовані, але наступні збірки будуть виконуватися швидше. Крім того, якщо вам потрібно вказати інші аргументи для команди збірки, ви можете зробити це в кінці команди у змінній `<OPTIONAL-ARGS>`. Наприклад, якщо ви хочете створити оптимізовану версію, ви маєте запустити наведену вище команду і в кінці рядка додати `--release`. Отриманий виконуваний файл буде доступний у цільовій папці вашої системи і може бути запущений за допомогою:
|
||||
|
||||
```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 та інші допоміжні функції, спільні із сервером
|
||||
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, функції файлової системи для передавання файлів, код клавіатури та платформоспецифічний код, що використовуються лише цим застосунком
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфіг, обгортка tcp/udp, protobuf, функції fs для передавання файлів і деякі інші службові функції
|
||||
- **[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)**: застарілий інтерфейс 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 для настільних і мобільних платформ
|
||||
- **[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 для мобільних пристроїв
|
||||
|
||||
## Знімки екрана
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
Aplicación de escritorio remoto de código abierto, la alternativa open source a TeamViewer.
|
||||
Código fuente: https://github.com/rustdesk/rustdesk
|
||||
Documentación: https://rustdesk.com/docs/en/manual/mobile/
|
||||
|
||||
Para que un dispositivo remoto controle tu Android mediante el ratón o el tacto, debes permitir que RustDesk utilice el servicio de "Accesibilidad". RustDesk utiliza la API AccessibilityService para implementar el control remoto en Android.
|
||||
|
||||
Además del control remoto, también puedes transferir archivos fácilmente entre dispositivos Android y ordenadores mediante RustDesk.
|
||||
|
||||
Tienes control total de tus datos, sin preocupaciones de seguridad. Puedes utilizar nuestro servidor rendezvous/relay, optar por el autoalojamiento o escribir tu propio servidor rendezvous/relay. El servidor autoalojado es gratuito y de código abierto: https://github.com/rustdesk/rustdesk-server
|
||||
|
||||
Descarga e instala la versión de escritorio desde: https://rustdesk.com — entonces podrás acceder y controlar tu ordenador desde tu teléfono, o controlar tu teléfono desde tu ordenador.
|
||||
@@ -1 +0,0 @@
|
||||
Aplicación de acceso remoto de código abierto, alternativa a TeamViewer.
|
||||
@@ -1,11 +0,0 @@
|
||||
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.
|
||||
@@ -1 +0,0 @@
|
||||
App open source per desktop remoto, alternativa a TeamViewer.
|
||||
@@ -1,11 +0,0 @@
|
||||
Aplicativo de desktop remoto de código aberto, a alternativa open source ao TeamViewer.
|
||||
Código-fonte: https://github.com/rustdesk/rustdesk
|
||||
Documentação: https://rustdesk.com/docs/pt/client/android/
|
||||
|
||||
Para que um dispositivo remoto controle seu Android via mouse ou toque, você precisa permitir que o RustDesk utilize o serviço de "Acessibilidade". O RustDesk usa a API AccessibilityService para implementar o controle remoto no Android.
|
||||
|
||||
Além do controle remoto, você também pode transferir arquivos entre dispositivos Android e PCs com facilidade usando o RustDesk.
|
||||
|
||||
Você tem controle total dos seus dados, sem preocupações com a segurança. Você pode usar nosso servidor rendezvous/relay, optar pela auto-hospedagem ou criar seu próprio servidor de rendezvous/relay. O servidor auto-hospedado é gratuito e open source: https://github.com/rustdesk/rustdesk-server
|
||||
|
||||
Baixe e instale a versão para desktop em: https://rustdesk.com — então você poderá acessar e controlar seu computador pelo celular ou controlar seu celular pelo computador.
|
||||
@@ -1 +0,0 @@
|
||||
Aplicativo de acesso remoto open source, alternativa ao TeamViewer.
|
||||
@@ -82,17 +82,15 @@ protobuf {
|
||||
}
|
||||
|
||||
android {
|
||||
namespace "com.carriez.flutter_hbb"
|
||||
compileSdkVersion 36
|
||||
compileSdkVersion 34
|
||||
sourceSets {
|
||||
main.java.srcDirs += 'src/main/kotlin'
|
||||
|
||||
main.proto.srcDirs += '../../../libs/base/protos'
|
||||
main.proto.srcDirs += '../../../libs/hbb_common/protos'
|
||||
main.proto.includes += "message.proto"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
coreLibraryDesugaringEnabled true
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
@@ -101,7 +99,7 @@ android {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId "com.carriez.flutter_hbb"
|
||||
minSdkVersion 22
|
||||
targetSdkVersion 36
|
||||
targetSdkVersion 33
|
||||
versionCode flutterVersionCode.toInteger()
|
||||
versionName flutterVersionName
|
||||
}
|
||||
@@ -130,7 +128,6 @@ flutter {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.4'
|
||||
implementation 'com.google.protobuf:protobuf-javalite:3.20.1'
|
||||
implementation "androidx.media:media:1.6.0"
|
||||
implementation 'com.github.getActivity:XXPermissions:18.5'
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="com.carriez.flutter_hbb">
|
||||
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
@@ -30,6 +26,7 @@
|
||||
android:name=".MainApplication"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="RustDesk"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:supportsRtl="true">
|
||||
|
||||
@@ -91,12 +88,7 @@
|
||||
<service
|
||||
android:name=".MainService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse|mediaProjection|microphone">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="@string/foreground_service_special_use_subtype" />
|
||||
</service>
|
||||
android:foregroundServiceType="mediaProjection" />
|
||||
|
||||
<service
|
||||
android:name=".FloatingWindowService"
|
||||
|
||||
@@ -18,40 +18,13 @@ const val AUDIO_SAMPLE_RATE = 48000
|
||||
const val AUDIO_CHANNEL_MASK = AudioFormat.CHANNEL_IN_STEREO
|
||||
|
||||
class AudioRecordHandle(private var context: Context, private var isVideoStart: ()->Boolean, private var isAudioStart: ()->Boolean) {
|
||||
companion object {
|
||||
private const val LOG_TAG = "LOG_AUDIO_RECORD_HANDLE"
|
||||
private const val NO_ACTIVE_PUBLISHERS = 0
|
||||
private var activeAudioFramePublishers = NO_ACTIVE_PUBLISHERS
|
||||
|
||||
@Synchronized
|
||||
private fun acquireAudioFramePublisher() {
|
||||
if (activeAudioFramePublishers == NO_ACTIVE_PUBLISHERS) {
|
||||
FFI.setFrameRawEnable("audio", true)
|
||||
}
|
||||
activeAudioFramePublishers++
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun releaseAudioFramePublisher() {
|
||||
if (activeAudioFramePublishers == NO_ACTIVE_PUBLISHERS) {
|
||||
Log.e(LOG_TAG, "No active audio frame publisher to release")
|
||||
return
|
||||
}
|
||||
activeAudioFramePublishers--
|
||||
if (activeAudioFramePublishers == NO_ACTIVE_PUBLISHERS) {
|
||||
FFI.setFrameRawEnable("audio", false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val logTag = LOG_TAG
|
||||
private val logTag = "LOG_AUDIO_RECORD_HANDLE"
|
||||
|
||||
private var audioRecorder: AudioRecord? = null
|
||||
private var audioReader: AudioReader? = null
|
||||
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 {
|
||||
@@ -106,102 +79,45 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
return
|
||||
}
|
||||
// read f32 to byte , length * 4
|
||||
val bufferSize = 2 * 4 * AudioRecord.getMinBufferSize(
|
||||
minBufferSize = 2 * 4 * AudioRecord.getMinBufferSize(
|
||||
AUDIO_SAMPLE_RATE,
|
||||
AUDIO_CHANNEL_MASK,
|
||||
AUDIO_ENCODING
|
||||
)
|
||||
if (bufferSize <= 0) {
|
||||
if (minBufferSize == 0) {
|
||||
Log.d(logTag, "get min buffer size fail!")
|
||||
return
|
||||
}
|
||||
audioReader = AudioReader(bufferSize, 4)
|
||||
minBufferSize = bufferSize
|
||||
audioReader = AudioReader(minBufferSize, 4)
|
||||
Log.d(logTag, "init audioData len:$minBufferSize")
|
||||
}
|
||||
|
||||
private fun releaseRecorder(recorder: AudioRecord) {
|
||||
try {
|
||||
recorder.release()
|
||||
} finally {
|
||||
if (audioRecorder === recorder) {
|
||||
audioRecorder = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun captureAudio(reader: AudioReader, recorder: AudioRecord) {
|
||||
try {
|
||||
while (audioRecordStat) {
|
||||
reader.readSync(recorder)?.let {
|
||||
FFI.onAudioFrameUpdate(it)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
minBufferSize = 0
|
||||
try {
|
||||
releaseRecorder(recorder)
|
||||
} finally {
|
||||
releaseAudioFramePublisher()
|
||||
Log.d(logTag, "Exit audio thread")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
fun startAudioRecorder(): Boolean {
|
||||
val recorder = audioRecorder
|
||||
if (recorder == null) {
|
||||
Log.d(logTag, "startAudioRecorder fail")
|
||||
return false
|
||||
}
|
||||
var audioFramePublisherAcquired = false
|
||||
return try {
|
||||
checkAudioReader()
|
||||
val reader = audioReader
|
||||
if (reader == null || minBufferSize == 0) {
|
||||
releaseRecorder(recorder)
|
||||
Log.d(logTag, "startAudioRecorder fail")
|
||||
return false
|
||||
}
|
||||
recorder.startRecording()
|
||||
if (recorder.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
|
||||
throw IllegalStateException("AudioRecord failed to enter recording state")
|
||||
}
|
||||
audioRecordStat = true
|
||||
val captureThread = thread(start = false) { captureAudio(reader, recorder) }
|
||||
acquireAudioFramePublisher()
|
||||
audioFramePublisherAcquired = true
|
||||
audioThread = captureThread
|
||||
captureThread.start()
|
||||
true
|
||||
} catch (error: Exception) {
|
||||
audioRecordStat = false
|
||||
audioThread = null
|
||||
Log.e(logTag, "startAudioRecorder fail", error)
|
||||
fun startAudioRecorder() {
|
||||
checkAudioReader()
|
||||
if (audioReader != null && audioRecorder != null && minBufferSize != 0) {
|
||||
try {
|
||||
releaseRecorder(recorder)
|
||||
} finally {
|
||||
if (audioFramePublisherAcquired) {
|
||||
releaseAudioFramePublisher()
|
||||
FFI.setFrameRawEnable("audio", true)
|
||||
audioRecorder!!.startRecording()
|
||||
audioRecordStat = true
|
||||
audioThread = thread {
|
||||
while (audioRecordStat) {
|
||||
audioReader!!.readSync(audioRecorder!!)?.let {
|
||||
FFI.onAudioFrameUpdate(it)
|
||||
}
|
||||
}
|
||||
// let's release here rather than onDestroy to avoid threading issue
|
||||
audioRecorder?.release()
|
||||
audioRecorder = null
|
||||
minBufferSize = 0
|
||||
FFI.setFrameRawEnable("audio", false)
|
||||
Log.d(logTag, "Exit audio thread")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.d(logTag, "startAudioRecorder fail:$e")
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun isVoiceCallActive(): Boolean {
|
||||
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 \"Share screen\" page."
|
||||
} else {
|
||||
"Failed to start voice call."
|
||||
Log.d(logTag, "startAudioRecorder fail")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,9 +137,11 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
if (!isSupportVoiceCall()) {
|
||||
return true
|
||||
}
|
||||
val switched = !isVideoStart() || switchOutVoiceCall(mediaProjection)
|
||||
if (isVideoStart()) {
|
||||
switchOutVoiceCall(mediaProjection)
|
||||
}
|
||||
tryReleaseAudio()
|
||||
return switched
|
||||
return true
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
@@ -232,7 +150,6 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
if (it.getAudioSource() == MediaRecorder.AudioSource.VOICE_COMMUNICATION) {
|
||||
return true
|
||||
}
|
||||
playbackCapturePending = true
|
||||
}
|
||||
audioRecordStat = false
|
||||
audioThread?.join()
|
||||
@@ -242,15 +159,17 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
Log.e(logTag, "createAudioRecorder fail")
|
||||
return false
|
||||
}
|
||||
return startAudioRecorder()
|
||||
startAudioRecorder()
|
||||
return true
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
fun switchOutVoiceCall(mediaProjection: MediaProjection?): Boolean {
|
||||
if (!isVoiceCallActive() && !playbackCapturePending) {
|
||||
return true
|
||||
audioRecorder?.let {
|
||||
if (it.getAudioSource() != MediaRecorder.AudioSource.VOICE_COMMUNICATION) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
playbackCapturePending = true
|
||||
audioRecordStat = false
|
||||
audioThread?.join()
|
||||
|
||||
@@ -258,11 +177,8 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
Log.e(logTag, "createAudioRecorder fail")
|
||||
return false
|
||||
}
|
||||
val started = startAudioRecorder()
|
||||
if (started) {
|
||||
playbackCapturePending = false
|
||||
}
|
||||
return started
|
||||
startAudioRecorder()
|
||||
return true
|
||||
}
|
||||
|
||||
fun tryReleaseAudio() {
|
||||
@@ -272,7 +188,6 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
||||
audioRecordStat = false
|
||||
audioThread?.join()
|
||||
audioThread = null
|
||||
playbackCapturePending = false
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
|
||||
@@ -9,7 +9,6 @@ package com.carriez.flutter_hbb
|
||||
|
||||
import ffi.FFI
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -25,10 +24,6 @@ import android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
|
||||
import android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar
|
||||
import android.media.MediaCodecList
|
||||
import android.media.MediaFormat
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import android.webkit.MimeTypeMap
|
||||
import android.util.DisplayMetrics
|
||||
import androidx.annotation.RequiresApi
|
||||
import org.json.JSONArray
|
||||
@@ -38,9 +33,6 @@ import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import kotlin.concurrent.thread
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
@@ -54,23 +46,6 @@ class MainActivity : FlutterActivity() {
|
||||
private val channelTag = "mChannel"
|
||||
private val logTag = "mMainActivity"
|
||||
private var mainService: MainService? = null
|
||||
private sealed class PendingPicker {
|
||||
data class ImportFiles(val result: MethodChannel.Result) : PendingPicker()
|
||||
data class ExportFile(val source: File, val result: MethodChannel.Result) : PendingPicker()
|
||||
data class ImportDirectory(val result: MethodChannel.Result) : PendingPicker()
|
||||
data class ExportFiles(
|
||||
val sources: List<File>,
|
||||
val rejected: Int,
|
||||
val result: MethodChannel.Result
|
||||
) : PendingPicker()
|
||||
}
|
||||
|
||||
private data class ExportSource(
|
||||
val file: File,
|
||||
val children: List<ExportSource>?
|
||||
)
|
||||
|
||||
private var pendingPicker: PendingPicker? = null
|
||||
|
||||
private var isAudioStart = false
|
||||
private val audioRecordHandle = AudioRecordHandle(this, { false }, { isAudioStart })
|
||||
@@ -116,108 +91,6 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode == REQ_IMPORT_FILES) {
|
||||
val pending = pendingPicker as? PendingPicker.ImportFiles ?: return
|
||||
pendingPicker = null
|
||||
if (resultCode != Activity.RESULT_OK || data == null) {
|
||||
pending.result.success(emptyList<Map<String, String>>())
|
||||
return
|
||||
}
|
||||
|
||||
val uris = linkedSetOf<Uri>()
|
||||
data.data?.let { uris.add(it) }
|
||||
data.clipData?.let { clipData ->
|
||||
for (index in 0 until clipData.itemCount) {
|
||||
uris.add(clipData.getItemAt(index).uri)
|
||||
}
|
||||
}
|
||||
thread {
|
||||
val files = uris.map { uri ->
|
||||
mapOf(
|
||||
"uri" to uri.toString(),
|
||||
"name" to (displayName(uri) ?: uri.lastPathSegment.orEmpty())
|
||||
)
|
||||
}
|
||||
runOnUiThread { pending.result.success(files) }
|
||||
}
|
||||
return
|
||||
}
|
||||
if (requestCode == REQ_EXPORT_FILE) {
|
||||
val pending = pendingPicker as? PendingPicker.ExportFile ?: return
|
||||
pendingPicker = null
|
||||
val destination = data?.data
|
||||
|
||||
if (resultCode != Activity.RESULT_OK || destination == null) {
|
||||
pending.result.success(false)
|
||||
return
|
||||
}
|
||||
|
||||
thread {
|
||||
try {
|
||||
FileInputStream(pending.source).use { input ->
|
||||
contentResolver.openOutputStream(destination, "wt")?.use { output ->
|
||||
input.copyTo(output)
|
||||
} ?: throw IllegalStateException("Unable to open the selected destination")
|
||||
}
|
||||
runOnUiThread { pending.result.success(true) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to export file", e)
|
||||
runOnUiThread {
|
||||
pending.result.error("export_failed", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (requestCode == REQ_IMPORT_DIRECTORY) {
|
||||
val pending = pendingPicker as? PendingPicker.ImportDirectory ?: return
|
||||
pendingPicker = null
|
||||
val treeUri = data?.data
|
||||
if (resultCode != Activity.RESULT_OK || treeUri == null) {
|
||||
pending.result.success(null)
|
||||
return
|
||||
}
|
||||
thread {
|
||||
val selected = mapOf(
|
||||
"uri" to treeUri.toString(),
|
||||
"name" to (treeDisplayName(treeUri) ?: "Imported")
|
||||
)
|
||||
runOnUiThread { pending.result.success(selected) }
|
||||
}
|
||||
return
|
||||
}
|
||||
if (requestCode == REQ_EXPORT_FILES) {
|
||||
val pending = pendingPicker as? PendingPicker.ExportFiles ?: return
|
||||
pendingPicker = null
|
||||
val treeUri = data?.data
|
||||
if (resultCode != Activity.RESULT_OK || treeUri == null) {
|
||||
pending.result.success(null)
|
||||
return
|
||||
}
|
||||
thread {
|
||||
var exported = 0
|
||||
var failed = pending.rejected
|
||||
var processed = 0
|
||||
try {
|
||||
val sources = pending.sources.map { snapshotExportSource(it) }
|
||||
val rootDocId = DocumentsContract.getTreeDocumentId(treeUri)
|
||||
sources.forEach { source ->
|
||||
val ok = source?.let {
|
||||
copyExportSourceToTree(treeUri, rootDocId, it)
|
||||
} ?: false
|
||||
if (ok) exported++ else failed++
|
||||
processed++
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to export selected files", e)
|
||||
failed += pending.sources.size - processed
|
||||
}
|
||||
runOnUiThread {
|
||||
pending.result.success(mapOf("exported" to exported, "failed" to failed))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if (requestCode == REQ_INVOKE_PERMISSION_ACTIVITY_MEDIA_PROJECTION && resultCode == RES_FAILED) {
|
||||
flutterMethodChannel?.invokeMethod("on_media_projection_canceled", null)
|
||||
}
|
||||
@@ -394,242 +267,6 @@ class MainActivity : FlutterActivity() {
|
||||
result.success(false)
|
||||
}
|
||||
}
|
||||
PICK_IMPORT_FILES -> {
|
||||
if (pendingPicker != null) {
|
||||
result.error("picker_in_progress", "Another document picker is already open", null)
|
||||
} else {
|
||||
pendingPicker = PendingPicker.ImportFiles(result)
|
||||
try {
|
||||
startActivityForResult(
|
||||
Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = "*/*"
|
||||
putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||
},
|
||||
REQ_IMPORT_FILES
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
pendingPicker = null
|
||||
result.error("picker_unavailable", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
IMPORT_FILE -> {
|
||||
val arguments = call.arguments as? Map<*, *>
|
||||
val uri = (arguments?.get("uri") as? String)?.let {
|
||||
runCatching { Uri.parse(it) }.getOrNull()
|
||||
}
|
||||
val path = arguments?.get("path") as? String
|
||||
val overwrite = arguments?.get("overwrite") as? Boolean ?: false
|
||||
val destination = path?.let { canonicalAppScopedFile(it) }
|
||||
|
||||
if (uri?.scheme != "content") {
|
||||
result.error("invalid_uri", "The selected document URI is invalid", null)
|
||||
} else if (destination == null ||
|
||||
destination.isDirectory ||
|
||||
destination.parentFile?.isDirectory != true) {
|
||||
result.error("invalid_destination", "The destination is outside app-scoped storage", null)
|
||||
} else {
|
||||
thread {
|
||||
var temporary: File? = null
|
||||
var reservedDestination = false
|
||||
var errorCode = "import_failed"
|
||||
try {
|
||||
val temporaryFile = File.createTempFile(
|
||||
".rustdesk-import-",
|
||||
".tmp",
|
||||
destination.parentFile
|
||||
)
|
||||
temporary = temporaryFile
|
||||
contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(temporaryFile).use { output ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
} ?: throw IllegalStateException("Unable to open the selected document")
|
||||
if (!overwrite) {
|
||||
reservedDestination = destination.createNewFile()
|
||||
if (!reservedDestination) {
|
||||
throw IllegalStateException("The destination already exists")
|
||||
}
|
||||
}
|
||||
if (!temporaryFile.renameTo(destination)) {
|
||||
if (reservedDestination) {
|
||||
destination.delete()
|
||||
}
|
||||
errorCode = "rename_failed"
|
||||
throw IllegalStateException("Unable to replace the destination")
|
||||
}
|
||||
runOnUiThread { result.success(true) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to import file", e)
|
||||
runOnUiThread {
|
||||
result.error(errorCode, e.message, null)
|
||||
}
|
||||
} finally {
|
||||
temporary?.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
EXPORT_FILE -> {
|
||||
val path = (call.arguments as? Map<*, *>)?.get("path") as? String
|
||||
val source = path?.let { canonicalExportSource(it) }
|
||||
|
||||
if (source?.isFile != true) {
|
||||
result.error("invalid_source", "The file is outside app-scoped storage", null)
|
||||
} else if (pendingPicker != null) {
|
||||
result.error("picker_in_progress", "Another document picker is already open", null)
|
||||
} else {
|
||||
val mimeType = MimeTypeMap.getSingleton()
|
||||
.getMimeTypeFromExtension(source.extension.lowercase())
|
||||
?: "application/octet-stream"
|
||||
pendingPicker = PendingPicker.ExportFile(source, result)
|
||||
try {
|
||||
startActivityForResult(
|
||||
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
|
||||
addCategory(Intent.CATEGORY_OPENABLE)
|
||||
type = mimeType
|
||||
putExtra(Intent.EXTRA_TITLE, source.name)
|
||||
},
|
||||
REQ_EXPORT_FILE
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
pendingPicker = null
|
||||
result.error("picker_unavailable", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
PICK_IMPORT_DIRECTORY -> {
|
||||
if (pendingPicker != null) {
|
||||
result.error("picker_in_progress", "Another document picker is already open", null)
|
||||
} else {
|
||||
pendingPicker = PendingPicker.ImportDirectory(result)
|
||||
try {
|
||||
startActivityForResult(
|
||||
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
|
||||
putExtra(Intent.EXTRA_TITLE, "Select the folder to import")
|
||||
},
|
||||
REQ_IMPORT_DIRECTORY
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
pendingPicker = null
|
||||
result.error("picker_unavailable", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
IMPORT_DIRECTORY -> {
|
||||
val arguments = call.arguments as? Map<*, *>
|
||||
val uri = (arguments?.get("uri") as? String)?.let {
|
||||
runCatching { Uri.parse(it) }.getOrNull()
|
||||
}
|
||||
val path = arguments?.get("path") as? String
|
||||
val overwrite = arguments?.get("overwrite") as? Boolean ?: false
|
||||
val destination = path?.let { canonicalAppScopedFile(it) }
|
||||
|
||||
if (uri?.scheme != "content") {
|
||||
result.error("invalid_uri", "The selected document URI is invalid", null)
|
||||
} else if (destination == null ||
|
||||
destination.parentFile?.isDirectory != true ||
|
||||
(destination.exists() && !destination.isDirectory)) {
|
||||
result.error("invalid_destination", "The destination is outside app-scoped storage", null)
|
||||
} else {
|
||||
thread {
|
||||
var temporary: File? = null
|
||||
var backup: File? = null
|
||||
val ok = try {
|
||||
val parent = destination.parentFile
|
||||
?: throw IllegalStateException("The destination has no parent")
|
||||
temporary = File.createTempFile(
|
||||
".rustdesk-import-dir-",
|
||||
".tmp",
|
||||
parent
|
||||
).also {
|
||||
if (!it.delete() || !it.mkdir()) {
|
||||
throw IllegalStateException("Unable to create a temporary folder")
|
||||
}
|
||||
}
|
||||
if (!copyDocumentTreeToFile(uri, temporary!!)) {
|
||||
throw IllegalStateException("Unable to read all folder contents")
|
||||
}
|
||||
if (destination.exists()) {
|
||||
if (!overwrite) {
|
||||
throw IllegalStateException("The destination already exists")
|
||||
}
|
||||
val backupFile = File.createTempFile(
|
||||
".rustdesk-import-backup-",
|
||||
".tmp",
|
||||
parent
|
||||
)
|
||||
if (!backupFile.delete()) {
|
||||
throw IllegalStateException("Unable to prepare the destination backup")
|
||||
}
|
||||
backup = backupFile
|
||||
if (!destination.renameTo(backupFile)) {
|
||||
throw IllegalStateException("Unable to replace the destination")
|
||||
}
|
||||
}
|
||||
if (!temporary!!.renameTo(destination)) {
|
||||
val destinationBackup = backup
|
||||
if (destinationBackup != null &&
|
||||
!destinationBackup.renameTo(destination)
|
||||
) {
|
||||
throw IllegalStateException(
|
||||
"Unable to move the imported folder and restore " +
|
||||
"the destination from $destinationBackup"
|
||||
)
|
||||
}
|
||||
throw IllegalStateException("Unable to move the imported folder")
|
||||
}
|
||||
temporary = null
|
||||
val destinationBackup = backup
|
||||
if (destinationBackup != null &&
|
||||
!destinationBackup.deleteRecursively()
|
||||
) {
|
||||
throw IllegalStateException(
|
||||
"Unable to remove the destination backup: $destinationBackup"
|
||||
)
|
||||
}
|
||||
backup = null
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to import directory", e)
|
||||
false
|
||||
} finally {
|
||||
temporary?.deleteRecursively()
|
||||
}
|
||||
runOnUiThread { result.success(ok) }
|
||||
}
|
||||
}
|
||||
}
|
||||
EXPORT_FILES -> {
|
||||
val paths = (call.arguments as? Map<*, *>)?.get("paths") as? List<*>
|
||||
if (paths.isNullOrEmpty()) {
|
||||
result.error("invalid_source", "The selected files are outside app-scoped storage", null)
|
||||
} else {
|
||||
val sources = paths.mapNotNull {
|
||||
(it as? String)?.let(::canonicalExportSource)
|
||||
}
|
||||
val rejected = paths.size - sources.size
|
||||
if (sources.isEmpty()) {
|
||||
result.success(mapOf("exported" to 0, "failed" to rejected))
|
||||
} else if (pendingPicker != null) {
|
||||
result.error("picker_in_progress", "Another document picker is already open", null)
|
||||
} else {
|
||||
pendingPicker = PendingPicker.ExportFiles(sources, rejected, result)
|
||||
try {
|
||||
startActivityForResult(
|
||||
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
|
||||
putExtra(Intent.EXTRA_TITLE, "Select the destination folder")
|
||||
},
|
||||
REQ_EXPORT_FILES
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
pendingPicker = null
|
||||
result.error("picker_unavailable", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
GET_VALUE -> {
|
||||
if (call.arguments is String) {
|
||||
if (call.arguments == KEY_IS_SUPPORT_VOICE_CALL) {
|
||||
@@ -654,228 +291,6 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun canonicalAppScopedFile(path: String): File? {
|
||||
val file = runCatching { File(path).canonicalFile }.getOrNull() ?: return null
|
||||
val allowedRoots = listOfNotNull(filesDir, getExternalFilesDir(null)).mapNotNull {
|
||||
runCatching { it.canonicalFile }.getOrNull()
|
||||
}
|
||||
return file.takeIf { candidate ->
|
||||
allowedRoots.any { root ->
|
||||
candidate == root || candidate.path.startsWith(root.path + File.separator)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun canonicalExportSource(path: String): File? {
|
||||
val original = File(path).absoluteFile
|
||||
val canonical = canonicalAppScopedFile(path) ?: return null
|
||||
return canonical.takeIf {
|
||||
original.path == canonical.path && (canonical.isFile || canonical.isDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
private fun snapshotExportSource(source: File): ExportSource? {
|
||||
val safeSource = canonicalExportSource(source.path) ?: return null
|
||||
if (safeSource.isFile) return ExportSource(safeSource, null)
|
||||
val sourceChildren = safeSource.listFiles() ?: return null
|
||||
val children = ArrayList<ExportSource>(sourceChildren.size)
|
||||
for (child in sourceChildren) {
|
||||
val snapshot = snapshotExportSource(child) ?: return null
|
||||
children.add(snapshot)
|
||||
}
|
||||
return ExportSource(safeSource, children)
|
||||
}
|
||||
|
||||
private fun copyExportSourceToTree(
|
||||
treeUri: Uri,
|
||||
parentDocId: String,
|
||||
source: ExportSource
|
||||
): Boolean {
|
||||
val children = source.children
|
||||
return if (children == null) {
|
||||
copyFileToTree(treeUri, parentDocId, source.file)
|
||||
} else {
|
||||
copyDirToTree(treeUri, parentDocId, source)
|
||||
}
|
||||
}
|
||||
|
||||
private fun treeDisplayName(treeUri: Uri): String? {
|
||||
return try {
|
||||
val rootDocId = DocumentsContract.getTreeDocumentId(treeUri)
|
||||
val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, rootDocId)
|
||||
contentResolver.query(
|
||||
docUri,
|
||||
arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)?.use { cursor -> if (cursor.moveToFirst()) cursor.getString(0) else null }
|
||||
} catch (e: Exception) {
|
||||
Log.w(logTag, "Failed to read selected folder name", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyDocumentTreeToFile(treeUri: Uri, destinationDir: File): Boolean {
|
||||
val rootDocId = DocumentsContract.getTreeDocumentId(treeUri)
|
||||
return copyChildrenToFile(treeUri, rootDocId, destinationDir)
|
||||
}
|
||||
|
||||
private fun copyChildrenToFile(
|
||||
treeUri: Uri,
|
||||
parentDocId: String,
|
||||
destinationDir: File
|
||||
): Boolean {
|
||||
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocId)
|
||||
var ok = true
|
||||
val destinationNames = HashSet<String>()
|
||||
val cursor = contentResolver.query(childrenUri, childColumns, null, null, null)
|
||||
?: return false
|
||||
cursor.use {
|
||||
while (cursor.moveToNext()) {
|
||||
val docId = cursor.getString(0)
|
||||
val name = cursor.getString(1)
|
||||
val mime = cursor.getString(2)
|
||||
val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId)
|
||||
if (name != null && !destinationNames.add(name)) {
|
||||
ok = false
|
||||
continue
|
||||
}
|
||||
val destination = safeDestinationChild(destinationDir, name)
|
||||
if (destination == null || destination.exists()) {
|
||||
ok = false
|
||||
continue
|
||||
}
|
||||
if (mime == DocumentsContract.Document.MIME_TYPE_DIR) {
|
||||
if (!destination.mkdirs() && !destination.isDirectory) {
|
||||
ok = false
|
||||
continue
|
||||
}
|
||||
if (!copyChildrenToFile(treeUri, docId, destination)) {
|
||||
ok = false
|
||||
}
|
||||
} else if (!copyDocumentToFile(docUri, destination)) {
|
||||
ok = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
private fun safeDestinationChild(destinationDir: File, name: String?): File? {
|
||||
if (name.isNullOrEmpty() || name == "." || name == ".." ||
|
||||
name.indexOf('\u0000') >= 0 || name.contains('/') || name.contains('\\')) {
|
||||
return null
|
||||
}
|
||||
val parent = runCatching { destinationDir.canonicalFile }.getOrNull() ?: return null
|
||||
val child = runCatching { File(parent, name).canonicalFile }.getOrNull() ?: return null
|
||||
return child.takeIf { it.path.startsWith(parent.path + File.separator) }
|
||||
}
|
||||
|
||||
private fun copyDocumentToFile(uri: Uri, destination: File): Boolean {
|
||||
return try {
|
||||
destination.parentFile?.mkdirs()
|
||||
if (destination.exists() && !destination.delete()) {
|
||||
return false
|
||||
}
|
||||
contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(destination).use { output -> input.copyTo(output) }
|
||||
} != null
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to copy document to $destination", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyFileToTree(treeUri: Uri, parentDocId: String, source: File): Boolean {
|
||||
val safeSource = canonicalExportSource(source.path)?.takeIf { it.isFile } ?: return false
|
||||
return try {
|
||||
val mime = MimeTypeMap.getSingleton()
|
||||
.getMimeTypeFromExtension(safeSource.extension.lowercase())
|
||||
?: "application/octet-stream"
|
||||
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, parentDocId)
|
||||
val docUri = DocumentsContract.createDocument(
|
||||
contentResolver,
|
||||
parentUri,
|
||||
mime,
|
||||
safeSource.name
|
||||
) ?: return false
|
||||
contentResolver.openOutputStream(docUri, "wt")?.use { output ->
|
||||
FileInputStream(safeSource).use { input -> input.copyTo(output) }
|
||||
} ?: return false
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to export file $safeSource", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyDirToTree(
|
||||
treeUri: Uri,
|
||||
parentDocId: String,
|
||||
source: ExportSource
|
||||
): Boolean {
|
||||
val children = source.children ?: return false
|
||||
val safeSource = canonicalExportSource(source.file.path)?.takeIf { it.isDirectory }
|
||||
?: return false
|
||||
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, parentDocId)
|
||||
var dirDocId = findChildDocId(treeUri, parentDocId, safeSource.name)
|
||||
if (dirDocId == null) {
|
||||
dirDocId = try {
|
||||
DocumentsContract.createDocument(
|
||||
contentResolver,
|
||||
parentUri,
|
||||
DocumentsContract.Document.MIME_TYPE_DIR,
|
||||
safeSource.name
|
||||
)?.let { DocumentsContract.getDocumentId(it) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(logTag, "Failed to create folder ${safeSource.name}", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
if (dirDocId == null) return false
|
||||
|
||||
var ok = true
|
||||
children.forEach { child ->
|
||||
val childOk = copyExportSourceToTree(treeUri, dirDocId, child)
|
||||
if (!childOk) ok = false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
private fun findChildDocId(treeUri: Uri, parentDocId: String, name: String): String? {
|
||||
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocId)
|
||||
val cursor = contentResolver.query(childrenUri, childColumns, null, null, null)
|
||||
?: throw IllegalStateException("Unable to query destination folder")
|
||||
cursor.use {
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(1) == name &&
|
||||
cursor.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR
|
||||
) {
|
||||
return cursor.getString(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private val childColumns = arrayOf(
|
||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||
DocumentsContract.Document.COLUMN_MIME_TYPE
|
||||
)
|
||||
|
||||
private fun displayName(uri: Uri): String? {
|
||||
return try {
|
||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
|
||||
if (cursor.moveToFirst()) cursor.getString(0) else null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(logTag, "Failed to read selected document name", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun setCodecInfo() {
|
||||
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
|
||||
val codecs = codecList.codecInfos
|
||||
@@ -969,7 +384,7 @@ class MainActivity : FlutterActivity() {
|
||||
flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to audioRecordHandle.getVoiceCallStartError()))
|
||||
"text" to "Failed to start voice call."))
|
||||
} else {
|
||||
Log.d(logTag, "onVoiceCallStarted success")
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ import android.app.PendingIntent.FLAG_UPDATE_CURRENT
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.content.res.Configuration
|
||||
import android.content.res.Configuration.ORIENTATION_LANDSCAPE
|
||||
import android.graphics.Color
|
||||
@@ -151,15 +150,21 @@ class MainService : Service() {
|
||||
if (incomingVoiceCall) {
|
||||
voiceCallRequestNotification(id, "Voice Call Request", username, peerId)
|
||||
} else {
|
||||
if (!switchOutVoiceCall()) {
|
||||
if (!audioRecordHandle.switchOutVoiceCall(mediaProjection)) {
|
||||
Log.e(logTag, "switchOutVoiceCall fail")
|
||||
showVoiceCallError("Failed to switch out voice call.")
|
||||
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to "Failed to switch out voice call."))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!switchToVoiceCall()) {
|
||||
if (!audioRecordHandle.switchToVoiceCall(mediaProjection)) {
|
||||
Log.e(logTag, "switchToVoiceCall fail")
|
||||
showVoiceCallError(audioRecordHandle.getVoiceCallStartError())
|
||||
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
|
||||
"type" to "custom-nook-nocancel-hasclose-error",
|
||||
"title" to "Voice call",
|
||||
"text" to "Failed to switch to voice call."))
|
||||
}
|
||||
}
|
||||
} catch (e: JSONException) {
|
||||
@@ -209,19 +214,6 @@ class MainService : Service() {
|
||||
|
||||
// video
|
||||
private var mediaProjection: MediaProjection? = null
|
||||
private var mediaProjectionCallback: MediaProjection.Callback? = null
|
||||
private var captureRestartPending = false
|
||||
private var captureRestartInVoiceCall = false
|
||||
private val mediaProjectionResultReceiver =
|
||||
object : ResultReceiver(Handler(Looper.getMainLooper())) {
|
||||
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
|
||||
if (resultCode == RES_FAILED) {
|
||||
cancelMediaProjectionRecovery()
|
||||
}
|
||||
}
|
||||
}
|
||||
private var mediaProjectionForegroundService = false
|
||||
private var microphoneForegroundService = false
|
||||
private var surface: Surface? = null
|
||||
private val sendVP9Thread = Executors.newSingleThreadExecutor()
|
||||
private var videoEncoder: MediaCodec? = null
|
||||
@@ -251,9 +243,7 @@ class MainService : Service() {
|
||||
// keep the config dir same with flutter
|
||||
val prefs = applicationContext.getSharedPreferences(KEY_SHARED_PREFERENCES, FlutterActivity.MODE_PRIVATE)
|
||||
val configPath = prefs.getString(KEY_APP_DIR_CONFIG_PATH, "") ?: ""
|
||||
val homePath = applicationContext.getExternalFilesDir(null)?.absolutePath
|
||||
?: applicationContext.filesDir.absolutePath
|
||||
FFI.startServer(configPath, homePath, "")
|
||||
FFI.startServer(configPath, "")
|
||||
|
||||
createForegroundNotification()
|
||||
}
|
||||
@@ -347,6 +337,8 @@ class MainService : Service() {
|
||||
Log.d("whichService", "this service: ${Thread.currentThread()}")
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
if (intent?.action == ACT_INIT_MEDIA_PROJECTION_AND_SERVICE) {
|
||||
createForegroundNotification()
|
||||
|
||||
if (intent.getBooleanExtra(EXT_INIT_FROM_BOOT, false)) {
|
||||
FFI.startService()
|
||||
}
|
||||
@@ -355,7 +347,10 @@ class MainService : Service() {
|
||||
getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
|
||||
intent.getParcelableExtra<Intent>(EXT_MEDIA_PROJECTION_RES_INTENT)?.let {
|
||||
replaceMediaProjection(mediaProjectionManager, it)
|
||||
mediaProjection =
|
||||
mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, it)
|
||||
checkMediaPermission()
|
||||
_isReady = true
|
||||
} ?: let {
|
||||
Log.d(logTag, "getParcelableExtra intent null, invoke requestMediaProjection")
|
||||
requestMediaProjection()
|
||||
@@ -369,23 +364,14 @@ class MainService : Service() {
|
||||
updateScreenInfo(newConfig.orientation)
|
||||
}
|
||||
|
||||
private fun requestMediaProjection(recovery: Boolean = false) {
|
||||
private fun requestMediaProjection() {
|
||||
val intent = Intent(this, PermissionRequestTransparentActivity::class.java).apply {
|
||||
action = ACT_REQUEST_MEDIA_PROJECTION
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
if (recovery) {
|
||||
putExtra(EXT_MEDIA_PROJECTION_RESULT_RECEIVER, mediaProjectionResultReceiver)
|
||||
}
|
||||
}
|
||||
startActivity(intent)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun cancelMediaProjectionRecovery() {
|
||||
captureRestartPending = false
|
||||
captureRestartInVoiceCall = false
|
||||
}
|
||||
|
||||
@SuppressLint("WrongConstant")
|
||||
private fun createSurface(): Surface? {
|
||||
return if (useVP9) {
|
||||
@@ -419,158 +405,15 @@ class MainService : Service() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseMediaProjection() {
|
||||
val projection = mediaProjection
|
||||
val callback = mediaProjectionCallback
|
||||
mediaProjection = null
|
||||
mediaProjectionCallback = null
|
||||
if (projection != null && callback != null) {
|
||||
projection.unregisterCallback(callback)
|
||||
}
|
||||
projection?.stop()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun handleMediaProjectionStopped(stoppedProjection: MediaProjection) {
|
||||
if (mediaProjection !== stoppedProjection) {
|
||||
return
|
||||
}
|
||||
Log.d(logTag, "MediaProjection stopped")
|
||||
setMediaProjectionForegroundService(false)
|
||||
stopCapture()
|
||||
virtualDisplay?.release()
|
||||
virtualDisplay = null
|
||||
mediaProjection = null
|
||||
mediaProjectionCallback = null
|
||||
_isReady = false
|
||||
checkMediaPermission()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun replaceMediaProjection(
|
||||
mediaProjectionManager: MediaProjectionManager,
|
||||
resultIntent: Intent,
|
||||
) {
|
||||
val wasCapturing = isStart
|
||||
val restartCapture = wasCapturing || captureRestartPending
|
||||
val restartInVoiceCall = if (wasCapturing) {
|
||||
audioRecordHandle.isVoiceCallActive()
|
||||
} else {
|
||||
captureRestartInVoiceCall
|
||||
}
|
||||
val hadProjection = mediaProjection != null
|
||||
if (!setMediaProjectionForegroundService(true)) {
|
||||
if (!hadProjection) {
|
||||
cancelMediaProjectionRecovery()
|
||||
_isReady = false
|
||||
checkMediaPermission()
|
||||
}
|
||||
return
|
||||
}
|
||||
val projection =
|
||||
mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, resultIntent)
|
||||
if (projection == null) {
|
||||
if (!hadProjection) {
|
||||
cancelMediaProjectionRecovery()
|
||||
_isReady = false
|
||||
setMediaProjectionForegroundService(false)
|
||||
checkMediaPermission()
|
||||
}
|
||||
return
|
||||
}
|
||||
if (wasCapturing) {
|
||||
stopCapture()
|
||||
}
|
||||
captureRestartPending = restartCapture
|
||||
virtualDisplay?.release()
|
||||
virtualDisplay = null
|
||||
releaseMediaProjection()
|
||||
val callback = object : MediaProjection.Callback() {
|
||||
override fun onStop() {
|
||||
handleMediaProjectionStopped(projection)
|
||||
}
|
||||
}
|
||||
projection.registerCallback(callback, Handler(Looper.getMainLooper()))
|
||||
mediaProjection = projection
|
||||
mediaProjectionCallback = callback
|
||||
_isReady = true
|
||||
checkMediaPermission()
|
||||
if (restartCapture) {
|
||||
captureRestartPending = false
|
||||
startCapture(restartInVoiceCall)
|
||||
}
|
||||
}
|
||||
|
||||
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)) {
|
||||
return false
|
||||
}
|
||||
if (startAudio()) {
|
||||
return true
|
||||
}
|
||||
setMicrophoneForegroundService(false)
|
||||
return false
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun stopMicrophoneCapture(stopAudio: () -> Boolean): Boolean {
|
||||
val stopped = stopAudio()
|
||||
val foregroundServiceUpdated = setMicrophoneForegroundService(false)
|
||||
return stopped && foregroundServiceUpdated
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun switchToVoiceCall(): Boolean {
|
||||
if (captureRestartPending) {
|
||||
captureRestartInVoiceCall = true
|
||||
}
|
||||
return startMicrophoneCapture {
|
||||
audioRecordHandle.switchToVoiceCall(mediaProjection)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun switchOutVoiceCall(): Boolean {
|
||||
captureRestartInVoiceCall = false
|
||||
val switched = audioRecordHandle.switchOutVoiceCall(mediaProjection)
|
||||
val foregroundServiceUpdated = setMicrophoneForegroundService(false)
|
||||
return switched && foregroundServiceUpdated
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun onVoiceCallStarted(): Boolean {
|
||||
if (captureRestartPending) {
|
||||
captureRestartInVoiceCall = true
|
||||
}
|
||||
return startMicrophoneCapture {
|
||||
audioRecordHandle.onVoiceCallStarted(mediaProjection)
|
||||
}
|
||||
return audioRecordHandle.onVoiceCallStarted(mediaProjection)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun onVoiceCallClosed(): Boolean {
|
||||
captureRestartInVoiceCall = false
|
||||
return stopMicrophoneCapture {
|
||||
audioRecordHandle.onVoiceCallClosed(mediaProjection)
|
||||
}
|
||||
return audioRecordHandle.onVoiceCallClosed(mediaProjection)
|
||||
}
|
||||
|
||||
fun startCapture(): Boolean {
|
||||
return startCapture(false)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun startCapture(inVoiceCall: Boolean): Boolean {
|
||||
if (isStart) {
|
||||
return true
|
||||
}
|
||||
@@ -578,35 +421,25 @@ class MainService : Service() {
|
||||
Log.w(logTag, "startCapture fail,mediaProjection is null")
|
||||
return false
|
||||
}
|
||||
captureRestartInVoiceCall = inVoiceCall
|
||||
|
||||
updateScreenInfo(resources.configuration.orientation)
|
||||
Log.d(logTag, "Start Capture")
|
||||
surface = createSurface()
|
||||
|
||||
val videoStarted = if (useVP9) {
|
||||
if (useVP9) {
|
||||
startVP9VideoRecorder(mediaProjection!!)
|
||||
} else {
|
||||
startRawVideoRecorder(mediaProjection!!)
|
||||
}
|
||||
if (!videoStarted) {
|
||||
if (!captureRestartPending) {
|
||||
captureRestartInVoiceCall = false
|
||||
}
|
||||
releaseFailedVideoCapture()
|
||||
return false
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val audioStarted = if (inVoiceCall) {
|
||||
switchToVoiceCall()
|
||||
if (!audioRecordHandle.createAudioRecorder(false, mediaProjection)) {
|
||||
Log.d(logTag, "createAudioRecorder fail")
|
||||
} else {
|
||||
audioRecordHandle.createAudioRecorder(false, mediaProjection) &&
|
||||
audioRecordHandle.startAudioRecorder()
|
||||
Log.d(logTag, "audio recorder start")
|
||||
audioRecordHandle.startAudioRecorder()
|
||||
}
|
||||
Log.d(logTag, if (audioStarted) "audio recorder start" else "audio recorder start failed")
|
||||
}
|
||||
captureRestartInVoiceCall = false
|
||||
checkMediaPermission()
|
||||
_isStart = true
|
||||
FFI.setFrameRawEnable("video",true)
|
||||
@@ -614,24 +447,9 @@ class MainService : Service() {
|
||||
return true
|
||||
}
|
||||
|
||||
private fun releaseFailedVideoCapture() {
|
||||
imageReader?.close()
|
||||
imageReader = null
|
||||
videoEncoder?.let {
|
||||
it.signalEndOfInputStream()
|
||||
it.stop()
|
||||
it.release()
|
||||
}
|
||||
videoEncoder = null
|
||||
surface?.release()
|
||||
surface = null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stopCapture() {
|
||||
Log.d(logTag, "Stop Capture")
|
||||
captureRestartPending = false
|
||||
captureRestartInVoiceCall = false
|
||||
FFI.setFrameRawEnable("video",false)
|
||||
_isStart = false
|
||||
MainActivity.rdClipboardManager?.setCaptureStarted(_isStart)
|
||||
@@ -662,11 +480,8 @@ class MainService : Service() {
|
||||
surface?.release()
|
||||
|
||||
// release audio
|
||||
stopMicrophoneCapture {
|
||||
_isAudioStart = false
|
||||
audioRecordHandle.tryReleaseAudio()
|
||||
true
|
||||
}
|
||||
_isAudioStart = false
|
||||
audioRecordHandle.tryReleaseAudio()
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
@@ -681,9 +496,7 @@ class MainService : Service() {
|
||||
virtualDisplay = null
|
||||
}
|
||||
|
||||
releaseMediaProjection()
|
||||
mediaProjectionForegroundService = false
|
||||
microphoneForegroundService = false
|
||||
mediaProjection = null
|
||||
checkMediaPermission()
|
||||
stopForeground(true)
|
||||
stopService(Intent(this, FloatingWindowService::class.java))
|
||||
@@ -706,70 +519,49 @@ class MainService : Service() {
|
||||
return isReady
|
||||
}
|
||||
|
||||
private fun startRawVideoRecorder(mp: MediaProjection): Boolean {
|
||||
private fun startRawVideoRecorder(mp: MediaProjection) {
|
||||
Log.d(logTag, "startRawVideoRecorder,screen info:$SCREEN_INFO")
|
||||
val captureSurface = surface
|
||||
if (captureSurface == null) {
|
||||
if (surface == null) {
|
||||
Log.d(logTag, "startRawVideoRecorder failed,surface is null")
|
||||
return false
|
||||
return
|
||||
}
|
||||
return createOrSetVirtualDisplay(mp, captureSurface)
|
||||
createOrSetVirtualDisplay(mp, surface!!)
|
||||
}
|
||||
|
||||
private fun startVP9VideoRecorder(mp: MediaProjection): Boolean {
|
||||
private fun startVP9VideoRecorder(mp: MediaProjection) {
|
||||
createMediaCodec()
|
||||
val encoder = videoEncoder ?: return false
|
||||
val inputSurface = encoder.createInputSurface()
|
||||
surface = inputSurface
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
inputSurface.setFrameRate(1F, FRAME_RATE_COMPATIBILITY_DEFAULT)
|
||||
videoEncoder?.let {
|
||||
surface = it.createInputSurface()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
surface!!.setFrameRate(1F, FRAME_RATE_COMPATIBILITY_DEFAULT)
|
||||
}
|
||||
it.setCallback(cb)
|
||||
it.start()
|
||||
createOrSetVirtualDisplay(mp, surface!!)
|
||||
}
|
||||
encoder.setCallback(cb)
|
||||
encoder.start()
|
||||
return createOrSetVirtualDisplay(mp, inputSurface)
|
||||
}
|
||||
|
||||
// https://github.com/bk138/droidVNC-NG/blob/b79af62db5a1c08ed94e6a91464859ffed6f4e97/app/src/main/java/net/christianbeier/droidvnc_ng/MediaProjectionService.java#L250
|
||||
// Reuse virtualDisplay if it exists, to avoid media projection confirmation dialog every connection.
|
||||
private fun createOrSetVirtualDisplay(mp: MediaProjection, s: Surface): Boolean {
|
||||
return try {
|
||||
val existingDisplay = virtualDisplay
|
||||
if (existingDisplay != null) {
|
||||
existingDisplay.resize(SCREEN_INFO.width, SCREEN_INFO.height, SCREEN_INFO.dpi)
|
||||
existingDisplay.setSurface(s)
|
||||
true
|
||||
} else {
|
||||
val display = mp.createVirtualDisplay(
|
||||
private fun createOrSetVirtualDisplay(mp: MediaProjection, s: Surface) {
|
||||
try {
|
||||
virtualDisplay?.let {
|
||||
it.resize(SCREEN_INFO.width, SCREEN_INFO.height, SCREEN_INFO.dpi)
|
||||
it.setSurface(s)
|
||||
} ?: let {
|
||||
virtualDisplay = mp.createVirtualDisplay(
|
||||
"RustDeskVD",
|
||||
SCREEN_INFO.width, SCREEN_INFO.height, SCREEN_INFO.dpi, VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
s, null, null
|
||||
)
|
||||
if (display == null) {
|
||||
Log.e(logTag, "createOrSetVirtualDisplay failed")
|
||||
handleVirtualDisplayFailure()
|
||||
} else {
|
||||
virtualDisplay = display
|
||||
true
|
||||
}
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(logTag, "createOrSetVirtualDisplay: got SecurityException", e)
|
||||
handleVirtualDisplayFailure()
|
||||
Log.w(logTag, "createOrSetVirtualDisplay: got SecurityException, re-requesting confirmation");
|
||||
// This initiates a prompt dialog for the user to confirm screen projection.
|
||||
requestMediaProjection()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleVirtualDisplayFailure(): Boolean {
|
||||
captureRestartPending = true
|
||||
virtualDisplay?.release()
|
||||
virtualDisplay = null
|
||||
releaseMediaProjection()
|
||||
setMediaProjectionForegroundService(false)
|
||||
_isReady = false
|
||||
checkMediaPermission()
|
||||
requestMediaProjection(true)
|
||||
return false
|
||||
}
|
||||
|
||||
private val cb: MediaCodec.Callback = object : MediaCodec.Callback() {
|
||||
override fun onInputBufferAvailable(codec: MediaCodec, index: Int) {}
|
||||
override fun onOutputFormatChanged(codec: MediaCodec, format: MediaFormat) {}
|
||||
@@ -860,63 +652,7 @@ class MainService : Service() {
|
||||
.setColor(ContextCompat.getColor(this, R.color.primary))
|
||||
.setWhen(System.currentTimeMillis())
|
||||
.build()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(DEFAULT_NOTIFY_ID, notification, foregroundServiceType())
|
||||
} else {
|
||||
startForeground(DEFAULT_NOTIFY_ID, notification)
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
private fun foregroundServiceType(): Int {
|
||||
var serviceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
// Keep a valid FGS type while the unattended host is idle and no capture type is active.
|
||||
serviceType = serviceType or ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
|
||||
}
|
||||
if (mediaProjectionForegroundService) {
|
||||
serviceType = serviceType or ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && microphoneForegroundService) {
|
||||
serviceType = serviceType or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
|
||||
}
|
||||
return serviceType
|
||||
}
|
||||
|
||||
private fun setMediaProjectionForegroundService(enabled: Boolean): Boolean {
|
||||
return updateForegroundServiceTypes(enabled, microphoneForegroundService)
|
||||
}
|
||||
|
||||
private fun setMicrophoneForegroundService(enabled: Boolean): Boolean {
|
||||
return updateForegroundServiceTypes(mediaProjectionForegroundService, enabled)
|
||||
}
|
||||
|
||||
private fun updateForegroundServiceTypes(
|
||||
mediaProjectionEnabled: Boolean,
|
||||
microphoneEnabled: Boolean,
|
||||
): Boolean {
|
||||
if (mediaProjectionForegroundService == mediaProjectionEnabled &&
|
||||
microphoneForegroundService == microphoneEnabled) {
|
||||
return true
|
||||
}
|
||||
val previousMediaProjection = mediaProjectionForegroundService
|
||||
val previousMicrophone = microphoneForegroundService
|
||||
mediaProjectionForegroundService = mediaProjectionEnabled
|
||||
microphoneForegroundService = microphoneEnabled
|
||||
return try {
|
||||
createForegroundNotification()
|
||||
true
|
||||
} catch (error: SecurityException) {
|
||||
mediaProjectionForegroundService = previousMediaProjection
|
||||
microphoneForegroundService = previousMicrophone
|
||||
Log.e(logTag, "Failed to update foreground service types", error)
|
||||
false
|
||||
} catch (error: IllegalStateException) {
|
||||
mediaProjectionForegroundService = previousMediaProjection
|
||||
microphoneForegroundService = previousMicrophone
|
||||
Log.e(logTag, "Failed to update foreground service types", error)
|
||||
false
|
||||
}
|
||||
startForeground(DEFAULT_NOTIFY_ID, notification)
|
||||
}
|
||||
|
||||
private fun loginRequestNotification(
|
||||
|
||||
+3
-17
@@ -2,11 +2,9 @@ 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
|
||||
import android.os.ResultReceiver
|
||||
import android.util.Log
|
||||
|
||||
class PermissionRequestTransparentActivity: Activity() {
|
||||
@@ -20,13 +18,7 @@ class PermissionRequestTransparentActivity: Activity() {
|
||||
ACT_REQUEST_MEDIA_PROJECTION -> {
|
||||
val mediaProjectionManager =
|
||||
getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
mediaProjectionManager.createScreenCaptureIntent(
|
||||
MediaProjectionConfig.createConfigForDefaultDisplay()
|
||||
)
|
||||
} else {
|
||||
mediaProjectionManager.createScreenCaptureIntent()
|
||||
}
|
||||
val intent = mediaProjectionManager.createScreenCaptureIntent()
|
||||
startActivityForResult(intent, REQ_REQUEST_MEDIA_PROJECTION)
|
||||
}
|
||||
else -> finish()
|
||||
@@ -39,13 +31,7 @@ class PermissionRequestTransparentActivity: Activity() {
|
||||
if (resultCode == RESULT_OK && data != null) {
|
||||
launchService(data)
|
||||
} else {
|
||||
val resultReceiver =
|
||||
intent.getParcelableExtra<ResultReceiver>(EXT_MEDIA_PROJECTION_RESULT_RECEIVER)
|
||||
if (resultReceiver != null) {
|
||||
resultReceiver.send(RES_FAILED, null)
|
||||
} else {
|
||||
setResult(RES_FAILED)
|
||||
}
|
||||
setResult(RES_FAILED)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,4 +51,4 @@ class PermissionRequestTransparentActivity: Activity() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -33,16 +33,11 @@ const val ACT_INIT_MEDIA_PROJECTION_AND_SERVICE = "INIT_MEDIA_PROJECTION_AND_SER
|
||||
const val ACT_LOGIN_REQ_NOTIFY = "LOGIN_REQ_NOTIFY"
|
||||
const val EXT_INIT_FROM_BOOT = "EXT_INIT_FROM_BOOT"
|
||||
const val EXT_MEDIA_PROJECTION_RES_INTENT = "MEDIA_PROJECTION_RES_INTENT"
|
||||
const val EXT_MEDIA_PROJECTION_RESULT_RECEIVER = "MEDIA_PROJECTION_RESULT_RECEIVER"
|
||||
const val EXT_LOGIN_REQ_NOTIFY = "LOGIN_REQ_NOTIFY"
|
||||
|
||||
// Activity requestCode
|
||||
const val REQ_INVOKE_PERMISSION_ACTIVITY_MEDIA_PROJECTION = 101
|
||||
const val REQ_REQUEST_MEDIA_PROJECTION = 201
|
||||
const val REQ_EXPORT_FILE = 301
|
||||
const val REQ_IMPORT_FILES = 302
|
||||
const val REQ_IMPORT_DIRECTORY = 303
|
||||
const val REQ_EXPORT_FILES = 304
|
||||
|
||||
// Activity responseCode
|
||||
const val RES_FAILED = -100
|
||||
@@ -52,12 +47,6 @@ const val START_ACTION = "start_action"
|
||||
const val GET_START_ON_BOOT_OPT = "get_start_on_boot_opt"
|
||||
const val SET_START_ON_BOOT_OPT = "set_start_on_boot_opt"
|
||||
const val SYNC_APP_DIR_CONFIG_PATH = "sync_app_dir"
|
||||
const val PICK_IMPORT_FILES = "pick_import_files"
|
||||
const val IMPORT_FILE = "import_file"
|
||||
const val EXPORT_FILE = "export_file"
|
||||
const val PICK_IMPORT_DIRECTORY = "pick_import_directory"
|
||||
const val IMPORT_DIRECTORY = "import_directory"
|
||||
const val EXPORT_FILES = "export_files"
|
||||
const val GET_VALUE = "get_value"
|
||||
|
||||
const val KEY_IS_SUPPORT_VOICE_CALL = "KEY_IS_SUPPORT_VOICE_CALL"
|
||||
@@ -165,4 +154,4 @@ fun getScreenSize(windowManager: WindowManager) : Pair<Int, Int>{
|
||||
fun translate(input: String): String {
|
||||
Log.d("common", "translate:$LOCAL_NAME")
|
||||
return FFI.translateLocale(LOCAL_NAME, input)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ object FFI {
|
||||
external fun init(ctx: Context)
|
||||
external fun onAppStart(ctx: Context)
|
||||
external fun setClipboardManager(clipboardManager: RdClipboardManager)
|
||||
external fun startServer(app_dir: String, home_dir: String, custom_client_config: String)
|
||||
external fun startServer(app_dir: String, custom_client_config: String)
|
||||
external fun startService()
|
||||
external fun onVideoFrameUpdate(buf: ByteBuffer)
|
||||
external fun onAudioFrameUpdate(buf: ByteBuffer)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">RustDesk</string>
|
||||
<string name="accessibility_service_description">Allow other devices to control your phone using virtual touch, when RustDesk screen sharing is established</string>
|
||||
<string name="foreground_service_special_use_subtype">Keeps the RustDesk remote desktop host available for authorized unattended connections and foreground notifications without starting screen capture before user approval.</string>
|
||||
</resources>
|
||||
|
||||
@@ -1,29 +1,3 @@
|
||||
def legacyPluginNamespaces = [
|
||||
external_path: 'com.pinciat.external_path',
|
||||
flutter_keyboard_visibility: 'com.jrai.flutter_keyboard_visibility',
|
||||
qr_code_scanner: 'net.touchcapture.qr.flutterqr',
|
||||
sqflite: 'com.tekartik.sqflite',
|
||||
uni_links: 'name.avioli.unilinks',
|
||||
]
|
||||
|
||||
def java8JvmTarget = JavaVersion.VERSION_1_8.toString()
|
||||
def java8KotlinJvmTargets = [
|
||||
app: java8JvmTarget,
|
||||
external_path: java8JvmTarget,
|
||||
qr_code_scanner: java8JvmTarget,
|
||||
]
|
||||
|
||||
def configureKotlinJvmTarget = { Project project, String kotlinJvmTarget ->
|
||||
project.plugins.withId('kotlin-android') {
|
||||
project.tasks.configureEach { task ->
|
||||
if (!task.hasProperty('kotlinOptions')) {
|
||||
return
|
||||
}
|
||||
task.kotlinOptions.jvmTarget = kotlinJvmTarget
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
@@ -35,16 +9,6 @@ allprojects {
|
||||
rootProject.buildDir = '../build'
|
||||
subprojects {
|
||||
project.buildDir = "${rootProject.buildDir}/${project.name}"
|
||||
def legacyNamespace = legacyPluginNamespaces[project.name]
|
||||
if (legacyNamespace != null) {
|
||||
project.plugins.withId('com.android.library') {
|
||||
project.android.namespace = legacyNamespace
|
||||
}
|
||||
}
|
||||
def kotlinJvmTarget = java8KotlinJvmTargets[project.name]
|
||||
if (kotlinJvmTarget != null) {
|
||||
configureKotlinJvmTarget(project, kotlinJvmTarget)
|
||||
}
|
||||
}
|
||||
subprojects {
|
||||
project.evaluationDependsOn(':app')
|
||||
|
||||
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-all.zip
|
||||
|
||||
@@ -18,7 +18,7 @@ pluginManagement {
|
||||
|
||||
plugins {
|
||||
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
|
||||
id "com.android.application" version "8.10.1" apply false
|
||||
id "com.android.application" version "7.3.1" apply false
|
||||
id "org.jetbrains.kotlin.android" version "2.1.21" apply false
|
||||
}
|
||||
|
||||
|
||||
+15
-2
@@ -1519,6 +1519,13 @@ class AndroidPermissionManager {
|
||||
static Timer? _timer;
|
||||
static var _current = "";
|
||||
|
||||
static bool isWaitingFile() {
|
||||
if (_completer != null) {
|
||||
return !_completer!.isCompleted && _current == kManageExternalStorage;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Future<bool> check(String type) {
|
||||
if (isDesktop || isWeb) {
|
||||
return Future.value(true);
|
||||
@@ -1633,8 +1640,7 @@ String bool2option(String option, bool b) {
|
||||
String res;
|
||||
if (option.startsWith('enable-') &&
|
||||
option != kOptionEnableUdpPunch &&
|
||||
option != kOptionEnableIpv6Punch &&
|
||||
option != kOptionEnableWebrtc) {
|
||||
option != kOptionEnableIpv6Punch) {
|
||||
res = b ? defaultOptionYes : 'N';
|
||||
} else if (option.startsWith('allow-') ||
|
||||
option == kOptionStopService ||
|
||||
@@ -2628,6 +2634,13 @@ connect(BuildContext context, String id,
|
||||
}
|
||||
} else {
|
||||
if (isFileTransfer) {
|
||||
if (isAndroid) {
|
||||
if (!await AndroidPermissionManager.check(kManageExternalStorage)) {
|
||||
if (!await AndroidPermissionManager.request(kManageExternalStorage)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isWeb) {
|
||||
Navigator.push(
|
||||
context,
|
||||
|
||||
@@ -606,9 +606,6 @@ class QualityMonitor extends StatelessWidget {
|
||||
_row(
|
||||
"Codec", qualityMonitorModel.data.codecFormat ?? '-'),
|
||||
_row("Chroma", qualityMonitorModel.data.chroma ?? '-'),
|
||||
if (qualityMonitorModel.webrtcTransport != null)
|
||||
_row("Transport",
|
||||
qualityMonitorModel.webrtcTransport!),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
@@ -244,38 +244,11 @@ List<(String, String)> otherDefaultSettings() {
|
||||
kKeyUseAllMyDisplaysForTheRemoteSession
|
||||
),
|
||||
('Keep terminal sessions on disconnect', kOptionTerminalPersistent),
|
||||
(
|
||||
'Allow terminal apps to copy to clipboard',
|
||||
kOptionAllowTerminalClipboardWrite
|
||||
),
|
||||
];
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
String getOtherDefaultSettingOption(String key) {
|
||||
if (key == kOptionAllowTerminalClipboardWrite) {
|
||||
return bind.mainGetLocalOption(key: key);
|
||||
}
|
||||
return bind.mainGetUserDefaultOption(key: key);
|
||||
}
|
||||
|
||||
Future<void> setOtherDefaultSettingOption(String key, String value) {
|
||||
if (key == kOptionAllowTerminalClipboardWrite) {
|
||||
return bind.mainSetLocalOption(
|
||||
key: key,
|
||||
value: value == kTerminalClipboardWriteAllowed
|
||||
? kTerminalClipboardWriteAllowed
|
||||
: kTerminalClipboardWriteDenied,
|
||||
);
|
||||
}
|
||||
return bind.mainSetUserDefaultOption(key: key, value: value);
|
||||
}
|
||||
|
||||
bool isOtherDefaultSettingReadOnly(String key) =>
|
||||
isOptionFixed(key) ||
|
||||
(key == kOptionAllowTerminalClipboardWrite && bind.isDisableSettings());
|
||||
|
||||
class TrackpadSpeedWidget extends StatefulWidget {
|
||||
final SimpleWrapper<int> value;
|
||||
// If null, no debouncer will be applied.
|
||||
|
||||
+1
-19
@@ -115,19 +115,12 @@ const String kOptionEnableAudio = "enable-audio";
|
||||
const String kOptionEnableCamera = "enable-camera";
|
||||
const String kOptionEnableTerminal = "enable-terminal";
|
||||
const String kOptionTerminalPersistent = "terminal-persistent";
|
||||
const String kOptionAllowTerminalClipboardWrite =
|
||||
"allow-terminal-clipboard-write";
|
||||
const String kTerminalClipboardWriteUnconfigured = "";
|
||||
const String kTerminalClipboardWriteAllowed = "Y";
|
||||
const String kTerminalClipboardWriteDenied = "N";
|
||||
const String kOptionEnableTunnel = "enable-tunnel";
|
||||
const String kOptionEnableRemoteRestart = "enable-remote-restart";
|
||||
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";
|
||||
@@ -166,7 +159,6 @@ const String kOptionPeerTabVisible = "peer-tab-visible";
|
||||
const String kOptionPeerCardUiType = "peer-card-ui-type";
|
||||
const String kOptionCurrentAbName = "current-ab-name";
|
||||
const String kOptionEnableConfirmClosingTabs = "enable-confirm-closing-tabs";
|
||||
const String kOptionEnablePortForwardMux = "enable-port-forward-mux";
|
||||
const String kOptionAllowAlwaysSoftwareRender = "allow-always-software-render";
|
||||
const String kOptionEnableCheckUpdate = "enable-check-update";
|
||||
const String kOptionAllowAutoUpdate = "allow-auto-update";
|
||||
@@ -174,13 +166,8 @@ const String kOptionAllowRemoveWallpaper = "allow-remove-wallpaper";
|
||||
const String kOptionStopService = "stop-service";
|
||||
const String kOptionDirectxCapture = "enable-directx-capture";
|
||||
const String kOptionAllowRemoteCmModification = "allow-remote-cm-modification";
|
||||
const String kOptionEnableTcpPunch = "enable-tcp-punch";
|
||||
const String kOptionEnableUdpPunch = "enable-udp-punch";
|
||||
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";
|
||||
@@ -452,6 +439,7 @@ const kActionApplicationDetailsSettings =
|
||||
const kActionAccessibilitySettings = "android.settings.ACCESSIBILITY_SETTINGS";
|
||||
|
||||
const kRecordAudio = "android.permission.RECORD_AUDIO";
|
||||
const kManageExternalStorage = "android.permission.MANAGE_EXTERNAL_STORAGE";
|
||||
const kRequestIgnoreBatteryOptimizations =
|
||||
"android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS";
|
||||
const kSystemAlertWindow = "android.permission.SYSTEM_ALERT_WINDOW";
|
||||
@@ -463,12 +451,6 @@ class AndroidChannel {
|
||||
static final kGetStartOnBootOpt = "get_start_on_boot_opt";
|
||||
static final kSetStartOnBootOpt = "set_start_on_boot_opt";
|
||||
static final kSyncAppDirConfigPath = "sync_app_dir";
|
||||
static final kPickImportFiles = "pick_import_files";
|
||||
static final kImportFile = "import_file";
|
||||
static final kExportFile = "export_file";
|
||||
static final kPickImportDirectory = "pick_import_directory";
|
||||
static final kImportDirectory = "import_directory";
|
||||
static final kExportFiles = "export_files";
|
||||
}
|
||||
|
||||
/// flutter/packages/flutter/lib/src/services/keyboard_key.dart -> _keyLabels
|
||||
|
||||
@@ -330,14 +330,12 @@ class _ConnectionPageState extends State<ConnectionPage>
|
||||
void onConnect(
|
||||
{bool isFileTransfer = false,
|
||||
bool isViewCamera = false,
|
||||
bool isTerminal = false,
|
||||
bool isTcpTunneling = false}) {
|
||||
bool isTerminal = false}) {
|
||||
var id = _idController.id;
|
||||
connect(context, id,
|
||||
isFileTransfer: isFileTransfer,
|
||||
isViewCamera: isViewCamera,
|
||||
isTerminal: isTerminal,
|
||||
isTcpTunneling: isTcpTunneling);
|
||||
isTerminal: isTerminal);
|
||||
}
|
||||
|
||||
/// UI for the remote ID TextField.
|
||||
@@ -570,14 +568,6 @@ class _ConnectionPageState extends State<ConnectionPage>
|
||||
'${translate('Terminal')} (beta)',
|
||||
() => onConnect(isTerminal: true)
|
||||
),
|
||||
// `connect` routes this through the
|
||||
// desktop path only; the peer card gates
|
||||
// it the same way.
|
||||
if (isDesktop)
|
||||
(
|
||||
'TCP tunneling',
|
||||
() => onConnect(isTcpTunneling: true)
|
||||
),
|
||||
]
|
||||
.map((e) => MenuEntryButton<String>(
|
||||
childBuilder: (TextStyle? style) =>
|
||||
|
||||
@@ -480,10 +480,6 @@ class _DesktopHomePageState extends State<DesktopHomePage>
|
||||
return buildInstallCard("Permissions", "config_screen", "Configure",
|
||||
() async {
|
||||
bind.mainIsCanScreenRecording(prompt: true);
|
||||
// macOS shows the request prompt only once per app, so later
|
||||
// presses would do nothing without opening the settings pane.
|
||||
launchUrl(Uri.parse(
|
||||
'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'));
|
||||
watchIsCanScreenRecording = true;
|
||||
}, help: 'Help', link: translate("doc_mac_permission"));
|
||||
} else if (!isOutgoingOnly && !bind.mainIsProcessTrusted(prompt: false)) {
|
||||
|
||||
@@ -509,15 +509,6 @@ class _GeneralState extends State<_General> {
|
||||
kOptionOpenNewConnInTabs,
|
||||
isServer: false,
|
||||
),
|
||||
Tooltip(
|
||||
message: translate('port-forward-mux-tip'),
|
||||
child: _OptionCheckBox(
|
||||
context,
|
||||
'Reuse one connection for port forwarding',
|
||||
kOptionEnablePortForwardMux,
|
||||
isServer: false,
|
||||
),
|
||||
),
|
||||
// though this is related to GUI, but opengl problem affects all users, so put in config rather than local
|
||||
if (isLinux)
|
||||
Tooltip(
|
||||
@@ -572,12 +563,6 @@ class _GeneralState extends State<_General> {
|
||||
kOptionDirectxCapture,
|
||||
),
|
||||
if (!isWeb && !incomingOnly) ...[
|
||||
_OptionCheckBox(
|
||||
context,
|
||||
'Enable TCP hole punching',
|
||||
kOptionEnableTcpPunch,
|
||||
isServer: false,
|
||||
),
|
||||
_OptionCheckBox(
|
||||
context,
|
||||
'Enable UDP hole punching',
|
||||
@@ -591,17 +576,6 @@ class _GeneralState extends State<_General> {
|
||||
isServer: false,
|
||||
),
|
||||
],
|
||||
if (!incomingOnly) ...webrtcOptions(context),
|
||||
if (!isWeb && !incomingOnly)
|
||||
Tooltip(
|
||||
message: translate('sync-clipboard-between-sessions-tip'),
|
||||
child: _OptionCheckBox(
|
||||
context,
|
||||
'Sync clipboard between sessions',
|
||||
kOptionAllowSyncClipboardBetweenSessions,
|
||||
isServer: false,
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
// Add client-side wakelock option for desktop platforms
|
||||
@@ -881,85 +855,6 @@ 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 {
|
||||
@@ -2176,13 +2071,14 @@ class _DisplayState extends State<_Display> {
|
||||
}
|
||||
|
||||
Widget otherRow(String label, String key) {
|
||||
final value = getOtherDefaultSettingOption(key) == 'Y';
|
||||
final isOptFixed = isOtherDefaultSettingReadOnly(key);
|
||||
final value = bind.mainGetUserDefaultOption(key: key) == 'Y';
|
||||
final isOptFixed = isOptionFixed(key);
|
||||
onChanged(bool b) async {
|
||||
await setOtherDefaultSettingOption(
|
||||
key,
|
||||
b ? 'Y' : (key == kOptionEnableFileCopyPaste ? 'N' : defaultOptionNo),
|
||||
);
|
||||
await bind.mainSetUserDefaultOption(
|
||||
key: key,
|
||||
value: b
|
||||
? 'Y'
|
||||
: (key == kOptionEnableFileCopyPaste ? 'N' : defaultOptionNo));
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
|
||||
@@ -62,15 +62,12 @@ class _InstallPageBody extends StatefulWidget {
|
||||
|
||||
class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
with WindowListener {
|
||||
static const _printerStatusTimeout = Duration(seconds: 5);
|
||||
|
||||
late final TextEditingController controller;
|
||||
final RxBool startmenu = true.obs;
|
||||
final RxBool desktopicon = true.obs;
|
||||
final RxBool printer = false.obs;
|
||||
final RxBool showProgress = false.obs;
|
||||
final RxBool btnEnabled = true.obs;
|
||||
final RxBool cancelEnabled = true.obs;
|
||||
|
||||
// todo move to theme.
|
||||
final buttonStyle = OutlinedButton.styleFrom(
|
||||
@@ -86,33 +83,10 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
printer.value = installOptions['PRINTER'] == '1';
|
||||
}
|
||||
|
||||
Future<void> _loadPrinterStatus() async {
|
||||
btnEnabled.value = false;
|
||||
showProgress.value = true;
|
||||
try {
|
||||
final status = await bind
|
||||
.mainGetCommon(key: 'is-printer-installed')
|
||||
.timeout(_printerStatusTimeout);
|
||||
printer.value = status == 'true';
|
||||
if (status != 'true' && status != 'false') {
|
||||
debugPrint('Failed to check printer installation status: $status');
|
||||
}
|
||||
} catch (e) {
|
||||
printer.value = false;
|
||||
debugPrint('Failed to check printer installation status: $e');
|
||||
} finally {
|
||||
showProgress.value = false;
|
||||
btnEnabled.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
windowManager.addListener(this);
|
||||
super.initState();
|
||||
if (printer.value) {
|
||||
_loadPrinterStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -243,9 +217,8 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
() => OutlinedButton.icon(
|
||||
icon: Icon(Icons.close_rounded, size: 16),
|
||||
label: Text(translate('Cancel')),
|
||||
onPressed: cancelEnabled.value
|
||||
? () => windowManager.close()
|
||||
: null,
|
||||
onPressed:
|
||||
btnEnabled.value ? () => windowManager.close() : null,
|
||||
style: buttonStyle,
|
||||
).marginOnly(right: 10),
|
||||
),
|
||||
@@ -280,7 +253,6 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
void install() {
|
||||
do_install() {
|
||||
btnEnabled.value = false;
|
||||
cancelEnabled.value = false;
|
||||
showProgress.value = true;
|
||||
String args = '';
|
||||
if (startmenu.value) args += ' startmenu';
|
||||
|
||||
@@ -1005,8 +1005,8 @@ class _RemotePageState extends State<RemotePage>
|
||||
bool get wantKeepAlive => true;
|
||||
}
|
||||
|
||||
/// Tracks view size and DPR to update CanvasModel.updateViewStyle()
|
||||
/// and InputModel.updateImageWidgetSize() only when either changes.
|
||||
/// A widget that tracks the view size and updates CanvasModel.updateViewStyle()
|
||||
/// and InputModel.updateImageWidgetSize() only when size actually changes.
|
||||
/// This avoids scheduling post-frame callbacks on every LayoutBuilder rebuild.
|
||||
class _ViewStyleUpdater extends StatefulWidget {
|
||||
final CanvasModel canvasModel;
|
||||
@@ -1026,12 +1026,10 @@ 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;
|
||||
@@ -1041,9 +1039,8 @@ class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
|
||||
return widget.child;
|
||||
}
|
||||
final newSize = Size(maxWidth, maxHeight);
|
||||
if (_lastSize != newSize || _lastDevicePixelRatio != devicePixelRatio) {
|
||||
if (_lastSize != newSize) {
|
||||
_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.
|
||||
@@ -1091,7 +1088,6 @@ 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;
|
||||
@@ -1105,19 +1101,25 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
final m = Provider.of<ImageModel>(context);
|
||||
var c = Provider.of<CanvasModel>(context);
|
||||
final s = c.scale;
|
||||
// Read the live DPR while the canvas's post-frame update is pending.
|
||||
final dpr = MediaQuery.devicePixelRatioOf(context);
|
||||
|
||||
bool isViewAdaptive() => c.viewStyle.style == kRemoteViewStyleAdaptive;
|
||||
bool isViewOriginal() => c.viewStyle.style == kRemoteViewStyleOriginal;
|
||||
|
||||
mouseRegion({child}) => Obx(() {
|
||||
double getCursorScale() {
|
||||
var c = Provider.of<CanvasModel>(context);
|
||||
if (isDesktop) {
|
||||
return _getDesktopCursorScale(c, dpr);
|
||||
var cursorScale = 1.0;
|
||||
if (isWindows) {
|
||||
// debug win10
|
||||
if (zoomCursor.value && isViewAdaptive()) {
|
||||
cursorScale = s * c.devicePixelRatio;
|
||||
}
|
||||
} else {
|
||||
return zoomCursor.value || isViewOriginal() ? s : 1.0;
|
||||
if (zoomCursor.value || isViewOriginal()) {
|
||||
cursorScale = s;
|
||||
}
|
||||
}
|
||||
return cursorScale;
|
||||
}
|
||||
|
||||
return MouseRegion(
|
||||
@@ -1191,70 +1193,11 @@ class _ImagePaintState extends State<ImagePaint> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: sizeScale),
|
||||
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: s),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1299,14 +1242,11 @@ 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: _trackCursorDisplay(
|
||||
Obx(() => Texture(
|
||||
textureId: textureId.value,
|
||||
filterQuality:
|
||||
isViewOriginal ? FilterQuality.none : FilterQuality.low,
|
||||
)),
|
||||
displays[i],
|
||||
),
|
||||
child: Obx(() => Texture(
|
||||
textureId: textureId.value,
|
||||
filterQuality:
|
||||
isViewOriginal ? FilterQuality.none : FilterQuality.low,
|
||||
)),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1317,20 +1257,6 @@ 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;
|
||||
|
||||
@@ -1073,10 +1073,7 @@ class _CmControlPanel extends StatelessWidget {
|
||||
final model = Provider.of<ServerModel>(context);
|
||||
final showElevation = canElevate &&
|
||||
model.showElevation &&
|
||||
client.type_() == ClientType.remote &&
|
||||
bind.mainGetBuildinOption(
|
||||
key: kOptionHideElevateButtonInAcceptWindow) !=
|
||||
'Y';
|
||||
client.type_() == ClientType.remote;
|
||||
final showAccept = model.approveMode != 'password';
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
|
||||
@@ -19,8 +19,6 @@ class TerminalPage extends StatefulWidget {
|
||||
required this.tabKey,
|
||||
this.forceRelay,
|
||||
this.connToken,
|
||||
this.onClipboardWriteBlocked,
|
||||
this.onClipboardWriteSucceeded,
|
||||
}) : super(key: key);
|
||||
final String id;
|
||||
final String? password;
|
||||
@@ -28,8 +26,6 @@ class TerminalPage extends StatefulWidget {
|
||||
final bool? forceRelay;
|
||||
final bool? isSharedPassword;
|
||||
final String? connToken;
|
||||
final ValueChanged<String>? onClipboardWriteBlocked;
|
||||
final ValueChanged<String>? onClipboardWriteSucceeded;
|
||||
final int terminalId;
|
||||
|
||||
/// Tab key for focus management, passed from parent to avoid duplicate construction
|
||||
@@ -75,8 +71,6 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
|
||||
// Create terminal model with specific terminal ID
|
||||
_terminalModel = TerminalModel(_ffi, widget.terminalId);
|
||||
_terminalModel.onClipboardWriteBlocked = widget.onClipboardWriteBlocked;
|
||||
_terminalModel.onClipboardWriteSucceeded = widget.onClipboardWriteSucceeded;
|
||||
debugPrint(
|
||||
'[TerminalPage] Terminal model created for terminal ${widget.terminalId}');
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:desktop_multi_window/desktop_multi_window.dart';
|
||||
@@ -11,8 +10,6 @@ import 'package:flutter_hbb/models/state_model.dart';
|
||||
import 'package:flutter_hbb/desktop/widgets/tabbar_widget.dart';
|
||||
import 'package:flutter_hbb/utils/multi_window_manager.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/terminal_copy_shortcut.dart';
|
||||
import 'package:flutter_hbb/models/terminal_model.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../models/platform_model.dart';
|
||||
@@ -22,12 +19,6 @@ import '../widgets/material_mod_popup_menu.dart' as mod_menu;
|
||||
import '../widgets/popup_menu.dart';
|
||||
import 'package:bot_toast/bot_toast.dart';
|
||||
|
||||
typedef _TerminalClipboardSource = ({
|
||||
String peerId,
|
||||
int terminalId,
|
||||
String tabKey,
|
||||
});
|
||||
|
||||
class TerminalTabPage extends StatefulWidget {
|
||||
final Map<String, dynamic> params;
|
||||
|
||||
@@ -39,18 +30,6 @@ class TerminalTabPage extends StatefulWidget {
|
||||
|
||||
class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
DesktopTabController get tabController => Get.find<DesktopTabController>();
|
||||
bool get _canConfigureTerminalClipboardPermission =>
|
||||
canConfigureTerminalClipboardPermission(
|
||||
settingsDisabled: bind.isDisableSettings(),
|
||||
optionFixed: isOptionFixed(kOptionAllowTerminalClipboardWrite),
|
||||
);
|
||||
bool get _canHandleTerminalClipboardWriteRequest =>
|
||||
canHandleTerminalClipboardWriteRequest(
|
||||
localOption: bind.mainGetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
),
|
||||
canConfigurePermission: _canConfigureTerminalClipboardPermission,
|
||||
);
|
||||
|
||||
static const IconData selectedIcon = Icons.terminal;
|
||||
static const IconData unselectedIcon = Icons.terminal_outlined;
|
||||
@@ -59,9 +38,6 @@ class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
final Set<String> _closingTabs = {};
|
||||
// When true, all session cleanup should persist (window-level close in progress)
|
||||
bool _windowClosing = false;
|
||||
CancelFunc? _terminalClipboardNoticeCancel;
|
||||
final _terminalClipboardNotice =
|
||||
TerminalClipboardNoticeCoordinator<_TerminalClipboardSource>();
|
||||
|
||||
_TerminalTabPageState(Map<String, dynamic> params) {
|
||||
Get.put(DesktopTabController(tabType: DesktopTabType.terminal));
|
||||
@@ -69,10 +45,7 @@ class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
WindowController.fromWindowId(windowId())
|
||||
.setTitle(getWindowNameWithId(id));
|
||||
};
|
||||
tabController.onRemoved = (_, id) {
|
||||
_closeTerminalClipboardNoticeForTab(id);
|
||||
onRemoveId(id);
|
||||
};
|
||||
tabController.onRemoved = (_, id) => onRemoveId(id);
|
||||
tabController.onCloseWindow = _closeWindowFromConnection;
|
||||
final terminalId = params['terminalId'] ?? _nextTerminalId++;
|
||||
tabController.add(_createTerminalTab(
|
||||
@@ -97,11 +70,6 @@ class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
final alias = bind.mainGetPeerOptionSync(id: peerId, key: 'alias');
|
||||
final tabLabel =
|
||||
alias.isNotEmpty ? '$alias #$terminalId' : '$peerId #$terminalId';
|
||||
final clipboardSource = (
|
||||
peerId: peerId,
|
||||
terminalId: terminalId,
|
||||
tabKey: tabKey,
|
||||
);
|
||||
return TabInfo(
|
||||
key: tabKey,
|
||||
label: tabLabel,
|
||||
@@ -118,169 +86,10 @@ class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
tabController: tabController,
|
||||
forceRelay: forceRelay,
|
||||
connToken: connToken,
|
||||
onClipboardWriteBlocked: _canHandleTerminalClipboardWriteRequest
|
||||
? (text) => _handleTerminalClipboardWriteBlocked(
|
||||
clipboardSource,
|
||||
text,
|
||||
)
|
||||
: null,
|
||||
onClipboardWriteSucceeded: (_) {
|
||||
_handleTerminalClipboardWriteSucceeded(clipboardSource);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardWriteBlocked(
|
||||
_TerminalClipboardSource source,
|
||||
String clipboardText,
|
||||
) {
|
||||
if (!mounted) return;
|
||||
final option = bind.mainGetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
);
|
||||
final request = _terminalClipboardNotice.recordBlocked(
|
||||
source: source,
|
||||
text: clipboardText,
|
||||
option: option,
|
||||
canWrite: _canWriteTerminalClipboard,
|
||||
);
|
||||
if (request != null) _showTerminalClipboardNotice(request);
|
||||
}
|
||||
|
||||
void _showTerminalClipboardNotice(
|
||||
TerminalClipboardNoticeRequest<_TerminalClipboardSource> request,
|
||||
) {
|
||||
_terminalClipboardNoticeCancel = BotToast.showCustomNotification(
|
||||
duration: null,
|
||||
enableSlideOff: false,
|
||||
onlyOne: true,
|
||||
onClose: _handleTerminalClipboardNoticeClosed,
|
||||
toastBuilder: (_) => AnimatedBuilder(
|
||||
animation: _terminalClipboardNotice,
|
||||
builder: (_, __) => MaterialBanner(
|
||||
leading: const Icon(Icons.content_copy_outlined),
|
||||
content: Text(translate(kTerminalClipboardNoticeMessageKey)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _terminalClipboardNotice.canClaimAction
|
||||
? _handleTerminalClipboardNegativeAction
|
||||
: null,
|
||||
child: Text(translate(request.negativeActionKey)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: _terminalClipboardNotice.canClaimAction
|
||||
? _handleTerminalClipboardPositiveAction
|
||||
: null,
|
||||
child: Text(translate(request.actionKey)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardNegativeAction() {
|
||||
final request = _terminalClipboardNotice.claimCurrentAction();
|
||||
if (request == null) return;
|
||||
if (request.persistAllowed) {
|
||||
unawaited(_declineTerminalClipboardWrite());
|
||||
} else {
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardPositiveAction() {
|
||||
final request = _terminalClipboardNotice.claimCurrentAction();
|
||||
if (request == null) return;
|
||||
unawaited(_completeTerminalClipboardWrite(request));
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardNoticeClosed() {
|
||||
_terminalClipboardNoticeCancel = null;
|
||||
_terminalClipboardNotice.noticeClosed();
|
||||
}
|
||||
|
||||
bool _canWriteTerminalClipboard(
|
||||
_TerminalClipboardSource source,
|
||||
) {
|
||||
if (!_canHandleTerminalClipboardWriteRequest) return false;
|
||||
final ffi = TerminalConnectionManager.getExistingConnection(source.peerId);
|
||||
return ffi != null &&
|
||||
!ffi.closed &&
|
||||
ffi.ffiModel.permissions['clipboard'] != false &&
|
||||
tabController.state.value.tabs.any((tab) => tab.key == source.tabKey) &&
|
||||
ffi.terminalModels.containsKey(source.terminalId);
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardWriteSucceeded(
|
||||
_TerminalClipboardSource source,
|
||||
) {
|
||||
final request = _terminalClipboardNotice.currentForSource(source);
|
||||
if (request == null) return;
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
Future<void> _declineTerminalClipboardWrite() async {
|
||||
try {
|
||||
await bind.mainSetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
value: kTerminalClipboardWriteDenied,
|
||||
);
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'[TerminalTabPage] Failed to save terminal clipboard permission: $error');
|
||||
return;
|
||||
} finally {
|
||||
_terminalClipboardNotice.releaseAction();
|
||||
}
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
Future<void> _completeTerminalClipboardWrite(
|
||||
TerminalClipboardNoticeRequest<_TerminalClipboardSource> request,
|
||||
) async {
|
||||
final source = request.source;
|
||||
var completed = false;
|
||||
try {
|
||||
completed = await completeTerminalClipboardWrite(
|
||||
clipboardText: request.text,
|
||||
canWrite: () => _canWriteTerminalClipboard(source),
|
||||
writeClipboard: writeTerminalClipboard,
|
||||
persistAllowed: request.persistAllowed
|
||||
? () => bind.mainSetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
value: kTerminalClipboardWriteAllowed,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'[TerminalTabPage] Failed to complete terminal clipboard write: $error');
|
||||
} finally {
|
||||
_terminalClipboardNotice.releaseAction();
|
||||
}
|
||||
if (!completed) return;
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
void _closeTerminalClipboardNoticeForTab(String tabKey) {
|
||||
final current = _terminalClipboardNotice.current;
|
||||
if (current?.source.tabKey != tabKey) return;
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
void _closeTerminalClipboardNotice() {
|
||||
if (!_terminalClipboardNotice.beginClose()) return;
|
||||
final cancel = _terminalClipboardNoticeCancel;
|
||||
if (cancel == null) {
|
||||
debugPrint('[TerminalTabPage] Clipboard notice controller is missing');
|
||||
_terminalClipboardNotice.noticeClosed();
|
||||
return;
|
||||
}
|
||||
cancel();
|
||||
}
|
||||
|
||||
/// Unified tab close handler for all close paths (button, shortcut, programmatic).
|
||||
/// Shows audit dialog, cleans up session if not persistent, then removes the UI tab.
|
||||
Future<void> _closeTab(String tabKey) async {
|
||||
@@ -338,8 +147,6 @@ class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
// Remove all UI tabs immediately (same instant behavior as the old tabController.clear())
|
||||
// Keep the cleanup target lookup below synchronous before its first await:
|
||||
// it relies on the current frame still retaining each TerminalPage's FFI/model.
|
||||
_terminalClipboardNotice.clear();
|
||||
_terminalClipboardNoticeCancel?.call();
|
||||
tabController.clear();
|
||||
// Run session cleanup in parallel with bounded timeout (closeTerminal() has internal 3s timeout).
|
||||
// Skip tabs already being closed by a concurrent _closeTab() to avoid duplicate FFI calls.
|
||||
@@ -550,8 +357,6 @@ class _TerminalTabPageState extends State<TerminalTabPage> {
|
||||
@override
|
||||
void dispose() {
|
||||
HardwareKeyboard.instance.removeHandler(_handleKeyEvent);
|
||||
_terminalClipboardNotice.clear();
|
||||
_terminalClipboardNoticeCancel?.call();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_breadcrumb/flutter_breadcrumb.dart';
|
||||
@@ -9,7 +8,6 @@ import 'package:toggle_switch/toggle_switch.dart';
|
||||
|
||||
import '../../common.dart';
|
||||
import '../../common/widgets/dialog.dart';
|
||||
import '../../consts.dart';
|
||||
|
||||
class FileManagerPage extends StatefulWidget {
|
||||
FileManagerPage(
|
||||
@@ -75,173 +73,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
DirectoryOptions get currentOptions => currentFileController.options.value;
|
||||
final _uniqueKey = UniqueKey();
|
||||
|
||||
Future<T> _runAndroidDocumentPicker<T>(Future<T> Function() action) async {
|
||||
gFFI.ffiModel.beginAndroidDocumentPicker();
|
||||
try {
|
||||
return await action();
|
||||
} finally {
|
||||
gFFI.ffiModel.endAndroidDocumentPicker();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _importFiles() async {
|
||||
var imported = 0;
|
||||
var failed = false;
|
||||
final importController = currentFileController;
|
||||
final importDirectory = currentDir.path;
|
||||
final importIsWindows = currentOptions.isWindows;
|
||||
try {
|
||||
final selectedFiles = await _runAndroidDocumentPicker(() =>
|
||||
gFFI.invokeMethodWithResult<List<dynamic>>(
|
||||
AndroidChannel.kPickImportFiles));
|
||||
if (selectedFiles == null || selectedFiles.isEmpty) return;
|
||||
|
||||
for (final selected in selectedFiles) {
|
||||
final uri = (selected as Map<dynamic, dynamic>)['uri'] as String?;
|
||||
final selectedName = selected['name'] as String?;
|
||||
final name = selectedName?.replaceAll('\\', '/').split('/').last;
|
||||
if (uri == null ||
|
||||
name == null ||
|
||||
!PathUtil.validName(name, importIsWindows)) {
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
final destination =
|
||||
PathUtil.join(importDirectory, name, importIsWindows);
|
||||
var overwrite = false;
|
||||
if (await File(destination).exists()) {
|
||||
final overwriteResult = await model.showFileConfirmDialog(
|
||||
translate('Overwrite'), destination, false, false);
|
||||
if (overwriteResult == false) break;
|
||||
if (overwriteResult != true) continue;
|
||||
overwrite = true;
|
||||
}
|
||||
try {
|
||||
final success = await gFFI.invokeMethod(
|
||||
AndroidChannel.kImportFile,
|
||||
{'uri': uri, 'path': destination, 'overwrite': overwrite});
|
||||
if (success == true) {
|
||||
imported++;
|
||||
} else {
|
||||
failed = true;
|
||||
}
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
debugPrint('Failed to import $name: $e');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
debugPrint('Failed to select files for import: $e');
|
||||
}
|
||||
await importController.refresh();
|
||||
if (failed) {
|
||||
showToast(translate('Failed'));
|
||||
} else if (imported > 0) {
|
||||
showToast(translate('Successful'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exportFile(Entry entry) async {
|
||||
try {
|
||||
final exported = await _runAndroidDocumentPicker(() => gFFI
|
||||
.invokeMethod(AndroidChannel.kExportFile, {'path': entry.path}));
|
||||
if (exported == true) {
|
||||
showToast(translate('Successful'));
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Failed to export ${entry.name}: $e');
|
||||
showToast(translate('Failed'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _importFolder() async {
|
||||
final importController = currentFileController;
|
||||
final importDirectory = currentDir.path;
|
||||
final importIsWindows = currentOptions.isWindows;
|
||||
try {
|
||||
final picked = await _runAndroidDocumentPicker(() =>
|
||||
gFFI.invokeMethodWithResult<Map<dynamic, dynamic>>(
|
||||
AndroidChannel.kPickImportDirectory));
|
||||
if (picked == null || picked.isEmpty) return;
|
||||
final uri = picked['uri'] as String?;
|
||||
final name =
|
||||
(picked['name'] as String?)?.replaceAll('\\', '/').split('/').last;
|
||||
if (uri == null ||
|
||||
name == null ||
|
||||
name == '.' ||
|
||||
name == '..' ||
|
||||
!PathUtil.validName(name, importIsWindows)) {
|
||||
showToast(translate('Failed'));
|
||||
return;
|
||||
}
|
||||
final destination = PathUtil.join(importDirectory, name, importIsWindows);
|
||||
final destinationType = await FileSystemEntity.type(destination);
|
||||
var overwrite = false;
|
||||
if (destinationType == FileSystemEntityType.directory) {
|
||||
final overwriteResult = await model.showFileConfirmDialog(
|
||||
translate('Overwrite'), destination, false, false);
|
||||
if (overwriteResult != true) return;
|
||||
overwrite = true;
|
||||
} else if (destinationType != FileSystemEntityType.notFound) {
|
||||
showToast(translate('Failed'));
|
||||
return;
|
||||
}
|
||||
final success = await gFFI.invokeMethod(AndroidChannel.kImportDirectory,
|
||||
{'uri': uri, 'path': destination, 'overwrite': overwrite});
|
||||
if (success == true) {
|
||||
showToast(translate('Successful'));
|
||||
} else {
|
||||
showToast(translate('Failed'));
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Failed to import folder: $e');
|
||||
showToast(translate('Failed'));
|
||||
}
|
||||
await importController.refresh();
|
||||
}
|
||||
|
||||
Future<void> _exportItems(SelectedItems items) async {
|
||||
await _exportPaths(items.items.map((e) => e.path));
|
||||
}
|
||||
|
||||
Future<void> _exportLogs() async {
|
||||
final home = currentFileController.homePath;
|
||||
if (home.isEmpty) {
|
||||
showToast(translate('Failed'));
|
||||
return;
|
||||
}
|
||||
final appDir = PathUtil.join(home, appName, false);
|
||||
final paths = [
|
||||
PathUtil.join(appDir, 'Logs', false),
|
||||
PathUtil.join(appDir, 'ScreenRecord', false),
|
||||
].where((p) => File(p).existsSync() || Directory(p).existsSync()).toList();
|
||||
if (paths.isEmpty) {
|
||||
showToast(translate('Failed'));
|
||||
return;
|
||||
}
|
||||
await _exportPaths(paths);
|
||||
}
|
||||
|
||||
Future<void> _exportPaths(Iterable<String> paths) async {
|
||||
try {
|
||||
final result = await _runAndroidDocumentPicker(() =>
|
||||
gFFI.invokeMethodWithResult<Map<dynamic, dynamic>>(
|
||||
AndroidChannel.kExportFiles, {'paths': paths.toList()}));
|
||||
if (result == null) return;
|
||||
final exported = result['exported'] as int? ?? 0;
|
||||
final failed = result['failed'] as int? ?? 0;
|
||||
if (failed > 0) {
|
||||
showToast(translate('Failed'));
|
||||
} else if (exported > 0) {
|
||||
showToast(translate('Successful'));
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Failed to export paths: $e');
|
||||
showToast(translate('Failed'));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -328,45 +159,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
),
|
||||
value: "refresh",
|
||||
),
|
||||
if (isAndroid)
|
||||
PopupMenuItem(
|
||||
enabled: showLocal && currentDir.path.isNotEmpty,
|
||||
value: "import",
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.add_to_drive,
|
||||
color: Theme.of(context).iconTheme.color),
|
||||
SizedBox(width: 5),
|
||||
Text(translate("Add"))
|
||||
],
|
||||
),
|
||||
),
|
||||
if (isAndroid)
|
||||
PopupMenuItem(
|
||||
enabled: showLocal && currentDir.path.isNotEmpty,
|
||||
value: "import_folder",
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.create_new_folder_outlined,
|
||||
color: Theme.of(context).iconTheme.color),
|
||||
SizedBox(width: 5),
|
||||
Text(translate("Import Folder"))
|
||||
],
|
||||
),
|
||||
),
|
||||
if (isAndroid)
|
||||
PopupMenuItem(
|
||||
enabled: showLocal && currentDir.path.isNotEmpty,
|
||||
value: "export_logs",
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.article_outlined,
|
||||
color: Theme.of(context).iconTheme.color),
|
||||
SizedBox(width: 5),
|
||||
Text(translate("Export Logs"))
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
enabled: currentDir.path != "/",
|
||||
child: Row(
|
||||
@@ -411,12 +203,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
onSelected: (v) {
|
||||
if (v == "refresh") {
|
||||
currentFileController.refresh();
|
||||
} else if (v == "import") {
|
||||
_importFiles();
|
||||
} else if (v == "import_folder") {
|
||||
_importFolder();
|
||||
} else if (v == "export_logs") {
|
||||
_exportLogs();
|
||||
} else if (v == "select") {
|
||||
model.localController.selectedItems.clear();
|
||||
model.remoteController.selectedItems.clear();
|
||||
@@ -514,24 +300,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
setState(() {});
|
||||
},
|
||||
actions: [
|
||||
if (isAndroid &&
|
||||
selectedItems?.isLocal == true &&
|
||||
selectedItems?.items.isNotEmpty == true) ...[
|
||||
if (selectedItems!.items.length == 1 &&
|
||||
selectedItems!.items.single.isFile)
|
||||
IconButton(
|
||||
tooltip: translate("Save as"),
|
||||
icon: Icon(Icons.save_alt),
|
||||
onPressed: () =>
|
||||
_exportFile(selectedItems!.items.single),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
tooltip: translate("Export"),
|
||||
icon: Icon(Icons.drive_folder_upload),
|
||||
onPressed: () => _exportItems(selectedItems!),
|
||||
),
|
||||
],
|
||||
IconButton(
|
||||
icon: Icon(Icons.compare_arrows),
|
||||
onPressed: () => setState(() => showLocal = !showLocal),
|
||||
|
||||
@@ -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 connection");
|
||||
gFFI.chatModel.onVoiceCallClosed("End connetion");
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -335,10 +335,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
||||
// clipboard
|
||||
oldValue = '';
|
||||
}
|
||||
// This length-only diff assumes the IME appends at the end. If an IME
|
||||
// leaves the caret inside paired punctuation, later insertions can replay
|
||||
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
|
||||
// client text-diff issue, independent of the host keyboard layout.
|
||||
if (newValue.length == oldValue.length) {
|
||||
// ?
|
||||
} else if (newValue.length < oldValue.length) {
|
||||
|
||||
@@ -225,6 +225,12 @@ class _ServerPageState extends State<ServerPage> {
|
||||
|
||||
void checkService() async {
|
||||
gFFI.invokeMethod("check_service");
|
||||
// for Android 10/11, request MANAGE_EXTERNAL_STORAGE permission from system setting page
|
||||
if (AndroidPermissionManager.isWaitingFile() && !gFFI.serverModel.fileOk) {
|
||||
AndroidPermissionManager.complete(kManageExternalStorage,
|
||||
await AndroidPermissionManager.check(kManageExternalStorage));
|
||||
debugPrint("file permission finished");
|
||||
}
|
||||
}
|
||||
|
||||
class ServiceNotRunningNotification extends StatelessWidget {
|
||||
|
||||
@@ -97,12 +97,10 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
|
||||
var _hideNetwork = false;
|
||||
var _hideWebSocket = false;
|
||||
var _enableTrustedDevices = false;
|
||||
var _enableTcpPunch = false;
|
||||
var _enableUdpPunch = false;
|
||||
var _allowInsecureTlsFallback = false;
|
||||
var _disableUdp = false;
|
||||
var _enableIpv6Punch = false;
|
||||
var _enableWebrtc = false;
|
||||
var _isUsingPublicServer = false;
|
||||
var _allowAskForNoteAtEndOfConnection = false;
|
||||
var _preventSleepWhileConnected = true;
|
||||
@@ -143,10 +141,8 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
|
||||
bind.mainGetBuildinOption(key: kOptionHideWebSocketSetting) == 'Y' ||
|
||||
isWeb;
|
||||
_enableTrustedDevices = mainGetBoolOptionSync(kOptionEnableTrustedDevices);
|
||||
_enableTcpPunch = mainGetLocalBoolOptionSync(kOptionEnableTcpPunch);
|
||||
_enableUdpPunch = mainGetLocalBoolOptionSync(kOptionEnableUdpPunch);
|
||||
_enableIpv6Punch = mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch);
|
||||
_enableWebrtc = mainGetLocalBoolOptionSync(kOptionEnableWebrtc);
|
||||
_allowAskForNoteAtEndOfConnection =
|
||||
mainGetLocalBoolOptionSync(kOptionAllowAskForNoteAtEndOfConnection);
|
||||
_preventSleepWhileConnected =
|
||||
@@ -819,65 +815,31 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
|
||||
});
|
||||
},
|
||||
),
|
||||
if (!incomingOnly)
|
||||
SettingsTile.switchTile(
|
||||
title: Text(translate('Enable TCP hole punching')),
|
||||
initialValue: _enableTcpPunch,
|
||||
onToggle: isOptionFixed(kOptionEnableTcpPunch)
|
||||
? null
|
||||
: (v) async {
|
||||
await mainSetLocalBoolOption(kOptionEnableTcpPunch, v);
|
||||
final newValue =
|
||||
mainGetLocalBoolOptionSync(kOptionEnableTcpPunch);
|
||||
setState(() {
|
||||
_enableTcpPunch = newValue;
|
||||
});
|
||||
},
|
||||
),
|
||||
if (!incomingOnly)
|
||||
SettingsTile.switchTile(
|
||||
title: Text(translate('Enable UDP hole punching')),
|
||||
initialValue: _enableUdpPunch,
|
||||
onToggle: isOptionFixed(kOptionEnableUdpPunch)
|
||||
? null
|
||||
: (v) async {
|
||||
await mainSetLocalBoolOption(kOptionEnableUdpPunch, v);
|
||||
final newValue =
|
||||
mainGetLocalBoolOptionSync(kOptionEnableUdpPunch);
|
||||
setState(() {
|
||||
_enableUdpPunch = newValue;
|
||||
});
|
||||
},
|
||||
onToggle: (v) async {
|
||||
await mainSetLocalBoolOption(kOptionEnableUdpPunch, v);
|
||||
final newValue =
|
||||
mainGetLocalBoolOptionSync(kOptionEnableUdpPunch);
|
||||
setState(() {
|
||||
_enableUdpPunch = newValue;
|
||||
});
|
||||
},
|
||||
),
|
||||
if (!incomingOnly)
|
||||
SettingsTile.switchTile(
|
||||
title: Text(translate('Enable IPv6 P2P connection')),
|
||||
initialValue: _enableIpv6Punch,
|
||||
onToggle: isOptionFixed(kOptionEnableIpv6Punch)
|
||||
? null
|
||||
: (v) async {
|
||||
await mainSetLocalBoolOption(kOptionEnableIpv6Punch, v);
|
||||
final newValue =
|
||||
mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch);
|
||||
setState(() {
|
||||
_enableIpv6Punch = newValue;
|
||||
});
|
||||
},
|
||||
),
|
||||
if (!incomingOnly)
|
||||
SettingsTile.switchTile(
|
||||
title: Text(translate('Enable WebRTC P2P connection')),
|
||||
initialValue: _enableWebrtc,
|
||||
onToggle: isOptionFixed(kOptionEnableWebrtc)
|
||||
? null
|
||||
: (v) async {
|
||||
await mainSetLocalBoolOption(kOptionEnableWebrtc, v);
|
||||
final newValue =
|
||||
mainGetLocalBoolOptionSync(kOptionEnableWebrtc);
|
||||
setState(() {
|
||||
_enableWebrtc = newValue;
|
||||
});
|
||||
},
|
||||
onToggle: (v) async {
|
||||
await mainSetLocalBoolOption(kOptionEnableIpv6Punch, v);
|
||||
final newValue =
|
||||
mainGetLocalBoolOptionSync(kOptionEnableIpv6Punch);
|
||||
setState(() {
|
||||
_enableIpv6Punch = newValue;
|
||||
});
|
||||
},
|
||||
),
|
||||
SettingsTile(
|
||||
title: Text(translate('Language')),
|
||||
@@ -1307,18 +1269,16 @@ class __DisplayPageState extends State<_DisplayPage> {
|
||||
}
|
||||
|
||||
SettingsTile otherRow(String label, String key) {
|
||||
final value = getOtherDefaultSettingOption(key) == 'Y';
|
||||
final isOptFixed = isOtherDefaultSettingReadOnly(key);
|
||||
final value = bind.mainGetUserDefaultOption(key: key) == 'Y';
|
||||
final isOptFixed = isOptionFixed(key);
|
||||
return SettingsTile.switchTile(
|
||||
initialValue: value,
|
||||
title: Text(translate(label)),
|
||||
onToggle: isOptFixed
|
||||
? null
|
||||
: (b) async {
|
||||
await setOtherDefaultSettingOption(
|
||||
key,
|
||||
b ? 'Y' : defaultOptionNo,
|
||||
);
|
||||
await bind.mainSetUserDefaultOption(
|
||||
key: key, value: b ? 'Y' : defaultOptionNo);
|
||||
setState(() {});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -9,9 +8,7 @@ import 'package:flutter_hbb/common/widgets/dialog.dart';
|
||||
import 'package:flutter_hbb/models/input_modifier_utils.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
import 'package:flutter_hbb/models/terminal_copy_shortcut.dart';
|
||||
import 'package:flutter_hbb/models/terminal_model.dart';
|
||||
import 'package:flutter_hbb/models/terminal_mouse_handler.dart';
|
||||
import 'package:flutter_hbb/mobile/terminal_keyboard_utils.dart';
|
||||
import 'package:flutter_hbb/web/dummy.dart'
|
||||
if (dart.library.html) 'package:flutter_hbb/web/terminal_font.dart';
|
||||
@@ -20,49 +17,6 @@ import 'package:xterm/xterm.dart';
|
||||
import '../../desktop/pages/terminal_connection_manager.dart';
|
||||
import '../../consts.dart';
|
||||
|
||||
const _terminalBackgroundOpacity = 0.7;
|
||||
|
||||
Widget _buildTerminalViewForPlatform({
|
||||
required bool reportMouseInput,
|
||||
required bool reportTouchInput,
|
||||
required Terminal terminal,
|
||||
required TerminalController controller,
|
||||
required TerminalStyle textStyle,
|
||||
required EdgeInsets padding,
|
||||
required bool deleteDetection,
|
||||
required Map<ShortcutActivator, Intent>? shortcuts,
|
||||
required FocusOnKeyEventCallback onKeyEvent,
|
||||
required void Function(TapDownDetails, CellOffset) onSecondaryTapDown,
|
||||
}) {
|
||||
if (reportMouseInput || reportTouchInput) {
|
||||
return TerminalMouseInteraction(
|
||||
terminal,
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
textStyle: textStyle,
|
||||
deleteDetection: deleteDetection,
|
||||
reportTouchInput: reportTouchInput,
|
||||
shortcuts: shortcuts,
|
||||
onKeyEvent: onKeyEvent,
|
||||
backgroundOpacity: _terminalBackgroundOpacity,
|
||||
padding: padding,
|
||||
onSecondaryTapDown: onSecondaryTapDown,
|
||||
);
|
||||
}
|
||||
return TerminalView(
|
||||
terminal,
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
textStyle: textStyle,
|
||||
deleteDetection: deleteDetection,
|
||||
shortcuts: shortcuts,
|
||||
onKeyEvent: onKeyEvent,
|
||||
backgroundOpacity: _terminalBackgroundOpacity,
|
||||
padding: padding,
|
||||
onSecondaryTapDown: onSecondaryTapDown,
|
||||
);
|
||||
}
|
||||
|
||||
class TerminalPage extends StatefulWidget {
|
||||
const TerminalPage({
|
||||
Key? key,
|
||||
@@ -85,19 +39,6 @@ class TerminalPage extends StatefulWidget {
|
||||
|
||||
class _TerminalPageState extends State<TerminalPage>
|
||||
with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
|
||||
bool get _canConfigureTerminalClipboardPermission =>
|
||||
canConfigureTerminalClipboardPermission(
|
||||
settingsDisabled: bind.isDisableSettings(),
|
||||
optionFixed: isOptionFixed(kOptionAllowTerminalClipboardWrite),
|
||||
);
|
||||
bool get _canHandleTerminalClipboardWriteRequest =>
|
||||
canHandleTerminalClipboardWriteRequest(
|
||||
localOption: bind.mainGetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
),
|
||||
canConfigurePermission: _canConfigureTerminalClipboardPermission,
|
||||
);
|
||||
|
||||
late FFI _ffi;
|
||||
late TerminalModel _terminalModel;
|
||||
double? _cellHeight;
|
||||
@@ -114,9 +55,6 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
// For iOS edge swipe gesture
|
||||
double _swipeStartX = 0;
|
||||
double _swipeCurrentX = 0;
|
||||
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>?
|
||||
_terminalClipboardNoticeController;
|
||||
final _terminalClipboardNotice = TerminalClipboardNoticeCoordinator<int>();
|
||||
|
||||
// For web only.
|
||||
// 'monospace' does not work on web, use Google Fonts, `??` is only for null safety.
|
||||
@@ -149,12 +87,6 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
|
||||
// Create terminal model with specific terminal ID
|
||||
_terminalModel = TerminalModel(_ffi, widget.terminalId);
|
||||
if (_canHandleTerminalClipboardWriteRequest) {
|
||||
_terminalModel.onClipboardWriteBlocked =
|
||||
_handleTerminalClipboardWriteBlocked;
|
||||
_terminalModel.onClipboardWriteSucceeded =
|
||||
_handleTerminalClipboardWriteSucceeded;
|
||||
}
|
||||
debugPrint(
|
||||
'[TerminalPage] Terminal model created for terminal ${widget.terminalId}');
|
||||
|
||||
@@ -200,144 +132,12 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
_ffi.ffiModel.updateEventListener(_ffi.sessionId, widget.id);
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardWriteBlocked(String clipboardText) {
|
||||
if (!mounted) return;
|
||||
final option = bind.mainGetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
);
|
||||
final request = _terminalClipboardNotice.recordBlocked(
|
||||
source: widget.terminalId,
|
||||
text: clipboardText,
|
||||
option: option,
|
||||
canWrite: (_) => _canWriteTerminalClipboard,
|
||||
);
|
||||
if (request != null) _showTerminalClipboardNotice(request);
|
||||
}
|
||||
|
||||
void _showTerminalClipboardNotice(
|
||||
TerminalClipboardNoticeRequest<int> request,
|
||||
) {
|
||||
final controller = ScaffoldMessenger.of(context).showMaterialBanner(
|
||||
MaterialBanner(
|
||||
leading: const Icon(Icons.content_copy_outlined),
|
||||
content: Text(translate(kTerminalClipboardNoticeMessageKey)),
|
||||
actions: [
|
||||
AnimatedBuilder(
|
||||
animation: _terminalClipboardNotice,
|
||||
builder: (_, __) => TextButton(
|
||||
onPressed: _terminalClipboardNotice.canClaimAction
|
||||
? _handleTerminalClipboardNegativeAction
|
||||
: null,
|
||||
child: Text(translate(request.negativeActionKey)),
|
||||
),
|
||||
),
|
||||
AnimatedBuilder(
|
||||
animation: _terminalClipboardNotice,
|
||||
builder: (_, __) => TextButton(
|
||||
onPressed: _terminalClipboardNotice.canClaimAction
|
||||
? _handleTerminalClipboardPositiveAction
|
||||
: null,
|
||||
child: Text(translate(request.actionKey)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
_terminalClipboardNoticeController = controller;
|
||||
unawaited(controller.closed.then<void>((_) {
|
||||
if (identical(_terminalClipboardNoticeController, controller)) {
|
||||
_terminalClipboardNoticeController = null;
|
||||
_terminalClipboardNotice.noticeClosed();
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardNegativeAction() {
|
||||
final request = _terminalClipboardNotice.claimCurrentAction();
|
||||
if (request == null) return;
|
||||
if (request.persistAllowed) {
|
||||
unawaited(_declineTerminalClipboardWrite());
|
||||
} else {
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleTerminalClipboardPositiveAction() {
|
||||
final request = _terminalClipboardNotice.claimCurrentAction();
|
||||
if (request == null) return;
|
||||
unawaited(_completeTerminalClipboardWrite(request));
|
||||
}
|
||||
|
||||
bool get _canWriteTerminalClipboard =>
|
||||
_canHandleTerminalClipboardWriteRequest &&
|
||||
!_ffi.closed &&
|
||||
_ffi.ffiModel.permissions['clipboard'] != false;
|
||||
|
||||
void _handleTerminalClipboardWriteSucceeded(String _) {
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
Future<void> _declineTerminalClipboardWrite() async {
|
||||
try {
|
||||
await bind.mainSetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
value: kTerminalClipboardWriteDenied,
|
||||
);
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'[TerminalPage] Failed to save terminal clipboard permission: $error');
|
||||
return;
|
||||
} finally {
|
||||
_terminalClipboardNotice.releaseAction();
|
||||
}
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
Future<void> _completeTerminalClipboardWrite(
|
||||
TerminalClipboardNoticeRequest<int> request,
|
||||
) async {
|
||||
var completed = false;
|
||||
try {
|
||||
completed = await completeTerminalClipboardWrite(
|
||||
clipboardText: request.text,
|
||||
canWrite: () => _canWriteTerminalClipboard,
|
||||
writeClipboard: writeTerminalClipboard,
|
||||
persistAllowed: request.persistAllowed
|
||||
? () => bind.mainSetLocalOption(
|
||||
key: kOptionAllowTerminalClipboardWrite,
|
||||
value: kTerminalClipboardWriteAllowed,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'[TerminalPage] Failed to complete terminal clipboard write: $error');
|
||||
} finally {
|
||||
_terminalClipboardNotice.releaseAction();
|
||||
}
|
||||
if (!completed) return;
|
||||
_closeTerminalClipboardNotice();
|
||||
}
|
||||
|
||||
void _closeTerminalClipboardNotice() {
|
||||
if (!_terminalClipboardNotice.beginClose()) return;
|
||||
final controller = _terminalClipboardNoticeController;
|
||||
if (controller == null) {
|
||||
debugPrint('[TerminalPage] Clipboard notice controller is missing');
|
||||
_terminalClipboardNotice.noticeClosed();
|
||||
return;
|
||||
}
|
||||
controller.close();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Unregister terminal model from FFI
|
||||
_ffi.unregisterTerminalModel(widget.terminalId);
|
||||
_terminalModel.dispose();
|
||||
_keyboardDebounce?.cancel();
|
||||
_terminalClipboardNotice.clear();
|
||||
_terminalClipboardNoticeController?.close();
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
super.dispose();
|
||||
TerminalConnectionManager.releaseConnection(widget.id);
|
||||
@@ -390,7 +190,6 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
KeyEventResult _handleTerminalKeyEvent(FocusNode _, KeyEvent event) {
|
||||
final hardwareKeyboard = HardwareKeyboard.instance;
|
||||
final shouldPaste = shouldHandleTerminalPasteShortcut(
|
||||
platform: defaultTargetPlatform,
|
||||
logicalKey: event.logicalKey,
|
||||
isKeyDown: event is KeyDownEvent,
|
||||
isKeyRepeat: event is KeyRepeatEvent,
|
||||
@@ -432,12 +231,12 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final heightPx = constraints.maxHeight;
|
||||
return _buildTerminalViewForPlatform(
|
||||
reportMouseInput: isWebDesktop || isAndroid,
|
||||
reportTouchInput: isIOS,
|
||||
terminal: _terminalModel.terminal,
|
||||
return TerminalView(
|
||||
_terminalModel.terminal,
|
||||
controller: _terminalModel.terminalController,
|
||||
autofocus: true,
|
||||
textStyle: _getTerminalStyle(),
|
||||
backgroundOpacity: 0.7,
|
||||
// The following comment is from xterm.dart source code:
|
||||
// Workaround to detect delete key for platforms and IMEs that do not
|
||||
// emit a hardware delete event. Preferred on mobile platforms. [false] by
|
||||
@@ -445,12 +244,7 @@ class _TerminalPageState extends State<TerminalPage>
|
||||
//
|
||||
// Android works fine without this workaround.
|
||||
deleteDetection: isIOS,
|
||||
shortcuts: platformTerminalShortcuts(),
|
||||
onKeyEvent: terminalCopyHandler(
|
||||
_terminalModel.terminal,
|
||||
_terminalModel.terminalController,
|
||||
fallback: _handleTerminalKeyEvent,
|
||||
),
|
||||
onKeyEvent: _handleTerminalKeyEvent,
|
||||
padding: _calculatePadding(heightPx),
|
||||
onSecondaryTapDown: (details, offset) async {
|
||||
final selection = _terminalModel.terminalController.selection;
|
||||
|
||||
@@ -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 connection");
|
||||
gFFI.chatModel.onVoiceCallClosed("End connetion");
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -381,14 +381,6 @@ class FileController {
|
||||
void set homePath(String path) => options.value.home = path;
|
||||
OverlayDialogManager? get dialogManager => rootState.target?.dialogManager;
|
||||
|
||||
bool _isPathAllowed(String candidate) {
|
||||
if (!isAndroid || !isLocal) return true;
|
||||
if (homePath.isEmpty || candidate.isEmpty) return false;
|
||||
final home = PathUtil.posixContext.normalize(homePath);
|
||||
final target = PathUtil.posixContext.normalize(candidate);
|
||||
return target == home || PathUtil.posixContext.isWithin(home, target);
|
||||
}
|
||||
|
||||
String get shortPath {
|
||||
final dirPath = directory.value.path;
|
||||
if (dirPath.startsWith(homePath)) {
|
||||
@@ -422,13 +414,8 @@ class FileController {
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 100));
|
||||
|
||||
var savedDir = (await bind.sessionGetPeerOption(
|
||||
final savedDir = (await bind.sessionGetPeerOption(
|
||||
sessionId: sessionId, name: isLocal ? "local_dir" : "remote_dir"));
|
||||
if (savedDir.isNotEmpty && !_isPathAllowed(savedDir)) {
|
||||
savedDir = options.value.home;
|
||||
await bind.sessionPeerOption(
|
||||
sessionId: sessionId, name: "local_dir", value: savedDir);
|
||||
}
|
||||
Future<bool> tryOpenReadyDirs() async {
|
||||
final dirs = <String>{
|
||||
if (directory.value.path.isNotEmpty) directory.value.path,
|
||||
@@ -498,9 +485,6 @@ class FileController {
|
||||
}
|
||||
|
||||
Future<bool> _openDirectoryPath(String path, {bool isBack = false}) async {
|
||||
if (!_isPathAllowed(path)) {
|
||||
return false;
|
||||
}
|
||||
if (!isBack) {
|
||||
pushHistory();
|
||||
}
|
||||
@@ -520,7 +504,6 @@ class FileController {
|
||||
return true;
|
||||
}
|
||||
fd.format(isWindows, sort: sortBy.value);
|
||||
selectedItems.reconcile(fd.entries);
|
||||
directory.value = fd;
|
||||
return true;
|
||||
} catch (e) {
|
||||
@@ -567,9 +550,6 @@ class FileController {
|
||||
final isWindows = options.value.isWindows;
|
||||
final dirPath = directory.value.path;
|
||||
var parent = PathUtil.dirname(dirPath, isWindows);
|
||||
if (!_isPathAllowed(parent)) {
|
||||
return true;
|
||||
}
|
||||
// specially for C:\, D:\, goto '/'
|
||||
if (parent == dirPath && isWindows) {
|
||||
return await _openDirectoryPath('/', isBack: isBack);
|
||||
@@ -1905,7 +1885,7 @@ class PathUtil {
|
||||
}
|
||||
|
||||
static bool validName(String name, bool isWindows) {
|
||||
final unixFileNamePattern = RegExp(r'^[^/\x00]+$');
|
||||
final unixFileNamePattern = RegExp(r'^[^/\0]+$');
|
||||
final windowsFileNamePattern = RegExp(r'^[^<>:"/\\|?*]+$');
|
||||
final reg = isWindows ? windowsFileNamePattern : unixFileNamePattern;
|
||||
return reg.hasMatch(name);
|
||||
@@ -1948,21 +1928,6 @@ class SelectedItems {
|
||||
items.clear();
|
||||
}
|
||||
|
||||
void reconcile(List<Entry> entries) {
|
||||
if (items.isEmpty) return;
|
||||
final currentByPath = {for (final entry in entries) entry.path: entry};
|
||||
final reconciled = <Entry>[];
|
||||
for (final item in items) {
|
||||
final current = currentByPath[item.path];
|
||||
if (current != null && current.entryType == item.entryType) {
|
||||
reconciled.add(current);
|
||||
}
|
||||
}
|
||||
items
|
||||
..clear()
|
||||
..addAll(reconciled);
|
||||
}
|
||||
|
||||
void selectAll(List<Entry> entries) {
|
||||
items.clear();
|
||||
items.addAll(entries);
|
||||
|
||||
@@ -117,11 +117,10 @@ String prepareTerminalInputPayload(
|
||||
|
||||
/// Returns true when a hardware paste shortcut must bypass keyboard modifiers.
|
||||
///
|
||||
/// xterm already handles each platform's paste shortcut in the common case.
|
||||
/// Only intercept while a virtual Ctrl/Alt lock is active, because xterm can
|
||||
/// emit a one-character paste as normal text when bracketed paste mode is off.
|
||||
/// xterm already handles hardware Ctrl/Cmd+V correctly in the common case. Only
|
||||
/// intercept while a virtual Ctrl/Alt lock is active, because xterm can emit a
|
||||
/// one-character paste as normal text when bracketed paste mode is disabled.
|
||||
bool shouldHandleTerminalPasteShortcut({
|
||||
required TargetPlatform platform,
|
||||
required LogicalKeyboardKey logicalKey,
|
||||
required bool isKeyDown,
|
||||
required bool isKeyRepeat,
|
||||
@@ -134,18 +133,8 @@ bool shouldHandleTerminalPasteShortcut({
|
||||
if (!modifierLockActive) return false;
|
||||
if (!isKeyDown && !isKeyRepeat) return false;
|
||||
if (logicalKey != LogicalKeyboardKey.keyV) return false;
|
||||
if (altPressed) return false;
|
||||
switch (platform) {
|
||||
case TargetPlatform.linux:
|
||||
return controlPressed && !metaPressed && shiftPressed;
|
||||
case TargetPlatform.iOS:
|
||||
case TargetPlatform.macOS:
|
||||
return !controlPressed && metaPressed && !shiftPressed;
|
||||
case TargetPlatform.android:
|
||||
case TargetPlatform.fuchsia:
|
||||
case TargetPlatform.windows:
|
||||
return controlPressed && !metaPressed && !shiftPressed;
|
||||
}
|
||||
if (altPressed || shiftPressed) return false;
|
||||
return controlPressed != metaPressed;
|
||||
}
|
||||
|
||||
/// Returns true when collapsing Row3 should also clear hidden modifier state.
|
||||
|
||||
+68
-422
@@ -58,8 +58,7 @@ const _restartReconnectSilentDelaySecs = 5;
|
||||
class CachedPeerData {
|
||||
Map<String, dynamic> updatePrivacyMode = {};
|
||||
Map<String, dynamic> peerInfo = {};
|
||||
// No shapes: the core keeps them for the session, and the window a tab moves to asks it
|
||||
// for the one in use.
|
||||
List<Map<String, dynamic>> cursorDataList = [];
|
||||
Map<String, dynamic> lastCursorId = {};
|
||||
Map<String, bool> permissions = {};
|
||||
|
||||
@@ -74,6 +73,7 @@ class CachedPeerData {
|
||||
return jsonEncode({
|
||||
'updatePrivacyMode': updatePrivacyMode,
|
||||
'peerInfo': peerInfo,
|
||||
'cursorDataList': cursorDataList,
|
||||
'lastCursorId': lastCursorId,
|
||||
'permissions': permissions,
|
||||
'secure': secure,
|
||||
@@ -88,6 +88,9 @@ 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;
|
||||
@@ -121,8 +124,6 @@ class FfiModel with ChangeNotifier {
|
||||
Timer? _restartReconnectDelayTimer;
|
||||
var _reconnects = 1;
|
||||
DateTime? _offlineReconnectStartTime;
|
||||
bool _androidDocumentPickerActive = false;
|
||||
bool _androidDocumentPickerInterruptedConnection = false;
|
||||
bool _viewOnly = false;
|
||||
bool _showMyCursor = false;
|
||||
WeakReference<FFI> parent;
|
||||
@@ -163,7 +164,6 @@ 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;
|
||||
@@ -255,8 +255,6 @@ class FfiModel with ChangeNotifier {
|
||||
_inputBlocked = false;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_androidDocumentPickerActive = false;
|
||||
_androidDocumentPickerInterruptedConnection = false;
|
||||
resetRestartReconnectState();
|
||||
clearPermissions();
|
||||
waitForImageTimer?.cancel();
|
||||
@@ -320,6 +318,10 @@ 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);
|
||||
@@ -349,6 +351,9 @@ 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);
|
||||
@@ -887,17 +892,6 @@ class FfiModel with ChangeNotifier {
|
||||
final text = evt['text'];
|
||||
final link = evt['link'];
|
||||
|
||||
// The peer-gone detector reconnects under `restarting-show` rather than an error title, so
|
||||
// it needs naming here too. By its own title, not the type: an explicitly restarted remote
|
||||
// device reaches the same type from a path this change does not touch.
|
||||
if (isAndroid &&
|
||||
_androidDocumentPickerActive &&
|
||||
(title == 'Connection Error' ||
|
||||
(type == 'restarting-show' && title == 'Connecting...'))) {
|
||||
_androidDocumentPickerInterruptedConnection = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable relative mouse mode on any error-type message to ensure cursor is released.
|
||||
// This includes connection errors, session-ending messages, elevation errors, etc.
|
||||
// Safety: releasing pointer lock on errors prevents the user from being stuck.
|
||||
@@ -974,23 +968,6 @@ class FfiModel with ChangeNotifier {
|
||||
_restartReconnectDelayTimer = null;
|
||||
}
|
||||
|
||||
void beginAndroidDocumentPicker() {
|
||||
if (!isAndroid) return;
|
||||
_androidDocumentPickerActive = true;
|
||||
_androidDocumentPickerInterruptedConnection = false;
|
||||
}
|
||||
|
||||
void endAndroidDocumentPicker() {
|
||||
if (!isAndroid) return;
|
||||
_androidDocumentPickerActive = false;
|
||||
if (!_androidDocumentPickerInterruptedConnection ||
|
||||
parent.target?.closed == true) {
|
||||
return;
|
||||
}
|
||||
_androidDocumentPickerInterruptedConnection = false;
|
||||
reconnect(parent.target!.dialogManager, sessionId, false);
|
||||
}
|
||||
|
||||
/// Auto-retry check for "Remote desktop is offline" error.
|
||||
/// returns true to auto-retry, false otherwise.
|
||||
bool shouldAutoRetryOnOffline(
|
||||
@@ -1427,9 +1404,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.
|
||||
// New monitor windows keep their selection in currentDisplay.
|
||||
final last = lastUserDisplay ?? _pi.currentDisplay;
|
||||
final last = lastUserDisplay;
|
||||
pendingMonitorRestore = (!isCache &&
|
||||
last != null &&
|
||||
last != currentDisplay &&
|
||||
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
|
||||
sessionId: sessionId) !=
|
||||
@@ -1652,14 +1629,9 @@ class FfiModel with ChangeNotifier {
|
||||
parent.target?.cursorModel.updateCursorId(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);
|
||||
handleCursorData(Map<String, dynamic> evt) async {
|
||||
cachedPeerData.cursorDataList.add(evt);
|
||||
await parent.target?.cursorModel.updateCursorData(evt);
|
||||
}
|
||||
|
||||
/// Handle the peer info synchronization event based on [evt].
|
||||
@@ -2397,9 +2369,7 @@ 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 &&
|
||||
_devicePixelRatio == ui.window.devicePixelRatio &&
|
||||
style != kRemoteViewStyleCustom) {
|
||||
if (_lastViewStyle == viewStyle && style != kRemoteViewStyleCustom) {
|
||||
return;
|
||||
}
|
||||
if (_lastViewStyle.style != viewStyle.style) {
|
||||
@@ -2459,8 +2429,6 @@ 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,8 +2440,7 @@ class CanvasModel with ChangeNotifier {
|
||||
style != null ? ScrollStyle.fromString(style) : ScrollStyle.scrollauto;
|
||||
|
||||
if (_scrollStyle != ScrollStyle.scrollauto) {
|
||||
// Scrollbar and Scroll Edge share controllers and retain their positions.
|
||||
updateScrollPercent();
|
||||
_resetScroll();
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
@@ -2853,13 +2820,9 @@ class CanvasModel with ChangeNotifier {
|
||||
|
||||
// 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;
|
||||
img2.Image? _image;
|
||||
final img2.Image image;
|
||||
double scale;
|
||||
Uint8List? data;
|
||||
final double hotxOrigin;
|
||||
@@ -2868,146 +2831,68 @@ 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 img2.Image image,
|
||||
required this.image,
|
||||
required this.scale,
|
||||
required this.data,
|
||||
required this.hotxOrigin,
|
||||
required this.hotyOrigin,
|
||||
required this.width,
|
||||
required this.height,
|
||||
}) : _image = image,
|
||||
_rasterWidth = (width * scale).ceil(),
|
||||
_rasterHeight = (height * scale).ceil(),
|
||||
hotx = hotxOrigin * scale,
|
||||
}) : hotx = hotxOrigin * scale,
|
||||
hoty = hotyOrigin * scale;
|
||||
|
||||
int _doubleToInt(double v) => (v * 10e6).round().toInt();
|
||||
|
||||
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).');
|
||||
}
|
||||
_scaleLimitReported = limited;
|
||||
return limitedScale;
|
||||
}
|
||||
|
||||
double _checkUpdateScale(double scale) {
|
||||
scale = _limitScale(scale);
|
||||
double oldScale = this.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));
|
||||
// Update data if scale changed.
|
||||
final tgtWidth = (width * scale).toInt();
|
||||
final tgtHeight = (width * scale).toInt();
|
||||
if (tgtWidth < kMinCursorSize || tgtHeight < kMinCursorSize) {
|
||||
double sw = kMinCursorSize.toDouble() / width;
|
||||
double sh = kMinCursorSize.toDouble() / height;
|
||||
scale = sw < sh ? sh : sw;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
if (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
|
||||
if (_doubleToInt(oldScale) != _doubleToInt(scale)) {
|
||||
if (isWindows) {
|
||||
data = img2
|
||||
.copyResize(
|
||||
image,
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
width: (width * scale).toInt(),
|
||||
height: (height * scale).toInt(),
|
||||
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: targetWidth,
|
||||
height: targetHeight,
|
||||
width: (width * scale).toInt(),
|
||||
height: (height * scale).toInt(),
|
||||
interpolation: img2.Interpolation.average,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
_rasterWidth = targetWidth;
|
||||
_rasterHeight = targetHeight;
|
||||
}
|
||||
|
||||
this.scale = scale;
|
||||
hotx = hotxOrigin * _rasterWidth / width;
|
||||
hoty = hotyOrigin * _rasterHeight / height;
|
||||
hotx = hotxOrigin * scale;
|
||||
hoty = hotyOrigin * scale;
|
||||
return scale;
|
||||
}
|
||||
|
||||
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()}';
|
||||
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3178,16 +3063,7 @@ class CursorModel with ChangeNotifier {
|
||||
|
||||
get lastIsBlocked => _lastIsBlocked;
|
||||
|
||||
/// 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;
|
||||
}
|
||||
|
||||
ui.Image? get image => _image;
|
||||
CursorData? get cache => _cache;
|
||||
|
||||
double get x => _x - _displayOriginX;
|
||||
@@ -3200,10 +3076,7 @@ class CursorModel with ChangeNotifier {
|
||||
double get hotx => _hotx;
|
||||
double get hoty => _hoty;
|
||||
|
||||
set id(String id) {
|
||||
if (_id != id) _unavailable = null;
|
||||
_id = id;
|
||||
}
|
||||
set id(String id) => _id = id;
|
||||
|
||||
bool get isPeerControlProtected =>
|
||||
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
|
||||
@@ -3218,12 +3091,7 @@ class CursorModel with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
CursorModel(this.parent);
|
||||
|
||||
Set<String> get cachedKeys => _cacheKeys;
|
||||
addKey(String key) => _cacheKeys.add(key);
|
||||
@@ -3522,44 +3390,30 @@ class CursorModel with ChangeNotifier {
|
||||
_images.clear();
|
||||
}
|
||||
|
||||
/// 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();
|
||||
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']);
|
||||
List<dynamic> colors = json.decode(evt['colors']);
|
||||
final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
|
||||
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(
|
||||
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();
|
||||
if (await _updateCache(rgba, image, id, hotx, hoty, width, height)) {
|
||||
_images[id]?.item1.dispose();
|
||||
_images[id] = Tuple3(image, hotx, hoty);
|
||||
}
|
||||
|
||||
// Update last cursor data.
|
||||
// Do not use the previous `image` and `id`, because `_id` may be changed.
|
||||
_updateCurData();
|
||||
final cache = _cacheMap[id];
|
||||
if (id != _id && cache != null) _switchedAway(cache);
|
||||
}
|
||||
|
||||
Future<bool> _updateCache(
|
||||
int generation,
|
||||
Uint8List rgba,
|
||||
ui.Image image,
|
||||
String id,
|
||||
@@ -3570,11 +3424,7 @@ class CursorModel with ChangeNotifier {
|
||||
) async {
|
||||
Uint8List? data;
|
||||
img2.Image imgOrigin = img2.Image.fromBytes(
|
||||
width: w,
|
||||
height: h,
|
||||
bytes: rgba.buffer,
|
||||
bytesOffset: rgba.offsetInBytes,
|
||||
order: img2.ChannelOrder.rgba);
|
||||
width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
|
||||
if (isWindows) {
|
||||
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
|
||||
} else {
|
||||
@@ -3584,17 +3434,6 @@ class CursorModel with ChangeNotifier {
|
||||
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,
|
||||
@@ -3607,200 +3446,34 @@ 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() {
|
||||
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);
|
||||
_cache = _cacheMap[_id];
|
||||
final tmp = _images[_id];
|
||||
if (tmp != null) {
|
||||
_images[_id] = tmp;
|
||||
_image = tmp.item1;
|
||||
_hotx = tmp.item2;
|
||||
_hoty = tmp.item3;
|
||||
} else if (_unavailable == _id) {
|
||||
_image = null;
|
||||
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;
|
||||
}
|
||||
_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()) {
|
||||
restorePixels(_id);
|
||||
debugPrint(
|
||||
'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3853,10 +3526,6 @@ class CursorModel with ChangeNotifier {
|
||||
_clearCache();
|
||||
_cache = null;
|
||||
_cacheMap.clear();
|
||||
_nativeIds.clear();
|
||||
_awaitingNative.clear();
|
||||
_unavailable = null;
|
||||
_generation++;
|
||||
}
|
||||
|
||||
_clearCache() {
|
||||
@@ -3865,8 +3534,6 @@ class CursorModel with ChangeNotifier {
|
||||
debugPrint("deleting cursor with key $k");
|
||||
deleteCustomCursor(k);
|
||||
}
|
||||
_cacheKeys.clear();
|
||||
shownKey = null;
|
||||
resetSystemCursor();
|
||||
}
|
||||
|
||||
@@ -3902,18 +3569,6 @@ class QualityMonitorModel with ChangeNotifier {
|
||||
bool get show => _show;
|
||||
QualityMonitorData get data => _data;
|
||||
|
||||
// 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;
|
||||
if (!streamType.startsWith('WebRTC')) return null;
|
||||
return ffiModel.direct == false ? '$streamType (TURN)' : streamType;
|
||||
}
|
||||
|
||||
checkShowQualityMonitor(SessionID sessionId) async {
|
||||
final show = await bind.sessionGetToggleOption(
|
||||
sessionId: sessionId, arg: 'show-quality-monitor') ==
|
||||
@@ -4206,7 +3861,6 @@ class FFI {
|
||||
}
|
||||
|
||||
if (isWeb) {
|
||||
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
|
||||
platformFFI.setRgbaCallback((int display, Uint8List data) {
|
||||
onEvent2UIRgba();
|
||||
imageModel.onRgba(display, data);
|
||||
@@ -4289,9 +3943,6 @@ 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;
|
||||
@@ -4409,11 +4060,6 @@ class FFI {
|
||||
return await platformFFI.invokeMethod(method, arguments);
|
||||
}
|
||||
|
||||
Future<T?> invokeMethodWithResult<T>(String method,
|
||||
[dynamic arguments]) async {
|
||||
return await platformFFI.invokeMethodWithResult<T>(method, arguments);
|
||||
}
|
||||
|
||||
// Terminal model management
|
||||
void registerTerminalModel(int terminalId, TerminalModel model) {
|
||||
debugPrint('[FFI] Registering terminal model for terminal $terminalId');
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:external_path/external_path.dart';
|
||||
import 'package:ffi/ffi.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -170,10 +171,8 @@ class PlatformFFI {
|
||||
_startListenEvent(_ffiBind); // global event
|
||||
try {
|
||||
if (isAndroid) {
|
||||
// Android file transfer uses app-specific storage. User-selected
|
||||
// files enter and leave this workspace through the system picker.
|
||||
_homeDir = (await getExternalStorageDirectory())?.path ??
|
||||
(await getApplicationSupportDirectory()).path;
|
||||
// only support for android
|
||||
_homeDir = (await ExternalPath.getExternalStorageDirectories())[0];
|
||||
} else if (isIOS) {
|
||||
// The previous code was `_homeDir = (await getDownloadsDirectory())?.path ?? '';`,
|
||||
// which provided the `downloads` path in the sandbox.
|
||||
@@ -285,10 +284,6 @@ 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) {}
|
||||
@@ -311,12 +306,6 @@ class PlatformFFI {
|
||||
return await _toAndroidChannel.invokeMethod(method, arguments);
|
||||
}
|
||||
|
||||
Future<T?> invokeMethodWithResult<T>(String method,
|
||||
[dynamic arguments]) async {
|
||||
if (!isAndroid) return null;
|
||||
return await _toAndroidChannel.invokeMethod<T>(method, arguments);
|
||||
}
|
||||
|
||||
void syncAndroidServiceAppDirConfigPath() {
|
||||
invokeMethod(AndroidChannel.kSyncAppDirConfigPath, _dir);
|
||||
}
|
||||
|
||||
@@ -1,108 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:xterm/xterm.dart';
|
||||
|
||||
enum TerminalClipboardWritePermission { denied, unconfigured, allowed }
|
||||
|
||||
class RustDeskTerminal extends Terminal {
|
||||
RustDeskTerminal({
|
||||
super.maxLines,
|
||||
required TerminalClipboardWritePermission Function()
|
||||
clipboardWritePermission,
|
||||
required Future<bool> Function(String) onClipboardWrite,
|
||||
ValueChanged<String>? onClipboardWriteBlocked,
|
||||
ValueChanged<String>? onClipboardWriteSucceeded,
|
||||
}) : _clipboardWritePermission = clipboardWritePermission,
|
||||
_onClipboardWrite = onClipboardWrite,
|
||||
_onClipboardWriteBlocked = onClipboardWriteBlocked,
|
||||
_onClipboardWriteSucceeded = onClipboardWriteSucceeded {
|
||||
onPrivateOSC = _handlePrivateOsc;
|
||||
}
|
||||
|
||||
static const _clipboardOscCode = '52';
|
||||
static const _systemClipboardSelection = 'c';
|
||||
// Match the terminal helper's existing payload safety ceiling.
|
||||
static const _maxClipboardWriteBytes = 16 * 1024 * 1024;
|
||||
static const _base64InputBytesPerBlock = 3;
|
||||
static const _base64EncodedCharsPerBlock = 4;
|
||||
static final _osc52Selection = RegExp(r'^[cpqs0-7]*$');
|
||||
final TerminalClipboardWritePermission Function() _clipboardWritePermission;
|
||||
final Future<bool> Function(String) _onClipboardWrite;
|
||||
final ValueChanged<String>? _onClipboardWriteBlocked;
|
||||
final ValueChanged<String>? _onClipboardWriteSucceeded;
|
||||
|
||||
bool get isClipboardWriteAllowed =>
|
||||
_clipboardWritePermission() == TerminalClipboardWritePermission.allowed;
|
||||
|
||||
void _handlePrivateOsc(String code, List<String> args) {
|
||||
if (code != _clipboardOscCode) return;
|
||||
if (args.length != 2 || !_osc52Selection.hasMatch(args.first)) {
|
||||
debugPrint('[RustDeskTerminal] Rejected malformed OSC 52 command');
|
||||
return;
|
||||
}
|
||||
if (args.last == '?') {
|
||||
debugPrint('[RustDeskTerminal] Rejected OSC 52 clipboard query');
|
||||
return;
|
||||
}
|
||||
final permission = _clipboardWritePermission();
|
||||
if (permission == TerminalClipboardWritePermission.denied) {
|
||||
debugPrint('[RustDeskTerminal] Rejected unauthorized OSC 52 write');
|
||||
return;
|
||||
}
|
||||
final selection = args.first;
|
||||
if (selection.isNotEmpty &&
|
||||
!selection.contains(_systemClipboardSelection)) {
|
||||
debugPrint('[RustDeskTerminal] Ignored unsupported OSC 52 selection');
|
||||
return;
|
||||
}
|
||||
if (selection.replaceAll(_systemClipboardSelection, '').isNotEmpty) {
|
||||
debugPrint('[RustDeskTerminal] Ignored unsupported OSC 52 selections');
|
||||
}
|
||||
final text = _decodeClipboardPayload(args.last);
|
||||
if (text == null) return;
|
||||
if (permission == TerminalClipboardWritePermission.unconfigured) {
|
||||
debugPrint('[RustDeskTerminal] Blocked OSC 52 write pending consent');
|
||||
_onClipboardWriteBlocked?.call(text);
|
||||
return;
|
||||
}
|
||||
unawaited(_writeClipboard(text));
|
||||
}
|
||||
|
||||
Future<void> _writeClipboard(String text) async {
|
||||
final succeeded = await _onClipboardWrite(text);
|
||||
if (succeeded) {
|
||||
_onClipboardWriteSucceeded?.call(text);
|
||||
return;
|
||||
}
|
||||
debugPrint(
|
||||
'[RustDeskTerminal] OSC 52 clipboard write requires interaction');
|
||||
_onClipboardWriteBlocked?.call(text);
|
||||
}
|
||||
|
||||
String? _decodeClipboardPayload(String payload) {
|
||||
if (payload.length > _maxBase64EncodedLength(_maxClipboardWriteBytes)) {
|
||||
debugPrint('[RustDeskTerminal] Rejected oversized OSC 52 payload');
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final bytes = base64.decode(payload);
|
||||
if (bytes.length > _maxClipboardWriteBytes) {
|
||||
debugPrint('[RustDeskTerminal] Rejected oversized OSC 52 payload');
|
||||
return null;
|
||||
}
|
||||
return utf8.decode(bytes);
|
||||
} on FormatException {
|
||||
debugPrint('[RustDeskTerminal] Rejected malformed OSC 52 payload');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static int _maxBase64EncodedLength(int maxBytes) =>
|
||||
((maxBytes + _base64InputBytesPerBlock - 1) ~/
|
||||
_base64InputBytesPerBlock) *
|
||||
_base64EncodedCharsPerBlock;
|
||||
RustDeskTerminal({super.maxLines});
|
||||
|
||||
@override
|
||||
void eraseScrollbackOnly() {
|
||||
|
||||
@@ -210,10 +210,15 @@ class ServerModel with ChangeNotifier {
|
||||
_audioOk = audioOption != 'N';
|
||||
}
|
||||
|
||||
// Android file transfer is confined to app-specific storage. Files enter
|
||||
// and leave the workspace through Android's system document picker.
|
||||
final fileOption = await bind.mainGetOption(key: kOptionEnableFileTransfer);
|
||||
_fileOk = fileOption != 'N';
|
||||
// file
|
||||
if (!await AndroidPermissionManager.check(kManageExternalStorage)) {
|
||||
_fileOk = false;
|
||||
bind.mainSetOption(key: kOptionEnableFileTransfer, value: "N");
|
||||
} else {
|
||||
final fileOption =
|
||||
await bind.mainGetOption(key: kOptionEnableFileTransfer);
|
||||
_fileOk = fileOption != 'N';
|
||||
}
|
||||
|
||||
// clipboard
|
||||
final clipOption = await bind.mainGetOption(key: kOptionEnableClipboard);
|
||||
@@ -314,6 +319,16 @@ class ServerModel with ChangeNotifier {
|
||||
if (clients.any((c) => !c.disconnected)) {
|
||||
await showClientsMayNotBeChangedAlert(parent.target);
|
||||
}
|
||||
if (!_fileOk &&
|
||||
!await AndroidPermissionManager.check(kManageExternalStorage)) {
|
||||
final res =
|
||||
await AndroidPermissionManager.request(kManageExternalStorage);
|
||||
if (!res) {
|
||||
showToast(translate('Failed'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_fileOk = !_fileOk;
|
||||
bind.mainSetOption(
|
||||
key: kOptionEnableFileTransfer,
|
||||
@@ -403,6 +418,9 @@ class ServerModel with ChangeNotifier {
|
||||
if (bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) != 'Y') {
|
||||
await checkFloatingWindowPermission();
|
||||
}
|
||||
if (!await AndroidPermissionManager.check(kManageExternalStorage)) {
|
||||
await AndroidPermissionManager.request(kManageExternalStorage);
|
||||
}
|
||||
final res = await parent.target?.dialogManager
|
||||
.show<bool>((setState, close, context) {
|
||||
submit() => close(true);
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
Future<bool> writeTerminalClipboardPlatform(
|
||||
String text, {
|
||||
bool userInitiated = false,
|
||||
}) async {
|
||||
try {
|
||||
await Clipboard.setData(ClipboardData(text: text));
|
||||
return true;
|
||||
} catch (error) {
|
||||
debugPrint('[Terminal] Failed to write clipboard: $error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import 'dart:js_interop';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
const _writeTerminalClipboardCommand = 'write_terminal_clipboard';
|
||||
|
||||
@JS('setByName')
|
||||
external JSPromise<JSBoolean> _setByName(
|
||||
JSString name,
|
||||
JSString value,
|
||||
JSBoolean userInitiated,
|
||||
);
|
||||
|
||||
Future<bool> writeTerminalClipboardPlatform(
|
||||
String text, {
|
||||
bool userInitiated = false,
|
||||
}) async {
|
||||
try {
|
||||
final result = await _setByName(
|
||||
_writeTerminalClipboardCommand.toJS,
|
||||
text.toJS,
|
||||
userInitiated.toJS,
|
||||
).toDart;
|
||||
return result.toDart;
|
||||
} catch (error) {
|
||||
debugPrint('[Terminal] Failed to write Web clipboard: $error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -3,195 +3,60 @@ import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_hbb/consts.dart';
|
||||
import 'package:xterm/xterm.dart';
|
||||
|
||||
import 'terminal_clipboard_writer.dart'
|
||||
if (dart.library.html) 'terminal_clipboard_writer_web.dart';
|
||||
|
||||
const _controlShiftVPasteShortcut = SingleActivator(
|
||||
LogicalKeyboardKey.keyV,
|
||||
control: true,
|
||||
shift: true,
|
||||
);
|
||||
|
||||
typedef TerminalClipboardWriter = Future<bool> Function(
|
||||
String text, {
|
||||
required bool userInitiated,
|
||||
});
|
||||
|
||||
class TerminalClipboardNoticeRequest<T> {
|
||||
const TerminalClipboardNoticeRequest({
|
||||
required this.source,
|
||||
required this.text,
|
||||
required this.persistAllowed,
|
||||
});
|
||||
|
||||
final T source;
|
||||
final String text;
|
||||
final bool persistAllowed;
|
||||
|
||||
String get actionKey => persistAllowed ? 'Enable' : 'Copy to clipboard';
|
||||
|
||||
String get negativeActionKey => persistAllowed ? 'Decline' : 'Dismiss';
|
||||
}
|
||||
|
||||
const kTerminalClipboardNoticeMessageKey = 'terminal-clipboard-write-tip';
|
||||
|
||||
class TerminalClipboardNoticeCoordinator<T> extends ChangeNotifier {
|
||||
TerminalClipboardNoticeRequest<T>? _current;
|
||||
bool _noticeVisible = false;
|
||||
bool _actionInProgress = false;
|
||||
|
||||
TerminalClipboardNoticeRequest<T>? get current => _current;
|
||||
bool get canClaimAction =>
|
||||
_noticeVisible && !_actionInProgress && _current != null;
|
||||
|
||||
TerminalClipboardNoticeRequest<T>? currentForSource(T source) {
|
||||
final current = _current;
|
||||
if (current == null || current.source != source) return null;
|
||||
return current;
|
||||
Future<void> writeTerminalClipboard(String text) async {
|
||||
try {
|
||||
await Clipboard.setData(ClipboardData(text: text));
|
||||
} catch (error) {
|
||||
debugPrint('[Terminal] Failed to write clipboard: $error');
|
||||
}
|
||||
|
||||
TerminalClipboardNoticeRequest<T>? recordBlocked({
|
||||
required T source,
|
||||
required String text,
|
||||
required String option,
|
||||
required bool Function(T source) canWrite,
|
||||
}) {
|
||||
if (!canWrite(source)) return null;
|
||||
final requestAllowsPersistence =
|
||||
option == kTerminalClipboardWriteUnconfigured;
|
||||
if (option != kTerminalClipboardWriteAllowed && !requestAllowsPersistence) {
|
||||
return null;
|
||||
}
|
||||
if (_noticeVisible && _actionInProgress) return null;
|
||||
final wasVisible = _noticeVisible;
|
||||
final persistAllowed =
|
||||
wasVisible ? _current?.persistAllowed : requestAllowsPersistence;
|
||||
final request = TerminalClipboardNoticeRequest(
|
||||
source: source,
|
||||
text: text,
|
||||
persistAllowed: persistAllowed ?? requestAllowsPersistence,
|
||||
);
|
||||
_current = request;
|
||||
if (wasVisible) return null;
|
||||
_noticeVisible = true;
|
||||
return request;
|
||||
}
|
||||
|
||||
TerminalClipboardNoticeRequest<T>? claimCurrentAction() {
|
||||
if (!canClaimAction) return null;
|
||||
final current = _current;
|
||||
if (current == null) return null;
|
||||
_actionInProgress = true;
|
||||
notifyListeners();
|
||||
return current;
|
||||
}
|
||||
|
||||
void releaseAction() {
|
||||
if (!_actionInProgress) return;
|
||||
_actionInProgress = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool beginClose() {
|
||||
if (!_noticeVisible) return false;
|
||||
_actionInProgress = true;
|
||||
notifyListeners();
|
||||
return true;
|
||||
}
|
||||
|
||||
void noticeClosed() => clear();
|
||||
|
||||
void clear() {
|
||||
_current = null;
|
||||
_noticeVisible = false;
|
||||
_actionInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> writeTerminalClipboard(
|
||||
String text, {
|
||||
bool userInitiated = false,
|
||||
}) =>
|
||||
writeTerminalClipboardPlatform(text, userInitiated: userInitiated);
|
||||
|
||||
Future<bool> completeTerminalClipboardWrite({
|
||||
required String clipboardText,
|
||||
required bool Function() canWrite,
|
||||
required TerminalClipboardWriter writeClipboard,
|
||||
Future<void> Function()? persistAllowed,
|
||||
}) async {
|
||||
if (!canWrite()) return false;
|
||||
if (!await writeClipboard(clipboardText, userInitiated: true)) return false;
|
||||
await persistAllowed?.call();
|
||||
return true;
|
||||
}
|
||||
|
||||
Map<ShortcutActivator, Intent>? platformTerminalShortcuts() {
|
||||
final platform = defaultTargetPlatform;
|
||||
if (platform == TargetPlatform.linux) {
|
||||
return {
|
||||
for (final entry in defaultTerminalShortcuts.entries)
|
||||
if (!_isControlShortcut(entry.key, LogicalKeyboardKey.keyV))
|
||||
entry.key: entry.value,
|
||||
_controlShiftVPasteShortcut:
|
||||
const PasteTextIntent(SelectionChangedCause.keyboard),
|
||||
};
|
||||
}
|
||||
if (platform != TargetPlatform.windows &&
|
||||
platform != TargetPlatform.android) {
|
||||
return null;
|
||||
}
|
||||
if (defaultTargetPlatform != TargetPlatform.linux) return null;
|
||||
return {
|
||||
for (final entry in defaultTerminalShortcuts.entries)
|
||||
if (!_isControlShortcut(
|
||||
entry.key,
|
||||
LogicalKeyboardKey.keyC,
|
||||
shift: true,
|
||||
))
|
||||
entry.key: entry.value,
|
||||
if (!_isControlVShortcut(entry.key)) entry.key: entry.value,
|
||||
_controlShiftVPasteShortcut:
|
||||
const PasteTextIntent(SelectionChangedCause.keyboard),
|
||||
};
|
||||
}
|
||||
|
||||
bool _isControlShortcut(
|
||||
ShortcutActivator shortcut,
|
||||
LogicalKeyboardKey key, {
|
||||
bool shift = false,
|
||||
}) =>
|
||||
bool _isControlVShortcut(ShortcutActivator shortcut) =>
|
||||
shortcut is SingleActivator &&
|
||||
shortcut.trigger == key &&
|
||||
shortcut.trigger == LogicalKeyboardKey.keyV &&
|
||||
shortcut.control &&
|
||||
shortcut.shift == shift &&
|
||||
!shortcut.shift &&
|
||||
!shortcut.alt &&
|
||||
!shortcut.meta;
|
||||
|
||||
FocusOnKeyEventCallback terminalCopyHandler(
|
||||
Terminal terminal,
|
||||
TerminalController controller, {
|
||||
FocusOnKeyEventCallback? fallback,
|
||||
}) =>
|
||||
(focusNode, event) {
|
||||
if (_isSelectionCopyShortcut(event)) {
|
||||
final selection = controller.selection;
|
||||
if (selection != null && !selection.isCollapsed) {
|
||||
if (event is KeyDownEvent) {
|
||||
final text = terminal.buffer.getText(selection);
|
||||
unawaited(writeTerminalClipboard(text, userInitiated: true));
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
TerminalController controller,
|
||||
) =>
|
||||
(_, event) {
|
||||
if (!_isWindowsCopyShortcut(event)) return KeyEventResult.ignored;
|
||||
final selection = controller.selection;
|
||||
if (selection == null || selection.isCollapsed) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
return fallback?.call(focusNode, event) ?? KeyEventResult.ignored;
|
||||
if (event is KeyDownEvent) {
|
||||
final text = terminal.buffer.getText(selection);
|
||||
unawaited(writeTerminalClipboard(text));
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
};
|
||||
|
||||
bool _isSelectionCopyShortcut(KeyEvent event) {
|
||||
bool _isWindowsCopyShortcut(KeyEvent event) {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
final platform = defaultTargetPlatform;
|
||||
final usesControlCopy =
|
||||
platform == TargetPlatform.windows || platform == TargetPlatform.android;
|
||||
return usesControlCopy &&
|
||||
return defaultTargetPlatform == TargetPlatform.windows &&
|
||||
(event is KeyDownEvent || event is KeyRepeatEvent) &&
|
||||
event.logicalKey == LogicalKeyboardKey.keyC &&
|
||||
keyboard.isControlPressed &&
|
||||
|
||||
@@ -11,38 +11,8 @@ import 'input_modifier_utils.dart';
|
||||
import 'model.dart';
|
||||
import 'platform_model.dart';
|
||||
import 'rustdesk_terminal.dart';
|
||||
import 'terminal_copy_shortcut.dart';
|
||||
import 'terminal_mouse_handler.dart';
|
||||
|
||||
bool canConfigureTerminalClipboardPermission({
|
||||
required bool settingsDisabled,
|
||||
required bool optionFixed,
|
||||
}) =>
|
||||
!settingsDisabled && !optionFixed;
|
||||
|
||||
bool canHandleTerminalClipboardWriteRequest({
|
||||
required String localOption,
|
||||
required bool canConfigurePermission,
|
||||
}) =>
|
||||
canConfigurePermission || localOption == kTerminalClipboardWriteAllowed;
|
||||
|
||||
TerminalClipboardWritePermission terminalClipboardWritePermission(
|
||||
String localOption, {
|
||||
required bool remoteClipboardEnabled,
|
||||
bool canRequestConsent = true,
|
||||
}) {
|
||||
if (!remoteClipboardEnabled) {
|
||||
return TerminalClipboardWritePermission.denied;
|
||||
}
|
||||
if (localOption == kTerminalClipboardWriteAllowed) {
|
||||
return TerminalClipboardWritePermission.allowed;
|
||||
}
|
||||
if (localOption == kTerminalClipboardWriteUnconfigured && canRequestConsent) {
|
||||
return TerminalClipboardWritePermission.unconfigured;
|
||||
}
|
||||
return TerminalClipboardWritePermission.denied;
|
||||
}
|
||||
|
||||
class TerminalModel with ChangeNotifier {
|
||||
final String id; // peer id
|
||||
final FFI parent;
|
||||
@@ -92,9 +62,6 @@ class TerminalModel with ChangeNotifier {
|
||||
/// The listener (typically TerminalPage) can use this to auto-close the tab/page.
|
||||
VoidCallback? onClosed;
|
||||
|
||||
ValueChanged<String>? onClipboardWriteBlocked;
|
||||
ValueChanged<String>? onClipboardWriteSucceeded;
|
||||
|
||||
Future<void> _handleInput(String data) async {
|
||||
// xterm can complete asynchronous input after the Flutter page has gone
|
||||
// away. Stop before reading or clearing widget-owned modifier state.
|
||||
@@ -163,19 +130,7 @@ class TerminalModel with ChangeNotifier {
|
||||
}
|
||||
|
||||
TerminalModel(this.parent, [this.terminalId = 0]) : id = parent.id {
|
||||
terminal = RustDeskTerminal(
|
||||
maxLines: 10000,
|
||||
onClipboardWrite: writeTerminalClipboard,
|
||||
clipboardWritePermission: () => terminalClipboardWritePermission(
|
||||
bind.mainGetLocalOption(key: kOptionAllowTerminalClipboardWrite),
|
||||
remoteClipboardEnabled:
|
||||
parent.ffiModel.permissions['clipboard'] != false,
|
||||
canRequestConsent: onClipboardWriteBlocked != null,
|
||||
),
|
||||
onClipboardWriteBlocked: (text) => onClipboardWriteBlocked?.call(text),
|
||||
onClipboardWriteSucceeded: (text) =>
|
||||
onClipboardWriteSucceeded?.call(text),
|
||||
);
|
||||
terminal = RustDeskTerminal(maxLines: 10000);
|
||||
terminal.mouseHandler = const WheelButtonFixMouseHandler();
|
||||
terminalController = TerminalController();
|
||||
|
||||
@@ -638,8 +593,6 @@ class TerminalModel with ChangeNotifier {
|
||||
clearAltLock = null;
|
||||
onResizeExternal = null;
|
||||
onClosed = null;
|
||||
onClipboardWriteBlocked = null;
|
||||
onClipboardWriteSucceeded = null;
|
||||
// Clear buffers to free memory
|
||||
_inputBuffer.clear();
|
||||
_pendingOutputChunks.clear();
|
||||
|
||||
@@ -62,17 +62,13 @@ class TerminalMouseDragReporter {
|
||||
var _ownsControllerSuspension = false;
|
||||
var _releasePending = false;
|
||||
var _reporting = false;
|
||||
var _dragged = false;
|
||||
|
||||
bool handleDown(
|
||||
PointerDownEvent event,
|
||||
Terminal terminal,
|
||||
TerminalViewState? terminalView, {
|
||||
bool reportTouchInput = false,
|
||||
bool deferReport = false,
|
||||
}) {
|
||||
if (!_isPrimaryPointer(event, reportTouchInput) ||
|
||||
!_reportsDrag(terminal.mouseMode)) {
|
||||
TerminalViewState? terminalView,
|
||||
) {
|
||||
if (!_isPrimaryMouse(event) || !_reportsDrag(terminal.mouseMode)) {
|
||||
return false;
|
||||
}
|
||||
if (terminalView == null || terminalView.widget.readOnly) return false;
|
||||
@@ -87,33 +83,14 @@ class TerminalMouseDragReporter {
|
||||
_pointerId = event.pointer;
|
||||
_controller = controller;
|
||||
_ownsControllerSuspension = true;
|
||||
_releasePending = !deferReport;
|
||||
_reporting = !deferReport;
|
||||
_dragged = false;
|
||||
_releasePending = true;
|
||||
_reporting = true;
|
||||
controller.setSuspendPointerInput(true);
|
||||
_clearSelection(controller);
|
||||
final position = _cellAt(event, terminalView);
|
||||
_lastReportedPosition = position;
|
||||
if (!deferReport) {
|
||||
terminal.textInput(
|
||||
_report(terminal.mouseReportMode, position),
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool activateDeferredDown(Terminal terminal) {
|
||||
if (_pointerId == null ||
|
||||
_controller == null ||
|
||||
_releasePending ||
|
||||
!_reportsDrag(terminal.mouseMode)) {
|
||||
return false;
|
||||
}
|
||||
_releasePending = true;
|
||||
_reporting = true;
|
||||
_clearSelection(_controller);
|
||||
terminal.textInput(
|
||||
_report(terminal.mouseReportMode, _lastReportedPosition),
|
||||
_report(terminal.mouseReportMode, position),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -121,36 +98,26 @@ class TerminalMouseDragReporter {
|
||||
bool handleMove(
|
||||
PointerMoveEvent event,
|
||||
Terminal terminal,
|
||||
TerminalViewState? terminalView, {
|
||||
void Function(bool dragged)? beforeRelease,
|
||||
void Function()? onCancel,
|
||||
}) {
|
||||
TerminalViewState? terminalView,
|
||||
) {
|
||||
if (event.pointer != _pointerId) return false;
|
||||
if (terminalView == null) {
|
||||
onCancel?.call();
|
||||
cancel();
|
||||
return true;
|
||||
}
|
||||
final reportsDrag = _reportsDrag(terminal.mouseMode);
|
||||
if (!_hasPrimaryButton(event)) {
|
||||
if (!_isPrimaryMouse(event)) {
|
||||
if (_releasePending && reportsDrag) {
|
||||
_finishRelease(
|
||||
event,
|
||||
_reportRelease(
|
||||
terminal,
|
||||
terminalView,
|
||||
beforeRelease: beforeRelease,
|
||||
_reporting ? _cellAt(event, terminalView) : _lastReportedPosition,
|
||||
);
|
||||
} else {
|
||||
onCancel?.call();
|
||||
}
|
||||
cancel();
|
||||
return true;
|
||||
}
|
||||
if (!_reporting || !reportsDrag) {
|
||||
if (!reportsDrag && _releasePending) {
|
||||
_releasePending = false;
|
||||
onCancel?.call();
|
||||
}
|
||||
if (!reportsDrag) _releasePending = false;
|
||||
_reporting = false;
|
||||
// Keep ownership until the matching end event to suppress local selection.
|
||||
final controller = _controller;
|
||||
@@ -159,7 +126,7 @@ class TerminalMouseDragReporter {
|
||||
}
|
||||
|
||||
final position = _cellAt(event, terminalView);
|
||||
_recordPosition(position);
|
||||
_lastReportedPosition = position;
|
||||
terminal.textInput(
|
||||
_report(terminal.mouseReportMode, position, motion: true),
|
||||
);
|
||||
@@ -171,22 +138,16 @@ class TerminalMouseDragReporter {
|
||||
bool handleEnd(
|
||||
PointerEvent event,
|
||||
Terminal terminal,
|
||||
TerminalViewState? terminalView, {
|
||||
void Function(bool dragged)? beforeRelease,
|
||||
void Function()? onCancel,
|
||||
}) {
|
||||
TerminalViewState? terminalView,
|
||||
) {
|
||||
if (event.pointer != _pointerId) return false;
|
||||
if (terminalView != null &&
|
||||
_releasePending &&
|
||||
_reportsDrag(terminal.mouseMode)) {
|
||||
_finishRelease(
|
||||
event,
|
||||
_reportRelease(
|
||||
terminal,
|
||||
terminalView,
|
||||
beforeRelease: beforeRelease,
|
||||
_reporting ? _cellAt(event, terminalView) : _lastReportedPosition,
|
||||
);
|
||||
} else {
|
||||
onCancel?.call();
|
||||
}
|
||||
_clearSelection(_controller);
|
||||
final controller = _controller;
|
||||
@@ -211,7 +172,6 @@ class TerminalMouseDragReporter {
|
||||
_ownsControllerSuspension = false;
|
||||
_releasePending = false;
|
||||
_reporting = false;
|
||||
_dragged = false;
|
||||
}
|
||||
|
||||
void updateController(TerminalController controller) {
|
||||
@@ -243,24 +203,6 @@ class TerminalMouseDragReporter {
|
||||
);
|
||||
}
|
||||
|
||||
void _finishRelease(
|
||||
PointerEvent event,
|
||||
Terminal terminal,
|
||||
TerminalViewState terminalView, {
|
||||
void Function(bool dragged)? beforeRelease,
|
||||
}) {
|
||||
final position =
|
||||
_reporting ? _cellAt(event, terminalView) : _lastReportedPosition;
|
||||
if (_reporting) _recordPosition(position);
|
||||
beforeRelease?.call(_dragged);
|
||||
_reportRelease(terminal, position);
|
||||
}
|
||||
|
||||
void _recordPosition(CellOffset position) {
|
||||
_dragged = _dragged || position != _lastReportedPosition;
|
||||
_lastReportedPosition = position;
|
||||
}
|
||||
|
||||
CellOffset _cellAt(PointerEvent event, TerminalViewState terminalView) {
|
||||
final renderTerminal = terminalView.renderTerminal;
|
||||
return renderTerminal.getCellOffset(
|
||||
@@ -268,13 +210,9 @@ class TerminalMouseDragReporter {
|
||||
);
|
||||
}
|
||||
|
||||
bool _isPrimaryPointer(PointerEvent event, bool reportTouchInput) =>
|
||||
(event.kind == PointerDeviceKind.mouse ||
|
||||
reportTouchInput && event.kind == PointerDeviceKind.touch) &&
|
||||
_hasPrimaryButton(event);
|
||||
|
||||
bool _hasPrimaryButton(PointerEvent event) =>
|
||||
(event.buttons & kPrimaryButton) == kPrimaryButton;
|
||||
bool _isPrimaryMouse(PointerEvent event) =>
|
||||
event.kind == PointerDeviceKind.mouse &&
|
||||
(event.buttons & kPrimaryMouseButton) == kPrimaryMouseButton;
|
||||
|
||||
bool _reportsDrag(MouseMode mode) =>
|
||||
mode == MouseMode.upDownScrollDrag || mode == MouseMode.upDownScrollMove;
|
||||
|
||||
@@ -1,18 +1,45 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:xterm/xterm.dart';
|
||||
|
||||
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';
|
||||
/// xterm 4.0.0 encodes wheel buttons as 68..71; the extra bit reads as a Shift
|
||||
/// modifier, so strict full-screen apps ignore the report and never scroll.
|
||||
/// Upstream fix: TerminalStudio/xterm.dart#238.
|
||||
class WheelButtonFixMouseHandler implements TerminalMouseHandler {
|
||||
const WheelButtonFixMouseHandler({this.positionProvider});
|
||||
|
||||
final CellOffset? Function()? positionProvider;
|
||||
|
||||
@override
|
||||
String? call(TerminalMouseEvent event) {
|
||||
if (!event.button.isWheel) {
|
||||
return defaultMouseHandler(event);
|
||||
}
|
||||
// Same gate as UpDownMouseHandler: only the scroll modes report a wheel,
|
||||
// and a wheel release is never reported, so the report is always a press.
|
||||
if (!event.state.mouseMode.reportScroll ||
|
||||
event.buttonState == TerminalMouseButtonState.up) {
|
||||
return null;
|
||||
}
|
||||
return _reportWheel(event);
|
||||
}
|
||||
|
||||
String _reportWheel(TerminalMouseEvent event) {
|
||||
// Wheel buttons 4..7 go on the wire as 64..67, but `id` is 64 + 4..7.
|
||||
final button = event.button.id - 4;
|
||||
final position = positionProvider?.call() ?? event.position;
|
||||
return encodeTerminalMouseReport(
|
||||
event.state.mouseReportMode,
|
||||
button,
|
||||
position,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class TerminalMouseInteraction extends StatefulWidget {
|
||||
const TerminalMouseInteraction(
|
||||
@@ -20,12 +47,6 @@ class TerminalMouseInteraction extends StatefulWidget {
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.focusNode,
|
||||
this.autofocus = false,
|
||||
this.textStyle = const TerminalStyle(),
|
||||
this.deleteDetection = false,
|
||||
this.reportTouchInput = false,
|
||||
this.shortcuts,
|
||||
this.onKeyEvent,
|
||||
this.backgroundOpacity = 1,
|
||||
this.padding,
|
||||
this.onSecondaryTapDown,
|
||||
@@ -34,12 +55,6 @@ class TerminalMouseInteraction extends StatefulWidget {
|
||||
final Terminal terminal;
|
||||
final TerminalController controller;
|
||||
final FocusNode? focusNode;
|
||||
final bool autofocus;
|
||||
final TerminalStyle textStyle;
|
||||
final bool deleteDetection;
|
||||
final bool reportTouchInput;
|
||||
final Map<ShortcutActivator, Intent>? shortcuts;
|
||||
final FocusOnKeyEventCallback? onKeyEvent;
|
||||
final double backgroundOpacity;
|
||||
final EdgeInsets? padding;
|
||||
final void Function(TapDownDetails, CellOffset)? onSecondaryTapDown;
|
||||
@@ -56,7 +71,7 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
static const _scrollDown = 1;
|
||||
|
||||
final _terminalViewKey = GlobalKey<TerminalViewState>();
|
||||
late final _scrollController = TerminalScrollController(() => widget.terminal);
|
||||
final _scrollController = ScrollController();
|
||||
final _mouseDrag = TerminalMouseDragReporter();
|
||||
late final WheelButtonFixMouseHandler _mouseHandler;
|
||||
TerminalMouseHandler? _previousMouseHandler;
|
||||
@@ -66,13 +81,8 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
Buffer? _selectionBuffer;
|
||||
int? _selectionPointerId;
|
||||
Timer? _selectionScrollTimer;
|
||||
Timer? _pendingTouchMouseTimer;
|
||||
PointerDownEvent? _pendingTouchMouseDown;
|
||||
var _selectionHasScrolled = false;
|
||||
var _scrollDirection = _noScroll;
|
||||
// xterm can finish its tap callbacks after the raw drag was reported.
|
||||
var _suppressXtermLeftButton = false;
|
||||
var _terminalClipboardGesturePrepared = false;
|
||||
TerminalViewState? get _terminalView => _terminalViewKey.currentState;
|
||||
|
||||
@override
|
||||
@@ -80,7 +90,6 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
super.initState();
|
||||
_mouseHandler = WheelButtonFixMouseHandler(
|
||||
positionProvider: _cellAtPointer,
|
||||
suppressLeftButton: kIsWeb ? _consumeXtermLeftButtonSuppression : null,
|
||||
);
|
||||
_installMouseHandler(widget.terminal);
|
||||
}
|
||||
@@ -91,15 +100,10 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
final terminalChanged = !identical(oldWidget.terminal, widget.terminal);
|
||||
final controllerChanged =
|
||||
!identical(oldWidget.controller, widget.controller);
|
||||
final touchInputChanged =
|
||||
oldWidget.reportTouchInput != widget.reportTouchInput;
|
||||
if (!terminalChanged && !controllerChanged && !touchInputChanged) return;
|
||||
_cancelPendingTouchMouseDrag();
|
||||
if (!terminalChanged && !controllerChanged) return;
|
||||
if (controllerChanged && !terminalChanged) {
|
||||
_mouseDrag.updateController(widget.controller);
|
||||
} else {
|
||||
_discardPendingTerminalClipboardWrites();
|
||||
_mouseDrag.cancel();
|
||||
}
|
||||
_clearSelectionDrag();
|
||||
@@ -119,18 +123,46 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
}
|
||||
}
|
||||
|
||||
void _handlePointerMove(PointerMoveEvent event) {
|
||||
CellOffset? _cellAtPointer() {
|
||||
final terminalView = _terminalView;
|
||||
final pointerPosition = _pointerPosition;
|
||||
if (terminalView == null || pointerPosition == null) return null;
|
||||
final renderTerminal = terminalView.renderTerminal;
|
||||
return renderTerminal.getCellOffset(
|
||||
renderTerminal.globalToLocal(pointerPosition),
|
||||
);
|
||||
}
|
||||
|
||||
void _updatePointerPosition(PointerEvent event) =>
|
||||
_pointerPosition = event.position;
|
||||
|
||||
void _handlePointerDown(PointerDownEvent event) {
|
||||
_updatePointerPosition(event);
|
||||
if (_handlePendingTouchMove(event)) return;
|
||||
if (_mouseDrag.handleMove(
|
||||
event,
|
||||
widget.terminal,
|
||||
_terminalView,
|
||||
beforeRelease: _finishTerminalClipboardWrite,
|
||||
onCancel: _cancelTerminalClipboardWrite,
|
||||
)) {
|
||||
if (_mouseDrag.handleDown(event, widget.terminal, _terminalView)) {
|
||||
_clearSelectionDrag();
|
||||
return;
|
||||
}
|
||||
if (event.kind != PointerDeviceKind.mouse ||
|
||||
(event.buttons & kPrimaryMouseButton) != kPrimaryMouseButton) {
|
||||
return;
|
||||
}
|
||||
_clearSelectionDrag();
|
||||
final terminalView = _terminalView;
|
||||
if (terminalView == null) return;
|
||||
final renderTerminal = terminalView.renderTerminal;
|
||||
final localPosition = renderTerminal.globalToLocal(event.position);
|
||||
final selectionBuffer = widget.terminal.buffer;
|
||||
_selectionPointerId = event.pointer;
|
||||
_selectionBase = selectionBuffer.createAnchorFromOffset(
|
||||
renderTerminal.getCellOffset(localPosition),
|
||||
);
|
||||
_selectionBuffer = selectionBuffer;
|
||||
_selectionPointer = localPosition;
|
||||
}
|
||||
|
||||
void _handlePointerMove(PointerMoveEvent event) {
|
||||
_updatePointerPosition(event);
|
||||
if (_mouseDrag.handleMove(event, widget.terminal, _terminalView)) return;
|
||||
if (event.pointer != _selectionPointerId) return;
|
||||
if (event.kind != PointerDeviceKind.mouse ||
|
||||
(event.buttons & kPrimaryMouseButton) != kPrimaryMouseButton) {
|
||||
@@ -209,28 +241,8 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
|
||||
void _handlePointerEnd(PointerEvent event) {
|
||||
_updatePointerPosition(event);
|
||||
final pendingTouch = _pendingTouchMouseDown;
|
||||
if (pendingTouch != null && pendingTouch.pointer == event.pointer) {
|
||||
final movedBeyondSlop =
|
||||
(event.position - pendingTouch.position).distance > kTouchSlop;
|
||||
if (event is PointerUpEvent && !movedBeyondSlop) {
|
||||
_activatePendingTouchMouseDrag(cancelOnFailure: false);
|
||||
} else {
|
||||
_takePendingTouchMouseDrag(pointer: event.pointer);
|
||||
}
|
||||
}
|
||||
final handledByMouseDrag = _mouseDrag.handleEnd(
|
||||
event,
|
||||
widget.terminal,
|
||||
_terminalView,
|
||||
beforeRelease: event is PointerUpEvent
|
||||
? _finishTerminalClipboardWrite
|
||||
: (_) => _cancelTerminalClipboardWrite(),
|
||||
onCancel: _cancelTerminalClipboardWrite,
|
||||
);
|
||||
if (!handledByMouseDrag && event.pointer != _selectionPointerId) {
|
||||
return;
|
||||
}
|
||||
if (!_mouseDrag.handleEnd(event, widget.terminal, _terminalView) &&
|
||||
event.pointer != _selectionPointerId) return;
|
||||
if (_selectionHasScrolled) _scrollSelection(scroll: false);
|
||||
_clearSelectionDrag();
|
||||
}
|
||||
@@ -253,8 +265,6 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_discardPendingTerminalClipboardWrites();
|
||||
_cancelPendingTouchMouseDrag();
|
||||
_mouseDrag.cancel();
|
||||
_clearSelectionDrag();
|
||||
_restoreMouseHandler(widget.terminal);
|
||||
@@ -280,14 +290,10 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
|
||||
controller: widget.controller,
|
||||
scrollController: _scrollController,
|
||||
focusNode: widget.focusNode,
|
||||
autofocus: widget.autofocus,
|
||||
textStyle: widget.textStyle,
|
||||
deleteDetection: widget.deleteDetection,
|
||||
backgroundOpacity: widget.backgroundOpacity,
|
||||
padding: widget.padding,
|
||||
shortcuts: widget.shortcuts ?? platformTerminalShortcuts(),
|
||||
onKeyEvent: widget.onKeyEvent ??
|
||||
terminalCopyHandler(widget.terminal, widget.controller),
|
||||
shortcuts: platformTerminalShortcuts(),
|
||||
onKeyEvent: terminalCopyHandler(widget.terminal, widget.controller),
|
||||
onSecondaryTapDown: widget.onSecondaryTapDown,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
part of 'terminal_mouse_handler.dart';
|
||||
|
||||
/// xterm 4.0.0 encodes wheel buttons as 68..71; the extra bit reads as a Shift
|
||||
/// modifier, so strict full-screen apps ignore the report and never scroll.
|
||||
/// Upstream fix: TerminalStudio/xterm.dart#238.
|
||||
class WheelButtonFixMouseHandler implements TerminalMouseHandler {
|
||||
const WheelButtonFixMouseHandler({
|
||||
this.positionProvider,
|
||||
this.suppressLeftButton,
|
||||
});
|
||||
|
||||
final CellOffset? Function()? positionProvider;
|
||||
final bool Function(TerminalMouseButtonState)? suppressLeftButton;
|
||||
|
||||
@override
|
||||
String? call(TerminalMouseEvent event) {
|
||||
if (!event.button.isWheel) {
|
||||
if (event.button == TerminalMouseButton.left &&
|
||||
suppressLeftButton?.call(event.buttonState) == true) {
|
||||
return null;
|
||||
}
|
||||
return defaultMouseHandler(event);
|
||||
}
|
||||
// Same gate as UpDownMouseHandler: only the scroll modes report a wheel,
|
||||
// and a wheel release is never reported, so the report is always a press.
|
||||
if (!event.state.mouseMode.reportScroll ||
|
||||
event.buttonState == TerminalMouseButtonState.up) {
|
||||
return null;
|
||||
}
|
||||
return _reportWheel(event);
|
||||
}
|
||||
|
||||
String _reportWheel(TerminalMouseEvent event) {
|
||||
// Wheel buttons 4..7 go on the wire as 64..67, but `id` is 64 + 4..7.
|
||||
final button = event.button.id - 4;
|
||||
final position = positionProvider?.call() ?? event.position;
|
||||
return encodeTerminalMouseReport(
|
||||
event.state.mouseReportMode,
|
||||
button,
|
||||
position,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension _TerminalMouseInput on _TerminalMouseInteractionState {
|
||||
CellOffset? _cellAtPointer() {
|
||||
final terminalView = _terminalView;
|
||||
final pointerPosition = _pointerPosition;
|
||||
if (terminalView == null || pointerPosition == null) return null;
|
||||
final renderTerminal = terminalView.renderTerminal;
|
||||
return renderTerminal.getCellOffset(
|
||||
renderTerminal.globalToLocal(pointerPosition),
|
||||
);
|
||||
}
|
||||
|
||||
void _updatePointerPosition(PointerEvent event) =>
|
||||
_pointerPosition = event.position;
|
||||
|
||||
void _handlePointerDown(PointerDownEvent event) {
|
||||
_updatePointerPosition(event);
|
||||
_suppressXtermLeftButton = false;
|
||||
if (_startPendingTouchMouseDrag(event)) return;
|
||||
if (_mouseDrag.handleDown(event, widget.terminal, _terminalView)) {
|
||||
_prepareTerminalClipboardWrite();
|
||||
if (kIsWeb) _suppressXtermLeftButton = true;
|
||||
_clearSelectionDrag();
|
||||
return;
|
||||
}
|
||||
if (event.kind != PointerDeviceKind.mouse ||
|
||||
(event.buttons & kPrimaryMouseButton) != kPrimaryMouseButton) {
|
||||
return;
|
||||
}
|
||||
_clearSelectionDrag();
|
||||
final terminalView = _terminalView;
|
||||
if (terminalView == null) return;
|
||||
final renderTerminal = terminalView.renderTerminal;
|
||||
final localPosition = renderTerminal.globalToLocal(event.position);
|
||||
final selectionBuffer = widget.terminal.buffer;
|
||||
_selectionPointerId = event.pointer;
|
||||
_selectionBase = selectionBuffer.createAnchorFromOffset(
|
||||
renderTerminal.getCellOffset(localPosition),
|
||||
);
|
||||
_selectionBuffer = selectionBuffer;
|
||||
_selectionPointer = localPosition;
|
||||
}
|
||||
|
||||
bool _startPendingTouchMouseDrag(PointerDownEvent event) {
|
||||
if (!widget.reportTouchInput ||
|
||||
event.kind != PointerDeviceKind.touch ||
|
||||
!_mouseDrag.handleDown(
|
||||
event,
|
||||
widget.terminal,
|
||||
_terminalView,
|
||||
reportTouchInput: true,
|
||||
deferReport: true,
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
_pendingTouchMouseDown = event;
|
||||
_pendingTouchMouseTimer = Timer(
|
||||
kLongPressTimeout,
|
||||
_activatePendingTouchMouseDrag,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool _activatePendingTouchMouseDrag({
|
||||
bool cancelOnFailure = true,
|
||||
}) {
|
||||
if (_takePendingTouchMouseDrag() == null) return false;
|
||||
if (_mouseDrag.activateDeferredDown(widget.terminal)) {
|
||||
_prepareTerminalClipboardWrite();
|
||||
_clearSelectionDrag();
|
||||
return true;
|
||||
}
|
||||
if (cancelOnFailure) _mouseDrag.cancel();
|
||||
return false;
|
||||
}
|
||||
|
||||
PointerDownEvent? _takePendingTouchMouseDrag({int? pointer}) {
|
||||
final pending = _pendingTouchMouseDown;
|
||||
if (pending == null || pointer != null && pointer != pending.pointer) {
|
||||
return null;
|
||||
}
|
||||
_pendingTouchMouseTimer?.cancel();
|
||||
_pendingTouchMouseTimer = null;
|
||||
_pendingTouchMouseDown = null;
|
||||
return pending;
|
||||
}
|
||||
|
||||
void _cancelPendingTouchMouseDrag({
|
||||
int? pointer,
|
||||
bool deferCancel = false,
|
||||
}) {
|
||||
if (_takePendingTouchMouseDrag(pointer: pointer) == null) return;
|
||||
if (deferCancel) {
|
||||
scheduleMicrotask(_mouseDrag.cancel);
|
||||
} else {
|
||||
_mouseDrag.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
bool _handlePendingTouchMove(PointerMoveEvent event) {
|
||||
final pending = _pendingTouchMouseDown;
|
||||
if (pending == null || pending.pointer != event.pointer) return false;
|
||||
if ((event.position - pending.position).distance > kTouchSlop) {
|
||||
_cancelPendingTouchMouseDrag(
|
||||
pointer: event.pointer,
|
||||
deferCancel: true,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool _consumeXtermLeftButtonSuppression(TerminalMouseButtonState state) {
|
||||
final suppress = _suppressXtermLeftButton;
|
||||
if (state == TerminalMouseButtonState.up) {
|
||||
_suppressXtermLeftButton = false;
|
||||
}
|
||||
return suppress;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
part of 'terminal_mouse_handler.dart';
|
||||
|
||||
const _prepareTerminalClipboardCommand = 'prepare_terminal_clipboard';
|
||||
const _finishTerminalClipboardCommand = 'finish_terminal_clipboard';
|
||||
const _cancelTerminalClipboardCommand = 'cancel_terminal_clipboard';
|
||||
|
||||
extension _TerminalWebClipboardGesture on _TerminalMouseInteractionState {
|
||||
void _prepareTerminalClipboardWrite() {
|
||||
if (!kIsWeb) return;
|
||||
_cancelTerminalClipboardWrite();
|
||||
final terminal = widget.terminal;
|
||||
if (terminal is! RustDeskTerminal || !terminal.isClipboardWriteAllowed) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ffiSetByName(_prepareTerminalClipboardCommand);
|
||||
_terminalClipboardGesturePrepared = true;
|
||||
} catch (error) {
|
||||
debugPrint('[Terminal] Failed to prepare Web clipboard write: $error');
|
||||
}
|
||||
}
|
||||
|
||||
void _finishTerminalClipboardWrite(bool responseExpected) {
|
||||
if (!_terminalClipboardGesturePrepared) return;
|
||||
_terminalClipboardGesturePrepared = false;
|
||||
if (!kIsWeb) return;
|
||||
try {
|
||||
ffiSetByName(
|
||||
_finishTerminalClipboardCommand,
|
||||
responseExpected ? 'true' : 'false',
|
||||
);
|
||||
} catch (error) {
|
||||
debugPrint('[Terminal] Failed to finish Web clipboard write: $error');
|
||||
}
|
||||
}
|
||||
|
||||
void _cancelTerminalClipboardWrite() {
|
||||
if (!_terminalClipboardGesturePrepared) return;
|
||||
_terminalClipboardGesturePrepared = false;
|
||||
_sendTerminalClipboardCancel();
|
||||
}
|
||||
|
||||
void _discardPendingTerminalClipboardWrites() {
|
||||
_cancelTerminalClipboardWrite();
|
||||
_sendTerminalClipboardCancel();
|
||||
}
|
||||
|
||||
void _sendTerminalClipboardCancel() {
|
||||
if (!kIsWeb) return;
|
||||
try {
|
||||
ffiSetByName(_cancelTerminalClipboardCommand);
|
||||
} catch (error) {
|
||||
debugPrint('[Terminal] Failed to cancel Web clipboard write: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -189,17 +189,6 @@ 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
|
||||
@@ -262,11 +251,6 @@ class PlatformFFI {
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<T?> invokeMethodWithResult<T>(String method,
|
||||
[dynamic arguments]) async {
|
||||
return null;
|
||||
}
|
||||
|
||||
// just for compilation
|
||||
void syncAndroidServiceAppDirConfigPath() {}
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@ import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.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);
|
||||
@@ -16,21 +14,15 @@ resetSystemCursor() {}
|
||||
MouseCursor buildCursorOfCache(
|
||||
CursorModel cursor, double scale, CursorData? cache) {
|
||||
if (cache == null) {
|
||||
return _shownCursor(cursor);
|
||||
return MouseCursor.defer;
|
||||
} else {
|
||||
final key = cursor.nativeKey(cache, scale);
|
||||
final key = cache.updateGetKey(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);
|
||||
return MouseCursor.defer;
|
||||
}
|
||||
// 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})");
|
||||
// [Safety]
|
||||
@@ -40,39 +32,13 @@ MouseCursor buildCursorOfCache(
|
||||
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
|
||||
..buffer = data
|
||||
..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(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));
|
||||
}
|
||||
|
||||
@@ -26,14 +26,6 @@ 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 {
|
||||
@@ -58,60 +50,7 @@ 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");
|
||||
}
|
||||
@@ -962,11 +901,7 @@ class RustdeskImpl {
|
||||
}
|
||||
|
||||
String mainGetLocalOption({required String key, dynamic hint}) {
|
||||
final v = js.context.callMethod('getByName', ['option:local', key]);
|
||||
if (key == 'lang' && (v == 'pt' || v == 'br')) {
|
||||
return 'pt-br';
|
||||
}
|
||||
return v;
|
||||
return js.context.callMethod('getByName', ['option:local', key]);
|
||||
}
|
||||
|
||||
// Do not return the real environment variables.
|
||||
|
||||
@@ -102,15 +102,14 @@ resetSystemCursor() => CursorManager.instance.resetSystemCursor();
|
||||
MouseCursor buildCursorOfCache(
|
||||
model.CursorModel cursor, double scale, model.CursorData? cache) {
|
||||
if (cache == null) {
|
||||
return _shownCursor(cursor);
|
||||
return MouseCursor.defer;
|
||||
} else {
|
||||
final key = cursor.nativeKey(cache, scale);
|
||||
final key = cache.updateGetKey(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);
|
||||
return MouseCursor.defer;
|
||||
}
|
||||
debugPrint(
|
||||
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
|
||||
@@ -122,17 +121,7 @@ MouseCursor buildCursorOfCache(
|
||||
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);
|
||||
}
|
||||
|
||||
+12
-4
@@ -306,7 +306,7 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "."
|
||||
ref: bd6b5b41254e57c5bcece202ebfb234de63e6487
|
||||
ref: HEAD
|
||||
resolved-ref: bd6b5b41254e57c5bcece202ebfb234de63e6487
|
||||
url: "https://github.com/rustdesk-org/Dash-Chat-2"
|
||||
source: git
|
||||
@@ -339,8 +339,8 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "."
|
||||
ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
|
||||
resolved-ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
|
||||
ref: HEAD
|
||||
resolved-ref: 8b774a66671cbb9bcb2631af6ac28f9bdd469ce3
|
||||
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
|
||||
source: git
|
||||
version: "0.1.0"
|
||||
@@ -409,6 +409,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "12.0.1"
|
||||
external_path:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: external_path
|
||||
sha256: "2095c626fbbefe70d5a4afc9b1137172a68ee2c276e51c3c1283394485bea8f4"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.3"
|
||||
ffi:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -1581,7 +1589,7 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "."
|
||||
ref: cf4aef0512092fad9344a27ffe1c47ad83269dfc
|
||||
ref: HEAD
|
||||
resolved-ref: cf4aef0512092fad9344a27ffe1c47ad83269dfc
|
||||
url: "https://github.com/rustdesk-org/window_manager"
|
||||
source: git
|
||||
|
||||
@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
|
||||
# Read more about iOS versioning at
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# 1.1.9-1 works for android, but for ios it becomes 1.1.91, need to set it to 1.1.9-a.1 for iOS, will get 1.1.9.1, but iOS store not allow 4 numbers
|
||||
version: 1.5.0+68
|
||||
version: 1.4.9+67
|
||||
|
||||
environment:
|
||||
sdk: '^3.1.0'
|
||||
@@ -29,6 +29,7 @@ dependencies:
|
||||
|
||||
ffi: ^2.1.0
|
||||
path_provider: ^2.1.1
|
||||
external_path: ^1.0.3
|
||||
provider: ^6.0.5
|
||||
tuple: ^2.0.0
|
||||
wakelock_plus: ^1.1.3
|
||||
@@ -40,7 +41,6 @@ dependencies:
|
||||
dash_chat_2:
|
||||
git:
|
||||
url: https://github.com/rustdesk-org/Dash-Chat-2
|
||||
ref: bd6b5b41254e57c5bcece202ebfb234de63e6487
|
||||
draggable_float_widget: ^0.1.0
|
||||
settings_ui: ^2.0.2
|
||||
flutter_breadcrumb: ^1.0.1
|
||||
@@ -54,11 +54,9 @@ dependencies:
|
||||
window_manager:
|
||||
git:
|
||||
url: https://github.com/rustdesk-org/window_manager
|
||||
ref: cf4aef0512092fad9344a27ffe1c47ad83269dfc
|
||||
desktop_multi_window:
|
||||
git:
|
||||
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
|
||||
ref: cddc2e64f8fefce4f80db87b20bcda2dd019bed6
|
||||
freezed_annotation: ^2.0.3
|
||||
flutter_custom_cursor:
|
||||
git:
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
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,683 +0,0 @@
|
||||
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,368 +0,0 @@
|
||||
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());
|
||||
}
|
||||
@@ -342,43 +342,11 @@ void main() {
|
||||
});
|
||||
|
||||
group('shouldHandleTerminalPasteShortcut', () {
|
||||
test('handles only Ctrl+Shift+V on Linux with a virtual lock', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.linux,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: true,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: true,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.linux,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: true,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: false,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'keeps default xterm paste behavior when virtual modifiers are inactive',
|
||||
() {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
@@ -396,7 +364,6 @@ void main() {
|
||||
() {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
@@ -410,7 +377,6 @@ void main() {
|
||||
);
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.macOS,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
@@ -427,7 +393,6 @@ void main() {
|
||||
test('handles paste shortcut repeats while a virtual lock is active', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: false,
|
||||
isKeyRepeat: true,
|
||||
@@ -444,7 +409,6 @@ void main() {
|
||||
test('ignores key-up and unmodified V events', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: false,
|
||||
isKeyRepeat: false,
|
||||
@@ -458,7 +422,6 @@ void main() {
|
||||
);
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
@@ -481,7 +444,6 @@ void main() {
|
||||
]) {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
@@ -499,7 +461,6 @@ void main() {
|
||||
test('ignores non-V key events', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyC,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
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,22 +59,19 @@ constexpr UINT kForceRedrawMaxTries = 25;
|
||||
// per call (each nudge re-enters the 100ms resize wait).
|
||||
constexpr UINT kForceRedrawCheapTries = 2;
|
||||
|
||||
// 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.
|
||||
// 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.
|
||||
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, 0, height,
|
||||
SetWindowPos(child, nullptr, 0, 0, width + 1, 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,14 +104,6 @@ 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 {
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
[package]
|
||||
name = "base"
|
||||
version = "0.1.0"
|
||||
authors = ["rustdesk <info@rustdesk.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# Code that only RustDesk itself uses. `hbb_common` stays the crate shared with
|
||||
# the server, so anything the server never touches belongs here instead.
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# The isolated Wayland socket-probe fallback (src/platform/linux/wayland_probe.rs).
|
||||
# Off by default so the base Wayland enumeration is untouched; the DRM login-screen
|
||||
# build (scrap/drm) turns it on.
|
||||
wayland_probe = []
|
||||
|
||||
[dependencies]
|
||||
hbb_common = { path = "../hbb_common" }
|
||||
protobuf = { version = "3.7", features = ["with-bytes"] }
|
||||
# the generated protobuf code refers to `::bytes::Bytes` (tokio_bytes codegen)
|
||||
bytes = { version = "1.10", features = ["serde"] }
|
||||
tokio = { version = "1.44", features = ["full"] }
|
||||
serde_derive = "1.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
filetime = "0.2"
|
||||
libc = "0.2"
|
||||
backtrace = "0.3"
|
||||
log = "0.4"
|
||||
lazy_static = "1.5"
|
||||
anyhow = "1.0"
|
||||
|
||||
[build-dependencies]
|
||||
protobuf-codegen = { version = "3.7" }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Every module the moved sources name, spelled out rather than left to feature
|
||||
# unification with the root crate.
|
||||
winapi = { version = "0.3", features = [
|
||||
"fileapi",
|
||||
"handleapi",
|
||||
"minwindef",
|
||||
"pdh",
|
||||
"synchapi",
|
||||
"sysinfoapi",
|
||||
"winbase",
|
||||
"winnt",
|
||||
] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
osascript = "0.3"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
sctk = { package = "smithay-client-toolkit", version = "0.20.0", default-features = false, features = [
|
||||
"calloop",
|
||||
] }
|
||||
users = { version = "0.11" }
|
||||
@@ -1,14 +0,0 @@
|
||||
fn main() {
|
||||
let out_dir = format!("{}/protos", std::env::var("OUT_DIR").unwrap());
|
||||
|
||||
std::fs::create_dir_all(&out_dir).unwrap();
|
||||
|
||||
protobuf_codegen::Codegen::new()
|
||||
.pure()
|
||||
.out_dir(out_dir)
|
||||
.inputs(["protos/message.proto"])
|
||||
.include("protos")
|
||||
.customize(protobuf_codegen::Customize::default().tokio_bytes(true))
|
||||
.run()
|
||||
.expect("Codegen failed.");
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
extern crate base;
|
||||
#[cfg(target_os = "linux")]
|
||||
use base::platform::linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
use base::platform::macos;
|
||||
|
||||
fn main() {
|
||||
#[cfg(target_os = "linux")]
|
||||
let res = linux::system_message("test title", "test message", true);
|
||||
#[cfg(target_os = "macos")]
|
||||
let res = macos::alert(
|
||||
"System Preferences".to_owned(),
|
||||
"warning".to_owned(),
|
||||
"test title".to_owned(),
|
||||
"test message".to_owned(),
|
||||
["Ok".to_owned()].to_vec(),
|
||||
);
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
println!("result {:?}", &res);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,408 +0,0 @@
|
||||
//! Option keys shared across the app.
|
||||
//!
|
||||
//! The handful that `hbb_common` itself reads stay defined there and are
|
||||
//! re-exported here, so callers always use this one path.
|
||||
|
||||
pub use hbb_common::config::keys::*;
|
||||
|
||||
pub const OPTION_VIEW_ONLY: &str = "view_only";
|
||||
pub const OPTION_SHOW_MONITORS_TOOLBAR: &str = "show_monitors_toolbar";
|
||||
pub const OPTION_SHOW_REMOTE_CURSOR: &str = "show_remote_cursor";
|
||||
pub const OPTION_FOLLOW_REMOTE_CURSOR: &str = "follow_remote_cursor";
|
||||
pub const OPTION_FOLLOW_REMOTE_WINDOW: &str = "follow_remote_window";
|
||||
pub const OPTION_SHOW_QUALITY_MONITOR: &str = "show_quality_monitor";
|
||||
pub const OPTION_DISABLE_AUDIO: &str = "disable_audio";
|
||||
pub const OPTION_ENABLE_REMOTE_PRINTER: &str = "enable-remote-printer";
|
||||
pub const OPTION_DISABLE_CLIPBOARD: &str = "disable_clipboard";
|
||||
pub const OPTION_LOCK_AFTER_SESSION_END: &str = "lock_after_session_end";
|
||||
pub const OPTION_PRIVACY_MODE: &str = "privacy_mode";
|
||||
pub const OPTION_TOUCH_MODE: &str = "touch-mode";
|
||||
pub const OPTION_SYNC_INIT_CLIPBOARD: &str = "sync-init-clipboard";
|
||||
pub const OPTION_THEME: &str = "theme";
|
||||
pub const OPTION_REMOTE_MENUBAR_DRAG_LEFT: &str = "remote-menubar-drag-left";
|
||||
pub const OPTION_REMOTE_MENUBAR_DRAG_RIGHT: &str = "remote-menubar-drag-right";
|
||||
pub const OPTION_HIDE_AB_TAGS_PANEL: &str = "hideAbTagsPanel";
|
||||
pub const OPTION_ENABLE_CONFIRM_CLOSING_TABS: &str = "enable-confirm-closing-tabs";
|
||||
pub const OPTION_ENABLE_OPEN_NEW_CONNECTIONS_IN_TABS: &str = "enable-open-new-connections-in-tabs";
|
||||
pub const OPTION_TEXTURE_RENDER: &str = "use-texture-render";
|
||||
// Internal health record written by the texture-render watchdog/probe;
|
||||
// "failed-*" flips the texture-render default to opt-in on this machine.
|
||||
pub const OPTION_TEXTURE_RENDER_HEALTH: &str = "texture-render-health";
|
||||
pub const OPTION_ALLOW_D3D_RENDER: &str = "allow-d3d-render";
|
||||
pub const OPTION_ENABLE_CHECK_UPDATE: &str = "enable-check-update";
|
||||
pub const OPTION_ALLOW_AUTO_UPDATE: &str = "allow-auto-update";
|
||||
pub const OPTION_SYNC_AB_WITH_RECENT_SESSIONS: &str = "sync-ab-with-recent-sessions";
|
||||
pub const OPTION_SYNC_AB_TAGS: &str = "sync-ab-tags";
|
||||
pub const OPTION_FILTER_AB_BY_INTERSECTION: &str = "filter-ab-by-intersection";
|
||||
pub const OPTION_ACCESS_MODE: &str = "access-mode";
|
||||
pub const OPTION_ENABLE_KEYBOARD: &str = "enable-keyboard";
|
||||
pub const OPTION_ENABLE_CLIPBOARD: &str = "enable-clipboard";
|
||||
pub const OPTION_ENABLE_FILE_TRANSFER: &str = "enable-file-transfer";
|
||||
pub const OPTION_ENABLE_CAMERA: &str = "enable-camera";
|
||||
pub const OPTION_ENABLE_TERMINAL: &str = "enable-terminal";
|
||||
pub const OPTION_TERMINAL_PERSISTENT: &str = "terminal-persistent";
|
||||
pub const OPTION_ENABLE_AUDIO: &str = "enable-audio";
|
||||
pub const OPTION_ENABLE_TUNNEL: &str = "enable-tunnel";
|
||||
pub const OPTION_ENABLE_REMOTE_RESTART: &str = "enable-remote-restart";
|
||||
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";
|
||||
pub const OPTION_ENABLE_LAN_DISCOVERY: &str = "enable-lan-discovery";
|
||||
pub const OPTION_DIRECT_ACCESS_PORT: &str = "direct-access-port";
|
||||
pub const OPTION_WHITELIST: &str = "whitelist";
|
||||
pub const OPTION_ID_WHITELIST: &str = "id-whitelist";
|
||||
pub const OPTION_ALLOW_AUTO_DISCONNECT: &str = "allow-auto-disconnect";
|
||||
pub const OPTION_AUTO_DISCONNECT_TIMEOUT: &str = "auto-disconnect-timeout";
|
||||
pub const OPTION_ALLOW_ONLY_CONN_WINDOW_OPEN: &str = "allow-only-conn-window-open";
|
||||
pub const OPTION_ALLOW_AUTO_RECORD_INCOMING: &str = "allow-auto-record-incoming";
|
||||
pub const OPTION_ALLOW_AUTO_RECORD_OUTGOING: &str = "allow-auto-record-outgoing";
|
||||
pub const OPTION_HIDE_RECORDING_BUTTON: &str = "hide-recording-button";
|
||||
pub const OPTION_WINDOWS_SERVICE_VIDEO_SAVE_DIRECTORY: &str =
|
||||
"windows-service-video-save-directory";
|
||||
pub const OPTION_VIDEO_SAVE_DIRECTORY: &str = "video-save-directory";
|
||||
pub const OPTION_ENABLE_ABR: &str = "enable-abr";
|
||||
pub const OPTION_ALLOW_REMOVE_WALLPAPER: &str = "allow-remove-wallpaper";
|
||||
pub const OPTION_ALLOW_ALWAYS_SOFTWARE_RENDER: &str = "allow-always-software-render";
|
||||
pub const OPTION_ENABLE_HWCODEC: &str = "enable-hwcodec";
|
||||
pub const OPTION_APPROVE_MODE: &str = "approve-mode";
|
||||
pub const OPTION_VERIFICATION_METHOD: &str = "verification-method";
|
||||
pub const OPTION_TEMPORARY_PASSWORD_LENGTH: &str = "temporary-password-length";
|
||||
pub const OPTION_CUSTOM_RENDEZVOUS_SERVER: &str = "custom-rendezvous-server";
|
||||
pub const OPTION_API_SERVER: &str = "api-server";
|
||||
pub const OPTION_KEY: &str = "key";
|
||||
pub const OPTION_PRESET_ADDRESS_BOOK_NAME: &str = "preset-address-book-name";
|
||||
pub const OPTION_PRESET_ADDRESS_BOOK_TAG: &str = "preset-address-book-tag";
|
||||
pub const OPTION_PRESET_ADDRESS_BOOK_ALIAS: &str = "preset-address-book-alias";
|
||||
pub const OPTION_PRESET_ADDRESS_BOOK_PASSWORD: &str = "preset-address-book-password";
|
||||
pub const OPTION_PRESET_ADDRESS_BOOK_NOTE: &str = "preset-address-book-note";
|
||||
pub const OPTION_PRESET_DEVICE_USERNAME: &str = "preset-device-username";
|
||||
pub const OPTION_PRESET_DEVICE_NAME: &str = "preset-device-name";
|
||||
pub const OPTION_PRESET_NOTE: &str = "preset-note";
|
||||
pub const OPTION_ENABLE_DIRECTX_CAPTURE: &str = "enable-directx-capture";
|
||||
pub const OPTION_ENABLE_ANDROID_SOFTWARE_ENCODING_HALF_SCALE: &str =
|
||||
"enable-android-software-encoding-half-scale";
|
||||
pub const OPTION_ENABLE_TRUSTED_DEVICES: &str = "enable-trusted-devices";
|
||||
pub const OPTION_AV1_TEST: &str = "av1-test";
|
||||
/// Maximum number of files allowed during a single file transfer request.
|
||||
///
|
||||
/// Key: `file-transfer-max-files`.
|
||||
/// Unit: number of files (not bytes).
|
||||
///
|
||||
/// Behaviour:
|
||||
/// - If set to a positive integer N, at most N files are allowed.
|
||||
/// - If set to 0, a safe built-in default is used (see DEFAULT_MAX_VALIDATED_FILES).
|
||||
/// - If unset, negative, or non-integer, no explicit limit is enforced for backward compatibility.
|
||||
pub const OPTION_FILE_TRANSFER_MAX_FILES: &str = "file-transfer-max-files";
|
||||
pub const OPTION_DISABLE_UDP: &str = "disable-udp";
|
||||
pub const OPTION_SHOW_VIRTUAL_MOUSE: &str = "show-virtual-mouse";
|
||||
// joystick is the virtual mouse.
|
||||
// So `OPTION_SHOW_VIRTUAL_MOUSE` should also be set if `OPTION_SHOW_VIRTUAL_JOYSTICK` is set.
|
||||
pub const OPTION_SHOW_VIRTUAL_JOYSTICK: &str = "show-virtual-joystick";
|
||||
pub const OPTION_ENABLE_FLUTTER_HTTP_ON_RUST: &str = "enable-flutter-http-on-rust";
|
||||
pub const OPTION_ALLOW_ASK_FOR_NOTE: &str = "allow-ask-for-note";
|
||||
|
||||
// built-in options
|
||||
pub const OPTION_DISPLAY_NAME: &str = "display-name";
|
||||
pub const OPTION_AVATAR: &str = "avatar";
|
||||
pub const OPTION_PRESET_DEVICE_GROUP_NAME: &str = "preset-device-group-name";
|
||||
pub const OPTION_PRESET_USERNAME: &str = "preset-user-name";
|
||||
pub const OPTION_PRESET_STRATEGY_NAME: &str = "preset-strategy-name";
|
||||
pub const OPTION_REMOVE_PRESET_PASSWORD_WARNING: &str = "remove-preset-password-warning";
|
||||
pub const OPTION_HIDE_GENERAL_SETTINGS: &str = "hide-general-settings";
|
||||
pub const OPTION_HIDE_SECURITY_SETTINGS: &str = "hide-security-settings";
|
||||
pub const OPTION_HIDE_NETWORK_SETTINGS: &str = "hide-network-settings";
|
||||
pub const OPTION_HIDE_SERVER_SETTINGS: &str = "hide-server-settings";
|
||||
pub const OPTION_HIDE_PROXY_SETTINGS: &str = "hide-proxy-settings";
|
||||
pub const OPTION_HIDE_REMOTE_PRINTER_SETTINGS: &str = "hide-remote-printer-settings";
|
||||
pub const OPTION_HIDE_WEBSOCKET_SETTINGS: &str = "hide-websocket-settings";
|
||||
pub const OPTION_HIDE_STOP_SERVICE: &str = "hide-stop-service";
|
||||
pub const OPTION_ALLOW_COMMAND_LINE_SETTINGS_WHEN_SETTINGS_DISABLED: &str =
|
||||
"allow-command-line-settings-when-settings-disabled";
|
||||
|
||||
// Connection punch-through / port-forward options
|
||||
pub const OPTION_ENABLE_TCP_PUNCH: &str = "enable-tcp-punch";
|
||||
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";
|
||||
pub const OPTION_DEFAULT_CONNECT_PASSWORD: &str = "default-connect-password";
|
||||
pub const OPTION_HIDE_TRAY: &str = "hide-tray";
|
||||
pub const OPTION_ONE_WAY_CLIPBOARD_REDIRECTION: &str = "one-way-clipboard-redirection";
|
||||
pub const OPTION_ALLOW_LOGON_SCREEN_PASSWORD: &str = "allow-logon-screen-password";
|
||||
pub const OPTION_ALLOW_DEEP_LINK_PASSWORD: &str = "allow-deep-link-password";
|
||||
pub const OPTION_ALLOW_DEEP_LINK_SERVER_SETTINGS: &str = "allow-deep-link-server-settings";
|
||||
pub const OPTION_ONE_WAY_FILE_TRANSFER: &str = "one-way-file-transfer";
|
||||
pub const OPTION_ALLOW_HTTPS_21114: &str = "allow-https-21114";
|
||||
pub const OPTION_USE_RAW_TCP_FOR_API: &str = "use-raw-tcp-for-api";
|
||||
pub const OPTION_HIDE_POWERED_BY_ME: &str = "hide-powered-by-me";
|
||||
pub const OPTION_MAIN_WINDOW_ALWAYS_ON_TOP: &str = "main-window-always-on-top";
|
||||
|
||||
// flutter local options
|
||||
pub const OPTION_FLUTTER_REMOTE_MENUBAR_STATE: &str = "remoteMenubarState";
|
||||
pub const OPTION_FLUTTER_PEER_SORTING: &str = "peer-sorting";
|
||||
pub const OPTION_FLUTTER_PEER_TAB_INDEX: &str = "peer-tab-index";
|
||||
pub const OPTION_FLUTTER_PEER_TAB_ORDER: &str = "peer-tab-order";
|
||||
pub const OPTION_FLUTTER_PEER_TAB_VISIBLE: &str = "peer-tab-visible";
|
||||
pub const OPTION_FLUTTER_PEER_CARD_UI_TYLE: &str = "peer-card-ui-type";
|
||||
pub const OPTION_FLUTTER_CURRENT_AB_NAME: &str = "current-ab-name";
|
||||
pub const OPTION_ALLOW_REMOTE_CM_MODIFICATION: &str = "allow-remote-cm-modification";
|
||||
pub const OPTION_ALLOW_SYNC_CLIPBOARD_BETWEEN_SESSIONS: &str =
|
||||
"allow-sync-clipboard-between-sessions";
|
||||
|
||||
pub const OPTION_PRINTER_INCOMING_JOB_ACTION: &str = "printer-incomming-job-action";
|
||||
pub const OPTION_PRINTER_ALLOW_AUTO_PRINT: &str = "allow-printer-auto-print";
|
||||
pub const OPTION_PRINTER_SELECTED_NAME: &str = "printer-selected-name";
|
||||
|
||||
// android floating window options
|
||||
pub const OPTION_DISABLE_FLOATING_WINDOW: &str = "disable-floating-window";
|
||||
pub const OPTION_FLOATING_WINDOW_SIZE: &str = "floating-window-size";
|
||||
pub const OPTION_FLOATING_WINDOW_UNTOUCHABLE: &str = "floating-window-untouchable";
|
||||
pub const OPTION_FLOATING_WINDOW_TRANSPARENCY: &str = "floating-window-transparency";
|
||||
pub const OPTION_FLOATING_WINDOW_SVG: &str = "floating-window-svg";
|
||||
|
||||
// android keep screen on
|
||||
pub const OPTION_KEEP_SCREEN_ON: &str = "keep-screen-on";
|
||||
|
||||
// Server-side: keep host system awake during incoming sessions (Security setting)
|
||||
pub const OPTION_KEEP_AWAKE_DURING_INCOMING_SESSIONS: &str = "keep-awake-during-incoming-sessions";
|
||||
|
||||
// Client-side: keep client system awake during outgoing sessions (General setting)
|
||||
pub const OPTION_KEEP_AWAKE_DURING_OUTGOING_SESSIONS: &str = "keep-awake-during-outgoing-sessions";
|
||||
|
||||
pub const OPTION_DISABLE_GROUP_PANEL: &str = "disable-group-panel";
|
||||
pub const OPTION_DISABLE_DISCOVERY_PANEL: &str = "disable-discovery-panel";
|
||||
pub const OPTION_PRE_ELEVATE_SERVICE: &str = "pre-elevate-service";
|
||||
|
||||
// DEFAULT_DISPLAY_SETTINGS, OVERWRITE_DISPLAY_SETTINGS
|
||||
pub const KEYS_DISPLAY_SETTINGS: &[&str] = &[
|
||||
OPTION_VIEW_ONLY,
|
||||
OPTION_SHOW_MONITORS_TOOLBAR,
|
||||
OPTION_COLLAPSE_TOOLBAR,
|
||||
OPTION_SHOW_REMOTE_CURSOR,
|
||||
OPTION_FOLLOW_REMOTE_CURSOR,
|
||||
OPTION_FOLLOW_REMOTE_WINDOW,
|
||||
OPTION_ZOOM_CURSOR,
|
||||
OPTION_SHOW_QUALITY_MONITOR,
|
||||
OPTION_DISABLE_AUDIO,
|
||||
OPTION_ENABLE_FILE_COPY_PASTE,
|
||||
OPTION_DISABLE_CLIPBOARD,
|
||||
OPTION_LOCK_AFTER_SESSION_END,
|
||||
OPTION_PRIVACY_MODE,
|
||||
OPTION_TOUCH_MODE,
|
||||
OPTION_I444,
|
||||
OPTION_REVERSE_MOUSE_WHEEL,
|
||||
OPTION_SWAP_LEFT_RIGHT_MOUSE,
|
||||
OPTION_DISPLAYS_AS_INDIVIDUAL_WINDOWS,
|
||||
OPTION_USE_ALL_MY_DISPLAYS_FOR_THE_REMOTE_SESSION,
|
||||
OPTION_VIEW_STYLE,
|
||||
OPTION_TERMINAL_PERSISTENT,
|
||||
OPTION_SCROLL_STYLE,
|
||||
OPTION_EDGE_SCROLL_EDGE_THICKNESS,
|
||||
OPTION_IMAGE_QUALITY,
|
||||
OPTION_CUSTOM_IMAGE_QUALITY,
|
||||
OPTION_CUSTOM_FPS,
|
||||
OPTION_CODEC_PREFERENCE,
|
||||
OPTION_SYNC_INIT_CLIPBOARD,
|
||||
OPTION_TRACKPAD_SPEED,
|
||||
];
|
||||
// DEFAULT_LOCAL_SETTINGS, OVERWRITE_LOCAL_SETTINGS
|
||||
pub const KEYS_LOCAL_SETTINGS: &[&str] = &[
|
||||
OPTION_THEME,
|
||||
OPTION_LANGUAGE,
|
||||
OPTION_ENABLE_CONFIRM_CLOSING_TABS,
|
||||
OPTION_ENABLE_OPEN_NEW_CONNECTIONS_IN_TABS,
|
||||
OPTION_TEXTURE_RENDER,
|
||||
OPTION_ALLOW_D3D_RENDER,
|
||||
OPTION_SYNC_AB_WITH_RECENT_SESSIONS,
|
||||
OPTION_SYNC_AB_TAGS,
|
||||
OPTION_FILTER_AB_BY_INTERSECTION,
|
||||
OPTION_REMOTE_MENUBAR_DRAG_LEFT,
|
||||
OPTION_REMOTE_MENUBAR_DRAG_RIGHT,
|
||||
OPTION_HIDE_AB_TAGS_PANEL,
|
||||
OPTION_FLUTTER_REMOTE_MENUBAR_STATE,
|
||||
OPTION_FLUTTER_PEER_SORTING,
|
||||
OPTION_FLUTTER_PEER_TAB_INDEX,
|
||||
OPTION_FLUTTER_PEER_TAB_ORDER,
|
||||
OPTION_FLUTTER_PEER_TAB_VISIBLE,
|
||||
OPTION_FLUTTER_PEER_CARD_UI_TYLE,
|
||||
OPTION_FLUTTER_CURRENT_AB_NAME,
|
||||
OPTION_DISABLE_FLOATING_WINDOW,
|
||||
OPTION_FLOATING_WINDOW_SIZE,
|
||||
OPTION_FLOATING_WINDOW_UNTOUCHABLE,
|
||||
OPTION_FLOATING_WINDOW_TRANSPARENCY,
|
||||
OPTION_FLOATING_WINDOW_SVG,
|
||||
OPTION_KEEP_SCREEN_ON,
|
||||
// Client-side: keep client system awake during outgoing sessions (General setting)
|
||||
OPTION_KEEP_AWAKE_DURING_OUTGOING_SESSIONS,
|
||||
OPTION_DISABLE_GROUP_PANEL,
|
||||
OPTION_DISABLE_DISCOVERY_PANEL,
|
||||
OPTION_PRE_ELEVATE_SERVICE,
|
||||
OPTION_ALLOW_REMOTE_CM_MODIFICATION,
|
||||
OPTION_ALLOW_SYNC_CLIPBOARD_BETWEEN_SESSIONS,
|
||||
OPTION_ENABLE_CHECK_UPDATE,
|
||||
OPTION_PRINTER_INCOMING_JOB_ACTION,
|
||||
OPTION_PRINTER_ALLOW_AUTO_PRINT,
|
||||
OPTION_PRINTER_SELECTED_NAME,
|
||||
OPTION_ALLOW_AUTO_RECORD_OUTGOING,
|
||||
OPTION_HIDE_RECORDING_BUTTON,
|
||||
OPTION_VIDEO_SAVE_DIRECTORY,
|
||||
OPTION_ENABLE_TCP_PUNCH,
|
||||
OPTION_ENABLE_UDP_PUNCH,
|
||||
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,
|
||||
OPTION_ENABLE_FLUTTER_HTTP_ON_RUST,
|
||||
OPTION_ALLOW_ASK_FOR_NOTE,
|
||||
];
|
||||
// DEFAULT_SETTINGS, OVERWRITE_SETTINGS
|
||||
pub const KEYS_SETTINGS: &[&str] = &[
|
||||
OPTION_ACCESS_MODE,
|
||||
OPTION_ENABLE_KEYBOARD,
|
||||
OPTION_ENABLE_CLIPBOARD,
|
||||
OPTION_ENABLE_FILE_TRANSFER,
|
||||
OPTION_ENABLE_CAMERA,
|
||||
OPTION_ENABLE_TERMINAL,
|
||||
OPTION_ENABLE_REMOTE_PRINTER,
|
||||
OPTION_ENABLE_AUDIO,
|
||||
OPTION_ENABLE_TUNNEL,
|
||||
OPTION_ENABLE_REMOTE_RESTART,
|
||||
OPTION_ENABLE_RECORD_SESSION,
|
||||
OPTION_ENABLE_BLOCK_INPUT,
|
||||
OPTION_ENABLE_PRIVACY_MODE,
|
||||
OPTION_ALLOW_SCOPE_VIOLATION_CLOSE,
|
||||
OPTION_ALLOW_SCOPE_VIOLATION_ALARM,
|
||||
OPTION_ALLOW_REMOTE_CONFIG_MODIFICATION,
|
||||
OPTION_ALLOW_NUMERNIC_ONE_TIME_PASSWORD,
|
||||
OPTION_ENABLE_LAN_DISCOVERY,
|
||||
OPTION_DIRECT_SERVER,
|
||||
OPTION_DIRECT_ACCESS_PORT,
|
||||
OPTION_WHITELIST,
|
||||
OPTION_ID_WHITELIST,
|
||||
OPTION_ALLOW_AUTO_DISCONNECT,
|
||||
OPTION_AUTO_DISCONNECT_TIMEOUT,
|
||||
OPTION_ALLOW_ONLY_CONN_WINDOW_OPEN,
|
||||
OPTION_ALLOW_AUTO_RECORD_INCOMING,
|
||||
OPTION_WINDOWS_SERVICE_VIDEO_SAVE_DIRECTORY,
|
||||
OPTION_ENABLE_ABR,
|
||||
OPTION_ALLOW_REMOVE_WALLPAPER,
|
||||
OPTION_ALLOW_ALWAYS_SOFTWARE_RENDER,
|
||||
OPTION_ENABLE_HWCODEC,
|
||||
OPTION_APPROVE_MODE,
|
||||
OPTION_VERIFICATION_METHOD,
|
||||
OPTION_TEMPORARY_PASSWORD_LENGTH,
|
||||
OPTION_PROXY_URL,
|
||||
OPTION_PROXY_USERNAME,
|
||||
OPTION_PROXY_PASSWORD,
|
||||
OPTION_CUSTOM_RENDEZVOUS_SERVER,
|
||||
OPTION_API_SERVER,
|
||||
OPTION_KEY,
|
||||
OPTION_ALLOW_WEBSOCKET,
|
||||
OPTION_PRESET_ADDRESS_BOOK_NAME,
|
||||
OPTION_PRESET_ADDRESS_BOOK_TAG,
|
||||
OPTION_PRESET_ADDRESS_BOOK_ALIAS,
|
||||
OPTION_PRESET_ADDRESS_BOOK_PASSWORD,
|
||||
OPTION_PRESET_ADDRESS_BOOK_NOTE,
|
||||
OPTION_PRESET_DEVICE_USERNAME,
|
||||
OPTION_PRESET_DEVICE_NAME,
|
||||
OPTION_PRESET_NOTE,
|
||||
OPTION_ENABLE_DIRECTX_CAPTURE,
|
||||
OPTION_ENABLE_ANDROID_SOFTWARE_ENCODING_HALF_SCALE,
|
||||
OPTION_ENABLE_TRUSTED_DEVICES,
|
||||
OPTION_RELAY_SERVER,
|
||||
OPTION_ICE_SERVERS,
|
||||
OPTION_DISABLE_UDP,
|
||||
OPTION_ALLOW_INSECURE_TLS_FALLBACK,
|
||||
OPTION_KEEP_AWAKE_DURING_INCOMING_SESSIONS,
|
||||
OPTION_ALLOW_AUTO_UPDATE,
|
||||
OPTION_ALLOW_KCP_CC,
|
||||
OPTION_ALLOW_WEBRTC_CC,
|
||||
];
|
||||
|
||||
// BUILDIN_SETTINGS
|
||||
pub const KEYS_BUILDIN_SETTINGS: &[&str] = &[
|
||||
OPTION_DISPLAY_NAME,
|
||||
OPTION_AVATAR,
|
||||
OPTION_PRESET_DEVICE_GROUP_NAME,
|
||||
OPTION_PRESET_USERNAME,
|
||||
OPTION_PRESET_STRATEGY_NAME,
|
||||
OPTION_REMOVE_PRESET_PASSWORD_WARNING,
|
||||
OPTION_HIDE_GENERAL_SETTINGS,
|
||||
OPTION_HIDE_SECURITY_SETTINGS,
|
||||
OPTION_HIDE_NETWORK_SETTINGS,
|
||||
OPTION_HIDE_SERVER_SETTINGS,
|
||||
OPTION_HIDE_PROXY_SETTINGS,
|
||||
OPTION_HIDE_REMOTE_PRINTER_SETTINGS,
|
||||
OPTION_HIDE_WEBSOCKET_SETTINGS,
|
||||
OPTION_HIDE_STOP_SERVICE,
|
||||
OPTION_HIDE_USERNAME_ON_CARD,
|
||||
OPTION_HIDE_HELP_CARDS,
|
||||
OPTION_DEFAULT_CONNECT_PASSWORD,
|
||||
OPTION_HIDE_TRAY,
|
||||
OPTION_ONE_WAY_CLIPBOARD_REDIRECTION,
|
||||
OPTION_ALLOW_LOGON_SCREEN_PASSWORD,
|
||||
OPTION_ALLOW_DEEP_LINK_PASSWORD,
|
||||
OPTION_ALLOW_DEEP_LINK_SERVER_SETTINGS,
|
||||
OPTION_ONE_WAY_FILE_TRANSFER,
|
||||
OPTION_ALLOW_HTTPS_21114,
|
||||
OPTION_ALLOW_HOSTNAME_AS_ID,
|
||||
OPTION_REGISTER_DEVICE,
|
||||
OPTION_HIDE_POWERED_BY_ME,
|
||||
OPTION_MAIN_WINDOW_ALWAYS_ON_TOP,
|
||||
OPTION_FILE_TRANSFER_MAX_FILES,
|
||||
OPTION_DISABLE_CHANGE_PERMANENT_PASSWORD,
|
||||
OPTION_DISABLE_CHANGE_ID,
|
||||
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,
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// The glob above and the constants below share one namespace, and Rust
|
||||
/// silently prefers the explicit item over a glob import. A key defined on
|
||||
/// both sides would therefore compile, with the client and the server
|
||||
/// disagreeing about its string value and nothing to signal it. Keep the
|
||||
/// two sets apart.
|
||||
#[test]
|
||||
fn key_names_do_not_collide_with_hbb_common() {
|
||||
fn names(src: &str) -> Vec<&str> {
|
||||
src.lines()
|
||||
.filter_map(|l| l.trim().strip_prefix("pub const "))
|
||||
.filter_map(|l| l.split(':').next())
|
||||
.map(str::trim)
|
||||
.filter(|n| n.starts_with("OPTION_") || n.starts_with("KEYS_"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
let here = names(include_str!("keys.rs"));
|
||||
let there = names(include_str!("../../../hbb_common/src/config.rs"));
|
||||
assert!(
|
||||
!here.is_empty() && !there.is_empty(),
|
||||
"key parsing found nothing"
|
||||
);
|
||||
|
||||
let both: Vec<_> = here.iter().filter(|n| there.contains(n)).collect();
|
||||
assert!(
|
||||
both.is_empty(),
|
||||
"defined in both crates, so the local one shadows hbb_common's \
|
||||
with no diagnostic: {:?}",
|
||||
both
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod keys;
|
||||
-1813
File diff suppressed because it is too large
Load Diff
@@ -1,39 +0,0 @@
|
||||
use std::{fmt, slice::Iter, str::FromStr};
|
||||
|
||||
use crate::protos::message::KeyboardMode;
|
||||
|
||||
impl fmt::Display for KeyboardMode {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
KeyboardMode::Legacy => write!(f, "legacy"),
|
||||
KeyboardMode::Map => write!(f, "map"),
|
||||
KeyboardMode::Translate => write!(f, "translate"),
|
||||
KeyboardMode::Auto => write!(f, "auto"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for KeyboardMode {
|
||||
type Err = ();
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"legacy" => Ok(KeyboardMode::Legacy),
|
||||
"map" => Ok(KeyboardMode::Map),
|
||||
"translate" => Ok(KeyboardMode::Translate),
|
||||
"auto" => Ok(KeyboardMode::Auto),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyboardMode {
|
||||
pub fn iter() -> Iter<'static, KeyboardMode> {
|
||||
static KEYBOARD_MODES: [KeyboardMode; 4] = [
|
||||
KeyboardMode::Legacy,
|
||||
KeyboardMode::Map,
|
||||
KeyboardMode::Translate,
|
||||
KeyboardMode::Auto,
|
||||
];
|
||||
KEYBOARD_MODES.iter()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
pub mod config;
|
||||
pub mod fs;
|
||||
pub mod keyboard;
|
||||
pub mod platform;
|
||||
pub mod protos;
|
||||
|
||||
pub use protos::message as message_proto;
|
||||
@@ -1,618 +0,0 @@
|
||||
use hbb_common::ResultType;
|
||||
// Kept in hbb_common because `config::patch()` needs the shell lookup; re-exported
|
||||
// here so the long-standing `platform::linux::CMD_SH` paths are unchanged.
|
||||
pub use hbb_common::sh::{run_cmds_trim_newline, CMD_LOGINCTL, CMD_PS, CMD_SH};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
use users::{get_current_uid, get_user_by_uid, os::unix::UserExt};
|
||||
|
||||
use sctk::{
|
||||
output::OutputData,
|
||||
output::{OutputHandler, OutputState},
|
||||
reexports::client::protocol::wl_output::WlOutput,
|
||||
reexports::client::{globals, Proxy},
|
||||
reexports::client::{Connection, QueueHandle},
|
||||
registry::{ProvidesRegistryState, RegistryState},
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref DISTRO: Distro = Distro::new();
|
||||
}
|
||||
|
||||
pub const DISPLAY_SERVER_WAYLAND: &str = "wayland";
|
||||
pub const DISPLAY_SERVER_X11: &str = "x11";
|
||||
pub const DISPLAY_DESKTOP_KDE: &str = "KDE";
|
||||
|
||||
pub const XDG_CURRENT_DESKTOP: &str = "XDG_CURRENT_DESKTOP";
|
||||
|
||||
pub struct Distro {
|
||||
pub name: String,
|
||||
pub version_id: String,
|
||||
}
|
||||
|
||||
impl Distro {
|
||||
fn new() -> Self {
|
||||
let name = run_cmds("awk -F'=' '/^NAME=/ {print $2}' /etc/os-release")
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.trim_matches('"')
|
||||
.to_string();
|
||||
let version_id = run_cmds("awk -F'=' '/^VERSION_ID=/ {print $2}' /etc/os-release")
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.trim_matches('"')
|
||||
.to_string();
|
||||
Self { name, version_id }
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated. Use `base::platform::linux::is_kde_session()` instead for now.
|
||||
// Or we need to set the correct environment variable in the server process.
|
||||
#[inline]
|
||||
pub fn is_kde() -> bool {
|
||||
if let Ok(env) = std::env::var(XDG_CURRENT_DESKTOP) {
|
||||
env == DISPLAY_DESKTOP_KDE
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// Don't use `base::platform::linux::is_kde()` here.
|
||||
// It's not correct in the server process.
|
||||
pub fn is_kde_session() -> bool {
|
||||
std::process::Command::new(CMD_SH.as_str())
|
||||
.arg("-c")
|
||||
.arg("pgrep -f kded[0-9]+")
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.output()
|
||||
.map(|o| !o.stdout.is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_gdm_user(username: &str) -> bool {
|
||||
username == "gdm" || username == "sddm"
|
||||
// || username == "lightgdm"
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_desktop_wayland() -> bool {
|
||||
get_display_server() == DISPLAY_SERVER_WAYLAND
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_x11_or_headless() -> bool {
|
||||
!is_desktop_wayland()
|
||||
}
|
||||
|
||||
// -1
|
||||
const INVALID_SESSION: &str = "4294967295";
|
||||
|
||||
pub fn get_display_server() -> String {
|
||||
// Check for forced display server environment variable first
|
||||
if let Ok(forced_display) = std::env::var("RUSTDESK_FORCED_DISPLAY_SERVER") {
|
||||
return forced_display;
|
||||
}
|
||||
|
||||
// Check if `loginctl` can be called successfully
|
||||
if run_loginctl(None).is_err() {
|
||||
return DISPLAY_SERVER_X11.to_owned();
|
||||
}
|
||||
|
||||
let mut session = get_values_of_seat0(&[0])[0].clone();
|
||||
if session.is_empty() {
|
||||
// loginctl has not given the expected output. try something else.
|
||||
if let Ok(sid) = std::env::var("XDG_SESSION_ID") {
|
||||
// could also execute "cat /proc/self/sessionid"
|
||||
session = sid;
|
||||
}
|
||||
if session.is_empty() {
|
||||
session = run_cmds("cat /proc/self/sessionid").unwrap_or_default();
|
||||
if session == INVALID_SESSION {
|
||||
session = "".to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
if session.is_empty() {
|
||||
std::env::var("XDG_SESSION_TYPE").unwrap_or("x11".to_owned())
|
||||
} else {
|
||||
get_display_server_of_session(&session)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_display_server_of_session(session: &str) -> String {
|
||||
let mut display_server = if let Ok(output) =
|
||||
run_loginctl(Some(vec!["show-session", "-p", "Type", session]))
|
||||
// Check session type of the session
|
||||
{
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.replace("Type=", "")
|
||||
.trim_end()
|
||||
.into()
|
||||
} else {
|
||||
"".to_owned()
|
||||
};
|
||||
if display_server.is_empty() || display_server == "tty" || display_server == "unspecified" {
|
||||
if let Ok(sestype) = std::env::var("XDG_SESSION_TYPE") {
|
||||
if !sestype.is_empty() {
|
||||
return sestype.to_lowercase();
|
||||
}
|
||||
}
|
||||
display_server = "x11".to_owned();
|
||||
}
|
||||
display_server.to_lowercase()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn line_values(indices: &[usize], line: &str) -> Vec<String> {
|
||||
indices
|
||||
.into_iter()
|
||||
.map(|idx| line.split_whitespace().nth(*idx).unwrap_or("").to_owned())
|
||||
.collect::<Vec<String>>()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_values_of_seat0(indices: &[usize]) -> Vec<String> {
|
||||
_get_values_of_seat0(indices, true)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_values_of_seat0_with_gdm_wayland(indices: &[usize]) -> Vec<String> {
|
||||
_get_values_of_seat0(indices, false)
|
||||
}
|
||||
|
||||
// Ignore "3 sessions listed."
|
||||
fn ignore_loginctl_line(line: &str) -> bool {
|
||||
line.contains("sessions") || line.split(" ").count() < 4
|
||||
}
|
||||
|
||||
fn _get_values_of_seat0(indices: &[usize], ignore_gdm_wayland: bool) -> Vec<String> {
|
||||
if let Ok(output) = run_loginctl(None) {
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
if ignore_loginctl_line(line) {
|
||||
continue;
|
||||
}
|
||||
if line.contains("seat0") {
|
||||
if let Some(sid) = line.split_whitespace().next() {
|
||||
if is_active(sid) {
|
||||
if ignore_gdm_wayland {
|
||||
if is_gdm_user(line.split_whitespace().nth(2).unwrap_or(""))
|
||||
&& get_display_server_of_session(sid) == DISPLAY_SERVER_WAYLAND
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return line_values(indices, line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// some case, there is no seat0 https://github.com/rustdesk/rustdesk/issues/73
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
if ignore_loginctl_line(line) {
|
||||
continue;
|
||||
}
|
||||
if let Some(sid) = line.split_whitespace().next() {
|
||||
if is_active(sid) {
|
||||
let d = get_display_server_of_session(sid);
|
||||
if ignore_gdm_wayland {
|
||||
if is_gdm_user(line.split_whitespace().nth(2).unwrap_or(""))
|
||||
&& d == DISPLAY_SERVER_WAYLAND
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if d == "tty" || d == "unspecified" {
|
||||
continue;
|
||||
}
|
||||
return line_values(indices, line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
line_values(indices, "")
|
||||
}
|
||||
|
||||
pub fn is_active(sid: &str) -> bool {
|
||||
if let Ok(output) = run_loginctl(Some(vec!["show-session", "-p", "State", sid])) {
|
||||
String::from_utf8_lossy(&output.stdout).contains("active")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active_and_seat0(sid: &str) -> bool {
|
||||
if let Ok(output) = run_loginctl(Some(vec!["show-session", sid])) {
|
||||
String::from_utf8_lossy(&output.stdout).contains("State=active")
|
||||
&& String::from_utf8_lossy(&output.stdout).contains("Seat=seat0")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// Check both "Lock" and "Switch user"
|
||||
pub fn is_session_locked(sid: &str) -> bool {
|
||||
if let Ok(output) = run_loginctl(Some(vec!["show-session", sid, "--property=LockedHint"])) {
|
||||
String::from_utf8_lossy(&output.stdout).contains("LockedHint=yes")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// **Note** that the return value here, the last character is '\n'.
|
||||
// Use `run_cmds_trim_newline()` if you want to remove '\n' at the end.
|
||||
pub fn run_cmds(cmds: &str) -> ResultType<String> {
|
||||
let output = std::process::Command::new(CMD_SH.as_str())
|
||||
.args(vec!["-c", cmds])
|
||||
.output()?;
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
}
|
||||
|
||||
fn run_loginctl(args: Option<Vec<&str>>) -> std::io::Result<std::process::Output> {
|
||||
if std::env::var("FLATPAK_ID").is_ok() {
|
||||
let mut l_args = CMD_LOGINCTL.to_string();
|
||||
if let Some(a) = args.as_ref() {
|
||||
l_args = format!("{} {}", l_args, a.join(" "));
|
||||
}
|
||||
let res = std::process::Command::new("flatpak-spawn")
|
||||
.args(vec![String::from("--host"), l_args])
|
||||
.output();
|
||||
if res.is_ok() {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
let mut cmd = std::process::Command::new(CMD_LOGINCTL.as_str());
|
||||
if let Some(a) = args {
|
||||
return cmd.args(a).output();
|
||||
}
|
||||
cmd.output()
|
||||
}
|
||||
|
||||
/// forever: may not work
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn system_message(title: &str, msg: &str, forever: bool) -> ResultType<()> {
|
||||
let cmds: HashMap<&str, Vec<&str>> = HashMap::from([
|
||||
("notify-send", [title, msg].to_vec()),
|
||||
(
|
||||
"zenity",
|
||||
[
|
||||
"--info",
|
||||
"--timeout",
|
||||
if forever { "0" } else { "3" },
|
||||
"--title",
|
||||
title,
|
||||
"--text",
|
||||
msg,
|
||||
]
|
||||
.to_vec(),
|
||||
),
|
||||
("kdialog", ["--title", title, "--msgbox", msg].to_vec()),
|
||||
(
|
||||
"xmessage",
|
||||
[
|
||||
"-center",
|
||||
"-timeout",
|
||||
if forever { "0" } else { "3" },
|
||||
title,
|
||||
msg,
|
||||
]
|
||||
.to_vec(),
|
||||
),
|
||||
]);
|
||||
for (k, v) in cmds {
|
||||
if Command::new(k).args(v).spawn().is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
hbb_common::bail!("failed to post system message");
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde_derive::Serialize, serde_derive::Deserialize)]
|
||||
pub struct WaylandDisplayInfo {
|
||||
pub name: String,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub logical_size: Option<(i32, 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
|
||||
/// rotated output is indistinguishable from a scaled one. Flipped variants map to their
|
||||
/// rotation. Defaulted so a serialized snapshot from an older probe child still deserializes.
|
||||
#[serde(default)]
|
||||
pub transform: i32,
|
||||
}
|
||||
|
||||
/// The isolated socket-probe fallback, in its own file and behind the `wayland_probe` feature so
|
||||
/// the base Wayland path never compiles it. The DRM login-screen build turns it on.
|
||||
#[cfg(feature = "wayland_probe")]
|
||||
pub mod wayland_probe;
|
||||
#[cfg(feature = "wayland_probe")]
|
||||
pub use wayland_probe::{wayland_display_probe_child_main, WAYLAND_DISPLAY_PROBE_ARG};
|
||||
|
||||
// Retrieves information about all connected displays via the Wayland protocol.
|
||||
pub fn get_wayland_displays() -> ResultType<Vec<WaylandDisplayInfo>> {
|
||||
// Read before connecting: `connect_to_env` consumes `WAYLAND_SOCKET`. Only the probe fallback
|
||||
// needs this, so it is computed only when that feature is compiled in.
|
||||
#[cfg(feature = "wayland_probe")]
|
||||
let named_endpoint = wayland_probe::env_names_wayland_endpoint();
|
||||
match Connection::connect_to_env() {
|
||||
Ok(conn) => collect_wayland_displays(&conn),
|
||||
// Without the feature, the connect error is final, exactly as before this fallback existed.
|
||||
#[cfg(not(feature = "wayland_probe"))]
|
||||
Err(err) => Err(err.into()),
|
||||
#[cfg(feature = "wayland_probe")]
|
||||
Err(err) => wayland_probe::wayland_displays_from_runtime_dir(named_endpoint)
|
||||
.map_err(|fallback_err| anyhow::anyhow!("{err}; {fallback_err}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `wl_output::Transform` as degrees. Flipped variants report their rotation ONLY: wayland
|
||||
/// defines them as a vertical-axis mirror followed by the rotation, and the mirror half is
|
||||
/// dropped here - a consumer correcting frames by this value serves a flipped output mirrored.
|
||||
/// Said once in the log rather than silently, because no compositor of ours produces a flipped
|
||||
/// output to measure the mirror half against; carrying it must wait for a measured producer.
|
||||
fn transform_degrees(t: sctk::reexports::client::protocol::wl_output::Transform) -> i32 {
|
||||
use sctk::reexports::client::protocol::wl_output::Transform;
|
||||
match t {
|
||||
Transform::Normal => 0,
|
||||
Transform::_90 => 90,
|
||||
Transform::_180 => 180,
|
||||
Transform::_270 => 270,
|
||||
Transform::Flipped | Transform::Flipped90 | Transform::Flipped180
|
||||
| Transform::Flipped270 => {
|
||||
static FLIPPED_WARNED: std::sync::atomic::AtomicBool =
|
||||
std::sync::atomic::AtomicBool::new(false);
|
||||
if !FLIPPED_WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
log::warn!(
|
||||
"an output reports a flipped transform ({t:?}); only its rotation is \
|
||||
corrected, the mirror is not"
|
||||
);
|
||||
}
|
||||
match t {
|
||||
Transform::Flipped90 => 90,
|
||||
Transform::Flipped180 => 180,
|
||||
Transform::Flipped270 => 270,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_wayland_displays(conn: &Connection) -> ResultType<Vec<WaylandDisplayInfo>> {
|
||||
struct WaylandEnv {
|
||||
registry_state: RegistryState,
|
||||
output_state: OutputState,
|
||||
}
|
||||
|
||||
impl OutputHandler for WaylandEnv {
|
||||
fn output_state(&mut self) -> &mut OutputState {
|
||||
&mut self.output_state
|
||||
}
|
||||
|
||||
fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: WlOutput) {}
|
||||
fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: WlOutput) {}
|
||||
fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: WlOutput) {}
|
||||
}
|
||||
|
||||
impl ProvidesRegistryState for WaylandEnv {
|
||||
fn registry(&mut self) -> &mut RegistryState {
|
||||
&mut self.registry_state
|
||||
}
|
||||
|
||||
sctk::registry_handlers![OutputState];
|
||||
}
|
||||
|
||||
sctk::delegate_output!(WaylandEnv);
|
||||
sctk::delegate_registry!(WaylandEnv);
|
||||
|
||||
let (globals, mut event_queue) = globals::registry_queue_init(conn)?;
|
||||
let queue_handle = event_queue.handle();
|
||||
|
||||
let registry_state = RegistryState::new(&globals);
|
||||
let output_state = OutputState::new(&globals, &queue_handle);
|
||||
|
||||
let mut environment = WaylandEnv {
|
||||
registry_state,
|
||||
output_state,
|
||||
};
|
||||
|
||||
event_queue.roundtrip(&mut environment)?;
|
||||
|
||||
let outputs: Vec<_> = environment.output_state.outputs().collect();
|
||||
let mut display_infos = Vec::new();
|
||||
|
||||
for output in outputs {
|
||||
if let Some(output_data) = output.data::<OutputData>() {
|
||||
output_data.with_output_info(|info| {
|
||||
if let Some(mode) = info.modes.iter().find(|m| m.current) {
|
||||
// wlroots compositors leave wl_output.geometry at (0, 0) for every output and
|
||||
// publish the real layout only through xdg-output, so taking `location` there
|
||||
// stacks the whole desktop on the origin. Mutter fills both, so this stays a
|
||||
// no-op on GNOME.
|
||||
let (x, y) = info.logical_position.unwrap_or(info.location);
|
||||
let (width, height) = mode.dimensions;
|
||||
let refresh_rate = mode.refresh_rate;
|
||||
let name = info.name.clone().unwrap_or_default();
|
||||
let logical_size = info.logical_size;
|
||||
let transform = transform_degrees(info.transform);
|
||||
display_infos.push(WaylandDisplayInfo {
|
||||
name,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
logical_size,
|
||||
refresh_rate,
|
||||
transform,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(display_infos)
|
||||
}
|
||||
|
||||
/// Escape a string for safe use in shell commands by wrapping in single quotes.
|
||||
///
|
||||
/// This function handles the edge case of single quotes within the string by:
|
||||
/// 1. Ending the current single-quoted section
|
||||
/// 2. Adding an escaped single quote
|
||||
/// 3. Starting a new single-quoted section
|
||||
///
|
||||
/// Example: "it's here" -> "'it'\''s here'"
|
||||
#[inline]
|
||||
pub fn shell_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace("'", "'\\''"))
|
||||
}
|
||||
|
||||
/// Get the current user's home directory via getpwuid (trusted source).
|
||||
///
|
||||
/// This function uses the system's password database (via `getpwuid`) to retrieve
|
||||
/// the home directory, avoiding the security risk of relying on the `HOME`
|
||||
/// environment variable which can be manipulated by untrusted input.
|
||||
///
|
||||
/// # Returns
|
||||
/// - `Some(PathBuf)` if the home directory was found and exists
|
||||
/// - `None` if the user lookup failed or the directory doesn't exist
|
||||
///
|
||||
/// # Security
|
||||
/// This function is designed to be safe against confused-deputy attacks where
|
||||
/// an attacker might manipulate environment variables to influence privileged
|
||||
/// operations.
|
||||
pub fn get_home_dir_trusted() -> Option<PathBuf> {
|
||||
let uid = get_current_uid();
|
||||
match get_user_by_uid(uid) {
|
||||
Some(user) => {
|
||||
let home = user.home_dir();
|
||||
if Path::is_dir(home) {
|
||||
Some(PathBuf::from(home))
|
||||
} else {
|
||||
log::warn!(
|
||||
"Home directory for uid {} does not exist or is not a directory: {:?}",
|
||||
uid,
|
||||
home
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
None => {
|
||||
log::warn!("Failed to get user info for uid {}", uid);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_transform_degrees_maps_all_eight_variants() {
|
||||
use sctk::reexports::client::protocol::wl_output::Transform;
|
||||
// Flipped variants report their rotation: the frame still needs that turn to read
|
||||
// upright, and the mirror half has no producer among desktop compositors to test.
|
||||
for (t, deg) in [
|
||||
(Transform::Normal, 0),
|
||||
(Transform::_90, 90),
|
||||
(Transform::_180, 180),
|
||||
(Transform::_270, 270),
|
||||
(Transform::Flipped, 0),
|
||||
(Transform::Flipped90, 90),
|
||||
(Transform::Flipped180, 180),
|
||||
(Transform::Flipped270, 270),
|
||||
] {
|
||||
assert_eq!(transform_degrees(t), deg, "{t:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_display_info_without_transform_defaults_to_zero() {
|
||||
// A snapshot serialized by an older probe child carries no transform field; it must
|
||||
// deserialize with 0 rather than fail, or a greeter-side child update becomes a
|
||||
// lockstep upgrade.
|
||||
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);
|
||||
let roundtrip: WaylandDisplayInfo =
|
||||
serde_json::from_str(&serde_json::to_string(&info).unwrap()).unwrap();
|
||||
assert_eq!(roundtrip.transform, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_cmds_trim_newline() {
|
||||
assert_eq!(run_cmds_trim_newline("echo -n 123").unwrap(), "123");
|
||||
assert_eq!(run_cmds_trim_newline("echo 123").unwrap(), "123");
|
||||
assert_eq!(
|
||||
run_cmds_trim_newline("whoami").unwrap() + "\n",
|
||||
run_cmds("whoami").unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
/// Test get_home_dir_trusted: returns valid path and ignores HOME env var
|
||||
#[test]
|
||||
fn test_get_home_dir_trusted() {
|
||||
let original_home = std::env::var("HOME").ok();
|
||||
|
||||
// Set HOME to a fake/malicious path
|
||||
std::env::set_var("HOME", "/tmp/fake_malicious_home");
|
||||
let result = get_home_dir_trusted();
|
||||
|
||||
// Restore original HOME
|
||||
match original_home {
|
||||
Some(home) => std::env::set_var("HOME", home),
|
||||
None => std::env::remove_var("HOME"),
|
||||
}
|
||||
|
||||
// Verify: returns valid path that is NOT the fake HOME
|
||||
if let Some(path) = result {
|
||||
assert!(path.is_absolute(), "Path should be absolute: {:?}", path);
|
||||
assert!(path.is_dir(), "Path should be a directory: {:?}", path);
|
||||
assert_ne!(
|
||||
path.to_string_lossy(),
|
||||
"/tmp/fake_malicious_home",
|
||||
"Should not use HOME env var"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Test shell_quote with normal strings
|
||||
#[test]
|
||||
fn test_shell_quote_normal() {
|
||||
assert_eq!(shell_quote("hello"), "'hello'");
|
||||
assert_eq!(shell_quote("/home/user"), "'/home/user'");
|
||||
}
|
||||
|
||||
/// Test shell_quote with spaces
|
||||
#[test]
|
||||
fn test_shell_quote_spaces() {
|
||||
assert_eq!(shell_quote("/home/my user/file"), "'/home/my user/file'");
|
||||
assert_eq!(shell_quote("path with spaces"), "'path with spaces'");
|
||||
}
|
||||
|
||||
/// Test shell_quote with single quotes (the tricky case)
|
||||
#[test]
|
||||
fn test_shell_quote_single_quotes() {
|
||||
assert_eq!(shell_quote("it's"), "'it'\\''s'");
|
||||
assert_eq!(shell_quote("don't stop"), "'don'\\''t stop'");
|
||||
}
|
||||
|
||||
/// Test shell_quote with shell metacharacters
|
||||
#[test]
|
||||
fn test_shell_quote_metacharacters() {
|
||||
// These should all be safely quoted
|
||||
assert_eq!(shell_quote("test;rm -rf /"), "'test;rm -rf /'");
|
||||
assert_eq!(shell_quote("$(whoami)"), "'$(whoami)'");
|
||||
assert_eq!(shell_quote("`id`"), "'`id`'");
|
||||
assert_eq!(shell_quote("a && b"), "'a && b'");
|
||||
assert_eq!(shell_quote("a | b"), "'a | b'");
|
||||
}
|
||||
}
|
||||
@@ -1,349 +0,0 @@
|
||||
//! Isolated Wayland display probe: enumerates a compositor over a runtime-directory socket when
|
||||
//! the environment names no endpoint (a greeter's `--server` and the root service are given no
|
||||
//! compositor variables). Gated behind the `wayland_probe` feature so the base Wayland path is
|
||||
//! untouched — a consumer that does not build the DRM login-screen backend never compiles this,
|
||||
//! and `get_wayland_displays` keeps its original behavior of returning the connect error.
|
||||
|
||||
use super::{collect_wayland_displays, get_values_of_seat0_with_gdm_wayland, WaylandDisplayInfo};
|
||||
use hbb_common::{bail, ResultType};
|
||||
use sctk::reexports::client::Connection;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const RUNTIME_DIR_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// The argument the consumer binary must dispatch to `wayland_display_probe_child_main` before
|
||||
/// any other startup work; see that function for why the probe is its own process.
|
||||
pub const WAYLAND_DISPLAY_PROBE_ARG: &str = "--wayland-display-probe";
|
||||
|
||||
/// First stdout line of a probe child. A binary that does not dispatch the arg never prints it.
|
||||
const WAYLAND_PROBE_MAGIC: &str = "wayland-display-probe-v1";
|
||||
|
||||
/// Latched on a failed handshake: a consumer that does not dispatch the probe arg runs its NORMAL
|
||||
/// startup instead, and this path re-enters every enumeration cycle.
|
||||
static PROBE_UNSUPPORTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
static RUNTIME_DIR_PROBE_BUSY: std::sync::atomic::AtomicBool =
|
||||
std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// Clears the in-flight flag on every exit path of the parent, error arms included.
|
||||
struct ProbeBusyGuard;
|
||||
|
||||
impl Drop for ProbeBusyGuard {
|
||||
fn drop(&mut self) {
|
||||
RUNTIME_DIR_PROBE_BUSY.store(false, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point of the isolated probe process. The consumer binary dispatches
|
||||
/// `WAYLAND_DISPLAY_PROBE_ARG` here first, before config, logging or any other startup work.
|
||||
///
|
||||
/// Its own process because the release profile builds with panic=abort: sctk panics on malformed
|
||||
/// protocol bytes, and in-process that abort takes the whole server down. Here it takes down only
|
||||
/// this child, which the parent reports as a failed probe. The seat0 lookup also runs in here, so
|
||||
/// the parent's single deadline bounds the loginctl reads too.
|
||||
pub fn wayland_display_probe_child_main() -> ! {
|
||||
use std::io::Write;
|
||||
// The handshake first, so the parent can tell this entry point ran and not a consumer binary
|
||||
// that fell through to its normal startup.
|
||||
println!("{WAYLAND_PROBE_MAGIC}");
|
||||
let _ = std::io::stdout().flush();
|
||||
let code = match seat0_runtime_dir()
|
||||
.and_then(|dir| {
|
||||
drop_to_dir_owner(&dir)?;
|
||||
probe_runtime_dir(&dir)
|
||||
})
|
||||
.and_then(|displays| serde_json::to_string(&displays).map_err(anyhow::Error::from))
|
||||
{
|
||||
Ok(json) => {
|
||||
println!("{json}");
|
||||
0
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("{err:#}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let _ = std::io::stdout().flush();
|
||||
std::process::exit(code)
|
||||
}
|
||||
|
||||
static ENDPOINT_WAS_NAMED: std::sync::atomic::AtomicBool =
|
||||
std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// Whether the environment ever named a wayland endpoint in this process. Empty is not a name.
|
||||
///
|
||||
/// Read before `connect_to_env`, which removes `WAYLAND_SOCKET` from the environment on both its
|
||||
/// success and its bad-fd path; and latched, so a consumed variable cannot turn a process that WAS
|
||||
/// pointed at a compositor into one that is free to go looking for another.
|
||||
pub(super) fn env_names_wayland_endpoint() -> bool {
|
||||
use std::sync::atomic::Ordering;
|
||||
let named = ["WAYLAND_DISPLAY", "WAYLAND_SOCKET"]
|
||||
.iter()
|
||||
.any(|key| std::env::var_os(key).is_some_and(|value| !value.is_empty()));
|
||||
if named {
|
||||
ENDPOINT_WAS_NAMED.store(true, Ordering::Release);
|
||||
}
|
||||
ENDPOINT_WAS_NAMED.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// The probe parses compositor-controlled protocol data; a root service must not do that as
|
||||
/// root. Before touching the socket, become the runtime directory's owner — and refuse to probe
|
||||
/// at all if the drop fails, since staying root is the one unacceptable outcome.
|
||||
fn drop_to_dir_owner(dir: &Path) -> ResultType<()> {
|
||||
if unsafe { libc::geteuid() } != 0 {
|
||||
return Ok(());
|
||||
}
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let meta = std::fs::metadata(dir)?;
|
||||
let (uid, gid) = (meta.uid(), meta.gid());
|
||||
if uid == 0 {
|
||||
// Root's own session: there is no boundary to cross and nothing to drop to.
|
||||
return Ok(());
|
||||
}
|
||||
unsafe {
|
||||
if libc::setgroups(0, std::ptr::null()) != 0
|
||||
|| libc::setgid(gid) != 0
|
||||
|| libc::setuid(uid) != 0
|
||||
|| libc::setuid(0) == 0
|
||||
{
|
||||
bail!("could not drop privileges for the socket probe");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `/run/user/<uid>` of the active seat0 session, a greeter included.
|
||||
///
|
||||
/// Derived from the uid rather than read from `XDG_RUNTIME_DIR`: the root service is given no such
|
||||
/// variable, and `get_home_dir_trusted` refuses to trust the environment for the same reason.
|
||||
fn seat0_runtime_dir() -> ResultType<PathBuf> {
|
||||
let uid = get_values_of_seat0_with_gdm_wayland(&[1]).remove(0);
|
||||
if uid.is_empty() || !uid.bytes().all(|b| b.is_ascii_digit()) {
|
||||
bail!("no active seat0 session to take a runtime directory from");
|
||||
}
|
||||
Ok(PathBuf::from(format!("/run/user/{uid}")))
|
||||
}
|
||||
|
||||
/// The wayland sockets present in `dir`, lowest display number first.
|
||||
///
|
||||
/// Scanned rather than guessed: `wl_display_add_socket_auto` takes the first FREE name up to
|
||||
/// `wayland-32`, and a greeter is where leftovers accumulate across compositor restarts. Only that
|
||||
/// name pattern, because the same directory holds pipewire and dbus sockets.
|
||||
fn wayland_sockets_in(dir: &Path) -> Vec<PathBuf> {
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
let mut paths: Vec<PathBuf> = match std::fs::read_dir(dir) {
|
||||
Ok(entries) => entries
|
||||
.flatten()
|
||||
.filter(|entry| {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
name.starts_with("wayland-")
|
||||
&& !name.ends_with(".lock")
|
||||
&& entry.file_type().map(|t| t.is_socket()).unwrap_or(false)
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
paths.sort_by_key(|path| {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.and_then(|name| name.strip_prefix("wayland-"))
|
||||
.and_then(|number| number.parse::<u32>().ok())
|
||||
.unwrap_or(u32::MAX)
|
||||
});
|
||||
paths
|
||||
}
|
||||
|
||||
/// Enumerate through a socket in the seat0 runtime directory, for the case where nothing named an
|
||||
/// endpoint: a greeter's `--server` and the root service are given no compositor variables, so
|
||||
/// nothing tells the enumerator where a compositor that IS running lives. An endpoint that WAS
|
||||
/// named and failed must not silently reattach to a different compositor.
|
||||
///
|
||||
/// In a subprocess and bounded, because the caller holds a process-wide lock across the call while
|
||||
/// `connect(2)` parks on a full backlog and sctk's roundtrip polls without a deadline; and because
|
||||
/// sctk panics on malformed output events, which the release profile's panic=abort turns into an
|
||||
/// abort of the whole server. A child dies alone, and on the deadline it is killed instead of
|
||||
/// leaking a thread. The seat0 lookup runs inside the child, under the same deadline.
|
||||
pub(super) fn wayland_displays_from_runtime_dir(
|
||||
named_endpoint: bool,
|
||||
) -> ResultType<Vec<WaylandDisplayInfo>> {
|
||||
use std::sync::atomic::Ordering;
|
||||
if named_endpoint {
|
||||
bail!("an explicit wayland endpoint is set and did not connect");
|
||||
}
|
||||
if PROBE_UNSUPPORTED.load(Ordering::Acquire) {
|
||||
bail!("this binary does not dispatch {WAYLAND_DISPLAY_PROBE_ARG}");
|
||||
}
|
||||
if RUNTIME_DIR_PROBE_BUSY.swap(true, Ordering::AcqRel) {
|
||||
bail!("an earlier probe has not returned");
|
||||
}
|
||||
let _busy = ProbeBusyGuard;
|
||||
let exe = std::env::current_exe()?;
|
||||
// Its own process group, so the deadline can kill loginctl descendants along with the child,
|
||||
// and so no surviving descendant can hold the pipes open past the reads below.
|
||||
use std::os::unix::process::CommandExt;
|
||||
let mut child = std::process::Command::new(exe)
|
||||
.arg(WAYLAND_DISPLAY_PROBE_ARG)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.process_group(0)
|
||||
.spawn()?;
|
||||
let probe_pgid = child.id() as libc::pid_t;
|
||||
let kill_probe_group = || unsafe {
|
||||
let _ = libc::kill(-probe_pgid, libc::SIGKILL);
|
||||
};
|
||||
let deadline = std::time::Instant::now() + RUNTIME_DIR_PROBE_TIMEOUT;
|
||||
let status = loop {
|
||||
match child.try_wait()? {
|
||||
Some(status) => {
|
||||
kill_probe_group();
|
||||
break status;
|
||||
}
|
||||
None if std::time::Instant::now() >= deadline => {
|
||||
kill_probe_group();
|
||||
// The direct pid too, not only its group: if the child left the group its own
|
||||
// kill would miss it, and the wait below would then block on a live child. A
|
||||
// pid-targeted SIGKILL is uncatchable, so wait() is bounded either way.
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
// An unwired binary runs its normal startup, and a long-running one (the
|
||||
// server itself) lands HERE rather than at the handshake check below — latch
|
||||
// on this path too, or every enumeration cycle spawns a full consumer
|
||||
// process. Judged by what the child already wrote: a real probe prints the
|
||||
// magic line first and flushes, so its absence after a whole deadline means
|
||||
// this is not a probe. Only buffered bytes are read — a blocking read could
|
||||
// hang on a grandchild that inherited the write end.
|
||||
match first_buffered_line(child.stdout.take()) {
|
||||
// The pipe could not be inspected at all: no evidence, no latch.
|
||||
None => {
|
||||
bail!("the wayland socket probe timed out and its output was uninspectable")
|
||||
}
|
||||
Some(head) if head.as_deref() == Some(WAYLAND_PROBE_MAGIC) => {
|
||||
bail!("the wayland socket probe did not answer and was killed");
|
||||
}
|
||||
Some(_) => {
|
||||
PROBE_UNSUPPORTED.store(true, Ordering::Release);
|
||||
bail!("the wayland socket probe timed out without the handshake; probe disabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
None => std::thread::sleep(std::time::Duration::from_millis(25)),
|
||||
}
|
||||
};
|
||||
// Drained non-blocking, not read_to_string: the child exited so its output is already
|
||||
// buffered, but a descendant that escaped the process group could still hold a write end open
|
||||
// and an EOF-seeking read would then hang here forever.
|
||||
let stdout = drain_nonblocking(child.stdout.take()).unwrap_or_default();
|
||||
let stderr = drain_nonblocking(child.stderr.take()).unwrap_or_default();
|
||||
let mut lines = stdout.lines();
|
||||
if lines.next() != Some(WAYLAND_PROBE_MAGIC) {
|
||||
// Not a probe: the binary ran its normal startup. Latch, or this path would spawn one
|
||||
// full consumer process per enumeration cycle.
|
||||
PROBE_UNSUPPORTED.store(true, Ordering::Release);
|
||||
bail!("this binary does not dispatch {WAYLAND_DISPLAY_PROBE_ARG}; probe disabled");
|
||||
}
|
||||
if !status.success() {
|
||||
let detail = stderr.trim();
|
||||
if detail.is_empty() {
|
||||
// panic=abort or a signal leaves stderr empty; the status is then the only cause.
|
||||
bail!("wayland socket probe failed: {status}");
|
||||
}
|
||||
bail!("wayland socket probe failed ({status}): {detail}");
|
||||
}
|
||||
let displays: Vec<WaylandDisplayInfo> =
|
||||
match serde_json::from_str(lines.next().unwrap_or_default()) {
|
||||
Ok(displays) => displays,
|
||||
Err(err) => bail!("wayland socket probe answered a malformed list: {err}"),
|
||||
};
|
||||
// The child already refuses an empty list; refuse it here too, so a truncated pipe cannot
|
||||
// become a cached-for-life empty enumeration.
|
||||
if displays.is_empty() {
|
||||
bail!("wayland socket probe returned no outputs");
|
||||
}
|
||||
log::debug!(
|
||||
"wayland: {} output(s) via the probe subprocess",
|
||||
displays.len()
|
||||
);
|
||||
Ok(displays)
|
||||
}
|
||||
|
||||
/// Everything already buffered in the pipe, read strictly non-blocking and capped: a descendant
|
||||
/// that escaped the probe's process group can hold a write end open, so a blocking read (even
|
||||
/// after the child exits) could hang the enumeration forever. `None` means the pipe could not be
|
||||
/// INSPECTED (missing handle or fcntl failure) and must not be read as evidence of anything;
|
||||
/// `Some` is whatever bytes were buffered, whether or not EOF arrived.
|
||||
fn drain_nonblocking<R: std::io::Read + std::os::fd::AsRawFd>(pipe: Option<R>) -> Option<String> {
|
||||
let mut pipe = pipe?;
|
||||
let fd = pipe.as_raw_fd();
|
||||
unsafe {
|
||||
let flags = libc::fcntl(fd, libc::F_GETFL);
|
||||
if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// Capped so a descendant that keeps writing cannot spin this read forever.
|
||||
const CAP: usize = 64 * 1024;
|
||||
let mut out = Vec::new();
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) => break, // EOF: the write end is fully closed
|
||||
Ok(n) => {
|
||||
out.extend_from_slice(&buf[..n]);
|
||||
if out.len() >= CAP {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
// WouldBlock: what is buffered is drained (a descendant may still hold the writer).
|
||||
// Any other error: stop with what we have.
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Some(String::from_utf8_lossy(&out).into_owned())
|
||||
}
|
||||
|
||||
/// The first line the child buffered, for the timeout latch decision. `Some(None)` is an
|
||||
/// inspected-but-empty buffer (genuine absence of the handshake); outer `None` is uninspectable.
|
||||
fn first_buffered_line(pipe: Option<std::process::ChildStdout>) -> Option<Option<String>> {
|
||||
drain_nonblocking(pipe).map(|s| s.lines().next().map(str::to_owned))
|
||||
}
|
||||
|
||||
fn probe_runtime_dir(dir: &Path) -> ResultType<Vec<WaylandDisplayInfo>> {
|
||||
use std::os::unix::net::UnixStream;
|
||||
let mut errs = Vec::new();
|
||||
for path in wayland_sockets_in(dir) {
|
||||
match UnixStream::connect(&path)
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|s| Connection::from_socket(s).map_err(anyhow::Error::from))
|
||||
.and_then(|conn| collect_wayland_displays(&conn))
|
||||
{
|
||||
// The caller caches an empty list as ground truth for the process lifetime, and a
|
||||
// compositor still probing its monitors is exactly what this path connects to.
|
||||
Ok(displays) if displays.is_empty() => {
|
||||
errs.push(format!("{}: no outputs yet", path.display()))
|
||||
}
|
||||
Ok(displays) => {
|
||||
// Which socket answered, when nothing in the environment named one.
|
||||
log::debug!(
|
||||
"wayland: {} output(s) from {}, found by scanning",
|
||||
displays.len(),
|
||||
path.display()
|
||||
);
|
||||
return Ok(displays);
|
||||
}
|
||||
Err(err) => errs.push(format!("{}: {err}", path.display())),
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"no usable wayland socket in {} ({})",
|
||||
dir.display(),
|
||||
if errs.is_empty() {
|
||||
"none present".to_owned()
|
||||
} else {
|
||||
errs.join("; ")
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
use hbb_common::ResultType;
|
||||
use osascript;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AlertParams {
|
||||
title: String,
|
||||
message: String,
|
||||
alert_type: String,
|
||||
buttons: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AlertResult {
|
||||
#[serde(rename = "buttonReturned")]
|
||||
button: String,
|
||||
}
|
||||
|
||||
/// Firstly run the specified app, then alert a dialog. Return the clicked button value.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `app` - The app to execute the script.
|
||||
/// * `alert_type` - Alert type. . informational, warning, critical
|
||||
/// * `title` - The alert title.
|
||||
/// * `message` - The alert message.
|
||||
/// * `buttons` - The buttons to show.
|
||||
pub fn alert(
|
||||
app: String,
|
||||
alert_type: String,
|
||||
title: String,
|
||||
message: String,
|
||||
buttons: Vec<String>,
|
||||
) -> ResultType<String> {
|
||||
let script = osascript::JavaScript::new(&format!(
|
||||
"
|
||||
var App = Application('{}');
|
||||
App.includeStandardAdditions = true;
|
||||
return App.displayAlert($params.title, {{
|
||||
message: $params.message,
|
||||
'as': $params.alert_type,
|
||||
buttons: $params.buttons,
|
||||
}});
|
||||
",
|
||||
app
|
||||
));
|
||||
|
||||
let result: AlertResult = script.execute_with_params(AlertParams {
|
||||
title,
|
||||
message,
|
||||
alert_type,
|
||||
buttons,
|
||||
})?;
|
||||
Ok(result.button)
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod linux;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod macos;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub mod windows;
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
use hbb_common::{config::Config, log};
|
||||
#[cfg(not(debug_assertions))]
|
||||
use std::process::exit;
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
static mut GLOBAL_CALLBACK: Option<Box<dyn Fn()>> = None;
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
extern "C" fn breakdown_signal_handler(sig: i32) {
|
||||
let mut stack = vec![];
|
||||
backtrace::trace(|frame| {
|
||||
backtrace::resolve_frame(frame, |symbol| {
|
||||
if let Some(name) = symbol.name() {
|
||||
stack.push(name.to_string());
|
||||
}
|
||||
});
|
||||
true // keep going to the next frame
|
||||
});
|
||||
let mut info = String::default();
|
||||
if stack.iter().any(|s| {
|
||||
s.contains(&"nouveau_pushbuf_kick")
|
||||
|| s.to_lowercase().contains("nvidia")
|
||||
|| s.contains("gdk_window_end_draw_frame")
|
||||
|| s.contains("glGetString")
|
||||
}) {
|
||||
Config::set_option("allow-always-software-render".to_string(), "Y".to_string());
|
||||
info = "Always use software rendering will be set.".to_string();
|
||||
log::info!("{}", info);
|
||||
}
|
||||
if stack.iter().any(|s| {
|
||||
s.to_lowercase().contains("nvidia")
|
||||
|| s.to_lowercase().contains("amf")
|
||||
|| s.to_lowercase().contains("mfx")
|
||||
|| s.contains("cuProfilerStop")
|
||||
}) {
|
||||
Config::set_option("enable-hwcodec".to_string(), "N".to_string());
|
||||
info = "Perhaps hwcodec causing the crash, disable it first".to_string();
|
||||
log::info!("{}", info);
|
||||
}
|
||||
log::error!(
|
||||
"Got signal {} and exit. stack:\n{}",
|
||||
sig,
|
||||
stack.join("\n").to_string()
|
||||
);
|
||||
if !info.is_empty() {
|
||||
#[cfg(target_os = "linux")]
|
||||
linux::system_message(
|
||||
"RustDesk",
|
||||
&format!("Got signal {} and exit.{}", sig, info),
|
||||
true,
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
unsafe {
|
||||
#[allow(static_mut_refs)]
|
||||
if let Some(callback) = &GLOBAL_CALLBACK {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub fn register_breakdown_handler<T>(callback: T)
|
||||
where
|
||||
T: Fn() + 'static,
|
||||
{
|
||||
unsafe {
|
||||
GLOBAL_CALLBACK = Some(Box::new(callback));
|
||||
libc::signal(libc::SIGSEGV, breakdown_signal_handler as _);
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
sync::{Arc, Mutex},
|
||||
time::Instant,
|
||||
};
|
||||
use winapi::{
|
||||
shared::minwindef::{DWORD, FALSE, TRUE},
|
||||
um::{
|
||||
handleapi::CloseHandle,
|
||||
pdh::{
|
||||
PdhAddEnglishCounterA, PdhCloseQuery, PdhCollectQueryData, PdhCollectQueryDataEx,
|
||||
PdhGetFormattedCounterValue, PdhOpenQueryA, PDH_FMT_COUNTERVALUE, PDH_FMT_DOUBLE,
|
||||
PDH_HCOUNTER, PDH_HQUERY,
|
||||
},
|
||||
synchapi::{CreateEventA, WaitForSingleObject},
|
||||
sysinfoapi::VerSetConditionMask,
|
||||
winbase::{VerifyVersionInfoW, INFINITE, WAIT_OBJECT_0},
|
||||
winnt::{
|
||||
HANDLE, OSVERSIONINFOEXW, VER_BUILDNUMBER, VER_GREATER_EQUAL, VER_MAJORVERSION,
|
||||
VER_MINORVERSION, VER_SERVICEPACKMAJOR, VER_SERVICEPACKMINOR,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref CPU_USAGE_ONE_MINUTE: Arc<Mutex<Option<(f64, Instant)>>> = Arc::new(Mutex::new(None));
|
||||
}
|
||||
|
||||
// https://github.com/mgostIH/process_list/blob/master/src/windows/mod.rs
|
||||
#[repr(transparent)]
|
||||
pub struct RAIIHandle(pub HANDLE);
|
||||
|
||||
impl Drop for RAIIHandle {
|
||||
fn drop(&mut self) {
|
||||
// This never gives problem except when running under a debugger.
|
||||
unsafe { CloseHandle(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
pub(self) struct RAIIPDHQuery(pub PDH_HQUERY);
|
||||
|
||||
impl Drop for RAIIPDHQuery {
|
||||
fn drop(&mut self) {
|
||||
unsafe { PdhCloseQuery(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_cpu_performance_monitor() {
|
||||
// Code from:
|
||||
// https://learn.microsoft.com/en-us/windows/win32/perfctrs/collecting-performance-data
|
||||
// https://learn.microsoft.com/en-us/windows/win32/api/pdh/nf-pdh-pdhcollectquerydataex
|
||||
// Why value lower than taskManager:
|
||||
// https://aaron-margosis.medium.com/task-managers-cpu-numbers-are-all-but-meaningless-2d165b421e43
|
||||
// Therefore we should compare with Precess Explorer rather than taskManager
|
||||
|
||||
let f = || unsafe {
|
||||
// load avg or cpu usage, test with prime95.
|
||||
// Prefer cpu usage because we can get accurate value from Precess Explorer.
|
||||
// const COUNTER_PATH: &'static str = "\\System\\Processor Queue Length\0";
|
||||
const COUNTER_PATH: &'static str = "\\Processor(_total)\\% Processor Time\0";
|
||||
const SAMPLE_INTERVAL: DWORD = 2; // 2 second
|
||||
|
||||
let mut ret;
|
||||
let mut query: PDH_HQUERY = std::mem::zeroed();
|
||||
ret = PdhOpenQueryA(std::ptr::null() as _, 0, &mut query);
|
||||
if ret != 0 {
|
||||
log::error!("PdhOpenQueryA failed: 0x{:X}", ret);
|
||||
return;
|
||||
}
|
||||
let _query = RAIIPDHQuery(query);
|
||||
let mut counter: PDH_HCOUNTER = std::mem::zeroed();
|
||||
ret = PdhAddEnglishCounterA(query, COUNTER_PATH.as_ptr() as _, 0, &mut counter);
|
||||
if ret != 0 {
|
||||
log::error!("PdhAddEnglishCounterA failed: 0x{:X}", ret);
|
||||
return;
|
||||
}
|
||||
ret = PdhCollectQueryData(query);
|
||||
if ret != 0 {
|
||||
log::error!("PdhCollectQueryData failed: 0x{:X}", ret);
|
||||
return;
|
||||
}
|
||||
let mut _counter_type: DWORD = 0;
|
||||
let mut counter_value: PDH_FMT_COUNTERVALUE = std::mem::zeroed();
|
||||
let event = CreateEventA(std::ptr::null_mut(), FALSE, FALSE, std::ptr::null() as _);
|
||||
if event.is_null() {
|
||||
log::error!("CreateEventA failed");
|
||||
return;
|
||||
}
|
||||
let _event: RAIIHandle = RAIIHandle(event);
|
||||
ret = PdhCollectQueryDataEx(query, SAMPLE_INTERVAL, event);
|
||||
if ret != 0 {
|
||||
log::error!("PdhCollectQueryDataEx failed: 0x{:X}", ret);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut queue: VecDeque<f64> = VecDeque::new();
|
||||
let mut recent_valid: VecDeque<bool> = VecDeque::new();
|
||||
loop {
|
||||
// latest one minute
|
||||
if queue.len() == 31 {
|
||||
queue.pop_front();
|
||||
}
|
||||
if recent_valid.len() == 31 {
|
||||
recent_valid.pop_front();
|
||||
}
|
||||
// allow get value within one minute
|
||||
if queue.len() > 0 && recent_valid.iter().filter(|v| **v).count() > queue.len() / 2 {
|
||||
let sum: f64 = queue.iter().map(|f| f.to_owned()).sum();
|
||||
let avg = sum / (queue.len() as f64);
|
||||
*CPU_USAGE_ONE_MINUTE.lock().unwrap() = Some((avg, Instant::now()));
|
||||
} else {
|
||||
*CPU_USAGE_ONE_MINUTE.lock().unwrap() = None;
|
||||
}
|
||||
if WAIT_OBJECT_0 != WaitForSingleObject(event, INFINITE) {
|
||||
recent_valid.push_back(false);
|
||||
continue;
|
||||
}
|
||||
if PdhGetFormattedCounterValue(
|
||||
counter,
|
||||
PDH_FMT_DOUBLE,
|
||||
&mut _counter_type,
|
||||
&mut counter_value,
|
||||
) != 0
|
||||
|| counter_value.CStatus != 0
|
||||
{
|
||||
recent_valid.push_back(false);
|
||||
continue;
|
||||
}
|
||||
queue.push_back(counter_value.u.doubleValue().clone());
|
||||
recent_valid.push_back(true);
|
||||
}
|
||||
};
|
||||
use std::sync::Once;
|
||||
static ONCE: Once = Once::new();
|
||||
ONCE.call_once(|| {
|
||||
std::thread::spawn(f);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn cpu_uage_one_minute() -> Option<f64> {
|
||||
let v = CPU_USAGE_ONE_MINUTE.lock().unwrap().clone();
|
||||
if let Some((v, instant)) = v {
|
||||
if instant.elapsed().as_secs() < 30 {
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn sync_cpu_usage(cpu_usage: Option<f64>) {
|
||||
let v = match cpu_usage {
|
||||
Some(cpu_usage) => Some((cpu_usage, Instant::now())),
|
||||
None => None,
|
||||
};
|
||||
*CPU_USAGE_ONE_MINUTE.lock().unwrap() = v;
|
||||
log::info!("cpu usage synced: {:?}", cpu_usage);
|
||||
}
|
||||
|
||||
// https://learn.microsoft.com/en-us/windows/win32/sysinfo/targeting-your-application-at-windows-8-1
|
||||
// https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/deps/uv/src/win/util.c#L780
|
||||
pub fn is_windows_version_or_greater(
|
||||
os_major: u32,
|
||||
os_minor: u32,
|
||||
build_number: u32,
|
||||
service_pack_major: u32,
|
||||
service_pack_minor: u32,
|
||||
) -> bool {
|
||||
let mut osvi: OSVERSIONINFOEXW = unsafe { std::mem::zeroed() };
|
||||
osvi.dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOEXW>() as DWORD;
|
||||
osvi.dwMajorVersion = os_major as _;
|
||||
osvi.dwMinorVersion = os_minor as _;
|
||||
osvi.dwBuildNumber = build_number as _;
|
||||
osvi.wServicePackMajor = service_pack_major as _;
|
||||
osvi.wServicePackMinor = service_pack_minor as _;
|
||||
|
||||
let result = unsafe {
|
||||
let mut condition_mask = 0;
|
||||
let op = VER_GREATER_EQUAL;
|
||||
condition_mask = VerSetConditionMask(condition_mask, VER_MAJORVERSION, op);
|
||||
condition_mask = VerSetConditionMask(condition_mask, VER_MINORVERSION, op);
|
||||
condition_mask = VerSetConditionMask(condition_mask, VER_BUILDNUMBER, op);
|
||||
condition_mask = VerSetConditionMask(condition_mask, VER_SERVICEPACKMAJOR, op);
|
||||
condition_mask = VerSetConditionMask(condition_mask, VER_SERVICEPACKMINOR, op);
|
||||
|
||||
VerifyVersionInfoW(
|
||||
&mut osvi as *mut OSVERSIONINFOEXW,
|
||||
VER_MAJORVERSION
|
||||
| VER_MINORVERSION
|
||||
| VER_BUILDNUMBER
|
||||
| VER_SERVICEPACKMAJOR
|
||||
| VER_SERVICEPACKMINOR,
|
||||
condition_mask,
|
||||
)
|
||||
};
|
||||
|
||||
result == TRUE
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
include!(concat!(env!("OUT_DIR"), "/protos/mod.rs"));
|
||||
@@ -30,7 +30,6 @@ lazy_static = "1.4"
|
||||
serde = "1.0"
|
||||
serde_derive = "1.0"
|
||||
hbb_common = { path = "../hbb_common" }
|
||||
base = { path = "../base" }
|
||||
parking_lot = {version = "0.12"}
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]
|
||||
|
||||
@@ -48,19 +48,6 @@ 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> {
|
||||
@@ -73,8 +60,10 @@ pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
|
||||
description: "clipboard file name is not a normalized relative path".to_string(),
|
||||
});
|
||||
}
|
||||
base::fs::validate_file_name_no_traversal(name).map_err(|error| CliprdrError::InvalidRequest {
|
||||
description: error.to_string(),
|
||||
hbb_common::fs::validate_file_name_no_traversal(name).map_err(|error| {
|
||||
CliprdrError::InvalidRequest {
|
||||
description: error.to_string(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -82,7 +71,6 @@ 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
|
||||
@@ -140,13 +128,12 @@ 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
|
||||
};
|
||||
@@ -169,11 +156,8 @@ 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;
|
||||
let last_write_time = Duration::new(
|
||||
last_write_time / 10_000_000,
|
||||
(last_write_time % 10_000_000) as u32 * 100,
|
||||
);
|
||||
let last_write_time = (last_write_time - LDAP_EPOCH_DELTA) * 100;
|
||||
let last_write_time = Duration::from_nanos(last_write_time);
|
||||
SystemTime::UNIX_EPOCH + last_write_time
|
||||
} else {
|
||||
SystemTime::UNIX_EPOCH
|
||||
@@ -193,7 +177,6 @@ impl FileDescription {
|
||||
creation_time: last_modified,
|
||||
size,
|
||||
perm,
|
||||
clip_data_id,
|
||||
};
|
||||
|
||||
Ok(desc)
|
||||
@@ -205,7 +188,6 @@ 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 {
|
||||
@@ -226,7 +208,7 @@ impl FileDescription {
|
||||
|
||||
let mut files = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
|
||||
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
|
||||
files.push(desc);
|
||||
}
|
||||
|
||||
@@ -242,7 +224,6 @@ 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;
|
||||
@@ -303,22 +284,6 @@ 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);
|
||||
@@ -327,57 +292,4 @@ 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: true,
|
||||
clip_data_id: node.clip_data_id,
|
||||
have_clip_data_id: false,
|
||||
clip_data_id: 0,
|
||||
};
|
||||
|
||||
send_data(node.conn_id, request.clone()).map_err(|e| {
|
||||
@@ -611,9 +611,6 @@ 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
|
||||
@@ -637,7 +634,6 @@ 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
|
||||
@@ -654,7 +650,6 @@ impl FuseNode {
|
||||
pub fn new_root() -> Self {
|
||||
Self {
|
||||
conn_id: 0,
|
||||
clip_data_id: 0,
|
||||
index: 0,
|
||||
name: String::from("/"),
|
||||
parent: None,
|
||||
@@ -903,7 +898,6 @@ 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()
|
||||
/ 100) as u64
|
||||
.as_nanos() as u64
|
||||
/ 100
|
||||
+ LDAP_EPOCH_DELTA;
|
||||
|
||||
let size_high = (self.size >> 32) as u32;
|
||||
@@ -323,7 +323,6 @@ mod file_list_test {
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use hbb_common::bytes::{BufMut, BytesMut};
|
||||
@@ -491,46 +490,4 @@ 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(())
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user