Compare commits
89
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1ca09766c | ||
|
|
0aaf3a02bf | ||
|
|
eba0a6e552 | ||
|
|
3cb027a372 | ||
|
|
5217f32a12 | ||
|
|
c8cb6fb509 | ||
|
|
df9df7e914 | ||
|
|
acda5a73e2 | ||
|
|
04360797ad | ||
|
|
bb8083cb2f | ||
|
|
350966b331 | ||
|
|
d0a1af8c51 | ||
|
|
894f532835 | ||
|
|
eb23902450 | ||
|
|
59f2953c94 | ||
|
|
a5e986401c | ||
|
|
182356ee8b | ||
|
|
f96a44a019 | ||
|
|
1297da6d18 | ||
|
|
8814503e06 | ||
|
|
c8a4e0680c | ||
|
|
ed6a1acce8 | ||
|
|
4d37f00af9 | ||
|
|
21c488b6ce | ||
|
|
01e1323e51 | ||
|
|
106f700be4 | ||
|
|
f7b0af78cb | ||
|
|
25d2742273 | ||
|
|
eb6c32bd57 | ||
|
|
398364fa18 | ||
|
|
828d1101af | ||
|
|
3ec041644d | ||
|
|
d97351ad73 | ||
|
|
2b6fedfc8e | ||
|
|
f010d33ca6 | ||
|
|
bd92623972 | ||
|
|
4e93a41ecc | ||
|
|
ce54e33c71 | ||
|
|
2016f48dd7 | ||
|
|
b44b71cfab | ||
|
|
eef1096395 | ||
|
|
8b61033178 | ||
|
|
c29bef18bb | ||
|
|
c6258f4166 | ||
|
|
989beee17f | ||
|
|
4b1821d1ff | ||
|
|
3202d1764c | ||
|
|
c7f212df2c | ||
|
|
7f5a401947 | ||
|
|
bbffc1de5a | ||
|
|
4b92080e3e | ||
|
|
0cbeb04730 | ||
|
|
1042a26deb | ||
|
|
53996e3c40 | ||
|
|
e400bb7554 | ||
|
|
392188596c | ||
|
|
c0750fb50c | ||
|
|
f705902ec3 | ||
|
|
0d36ac0cba | ||
|
|
f1fa432bc8 | ||
|
|
538126d42c | ||
|
|
9c6d3fcb4f | ||
|
|
c230c57139 | ||
|
|
e614de83fc | ||
|
|
e910029f51 | ||
|
|
256dc9bc12 | ||
|
|
b1761ee676 | ||
|
|
d011aa3ea6 | ||
|
|
9997b7a3b8 | ||
|
|
76ab280ae9 | ||
|
|
29a160fc7e | ||
|
|
49a9574f97 | ||
|
|
0740063863 | ||
|
|
13e1278b4c | ||
|
|
0b5a3d74de | ||
|
|
109c39bccb | ||
|
|
ccfa714d2e | ||
|
|
0921a7432f | ||
|
|
c8532719c0 | ||
|
|
4411d10f45 | ||
|
|
67090d3aa1 | ||
|
|
001b0e9617 | ||
|
|
0bc2473ffe | ||
|
|
3f4bfe535e | ||
|
|
9b9e5f113a | ||
|
|
1d4abd0258 | ||
|
|
6da7977a94 | ||
|
|
25d2c6db55 | ||
|
|
f0bd880fe7 |
@@ -234,7 +234,7 @@ jobs:
|
||||
CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}"
|
||||
;;
|
||||
*)
|
||||
CARGO_TEST_OPTIONS="--workspace --no-fail-fast -- --skip test_get_cursor_pos --skip test_get_key_state"
|
||||
CARGO_TEST_OPTIONS="--workspace --no-fail-fast"
|
||||
;;
|
||||
esac;
|
||||
|
||||
|
||||
@@ -9,6 +9,9 @@ on:
|
||||
upload-tag:
|
||||
type: string
|
||||
default: "nightly"
|
||||
publish-update-metadata:
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
|
||||
# variables from this workflow!
|
||||
@@ -45,16 +48,54 @@ env:
|
||||
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.5.1"
|
||||
NDK_VERSION: "r28c"
|
||||
#signing keys env variable checks
|
||||
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
||||
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
|
||||
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
|
||||
PUBLISH_UPDATE_METADATA: "${{ inputs.publish-update-metadata }}"
|
||||
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
|
||||
|
||||
jobs:
|
||||
validate-update-metadata-keys:
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout source code
|
||||
if: ${{ inputs.publish-update-metadata }}
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Python
|
||||
if: ${{ inputs.publish-update-metadata }}
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install Python dependencies
|
||||
if: ${{ inputs.publish-update-metadata }}
|
||||
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
|
||||
|
||||
- name: Test update metadata signer
|
||||
if: ${{ inputs.publish-update-metadata }}
|
||||
run: |
|
||||
python -m unittest \
|
||||
res/update/test_generate_update_metadata.py \
|
||||
res/update/test_update_metadata_cli.py \
|
||||
res/update/test_macos_update_scripts.py
|
||||
|
||||
- name: Validate update metadata keys
|
||||
if: ${{ inputs.publish-update-metadata }}
|
||||
env:
|
||||
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
|
||||
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
|
||||
run: python res/update/generate_update_metadata.py check-key
|
||||
|
||||
generate-sbom:
|
||||
needs: [validate-update-metadata-keys]
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
@@ -83,9 +124,11 @@ jobs:
|
||||
rustdesk.sbom.json
|
||||
|
||||
generate-bridge:
|
||||
needs: [validate-update-metadata-keys]
|
||||
uses: ./.github/workflows/bridge.yml
|
||||
|
||||
build-RustDeskTempTopMostWindow:
|
||||
needs: [validate-update-metadata-keys]
|
||||
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -323,6 +366,17 @@ jobs:
|
||||
Write-Host "Ingore the printer driver error."
|
||||
}
|
||||
|
||||
- name: Run the Rust tests
|
||||
# x86_64 only: the tests are the same code on arm64, and that runner is the slow one.
|
||||
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'x86_64' }}
|
||||
shell: bash
|
||||
run: |
|
||||
# The build's own features, so the tests see the code that ships.
|
||||
FEATURES=$(python3 ./build.py --portable --flutter --skip-portable-pack --hwcodec ${{ matrix.job.build-args }} --print-features)
|
||||
cargo test --locked --release --lib --features "$FEATURES"
|
||||
# Its Windows tests run nowhere else.
|
||||
cargo test --locked --release -p clipboard
|
||||
|
||||
- name: find Runner.res
|
||||
# Windows: find Runner.res (compiled from ./flutter/windows/runner/Runner.rc), copy to ./Runner.res
|
||||
# Runner.rc does not contain actual version, but Runner.res does
|
||||
@@ -360,6 +414,18 @@ jobs:
|
||||
pip3 install requests argparse
|
||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./rustdesk/
|
||||
|
||||
- name: Verify Windows Flutter version
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
|
||||
shell: powershell
|
||||
run: |
|
||||
$reportedVersion = (& ".\rustdesk\rustdesk.exe" --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "rustdesk --version exited with $LASTEXITCODE"
|
||||
}
|
||||
if ($reportedVersion -cne $env:VERSION) {
|
||||
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
|
||||
}
|
||||
|
||||
- name: Build self-extracted executable
|
||||
shell: bash
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
@@ -450,9 +516,25 @@ jobs:
|
||||
run: |
|
||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput
|
||||
|
||||
- name: Upload signed Windows Flutter EXE
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: windows-flutter-${{ matrix.job.arch }}-exe
|
||||
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.exe
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload signed Windows Flutter MSI
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: windows-flutter-${{ matrix.job.arch }}-msi
|
||||
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.msi
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Publish Release
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
|
||||
with:
|
||||
prerelease: true
|
||||
tag_name: ${{ env.TAG_NAME }}
|
||||
@@ -463,6 +545,7 @@ jobs:
|
||||
# The fallback for the flutter version, we use Sciter for 32bit Windows.
|
||||
build-for-windows-sciter:
|
||||
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
|
||||
needs: [validate-update-metadata-keys]
|
||||
runs-on: ${{ matrix.job.os }}
|
||||
# Temporarily disable this action due to additional test is needed.
|
||||
# if: false
|
||||
@@ -595,6 +678,18 @@ jobs:
|
||||
pip3 install requests argparse
|
||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./Release/
|
||||
|
||||
- name: Verify Windows Sciter version
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
|
||||
shell: powershell
|
||||
run: |
|
||||
$reportedVersion = (& ".\Release\rustdesk.exe" --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "rustdesk --version exited with $LASTEXITCODE"
|
||||
}
|
||||
if ($reportedVersion -cne $env:VERSION) {
|
||||
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
|
||||
}
|
||||
|
||||
- name: Build self-extracted executable
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -612,9 +707,17 @@ jobs:
|
||||
run: |
|
||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput/
|
||||
|
||||
- name: Upload signed Windows Sciter EXE
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: windows-sciter-x86-exe
|
||||
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}-sciter.exe
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Publish Release
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
|
||||
with:
|
||||
prerelease: true
|
||||
tag_name: ${{ env.TAG_NAME }}
|
||||
@@ -755,6 +858,7 @@ jobs:
|
||||
target: x86_64-apple-darwin,
|
||||
os: macos-15-intel, #macos-latest or macos-14 use M1 now, https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#:~:text=14%20GB-,macos%2Dlatest%20or%20macos%2D14,-The%20macos%2Dlatestlabel
|
||||
extra-build-args: "",
|
||||
extra-cargo-features: "",
|
||||
arch: x86_64,
|
||||
vcpkg-triplet: x64-osx,
|
||||
}
|
||||
@@ -763,6 +867,7 @@ jobs:
|
||||
os: macos-14,
|
||||
# extra-build-args: "--disable-flutter-texture-render", # disable this for mac, because we see a lot of users reporting flickering both on arm and x64, and we can not confirm if texture rendering has better performance if htere is no vram, https://github.com/rustdesk/rustdesk/issues/6296
|
||||
extra-build-args: "--screencapturekit",
|
||||
extra-cargo-features: ",screencapturekit",
|
||||
arch: aarch64,
|
||||
vcpkg-triplet: arm64-osx,
|
||||
}
|
||||
@@ -871,10 +976,10 @@ jobs:
|
||||
name: bridge-artifact
|
||||
path: ./
|
||||
|
||||
- name: Test cursor sizing
|
||||
- name: Run the Dart tests
|
||||
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
|
||||
run: flutter test --timeout 60s
|
||||
|
||||
- name: Setup vcpkg with Github Actions binary cache
|
||||
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
||||
@@ -916,9 +1021,28 @@ jobs:
|
||||
sed -i -e "s/platform :osx, '.*'/platform :osx, '${MIN_MACOS_VERSION}'/" flutter/macos/Podfile
|
||||
sed -i -e "s/osx_minimum_system_version = \"[0-9]*.[0-9]*\"/osx_minimum_system_version = \"${MIN_MACOS_VERSION}\"/" Cargo.toml
|
||||
sed -i -e "s/MACOSX_DEPLOYMENT_TARGET = [0-9]*.[0-9]*;/MACOSX_DEPLOYMENT_TARGET = ${MIN_MACOS_VERSION};/" flutter/macos/Runner.xcodeproj/project.pbxproj
|
||||
echo "MACOSX_DEPLOYMENT_TARGET=${MIN_MACOS_VERSION}" >> "$GITHUB_ENV"
|
||||
fi
|
||||
./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }}
|
||||
|
||||
- name: Test verified updates
|
||||
if: env.PUBLISH_UPDATE_METADATA == 'true'
|
||||
run: |
|
||||
python3 -m unittest res/update/test_macos_update_scripts.py
|
||||
cargo test --locked --release --lib platform::macos::update_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
|
||||
cargo test --locked --release --lib verified_dmg_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
|
||||
cargo test --locked --release --lib update_metadata::tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
|
||||
|
||||
- name: Run the Rust tests
|
||||
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
||||
run: |
|
||||
# The build's own features, so the tests see the code that ships. MACOSX_DEPLOYMENT_TARGET
|
||||
# comes from the build step's export.
|
||||
FEATURES=$(./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }} --print-features)
|
||||
cargo test --locked --release --lib --features "$FEATURES"
|
||||
# Opt-in, and its macOS tests run nowhere else.
|
||||
cargo test --locked --release -p clipboard --features unix-file-copy-paste
|
||||
|
||||
- name: create unsigned dmg
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
run: |
|
||||
@@ -951,6 +1075,13 @@ jobs:
|
||||
./flutter/build/macos/Build/Products/Release/RustDesk.app \
|
||||
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
|
||||
./flutter/macos/Runner/Release.entitlements
|
||||
if [ "$PUBLISH_UPDATE_METADATA" = "true" ]; then
|
||||
reported_version="$(./flutter/build/macos/Build/Products/Release/RustDesk.app/Contents/MacOS/RustDesk --version)"
|
||||
if [ "$reported_version" != "$VERSION" ]; then
|
||||
echo "::error::RustDesk reports version '$reported_version', expected '$VERSION'"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
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
|
||||
@@ -958,13 +1089,26 @@ jobs:
|
||||
|
||||
- name: Rename rustdesk
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
VERSION: ${{ env.VERSION }}
|
||||
ARCH: ${{ matrix.job.arch }}
|
||||
run: |
|
||||
for name in rustdesk*??.dmg; do
|
||||
mv "$name" "${name%%.dmg}-${{ matrix.job.arch }}.dmg"
|
||||
done
|
||||
if [ -f "rustdesk-${VERSION}.dmg" ]; then
|
||||
mv "rustdesk-${VERSION}.dmg" "rustdesk-${VERSION}-${ARCH}.dmg"
|
||||
fi
|
||||
test -f "rustdesk-${VERSION}-${ARCH}.dmg"
|
||||
|
||||
- name: Upload signed macOS DMG
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.MACOS_P12_BASE64 != null
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: macos-${{ matrix.job.arch }}-dmg
|
||||
path: ./rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.dmg
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Publish DMG package
|
||||
if: env.UPLOAD_ARTIFACT == 'true'
|
||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
with:
|
||||
prerelease: true
|
||||
@@ -972,6 +1116,141 @@ jobs:
|
||||
files: |
|
||||
rustdesk*-${{ matrix.job.arch }}.dmg
|
||||
|
||||
publish-signed-update-metadata:
|
||||
needs: [build-for-windows-flutter, build-for-windows-sciter, build-for-macOS]
|
||||
runs-on: ubuntu-22.04
|
||||
if: ${{ inputs.upload-artifact && inputs.publish-update-metadata && github.repository == 'rustdesk/rustdesk' }}
|
||||
concurrency:
|
||||
group: signed-update-${{ inputs.upload-tag }}
|
||||
cancel-in-progress: false
|
||||
permissions:
|
||||
# Required to inspect and publish signed release assets for the target tag.
|
||||
contents: write
|
||||
steps:
|
||||
- name: Refuse to replace published update metadata
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG_NAME: ${{ env.TAG_NAME }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
releases="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases?per_page=100")"
|
||||
release_id="$(
|
||||
jq -r --arg tag "$TAG_NAME" '
|
||||
[.[][] | select(.tag_name == $tag)] |
|
||||
if length == 0 then ""
|
||||
elif length == 1 then .[0].id
|
||||
else error("multiple releases found for tag")
|
||||
end
|
||||
' <<<"$releases"
|
||||
)"
|
||||
if [ -z "$release_id" ]; then
|
||||
exit 0
|
||||
fi
|
||||
assets="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases/${release_id}/assets?per_page=100")"
|
||||
if jq -e 'any(.[][]; .name == "rustdesk-update.json")' <<<"$assets" >/dev/null; then
|
||||
echo "::error::Signed update metadata is already published for ${TAG_NAME}; use a new release tag for corrected artifacts."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Checkout source code
|
||||
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install Python
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install Python dependencies
|
||||
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
|
||||
|
||||
- name: Download Windows artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: windows-*
|
||||
path: ./artifacts/
|
||||
merge-multiple: true
|
||||
|
||||
- name: Download macOS artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: macos-*
|
||||
path: ./artifacts/
|
||||
merge-multiple: true
|
||||
|
||||
- name: Sign update metadata
|
||||
env:
|
||||
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
|
||||
run: |
|
||||
python res/update/generate_update_metadata.py sign \
|
||||
--artifact windows x86_64 exe "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
|
||||
--artifact windows x86_64 msi "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
|
||||
--artifact windows aarch64 exe "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
|
||||
--artifact windows aarch64 msi "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
|
||||
--artifact windows x86 exe "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
|
||||
--artifact macos aarch64 dmg "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
|
||||
--artifact macos x86_64 dmg "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
|
||||
--version "$VERSION" --release-id "$TAG_NAME" \
|
||||
--package-id rustdesk \
|
||||
--release-base-url https://github.com/rustdesk/rustdesk/releases/download \
|
||||
--published-at "$(git log -1 --format=%cI)" \
|
||||
--metadata-out ./rustdesk-update.json \
|
||||
--signature-out ./rustdesk-update.json.sig
|
||||
|
||||
- name: Verify update metadata
|
||||
env:
|
||||
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
|
||||
run: |
|
||||
python res/update/generate_update_metadata.py verify \
|
||||
--metadata ./rustdesk-update.json \
|
||||
--signature ./rustdesk-update.json.sig \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
|
||||
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
|
||||
--version "$VERSION" --release-id "$TAG_NAME" \
|
||||
--package-id rustdesk \
|
||||
--release-base-url https://github.com/rustdesk/rustdesk/releases/download
|
||||
|
||||
- name: Upload signed update artifacts
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
with:
|
||||
prerelease: true
|
||||
fail_on_unmatched_files: true
|
||||
tag_name: ${{ env.TAG_NAME }}
|
||||
files: |
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.exe
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.msi
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.exe
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.msi
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-x86-sciter.exe
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.dmg
|
||||
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.dmg
|
||||
|
||||
# The release action replaces same-name assets, so keep published sidecars
|
||||
# until replacements are ready.
|
||||
- name: Upload signed update metadata signature
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
with:
|
||||
prerelease: true
|
||||
fail_on_unmatched_files: true
|
||||
tag_name: ${{ env.TAG_NAME }}
|
||||
files: ./rustdesk-update.json.sig
|
||||
|
||||
# Clients discover the release through metadata, so publish it only after every referenced asset.
|
||||
- name: Publish signed update metadata
|
||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||
with:
|
||||
prerelease: true
|
||||
fail_on_unmatched_files: true
|
||||
tag_name: ${{ env.TAG_NAME }}
|
||||
files: ./rustdesk-update.json
|
||||
|
||||
publish_unsigned:
|
||||
needs:
|
||||
- build-for-macOS
|
||||
@@ -2086,12 +2365,21 @@ jobs:
|
||||
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 "rustdesk drm_pacing_tests" \
|
||||
cargo test --locked --lib --features drm drm_pacing_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 crtc_refresh_tests" \
|
||||
cargo test --locked -p scrap --features drm crtc_refresh_tests
|
||||
run_drm_tests "scrap plane_rotation_tests" \
|
||||
cargo test --locked -p scrap --features drm plane_rotation_tests
|
||||
run_drm_tests "scrap drmtap_dl::tests" \
|
||||
cargo test --locked -p scrap --features drm drmtap_dl::tests
|
||||
# Opt-in like drm, and this container already builds with it.
|
||||
run_drm_tests "clipboard unix-file-copy-paste" \
|
||||
cargo test --locked -p clipboard --features unix-file-copy-paste
|
||||
cargo build --locked --lib --features "$FEATURES" --release
|
||||
rm -rf target/release/deps target/release/build
|
||||
rm -rf ~/.cargo
|
||||
@@ -2172,6 +2460,7 @@ jobs:
|
||||
|
||||
build-rustdesk-linux-sciter:
|
||||
if: ${{ inputs.upload-artifact }}
|
||||
needs: [validate-update-metadata-keys]
|
||||
runs-on: ${{ matrix.job.on }}
|
||||
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
|
||||
strategy:
|
||||
@@ -2552,6 +2841,7 @@ jobs:
|
||||
|
||||
build-rustdesk-web:
|
||||
if: False
|
||||
needs: [validate-update-metadata-keys]
|
||||
name: build-rustdesk-web
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
|
||||
@@ -15,4 +15,5 @@ jobs:
|
||||
secrets: inherit
|
||||
with:
|
||||
upload-artifact: true
|
||||
upload-tag: ${{ github.ref_name }}
|
||||
upload-tag: ${{ github.ref_name }}
|
||||
publish-update-metadata: ${{ github.repository == 'rustdesk/rustdesk' }}
|
||||
|
||||
@@ -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.5.1"
|
||||
NDK_VERSION: "r26d"
|
||||
#signing keys env variable checks
|
||||
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
||||
|
||||
@@ -186,6 +186,10 @@ A refactor added to cover a corner case rarely converges. Each new counter, time
|
||||
* 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.
|
||||
* Dart tests go in `flutter/test/*_test.dart`, nowhere else: CI runs `flutter test` over that directory and nothing outside it. It runs on the VM, so a `@TestOn('browser')` suite runs in no CI job.
|
||||
* Rust unit tests go in a `#[cfg(test)]` module beside the code. CI runs `cargo test --workspace` with the default features on x86_64 Linux, `cargo test --lib` on the root package with the release feature set on macOS and Windows plus `-p clipboard` there, and on Linux the `drm` test modules by name plus the `clipboard` package with `unix-file-copy-paste`. On macOS and Windows, a platform-gated test in another workspace crate runs only if that platform's job names the crate with `-p`. Gate a test module on a feature or `target_os` only when the code under test is gated; a pure helper that only a gated path calls gets `#[cfg(any(feature = "...", test))]`, so its tests run everywhere.
|
||||
* A test behind a feature that no CI build enables needs a `cargo test` line in `.github/workflows/flutter-build.yml` that names it. In the Linux drm job, wrap it in `run_drm_tests` so a filter that matches nothing fails instead of passing.
|
||||
* Web core tests are `flutter/web/js/src/*.test.ts`, run by jest in that repository's own CI.
|
||||
|
||||
## Reviewing a PR
|
||||
|
||||
|
||||
Generated
+31
-35
@@ -3737,7 +3737,7 @@ dependencies = [
|
||||
"url",
|
||||
"users",
|
||||
"uuid",
|
||||
"webpki-roots 1.0.9",
|
||||
"webpki-roots 1.0.11",
|
||||
"webrtc",
|
||||
"whoami",
|
||||
"x11 2.21.0",
|
||||
@@ -3888,8 +3888,8 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
|
||||
|
||||
[[package]]
|
||||
name = "hwcodec"
|
||||
version = "0.7.1"
|
||||
source = "git+https://github.com/rustdesk-org/hwcodec#778df1f99597722473b29443bac22ae6c23946fe"
|
||||
version = "0.8.0"
|
||||
source = "git+https://github.com/rustdesk-org/hwcodec#ec38ebaf2454269d4c5668a57e3813c6e5541be7"
|
||||
dependencies = [
|
||||
"bindgen 0.59.2",
|
||||
"cc",
|
||||
@@ -3935,7 +3935,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower-service",
|
||||
"webpki-roots 1.0.9",
|
||||
"webpki-roots 1.0.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4163,16 +4163,6 @@ 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"
|
||||
@@ -6772,7 +6762,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rdev"
|
||||
version = "0.5.0-2"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
|
||||
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
|
||||
dependencies = [
|
||||
"cocoa 0.24.1",
|
||||
"core-foundation 0.9.4",
|
||||
@@ -6901,11 +6891,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.24"
|
||||
version = "0.12.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
@@ -6934,7 +6923,6 @@ dependencies = [
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
@@ -6942,7 +6930,7 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots 1.0.9",
|
||||
"webpki-roots 1.0.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7053,7 +7041,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rust-pulsectl"
|
||||
version = "0.2.12"
|
||||
source = "git+https://github.com/rustdesk-org/pulsectl#aa34dde499aa912a3abc5289cc0b547bd07dd6e2"
|
||||
source = "git+https://github.com/rustdesk-org/pulsectl#d2ec086b5770dce934a66956364d09df8cc9484c"
|
||||
dependencies = [
|
||||
"libpulse-binding",
|
||||
]
|
||||
@@ -7087,7 +7075,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustdesk"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
dependencies = [
|
||||
"android-wakelock",
|
||||
"android_logger",
|
||||
@@ -7187,6 +7175,7 @@ dependencies = [
|
||||
"uuid",
|
||||
"virtual_display",
|
||||
"wallpaper",
|
||||
"wayland-client",
|
||||
"winapi 0.3.9",
|
||||
"windows 0.61.1",
|
||||
"windows-service",
|
||||
@@ -7196,13 +7185,14 @@ 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.5.1"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"dirs 5.0.1",
|
||||
@@ -7306,11 +7296,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.11.0"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
|
||||
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7342,9 +7333,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.3"
|
||||
version = "0.103.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435"
|
||||
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
@@ -8744,20 +8735,25 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tower-http"
|
||||
version = "0.6.6"
|
||||
version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
|
||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"bitflags 2.9.1",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"iri-string",
|
||||
"http-body-util",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9544,9 +9540,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "webpki-root-certs"
|
||||
version = "1.0.3"
|
||||
version = "1.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05d651ec480de84b762e7be71e6efa7461699c19d9e2c272c8d93455f567786e"
|
||||
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
@@ -9557,14 +9553,14 @@ version = "0.26.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
||||
dependencies = [
|
||||
"webpki-roots 1.0.9",
|
||||
"webpki-roots 1.0.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.9"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
|
||||
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
|
||||
dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rustdesk"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
authors = ["rustdesk <info@rustdesk.com>"]
|
||||
edition = "2021"
|
||||
build= "build.rs"
|
||||
@@ -202,6 +202,8 @@ 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"] }
|
||||
@@ -271,7 +273,7 @@ os-version = "0.2"
|
||||
[dev-dependencies]
|
||||
hound = "3.5"
|
||||
docopt = "1.1"
|
||||
tokio = { version = "1.44", features = ["test-util"] }
|
||||
tokio = "1.44"
|
||||
|
||||
[package.metadata.bundle]
|
||||
name = "RustDesk"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<a href="#how-to-build-with-docker">Docker</a> •
|
||||
<a href="#file-structure">Structure</a> •
|
||||
<a href="#screenshots">Screenshots</a><br>
|
||||
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
|
||||
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTPT.md">Português (Portugal)</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
|
||||
<b>We need your help to translate this README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> and <a href="https://github.com/rustdesk/doc.rustdesk.com">RustDesk Doc</a> to your native language</b>
|
||||
</p>
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ AppDir:
|
||||
id: rustdesk
|
||||
name: rustdesk
|
||||
icon: rustdesk
|
||||
version: 1.5.0
|
||||
version: 1.5.1
|
||||
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.5.1
|
||||
exec: usr/share/rustdesk/rustdesk
|
||||
exec_args: $@
|
||||
apt:
|
||||
|
||||
@@ -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.12.
|
||||
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
|
||||
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
|
||||
LIBDRMTAP_SHA_PINNED = '5936a7a88b94aa43516a3dd0eb509d2383f31e2d'
|
||||
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
|
||||
|
||||
@@ -2,7 +2,12 @@
|
||||
fn build_windows() {
|
||||
let file = "src/platform/windows.cc";
|
||||
let file2 = "src/platform/windows_delete_test_cert.cc";
|
||||
cc::Build::new().file(file).file(file2).compile("windows");
|
||||
let mut build = cc::Build::new();
|
||||
if !cfg!(feature = "flutter") {
|
||||
build.cpp(true).std("c++17").define("RUSTDESK_SCITER", None);
|
||||
println!("cargo:rerun-if-changed=flutter/windows/runner/service_control.h");
|
||||
}
|
||||
build.file(file).file(file2).compile("windows");
|
||||
println!("cargo:rustc-link-lib=WtsApi32");
|
||||
println!("cargo:rerun-if-changed={}", file);
|
||||
println!("cargo:rerun-if-changed={}", file2);
|
||||
|
||||
+8
-1
@@ -9,6 +9,10 @@
|
||||
<b>Kami membutuhkan bantuanmu untuk menterjemahkan file README dan <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> ke Bahasa Indonesia</b>
|
||||
</p>
|
||||
|
||||
> [!Caution]
|
||||
> **Peringatan Penyalahgunaan:** <br>
|
||||
> Pengembang RustDesk tidak membenarkan atau mendukung penggunaan perangkat lunak ini yang tidak etis atau melanggar hukum. Penyalahgunaan, seperti akses tanpa izin, pengambilalihan kendali, atau pelanggaran privasi, sangat dilarang berdasarkan pedoman kami. Para pengembang tidak bertanggung jawab atas penyalahgunaan aplikasi ini.
|
||||
|
||||
Mari mengobrol bersama kami: [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)
|
||||
@@ -30,6 +34,9 @@ RustDesk mengajak semua orang untuk ikut berkontribusi. Lihat [`docs/CONTRIBUTIN
|
||||
[<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)
|
||||
|
||||
## Dependensi
|
||||
|
||||
@@ -154,7 +161,7 @@ Harap pastikan bahwa kamu menjalankan perintah ini dari repositori root RustDesk
|
||||
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
|
||||
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikasi dengan [rustdesk-server](https://github.com/rustdesk/rustdesk-server), menunggu untuk remote direct (TCP hole punching) atau relayed connection
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: kode khusus platform
|
||||
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: kode Flutter untuk platform desktop dan perangkat seluler
|
||||
## Snapshots
|
||||
|
||||

|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
<p align="center">
|
||||
<img src="../res/logo-header.svg" alt="RustDesk - O seu ambiente de trabalho remoto"><br>
|
||||
<a href="#compilar">Compilar</a> •
|
||||
<a href="#como-compilar-com-o-docker">Docker</a> •
|
||||
<a href="#estrutura-de-ficheiros">Estrutura</a> •
|
||||
<a href="#capturas-de-ecrã">Capturas de Ecrã</a><br>
|
||||
[<a href="../README.md">Inglês</a>] | [<a href="README-UA.md">Ucraniano</a>] | [<a href="README-CS.md">Checo</a>] | [<a href="README-ZH.md">Chinês</a>] | [<a href="README-HU.md">Húngaro</a>] | [<a href="README-ES.md">Espanhol</a>] | [<a href="README-FA.md">Persa</a>] | [<a href="README-FR.md">Francês</a>] | [<a href="README-DE.md">Alemão</a>] | [<a href="README-PL.md">Polaco</a>] | [<a href="README-ID.md">Indonésio</a>] | [<a href="README-FI.md">Finlandês</a>] | [<a href="README-ML.md">Malaiala</a>] | [<a href="README-JP.md">Japonês</a>] | [<a href="README-NL.md">Holandês</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Russo</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">Coreano</a>] | [<a href="README-AR.md">Árabe</a>] | [<a href="README-VN.md">Vietnamita</a>] | [<a href="README-DA.md">Dinamarquês</a>] | [<a href="README-GR.md">Grego</a>] | [<a href="README-TR.md">Turco</a>] | [<a href="README-NO.md">Norueguês</a>] | [<a href="README-RO.md">Romeno</a>]<br>
|
||||
<b>Precisamos da sua ajuda para traduzir este README, a <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">Interface do RustDesk</a> e a <a href="https://github.com/rustdesk/doc.rustdesk.com">Documentação do RustDesk</a> para o seu idioma nativo</b>
|
||||
</p>
|
||||
|
||||
> [!Caution]
|
||||
> **Aviso de Isenção de Responsabilidade por Uso Indevido:** <br>
|
||||
> Os programadores do RustDesk não toleram ou apoiam qualquer uso antiético ou ilegal deste software. O uso indevido, como acesso não autorizado, controlo ou invasão de privacidade, é estritamente contrário às nossas diretrizes. Os autores não se responsabilizam por qualquer uso indevido da aplicação.
|
||||
|
||||
|
||||
Converse connosco: [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)
|
||||
|
||||
Mais uma solução de ambiente de trabalho remoto, escrita em Rust. Funciona imediatamente, sem necessidade de configuração. Tem controlo total dos seus dados, sem preocupações com a segurança. Pode usar o nosso servidor de ligação/retransmissão (rendezvous/relay), [configurar o seu próprio](https://rustdesk.com/server) ou [escrever o seu próprio servidor de ligação/retransmissão](https://github.com/rustdesk/rustdesk-server-demo).
|
||||
|
||||

|
||||
|
||||
O RustDesk agradece as contribuições de todos. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para obter ajuda para começar.
|
||||
|
||||
[**Perguntas Frequentes (FAQ)**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
|
||||
|
||||
[**DOWNLOAD DOS BINÁRIOS**](https://github.com/rustdesk/rustdesk/releases)
|
||||
|
||||
[**VERSÕES NIGHTLY (EM DESENVOLVIMENTO)**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
|
||||
|
||||
[<img src="https://f-droid.org/badge/get-it-on.png"
|
||||
alt="Transfira no 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="Transfira no Flathub"
|
||||
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
|
||||
|
||||
## Dependências
|
||||
|
||||
As versões para ambiente de trabalho usam Flutter ou Sciter (descontinuado) para a interface gráfica (GUI). Este tutorial é apenas para o Sciter, por ser mais fácil e acessível para começar. Consulte o nosso [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) para instruções de compilação da versão Flutter.
|
||||
|
||||
Por favor transfira a biblioteca dinâmica do Sciter por conta própria.
|
||||
|
||||
[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) |
|
||||
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
|
||||
|
||||
## Passos básicos para compilar
|
||||
|
||||
- Prepare o seu ambiente de desenvolvimento Rust e o ambiente de compilação C++
|
||||
|
||||
- Instale o [vcpkg](https://github.com/microsoft/vcpkg) e configure a variável de ambiente `VCPKG_ROOT` corretamente
|
||||
|
||||
- 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`
|
||||
|
||||
- Execute `cargo run`
|
||||
|
||||
## [Compilar](https://rustdesk.com/docs/en/dev/build/)
|
||||
|
||||
## Como Compilar no Linux
|
||||
|
||||
### Ubuntu 18 (Debian 10)
|
||||
|
||||
```sh
|
||||
sudo apt install -y zip g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake make libclang-dev ninja-build libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
|
||||
```
|
||||
|
||||
### openSUSE Tumbleweed
|
||||
|
||||
```sh
|
||||
sudo zypper install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libXfixes-devel cmake alsa-lib-devel gstreamer-devel gstreamer-plugins-base-devel xdotool-devel
|
||||
```
|
||||
|
||||
### Fedora 28 (CentOS 8)
|
||||
|
||||
```sh
|
||||
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel gstreamer1-devel gstreamer1-plugins-base-devel
|
||||
```
|
||||
|
||||
### Arch (Manjaro)
|
||||
|
||||
```sh
|
||||
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pipewire
|
||||
```
|
||||
|
||||
### Instalar o vcpkg
|
||||
|
||||
```sh
|
||||
git clone https://github.com/microsoft/vcpkg
|
||||
cd vcpkg
|
||||
git checkout 2023.04.15
|
||||
cd ..
|
||||
vcpkg/bootstrap-vcpkg.sh
|
||||
export VCPKG_ROOT=$HOME/vcpkg
|
||||
vcpkg/vcpkg install libvpx libyuv opus aom
|
||||
```
|
||||
|
||||
### Corrigir o libvpx (Para Fedora)
|
||||
|
||||
```sh
|
||||
cd vcpkg/buildtrees/libvpx/src
|
||||
cd *
|
||||
./configure
|
||||
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
|
||||
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
|
||||
make
|
||||
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
|
||||
cd
|
||||
```
|
||||
|
||||
### Compilar
|
||||
|
||||
```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
|
||||
cd rustdesk
|
||||
mkdir -p target/debug
|
||||
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
|
||||
mv libsciter-gtk.so target/debug
|
||||
VCPKG_ROOT=$HOME/vcpkg cargo run
|
||||
```
|
||||
|
||||
## Como compilar com o Docker
|
||||
|
||||
Comece por clonar o repositório e construir o contentor Docker:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/rustdesk/rustdesk
|
||||
cd rustdesk
|
||||
git submodule update --init --recursive
|
||||
docker build -t "rustdesk-builder" .
|
||||
```
|
||||
|
||||
Depois, cada vez que precisar de compilar a aplicação, execute o seguinte comando:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Note que a primeira compilação pode demorar mais até que as dependências sejam armazenadas em cache, as compilações subsequentes serão mais rápidas. Além disso, se precisar especificar argumentos diferentes para o comando de compilação, poderá fazê-lo no final do comando na posição `<ARGUMENTOS-OPCIONAIS>`. Por exemplo, se quiser compilar uma versão de lançamento (release) otimizada, executaria o comando acima seguido de `--release`. O executável resultante estará disponível na pasta `target` do seu sistema e pode ser executado com:
|
||||
|
||||
```sh
|
||||
target/debug/rustdesk
|
||||
```
|
||||
|
||||
Ou, se estiver a correr o executável de lançamento:
|
||||
|
||||
```sh
|
||||
target/release/rustdesk
|
||||
```
|
||||
|
||||
Certifique-se de que executa estes comandos a partir da raiz do repositório do RustDesk, caso contrário a aplicação poderá não encontrar os recursos necessários. Note também que outros subcomandos do cargo, como `install` ou `run`, não são suportados atualmente por este método, pois instalariam ou executariam o programa dentro do contentor em vez de o fazerem no host.
|
||||
|
||||
## Estrutura de Ficheiros
|
||||
|
||||
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: codec de vídeo, configuração, wrapper TCP/UDP e algumas outras funções utilitárias partilhadas com o servidor
|
||||
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, funções fs para transferência de ficheiros, código relacionado com o teclado e com a plataforma utilizado exclusivamente por esta aplicação
|
||||
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de ecrã
|
||||
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: controlo de teclado/rato específico da plataforma.
|
||||
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: implementação de copiar e colar ficheiros para Windows, Linux e macOS.
|
||||
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: interface Sciter obsoleta (descontinuada).
|
||||
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: serviços de áudio, área de transferência, entrada e vídeo, e ligações de rede
|
||||
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: inicia uma ligação entre pares
|
||||
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunica com o [rustdesk-server](https://github.com/rustdesk/rustdesk-server), aguarda por uma ligação direta remota (TCP hole punching) ou uma ligação retransmitida
|
||||
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico da plataforma
|
||||
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: código Flutter para ambiente de trabalho e dispositivos móveis
|
||||
|
||||
## Capturas de Ecrã
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
@@ -0,0 +1,41 @@
|
||||
package com.carriez.flutter_hbb
|
||||
|
||||
import android.os.ParcelFileDescriptor
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
internal class DocumentDescriptors {
|
||||
private val descriptors = ConcurrentHashMap<String, ParcelFileDescriptor>()
|
||||
|
||||
fun open(descriptor: ParcelFileDescriptor): JSONObject {
|
||||
val id = UUID.randomUUID().toString()
|
||||
try {
|
||||
// Only detach the duplicate: the original carries the provider's close/error channel.
|
||||
val duplicate = ParcelFileDescriptor.dup(descriptor.fileDescriptor)
|
||||
descriptors[id] = descriptor
|
||||
return JSONObject().put("fd", duplicate.detachFd()).put("descriptor", id)
|
||||
} catch (error: Exception) {
|
||||
descriptors.remove(id)
|
||||
try {
|
||||
descriptor.closeWithError(error.message ?: "Unable to open document")
|
||||
} catch (closeError: Exception) {
|
||||
error.addSuppressed(closeError)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
fun close(request: JSONObject): Boolean {
|
||||
val descriptor = descriptors.remove(request.getString("descriptor"))
|
||||
?: throw IOException("Document descriptor was already closed")
|
||||
val error = request.optString("error", "")
|
||||
if (error.isNotEmpty()) {
|
||||
descriptor.closeWithError(error)
|
||||
} else {
|
||||
descriptor.use { if (it.canDetectErrors()) it.checkError() }
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package com.carriez.flutter_hbb
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.DocumentsContract.Document
|
||||
import android.util.Log
|
||||
import java.io.FileNotFoundException
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
internal class DocumentLogs(private val context: Context) {
|
||||
private val resolver = context.contentResolver
|
||||
private val prefs = context.getSharedPreferences(DOCUMENT_PREFS, Context.MODE_PRIVATE)
|
||||
private val appName = context.applicationInfo.loadLabel(context.packageManager).toString()
|
||||
private val appDirectoryId = "$PARENT_ID/$appName"
|
||||
private val directoryId = "$appDirectoryId/Logs"
|
||||
val directoryPath = directoryId.substringAfter(':')
|
||||
private var output: ParcelFileDescriptor.AutoCloseOutputStream? = null
|
||||
private var written = 0L
|
||||
private var openedDay = 0L
|
||||
private var failure: Exception? = null
|
||||
private val lock = ReentrantLock()
|
||||
|
||||
init {
|
||||
setEnabled(grant() != null)
|
||||
}
|
||||
|
||||
@androidx.annotation.Keep
|
||||
private external fun setEnabled(enabled: Boolean)
|
||||
|
||||
private fun grant(): Uri? = prefs.getString(LOG_GRANT, null)?.let(Uri::parse)
|
||||
|
||||
fun hasPermission(): Boolean {
|
||||
val uri = grant() ?: return false
|
||||
if (!isLogGrant(uri)) return false
|
||||
return resolver.persistedUriPermissions.any {
|
||||
it.uri == uri && it.isReadPermission && it.isWritePermission
|
||||
}
|
||||
}
|
||||
|
||||
private fun isLogGrant(uri: Uri): Boolean =
|
||||
uri.authority == AUTHORITY && DocumentsContract.isTreeUri(uri) &&
|
||||
DocumentsContract.getTreeDocumentId(uri) in listOf(PARENT_ID, appDirectoryId, directoryId)
|
||||
|
||||
private fun isDirectory(uri: Uri): Boolean = try {
|
||||
resolver.query(uri, arrayOf(Document.COLUMN_MIME_TYPE), null, null, null)?.use {
|
||||
it.moveToFirst() && it.getString(it.getColumnIndexOrThrow(
|
||||
Document.COLUMN_MIME_TYPE)) == Document.MIME_TYPE_DIR
|
||||
} ?: false
|
||||
} catch (_: FileNotFoundException) {
|
||||
false
|
||||
}
|
||||
|
||||
private fun containsDirectory(grant: Uri, parentId: String, id: String): Boolean {
|
||||
val children = DocumentsContract.buildChildDocumentsUriUsingTree(grant, parentId)
|
||||
val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE)
|
||||
return resolver.query(children, columns, null, null, null)?.use { cursor ->
|
||||
checkDocumentListing(cursor, "Unable to list ${parentId.substringAfter(':')}",
|
||||
"${parentId.substringAfter(':')} is still loading")
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DOCUMENT_ID)) != id) continue
|
||||
check(cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE)) ==
|
||||
Document.MIME_TYPE_DIR) { "${id.substringAfter(':')} is not a directory" }
|
||||
return@use true
|
||||
}
|
||||
false
|
||||
} ?: throw IOException("Unable to list ${parentId.substringAfter(':')}")
|
||||
}
|
||||
|
||||
private fun ensureDirectory(grant: Uri): Uri {
|
||||
checkDocumentName(appName)
|
||||
val rootId = DocumentsContract.getTreeDocumentId(grant)
|
||||
var parent = DocumentsContract.buildDocumentUriUsingTree(grant, rootId)
|
||||
check(isDirectory(parent)) { "The authorized log folder is unavailable" }
|
||||
val children = when (rootId) {
|
||||
PARENT_ID -> listOf(appDirectoryId, directoryId)
|
||||
appDirectoryId -> listOf(directoryId)
|
||||
directoryId -> emptyList()
|
||||
else -> throw IOException("The selected folder does not contain $directoryPath")
|
||||
}
|
||||
for (id in children) {
|
||||
val child = DocumentsContract.buildDocumentUriUsingTree(grant, id)
|
||||
if (!containsDirectory(grant, DocumentsContract.getDocumentId(parent), id)) {
|
||||
closeOutput()
|
||||
val created = DocumentsContract.createDocument(
|
||||
resolver, parent, Document.MIME_TYPE_DIR, id.substringAfterLast('/'))
|
||||
?: throw IOException("Unable to create ${id.substringAfter(':')}")
|
||||
check(DocumentsContract.getDocumentId(created) == id) {
|
||||
"${id.substringAfter(':')} is not available as a directory"
|
||||
}
|
||||
}
|
||||
parent = child
|
||||
}
|
||||
return parent
|
||||
}
|
||||
|
||||
fun select(uri: Uri, flags: Int) = lock.withLock {
|
||||
require(isLogGrant(uri)) {
|
||||
"Please select Android → media."
|
||||
}
|
||||
val permissions = flags and GRANT_FLAGS
|
||||
require(permissions == GRANT_FLAGS) { "Read and write access is required for logs" }
|
||||
setEnabled(false)
|
||||
resolver.takePersistableUriPermission(uri, permissions)
|
||||
ensureDirectory(uri)
|
||||
closeOutput()
|
||||
check(prefs.edit().putString(LOG_GRANT, uri.toString()).commit()) {
|
||||
"Unable to remember the log directory"
|
||||
}
|
||||
check(ensureReady()) { "Log directory access was revoked" }
|
||||
}
|
||||
|
||||
fun ensureReady(): Boolean = lock.withLock {
|
||||
setEnabled(false)
|
||||
if (!hasPermission()) return false
|
||||
val uri = grant() ?: return false
|
||||
val root = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri))
|
||||
if (!isDirectory(root)) return false
|
||||
ensureDirectory(uri)
|
||||
failure = null
|
||||
if (output == null) openNext(uri)
|
||||
setEnabled(true)
|
||||
return true
|
||||
}
|
||||
|
||||
fun write(message: String): Boolean {
|
||||
if (!lock.tryLock()) return false
|
||||
return try {
|
||||
writeLocked(message)
|
||||
} finally {
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeLocked(message: String): Boolean {
|
||||
val uri = grant() ?: return false
|
||||
failure?.let { throw IOException("File logging stopped: ${it.message}", it) }
|
||||
try {
|
||||
if (output == null && !hasPermission()) {
|
||||
throw IOException("Log directory access was revoked")
|
||||
}
|
||||
if (output == null || written >= MAX_LOG_BYTES || openedDay != currentDay()) {
|
||||
openNext(uri)
|
||||
}
|
||||
val bytes = message.toByteArray(Charsets.UTF_8)
|
||||
val stream = output ?: throw IOException("The log file is not open")
|
||||
stream.write(bytes)
|
||||
written += bytes.size
|
||||
return true
|
||||
} catch (error: Exception) {
|
||||
setEnabled(false)
|
||||
failure = error
|
||||
try {
|
||||
closeOutput()
|
||||
} catch (closeError: Exception) {
|
||||
error.addSuppressed(closeError)
|
||||
}
|
||||
Log.e("DocumentLogs", "File logging stopped", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private fun closeOutput() {
|
||||
val stream = output
|
||||
output = null
|
||||
stream?.close()
|
||||
}
|
||||
|
||||
private fun openNext(grant: Uri) {
|
||||
closeOutput()
|
||||
val name = "rustdesk-${System.currentTimeMillis()}-${UUID.randomUUID()}.txt"
|
||||
val document = DocumentsContract.createDocument(
|
||||
resolver, ensureDirectory(grant), "text/plain", name)
|
||||
?: throw IOException("Unable to create a log file")
|
||||
try {
|
||||
val descriptor = resolver.openFileDescriptor(document, "w")
|
||||
?: throw IOException("Unable to open the log file")
|
||||
output = ParcelFileDescriptor.AutoCloseOutputStream(descriptor)
|
||||
} catch (error: Exception) {
|
||||
try {
|
||||
if (!DocumentsContract.deleteDocument(resolver, document)) {
|
||||
throw IOException("Unable to remove the unopened log file")
|
||||
}
|
||||
} catch (cleanupError: Exception) {
|
||||
error.addSuppressed(cleanupError)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
written = 0L
|
||||
openedDay = currentDay()
|
||||
val logs = files(grant).sortedBy { it.second }
|
||||
for ((uri, _) in logs.filter { it.first != document }
|
||||
.take((logs.size - MAX_LOG_FILES).coerceAtLeast(0))) {
|
||||
try {
|
||||
if (!DocumentsContract.deleteDocument(resolver, uri)) {
|
||||
throw IOException("Unable to remove an expired log file")
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w("DocumentLogs", "Unable to remove an expired log file", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun files(grant: Uri): List<Pair<Uri, String>> {
|
||||
val children = DocumentsContract.buildChildDocumentsUriUsingTree(grant, directoryId)
|
||||
val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME,
|
||||
Document.COLUMN_MIME_TYPE)
|
||||
return resolver.query(children, columns, null, null, null)?.use { cursor ->
|
||||
checkDocumentListing(cursor, "Unable to list logs", "The log directory is still loading")
|
||||
val entries = mutableListOf<Pair<Uri, String>>()
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE)) ==
|
||||
Document.MIME_TYPE_DIR) continue
|
||||
val name = cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DISPLAY_NAME))
|
||||
if (!LOG_NAME.matches(name)) continue
|
||||
val id = cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DOCUMENT_ID))
|
||||
entries.add(DocumentsContract.buildDocumentUriUsingTree(grant, id) to name)
|
||||
}
|
||||
entries
|
||||
} ?: throw IOException("Unable to list logs")
|
||||
}
|
||||
|
||||
fun exportTo(destination: Uri): Int {
|
||||
val uri = grant() ?: return 0
|
||||
check(hasPermission()) { "Log directory access was revoked" }
|
||||
val parent = DocumentsContract.buildDocumentUriUsingTree(
|
||||
destination, DocumentsContract.getTreeDocumentId(destination))
|
||||
val logs = files(uri)
|
||||
for ((source, name) in logs) {
|
||||
val target = DocumentsContract.createDocument(resolver, parent, "text/plain", name)
|
||||
?: throw IOException("Unable to create an exported log")
|
||||
val input = resolver.openInputStream(source)
|
||||
?: throw IOException("Unable to read log $name")
|
||||
input.use {
|
||||
val output = resolver.openOutputStream(target, "w")
|
||||
?: throw IOException("Unable to write log $name")
|
||||
output.use { destinationStream -> it.copyTo(destinationStream) }
|
||||
}
|
||||
}
|
||||
return logs.size
|
||||
}
|
||||
|
||||
private fun currentDay(): Long = System.currentTimeMillis() / TimeUnit.DAYS.toMillis(1)
|
||||
|
||||
companion object {
|
||||
const val AUTHORITY = "com.android.externalstorage.documents"
|
||||
const val PARENT_ID = "primary:Android/media"
|
||||
private const val LOG_GRANT = "log-folder"
|
||||
private const val GRANT_FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION or
|
||||
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
private const val MAX_LOG_BYTES = 16L * 1024 * 1024
|
||||
private const val MAX_LOG_FILES = 90
|
||||
private val LOG_NAME = Regex("rustdesk-[0-9]+-[0-9a-f-]{36}\\.txt")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.carriez.flutter_hbb
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.provider.DocumentsContract
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
internal class DocumentPicker(private val activity: Activity) {
|
||||
private var pending: Pair<MethodChannel.Result, Boolean>? = null
|
||||
private var pendingLogFolder: MethodChannel.Result? = null
|
||||
private val storage = (activity.application as MainApplication).documentStorage
|
||||
|
||||
fun handle(call: MethodCall, result: MethodChannel.Result): Boolean {
|
||||
when (call.method) {
|
||||
"document_require_log_folder" ->
|
||||
requireLogFolder(result, call.argument<Boolean>("checkOnly") == true)
|
||||
"document_workspace" -> if (call.argument<Boolean>("share") == true) {
|
||||
run(result) { storage.shareWorkspace() }
|
||||
} else {
|
||||
result.success((activity.getExternalFilesDir(null) ?: activity.filesDir).path)
|
||||
}
|
||||
"document_folder" -> pick(result, call.argument<Boolean>("share") == true)
|
||||
else -> return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun pick(result: MethodChannel.Result, share: Boolean) {
|
||||
if (pending != null || pendingLogFolder != null) {
|
||||
result.error("picker_in_progress", "Another document picker is already open", null)
|
||||
return
|
||||
}
|
||||
try {
|
||||
val intent = treePickerIntent("primary:Documents")
|
||||
pending = result to share
|
||||
activity.startActivityForResult(intent, REQUEST_DOCUMENT)
|
||||
} catch (error: Exception) {
|
||||
pending = null
|
||||
result.error("picker_unavailable", error.message, null)
|
||||
}
|
||||
}
|
||||
|
||||
fun onResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
|
||||
if (requestCode == REQUEST_LOG_FOLDER) {
|
||||
val result = pendingLogFolder ?: return true
|
||||
pendingLogFolder = null
|
||||
if (resultCode != Activity.RESULT_OK || data?.data == null) {
|
||||
result.success(false)
|
||||
} else {
|
||||
run(result) {
|
||||
storage.logs.select(requireNotNull(data.data), data.flags)
|
||||
true
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (requestCode != REQUEST_DOCUMENT) return false
|
||||
val (result, share) = pending ?: return true
|
||||
pending = null
|
||||
if (resultCode != Activity.RESULT_OK || data == null) {
|
||||
result.success(null)
|
||||
return true
|
||||
}
|
||||
run(result) {
|
||||
storage.select(requireNotNull(data.data), data.flags, share).toString()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun close() {
|
||||
pendingLogFolder?.error("picker_closed", "Log directory selection was interrupted", null)
|
||||
pendingLogFolder = null
|
||||
pending?.first?.error("picker_closed", "Document selection was interrupted", null)
|
||||
pending = null
|
||||
}
|
||||
|
||||
private fun run(result: MethodChannel.Result, action: () -> Any?) {
|
||||
thread {
|
||||
try {
|
||||
val value = action()
|
||||
activity.runOnUiThread { result.success(value) }
|
||||
} catch (error: Exception) {
|
||||
activity.runOnUiThread { result.error("document_failed", error.message, null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun requireLogFolder(result: MethodChannel.Result, checkOnly: Boolean) {
|
||||
if (pending != null || pendingLogFolder != null) {
|
||||
result.error("picker_in_progress", "Another document picker is already open", null)
|
||||
return
|
||||
}
|
||||
pendingLogFolder = result
|
||||
thread {
|
||||
val ready = runCatching { storage.logs.ensureReady() }
|
||||
activity.runOnUiThread { completeLogFolderCheck(result, ready, checkOnly) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun completeLogFolderCheck(
|
||||
result: MethodChannel.Result, ready: Result<Boolean>, checkOnly: Boolean
|
||||
) {
|
||||
if (pendingLogFolder !== result) return
|
||||
ready.fold(onSuccess = {
|
||||
if (it || checkOnly) {
|
||||
pendingLogFolder = null
|
||||
result.success(it)
|
||||
} else {
|
||||
pickLogFolder(result)
|
||||
}
|
||||
}, onFailure = {
|
||||
pendingLogFolder = null
|
||||
result.error("log_directory_failed", it.message, null)
|
||||
})
|
||||
}
|
||||
|
||||
private fun treePickerIntent(initialId: String): Intent =
|
||||
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or
|
||||
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
putExtra(DocumentsContract.EXTRA_INITIAL_URI,
|
||||
DocumentsContract.buildDocumentUri(DocumentLogs.AUTHORITY, initialId))
|
||||
}
|
||||
}
|
||||
|
||||
private fun pickLogFolder(result: MethodChannel.Result) {
|
||||
try {
|
||||
activity.startActivityForResult(treePickerIntent(DocumentLogs.PARENT_ID), REQUEST_LOG_FOLDER)
|
||||
} catch (error: Exception) {
|
||||
pendingLogFolder = null
|
||||
result.error("picker_unavailable", error.message, null)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_DOCUMENT = 4251
|
||||
private const val REQUEST_LOG_FOLDER = 4252
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.carriez.flutter_hbb
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.util.Base64
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
|
||||
private const val TREE_ROOT = "/@rustdesk/tree/"
|
||||
internal const val DOCUMENT_PREFS = "document-storage"
|
||||
internal const val DEFAULT_LOCATION = "default-location"
|
||||
private const val URI_FLAGS = Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
|
||||
private const val MIN_LOCATION_COMPONENTS = 2
|
||||
|
||||
internal fun documentRoot(uri: Uri): String =
|
||||
"$TREE_ROOT${Base64.encodeToString(uri.toString().toByteArray(Charsets.UTF_8), URI_FLAGS)}"
|
||||
|
||||
internal fun checkDocumentName(name: String): String {
|
||||
require(name.isNotEmpty() && name != "." && name != ".." &&
|
||||
!name.contains('/') && !name.contains('\\') && !name.contains('\u0000')) {
|
||||
"Invalid document name"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
internal fun checkDocumentListing(cursor: Cursor, errorMessage: String, loadingMessage: String) {
|
||||
val extras = cursor.extras
|
||||
extras.getString(DocumentsContract.EXTRA_ERROR)?.let {
|
||||
throw IOException("$errorMessage: $it")
|
||||
}
|
||||
if (extras.getBoolean(DocumentsContract.EXTRA_LOADING)) {
|
||||
throw IOException(loadingMessage)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun documentEntry(name: String, directory: Boolean, size: Long = 0): JSONObject =
|
||||
JSONObject().put("name", name).put("directory", directory)
|
||||
.put("size", size).put("modified", 0)
|
||||
|
||||
internal class DocumentStorage(private val context: Context) {
|
||||
private val prefs = context.getSharedPreferences(DOCUMENT_PREFS, Context.MODE_PRIVATE)
|
||||
private val descriptors = DocumentDescriptors()
|
||||
val logs = DocumentLogs(context)
|
||||
|
||||
fun home(): String? = prefs.getString(DEFAULT_LOCATION, null)
|
||||
|
||||
fun shareWorkspace(): String {
|
||||
check(prefs.edit().remove(DEFAULT_LOCATION).commit()) {
|
||||
"Unable to remember the shared folder"
|
||||
}
|
||||
return (context.getExternalFilesDir(null) ?: context.filesDir).path
|
||||
}
|
||||
|
||||
fun select(uri: Uri, flags: Int, share: Boolean): JSONObject {
|
||||
require(uri.scheme == "content") { "Invalid document selection" }
|
||||
val grants = flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or
|
||||
Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
|
||||
require(grants != 0) { "The selected location has no access grant" }
|
||||
context.contentResolver.takePersistableUriPermission(uri, grants)
|
||||
val root = documentRoot(uri)
|
||||
val backend = DocumentTree(context, uri, descriptors)
|
||||
val name = checkDocumentName(backend.rootName())
|
||||
val path = "$root/$name"
|
||||
if (share) {
|
||||
check(prefs.edit().putString(DEFAULT_LOCATION, path).commit()) {
|
||||
"Unable to remember the shared folder"
|
||||
}
|
||||
}
|
||||
return JSONObject().put("path", path).put("name", name)
|
||||
}
|
||||
|
||||
fun backend(path: String): DocumentTree {
|
||||
require(path.startsWith(TREE_ROOT)) { "Invalid document location" }
|
||||
val parts = path.removePrefix(TREE_ROOT).split('/')
|
||||
require(parts.size >= MIN_LOCATION_COMPONENTS) { "Invalid document location" }
|
||||
parts.forEach(::checkDocumentName)
|
||||
val uri = Uri.parse(String(Base64.decode(parts.first(), URI_FLAGS), Charsets.UTF_8))
|
||||
require(uri.scheme == "content") { "Invalid document URI" }
|
||||
val authorized =
|
||||
context.contentResolver.persistedUriPermissions.any { it.uri == uri && it.isReadPermission }
|
||||
check(authorized) {
|
||||
"Access to this location was revoked. Select it again on the Android device."
|
||||
}
|
||||
return DocumentTree(context, uri, descriptors)
|
||||
}
|
||||
|
||||
fun request(request: String): String = try {
|
||||
JSONObject().put("value", execute(JSONObject(request)) ?: JSONObject.NULL).toString()
|
||||
} catch (error: Exception) {
|
||||
JSONObject().put("error", error.message ?: error.javaClass.simpleName).toString()
|
||||
}
|
||||
|
||||
private fun execute(request: JSONObject): Any? {
|
||||
val operation = request.getString("op")
|
||||
if (operation == "home") return home()
|
||||
if (operation == "log_write") return logs.write(request.getString("message"))
|
||||
if (operation == "close") return descriptors.close(request)
|
||||
val path = request.getString("path")
|
||||
val backend = backend(path)
|
||||
return when (operation) {
|
||||
"allowed" -> true
|
||||
"list" -> backend.list(path)
|
||||
"stat" -> backend.stat(path)
|
||||
"open" -> backend.open(path)
|
||||
else -> mutate(request, backend)
|
||||
}
|
||||
}
|
||||
|
||||
private fun mutate(request: JSONObject, backend: DocumentTree): Any {
|
||||
val path = request.getString("path")
|
||||
return when (val operation = request.getString("op")) {
|
||||
"begin" -> backend.begin(path, request.getBoolean("overwrite"))
|
||||
"finish" -> backend.finish(request.getJSONObject("token")).let { true }
|
||||
"discard" -> backend.discard(request.getJSONObject("token")).let { true }
|
||||
"delete" -> backend.delete(path).let { true }
|
||||
"mkdir" -> backend.mkdir(path).let { true }
|
||||
"rename" -> backend.rename(path, checkDocumentName(request.getString("name"))).let { true }
|
||||
else -> throw IOException("Unsupported document operation: $operation")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.carriez.flutter_hbb
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.DocumentsContract.Document
|
||||
import android.webkit.MimeTypeMap
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.FileNotFoundException
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
internal class DocumentTree(
|
||||
context: Context,
|
||||
private val grant: Uri,
|
||||
private val descriptors: DocumentDescriptors
|
||||
) {
|
||||
private val root = documentRoot(grant)
|
||||
private val resolver = context.contentResolver
|
||||
private val rootUri: Uri get() = DocumentsContract.buildDocumentUriUsingTree(
|
||||
grant, DocumentsContract.getTreeDocumentId(grant))
|
||||
private val projection = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME,
|
||||
Document.COLUMN_MIME_TYPE, Document.COLUMN_SIZE, Document.COLUMN_LAST_MODIFIED)
|
||||
|
||||
fun rootName(): String = metadata(rootUri)?.getString("name")
|
||||
?: throw FileNotFoundException("The selected document no longer exists")
|
||||
|
||||
private fun metadata(uri: Uri): JSONObject? = resolver.query(uri, projection, null, null, null)?.use {
|
||||
if (!it.moveToFirst()) return@use null
|
||||
val directory = it.getString(MIME_COLUMN) == Document.MIME_TYPE_DIR
|
||||
val size = if (it.isNull(SIZE_COLUMN)) -1 else it.getLong(SIZE_COLUMN)
|
||||
documentEntry(it.getString(NAME_COLUMN), directory, size)
|
||||
.put("modified", it.getLong(MODIFIED_COLUMN) / MILLIS_PER_SECOND).put("uri", uri.toString())
|
||||
} ?: throw IOException("Unable to query the selected document")
|
||||
|
||||
private fun children(uri: Uri): List<Pair<Uri, JSONObject>> {
|
||||
val query = DocumentsContract.buildChildDocumentsUriUsingTree(
|
||||
grant, DocumentsContract.getDocumentId(uri))
|
||||
return resolver.query(query, projection, null, null, null)?.use { cursor ->
|
||||
checkDocumentListing(cursor, "Unable to list the selected folder",
|
||||
"The selected folder is still loading. Try again.")
|
||||
val entries = mutableListOf<Pair<Uri, JSONObject>>()
|
||||
while (cursor.moveToNext()) {
|
||||
val child = DocumentsContract.buildDocumentUriUsingTree(grant, cursor.getString(ID_COLUMN))
|
||||
val name = checkDocumentName(cursor.getString(NAME_COLUMN))
|
||||
val entry = documentEntry(name, cursor.getString(MIME_COLUMN) == Document.MIME_TYPE_DIR,
|
||||
if (cursor.isNull(SIZE_COLUMN)) -1 else cursor.getLong(SIZE_COLUMN))
|
||||
.put("modified", cursor.getLong(MODIFIED_COLUMN) / MILLIS_PER_SECOND)
|
||||
.put("uri", child.toString())
|
||||
entries.add(child to entry)
|
||||
}
|
||||
entries
|
||||
} ?: throw IOException("Unable to list the selected folder")
|
||||
}
|
||||
|
||||
private fun relative(path: String): List<String> {
|
||||
val parts = path.removePrefix("$root/").split('/')
|
||||
require(path.startsWith("$root/") && parts.first() == rootName()) {
|
||||
"The selected document was moved or renamed. Select it again."
|
||||
}
|
||||
parts.forEach(::checkDocumentName)
|
||||
return parts.drop(1)
|
||||
}
|
||||
|
||||
private fun resolve(path: String, createParents: Boolean = false): Uri? {
|
||||
var current = rootUri
|
||||
for (name in relative(path)) {
|
||||
val matches = children(current).filter { it.second.getString("name") == name }
|
||||
check(matches.size <= 1) { "The provider returned multiple documents named $name" }
|
||||
val child = matches.singleOrNull()
|
||||
current = child?.first ?: if (createParents) {
|
||||
val created = DocumentsContract.createDocument(resolver, current, Document.MIME_TYPE_DIR, name)
|
||||
?: throw IOException("Unable to create folder $name")
|
||||
check(metadata(created)?.getString("name") == name) {
|
||||
"The provider cannot preserve folder name: $name"
|
||||
}
|
||||
created
|
||||
} else return null
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
fun uri(path: String): Uri = resolve(path)
|
||||
?: throw FileNotFoundException("Document does not exist: $path")
|
||||
|
||||
fun list(path: String): JSONArray = JSONArray(children(uri(path)).map { it.second })
|
||||
|
||||
fun stat(path: String): JSONObject? = resolve(path)?.let(::metadata)
|
||||
|
||||
fun open(path: String): JSONObject = descriptors.open(
|
||||
resolver.openFileDescriptor(uri(path), "r") ?: throw IOException("Unable to open document"))
|
||||
|
||||
fun begin(path: String, overwrite: Boolean): JSONObject {
|
||||
val original = resolve(path)
|
||||
check(original == null || overwrite) { "Document overwrite requires confirmation" }
|
||||
require(original == null || metadata(original)?.getBoolean("directory") == false) {
|
||||
"Cannot replace a folder with a file"
|
||||
}
|
||||
val parent = resolve(path.substringBeforeLast('/'), true)
|
||||
?: throw FileNotFoundException("Destination folder no longer exists")
|
||||
val name = checkDocumentName(path.substringAfterLast('/'))
|
||||
val temporary = DocumentsContract.createDocument(resolver, parent, mime(name),
|
||||
temporaryName(name, "download"))
|
||||
?: throw IOException("Unable to create the receiving file")
|
||||
try {
|
||||
val descriptor = resolver.openFileDescriptor(temporary, "rw")
|
||||
?: throw IOException("Unable to open the receiving file")
|
||||
return descriptors.open(descriptor).put("uri", temporary.toString())
|
||||
.put("path", path).put("original", original?.toString() ?: JSONObject.NULL)
|
||||
} catch (error: Exception) {
|
||||
try {
|
||||
check(DocumentsContract.deleteDocument(resolver, temporary)) {
|
||||
"Unable to remove the receiving file"
|
||||
}
|
||||
} catch (cleanup: Exception) {
|
||||
error.addSuppressed(cleanup)
|
||||
throw IOException("${error.message ?: error.javaClass.simpleName}; " +
|
||||
"temporary file cleanup failed: ${cleanup.message}", error)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
fun finish(token: JSONObject) {
|
||||
val path = token.getString("path")
|
||||
val name = checkDocumentName(path.substringAfterLast('/'))
|
||||
val original = resolve(path)
|
||||
val expected = if (token.isNull("original")) null else token.getString("original")
|
||||
check(original?.toString() == expected) {
|
||||
"The destination changed during the transfer; the received data was retained"
|
||||
}
|
||||
val backup = original?.let { renameChecked(it, temporaryName(name, "backup")) }
|
||||
try {
|
||||
renameChecked(Uri.parse(token.getString("uri")), name)
|
||||
} catch (error: Exception) {
|
||||
if (backup != null) {
|
||||
try { renameChecked(backup, name) } catch (restore: Exception) {
|
||||
error.addSuppressed(restore)
|
||||
throw IOException("Publishing failed and the original remains in $backup: ${restore.message}", error)
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (backup != null && !DocumentsContract.deleteDocument(resolver, backup)) {
|
||||
throw IOException("File saved, but the previous copy could not be removed: $backup")
|
||||
}
|
||||
}
|
||||
|
||||
private fun renameChecked(uri: Uri, name: String): Uri {
|
||||
val renamed = DocumentsContract.renameDocument(resolver, uri, name)
|
||||
?: throw IOException("Unable to publish the received file; the partial file was retained")
|
||||
check(metadata(renamed)?.getString("name") == name) { "The provider changed the saved filename" }
|
||||
return renamed
|
||||
}
|
||||
|
||||
fun discard(token: JSONObject) {
|
||||
check(DocumentsContract.deleteDocument(resolver, Uri.parse(token.getString("uri")))) {
|
||||
"Unable to remove the canceled transfer"
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(path: String) {
|
||||
require(relative(path).isNotEmpty()) { "Cannot delete a shared root" }
|
||||
check(DocumentsContract.deleteDocument(resolver, uri(path))) { "Unable to delete document" }
|
||||
}
|
||||
|
||||
fun mkdir(path: String) {
|
||||
val created = resolve(path, true) ?: throw IOException("Unable to create folder")
|
||||
check(metadata(created)?.getBoolean("directory") == true) { "The destination is not a folder" }
|
||||
}
|
||||
|
||||
fun rename(path: String, name: String) {
|
||||
require(relative(path).isNotEmpty()) { "Cannot rename a shared root" }
|
||||
if (resolve(path.substringBeforeLast('/') + "/" + name) != null) throw IOException(EXISTS_MESSAGE)
|
||||
renameChecked(uri(path), name)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val ID_COLUMN = 0
|
||||
private const val NAME_COLUMN = 1
|
||||
private const val MIME_COLUMN = 2
|
||||
private const val SIZE_COLUMN = 3
|
||||
private const val MODIFIED_COLUMN = 4
|
||||
private const val MILLIS_PER_SECOND = 1000L
|
||||
const val EXISTS_MESSAGE = "A file already exists at the destination. Rename the file or select another folder."
|
||||
fun temporaryName(name: String, purpose: String): String {
|
||||
// Providers can append the MIME extension when renaming; preserve it for temporary files.
|
||||
val extension = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }
|
||||
return ".rustdesk-${UUID.randomUUID()}.$purpose$extension"
|
||||
}
|
||||
|
||||
fun mime(name: String): String = MimeTypeMap.getSingleton()
|
||||
.getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase())
|
||||
?: "application/octet-stream"
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,15 @@ const val WHEEL_BUTTON_UP = 34
|
||||
const val WHEEL_DOWN = 523331
|
||||
const val WHEEL_UP = 963
|
||||
|
||||
// src/common.rs MOUSE_TYPE_WHEEL: the controller sends a wheel tick as a
|
||||
// MouseEvent with these type bits and the scroll delta in y (y < 0 = down).
|
||||
const val MOUSE_TYPE_WHEEL = 3
|
||||
|
||||
// Wheel-tick travel for MOUSE_TYPE_WHEEL events. Three quarters of the legacy
|
||||
// WHEEL_STEP; tuned on real devices during review (the full 120px felt too
|
||||
// far per tick).
|
||||
const val MOUSE_WHEEL_STEP = 90
|
||||
|
||||
const val TOUCH_SCALE_START = 1
|
||||
const val TOUCH_SCALE = 2
|
||||
const val TOUCH_SCALE_END = 3
|
||||
@@ -102,6 +111,12 @@ class InputService : AccessibilityService() {
|
||||
|
||||
private val volumeController: VolumeController by lazy { VolumeController(applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager) }
|
||||
|
||||
/**
|
||||
* Handles a remote mouse event on the gesture path. [mask] is the
|
||||
* button/phase mask of the mouse protocol ([MOUSE_TYPE_WHEEL] ticks carry
|
||||
* the scroll delta in [_y] instead of a position), x/y the screen-space
|
||||
* position. Requires API 24 for the gesture APIs.
|
||||
*/
|
||||
@RequiresApi(Build.VERSION_CODES.N)
|
||||
fun onMouseInput(mask: Int, _x: Int, _y: Int) {
|
||||
val x = max(0, _x)
|
||||
@@ -184,6 +199,38 @@ class InputService : AccessibilityService() {
|
||||
return
|
||||
}
|
||||
|
||||
// The controller sends a wheel tick as a MouseEvent with the type bits
|
||||
// MOUSE_TYPE_WHEEL (src/common.rs) and the scroll delta in _y
|
||||
// (y < 0 = wheel down); the WHEEL_DOWN/WHEEL_UP masks below are legacy
|
||||
// values that current controllers never send. Gated to API 24+ like
|
||||
// the rest of the gesture path - below that, legacy devices take the
|
||||
// Shizuku backend or a no-op, not this class.
|
||||
if (mask == MOUSE_TYPE_WHEEL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
// A horizontal tick (the controller sends y = 0 when the
|
||||
// horizontal delta dominates) or a delta truncated to zero is not
|
||||
// a vertical swipe.
|
||||
if (_y == 0) {
|
||||
return
|
||||
}
|
||||
if (mouseY < MOUSE_WHEEL_STEP) {
|
||||
return
|
||||
}
|
||||
val path = Path()
|
||||
path.moveTo(mouseX.toFloat(), mouseY.toFloat())
|
||||
val deltaY = if (_y < 0) -MOUSE_WHEEL_STEP else MOUSE_WHEEL_STEP
|
||||
path.lineTo(mouseX.toFloat(), (mouseY + deltaY).toFloat())
|
||||
val stroke = GestureDescription.StrokeDescription(
|
||||
path,
|
||||
0,
|
||||
WHEEL_DURATION
|
||||
)
|
||||
val builder = GestureDescription.Builder()
|
||||
builder.addStroke(stroke)
|
||||
wheelActionsQueue.offer(builder.build())
|
||||
consumeWheelActions()
|
||||
return
|
||||
}
|
||||
|
||||
if (mask == WHEEL_DOWN) {
|
||||
if (mouseY < WHEEL_STEP) {
|
||||
return
|
||||
|
||||
@@ -63,7 +63,8 @@ class MainActivity : FlutterActivity() {
|
||||
data class ExportFiles(
|
||||
val sources: List<File>,
|
||||
val rejected: Int,
|
||||
val result: MethodChannel.Result
|
||||
val result: MethodChannel.Result,
|
||||
val documentLogs: Boolean = false
|
||||
) : PendingPicker()
|
||||
}
|
||||
|
||||
@@ -73,6 +74,7 @@ class MainActivity : FlutterActivity() {
|
||||
)
|
||||
|
||||
private var pendingPicker: PendingPicker? = null
|
||||
private val documentPicker by lazy { DocumentPicker(this) }
|
||||
|
||||
private var isAudioStart = false
|
||||
private val audioRecordHandle = AudioRecordHandle(this, { false }, { isAudioStart })
|
||||
@@ -127,6 +129,7 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (documentPicker.onResult(requestCode, resultCode, data)) return
|
||||
if (requestCode == REQ_IMPORT_FILES) {
|
||||
val pending = pendingPicker as? PendingPicker.ImportFiles ?: return
|
||||
pendingPicker = null
|
||||
@@ -223,6 +226,14 @@ class MainActivity : FlutterActivity() {
|
||||
Log.e(logTag, "Failed to export selected files", e)
|
||||
failed += pending.sources.size - processed
|
||||
}
|
||||
if (pending.documentLogs) {
|
||||
try {
|
||||
exported += (application as MainApplication).documentStorage.logs.exportTo(treeUri)
|
||||
} catch (error: Exception) {
|
||||
Log.e(logTag, "Failed to export document logs", error)
|
||||
failed++
|
||||
}
|
||||
}
|
||||
runOnUiThread {
|
||||
pending.result.success(mapOf("exported" to exported, "failed" to failed))
|
||||
}
|
||||
@@ -243,6 +254,7 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
documentPicker.close()
|
||||
Log.e(logTag, "onDestroy")
|
||||
// The process can outlive the UI whenever something keeps it alive:
|
||||
// MainService, or the accessibility InputService on its own. Only the
|
||||
@@ -275,6 +287,7 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
private fun initFlutterChannel(flutterMethodChannel: MethodChannel) {
|
||||
flutterMethodChannel.setMethodCallHandler { call, result ->
|
||||
if (documentPicker.handle(call, result)) return@setMethodCallHandler
|
||||
// make sure result will be invoked, otherwise flutter will await forever
|
||||
when (call.method) {
|
||||
"init_service" -> {
|
||||
@@ -614,19 +627,22 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
EXPORT_FILES -> {
|
||||
val paths = (call.arguments as? Map<*, *>)?.get("paths") as? List<*>
|
||||
if (paths.isNullOrEmpty()) {
|
||||
val documentLogs = (call.arguments as? Map<*, *>)?.get("documentLogs") == true
|
||||
if (paths == null || (paths.isEmpty() && !documentLogs)) {
|
||||
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()) {
|
||||
if (sources.isEmpty() && (!documentLogs ||
|
||||
!(application as MainApplication).documentStorage.logs.hasPermission())) {
|
||||
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)
|
||||
pendingPicker = PendingPicker.ExportFiles(
|
||||
sources, rejected, result, documentLogs = documentLogs)
|
||||
try {
|
||||
startActivityForResult(
|
||||
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
|
||||
|
||||
@@ -5,6 +5,11 @@ import android.util.Log
|
||||
import ffi.FFI
|
||||
|
||||
class MainApplication : Application() {
|
||||
internal val documentStorage by lazy { DocumentStorage(this) }
|
||||
|
||||
@androidx.annotation.Keep
|
||||
fun rustDocumentStorage(request: String): String = documentStorage.request(request)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MainApplication"
|
||||
}
|
||||
|
||||
+66
-57
@@ -154,7 +154,7 @@ prebuild)
|
||||
.github/workflows/bridge.yml)"
|
||||
|
||||
FLUTTER_BRIDGE_VERSION="$(yq -r \
|
||||
.env.FLUTTER_VERSION \
|
||||
'.jobs.generate_bridge.strategy.matrix.job[] | select(.["artifact-name"] == "bridge-artifact") | .["flutter-version"]' \
|
||||
.github/workflows/bridge.yml)"
|
||||
|
||||
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
|
||||
@@ -306,67 +306,69 @@ prebuild)
|
||||
|
||||
git apply res/fdroid/patches/*.patch
|
||||
|
||||
# If Flutter version used to generate bridge files differs from Flutter
|
||||
# version used to compile Rustdesk library, generate bridge using the
|
||||
# `FLUTTER_BRIDGE_VERSION` an restore the pubspec later
|
||||
# Generate bridge files using `FLUTTER_BRIDGE_VERSION`, which may differ
|
||||
# from the Flutter version used to compile RustDesk library, and restore
|
||||
# the pubspec later
|
||||
|
||||
if [ "${FLUTTER_VERSION}" != "${FLUTTER_BRIDGE_VERSION}" ]; then
|
||||
# Find first libclang.so and set BRIDGE_LLVM_PATH
|
||||
# Find first libclang.so and set BRIDGE_LLVM_PATH
|
||||
|
||||
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
|
||||
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
|
||||
|
||||
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
|
||||
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
|
||||
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
|
||||
|
||||
# Install Flutter bridge version
|
||||
|
||||
prepare_flutter "${FLUTTER_BRIDGE_VERSION}" "${HOME}/flutter"
|
||||
|
||||
# Save changes
|
||||
|
||||
git add .
|
||||
|
||||
# Edit pubspec to make flutter bridge version work
|
||||
|
||||
sed \
|
||||
-i \
|
||||
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
|
||||
flutter/pubspec.yaml
|
||||
|
||||
# Download Flutter dependencies
|
||||
|
||||
pushd flutter
|
||||
|
||||
flutter clean
|
||||
flutter packages pub get
|
||||
|
||||
popd # flutter
|
||||
|
||||
# Generate FFI bindings
|
||||
|
||||
flutter_rust_bridge_codegen \
|
||||
--rust-input ./src/flutter_ffi.rs \
|
||||
--dart-output ./flutter/lib/generated_bridge.dart \
|
||||
--llvm-path "${BRIDGE_LLVM_PATH}"
|
||||
|
||||
# Add bridge files to save-list
|
||||
|
||||
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
|
||||
|
||||
# Restore everything
|
||||
|
||||
git checkout '*'
|
||||
git clean -dffx
|
||||
git reset
|
||||
|
||||
unset BRIDGE_LLVM_PATH
|
||||
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
|
||||
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
|
||||
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
|
||||
|
||||
# Install Flutter bridge version
|
||||
|
||||
# Unbraced on purpose: F-Droid recipes rewrite the braced form with sed to
|
||||
# pin a version, but the bridge generator only works with the Flutter
|
||||
# version bridge.yml uses
|
||||
|
||||
prepare_flutter "$FLUTTER_BRIDGE_VERSION" "${HOME}/flutter"
|
||||
|
||||
# Save changes
|
||||
|
||||
git add .
|
||||
|
||||
# Edit pubspec to make flutter bridge version work
|
||||
|
||||
sed \
|
||||
-i \
|
||||
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
|
||||
flutter/pubspec.yaml
|
||||
|
||||
# Download Flutter dependencies
|
||||
|
||||
pushd flutter
|
||||
|
||||
flutter clean
|
||||
flutter packages pub get --enforce-lockfile
|
||||
|
||||
popd # flutter
|
||||
|
||||
# Generate FFI bindings
|
||||
|
||||
flutter_rust_bridge_codegen \
|
||||
--rust-input ./src/flutter_ffi.rs \
|
||||
--dart-output ./flutter/lib/generated_bridge.dart \
|
||||
--llvm-path "${BRIDGE_LLVM_PATH}"
|
||||
|
||||
# Add bridge files to save-list
|
||||
|
||||
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
|
||||
|
||||
# Restore everything
|
||||
|
||||
git checkout '*'
|
||||
git clean -dffx
|
||||
git reset
|
||||
|
||||
unset BRIDGE_LLVM_PATH
|
||||
|
||||
# Install Flutter version for RustDesk library build
|
||||
|
||||
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
|
||||
@@ -379,6 +381,13 @@ prebuild)
|
||||
flutter/android/build.gradle \
|
||||
flutter/android/app/build.gradle
|
||||
|
||||
# Gradle 8 / AGP 8 thrash in the default 1 GiB heap; raise it as CI does
|
||||
|
||||
sed \
|
||||
-i \
|
||||
-e 's/org.gradle.jvmargs=-Xmx1024M/org.gradle.jvmargs=-Xmx2g/g' \
|
||||
flutter/android/gradle.properties
|
||||
|
||||
# `firebase_analytics` is not in these files now, but we still keep the following lines.
|
||||
|
||||
sed \
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import UIKit
|
||||
import Flutter
|
||||
import AVFoundation
|
||||
|
||||
@main
|
||||
@objc class AppDelegate: FlutterAppDelegate {
|
||||
@@ -8,6 +9,12 @@ import Flutter
|
||||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
|
||||
) -> Bool {
|
||||
GeneratedPluginRegistrant.register(with: self)
|
||||
do {
|
||||
// Mix remote audio with other apps while still respecting silent mode.
|
||||
try AVAudioSession.sharedInstance().setCategory(.ambient)
|
||||
} catch {
|
||||
NSLog("Failed to configure audio mixing: %@", error.localizedDescription)
|
||||
}
|
||||
dummyMethodToEnforceBundling();
|
||||
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
|
||||
String _resolveApiServer({required String api, required String custom}) {
|
||||
final key = 'resolve-api-server:${jsonEncode([api, custom])}';
|
||||
final response = jsonDecode(bind.mainGetCommonSync(key: key));
|
||||
if (response['error'] != null) {
|
||||
throw FormatException('Failed to resolve API server: ${response['error']}');
|
||||
}
|
||||
return response['url'] as String;
|
||||
}
|
||||
|
||||
bool shouldWarnApiServer(String? apiServer) {
|
||||
final uri = Uri.tryParse(apiServer?.trim() ?? '');
|
||||
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
|
||||
return false;
|
||||
}
|
||||
return !const {'localhost', '127.0.0.1', '::1'}.contains(uri.host);
|
||||
}
|
||||
|
||||
class ApiServerWarning extends StatelessWidget {
|
||||
final TextEditingController controller;
|
||||
final TextEditingController idController;
|
||||
final String message;
|
||||
final String emptyMessage;
|
||||
final String Function({required String api, required String custom})
|
||||
resolveApiServer;
|
||||
|
||||
const ApiServerWarning({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.idController,
|
||||
required this.message,
|
||||
required this.emptyMessage,
|
||||
this.resolveApiServer = _resolveApiServer,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([controller, idController]),
|
||||
builder: (context, child) {
|
||||
final apiServer = controller.text;
|
||||
final idServer = idController.text;
|
||||
final String effectiveApiServer;
|
||||
try {
|
||||
effectiveApiServer =
|
||||
resolveApiServer(api: apiServer.trim(), custom: idServer.trim());
|
||||
} catch (error, stack) {
|
||||
FlutterError.reportError(FlutterErrorDetails(
|
||||
exception: error,
|
||||
stack: stack,
|
||||
context: ErrorDescription('while resolving the API server warning'),
|
||||
));
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (!shouldWarnApiServer(effectiveApiServer)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: Text(
|
||||
controller.text.trim().isEmpty ? emptyMessage : message,
|
||||
style: TextStyle(color: Colors.orange.shade700),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -271,11 +271,6 @@ class AllPeersLoader {
|
||||
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
|
||||
_updateOnlineState(evt);
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
bool applyLastOnlineStateForTesting(List<Peer> peers) {
|
||||
return _applyLastOnlineState(peers);
|
||||
}
|
||||
}
|
||||
|
||||
class AutocompletePeerTile extends StatefulWidget {
|
||||
|
||||
@@ -2278,9 +2278,12 @@ void changeBot({Function()? callback}) async {
|
||||
|
||||
void change2fa({Function()? callback}) async {
|
||||
if (bind.mainHasValid2FaSync()) {
|
||||
await bind.mainSetOption(key: "2fa", value: "");
|
||||
await bind.mainClearTrustedDevices();
|
||||
callback?.call();
|
||||
try {
|
||||
await bind.mainSetOption(key: "2fa", value: "");
|
||||
callback?.call();
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
return;
|
||||
}
|
||||
var new2fa = (await bind.mainGenerate2Fa());
|
||||
@@ -2795,23 +2798,48 @@ void confrimDeleteTrustedDevicesDialog(
|
||||
CommonConfirmDialog(gFFI.dialogManager, '${translate('Confirm Delete')}?',
|
||||
() async {
|
||||
if (selectedDevices.isEmpty) return;
|
||||
if (selectedDevices.length == trustedDevices.length) {
|
||||
await bind.mainClearTrustedDevices();
|
||||
trustedDevices.clear();
|
||||
selectedDevices.clear();
|
||||
} else {
|
||||
final json = jsonEncode(selectedDevices.map((e) => e.toList()).toList());
|
||||
await bind.mainRemoveTrustedDevices(json: json);
|
||||
trustedDevices.removeWhere((element) {
|
||||
return selectedDevices.contains(element.hwid);
|
||||
});
|
||||
selectedDevices.clear();
|
||||
try {
|
||||
if (selectedDevices.length == trustedDevices.length) {
|
||||
await bind.mainClearTrustedDevices();
|
||||
trustedDevices.clear();
|
||||
selectedDevices.clear();
|
||||
} else {
|
||||
final json = jsonEncode(selectedDevices.map((e) => e.toList()).toList());
|
||||
await bind.mainRemoveTrustedDevices(json: json);
|
||||
trustedDevices.removeWhere((element) {
|
||||
return selectedDevices.contains(element.recordId);
|
||||
});
|
||||
selectedDevices.clear();
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> renewTrustedDevice(
|
||||
TrustedDevice device,
|
||||
RxList<TrustedDevice> trustedDevices,
|
||||
RxList<Uint8List> selectedDevices) async {
|
||||
try {
|
||||
final json = jsonEncode([device.recordId.toList()]);
|
||||
await bind.mainRenewTrustedDevices(json: json);
|
||||
final result = await TrustedDevice.get();
|
||||
selectedDevices.clear();
|
||||
trustedDevices.assignAll(result);
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void manageTrustedDeviceDialog() async {
|
||||
RxList<TrustedDevice> trustedDevices = (await TrustedDevice.get()).obs;
|
||||
late final RxList<TrustedDevice> trustedDevices;
|
||||
try {
|
||||
trustedDevices = (await TrustedDevice.get()).obs;
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
return;
|
||||
}
|
||||
RxList<Uint8List> selectedDevices = RxList.empty();
|
||||
gFFI.dialogManager.show((setState, close, context) {
|
||||
return CustomAlertDialog(
|
||||
@@ -2837,25 +2865,67 @@ void manageTrustedDeviceDialog() async {
|
||||
});
|
||||
}
|
||||
|
||||
Widget trustedDeviceExpiration({
|
||||
required bool enabled,
|
||||
required VoidCallback onChanged,
|
||||
bool showLabel = true,
|
||||
}) {
|
||||
final period = bind.mainGetOptionSync(key: kOptionTrustedDeviceExpiration);
|
||||
const periods = ['1', '7', '30', '90', '0'];
|
||||
const dropdownHeight = 36.0;
|
||||
return Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
if (showLabel) Text(translate('Trust duration (days)')),
|
||||
SizedBox(
|
||||
width: isDesktop || isWebDesktop ? 140 : 100,
|
||||
height: dropdownHeight,
|
||||
child: ComboBox(
|
||||
keys: periods,
|
||||
values: ['1', '7', '30', '90', translate('Never')],
|
||||
initialKey: periods.contains(period) ? period : '90',
|
||||
enabled: enabled && !isOptionFixed(kOptionTrustedDeviceExpiration),
|
||||
onChanged: (value) async {
|
||||
try {
|
||||
await bind.mainSetOption(
|
||||
key: kOptionTrustedDeviceExpiration, value: value);
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
onChanged();
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class TrustedDevice {
|
||||
late final Uint8List hwid;
|
||||
late final Uint8List recordId;
|
||||
late final int time;
|
||||
late final int expiresAt;
|
||||
late final String id;
|
||||
late final String name;
|
||||
late final String platform;
|
||||
|
||||
TrustedDevice.fromJson(Map<String, dynamic> json) {
|
||||
final hwidList = json['hwid'] as List<dynamic>;
|
||||
hwid = Uint8List.fromList(hwidList.cast<int>());
|
||||
final recordIdList = json['record_id'] as List<dynamic>;
|
||||
recordId = Uint8List.fromList(recordIdList.cast<int>());
|
||||
time = json['time'];
|
||||
expiresAt = json['expires_at'];
|
||||
id = json['id'];
|
||||
name = json['name'];
|
||||
platform = json['platform'];
|
||||
}
|
||||
|
||||
String daysRemaining() {
|
||||
final expiry = time + 90 * 24 * 60 * 60 * 1000;
|
||||
final remaining = expiry - DateTime.now().millisecondsSinceEpoch;
|
||||
if (expiresAt == 0) return translate('Never');
|
||||
final remaining = expiresAt - DateTime.now().millisecondsSinceEpoch;
|
||||
if (remaining < 0) {
|
||||
return '0';
|
||||
}
|
||||
@@ -2864,18 +2934,11 @@ class TrustedDevice {
|
||||
|
||||
static Future<List<TrustedDevice>> get() async {
|
||||
final List<TrustedDevice> devices = List.empty(growable: true);
|
||||
try {
|
||||
final devicesJson = await bind.mainGetTrustedDevices();
|
||||
if (devicesJson.isNotEmpty) {
|
||||
final devicesList = json.decode(devicesJson);
|
||||
if (devicesList is List) {
|
||||
for (var device in devicesList) {
|
||||
devices.add(TrustedDevice.fromJson(device));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print(e.toString());
|
||||
final devicesJson = await bind.mainGetTrustedDevices();
|
||||
final result = json.decode(devicesJson) as Map<String, dynamic>;
|
||||
final devicesList = result['devices'] as List;
|
||||
for (final device in devicesList) {
|
||||
devices.add(TrustedDevice.fromJson(device));
|
||||
}
|
||||
devices.sort((a, b) => b.time.compareTo(a.time));
|
||||
return devices;
|
||||
@@ -2909,7 +2972,7 @@ Widget trustedDevicesTable(
|
||||
onChanged: (value) {
|
||||
if (value == true) {
|
||||
selectedDevices.clear();
|
||||
selectedDevices.addAll(devices.map((e) => e.hwid));
|
||||
selectedDevices.addAll(devices.map((e) => e.recordId));
|
||||
} else {
|
||||
selectedDevices.clear();
|
||||
}
|
||||
@@ -2923,21 +2986,30 @@ Widget trustedDevicesTable(
|
||||
rows: devices.map((device) {
|
||||
return DataRow(cells: [
|
||||
DataCell(Checkbox(
|
||||
value: selectedDevices.contains(device.hwid),
|
||||
value: selectedDevices.contains(device.recordId),
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
if (value) {
|
||||
selectedDevices.remove(device.hwid);
|
||||
selectedDevices.add(device.hwid);
|
||||
selectedDevices.remove(device.recordId);
|
||||
selectedDevices.add(device.recordId);
|
||||
} else {
|
||||
selectedDevices.remove(device.hwid);
|
||||
selectedDevices.remove(device.recordId);
|
||||
}
|
||||
},
|
||||
)),
|
||||
DataCell(Text(device.platform)),
|
||||
DataCell(Text(device.id)),
|
||||
DataCell(Text(device.name)),
|
||||
DataCell(Text(device.daysRemaining())),
|
||||
DataCell(Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(device.daysRemaining()),
|
||||
if (device.expiresAt != 0)
|
||||
IconButton(
|
||||
icon: Icon(Icons.refresh),
|
||||
tooltip: translate('Renew trust'),
|
||||
onPressed: () =>
|
||||
renewTrustedDevice(device, devices, selectedDevices),
|
||||
),
|
||||
])),
|
||||
]);
|
||||
}).toList(),
|
||||
)),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:bot_toast/bot_toast.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hbb/common/widgets/dialog.dart';
|
||||
@@ -62,6 +63,8 @@ class _PeerCardState extends State<_PeerCard>
|
||||
final PeerTabModel peerTabModel = Provider.of(context);
|
||||
final peer = super.widget.peer;
|
||||
return GestureDetector(
|
||||
// Web card actions have their own semantics; preserve pointer double-clicks.
|
||||
excludeFromSemantics: isWebDesktop,
|
||||
onDoubleTap: peerTabModel.multiSelectionMode
|
||||
? null
|
||||
: () => widget.connect(context, peer.id),
|
||||
@@ -423,7 +426,7 @@ class _PeerCardState extends State<_PeerCard>
|
||||
final PeerTabModel peerTabModel = Provider.of(context);
|
||||
final selected = peerTabModel.isPeerSelected(peer.id);
|
||||
if (peerTabModel.multiSelectionMode) {
|
||||
return Padding(
|
||||
final checkbox = Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: selected
|
||||
? Icon(
|
||||
@@ -432,7 +435,16 @@ class _PeerCardState extends State<_PeerCard>
|
||||
)
|
||||
: Icon(Icons.check_box_outline_blank),
|
||||
);
|
||||
return isWebDesktop
|
||||
? Semantics(
|
||||
container: true,
|
||||
label: formatID(peer.id),
|
||||
checked: selected,
|
||||
onTap: () => peerTabModel.select(peer),
|
||||
child: checkbox)
|
||||
: checkbox;
|
||||
} else {
|
||||
if (isWebDesktop) return _actionMoreWeb(peer);
|
||||
return InkWell(
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(12), child: Icon(Icons.more_vert)),
|
||||
@@ -457,19 +469,27 @@ class _PeerCardState extends State<_PeerCard>
|
||||
color: MyTheme.accent,
|
||||
)
|
||||
: Icon(Icons.check_box_outline_blank);
|
||||
final checkbox = isWebDesktop
|
||||
? Semantics(
|
||||
container: true,
|
||||
label: formatID(peer.id),
|
||||
checked: selected,
|
||||
onTap: () => peerTabModel.select(peer),
|
||||
child: icon)
|
||||
: icon;
|
||||
bool last = peerTabModel.isShiftDown && peer.id == peerTabModel.lastId;
|
||||
double right = isTile ? 4 : 0;
|
||||
if (last) {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: MyTheme.accent, width: 1)),
|
||||
child: icon,
|
||||
child: checkbox,
|
||||
).marginOnly(right: right);
|
||||
} else {
|
||||
return icon.marginOnly(right: right);
|
||||
return checkbox.marginOnly(right: right);
|
||||
}
|
||||
} else {
|
||||
return _actionMore(peer);
|
||||
return isWebDesktop ? _actionMoreWeb(peer) : _actionMore(peer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,6 +502,20 @@ class _PeerCardState extends State<_PeerCard>
|
||||
onPointerUp: (_) => _showPeerMenu(peer.id),
|
||||
child: build_more(context));
|
||||
|
||||
Widget _actionMoreWeb(Peer peer) => Semantics(
|
||||
container: true,
|
||||
button: true,
|
||||
label: translate('More'),
|
||||
child: Builder(
|
||||
builder: (context) => build_more(context, onTap: () {
|
||||
final box = context.findRenderObject() as RenderBox;
|
||||
final position =
|
||||
box.localToGlobal(box.size.center(Offset.zero));
|
||||
_menuPos = RelativeRect.fromLTRB(
|
||||
position.dx, position.dy, position.dx, position.dy);
|
||||
_showPeerMenu(peer.id);
|
||||
})));
|
||||
|
||||
bool _shouldBuildPasswordIcon(Peer peer) {
|
||||
if (gFFI.peerTabModel.currentTab != PeerTabIndex.ab.index) return false;
|
||||
if (gFFI.abModel.current.isPersonal()) return false;
|
||||
@@ -1474,11 +1508,12 @@ Widget getOnline(double rightPadding, bool online) {
|
||||
radius: 3, backgroundColor: online ? Colors.green : kColorWarn)));
|
||||
}
|
||||
|
||||
Widget build_more(BuildContext context, {bool invert = false}) {
|
||||
Widget build_more(BuildContext context,
|
||||
{bool invert = false, VoidCallback? onTap}) {
|
||||
final RxBool hover = false.obs;
|
||||
return InkWell(
|
||||
final button = InkWell(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
onTap: () {},
|
||||
onTap: onTap ?? () {},
|
||||
onHover: (value) => hover.value = value,
|
||||
child: Obx(() => CircleAvatar(
|
||||
radius: 14,
|
||||
@@ -1498,6 +1533,19 @@ Widget build_more(BuildContext context, {bool invert = false}) {
|
||||
.titleLarge
|
||||
?.color
|
||||
?.withOpacity(0.5)))));
|
||||
if (onTap == null) return button;
|
||||
// Serial taps preserve cancellation without waiting for the card's double tap.
|
||||
return RawGestureDetector(
|
||||
excludeFromSemantics: true,
|
||||
gestures: {
|
||||
SerialTapGestureRecognizer:
|
||||
GestureRecognizerFactoryWithHandlers<SerialTapGestureRecognizer>(
|
||||
() => SerialTapGestureRecognizer(
|
||||
allowedButtonsFilter: (buttons) =>
|
||||
buttons == kPrimaryButton),
|
||||
(recognizer) => recognizer.onSerialTapUp = (_) => onTap()),
|
||||
},
|
||||
child: button);
|
||||
}
|
||||
|
||||
class TagPainter extends CustomPainter {
|
||||
|
||||
@@ -21,6 +21,7 @@ import 'package:flutter_svg/flutter_svg.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:pull_down_button/pull_down_button.dart';
|
||||
import 'package:url_launcher/url_launcher_string.dart';
|
||||
|
||||
import '../../common.dart';
|
||||
import '../../models/platform_model.dart';
|
||||
@@ -549,6 +550,28 @@ class _PeerTabPageState extends State<PeerTabPage>
|
||||
});
|
||||
}
|
||||
|
||||
Widget _openWebConsole() {
|
||||
return _hoverAction(
|
||||
context: context,
|
||||
toolTip: translate('ab_web_console_tip'),
|
||||
child: Icon(
|
||||
Icons.open_in_new,
|
||||
size: 18,
|
||||
),
|
||||
onTap: () async {
|
||||
final url = await bind.mainGetApiServer();
|
||||
if (await canLaunchUrlString(url)) {
|
||||
launchUrlString(url);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bool _showWebConsole(PeerTabModel model) =>
|
||||
model.currentTab == PeerTabIndex.ab.index &&
|
||||
gFFI.userModel.isLogin &&
|
||||
!gFFI.abModel.legacyMode.value &&
|
||||
gFFI.abModel.current.canWrite();
|
||||
|
||||
List<Widget> _landscapeRightActions(BuildContext context) {
|
||||
final model = Provider.of<PeerTabModel>(context);
|
||||
return [
|
||||
@@ -566,6 +589,10 @@ class _PeerTabPageState extends State<PeerTabPage>
|
||||
offstage: model.currentTab == PeerTabIndex.recent.index,
|
||||
child: PeerSortDropdown(),
|
||||
),
|
||||
Offstage(
|
||||
offstage: !_showWebConsole(model),
|
||||
child: _openWebConsole(),
|
||||
),
|
||||
Offstage(
|
||||
offstage: model.currentTab != PeerTabIndex.ab.index,
|
||||
child: _toggleTags(),
|
||||
@@ -630,6 +657,7 @@ class _PeerTabPageState extends State<PeerTabPage>
|
||||
final List<Widget> dynamicActions = [
|
||||
if (model.currentTabCachedPeers.isNotEmpty) _createMultiSelection(),
|
||||
if (model.currentTab != PeerTabIndex.recent.index) PeerSortDropdown(),
|
||||
if (_showWebConsole(model)) _openWebConsole(),
|
||||
if (model.currentTab == PeerTabIndex.ab.index) _toggleTags()
|
||||
];
|
||||
final rightWidth = availableWidth -
|
||||
|
||||
@@ -184,6 +184,7 @@ const String kOptionAllowSyncClipboardBetweenSessions =
|
||||
const String kOptionEnableWebrtc = "enable-webrtc";
|
||||
const String kOptionRelayFallbackDelay = "relay-fallback-delay";
|
||||
const String kOptionEnableTrustedDevices = "enable-trusted-devices";
|
||||
const String kOptionTrustedDeviceExpiration = "trusted-device-expiration-days";
|
||||
const String kOptionShowVirtualMouse = "show-virtual-mouse";
|
||||
const String kOptionVirtualMouseScale = "virtual-mouse-scale";
|
||||
const String kOptionShowVirtualJoystick = "show-virtual-joystick";
|
||||
|
||||
@@ -1144,6 +1144,13 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
|
||||
message: translate("enable-trusted-devices-tip"),
|
||||
child: _OptionCheckBox(context, "Enable trusted devices",
|
||||
kOptionEnableTrustedDevices,
|
||||
optSetter: (key, value) async {
|
||||
try {
|
||||
await mainSetBoolOption(key, value);
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
},
|
||||
enabled: !locked, update: (v) {
|
||||
setState(() {});
|
||||
}),
|
||||
@@ -1161,7 +1168,21 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
|
||||
).marginOnly(left: 30);
|
||||
|
||||
return Column(
|
||||
children: [tfa, bot, trust],
|
||||
children: [
|
||||
tfa,
|
||||
bot,
|
||||
trust,
|
||||
if (mainGetBoolOptionSync(kOptionEnableTrustedDevices))
|
||||
trustedDeviceExpiration(
|
||||
enabled: !locked,
|
||||
onChanged: () {
|
||||
if (mounted) setState(() {});
|
||||
},
|
||||
).marginOnly(
|
||||
left: _kCheckBoxLeftMargin + 20 + _kContentHSubMargin,
|
||||
top: _kContentHMargin,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -497,7 +497,12 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
},
|
||||
onExit: (evt) =>
|
||||
widget._mouseFocusScope.value = MouseFocusScope.none,
|
||||
child: _buildFileList(context, _fileListScrollController),
|
||||
child: Focus(
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: _onFileListKeyEvent,
|
||||
child: _buildFileList(context, _fileListScrollController),
|
||||
),
|
||||
))
|
||||
],
|
||||
),
|
||||
@@ -1135,6 +1140,7 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
: "${entry.lastModified().toString().replaceAll(".000", "")} ";
|
||||
var secondaryPosition = RelativeRect.fromLTRB(0, 0, 0, 0);
|
||||
onTap() {
|
||||
_keyboardNode.requestFocus();
|
||||
final items = selectedItems;
|
||||
// handle double click
|
||||
if (_checkDoubleClick(entry)) {
|
||||
@@ -1363,6 +1369,102 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
debugPrint("focused on ${searchResult.first.name}");
|
||||
}
|
||||
|
||||
KeyEventResult _onFileListKeyEvent(FocusNode node, KeyEvent event) {
|
||||
// A focused child such as a sort header keeps its default keys, e.g.
|
||||
// Enter to sort.
|
||||
if (!_keyboardNode.hasPrimaryFocus) return KeyEventResult.ignored;
|
||||
for (final binding in _fileListKeyBindings().entries) {
|
||||
if (binding.key.accepts(event, HardwareKeyboard.instance)) {
|
||||
binding.value();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
Map<ShortcutActivator, VoidCallback> _fileListKeyBindings() {
|
||||
int all() => controller.directory.value.entries.length;
|
||||
return {
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
|
||||
_moveSelectionByKey(-1, false),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
|
||||
_moveSelectionByKey(1, false),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): () =>
|
||||
_moveSelectionByKey(-1, true),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): () =>
|
||||
_moveSelectionByKey(1, true),
|
||||
// Unhandled, they would move keyboard focus to the other pane.
|
||||
const SingleActivator(LogicalKeyboardKey.arrowLeft): () {},
|
||||
const SingleActivator(LogicalKeyboardKey.arrowRight): () {},
|
||||
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
|
||||
_moveSelectionByKey(_pageDelta(false), false),
|
||||
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
|
||||
_moveSelectionByKey(_pageDelta(true), false),
|
||||
const SingleActivator(LogicalKeyboardKey.home): () =>
|
||||
_moveSelectionByKey(-all(), false),
|
||||
const SingleActivator(LogicalKeyboardKey.end): () =>
|
||||
_moveSelectionByKey(all(), false),
|
||||
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): () =>
|
||||
_moveSelectionByKey(_pageDelta(false), true),
|
||||
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): () =>
|
||||
_moveSelectionByKey(_pageDelta(true), true),
|
||||
const SingleActivator(LogicalKeyboardKey.home, shift: true): () =>
|
||||
_moveSelectionByKey(-all(), true),
|
||||
const SingleActivator(LogicalKeyboardKey.end, shift: true): () =>
|
||||
_moveSelectionByKey(all(), true),
|
||||
const SingleActivator(LogicalKeyboardKey.enter): _openSelectedDirectory,
|
||||
const SingleActivator(LogicalKeyboardKey.numpadEnter):
|
||||
_openSelectedDirectory,
|
||||
};
|
||||
}
|
||||
|
||||
void _openSelectedDirectory() {
|
||||
final items = selectedItems.items;
|
||||
if (items.length != 1 || items.first.isFile) return;
|
||||
controller.openDirectory(items.first.path);
|
||||
selectedItems.clear();
|
||||
}
|
||||
|
||||
List<Entry> _filteredEntries() {
|
||||
final entries = controller.directory.value.entries;
|
||||
return _searchText.isNotEmpty
|
||||
? entries.where((element) {
|
||||
return element.name.contains(_searchText.value);
|
||||
}).toList(growable: false)
|
||||
: entries;
|
||||
}
|
||||
|
||||
int _pageDelta(bool down) {
|
||||
final entries = _filteredEntries();
|
||||
final items = selectedItems.items;
|
||||
final index = items.isEmpty ? -1 : entries.indexOf(items.last);
|
||||
final position = _fileListScrollController.position;
|
||||
final first = (position.pixels / kDesktopFileTransferRowHeight).ceil();
|
||||
final last = ((position.pixels + position.viewportDimension) /
|
||||
kDesktopFileTransferRowHeight)
|
||||
.floor() -
|
||||
1;
|
||||
return pageDelta(
|
||||
index >= 0 ? index : (down ? -1 : entries.length), first, last, down);
|
||||
}
|
||||
|
||||
void _moveSelectionByKey(int delta, bool extend) {
|
||||
final filteredEntries = _filteredEntries();
|
||||
final selection =
|
||||
navigateSelection(filteredEntries, selectedItems.items, delta, extend);
|
||||
if (selection.isEmpty) return;
|
||||
selectedItems.items.assignAll(selection.where((e) => !e.isDrive));
|
||||
final position = _fileListScrollController.position;
|
||||
final top =
|
||||
filteredEntries.indexOf(selection.last) * kDesktopFileTransferRowHeight;
|
||||
final bottom = top + kDesktopFileTransferRowHeight;
|
||||
if (top < position.pixels) {
|
||||
_fileListScrollController.jumpTo(top);
|
||||
} else if (bottom > position.pixels + position.viewportDimension) {
|
||||
_fileListScrollController.jumpTo(bottom - position.viewportDimension);
|
||||
}
|
||||
}
|
||||
|
||||
void _onSelectedChanged(SelectedItems selectedItems, List<Entry> entries,
|
||||
Entry entry, bool isLocal) {
|
||||
final isCtrlDown = RawKeyboard.instance.keysPressed
|
||||
@@ -1717,6 +1819,36 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
// }
|
||||
}
|
||||
|
||||
/// Selection after a navigation key moves it by [delta] rows. A shift range is
|
||||
/// returned ordered from its anchor to the moved end, so the first and last
|
||||
/// items of [selected] stand for those two ends on the next press without
|
||||
/// separate state.
|
||||
@visibleForTesting
|
||||
List<Entry> navigateSelection(
|
||||
List<Entry> entries, List<Entry> selected, int delta, bool extend) {
|
||||
if (entries.isEmpty) return [];
|
||||
final current = selected.isEmpty ? -1 : entries.indexOf(selected.last);
|
||||
// With nothing selected, moving down starts above the first row and moving
|
||||
// up below the last one, as the Sciter grid did.
|
||||
final lead = current >= 0 ? current : (delta > 0 ? -1 : entries.length);
|
||||
final next = (lead + delta).clamp(0, entries.length - 1);
|
||||
if (!extend || current < 0) return [entries[next]];
|
||||
final first = entries.indexOf(selected.first);
|
||||
final anchor = first < 0 ? current : first;
|
||||
final step = next < anchor ? -1 : 1;
|
||||
return [for (var i = anchor; i != next + step; i += step) entries[i]];
|
||||
}
|
||||
|
||||
/// Rows a PageUp/PageDown press moves from [lead] while rows [first]..[last]
|
||||
/// are fully visible: to that edge first, then a page further, as list views
|
||||
/// do.
|
||||
@visibleForTesting
|
||||
int pageDelta(int lead, int first, int last, bool down) {
|
||||
final page = max(1, last - first);
|
||||
if (down) return lead < last ? last - lead : page;
|
||||
return lead > first ? first - lead : -page;
|
||||
}
|
||||
|
||||
Widget buildWindowsThisPC(BuildContext context, [TextStyle? textStyle]) {
|
||||
final color = Theme.of(context).iconTheme.color?.withOpacity(0.7);
|
||||
return Row(children: [
|
||||
|
||||
@@ -62,12 +62,15 @@ 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(
|
||||
@@ -83,10 +86,33 @@ 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
|
||||
@@ -217,8 +243,9 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
||||
() => OutlinedButton.icon(
|
||||
icon: Icon(Icons.close_rounded, size: 16),
|
||||
label: Text(translate('Cancel')),
|
||||
onPressed:
|
||||
btnEnabled.value ? () => windowManager.close() : null,
|
||||
onPressed: cancelEnabled.value
|
||||
? () => windowManager.close()
|
||||
: null,
|
||||
style: buttonStyle,
|
||||
).marginOnly(right: 10),
|
||||
),
|
||||
@@ -253,6 +280,7 @@ 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';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class ListSearchActionListener extends StatelessWidget {
|
||||
final FocusNode node;
|
||||
@@ -22,7 +23,7 @@ class ListSearchActionListener extends StatelessWidget {
|
||||
autofocus: true,
|
||||
onKeyEvent: (kv) {
|
||||
final ch = kv.character;
|
||||
if (ch == null) {
|
||||
if (ch == null || LogicalKeyboardKey.isControlCharacter(ch)) {
|
||||
return;
|
||||
}
|
||||
final action = buffer.input(ch);
|
||||
|
||||
@@ -418,6 +418,13 @@ class _DesktopTabState extends State<DesktopTab>
|
||||
}
|
||||
}
|
||||
|
||||
// On Linux, GTK destroys the window on a close request unless prevent-close
|
||||
// is on. It is off for the cm and install windows, and onActiveWindowChanged()
|
||||
// turns it off to quit, so the window can no longer be saved or hidden.
|
||||
// https://github.com/rustdesk/rustdesk/issues/16512
|
||||
Future<bool> _isLinuxWindowClosed() async =>
|
||||
isLinux && isMainWindow && !await windowManager.isPreventClose();
|
||||
|
||||
@override
|
||||
void onWindowMoved() {
|
||||
_saveFrame();
|
||||
@@ -465,6 +472,8 @@ class _DesktopTabState extends State<DesktopTab>
|
||||
});
|
||||
}
|
||||
|
||||
if (await _isLinuxWindowClosed()) return;
|
||||
|
||||
await _saveFrame(flush: true);
|
||||
|
||||
// hide window on close
|
||||
@@ -472,6 +481,7 @@ class _DesktopTabState extends State<DesktopTab>
|
||||
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
|
||||
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
|
||||
}
|
||||
if (await _isLinuxWindowClosed()) return;
|
||||
// macOS specific workaround, the window is not hiding when in fullscreen.
|
||||
if (isMacOS && await windowManager.isFullScreen()) {
|
||||
await windowManager.setFullScreen(false);
|
||||
|
||||
@@ -7,36 +7,49 @@ import 'package:flutter_hbb/models/platform_model.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
final _isExtracting = false.obs;
|
||||
const _eventKeyUpdateMe = 'update-me';
|
||||
|
||||
void handleUpdate(String releasePageUrl) {
|
||||
_isExtracting.value = false;
|
||||
String downloadUrl = releasePageUrl.replaceAll('tag', 'download');
|
||||
String version = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
|
||||
final String downloadFile =
|
||||
bind.mainGetCommonSync(key: 'download-file-$version');
|
||||
if (downloadFile.startsWith('error:')) {
|
||||
final error = downloadFile.replaceFirst('error:', '');
|
||||
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
|
||||
releasePageUrl, gFFI.dialogManager);
|
||||
Future<void> _handleUpdateMe(
|
||||
String releasePageUrl, Map<String, dynamic> evt) async {
|
||||
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
|
||||
if (evt.containsKey('error')) {
|
||||
_showUpdateError(releasePageUrl, evt['error'] as String);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> handleUpdate(String releasePageUrl) async {
|
||||
final dialogClosed = _showVerifyingUpdate();
|
||||
final String? downloadUrl;
|
||||
try {
|
||||
downloadUrl = await waitForUpdateVerification(
|
||||
bind.mainGetCommon(key: 'verified-download-url-$releasePageUrl'),
|
||||
dialogClosed,
|
||||
);
|
||||
} catch (error) {
|
||||
_showUpdateError(releasePageUrl, error.toString());
|
||||
return;
|
||||
}
|
||||
if (downloadUrl == null) {
|
||||
return;
|
||||
}
|
||||
final verifiedDownloadUrl = downloadUrl;
|
||||
if (downloadUrl.startsWith('error:')) {
|
||||
_showUpdateError(releasePageUrl, downloadUrl.replaceFirst('error:', ''));
|
||||
return;
|
||||
}
|
||||
downloadUrl = '$downloadUrl/$downloadFile';
|
||||
|
||||
SimpleWrapper downloadId = SimpleWrapper('');
|
||||
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
|
||||
gFFI.dialogManager.dismissAll();
|
||||
gFFI.dialogManager.show((setState, close, context) {
|
||||
return CustomAlertDialog(
|
||||
title: Obx(() => Text(translate(_isExtracting.isTrue
|
||||
? 'Preparing for installation ...'
|
||||
: 'Downloading {$appName}'))),
|
||||
content:
|
||||
UpdateProgress(releasePageUrl, downloadUrl, downloadId, onCanceled)
|
||||
.marginSymmetric(horizontal: 8)
|
||||
.paddingOnly(top: 12),
|
||||
title: Text(translate('Downloading {$appName}')),
|
||||
content: UpdateProgress(
|
||||
releasePageUrl, verifiedDownloadUrl, downloadId, onCanceled)
|
||||
.marginSymmetric(horizontal: 8)
|
||||
.paddingOnly(top: 12),
|
||||
actions: [
|
||||
if (_isExtracting.isFalse) dialogButton(translate('Cancel'), onPressed: () async {
|
||||
dialogButton('Cancel', onPressed: () async {
|
||||
onCanceled.value();
|
||||
await bind.mainSetCommon(
|
||||
key: 'cancel-downloader', value: downloadId.value);
|
||||
@@ -56,6 +69,40 @@ void handleUpdate(String releasePageUrl) {
|
||||
});
|
||||
}
|
||||
|
||||
Future<T?> waitForUpdateVerification<T extends Object>(
|
||||
Future<T> verification,
|
||||
Future<void> dialogClosed,
|
||||
) async {
|
||||
final dialogClosedMarker = Object();
|
||||
final result = await Future.any<Object>([
|
||||
verification.then<Object>((value) => value),
|
||||
dialogClosed.then<Object>((_) => dialogClosedMarker),
|
||||
]);
|
||||
return identical(result, dialogClosedMarker) ? null : result as T;
|
||||
}
|
||||
|
||||
Future<void> _showVerifyingUpdate() async {
|
||||
gFFI.dialogManager.dismissAll();
|
||||
await gFFI.dialogManager.show<void>(
|
||||
(setState, close, context) => CustomAlertDialog(
|
||||
title: Text(translate('Preparing for installation ...')),
|
||||
content: const LinearProgressIndicator(),
|
||||
actions: [
|
||||
dialogButton('Close', onPressed: close, isOutline: true),
|
||||
],
|
||||
onCancel: close,
|
||||
),
|
||||
tag: 'verifying-update',
|
||||
);
|
||||
}
|
||||
|
||||
void _showUpdateError(String releasePageUrl, String error) {
|
||||
debugPrint('Update error: $error');
|
||||
gFFI.dialogManager.dismissAll();
|
||||
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
|
||||
releasePageUrl, gFFI.dialogManager);
|
||||
}
|
||||
|
||||
class UpdateProgress extends StatefulWidget {
|
||||
final String releasePageUrl;
|
||||
final String downloadUrl;
|
||||
@@ -74,9 +121,9 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
Timer? _timer;
|
||||
int? _totalSize;
|
||||
int _downloadedSize = 0;
|
||||
bool _downloadFinished = false;
|
||||
int _getDataFailedCount = 0;
|
||||
final String _eventKeyDownloadNewVersion = 'download-new-version';
|
||||
final String _eventKeyExtractUpdateDmg = 'extract-update-dmg';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -88,11 +135,6 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
|
||||
replace: true);
|
||||
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
|
||||
if (isMacOS) {
|
||||
platformFFI.registerEventHandler(_eventKeyExtractUpdateDmg,
|
||||
_eventKeyExtractUpdateDmg, handleExtractUpdateDmg,
|
||||
replace: true);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -100,10 +142,7 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
cancelQueryTimer();
|
||||
platformFFI.unregisterEventHandler(
|
||||
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
|
||||
if (isMacOS) {
|
||||
platformFFI.unregisterEventHandler(
|
||||
_eventKeyExtractUpdateDmg, _eventKeyExtractUpdateDmg);
|
||||
}
|
||||
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -128,35 +167,33 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
}
|
||||
}
|
||||
|
||||
// `isExtractDmg` is true when handling extract-update-dmg event.
|
||||
// It's a rare case that the dmg file is corrupted and cannot be extracted.
|
||||
void _onError(String error, {bool isExtractDmg = false}) {
|
||||
void _onError(String error) {
|
||||
cancelQueryTimer();
|
||||
|
||||
debugPrint(
|
||||
'${isExtractDmg ? "Extract" : "Download"} new version error: $error');
|
||||
debugPrint('Download new version error: $error');
|
||||
final msgBoxType = 'custom-nocancel-nook-hasclose';
|
||||
final msgBoxTitle = 'Error';
|
||||
final msgBoxText = 'download-new-version-failed-tip';
|
||||
final dialogManager = gFFI.dialogManager;
|
||||
final releasePageUrl = widget.releasePageUrl;
|
||||
|
||||
close() {
|
||||
dialogManager.dismissAll();
|
||||
}
|
||||
|
||||
jumplink() {
|
||||
launchUrl(Uri.parse(widget.releasePageUrl));
|
||||
launchUrl(Uri.parse(releasePageUrl));
|
||||
dialogManager.dismissAll();
|
||||
}
|
||||
|
||||
retry() {
|
||||
dialogManager.dismissAll();
|
||||
handleUpdate(widget.releasePageUrl);
|
||||
handleUpdate(releasePageUrl);
|
||||
}
|
||||
|
||||
final List<Widget> buttons = [
|
||||
dialogButton('Download', onPressed: jumplink),
|
||||
if (!isExtractDmg) dialogButton('Retry', onPressed: retry),
|
||||
dialogButton('Retry', onPressed: retry),
|
||||
dialogButton('Close', onPressed: close),
|
||||
];
|
||||
dialogManager.dismissAll();
|
||||
@@ -186,6 +223,8 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
}
|
||||
} else if (key == 'downloaded_size') {
|
||||
_downloadedSize = value as int;
|
||||
} else if (key == 'finished') {
|
||||
_downloadFinished = value as bool;
|
||||
} else if (key == 'error') {
|
||||
if (value != null) {
|
||||
err = value.toString();
|
||||
@@ -204,7 +243,9 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
if (err != '') {
|
||||
_onError(err);
|
||||
} else {
|
||||
if (_totalSize != null && _downloadedSize >= _totalSize!) {
|
||||
if (_downloadFinished &&
|
||||
_totalSize != null &&
|
||||
_downloadedSize >= _totalSize!) {
|
||||
cancelQueryTimer();
|
||||
bind.mainSetCommon(
|
||||
key: 'remove-downloader', value: widget.downloadId.value);
|
||||
@@ -212,13 +253,7 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
_onError('The download file size is 0.');
|
||||
} else {
|
||||
setState(() {});
|
||||
if (isMacOS) {
|
||||
bind.mainSetCommon(
|
||||
key: 'extract-update-dmg', value: widget.downloadUrl);
|
||||
_isExtracting.value = true;
|
||||
} else {
|
||||
updateMsgBox();
|
||||
}
|
||||
updateMsgBox();
|
||||
}
|
||||
} else {
|
||||
setState(() {});
|
||||
@@ -227,6 +262,8 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
}
|
||||
|
||||
void updateMsgBox() {
|
||||
final releasePageUrl = widget.releasePageUrl;
|
||||
final downloadUrl = widget.downloadUrl;
|
||||
msgBox(
|
||||
gFFI.sessionId,
|
||||
'custom-nocancel',
|
||||
@@ -234,30 +271,30 @@ class UpdateProgressState extends State<UpdateProgress> {
|
||||
'{$appName}-to-update-tip',
|
||||
'',
|
||||
gFFI.dialogManager,
|
||||
onSubmit: () {
|
||||
onSubmit: () async {
|
||||
debugPrint('Downloaded, update to new version now');
|
||||
bind.mainSetCommon(key: 'update-me', value: widget.downloadUrl);
|
||||
platformFFI.registerEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe,
|
||||
(evt) => _handleUpdateMe(releasePageUrl, evt),
|
||||
replace: true);
|
||||
try {
|
||||
await bind.mainSetCommon(key: 'update-me', value: downloadUrl);
|
||||
} catch (error) {
|
||||
platformFFI.unregisterEventHandler(
|
||||
_eventKeyUpdateMe, _eventKeyUpdateMe);
|
||||
_showUpdateError(releasePageUrl, error.toString());
|
||||
}
|
||||
},
|
||||
submitTimeout: 5,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> handleExtractUpdateDmg(Map<String, dynamic> evt) async {
|
||||
_isExtracting.value = false;
|
||||
if (evt.containsKey('err') && (evt['err'] as String).isNotEmpty) {
|
||||
_onError(evt['err'] as String, isExtractDmg: true);
|
||||
} else {
|
||||
updateMsgBox();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
getValue() => _totalSize == null
|
||||
? 0.0
|
||||
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
|
||||
return LinearProgressIndicator(
|
||||
value: _isExtracting.isTrue ? null : getValue(),
|
||||
value: getValue(),
|
||||
minHeight: 20,
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
backgroundColor: Colors.grey[300],
|
||||
|
||||
@@ -577,6 +577,8 @@ _registerEventHandler() {
|
||||
|
||||
Widget keyListenerBuilder(BuildContext context, Widget? child) {
|
||||
return RawKeyboardListener(
|
||||
// Keep this keyboard-only wrapper from taking focus away from web inputs.
|
||||
includeSemantics: !isWeb,
|
||||
// `skipTraversal: isWeb` is to fix "Bad state: RenderBox was not laid out: minified:aeL#c19e4"
|
||||
focusNode: FocusNode(skipTraversal: isWeb),
|
||||
child: child ?? Container(),
|
||||
|
||||
@@ -10,6 +10,7 @@ import 'package:toggle_switch/toggle_switch.dart';
|
||||
import '../../common.dart';
|
||||
import '../../common/widgets/dialog.dart';
|
||||
import '../../consts.dart';
|
||||
import '../../utils/android_documents.dart';
|
||||
|
||||
class FileManagerPage extends StatefulWidget {
|
||||
FileManagerPage(
|
||||
@@ -142,6 +143,29 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _changeLocalStorage({required bool workspace}) async {
|
||||
try {
|
||||
final path = workspace
|
||||
? await AndroidDocuments.workspace()
|
||||
: (await AndroidDocuments.selectFolder())?['path'] as String?;
|
||||
if (path == null || !mounted) return;
|
||||
final previousHome = model.localController.homePath;
|
||||
model.localController.homePath = path;
|
||||
try {
|
||||
if (await model.localController.openDirectory(path, isBack: true)) {
|
||||
model.localController.history.clear();
|
||||
} else {
|
||||
model.localController.homePath = previousHome;
|
||||
}
|
||||
} catch (_) {
|
||||
model.localController.homePath = previousHome;
|
||||
rethrow;
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exportFile(Entry entry) async {
|
||||
try {
|
||||
final exported = await _runAndroidDocumentPicker(() => gFFI
|
||||
@@ -206,9 +230,11 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
}
|
||||
|
||||
Future<void> _exportLogs() async {
|
||||
final home = currentFileController.homePath;
|
||||
if (home.isEmpty) {
|
||||
showToast(translate('Failed'));
|
||||
final String home;
|
||||
try {
|
||||
home = await AndroidDocuments.workspace();
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
return;
|
||||
}
|
||||
final appDir = PathUtil.join(home, appName, false);
|
||||
@@ -216,22 +242,25 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
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);
|
||||
await _exportPaths(paths, includeDocumentLogs: true);
|
||||
}
|
||||
|
||||
Future<void> _exportPaths(Iterable<String> paths) async {
|
||||
Future<void> _exportPaths(Iterable<String> paths,
|
||||
{bool includeDocumentLogs = false}) async {
|
||||
try {
|
||||
final result = await _runAndroidDocumentPicker(() =>
|
||||
gFFI.invokeMethodWithResult<Map<dynamic, dynamic>>(
|
||||
AndroidChannel.kExportFiles, {'paths': paths.toList()}));
|
||||
final result = await _runAndroidDocumentPicker(() => gFFI
|
||||
.invokeMethodWithResult<Map<dynamic, dynamic>>(
|
||||
AndroidChannel.kExportFiles, {
|
||||
'paths': paths.toList(),
|
||||
if (includeDocumentLogs) 'documentLogs': true,
|
||||
}));
|
||||
if (result == null) return;
|
||||
final exported = result['exported'] as int? ?? 0;
|
||||
final failed = result['failed'] as int? ?? 0;
|
||||
if (failed > 0) {
|
||||
if (includeDocumentLogs && exported > 0 && failed > 0) {
|
||||
showToast('${translate('Successful')}: $exported, '
|
||||
'${translate('Failed')}: $failed');
|
||||
} else if (failed > 0 || (includeDocumentLogs && exported == 0)) {
|
||||
showToast(translate('Failed'));
|
||||
} else if (exported > 0) {
|
||||
showToast(translate('Successful'));
|
||||
@@ -317,6 +346,31 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
icon: Icon(Icons.more_vert),
|
||||
itemBuilder: (context) {
|
||||
return [
|
||||
if (isAndroid && showLocal) ...[
|
||||
PopupMenuItem(
|
||||
value: 'workspace',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.storage_outlined,
|
||||
color: Theme.of(context).iconTheme.color),
|
||||
SizedBox(width: 5),
|
||||
Text(translate('RustDesk storage')),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'choose_folder',
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.folder_open_outlined,
|
||||
color: Theme.of(context).iconTheme.color),
|
||||
SizedBox(width: 5),
|
||||
Text('${translate('Other folders')}…'),
|
||||
],
|
||||
),
|
||||
),
|
||||
const PopupMenuDivider(),
|
||||
],
|
||||
PopupMenuItem(
|
||||
child: Row(
|
||||
children: [
|
||||
@@ -328,7 +382,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
),
|
||||
value: "refresh",
|
||||
),
|
||||
if (isAndroid)
|
||||
if (isAndroid && !AndroidDocuments.isPath(currentDir.path))
|
||||
PopupMenuItem(
|
||||
enabled: showLocal && currentDir.path.isNotEmpty,
|
||||
value: "import",
|
||||
@@ -341,7 +395,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
],
|
||||
),
|
||||
),
|
||||
if (isAndroid)
|
||||
if (isAndroid && !AndroidDocuments.isPath(currentDir.path))
|
||||
PopupMenuItem(
|
||||
enabled: showLocal && currentDir.path.isNotEmpty,
|
||||
value: "import_folder",
|
||||
@@ -409,7 +463,9 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
];
|
||||
},
|
||||
onSelected: (v) {
|
||||
if (v == "refresh") {
|
||||
if (v == 'workspace' || v == 'choose_folder') {
|
||||
_changeLocalStorage(workspace: v == 'workspace');
|
||||
} else if (v == "refresh") {
|
||||
currentFileController.refresh();
|
||||
} else if (v == "import") {
|
||||
_importFiles();
|
||||
@@ -515,6 +571,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
|
||||
},
|
||||
actions: [
|
||||
if (isAndroid &&
|
||||
!AndroidDocuments.isPath(currentDir.path) &&
|
||||
selectedItems?.isLocal == true &&
|
||||
selectedItems?.items.isNotEmpty == true) ...[
|
||||
if (selectedItems!.items.length == 1 &&
|
||||
@@ -900,7 +957,7 @@ class _FileManagerViewState extends State<FileManagerView> {
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(30, 5, 30, 0),
|
||||
child: Text(
|
||||
controller.directory.value.path,
|
||||
AndroidDocuments.displayPath(controller.directory.value.path),
|
||||
style: TextStyle(color: MyTheme.darkGray),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -377,6 +377,10 @@ 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) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import '../../common/widgets/dialog.dart';
|
||||
import '../../consts.dart';
|
||||
import '../../models/platform_model.dart';
|
||||
import '../../models/server_model.dart';
|
||||
import '../../utils/android_documents.dart';
|
||||
import 'home_page.dart';
|
||||
|
||||
class ServerPage extends StatefulWidget implements PageShape {
|
||||
@@ -573,6 +574,44 @@ class PermissionChecker extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _PermissionCheckerState extends State<PermissionChecker> {
|
||||
static const _folderOptionIndent = 16.0;
|
||||
|
||||
Future<void> _selectFolder() async {
|
||||
try {
|
||||
final workspace = await gFFI.dialogManager.show<bool>(
|
||||
(_, close, __) => CustomAlertDialog(
|
||||
title: Text(translate('Change Path')),
|
||||
content: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
ListTile(
|
||||
title: Text(translate('RustDesk storage')),
|
||||
onTap: () => close(true),
|
||||
),
|
||||
ListTile(
|
||||
title: Text('${translate('Other folders')}…'),
|
||||
onTap: () => close(false),
|
||||
),
|
||||
]),
|
||||
),
|
||||
backDismiss: true,
|
||||
clickMaskDismiss: true);
|
||||
if (workspace == null) return;
|
||||
if (workspace) {
|
||||
showToast(await AndroidDocuments.workspace(share: true));
|
||||
await bind.setLocalFlutterOption(
|
||||
k: 'android-file-transfer-folder-setup', v: 'Y');
|
||||
return;
|
||||
}
|
||||
final selected = await AndroidDocuments.selectFolder(share: true);
|
||||
if (selected != null) {
|
||||
await bind.setLocalFlutterOption(
|
||||
k: 'android-file-transfer-folder-setup', v: 'Y');
|
||||
showToast(AndroidDocuments.displayPath(selected['path'] as String));
|
||||
}
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final serverModel = Provider.of<ServerModel>(context);
|
||||
@@ -620,6 +659,19 @@ class _PermissionCheckerState extends State<PermissionChecker> {
|
||||
serverModel.toggleFile,
|
||||
enabled: !permissionChangeLocked,
|
||||
),
|
||||
if (isAndroid &&
|
||||
!bind.isDisableSettings() &&
|
||||
!bind.isOutgoingOnly() &&
|
||||
bind.mainGetBuildinOption(key: kOptionHideSecuritySetting) != 'Y')
|
||||
ListTile(
|
||||
dense: true,
|
||||
contentPadding:
|
||||
const EdgeInsetsDirectional.only(start: _folderOptionIndent),
|
||||
title: Text(translate('Change Path')),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
enabled: !permissionChangeLocked,
|
||||
onTap: _selectFolder,
|
||||
),
|
||||
hasAudioPermission
|
||||
? PermissionRow(translate("Audio Capture"), serverModel.audioOk,
|
||||
serverModel.toggleAudio,
|
||||
|
||||
@@ -359,12 +359,28 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
|
||||
onToggle: isOptionFixed(kOptionEnableTrustedDevices)
|
||||
? null
|
||||
: (v) async {
|
||||
mainSetBoolOption(kOptionEnableTrustedDevices, v);
|
||||
setState(() {
|
||||
_enableTrustedDevices = v;
|
||||
});
|
||||
try {
|
||||
await mainSetBoolOption(kOptionEnableTrustedDevices, v);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_enableTrustedDevices = v;
|
||||
});
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
}
|
||||
},
|
||||
),
|
||||
if (enable2fa && _enableTrustedDevices)
|
||||
SettingsTile(
|
||||
title: Text(translate('Trust duration (days)')),
|
||||
trailing: trustedDeviceExpiration(
|
||||
enabled: true,
|
||||
showLabel: false,
|
||||
onChanged: () {
|
||||
if (mounted) setState(() {});
|
||||
},
|
||||
),
|
||||
),
|
||||
if (enable2fa && _enableTrustedDevices)
|
||||
SettingsTile(
|
||||
title: Text(translate('Manage trusted devices')),
|
||||
|
||||
@@ -11,10 +11,3 @@ const terminalKeyboardKeySpacing = 2.0;
|
||||
|
||||
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
|
||||
const terminalKeyboardRow3TrailingPlaceholderCount = 2;
|
||||
|
||||
/// Returns the fixed width occupied by a row of equally sized key slots.
|
||||
double terminalKeyboardRowWidth(int slotCount) {
|
||||
if (slotCount <= 0) return 0;
|
||||
return slotCount * terminalKeyboardKeyWidth +
|
||||
(slotCount - 1) * terminalKeyboardKeySpacing;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../common.dart';
|
||||
import '../../consts.dart';
|
||||
import '../../models/model.dart';
|
||||
import '../../models/platform_model.dart';
|
||||
import '../../utils/android_documents.dart';
|
||||
|
||||
const _setupOption = 'android-file-transfer-folder-setup';
|
||||
const _folderChoicePadding = EdgeInsets.fromLTRB(12, 12, 12, 0);
|
||||
const _folderChoiceSpacing = 4.0;
|
||||
|
||||
enum _FolderChoice { workspace, other, skip }
|
||||
|
||||
Future<bool> showAndroidFileTransferSetup(FFI ffi) async {
|
||||
if (bind.getLocalFlutterOption(k: _setupOption) == 'Y' ||
|
||||
!_canConfigureSharedFolder(ffi)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
final choice = await ffi.dialogManager.show<_FolderChoice>(
|
||||
(_, close, __) => _setupDialog(close),
|
||||
backDismiss: true,
|
||||
forceGlobal: true,
|
||||
);
|
||||
if (choice == null) return false;
|
||||
switch (choice) {
|
||||
case _FolderChoice.workspace:
|
||||
await AndroidDocuments.workspace(share: true);
|
||||
break;
|
||||
case _FolderChoice.other:
|
||||
if (await AndroidDocuments.selectFolder(share: true) == null) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case _FolderChoice.skip:
|
||||
break;
|
||||
}
|
||||
await bind.setLocalFlutterOption(k: _setupOption, v: 'Y');
|
||||
return true;
|
||||
} catch (error) {
|
||||
showToast(error.toString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _canConfigureSharedFolder(FFI ffi) =>
|
||||
!bind.isOutgoingOnly() &&
|
||||
!bind.isDisableSettings() &&
|
||||
bind.mainGetBuildinOption(key: kOptionHideSecuritySetting) != 'Y' &&
|
||||
(!ffi.serverModel.clients.any((client) => !client.disconnected) ||
|
||||
option2bool(
|
||||
kOptionEnablePermChangeInAcceptWindow,
|
||||
bind.mainGetBuildinOption(
|
||||
key: kOptionEnablePermChangeInAcceptWindow)));
|
||||
|
||||
CustomAlertDialog _setupDialog(void Function([dynamic]) close) {
|
||||
final choiceStyle = OutlinedButton.styleFrom(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
minimumSize: const Size(0, kMinInteractiveDimension),
|
||||
);
|
||||
return CustomAlertDialog(
|
||||
title: Text(translate('Transfer file')),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(translate('Choose which folder remote devices can access.')),
|
||||
Padding(
|
||||
padding: _folderChoicePadding,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
OutlinedButton(
|
||||
style: choiceStyle,
|
||||
onPressed: () => close(_FolderChoice.workspace),
|
||||
child: Text(translate('RustDesk storage')),
|
||||
),
|
||||
const SizedBox(height: _folderChoiceSpacing),
|
||||
OutlinedButton(
|
||||
style: choiceStyle,
|
||||
onPressed: () => close(_FolderChoice.other),
|
||||
child: Text('${translate('Other folders')}…'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => close(_FolderChoice.skip),
|
||||
child: Text(translate('Skip')),
|
||||
),
|
||||
],
|
||||
onCancel: close,
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
|
||||
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
|
||||
import 'package:flutter_hbb/common/widgets/toolbar.dart';
|
||||
import 'package:get/get.dart';
|
||||
@@ -69,6 +70,8 @@ void showServerSettingsWithValue(
|
||||
ServerConfig serverConfig,
|
||||
OverlayDialogManager dialogManager,
|
||||
void Function(VoidCallback)? upSetState) async {
|
||||
const labelWidth = 120.0;
|
||||
const labelSpacing = 8.0;
|
||||
var isInProgress = false;
|
||||
final idCtrl = TextEditingController(text: serverConfig.idServer);
|
||||
final relayCtrl = TextEditingController(text: serverConfig.relayServer);
|
||||
@@ -112,10 +115,10 @@ void showServerSettingsWithValue(
|
||||
return Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 120,
|
||||
width: labelWidth,
|
||||
child: Text(label),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
SizedBox(width: labelSpacing),
|
||||
Expanded(
|
||||
child: serverSettingsTextFormField(
|
||||
label: label,
|
||||
@@ -175,6 +178,17 @@ void showServerSettingsWithValue(
|
||||
return null;
|
||||
},
|
||||
),
|
||||
Padding(
|
||||
padding: EdgeInsetsDirectional.only(
|
||||
start: isDesktop || isWeb ? labelWidth + labelSpacing : 0,
|
||||
),
|
||||
child: ApiServerWarning(
|
||||
controller: apiCtrl,
|
||||
idController: idCtrl,
|
||||
message: translate('api_server_connection_tip'),
|
||||
emptyMessage: translate('api_server_empty_tip'),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
buildField('Key', keyCtrl, ''),
|
||||
if (isInProgress)
|
||||
|
||||
@@ -372,6 +372,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
Offset _position = Offset.zero;
|
||||
bool _isInitialized = false;
|
||||
bool _isDown = false;
|
||||
Object? _activePress;
|
||||
bool _remoteButtonDown = false;
|
||||
Rect? _lastBlockedRect;
|
||||
|
||||
Orientation? _previousOrientation;
|
||||
@@ -398,6 +400,11 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_activePress = null;
|
||||
if (_remoteButtonDown) {
|
||||
_remoteButtonDown = false;
|
||||
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||
}
|
||||
if (_lastBlockedRect != null) {
|
||||
_cursorModel.removeBlockedRect(_lastBlockedRect!);
|
||||
}
|
||||
@@ -569,6 +576,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
child: Listener(
|
||||
onPointerMove: _onBodyPointerMoveUpdate,
|
||||
onPointerDown: (event) async {
|
||||
final press = Object();
|
||||
_activePress = press;
|
||||
_isDragging = false;
|
||||
setState(() {
|
||||
_isDown = true;
|
||||
@@ -579,6 +588,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
isSpecialHoldDragActive = true;
|
||||
() async {
|
||||
await _cursorModel.syncCursorPosition();
|
||||
if (!mounted || !identical(_activePress, press)) return;
|
||||
_remoteButtonDown = true;
|
||||
await _inputModel
|
||||
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||
}();
|
||||
@@ -586,6 +597,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
});
|
||||
},
|
||||
onPointerUp: (event) {
|
||||
if (!mounted) return;
|
||||
_activePress = null;
|
||||
_cursorModel.blockEvents = false;
|
||||
setState(() {
|
||||
_isDown = false;
|
||||
@@ -604,8 +617,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
}));
|
||||
} else {
|
||||
// If it's not a quick tap, it could be a hold or drag.
|
||||
// If it was a hold, isSpecialHoldDragActive is true.
|
||||
if (isSpecialHoldDragActive) {
|
||||
if (_remoteButtonDown) {
|
||||
_remoteButtonDown = false;
|
||||
_inputModel
|
||||
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||
}
|
||||
@@ -617,13 +630,16 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
||||
isSpecialHoldDragActive = false;
|
||||
},
|
||||
onPointerCancel: (event) {
|
||||
if (!mounted) return;
|
||||
_activePress = null;
|
||||
_cursorModel.blockEvents = false;
|
||||
setState(() {
|
||||
_isDown = false;
|
||||
});
|
||||
_tapDownTimer?.cancel();
|
||||
_tapDownTimer = null;
|
||||
if (isSpecialHoldDragActive) {
|
||||
if (_remoteButtonDown) {
|
||||
_remoteButtonDown = false;
|
||||
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||
}
|
||||
isSpecialHoldDragActive = false;
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/common/widgets/dialog.dart';
|
||||
import 'package:flutter_hbb/utils/download_paths.dart';
|
||||
import 'package:flutter_hbb/utils/event_loop.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
@@ -11,6 +12,7 @@ import 'package:flutter_hbb/web/dummy.dart'
|
||||
if (dart.library.html) 'package:flutter_hbb/web/web_unique.dart';
|
||||
|
||||
import '../consts.dart';
|
||||
import '../utils/android_documents.dart';
|
||||
import 'model.dart';
|
||||
import 'platform_model.dart';
|
||||
|
||||
@@ -383,6 +385,7 @@ class FileController {
|
||||
|
||||
bool _isPathAllowed(String candidate) {
|
||||
if (!isAndroid || !isLocal) return true;
|
||||
if (AndroidDocuments.isPath(candidate)) return true;
|
||||
if (homePath.isEmpty || candidate.isEmpty) return false;
|
||||
final home = PathUtil.posixContext.normalize(homePath);
|
||||
final target = PathUtil.posixContext.normalize(candidate);
|
||||
@@ -408,6 +411,15 @@ class FileController {
|
||||
return DirectoryData(directory.value, options.value);
|
||||
}
|
||||
|
||||
Future<void> _restoreWorkspaceHome(String savedDir) async {
|
||||
if (savedDir.isEmpty || AndroidDocuments.isPath(savedDir)) return;
|
||||
final workspace = await AndroidDocuments.workspace();
|
||||
if (PathUtil.posixContext.equals(workspace, savedDir) ||
|
||||
PathUtil.posixContext.isWithin(workspace, savedDir)) {
|
||||
homePath = workspace;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> onReady() async {
|
||||
if (isLocal) {
|
||||
options.value.home = await bind.mainGetHomeDir();
|
||||
@@ -424,6 +436,7 @@ class FileController {
|
||||
|
||||
var savedDir = (await bind.sessionGetPeerOption(
|
||||
sessionId: sessionId, name: isLocal ? "local_dir" : "remote_dir"));
|
||||
if (isAndroid && isLocal) await _restoreWorkspaceHome(savedDir);
|
||||
if (savedDir.isNotEmpty && !_isPathAllowed(savedDir)) {
|
||||
savedDir = options.value.home;
|
||||
await bind.sessionPeerOption(
|
||||
@@ -436,7 +449,13 @@ class FileController {
|
||||
options.value.home,
|
||||
};
|
||||
for (final dir in dirs) {
|
||||
if (isAndroid && isLocal) await _restoreWorkspaceHome(dir);
|
||||
if (await _openDirectoryPath(dir, isBack: true)) {
|
||||
final documentRoot = RegExp(r'^/@rustdesk/tree/[^/]+/[^/]+')
|
||||
.stringMatch(directory.value.path);
|
||||
if (isLocal && documentRoot != null) {
|
||||
homePath = documentRoot;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -528,6 +547,9 @@ class FileController {
|
||||
return true;
|
||||
}
|
||||
debugPrint("Failed to openDirectory $path: $e");
|
||||
if (isAndroid && isLocal && AndroidDocuments.isPath(path)) {
|
||||
showToast(e.toString());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -564,6 +586,9 @@ class FileController {
|
||||
}
|
||||
|
||||
Future<bool> _goToParentDirectory({bool isBack = false}) async {
|
||||
if (AndroidDocuments.isRoot(directory.value.path)) {
|
||||
return false;
|
||||
}
|
||||
final isWindows = options.value.isWindows;
|
||||
final dirPath = directory.value.path;
|
||||
var parent = PathUtil.dirname(dirPath, isWindows);
|
||||
@@ -627,6 +652,17 @@ class FileController {
|
||||
final transferJobIds = <int>[];
|
||||
for (var from in items.items) {
|
||||
final jobID = jobController.addTransferJob(from, isRemoteToLocal);
|
||||
// Keep this check before PathUtil.join: Rust does not receive the selected
|
||||
// root separately, and Web transfers bypass Rust validation.
|
||||
if (isRemoteToLocal &&
|
||||
!DownloadPaths.validName(from.name, windows: isWindows)) {
|
||||
jobController.jobError({
|
||||
'id': '$jobID',
|
||||
'file_num': '0',
|
||||
'err': 'Invalid file name: ${from.name}',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
transferJobs.add((from, jobID));
|
||||
transferJobIds.add(jobID);
|
||||
}
|
||||
@@ -651,6 +687,15 @@ class FileController {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRemoteToLocal) {
|
||||
for (final (entry, jobID) in transferJobs) {
|
||||
if (entry.isDirectory) {
|
||||
await _downloadEmptyDirectories(entry, jobID, otherSideData);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Entry> entrys = items.items.toList();
|
||||
var isRemote = isLocal == true ? true : false;
|
||||
|
||||
@@ -683,6 +728,35 @@ class FileController {
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _downloadEmptyDirectories(
|
||||
Entry entry, int jobID, DirectoryData destination) async {
|
||||
try {
|
||||
final emptyDirs = await fileFetcher.readEmptyDirs(
|
||||
entry.path, false, destination.options.showHidden);
|
||||
final localRoot = PathUtil.join(destination.directory.path, entry.name,
|
||||
destination.options.isWindows);
|
||||
final paths = emptyDirs
|
||||
.map((dir) => DownloadPaths.mapDirectory(
|
||||
entry.path, dir.path, localRoot,
|
||||
remoteWindows: options.value.isWindows,
|
||||
localWindows: destination.options.isWindows))
|
||||
.toList();
|
||||
for (final path in paths) {
|
||||
await DownloadPaths.ensureNoLinks(destination.directory.path, path);
|
||||
}
|
||||
for (final path in paths) {
|
||||
await createDirWithRemote(path, false);
|
||||
}
|
||||
} on FormatException catch (err) {
|
||||
await bind.sessionCancelJob(sessionId: sessionId, actId: jobID);
|
||||
jobController.jobError({
|
||||
'id': '$jobID',
|
||||
'file_num': '0',
|
||||
'err': err.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
bool _removeCheckboxRemember = false;
|
||||
|
||||
Future<void> removeAction(SelectedItems items) async {
|
||||
@@ -692,7 +766,7 @@ class FileController {
|
||||
return;
|
||||
}
|
||||
final isWindows = options.value.isWindows;
|
||||
await Future.forEach(items.items, (Entry item) async {
|
||||
await Future.forEach(items.items.toList(), (Entry item) async {
|
||||
final jobID = JobController.jobID.next();
|
||||
var title = "";
|
||||
var content = "";
|
||||
@@ -1104,7 +1178,8 @@ class JobController {
|
||||
}
|
||||
|
||||
Future<bool> jobDone(Map<String, dynamic> evt) async {
|
||||
if (jobResultListener.isListening) {
|
||||
final waitingForResult = jobResultListener.isListening;
|
||||
if (waitingForResult) {
|
||||
jobResultListener.complete(evt);
|
||||
// return;
|
||||
}
|
||||
@@ -1120,6 +1195,11 @@ class JobController {
|
||||
return true;
|
||||
}
|
||||
final job = jobTable[jobIndex];
|
||||
if (job.type == JobType.transfer &&
|
||||
job.isRemoteToLocal &&
|
||||
job.state == JobState.error) {
|
||||
return true;
|
||||
}
|
||||
job.recvJobRes = true;
|
||||
if (job.type == JobType.deleteFile) {
|
||||
job.state = JobState.done;
|
||||
@@ -1150,7 +1230,8 @@ class JobController {
|
||||
if (job.type == JobType.deleteDir) {
|
||||
return job.state == JobState.done;
|
||||
} else {
|
||||
return true;
|
||||
// An awaiting file-deletion batch refreshes when removeAction finishes.
|
||||
return job.type != JobType.deleteFile || !waitingForResult;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1448,6 +1529,12 @@ class FileFetcher {
|
||||
if (!_removeRemoteReadTask(entry.key, task)) continue;
|
||||
task.completer.completeError(StateError(_kRemoteSessionChangedError));
|
||||
}
|
||||
for (final path in remoteEmptyDirsTasks.keys.toList()) {
|
||||
if (!AndroidDocuments.isPath(path)) continue;
|
||||
remoteEmptyDirsTasks
|
||||
.remove(path)
|
||||
?.completeError(StateError(_kRemoteSessionChangedError));
|
||||
}
|
||||
}
|
||||
|
||||
_RemoteReadTask _registerRemoteReadTask(String path, bool includeHidden) {
|
||||
@@ -1488,15 +1575,18 @@ class FileFetcher {
|
||||
final c = Completer<List<FileDirectory>>();
|
||||
tasks[path] = c;
|
||||
|
||||
Timer(Duration(seconds: 2), () {
|
||||
final timeout = AndroidDocuments.isPath(path)
|
||||
? _kRemoteReadDirTimeout
|
||||
: const Duration(seconds: 2);
|
||||
Timer(timeout, () {
|
||||
if (!identical(tasks[path], c)) return;
|
||||
tasks.remove(path);
|
||||
if (c.isCompleted) return;
|
||||
c.completeError("Failed to read empty dirs, timeout");
|
||||
});
|
||||
return c.future;
|
||||
}
|
||||
|
||||
Future<FileDirectory> registerReadRecursiveTask(int actID) {
|
||||
Future<FileDirectory> registerReadRecursiveTask(int actID, String path) {
|
||||
final tasks = readRecursiveTasks;
|
||||
if (tasks.containsKey(actID)) {
|
||||
throw "Failed to registerRemoveTask, already have same ReadRecursive job";
|
||||
@@ -1504,7 +1594,10 @@ class FileFetcher {
|
||||
final c = Completer<FileDirectory>();
|
||||
tasks[actID] = c;
|
||||
|
||||
Timer(Duration(seconds: 2), () {
|
||||
final timeout = AndroidDocuments.isPath(path)
|
||||
? _kRemoteReadDirTimeout
|
||||
: const Duration(seconds: 2);
|
||||
Timer(timeout, () {
|
||||
tasks.remove(actID);
|
||||
if (c.isCompleted) return;
|
||||
c.completeError("Failed to read dir, timeout");
|
||||
@@ -1586,8 +1679,13 @@ class FileFetcher {
|
||||
fdJsons.map((fdJson) => FileDirectory.fromJson(fdJson)).toList();
|
||||
return fds;
|
||||
} else {
|
||||
final generation = _remoteSessionGeneration;
|
||||
await bind.sessionReadRemoteEmptyDirsRecursiveSync(
|
||||
sessionId: sessionId, path: path, includeHidden: showHidden);
|
||||
if (AndroidDocuments.isPath(path) &&
|
||||
generation != _remoteSessionGeneration) {
|
||||
throw StateError(_kRemoteSessionChangedError);
|
||||
}
|
||||
return registerReadEmptyDirsTask(isLocal, path);
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -1601,6 +1699,11 @@ class FileFetcher {
|
||||
if (isLocal) {
|
||||
final res = await bind.sessionReadLocalDirSync(
|
||||
sessionId: sessionId, path: path, showHidden: showHidden);
|
||||
if (isAndroid && AndroidDocuments.isPath(path)) {
|
||||
final data = jsonDecode(res);
|
||||
if (data['error'] != null) throw StateError(data['error'] as String);
|
||||
return FileDirectory.fromJson(data);
|
||||
}
|
||||
final fd = FileDirectory.fromJson(jsonDecode(res));
|
||||
return fd;
|
||||
} else {
|
||||
@@ -1640,7 +1743,7 @@ class FileFetcher {
|
||||
path: path,
|
||||
isRemote: !isLocal,
|
||||
showHidden: showHidden);
|
||||
return registerReadRecursiveTask(actID);
|
||||
return registerReadRecursiveTask(actID, path);
|
||||
} catch (e) {
|
||||
return Future.error(e);
|
||||
}
|
||||
|
||||
@@ -459,6 +459,7 @@ class InputModel {
|
||||
// mouse
|
||||
final isPhysicalMouse = false.obs;
|
||||
int _lastButtons = 0;
|
||||
int _pressedMouseButtons = 0;
|
||||
Offset lastMousePos = Offset.zero;
|
||||
int _lastWheelTsUs = 0;
|
||||
|
||||
@@ -1388,6 +1389,10 @@ class InputModel {
|
||||
}
|
||||
}
|
||||
_lastButtons = hasStaleButtonsOnMouseUp ? 0 : evt.buttons;
|
||||
if (isDesktop && _relativeMouse.enabled.value && type == _kMouseEventUp) {
|
||||
// A relative up can finish a press sent before the mode switch.
|
||||
_pressedMouseButtons &= ~buttons;
|
||||
}
|
||||
|
||||
out['buttons'] = buttons;
|
||||
out['type'] = type;
|
||||
@@ -2134,9 +2139,16 @@ class InputModel {
|
||||
bool edgeScroll = false,
|
||||
}) {
|
||||
if (isViewCamera) return null;
|
||||
final buttons = evt['buttons'];
|
||||
final isMatchingMouseUp = (isDesktop || isWebDesktop) &&
|
||||
evt['type'] == _kMouseEventUp &&
|
||||
buttons is int &&
|
||||
mouseButtonsToPeer(buttons).isNotEmpty &&
|
||||
_pressedMouseButtons & buttons != 0;
|
||||
double x = offset.dx;
|
||||
double y = max(0.0, offset.dy);
|
||||
if (_checkPeerControlProtected(x, y)) {
|
||||
// Cursor ownership may change between a forwarded down and its up.
|
||||
if (_checkPeerControlProtected(x, y) && !isMatchingMouseUp) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2178,6 +2190,9 @@ class InputModel {
|
||||
if (pos == null) {
|
||||
return null;
|
||||
}
|
||||
if (isMatchingMouseUp) {
|
||||
_pressedMouseButtons &= ~buttons;
|
||||
}
|
||||
if (type != '') {
|
||||
evt['x'] = '0';
|
||||
evt['y'] = '0';
|
||||
@@ -2186,9 +2201,13 @@ class InputModel {
|
||||
evt['y'] = '${pos.y.toInt()}';
|
||||
}
|
||||
|
||||
final buttons = evt['buttons'];
|
||||
if (buttons is int) {
|
||||
evt['buttons'] = mouseButtonsToPeer(buttons);
|
||||
if ((isDesktop || isWebDesktop) &&
|
||||
type == kMouseEventTypeDown &&
|
||||
evt['buttons'] != '') {
|
||||
_pressedMouseButtons |= buttons;
|
||||
}
|
||||
} else {
|
||||
// Log warning if buttons exists but is not an int (unexpected caller).
|
||||
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
|
||||
|
||||
@@ -15,6 +15,8 @@ import '../common/formatter/id_formatter.dart';
|
||||
import '../desktop/pages/server_page.dart' as desktop;
|
||||
import '../desktop/widgets/tabbar_widget.dart';
|
||||
import '../mobile/pages/server_page.dart';
|
||||
import '../mobile/widgets/android_file_transfer_setup.dart';
|
||||
import '../utils/android_documents.dart';
|
||||
import 'model.dart';
|
||||
|
||||
const kLoginDialogTag = "LOGIN";
|
||||
@@ -399,6 +401,14 @@ class ServerModel with ChangeNotifier {
|
||||
stopService();
|
||||
}
|
||||
} else {
|
||||
if (isAndroid) {
|
||||
try {
|
||||
await AndroidDocuments.requireLogFolder();
|
||||
await showAndroidFileTransferSetup(gFFI);
|
||||
} catch (_) {
|
||||
debugPrint('Folder setup failed; continuing service startup');
|
||||
}
|
||||
}
|
||||
await checkRequestNotificationPermission();
|
||||
if (bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) != 'Y') {
|
||||
await checkFloatingWindowPermission();
|
||||
|
||||
@@ -70,10 +70,6 @@ class TerminalModel with ChangeNotifier {
|
||||
|
||||
final _inputBuffer = <String>[];
|
||||
|
||||
/// Exposes buffered input only for lifecycle regression tests.
|
||||
@visibleForTesting
|
||||
int get debugBufferedInputCount => _inputBuffer.length;
|
||||
|
||||
// Buffer for output data received before terminal view has valid dimensions.
|
||||
// This prevents NaN errors when writing to terminal before layout is complete.
|
||||
final _pendingOutputChunks = <String>[];
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../common.dart';
|
||||
|
||||
class AndroidDocuments {
|
||||
static const root = '/@rustdesk/';
|
||||
|
||||
static bool isPath(String path) => path.startsWith(root);
|
||||
|
||||
static bool isRoot(String path) =>
|
||||
RegExp(r'^/@rustdesk/tree/[^/]+/[^/]+$').hasMatch(path);
|
||||
|
||||
static String displayPath(String path) {
|
||||
if (!isPath(path)) return path;
|
||||
return path.replaceFirst(RegExp(r'^/@rustdesk/tree/[^/]+/'), '');
|
||||
}
|
||||
|
||||
static Future<Map<String, dynamic>?> selectFolder({bool share = false}) async {
|
||||
gFFI.ffiModel.beginAndroidDocumentPicker();
|
||||
try {
|
||||
final result = await gFFI.invokeMethodWithResult<String>(
|
||||
'document_folder', {'share': share});
|
||||
return result == null ? null : jsonDecode(result) as Map<String, dynamic>;
|
||||
} finally {
|
||||
gFFI.ffiModel.endAndroidDocumentPicker();
|
||||
}
|
||||
}
|
||||
|
||||
static Future<String> workspace({bool share = false}) async {
|
||||
final path = await gFFI
|
||||
.invokeMethodWithResult<String>('document_workspace', {'share': share});
|
||||
if (path == null || path.isEmpty) {
|
||||
throw StateError('App workspace is unavailable');
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
static Future<bool> requireLogFolder() async {
|
||||
gFFI.ffiModel.beginAndroidDocumentPicker();
|
||||
try {
|
||||
final ready = await gFFI.invokeMethodWithResult<bool>(
|
||||
'document_require_log_folder', {'checkOnly': true});
|
||||
if (ready == null) {
|
||||
throw StateError('Log directory setup did not complete');
|
||||
}
|
||||
if (ready) return true;
|
||||
if (!await _confirmLogFolder()) return false;
|
||||
final selected = await gFFI
|
||||
.invokeMethodWithResult<bool>('document_require_log_folder');
|
||||
if (selected == null) {
|
||||
throw StateError('Log directory setup did not complete');
|
||||
}
|
||||
return selected;
|
||||
} catch (error) {
|
||||
debugPrint('Log directory setup failed');
|
||||
await gFFI.dialogManager.show<void>(
|
||||
(_, close, __) => CustomAlertDialog(
|
||||
title: Text(translate('Error')),
|
||||
content: Text(error is PlatformException
|
||||
? translate(error.message ?? 'Failed')
|
||||
: error.toString()),
|
||||
actions: [
|
||||
TextButton(onPressed: close, child: Text(translate('OK'))),
|
||||
],
|
||||
onSubmit: close,
|
||||
onCancel: close,
|
||||
),
|
||||
backDismiss: true,
|
||||
forceGlobal: true,
|
||||
);
|
||||
rethrow;
|
||||
} finally {
|
||||
gFFI.ffiModel.endAndroidDocumentPicker();
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> _confirmLogFolder() async =>
|
||||
await gFFI.dialogManager.show<bool>(
|
||||
(_, close, __) => CustomAlertDialog(
|
||||
title: Text(translate('Permissions')),
|
||||
content: Text(
|
||||
'${translate('android-logs-folder-tip')}\n'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => close(true),
|
||||
child: Text(translate('Choose folder')),
|
||||
),
|
||||
],
|
||||
onCancel: () => close(false),
|
||||
),
|
||||
backDismiss: true,
|
||||
forceGlobal: true,
|
||||
) ==
|
||||
true;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
class DownloadPaths {
|
||||
static Future<void> ensureNoLinks(String root, String destination) async {
|
||||
if (!path.isWithin(root, destination)) {
|
||||
throw FormatException('Invalid download directory: $destination');
|
||||
}
|
||||
var current = root;
|
||||
for (final name in path.split(path.relative(destination, from: root))) {
|
||||
current = path.join(current, name);
|
||||
if (await FileSystemEntity.type(current, followLinks: false) ==
|
||||
FileSystemEntityType.link) {
|
||||
throw FormatException('Download directory contains a link: $current');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool validName(String name, {required bool windows}) {
|
||||
if (name.isEmpty || name == '.' || name == '..' || name.contains('\x00')) {
|
||||
return false;
|
||||
}
|
||||
if (name.contains('/')) return false;
|
||||
return !windows ||
|
||||
(!name.contains(RegExp(r'[<>:"\\|?*]')) &&
|
||||
!name.endsWith('.') &&
|
||||
!name.endsWith(' '));
|
||||
}
|
||||
|
||||
static String mapDirectory(
|
||||
String remoteRoot, String remotePath, String localRoot,
|
||||
{required bool remoteWindows, required bool localWindows}) {
|
||||
final remote = path.Context(
|
||||
style: remoteWindows ? path.Style.windows : path.Style.posix);
|
||||
final local = path.Context(
|
||||
style: localWindows ? path.Style.windows : path.Style.posix);
|
||||
if (remotePath.contains('\x00') ||
|
||||
remote.split(remotePath).contains('..') ||
|
||||
(!remote.equals(remoteRoot, remotePath) &&
|
||||
!remote.isWithin(remoteRoot, remotePath))) {
|
||||
throw FormatException('Invalid download directory: $remotePath');
|
||||
}
|
||||
final relative = remote.relative(remotePath, from: remoteRoot);
|
||||
if (relative == '.') return localRoot;
|
||||
final names = remote.split(relative);
|
||||
if (names.any((name) => !validName(name, windows: localWindows))) {
|
||||
throw FormatException('Invalid download directory: $remotePath');
|
||||
}
|
||||
return local.joinAll([localRoot, ...names]);
|
||||
}
|
||||
}
|
||||
@@ -1834,6 +1834,10 @@ class RustdeskImpl {
|
||||
throw UnimplementedError("mainRemoveTrustedDevices");
|
||||
}
|
||||
|
||||
Future<void> mainRenewTrustedDevices({required String json, dynamic hint}) {
|
||||
throw UnimplementedError("mainRenewTrustedDevices");
|
||||
}
|
||||
|
||||
Future<void> mainClearTrustedDevices({dynamic hint}) {
|
||||
throw UnimplementedError("mainClearTrustedDevices");
|
||||
}
|
||||
@@ -1928,6 +1932,11 @@ class RustdeskImpl {
|
||||
}
|
||||
|
||||
String mainGetCommonSync({required String key, dynamic hint}) {
|
||||
const prefix = 'resolve-api-server:';
|
||||
if (key.startsWith(prefix)) {
|
||||
return js.context
|
||||
.callMethod('getByName', ['api_server', key.substring(prefix.length)]);
|
||||
}
|
||||
throw UnimplementedError("mainGetCommonSync");
|
||||
}
|
||||
|
||||
|
||||
@@ -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.5.1+68
|
||||
|
||||
environment:
|
||||
sdk: '^3.1.0'
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/generated_bridge.dart';
|
||||
import 'package:flutter_hbb/mobile/widgets/android_file_transfer_setup.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
import 'package:flutter_hbb/models/server_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Binding extends Fake implements RustdeskImpl {
|
||||
final options = <String, String>{};
|
||||
|
||||
@override
|
||||
String translate(
|
||||
{required String name, required String locale, dynamic hint}) =>
|
||||
name;
|
||||
|
||||
@override
|
||||
String getLocalFlutterOption({required String k, dynamic hint}) =>
|
||||
options[k] ?? '';
|
||||
|
||||
@override
|
||||
Future<void> setLocalFlutterOption(
|
||||
{required String k, required String v, dynamic hint}) async {
|
||||
options[k] = v;
|
||||
}
|
||||
|
||||
@override
|
||||
bool isDisableSettings({dynamic hint}) => false;
|
||||
|
||||
@override
|
||||
bool isOutgoingOnly({dynamic hint}) => false;
|
||||
|
||||
@override
|
||||
String mainGetBuildinOption({required String key, dynamic hint}) => '';
|
||||
}
|
||||
|
||||
class _Server extends Fake implements ServerModel {
|
||||
@override
|
||||
List<Client> get clients => [];
|
||||
}
|
||||
|
||||
class _Session extends Fake implements FFI {
|
||||
@override
|
||||
final dialogManager = OverlayDialogManager();
|
||||
|
||||
@override
|
||||
final serverModel = _Server();
|
||||
}
|
||||
|
||||
void main() {
|
||||
late _Session session;
|
||||
|
||||
setUp(() {
|
||||
platformFFI.setBindingForTesting(_Binding());
|
||||
session = _Session();
|
||||
});
|
||||
|
||||
Future<void> openApp(WidgetTester tester) => tester.pumpWidget(MaterialApp(
|
||||
navigatorKey: globalKey,
|
||||
home: const Scaffold(),
|
||||
));
|
||||
|
||||
testWidgets('skipping folder setup suppresses later prompts', (tester) async {
|
||||
await openApp(tester);
|
||||
final first = showAndroidFileTransferSetup(session);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Skip'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(await first, isTrue);
|
||||
expect(await showAndroidFileTransferSetup(_Session()), isTrue);
|
||||
expect(find.byType(CustomAlertDialog), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('canceling setup leaves it available at the next entry',
|
||||
(tester) async {
|
||||
await openApp(tester);
|
||||
final first = showAndroidFileTransferSetup(session);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
|
||||
await tester.pumpAndSettle();
|
||||
expect(await first, isFalse);
|
||||
|
||||
final retry = showAndroidFileTransferSetup(session);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(CustomAlertDialog), findsOneWidget);
|
||||
await tester.tap(find.text('Skip'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(await retry, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
|
||||
|
||||
void main() {
|
||||
test('warns only for remote HTTP endpoints', () {
|
||||
final cases = <String?, bool>{
|
||||
null: false,
|
||||
'': false,
|
||||
'https://api.example.com': false,
|
||||
'http://api.example.com': true,
|
||||
'http://192.168.1.13:13000': true,
|
||||
'http://localhost:21114': false,
|
||||
'http://127.0.0.1:21114': false,
|
||||
'http://[::1]:21114': false,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
expect(shouldWarnApiServer(entry.key), entry.value, reason: entry.key);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('warning follows API and ID changes using the resolved endpoint',
|
||||
(tester) async {
|
||||
final api = TextEditingController();
|
||||
final id = TextEditingController(text: 'id.example.com');
|
||||
addTearDown(api.dispose);
|
||||
addTearDown(id.dispose);
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: ApiServerWarning(
|
||||
controller: api,
|
||||
idController: id,
|
||||
message: 'HTTP warning',
|
||||
emptyMessage: 'Default HTTP warning',
|
||||
resolveApiServer: ({required api, required custom}) =>
|
||||
api.isNotEmpty ? api : 'http://$custom',
|
||||
),
|
||||
));
|
||||
expect(find.text('Default HTTP warning'), findsOneWidget);
|
||||
|
||||
id.text = 'localhost';
|
||||
await tester.pump();
|
||||
expect(find.text('Default HTTP warning'), findsNothing);
|
||||
|
||||
api.text = 'http://api.example.com';
|
||||
await tester.pump();
|
||||
expect(find.text('HTTP warning'), findsOneWidget);
|
||||
|
||||
api.text = 'https://api.example.com';
|
||||
await tester.pump();
|
||||
expect(find.text('HTTP warning'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('resolver failures are reported without breaking the server form',
|
||||
(tester) async {
|
||||
final api = TextEditingController();
|
||||
final id = TextEditingController();
|
||||
addTearDown(api.dispose);
|
||||
addTearDown(id.dispose);
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Column(children: [
|
||||
TextField(controller: api),
|
||||
Expanded(
|
||||
child: ApiServerWarning(
|
||||
controller: api,
|
||||
idController: id,
|
||||
message: 'HTTP warning',
|
||||
emptyMessage: 'Default HTTP warning',
|
||||
resolveApiServer: ({required api, required custom}) =>
|
||||
throw const FormatException('API preview failed'),
|
||||
)),
|
||||
]),
|
||||
),
|
||||
));
|
||||
expect(tester.takeException(), isA<FormatException>());
|
||||
expect(find.byType(ErrorWidget), findsNothing);
|
||||
expect(find.text('Default HTTP warning'), findsNothing);
|
||||
expect(find.byType(TextField), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -48,74 +48,6 @@ void main() {
|
||||
expect(peers.single.online, isTrue);
|
||||
});
|
||||
|
||||
test('peer copies preserve online state', () {
|
||||
final peer = _peer(id: '987654321', online: true);
|
||||
|
||||
expect(Peer.copy(peer).online, isTrue);
|
||||
});
|
||||
|
||||
test('online callbacks update autocomplete-only peers', () {
|
||||
final peers = mergeAutocompletePeers(restRecentPeerIds: ['112233445']);
|
||||
|
||||
final changed = updateAutocompletePeerOnlineStates(
|
||||
peers,
|
||||
onlines: {'112233445'},
|
||||
offlines: {},
|
||||
);
|
||||
|
||||
expect(changed, isTrue);
|
||||
expect(peers.single.online, isTrue);
|
||||
});
|
||||
|
||||
test('online query ids are deduplicated and limited', () {
|
||||
final peers = List.generate(
|
||||
25,
|
||||
(index) => _peer(id: index.toString()),
|
||||
)..insert(1, _peer(id: '0'));
|
||||
|
||||
final ids = autocompleteOnlineQueryIds(peers, limit: 20);
|
||||
|
||||
expect(ids, hasLength(20));
|
||||
expect(ids.first, '0');
|
||||
expect(ids.where((id) => id == '0'), hasLength(1));
|
||||
expect(ids.last, '19');
|
||||
});
|
||||
|
||||
test('empty online query ids cancel pending debounce', () async {
|
||||
final queriedIds = <List<String>>[];
|
||||
final loader = AllPeersLoader(
|
||||
queryOnlines: (ids) async {
|
||||
queriedIds.add(ids);
|
||||
},
|
||||
queryOnlineDebounce: Duration(milliseconds: 1),
|
||||
);
|
||||
|
||||
loader.queryOnlines([_peer(id: '123456789')]);
|
||||
loader.queryOnlines([]);
|
||||
await Future.delayed(Duration(milliseconds: 2));
|
||||
|
||||
expect(queriedIds, isEmpty);
|
||||
});
|
||||
|
||||
test('failed online query enqueue does not suppress retry', () async {
|
||||
var queryCount = 0;
|
||||
final loader = AllPeersLoader(
|
||||
queryOnlines: (ids) {
|
||||
queryCount += 1;
|
||||
return Future<void>.error(Exception('queue full'));
|
||||
},
|
||||
queryOnlineDebounce: Duration(milliseconds: 1),
|
||||
);
|
||||
|
||||
loader.queryOnlines([_peer(id: '123456789')]);
|
||||
await Future.delayed(Duration(milliseconds: 2));
|
||||
|
||||
loader.queryOnlines([_peer(id: '123456789')]);
|
||||
await Future.delayed(Duration(milliseconds: 2));
|
||||
|
||||
expect(queryCount, 2);
|
||||
});
|
||||
|
||||
test('online callback updates currently displayed options', () async {
|
||||
final loader = AllPeersLoader(
|
||||
queryOnlines: (ids) async {},
|
||||
@@ -132,17 +64,4 @@ void main() {
|
||||
expect(displayedOptions.single.online, isTrue);
|
||||
await Future.delayed(Duration(milliseconds: 2));
|
||||
});
|
||||
|
||||
test('cached online callback state is reapplied after peers merge', () {
|
||||
final loader = AllPeersLoader();
|
||||
loader.updateOnlineStateForTesting({
|
||||
'onlines': '123456789',
|
||||
'offlines': '',
|
||||
});
|
||||
|
||||
final mergedPeers = [_peer(id: '123456789')];
|
||||
loader.applyLastOnlineStateForTesting(mergedPeers);
|
||||
|
||||
expect(mergedPeers.single.online, isTrue);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'cm_demo.dart' as cm_demo;
|
||||
|
||||
void main() {
|
||||
test('connection manager demo clients match the current Client API', () {
|
||||
expect(cm_demo.testClients, hasLength(4));
|
||||
expect(cm_demo.testClients.map((client) => client.name), [
|
||||
'UserAAAAAA',
|
||||
'UserBBBBB',
|
||||
'UserC',
|
||||
'UserDDDDDDDDDDDd',
|
||||
]);
|
||||
expect(
|
||||
cm_demo.testClients.every(
|
||||
(client) => client.keyboard && !client.clipboard && !client.audio),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -15,36 +14,14 @@ 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;
|
||||
return Future.value(core[id]);
|
||||
}
|
||||
|
||||
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;
|
||||
bool get showsRemoteCursor => false;
|
||||
}
|
||||
|
||||
String? _key(MouseCursor cursor) =>
|
||||
@@ -181,28 +158,6 @@ void main() {
|
||||
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;
|
||||
@@ -220,134 +175,6 @@ void main() {
|
||||
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);
|
||||
@@ -360,89 +187,6 @@ void main() {
|
||||
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);
|
||||
@@ -463,30 +207,6 @@ void main() {
|
||||
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);
|
||||
@@ -502,182 +222,4 @@ void main() {
|
||||
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');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -108,17 +108,11 @@ void main() {
|
||||
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);
|
||||
@@ -132,15 +126,15 @@ void main() {
|
||||
test('Windows peer cursor alpha survives resizing $pattern',
|
||||
() => _checkWindowsPeerAlpha(pattern, registrations));
|
||||
}
|
||||
for (final style in [
|
||||
kRemoteViewStyleOriginal,
|
||||
kRemoteViewStyleAdaptive,
|
||||
kRemoteViewStyleCustom
|
||||
for (final (style, zoom) in [
|
||||
(kRemoteViewStyleOriginal, false),
|
||||
(kRemoteViewStyleAdaptive, false),
|
||||
(kRemoteViewStyleAdaptive, true),
|
||||
(kRemoteViewStyleCustom, false),
|
||||
(kRemoteViewStyleCustom, true),
|
||||
]) {
|
||||
for (final zoom in [false, true]) {
|
||||
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
|
||||
(tester) => _checkView(tester, (style, zoom), registrations));
|
||||
}
|
||||
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
|
||||
(tester) => _checkView(tester, (style, zoom), registrations));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,31 +235,6 @@ void _expectSize(Map<dynamic, dynamic> args, (int, int) 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;
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_hbb/generated_bridge.dart';
|
||||
import 'package:flutter_hbb/models/file_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
final _sessionId = UuidValue('00000000-0000-4000-8000-000000000001');
|
||||
|
||||
class _Binding extends Fake implements RustdeskImpl {
|
||||
final sent = <String>[];
|
||||
final created = <String>[];
|
||||
int nextId = 0;
|
||||
|
||||
@override
|
||||
String mainGetCommonSync({required String key, dynamic hint}) =>
|
||||
'${++nextId}';
|
||||
|
||||
@override
|
||||
int versionToNumber({required String v, dynamic hint}) =>
|
||||
v == '1.3.3' ? 1 : 2;
|
||||
|
||||
@override
|
||||
Future<void> sessionSendFiles({
|
||||
required UuidValue sessionId,
|
||||
required int actId,
|
||||
required String path,
|
||||
required String to,
|
||||
required int fileNum,
|
||||
required bool includeHidden,
|
||||
required bool isRemote,
|
||||
required bool isDir,
|
||||
dynamic hint,
|
||||
}) async {
|
||||
expect(isRemote, isTrue);
|
||||
sent.add(to);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> sessionCreateDir({
|
||||
required UuidValue sessionId,
|
||||
required int actId,
|
||||
required String path,
|
||||
required bool isRemote,
|
||||
dynamic hint,
|
||||
}) async {
|
||||
expect(isRemote, isFalse);
|
||||
created.add(path);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> sessionCancelJob({
|
||||
required UuidValue sessionId,
|
||||
required int actId,
|
||||
dynamic hint,
|
||||
}) async {}
|
||||
}
|
||||
|
||||
class _Session extends Fake implements FFI {
|
||||
@override
|
||||
final String id = 'download-test';
|
||||
@override
|
||||
UuidValue get sessionId => _sessionId;
|
||||
@override
|
||||
late final ffiModel = FfiModel(WeakReference(this));
|
||||
}
|
||||
|
||||
class _Fetcher extends FileFetcher {
|
||||
_Fetcher() : super(() => _sessionId);
|
||||
List<String> emptyDirectories = [];
|
||||
|
||||
@override
|
||||
Future<List<FileDirectory>> readEmptyDirs(
|
||||
String path, bool isLocal, bool showHidden) async =>
|
||||
emptyDirectories.map((path) => FileDirectory()..path = path).toList();
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late _Binding binding;
|
||||
late _Session session;
|
||||
late _Fetcher fetcher;
|
||||
late FileController controller;
|
||||
late DirectoryData destination;
|
||||
|
||||
setUp(() {
|
||||
binding = _Binding();
|
||||
platformFFI.setBindingForTesting(binding);
|
||||
session = _Session();
|
||||
session.ffiModel.pi.version = '1.5.1';
|
||||
fetcher = _Fetcher();
|
||||
destination =
|
||||
DirectoryData(FileDirectory()..path = '/downloads', DirectoryOptions());
|
||||
controller = FileController(
|
||||
isLocal: false,
|
||||
getSessionID: () => _sessionId,
|
||||
rootState: WeakReference(session),
|
||||
jobController: JobController(() => _sessionId, () => null),
|
||||
fileFetcher: fetcher,
|
||||
getOtherSideDirectoryData: () => destination,
|
||||
);
|
||||
controller.directory.value.path = '/remote';
|
||||
});
|
||||
|
||||
tearDown(() => session.ffiModel.dispose());
|
||||
|
||||
Future<void> download(String name, {bool directory = false}) async {
|
||||
final entry = Entry()
|
||||
..name = name
|
||||
..path = '/remote/$name'
|
||||
..entryType = directory ? 0 : 4;
|
||||
final items = SelectedItems(isLocal: false)..add(entry);
|
||||
await controller.sendFiles(items, destination);
|
||||
}
|
||||
|
||||
test('downloads refuse peer listing names that escape the local folder',
|
||||
() async {
|
||||
await download('report.txt');
|
||||
expect(binding.sent, ['/downloads/report.txt']);
|
||||
binding.sent.clear();
|
||||
for (final windows in [false, true]) {
|
||||
destination.options.isWindows = windows;
|
||||
destination.directory.path = windows ? r'C:\downloads' : '/downloads';
|
||||
for (final name in [
|
||||
'../outside.txt',
|
||||
'/outside.txt',
|
||||
'.',
|
||||
'..',
|
||||
'',
|
||||
'bad\x00name',
|
||||
if (windows) ...[r'..\outside.txt', r'C:\outside.txt', r'\\host\share'],
|
||||
]) {
|
||||
await download(name);
|
||||
expect(binding.sent, isEmpty, reason: name);
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
}
|
||||
}
|
||||
await controller.jobController.jobDone({
|
||||
'id': '${controller.jobController.jobTable.last.id}',
|
||||
'file_num': '0',
|
||||
});
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
});
|
||||
|
||||
test('empty-directory downloads reject paths outside the selected folder',
|
||||
() async {
|
||||
for (final path in ['/remote/other/empty', '/remote/docs/../out']) {
|
||||
fetcher.emptyDirectories = ['/remote/docs/ok', path];
|
||||
await download('docs', directory: true);
|
||||
expect(binding.created, isEmpty, reason: path);
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
}
|
||||
fetcher.emptyDirectories = ['/remote/docs', '/remote/docs/sub/empty'];
|
||||
await download('docs', directory: true);
|
||||
expect(binding.created, ['/downloads/docs', '/downloads/docs/sub/empty']);
|
||||
});
|
||||
|
||||
test('empty-directory downloads refuse existing local links', () async {
|
||||
final temporary =
|
||||
await Directory.systemTemp.createTemp('rustdesk_download_');
|
||||
addTearDown(() => temporary.delete(recursive: true));
|
||||
final outside = await Directory('${temporary.path}/outside').create();
|
||||
final downloads = await Directory('${temporary.path}/downloads').create();
|
||||
await Link('${downloads.path}/docs').create(outside.path);
|
||||
destination.directory.path = downloads.path;
|
||||
destination.options.isWindows = Platform.isWindows;
|
||||
fetcher.emptyDirectories = ['/remote/docs/empty'];
|
||||
await download('docs', directory: true);
|
||||
expect(binding.created, isEmpty);
|
||||
expect(controller.jobController.jobTable.last.state, JobState.error);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hbb/desktop/pages/file_manager_page.dart';
|
||||
import 'package:flutter_hbb/desktop/widgets/list_search_action_listener.dart';
|
||||
import 'package:flutter_hbb/models/file_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
List<Entry> _entries(int count) => [
|
||||
for (var i = 0; i < count; i++)
|
||||
Entry()
|
||||
..name = 'f$i'
|
||||
..path = '/f$i'
|
||||
];
|
||||
|
||||
List<String> _names(List<Entry> entries) =>
|
||||
entries.map((e) => e.name).toList()..sort();
|
||||
|
||||
void main() {
|
||||
test('navigation keys move the selection and stop at the ends', () {
|
||||
final entries = _entries(5);
|
||||
expect(_names(navigateSelection(entries, [], 1, false)), ['f0']);
|
||||
expect(_names(navigateSelection(entries, [], -1, false)), ['f4']);
|
||||
var selected = navigateSelection(entries, [entries[1]], 1, false);
|
||||
expect(_names(selected), ['f2']);
|
||||
selected = navigateSelection(entries, selected, -1, false);
|
||||
expect(_names(selected), ['f1']);
|
||||
expect(_names(navigateSelection(entries, selected, -3, false)), ['f0']);
|
||||
expect(_names(navigateSelection(entries, selected, 5, false)), ['f4']);
|
||||
});
|
||||
|
||||
test('shift extends and shrinks the range from the anchor', () {
|
||||
final entries = _entries(5);
|
||||
var selected = [entries[2]];
|
||||
selected = navigateSelection(entries, selected, 1, true);
|
||||
selected = navigateSelection(entries, selected, 1, true);
|
||||
expect(_names(selected), ['f2', 'f3', 'f4']);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
selected = navigateSelection(entries, selected, -1, true);
|
||||
expect(_names(selected), ['f1', 'f2']);
|
||||
selected = navigateSelection(entries, selected, 1, false);
|
||||
expect(_names(selected), ['f2']);
|
||||
});
|
||||
|
||||
test('page keys go to the visible edge before paging', () {
|
||||
// Rows 10..19 are fully visible.
|
||||
expect(pageDelta(12, 10, 19, true), 7);
|
||||
expect(pageDelta(19, 10, 19, true), 9);
|
||||
expect(pageDelta(12, 10, 19, false), -2);
|
||||
expect(pageDelta(10, 10, 19, false), -9);
|
||||
});
|
||||
|
||||
testWidgets('Enter does not reach type-to-search', (tester) async {
|
||||
final node = FocusNode();
|
||||
addTearDown(node.dispose);
|
||||
final searched = <String>[];
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: ListSearchActionListener(
|
||||
node: node,
|
||||
buffer: TimeoutStringBuffer(),
|
||||
onNext: searched.add,
|
||||
onSearch: searched.add,
|
||||
child: const SizedBox(),
|
||||
),
|
||||
));
|
||||
node.requestFocus();
|
||||
await tester.pump();
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter, character: '\r');
|
||||
expect(searched, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_hbb/generated_bridge.dart';
|
||||
import 'package:flutter_hbb/models/file_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/platform_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
@@ -48,7 +50,124 @@ class _SentRead {
|
||||
const _SentRead(this.path, this.includeHidden);
|
||||
}
|
||||
|
||||
class _FileBinding extends Fake implements RustdeskImpl {
|
||||
int _jobId = 0;
|
||||
final emptyDirsDispatch = Completer<void>();
|
||||
|
||||
@override
|
||||
Future<void> sessionReadRemoteEmptyDirsRecursiveSync(
|
||||
{required UuidValue sessionId,
|
||||
required String path,
|
||||
required bool includeHidden,
|
||||
dynamic hint}) =>
|
||||
emptyDirsDispatch.future;
|
||||
|
||||
@override
|
||||
String translate(
|
||||
{required String name, required String locale, dynamic hint}) =>
|
||||
name;
|
||||
|
||||
@override
|
||||
String mainGetCommonSync({required String key, dynamic hint}) =>
|
||||
'${++_jobId}';
|
||||
}
|
||||
|
||||
class _DeletingController extends FileController {
|
||||
final confirmations = <String>[];
|
||||
|
||||
_DeletingController()
|
||||
: super(
|
||||
isLocal: false,
|
||||
getSessionID: () => _sessionId,
|
||||
rootState: WeakReference(_FakeFFI()),
|
||||
jobController: JobController(() => _sessionId, () => null),
|
||||
fileFetcher: FileFetcher(() => _sessionId),
|
||||
getOtherSideDirectoryData: () =>
|
||||
DirectoryData(FileDirectory(), DirectoryOptions()),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<bool?> showRemoveDialog(
|
||||
String title, String content, bool showCheckbox) async {
|
||||
confirmations.add(content);
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
void sendRemoveFile(String path, int fileNum, int actId) {
|
||||
scheduleMicrotask(() {
|
||||
selectedItems.reconcile(
|
||||
selectedItems.items.where((entry) => entry.path != path).toList());
|
||||
unawaited(
|
||||
jobController.jobDone({'id': '$actId', 'file_num': '$fileNum'}));
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> refresh() async => true;
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final scenario in ['completion', 'reconnect', 'dispatch reconnect']) {
|
||||
testWidgets('SAF retry after $scenario', (tester) async {
|
||||
const path = '/@rustdesk/tree/grant/root';
|
||||
final response = jsonEncode({
|
||||
'path': path,
|
||||
'empty_dirs': [jsonDecode(_directoryJson('$path/empty'))],
|
||||
});
|
||||
final binding = _FileBinding();
|
||||
platformFFI.setBindingForTesting(binding);
|
||||
final fetcher = FileFetcher(() => _sessionId);
|
||||
final first = expectLater(
|
||||
fetcher.readEmptyDirs(path, false, false),
|
||||
scenario == 'completion'
|
||||
? completion(isNotEmpty)
|
||||
: throwsA(isA<StateError>()));
|
||||
try {
|
||||
if (scenario != 'dispatch reconnect')
|
||||
binding.emptyDirsDispatch.complete();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
if (scenario != 'completion') {
|
||||
fetcher.beginRemoteSession();
|
||||
} else {
|
||||
fetcher.tryCompleteEmptyDirsTask(response, 'false');
|
||||
}
|
||||
if (scenario == 'dispatch reconnect')
|
||||
binding.emptyDirsDispatch.complete();
|
||||
await tester.pump();
|
||||
final retry = expectLater(
|
||||
fetcher.readEmptyDirs(path, false, false).then((directories) =>
|
||||
directories.map((directory) => directory.path)),
|
||||
completion(['$path/empty']));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(seconds: 28));
|
||||
fetcher.tryCompleteEmptyDirsTask(response, 'false');
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
await retry;
|
||||
} finally {
|
||||
await tester.pump(const Duration(seconds: 30));
|
||||
}
|
||||
await first;
|
||||
});
|
||||
}
|
||||
|
||||
test('deletion confirms all five files despite refreshed selection',
|
||||
() async {
|
||||
platformFFI.setBindingForTesting(_FileBinding());
|
||||
final controller = _DeletingController();
|
||||
final files = ['a.txt', 'b.txt', 'c.txt', 'd.txt', 'e.txt']
|
||||
.map((name) => Entry()
|
||||
..name = name
|
||||
..path = '/selected/$name')
|
||||
.toList();
|
||||
controller.selectedItems.selectAll(files);
|
||||
|
||||
await controller.removeAction(controller.selectedItems);
|
||||
|
||||
expect(controller.confirmations, files.map((file) => file.path));
|
||||
expect(controller.selectedItems.items, isEmpty);
|
||||
});
|
||||
|
||||
test('a fast remote response is matched after registration', () async {
|
||||
late final FileFetcher fileFetcher;
|
||||
fileFetcher = FileFetcher(
|
||||
@@ -62,19 +181,6 @@ void main() {
|
||||
expect(directory.path, '/fast');
|
||||
});
|
||||
|
||||
test('a send failure fails and removes its registered task', () async {
|
||||
final failure = StateError('send failed');
|
||||
final fileFetcher = FileFetcher(
|
||||
() => _sessionId,
|
||||
readRemoteDirectory: (_, __, ___) => Future<void>.error(failure),
|
||||
);
|
||||
await expectLater(
|
||||
fileFetcher.fetchDirectory('/failed', false, false),
|
||||
throwsA(same(failure)),
|
||||
);
|
||||
expect(fileFetcher.hasPendingRemoteRead('/failed'), isFalse);
|
||||
});
|
||||
|
||||
test('a resolved Home path completes the sole empty-path request', () async {
|
||||
final sent = <_SentRead>[];
|
||||
final fileFetcher = FileFetcher(
|
||||
@@ -107,35 +213,6 @@ void main() {
|
||||
expect(controller.directory.value.path, '/home/user');
|
||||
});
|
||||
|
||||
test('an exact path response is not taken by a pending Home request',
|
||||
() async {
|
||||
final sent = <_SentRead>[];
|
||||
final fileFetcher = FileFetcher(
|
||||
() => _sessionId,
|
||||
readRemoteDirectory: (_, path, includeHidden) async {
|
||||
sent.add(_SentRead(path, includeHidden));
|
||||
},
|
||||
);
|
||||
final home = fileFetcher.fetchDirectory('', false, false);
|
||||
final regular = fileFetcher.fetchDirectory('/regular', false, false);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
var homeCompleted = false;
|
||||
home.then<void>((_) => homeCompleted = true);
|
||||
|
||||
fileFetcher.tryCompleteTask(_directoryJson('/unmatched'), 'false');
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(homeCompleted, isFalse);
|
||||
|
||||
fileFetcher.tryCompleteTask(_directoryJson('/regular'), 'false');
|
||||
expect((await regular).path, '/regular');
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(homeCompleted, isFalse);
|
||||
|
||||
fileFetcher.tryCompleteTask(_directoryJson('/home/user'), 'false');
|
||||
expect((await home).path, '/home/user');
|
||||
expect(sent.map((request) => request.path), ['', '/regular']);
|
||||
});
|
||||
|
||||
test('a read error completes the sole pending request', () async {
|
||||
final fileFetcher = FileFetcher(
|
||||
() => _sessionId,
|
||||
@@ -230,35 +307,6 @@ void main() {
|
||||
expect((await replacement).path, '/same');
|
||||
});
|
||||
|
||||
test('a late dispatch failure cannot remove a replacement task', () async {
|
||||
final dispatches = <Completer<void>>[];
|
||||
final fileFetcher = FileFetcher(
|
||||
() => _sessionId,
|
||||
readRemoteDirectory: (_, __, ___) {
|
||||
final dispatch = Completer<void>();
|
||||
dispatches.add(dispatch);
|
||||
return dispatch.future;
|
||||
},
|
||||
);
|
||||
final first = fileFetcher.fetchDirectory('/same', false, false);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final firstError = expectLater(first, throwsA(isA<StateError>()));
|
||||
fileFetcher.beginRemoteSession();
|
||||
await firstError;
|
||||
|
||||
final replacement = fileFetcher.fetchDirectory('/same', false, false);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(dispatches, hasLength(2));
|
||||
dispatches.first.completeError(StateError('late dispatch failure'));
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(fileFetcher.hasPendingRemoteRead('/same'), isTrue);
|
||||
fileFetcher.tryCompleteTask(_directoryJson('/same'), 'false');
|
||||
expect((await replacement).path, '/same');
|
||||
dispatches.last.complete();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
});
|
||||
|
||||
test('navigation ignores stale directory responses', () async {
|
||||
final fileFetcher = FileFetcher(
|
||||
() => _sessionId,
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
@TestOn('browser')
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:js' as js;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hbb/common/widgets/remote_input.dart';
|
||||
import 'package:flutter_hbb/mobile/widgets/floating_mouse_widgets.dart';
|
||||
import 'package:flutter_hbb/models/input_model.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Input extends Fake implements InputModel {
|
||||
final events = <(String, MouseButtons)>[];
|
||||
|
||||
@override
|
||||
Future<void> tapDown(MouseButtons button) async =>
|
||||
events.add(('down', button));
|
||||
|
||||
@override
|
||||
Future<void> tapUp(MouseButtons button) async => events.add(('up', button));
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {}
|
||||
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
||||
final syncs = <Completer<void>>[];
|
||||
|
||||
@override
|
||||
Future<void> syncCursorPosition() {
|
||||
final sync = Completer<void>();
|
||||
syncs.add(sync);
|
||||
return sync.future;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
setUp(() {
|
||||
isSpecialHoldDragActive = false;
|
||||
js.context['isMobile'] = js.allowInterop(() => true);
|
||||
js.context['getByName'] =
|
||||
js.allowInterop((String name, [String? key]) => '');
|
||||
js.context['setByName'] = js.allowInterop((String name, dynamic value) {});
|
||||
});
|
||||
tearDown(() {
|
||||
isSpecialHoldDragActive = false;
|
||||
for (final name in ['isMobile', 'getByName', 'setByName']) {
|
||||
js.context.deleteProperty(name);
|
||||
}
|
||||
});
|
||||
|
||||
for (final end in ['release', 'cancel', 'dispose']) {
|
||||
testWidgets('pending hold cannot press after $end', (tester) async {
|
||||
final cancel = end == 'cancel';
|
||||
final ffi = _FFI();
|
||||
final input = _Input();
|
||||
final cursor = _Cursor(ffi);
|
||||
final button = cancel ? MouseButtons.right : MouseButtons.left;
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Stack(children: [
|
||||
FloatingLeftRightButton(
|
||||
isLeft: !cancel, inputModel: input, cursorModel: cursor),
|
||||
]),
|
||||
));
|
||||
await tester.pump();
|
||||
final target = find.byType(FloatingLeftRightButton);
|
||||
final first = await tester.startGesture(tester.getCenter(target));
|
||||
await tester.pump(const Duration(milliseconds: 201));
|
||||
expect(cursor.syncs, hasLength(1));
|
||||
if (end == 'dispose') {
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
cursor.syncs.single.complete();
|
||||
await tester.pump(const Duration(milliseconds: 1));
|
||||
expect(input.events, isEmpty);
|
||||
return;
|
||||
}
|
||||
if (cancel) {
|
||||
await first.cancel();
|
||||
} else {
|
||||
await first.up();
|
||||
}
|
||||
// A new press must not make the old synchronization valid again.
|
||||
final second = await tester.startGesture(tester.getCenter(target));
|
||||
await tester.pump(const Duration(milliseconds: 201));
|
||||
cursor.syncs.first.complete();
|
||||
await tester.pump();
|
||||
expect(input.events, isEmpty);
|
||||
cursor.syncs.last.complete();
|
||||
await tester.pump();
|
||||
expect(input.events, [('down', button)]);
|
||||
await second.up();
|
||||
expect(input.events, [('down', button), ('up', button)]);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump(const Duration(milliseconds: 1));
|
||||
expect(input.events, [('down', button), ('up', button)]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,19 +4,6 @@ import 'package:flutter_hbb/models/input_modifier_utils.dart';
|
||||
|
||||
void main() {
|
||||
group('shouldReleaseStaleMobileShift', () {
|
||||
test('does not release when cached shift is already false', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: true,
|
||||
cachedShiftPressed: false,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.keyD,
|
||||
hasTrackedShiftKeyDown: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('releases one-shot mobile shift after a text key', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
@@ -30,20 +17,6 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('does not release manually toggled shift without tracked key down',
|
||||
() {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: true,
|
||||
cachedShiftPressed: true,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.keyD,
|
||||
hasTrackedShiftKeyDown: false,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('does not release when shift is still physically pressed', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
@@ -56,84 +29,9 @@ void main() {
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('does not release on non-mobile platforms', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: false,
|
||||
cachedShiftPressed: true,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.keyD,
|
||||
hasTrackedShiftKeyDown: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('releases on enter key', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: true,
|
||||
cachedShiftPressed: true,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.enter,
|
||||
hasTrackedShiftKeyDown: true,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('releases on arrow key', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: true,
|
||||
cachedShiftPressed: true,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.arrowLeft,
|
||||
hasTrackedShiftKeyDown: true,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('does not release on modifier events', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: true,
|
||||
cachedShiftPressed: true,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.shiftLeft,
|
||||
hasTrackedShiftKeyDown: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('does not release on shiftRight modifier events', () {
|
||||
expect(
|
||||
shouldReleaseStaleMobileShift(
|
||||
isMobile: true,
|
||||
cachedShiftPressed: true,
|
||||
actualShiftPressed: false,
|
||||
logicalKey: LogicalKeyboardKey.shiftRight,
|
||||
hasTrackedShiftKeyDown: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('shouldApplyTerminalInputModifiers', () {
|
||||
test('accepts ordinary single-character keyboard input', () {
|
||||
expect(shouldApplyTerminalInputModifiers('a'), isTrue);
|
||||
expect(shouldApplyTerminalInputModifiers(' '), isTrue);
|
||||
expect(shouldApplyTerminalInputModifiers('/'), isTrue);
|
||||
});
|
||||
|
||||
test('accepts supplementary-plane single-character keyboard input', () {
|
||||
expect(shouldApplyTerminalInputModifiers('😀'), isTrue);
|
||||
});
|
||||
|
||||
test('rejects terminal control bytes and multi-character sequences', () {
|
||||
for (final input in ['\x00', '\x03', '\t', '\n', '\r', '\x1B', '\x7F']) {
|
||||
expect(
|
||||
@@ -147,43 +45,6 @@ void main() {
|
||||
});
|
||||
|
||||
group('applyTerminalInputModifiers', () {
|
||||
test('keeps decomposed graphemes intact under Ctrl', () {
|
||||
const decomposedEAcute = 'e\u0301';
|
||||
|
||||
expect(
|
||||
applyTerminalInputModifiers(
|
||||
decomposedEAcute,
|
||||
ctrlLocked: true,
|
||||
altLocked: false,
|
||||
),
|
||||
decomposedEAcute,
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps non-ASCII graphemes intact under Ctrl', () {
|
||||
for (final input in ['é', '😀']) {
|
||||
expect(
|
||||
applyTerminalInputModifiers(
|
||||
input,
|
||||
ctrlLocked: true,
|
||||
altLocked: false,
|
||||
),
|
||||
input,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('maps Ctrl underscore to unit separator', () {
|
||||
expect(
|
||||
applyTerminalInputModifiers(
|
||||
'_',
|
||||
ctrlLocked: true,
|
||||
altLocked: false,
|
||||
),
|
||||
'\x1F',
|
||||
);
|
||||
});
|
||||
|
||||
test('maps the complete Ctrl symbol range', () {
|
||||
const mappings = {
|
||||
'[': '\x1B',
|
||||
@@ -219,22 +80,6 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('terminalPastePayload', () {
|
||||
test('wraps paste text when bracketed paste mode is active', () {
|
||||
expect(
|
||||
terminalPastePayload('d', bracketedPasteMode: true),
|
||||
'\x1B[200~d\x1B[201~',
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps a lone newline unchanged when bracketed paste is disabled', () {
|
||||
expect(
|
||||
terminalPastePayload('\n', bracketedPasteMode: false),
|
||||
'\n',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('prepareTerminalInputPayload', () {
|
||||
test('normalizes a mobile keyboard Enter to carriage return', () {
|
||||
expect(
|
||||
@@ -278,26 +123,9 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps large keyboard payloads unchanged when modifiers are inactive',
|
||||
() {
|
||||
final payload = 'd' * (1024 * 1024);
|
||||
|
||||
expect(
|
||||
prepareTerminalInputPayload(
|
||||
payload,
|
||||
source: TerminalInputSource.keyboard,
|
||||
isMobileOrWebMobile: false,
|
||||
bracketedPasteMode: false,
|
||||
ctrlLocked: false,
|
||||
altLocked: false,
|
||||
),
|
||||
payload,
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps decomposed graphemes intact with locked keyboard modifiers',
|
||||
() {
|
||||
const decomposedEAcute = 'e\u0301';
|
||||
const decomposedEAcute = 'é';
|
||||
|
||||
expect(
|
||||
prepareTerminalInputPayload(
|
||||
@@ -312,20 +140,6 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('preserves a lone pasted newline when modifiers are locked', () {
|
||||
expect(
|
||||
prepareTerminalInputPayload(
|
||||
'\n',
|
||||
source: TerminalInputSource.paste,
|
||||
isMobileOrWebMobile: true,
|
||||
bracketedPasteMode: false,
|
||||
ctrlLocked: true,
|
||||
altLocked: true,
|
||||
),
|
||||
'\n',
|
||||
);
|
||||
});
|
||||
|
||||
test('wraps paste without applying locked modifiers', () {
|
||||
expect(
|
||||
prepareTerminalInputPayload(
|
||||
@@ -373,25 +187,6 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'keeps default xterm paste behavior when virtual modifiers are inactive',
|
||||
() {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: true,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: false,
|
||||
modifierLockActive: false,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('handles Ctrl+V and Meta+V when a virtual modifier lock is active',
|
||||
() {
|
||||
expect(
|
||||
@@ -423,95 +218,6 @@ void main() {
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('handles paste shortcut repeats while a virtual lock is active', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: false,
|
||||
isKeyRepeat: true,
|
||||
controlPressed: true,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: false,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('ignores key-up and unmodified V events', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: false,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: true,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: false,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: false,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: false,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('ignores paste shortcuts with extra modifiers', () {
|
||||
for (final state in [
|
||||
(control: true, meta: false, alt: true, shift: false),
|
||||
(control: true, meta: false, alt: false, shift: true),
|
||||
(control: false, meta: true, alt: false, shift: true),
|
||||
(control: true, meta: true, alt: false, shift: false),
|
||||
]) {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyV,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: state.control,
|
||||
metaPressed: state.meta,
|
||||
altPressed: state.alt,
|
||||
shiftPressed: state.shift,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('ignores non-V key events', () {
|
||||
expect(
|
||||
shouldHandleTerminalPasteShortcut(
|
||||
platform: TargetPlatform.windows,
|
||||
logicalKey: LogicalKeyboardKey.keyC,
|
||||
isKeyDown: true,
|
||||
isKeyRepeat: false,
|
||||
controlPressed: true,
|
||||
metaPressed: false,
|
||||
altPressed: false,
|
||||
shiftPressed: false,
|
||||
modifierLockActive: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('shouldClearTerminalModifiersWhenRow3Collapses', () {
|
||||
@@ -526,29 +232,5 @@ void main() {
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('does not clear modifiers when row expands', () {
|
||||
expect(
|
||||
shouldClearTerminalModifiersWhenRow3Collapses(
|
||||
wasExpanded: false,
|
||||
willExpand: true,
|
||||
ctrlLocked: true,
|
||||
altLocked: true,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('clears Alt state when expanded row is collapsed', () {
|
||||
expect(
|
||||
shouldClearTerminalModifiersWhenRow3Collapses(
|
||||
wasExpanded: true,
|
||||
willExpand: false,
|
||||
ctrlLocked: false,
|
||||
altLocked: true,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'dart:ui' show PointerDeviceKind, SemanticsAction;
|
||||
|
||||
import 'package:flutter/gestures.dart' show kSecondaryMouseButton;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hbb/common/widgets/peer_card.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
const doubleClickInterval = Duration(milliseconds: 75);
|
||||
const dragOffset = Offset(150, 0);
|
||||
// Keep pointer cases semantics-off to cover parent/child gesture competition.
|
||||
// VM taps bypass browser click-to-semantics conversion; verify that in a browser.
|
||||
for (final action in ['physical clicks', 'semantic tap', 'keyboard']) {
|
||||
testWidgets('More $action opens once without connecting the card',
|
||||
(tester) async {
|
||||
var opened = 0;
|
||||
var connected = 0;
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Material(
|
||||
child: GestureDetector(
|
||||
excludeFromSemantics: true,
|
||||
onTap: () {},
|
||||
onDoubleTap: () => connected++,
|
||||
onLongPress: () {},
|
||||
child: Builder(builder: (context) {
|
||||
return Center(
|
||||
child: build_more(context, onTap: () {
|
||||
opened++;
|
||||
showMenu<void>(
|
||||
context: context,
|
||||
position: RelativeRect.fill,
|
||||
items: const [PopupMenuItem(child: Text('Connect'))],
|
||||
);
|
||||
}));
|
||||
}),
|
||||
),
|
||||
),
|
||||
));
|
||||
final button = find.byIcon(Icons.more_vert);
|
||||
final position = tester.getCenter(button);
|
||||
if (action == 'semantic tap') {
|
||||
final node = tester.getSemantics(button);
|
||||
node.owner!.performAction(node.id, SemanticsAction.tap);
|
||||
} else if (action == 'keyboard') {
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
} else {
|
||||
await tester.tapAt(position,
|
||||
kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton);
|
||||
await tester.pumpAndSettle();
|
||||
expect(opened, 0, reason: 'A secondary click must not open More');
|
||||
await tester.dragFrom(position, dragOffset,
|
||||
kind: PointerDeviceKind.mouse);
|
||||
await tester.pumpAndSettle();
|
||||
expect(opened, 0, reason: 'Dragging out must cancel the More tap');
|
||||
await tester.tapAt(position, kind: PointerDeviceKind.mouse);
|
||||
}
|
||||
expect(opened, 1,
|
||||
reason: 'More must not wait for a possible double click');
|
||||
await tester.pump();
|
||||
if (action == 'physical clicks') {
|
||||
await tester.pump(doubleClickInterval);
|
||||
await tester.tapAt(position, kind: PointerDeviceKind.mouse);
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
expect({'menu': opened, 'connection': connected},
|
||||
{'menu': 1, 'connection': 0});
|
||||
}, semanticsEnabled: action != 'physical clicks');
|
||||
}
|
||||
}
|
||||
@@ -50,54 +50,20 @@ void main() {
|
||||
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',
|
||||
testWidgets('alternate screen reports trackpad after main-screen history',
|
||||
(tester) async {
|
||||
final view = await mount(tester);
|
||||
terminal.write('\x1b[?1049h$_captureMouse');
|
||||
await tester.pump();
|
||||
final render = view.renderTerminal;
|
||||
final start = render.localToGlobal(
|
||||
final point = 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);
|
||||
await scrollTrackpad(tester, point, render.lineHeight * 3);
|
||||
|
||||
expect(output, ['\x1b[<0;3;2M', '\x1b[<32;7;3M', '\x1b[<0;7;3m']);
|
||||
expect(output, isNotEmpty);
|
||||
expect(output, everyElement('\x1b[<64;3;2M'));
|
||||
expect(view.widget.scrollController!.offset, 0);
|
||||
expect(controller.selection, isNull);
|
||||
expect(controller.suspendedPointerInputs, isFalse);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets('leaving alternate screen restores local trackpad scrollback',
|
||||
|
||||
@@ -17,24 +17,5 @@ void main() {
|
||||
['Ctrl', 'Alt', '-', 'PgUp', 'PgDn'],
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps two trailing Row3 placeholders for row alignment', () {
|
||||
expect(terminalKeyboardRow3TrailingPlaceholderCount, 2);
|
||||
});
|
||||
|
||||
test('keeps every expanded row aligned at 348dp', () {
|
||||
final rowWidths = [
|
||||
terminalKeyboardRowWidth(terminalKeyboardRow1Keys.length),
|
||||
terminalKeyboardRowWidth(terminalKeyboardRow2Keys.length + 1),
|
||||
terminalKeyboardRowWidth(
|
||||
terminalKeyboardRow3Keys.length +
|
||||
terminalKeyboardRow3TrailingPlaceholderCount,
|
||||
),
|
||||
];
|
||||
|
||||
expect(terminalKeyboardKeyWidth, 48);
|
||||
expect(terminalKeyboardKeySpacing, 2);
|
||||
expect(rowWidths, everyElement(348));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/terminal_model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -14,42 +12,6 @@ class _FakeFFI implements FFI {
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('ignores paste that completes after the terminal model is disposed',
|
||||
() async {
|
||||
final model = TerminalModel(_FakeFFI());
|
||||
final delayedClipboardText = Completer<String>();
|
||||
|
||||
// This mirrors Ctrl/Cmd+V: clipboard access starts first, then the page and
|
||||
// model are disposed before the asynchronous read supplies its text.
|
||||
final paste = delayedClipboardText.future.then(model.pasteText);
|
||||
model.dispose();
|
||||
delayedClipboardText.complete('late clipboard text');
|
||||
await paste;
|
||||
|
||||
expect(model.debugBufferedInputCount, 0);
|
||||
});
|
||||
|
||||
test('ignores terminal text input after the terminal model is disposed', () {
|
||||
final model = TerminalModel(_FakeFFI());
|
||||
var checkedCtrlLock = false;
|
||||
var clearedCtrlLock = false;
|
||||
|
||||
model.isCtrlLocked = () {
|
||||
checkedCtrlLock = true;
|
||||
return true;
|
||||
};
|
||||
model.clearCtrlLock = () {
|
||||
clearedCtrlLock = true;
|
||||
};
|
||||
|
||||
model.dispose();
|
||||
model.terminal.textInput('d');
|
||||
|
||||
expect(checkedCtrlLock, isFalse);
|
||||
expect(clearedCtrlLock, isFalse);
|
||||
expect(model.debugBufferedInputCount, 0);
|
||||
});
|
||||
|
||||
test('builds its terminal with the wheel button fix', () {
|
||||
final model = TerminalModel(_FakeFFI());
|
||||
addTearDown(model.dispose);
|
||||
|
||||
@@ -71,10 +71,9 @@ void main() {
|
||||
String? report(
|
||||
TerminalMouseButton button, [
|
||||
TerminalMouseButtonState state = TerminalMouseButtonState.down,
|
||||
CellOffset position = const CellOffset(10, 5),
|
||||
]) {
|
||||
output.clear();
|
||||
terminal.mouseInput(button, state, position);
|
||||
terminal.mouseInput(button, state, const CellOffset(10, 5));
|
||||
return output.isEmpty ? null : output.single;
|
||||
}
|
||||
|
||||
@@ -102,40 +101,6 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('reports utf-encoding wheel buttons beyond the normal-mode range', () {
|
||||
terminal.write('\x1b[?1000h\x1b[?1005h');
|
||||
|
||||
expect(
|
||||
report(
|
||||
TerminalMouseButton.wheelDown,
|
||||
TerminalMouseButtonState.down,
|
||||
const CellOffset(400, 300),
|
||||
),
|
||||
'\x1b[M${String.fromCharCode(32 + 65)}'
|
||||
'${String.fromCharCode(32 + 401)}${String.fromCharCode(32 + 301)}',
|
||||
);
|
||||
});
|
||||
|
||||
test('reports urxvt-encoding wheel buttons shifted by 32', () {
|
||||
terminal.write('\x1b[?1000h\x1b[?1015h');
|
||||
|
||||
expect(report(TerminalMouseButton.wheelUp), '\x1b[96;11;6M');
|
||||
expect(report(TerminalMouseButton.wheelDown), '\x1b[97;11;6M');
|
||||
});
|
||||
|
||||
test('sends a null byte for coordinates past the encoding limit', () {
|
||||
terminal.write('\x1b[?1000h');
|
||||
|
||||
expect(
|
||||
report(
|
||||
TerminalMouseButton.wheelUp,
|
||||
TerminalMouseButtonState.down,
|
||||
const CellOffset(300, 300),
|
||||
),
|
||||
'\x1b[M${String.fromCharCode(32 + 64)}\x00\x00',
|
||||
);
|
||||
});
|
||||
|
||||
test('leaves non-wheel buttons to the upstream handler', () {
|
||||
terminal.write('\x1b[?1000h\x1b[?1006h');
|
||||
|
||||
@@ -147,27 +112,6 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('stays silent when the peer has not enabled mouse reporting', () {
|
||||
expect(report(TerminalMouseButton.wheelDown), isNull);
|
||||
expect(report(TerminalMouseButton.left), isNull);
|
||||
});
|
||||
|
||||
test('stays silent for the wheel in click-only mode', () {
|
||||
terminal.write('\x1b[?9h\x1b[?1006h');
|
||||
|
||||
expect(report(TerminalMouseButton.wheelDown), isNull);
|
||||
expect(report(TerminalMouseButton.left), '\x1b[<0;11;6M');
|
||||
});
|
||||
|
||||
test('does not report wheel button releases', () {
|
||||
terminal.write('\x1b[?1000h\x1b[?1006h');
|
||||
|
||||
expect(
|
||||
report(TerminalMouseButton.wheelDown, TerminalMouseButtonState.up),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('dragging below scrolls and extends selection', (tester) async {
|
||||
final controller = TerminalController();
|
||||
_writeLines(terminal, 80);
|
||||
@@ -258,42 +202,4 @@ void main() {
|
||||
expect(output.last, '\x1b[<0;${endCell.x + 1};${endCell.y + 1}m');
|
||||
expect(controller.suspendedPointerInputs, isFalse);
|
||||
});
|
||||
|
||||
testWidgets('tmux drag stays suppressed after mouse mode is disabled',
|
||||
(tester) async {
|
||||
final controller = TerminalController();
|
||||
terminal.write('\x1b[?1049h\x1b[?1002h\x1b[?1006hword');
|
||||
await tester.pumpWidget(_terminalHarness(terminal, controller));
|
||||
final renderTerminal = tester
|
||||
.state<TerminalViewState>(find.byType(TerminalView))
|
||||
.renderTerminal;
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
final start = renderTerminal.localToGlobal(const Offset(40, 40));
|
||||
final end = renderTerminal.localToGlobal(const Offset(240, 80));
|
||||
await mouse.down(start);
|
||||
output.clear();
|
||||
terminal.write('\x1b[?1002l');
|
||||
await mouse.moveTo(end);
|
||||
|
||||
expect(output, isEmpty);
|
||||
expect(controller.selection, isNull);
|
||||
expect(controller.suspendedPointerInputs, isTrue);
|
||||
terminal.write('\x1b[?1002h');
|
||||
await mouse.moveTo(start);
|
||||
expect(output, isEmpty);
|
||||
expect(controller.selection, isNull);
|
||||
await mouse.up();
|
||||
expect(output, isEmpty);
|
||||
expect(controller.suspendedPointerInputs, isFalse);
|
||||
|
||||
await mouse.down(start);
|
||||
output.clear();
|
||||
terminal.write('\x1b[?1002l');
|
||||
await mouse.up();
|
||||
await tester.pump(kDoubleTapTimeout);
|
||||
|
||||
expect(output, isEmpty);
|
||||
expect(controller.selection, isNull);
|
||||
expect(controller.suspendedPointerInputs, isFalse);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "win32_desktop.h"
|
||||
#include "flutter_window.h"
|
||||
#include "utils.h"
|
||||
#include "service_control.h"
|
||||
|
||||
typedef char** (*FUNC_RUSTDESK_CORE_MAIN)(int*);
|
||||
typedef void (*FUNC_RUSTDESK_FREE_ARGS)( char**, int);
|
||||
@@ -23,6 +24,9 @@ const wchar_t* getWindowClassName();
|
||||
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||
_In_ wchar_t *command_line, _In_ int show_command)
|
||||
{
|
||||
if (auto result = service_control::HandleCommand(command_line)) {
|
||||
return static_cast<int>(*result);
|
||||
}
|
||||
HINSTANCE hInstance = LoadLibraryA("librustdesk.dll");
|
||||
if (!hInstance)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
#ifndef RUSTDESK_RUNNER_SERVICE_CONTROL_H_
|
||||
#define RUSTDESK_RUNNER_SERVICE_CONTROL_H_
|
||||
|
||||
#include <windows.h>
|
||||
#include <shellapi.h>
|
||||
#include <winsvc.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cwchar>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
namespace service_control {
|
||||
|
||||
using ServiceHandle = std::unique_ptr<std::remove_pointer_t<SC_HANDLE>,
|
||||
decltype(&CloseServiceHandle)>;
|
||||
constexpr DWORD kStopTimeoutMilliseconds = 30000;
|
||||
constexpr DWORD kPollIntervalMilliseconds = 100;
|
||||
|
||||
inline DWORD StopService(SC_HANDLE service) {
|
||||
SERVICE_STATUS_PROCESS status{};
|
||||
DWORD bytes_needed = 0;
|
||||
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
|
||||
reinterpret_cast<BYTE*>(&status), sizeof(status),
|
||||
&bytes_needed)) {
|
||||
return GetLastError();
|
||||
}
|
||||
if (status.dwCurrentState == SERVICE_STOPPED) {
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
if (status.dwCurrentState != SERVICE_STOP_PENDING) {
|
||||
SERVICE_STATUS stopped{};
|
||||
if (!ControlService(service, SERVICE_CONTROL_STOP, &stopped)) {
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SERVICE_NOT_ACTIVE ? ERROR_SUCCESS : error;
|
||||
}
|
||||
}
|
||||
// The installer may remove files next; accepting STOP alone does not mean
|
||||
// the service has reached SERVICE_STOPPED.
|
||||
const ULONGLONG started = GetTickCount64();
|
||||
while (status.dwCurrentState != SERVICE_STOPPED) {
|
||||
if (GetTickCount64() - started >= kStopTimeoutMilliseconds) {
|
||||
return ERROR_TIMEOUT;
|
||||
}
|
||||
Sleep(kPollIntervalMilliseconds);
|
||||
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
|
||||
reinterpret_cast<BYTE*>(&status), sizeof(status),
|
||||
&bytes_needed)) {
|
||||
return GetLastError();
|
||||
}
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
inline DWORD RemoveService(const wchar_t* name) {
|
||||
ServiceHandle manager(OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT),
|
||||
CloseServiceHandle);
|
||||
if (!manager) {
|
||||
return GetLastError();
|
||||
}
|
||||
ServiceHandle service(
|
||||
OpenServiceW(manager.get(), name,
|
||||
SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE),
|
||||
CloseServiceHandle);
|
||||
if (!service) {
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SERVICE_DOES_NOT_EXIST ? ERROR_SUCCESS : error;
|
||||
}
|
||||
const DWORD stopped = StopService(service.get());
|
||||
if (stopped != ERROR_SUCCESS) {
|
||||
// The uninstall script must still reach its taskkill cleanup.
|
||||
std::fwprintf(stderr,
|
||||
L"Service did not stop cleanly: Windows error %lu\n", stopped);
|
||||
}
|
||||
if (DeleteService(service.get())) {
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
const DWORD error = GetLastError();
|
||||
return error == ERROR_SERVICE_MARKED_FOR_DELETE ? ERROR_SUCCESS : error;
|
||||
}
|
||||
|
||||
inline DWORD InstallService(const wchar_t* name, const wchar_t* executable,
|
||||
bool rollback_on_failure) {
|
||||
if (!*executable || wcschr(executable, L'"')) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
const std::wstring binary_path =
|
||||
L"\"" + std::wstring(executable) + L"\" --service";
|
||||
const std::wstring display_name = std::wstring(name) + L" Service";
|
||||
ServiceHandle manager(
|
||||
OpenSCManagerW(nullptr, nullptr,
|
||||
SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE),
|
||||
CloseServiceHandle);
|
||||
if (!manager) {
|
||||
return GetLastError();
|
||||
}
|
||||
ServiceHandle service(
|
||||
CreateServiceW(manager.get(), name, display_name.c_str(),
|
||||
SERVICE_START | DELETE, SERVICE_WIN32_OWN_PROCESS,
|
||||
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
|
||||
binary_path.c_str(), nullptr,
|
||||
nullptr, nullptr, nullptr, nullptr),
|
||||
CloseServiceHandle);
|
||||
const bool created = service != nullptr;
|
||||
// --after-install can reuse a registration. Preserve its executable and
|
||||
// account, as the previous create-then-start script did.
|
||||
if (!service && GetLastError() == ERROR_SERVICE_EXISTS) {
|
||||
service.reset(OpenServiceW(manager.get(), name, SERVICE_START));
|
||||
}
|
||||
if (!service) {
|
||||
return GetLastError();
|
||||
}
|
||||
if (StartServiceW(service.get(), 0, nullptr)) {
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
const DWORD error = GetLastError();
|
||||
// Only manual Start Service restores stop-service=Y on failure. Other
|
||||
// installation paths retain the registration for a later startup attempt.
|
||||
if (rollback_on_failure && created && error != ERROR_SERVICE_ALREADY_RUNNING &&
|
||||
!DeleteService(service.get())) {
|
||||
const DWORD rollback_error = GetLastError();
|
||||
std::fwprintf(stderr,
|
||||
L"Failed to roll back newly created service: Windows error %lu\n",
|
||||
rollback_error);
|
||||
}
|
||||
return error == ERROR_SERVICE_ALREADY_RUNNING ? ERROR_SUCCESS : error;
|
||||
}
|
||||
|
||||
inline DWORD RunCommand(int count, wchar_t** args) {
|
||||
constexpr int kRemoveArgumentCount = 4;
|
||||
constexpr int kInstallArgumentCount = 5;
|
||||
if (count < kRemoveArgumentCount) {
|
||||
return ERROR_BAD_ARGUMENTS;
|
||||
}
|
||||
if (!*args[3]) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
const std::wstring_view operation(args[2]);
|
||||
const bool rollback_on_failure = operation == L"create-service-with-rollback";
|
||||
if ((operation == L"create-service" || rollback_on_failure) &&
|
||||
count == kInstallArgumentCount) {
|
||||
return InstallService(args[3], args[4], rollback_on_failure);
|
||||
}
|
||||
if (operation == L"remove" && count == kRemoveArgumentCount) {
|
||||
return RemoveService(args[3]);
|
||||
}
|
||||
return ERROR_BAD_ARGUMENTS;
|
||||
}
|
||||
|
||||
// Keep these commands in the existing runner so installation/removal can control
|
||||
// services before loading librustdesk.dll or initializing the UI. A Rust-side
|
||||
// handler would first require that DLL to load. The header-only implementation
|
||||
// keeps main.cpp as a dispatch hook without adding a CMake source entry; it is
|
||||
// compiled into the existing EXE, not a separately packaged helper.
|
||||
inline std::optional<DWORD> HandleCommand(const wchar_t* command_line) {
|
||||
constexpr std::wstring_view option = L"--service-control";
|
||||
const std::wstring_view arguments(command_line);
|
||||
if (arguments.compare(0, option.size(), option) != 0 ||
|
||||
(arguments.size() > option.size() && arguments[option.size()] != L' ' &&
|
||||
arguments[option.size()] != L'\t')) {
|
||||
return std::nullopt;
|
||||
}
|
||||
int count = 0;
|
||||
wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
|
||||
if (!args) {
|
||||
return GetLastError();
|
||||
}
|
||||
const DWORD result = RunCommand(count, args);
|
||||
LocalFree(args);
|
||||
if (result != ERROR_SUCCESS) {
|
||||
std::fwprintf(stderr,
|
||||
L"RustDesk service control failed with Windows error %lu\n",
|
||||
result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace service_control
|
||||
|
||||
#endif // RUSTDESK_RUNNER_SERVICE_CONTROL_H_
|
||||
@@ -84,6 +84,8 @@ message LoginRequest {
|
||||
string my_platform = 13;
|
||||
bytes hwid = 14;
|
||||
string avatar = 17;
|
||||
bytes trusted_device_v2_token = 18;
|
||||
bool trusted_device_v2_supported = 19;
|
||||
}
|
||||
|
||||
message Terminal {
|
||||
@@ -93,6 +95,7 @@ message Terminal {
|
||||
message Auth2FA {
|
||||
string code = 1;
|
||||
bytes hwid = 2;
|
||||
bool trust_this_device = 3;
|
||||
}
|
||||
|
||||
message ChatMessage { string text = 1; }
|
||||
@@ -147,6 +150,8 @@ message LoginResponse {
|
||||
PeerInfo peer_info = 2;
|
||||
}
|
||||
bool enable_trusted_devices = 3;
|
||||
bool trusted_device_v2_supported = 4;
|
||||
bytes trusted_device_v2_token = 5;
|
||||
}
|
||||
|
||||
message TouchScaleUpdate {
|
||||
@@ -1030,5 +1035,7 @@ message Message {
|
||||
TerminalAction terminal_action = 31;
|
||||
TerminalResponse terminal_response = 32;
|
||||
PortForwardChannel port_forward_channel = 33;
|
||||
// Auto Login: the peer types the password only if it is at its logon or lock screen.
|
||||
OSLogin os_login = 34;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ 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_TRUSTED_DEVICE_EXPIRATION: &str = "trusted-device-expiration-days";
|
||||
pub const OPTION_AV1_TEST: &str = "av1-test";
|
||||
/// Maximum number of files allowed during a single file transfer request.
|
||||
///
|
||||
@@ -311,6 +312,7 @@ pub const KEYS_SETTINGS: &[&str] = &[
|
||||
OPTION_API_SERVER,
|
||||
OPTION_KEY,
|
||||
OPTION_ALLOW_WEBSOCKET,
|
||||
OPTION_WEBSOCKET_PORT,
|
||||
OPTION_PRESET_ADDRESS_BOOK_NAME,
|
||||
OPTION_PRESET_ADDRESS_BOOK_TAG,
|
||||
OPTION_PRESET_ADDRESS_BOOK_ALIAS,
|
||||
@@ -322,6 +324,7 @@ pub const KEYS_SETTINGS: &[&str] = &[
|
||||
OPTION_ENABLE_DIRECTX_CAPTURE,
|
||||
OPTION_ENABLE_ANDROID_SOFTWARE_ENCODING_HALF_SCALE,
|
||||
OPTION_ENABLE_TRUSTED_DEVICES,
|
||||
OPTION_TRUSTED_DEVICE_EXPIRATION,
|
||||
OPTION_RELAY_SERVER,
|
||||
OPTION_ICE_SERVERS,
|
||||
OPTION_DISABLE_UDP,
|
||||
|
||||
+170
-63
@@ -27,6 +27,21 @@ use hbb_common::{
|
||||
|
||||
static NEXT_JOB_ID: AtomicI32 = AtomicI32::new(1);
|
||||
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
pub mod android;
|
||||
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
mod android_transfer;
|
||||
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
mod android_descriptor;
|
||||
|
||||
pub mod download;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "fs/download_tests.rs"]
|
||||
mod download_tests;
|
||||
|
||||
pub fn get_next_job_id() -> i32 {
|
||||
NEXT_JOB_ID.fetch_add(1, Ordering::SeqCst)
|
||||
}
|
||||
@@ -36,6 +51,10 @@ pub fn update_next_job_id(id: i32) {
|
||||
}
|
||||
|
||||
pub fn read_dir(path: &Path, include_hidden: bool) -> ResultType<FileDirectory> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(path) {
|
||||
return android::read_dir(&get_string(path), include_hidden);
|
||||
}
|
||||
let mut dir = FileDirectory {
|
||||
path: get_string(path),
|
||||
..Default::default()
|
||||
@@ -140,6 +159,15 @@ pub fn get_path(path: &str) -> PathBuf {
|
||||
|
||||
#[inline]
|
||||
pub fn get_home_as_string() -> String {
|
||||
#[cfg(target_os = "android")]
|
||||
match android::home() {
|
||||
Ok(Some(path)) => return path,
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
log::trace!("Unable to load the selected document location: {}", error);
|
||||
return android::ROOT.trim_end_matches('/').to_owned();
|
||||
}
|
||||
}
|
||||
get_string(&Config::get_home())
|
||||
}
|
||||
|
||||
@@ -203,6 +231,10 @@ fn read_dir_recursive(
|
||||
}
|
||||
|
||||
pub fn get_recursive_files(path: &str, include_hidden: bool) -> ResultType<Vec<FileEntry>> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(Path::new(path)) {
|
||||
return android::recursive_files(path, include_hidden);
|
||||
}
|
||||
read_dir_recursive(&get_path(path), &get_path(""), include_hidden)
|
||||
}
|
||||
|
||||
@@ -248,6 +280,10 @@ pub fn get_empty_dirs_recursive(
|
||||
path: &str,
|
||||
include_hidden: bool,
|
||||
) -> ResultType<Vec<FileDirectory>> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(Path::new(path)) {
|
||||
return android::empty_dirs(path, include_hidden);
|
||||
}
|
||||
read_empty_dirs_recursive(&get_path(path), &get_path(""), include_hidden)
|
||||
}
|
||||
|
||||
@@ -391,6 +427,9 @@ pub struct FileDigest {
|
||||
#[derive(Default, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TransferJob {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
#[serde(skip)]
|
||||
document_transfer: android_transfer::DocumentTransfer,
|
||||
pub id: i32,
|
||||
pub r#type: JobType,
|
||||
pub remote: String,
|
||||
@@ -417,6 +456,8 @@ pub struct TransferJob {
|
||||
default_overwrite_strategy: Option<bool>,
|
||||
#[serde(skip_serializing)]
|
||||
digest: FileDigest,
|
||||
#[serde(skip)]
|
||||
download: Option<download::DownloadState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
|
||||
@@ -517,6 +558,11 @@ fn validate_fs_path_argument(path: &str, arg_name: &str) -> ResultType<()> {
|
||||
}
|
||||
|
||||
fn validate_no_symlink_components(base: &PathBuf, name: &str) -> ResultType<()> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(base) {
|
||||
// Document IDs are resolved and confined to their grant by Android, not the OS filesystem.
|
||||
return Ok(());
|
||||
}
|
||||
if name.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -576,6 +622,10 @@ impl TransferJob {
|
||||
enable_overwrite_detection: bool,
|
||||
) -> Self {
|
||||
log::info!("new write {}", data_source);
|
||||
let is_download = is_remote && r#type == JobType::Generic;
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
let is_download = is_download
|
||||
&& !matches!(&data_source, DataSource::FilePath(path) if android::is_path(path));
|
||||
Self {
|
||||
id,
|
||||
r#type,
|
||||
@@ -587,6 +637,7 @@ impl TransferJob {
|
||||
files: Vec::new(),
|
||||
total_size: 0,
|
||||
enable_overwrite_detection,
|
||||
download: is_download.then(Default::default),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -648,6 +699,17 @@ impl TransferJob {
|
||||
|
||||
#[inline]
|
||||
pub fn set_files(&mut self, files: Vec<FileEntry>) -> ResultType<()> {
|
||||
if self.is_download() && !self.files.is_empty() {
|
||||
bail!("cannot replace an accepted download file list");
|
||||
}
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_remote
|
||||
&& self.r#type == JobType::Generic
|
||||
&& self.is_document()
|
||||
&& !self.files.is_empty()
|
||||
{
|
||||
bail!("cannot replace an accepted download file list");
|
||||
}
|
||||
validate_transfer_file_names(&files)?;
|
||||
if let DataSource::FilePath(base) = &self.data_source {
|
||||
for file in &files {
|
||||
@@ -692,7 +754,12 @@ impl TransferJob {
|
||||
|
||||
fn resolve_entry_path(&self, base: &PathBuf, name: &str) -> Option<PathBuf> {
|
||||
if self.r#type == JobType::Generic {
|
||||
match join_validated_path(base, name) {
|
||||
let result = if self.is_download() {
|
||||
download::validated_target(base, name)
|
||||
} else {
|
||||
join_validated_path(base, name)
|
||||
};
|
||||
match result {
|
||||
Ok(path) => Some(path),
|
||||
Err(err) => {
|
||||
log::error!("Invalid file name in transfer job {}: {}", self.id, err);
|
||||
@@ -705,6 +772,16 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub fn modify_time(&self) {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
return;
|
||||
}
|
||||
if self.is_download() {
|
||||
if let Err(err) = self.finish_download() {
|
||||
log::error!("Failed to finish download {}: {}", self.id, err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.r#type == JobType::Printer {
|
||||
return;
|
||||
}
|
||||
@@ -729,6 +806,13 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub fn remove_download_file(&self) {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
return;
|
||||
}
|
||||
if self.is_download() && self.data_stream.is_none() {
|
||||
return;
|
||||
}
|
||||
if self.r#type == JobType::Printer {
|
||||
return;
|
||||
}
|
||||
@@ -761,9 +845,16 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub async fn write(&mut self, block: FileTransferBlock) -> ResultType<()> {
|
||||
if self.is_download() {
|
||||
return self.write_download(block).await;
|
||||
}
|
||||
if block.id != self.id {
|
||||
bail!("Wrong id");
|
||||
}
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
return self.write_document(block).await;
|
||||
}
|
||||
match &self.data_source {
|
||||
DataSource::FilePath(p) => {
|
||||
let file_num = block.file_num as usize;
|
||||
@@ -843,6 +934,10 @@ impl TransferJob {
|
||||
/// Open the data stream for the current file.
|
||||
/// Returns Ok(true) if job is done, Ok(false) otherwise.
|
||||
async fn open_data_stream(&mut self) -> ResultType<bool> {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
return self.open_document_stream().await;
|
||||
}
|
||||
let file_num = self.file_num as usize;
|
||||
match &mut self.data_source {
|
||||
DataSource::FilePath(p) => {
|
||||
@@ -882,6 +977,14 @@ impl TransferJob {
|
||||
|
||||
/// Get current file's digest (last_modified, file_size) for overwrite detection.
|
||||
async fn get_current_digest(&self) -> ResultType<(u64, u64)> {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
let entry = self
|
||||
.files
|
||||
.get(self.file_num as usize)
|
||||
.ok_or(anyhow!("Wrong file number"))?;
|
||||
return Ok((entry.modified_time, entry.size));
|
||||
}
|
||||
let meta = match self.data_stream.as_ref().ok_or(anyhow!("file is None"))? {
|
||||
DataStream::FileStream(file) => file.metadata().await?,
|
||||
DataStream::BufStream(_) => bail!("No digest for buf stream"),
|
||||
@@ -970,6 +1073,10 @@ impl TransferJob {
|
||||
self.data_stream = None;
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
self.fail_document_read(err.to_string());
|
||||
}
|
||||
return Err(err.into());
|
||||
}
|
||||
Ok(n) => {
|
||||
@@ -982,6 +1089,10 @@ impl TransferJob {
|
||||
}
|
||||
unsafe { buf.set_len(offset) };
|
||||
if offset == 0 {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
self.finish_document_read().await?;
|
||||
}
|
||||
if matches!(self.data_source, DataSource::MemoryCursor(_)) {
|
||||
self.data_stream.take();
|
||||
return Ok(None);
|
||||
@@ -1089,6 +1200,10 @@ impl TransferJob {
|
||||
|
||||
/// Get job error message, useful for getting status when job had finished
|
||||
pub fn job_error(&self) -> Option<String> {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if let Some(error) = &self.document_transfer.error {
|
||||
return Some(error.clone());
|
||||
}
|
||||
if self.job_skipped() {
|
||||
return Some("skipped".to_string());
|
||||
}
|
||||
@@ -1106,6 +1221,13 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
async fn set_stream_offset(&mut self, file_num: usize, offset: u64) {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() {
|
||||
if let Err(error) = self.seek_document(offset).await {
|
||||
self.fail_document_read(error.to_string());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if file_num >= self.files.len() {
|
||||
return;
|
||||
}
|
||||
@@ -1160,6 +1282,17 @@ impl TransferJob {
|
||||
}
|
||||
|
||||
pub async fn confirm(&mut self, r: &FileTransferSendConfirmRequest) -> bool {
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
if self.is_document() && self.is_remote {
|
||||
self.confirm_document(r);
|
||||
}
|
||||
if self.is_download() {
|
||||
self.confirm_download(r);
|
||||
// Open receiver resume streams in write() so validation errors reach the caller.
|
||||
if matches!(r.union, Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) if offset > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if self.file_num() != r.file_num {
|
||||
// This branch will always be hit if:
|
||||
// 1. `confirm()` is called in `ui_cm_interface.rs`
|
||||
@@ -1388,6 +1521,10 @@ pub async fn handle_read_jobs(
|
||||
}
|
||||
|
||||
pub fn remove_all_empty_dir(path: &Path) -> ResultType<()> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(path) {
|
||||
return android::remove_empty_tree(&get_string(path));
|
||||
}
|
||||
let fd = read_dir(path, true)?;
|
||||
for entry in fd.entries.iter() {
|
||||
match entry.entry_type.enum_value() {
|
||||
@@ -1406,6 +1543,10 @@ pub fn remove_all_empty_dir(path: &Path) -> ResultType<()> {
|
||||
|
||||
#[inline]
|
||||
pub fn remove_file(file: &str) -> ResultType<()> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(Path::new(file)) {
|
||||
return android::remove_file(file);
|
||||
}
|
||||
validate_fs_path_argument(file, "file path")?;
|
||||
std::fs::remove_file(get_path(file))?;
|
||||
Ok(())
|
||||
@@ -1413,6 +1554,10 @@ pub fn remove_file(file: &str) -> ResultType<()> {
|
||||
|
||||
#[inline]
|
||||
pub fn create_dir(dir: &str) -> ResultType<()> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(Path::new(dir)) {
|
||||
return android::operation("mkdir", dir);
|
||||
}
|
||||
validate_fs_path_argument(dir, "directory path")?;
|
||||
std::fs::create_dir_all(get_path(dir))?;
|
||||
Ok(())
|
||||
@@ -1420,6 +1565,10 @@ pub fn create_dir(dir: &str) -> ResultType<()> {
|
||||
|
||||
#[inline]
|
||||
pub fn rename_file(path: &str, new_name: &str) -> ResultType<()> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(Path::new(path)) {
|
||||
return android::rename(path, new_name);
|
||||
}
|
||||
validate_fs_path_argument(path, "path")?;
|
||||
if new_name.is_empty() {
|
||||
bail!("new file name cannot be empty");
|
||||
@@ -1457,6 +1606,26 @@ pub fn is_write_need_confirmation(
|
||||
file_path: &str,
|
||||
digest: &FileTransferDigest,
|
||||
) -> ResultType<DigestCheckResult> {
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
if android::is_path(Path::new(file_path)) {
|
||||
android::validate(file_path)?;
|
||||
if is_resume {
|
||||
bail!("Document transfers must be restarted after interruption");
|
||||
}
|
||||
return match android::stat(file_path)? {
|
||||
Some(entry) => Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
|
||||
id: digest.id,
|
||||
file_num: digest.file_num,
|
||||
last_modified: entry.modified_time,
|
||||
file_size: entry.size,
|
||||
is_identical: entry.modified_time != 0
|
||||
&& entry.modified_time == digest.last_modified
|
||||
&& entry.size == digest.file_size,
|
||||
..Default::default()
|
||||
})),
|
||||
None => Ok(DigestCheckResult::NoSuchFile),
|
||||
};
|
||||
}
|
||||
let path = Path::new(file_path);
|
||||
let digest_file = format!("{}.digest", file_path);
|
||||
let download_file = format!("{}.download", file_path);
|
||||
@@ -1677,15 +1846,6 @@ mod tests {
|
||||
assert_err_contains(err, "empty file name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_files_rejects_null_byte_name() {
|
||||
let mut job = new_validation_job(103);
|
||||
let err = job
|
||||
.set_files(vec![new_file_entry("bad\0name.txt")])
|
||||
.expect_err("null byte in file name must be rejected");
|
||||
assert_err_contains(err, "null bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_files_rejects_mixed_entries_when_one_is_traversal() {
|
||||
let mut job = new_validation_job(104);
|
||||
@@ -1708,39 +1868,6 @@ mod tests {
|
||||
assert_err_contains(err, "absolute path");
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn set_files_allows_backslash_prefixed_name_on_unix() {
|
||||
let mut job = new_validation_job(105);
|
||||
assert!(job
|
||||
.set_files(vec![new_file_entry("\\\\server\\share\\payload.txt")])
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_file_rejects_empty_path() {
|
||||
let err = remove_file("").expect_err("empty file path must be rejected");
|
||||
assert_err_contains(err, "cannot be empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_file_rejects_null_byte_path() {
|
||||
let err = remove_file("bad\0path").expect_err("null byte path must be rejected");
|
||||
assert_err_contains(err, "null bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_dir_rejects_empty_path() {
|
||||
let err = create_dir("").expect_err("empty directory path must be rejected");
|
||||
assert_err_contains(err, "cannot be empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_dir_rejects_null_byte_path() {
|
||||
let err = create_dir("bad\0path").expect_err("null byte path must be rejected");
|
||||
assert_err_contains(err, "null bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_file_rejects_invalid_new_name() {
|
||||
let tmp_root = TestTempDir::new("rustdesk_rename_invalid");
|
||||
@@ -1790,24 +1917,4 @@ mod tests {
|
||||
assert!(!src.exists());
|
||||
assert!(dst.exists());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn set_files_rejects_windows_drive_absolute_path() {
|
||||
let mut job = new_validation_job(106);
|
||||
let err = job
|
||||
.set_files(vec![new_file_entry("C:\\Windows\\Temp\\payload.txt")])
|
||||
.expect_err("drive-letter absolute path must be rejected");
|
||||
assert_err_contains(err, "absolute path");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn set_files_rejects_windows_verbatim_drive_absolute_path() {
|
||||
let mut job = new_validation_job(1061);
|
||||
let err = job
|
||||
.set_files(vec![new_file_entry(r"\\?\C:\Windows\Temp\x.txt")])
|
||||
.expect_err("verbatim drive absolute path must be rejected");
|
||||
assert_err_contains(err, "absolute path");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
use super::{FileDirectory, FileEntry, FileType};
|
||||
use hbb_common::{anyhow::anyhow, bail, ResultType};
|
||||
use serde_derive::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::{path::Path, sync::OnceLock};
|
||||
|
||||
pub const ROOT: &str = "/@rustdesk/";
|
||||
type Request = Box<dyn Fn(&str) -> ResultType<String> + Send + Sync>;
|
||||
static BACKEND: OnceLock<Request> = OnceLock::new();
|
||||
|
||||
pub fn initialize(
|
||||
request: impl Fn(&str) -> ResultType<String> + Send + Sync + 'static,
|
||||
) -> ResultType<()> {
|
||||
BACKEND
|
||||
.set(Box::new(request))
|
||||
.map_err(|_| anyhow!("Document storage already initialized"))
|
||||
}
|
||||
|
||||
pub fn is_path(path: &Path) -> bool {
|
||||
path.to_str().map_or(false, |p| {
|
||||
p == ROOT.trim_end_matches('/') || p.starts_with(ROOT)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn validate(path: &str) -> ResultType<()> {
|
||||
let relative = path
|
||||
.strip_prefix(ROOT)
|
||||
.and_then(|path| path.strip_prefix("tree/"))
|
||||
.ok_or(anyhow!("Invalid document path"))?;
|
||||
if relative
|
||||
.split('/')
|
||||
.any(|p| p.is_empty() || p == "." || p == ".." || p.contains(['\\', '\0']))
|
||||
{
|
||||
bail!("Invalid document path");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn request(value: Value) -> ResultType<Value> {
|
||||
if let Some(path) = value.get("path").and_then(Value::as_str) {
|
||||
validate(path)?;
|
||||
}
|
||||
let backend = BACKEND
|
||||
.get()
|
||||
.ok_or(anyhow!("Android document storage is unavailable"))?;
|
||||
let response: Value = serde_json::from_str(&backend(&value.to_string())?)?;
|
||||
if let Some(error) = response.get("error").and_then(Value::as_str) {
|
||||
bail!("{}", error);
|
||||
}
|
||||
response
|
||||
.get("value")
|
||||
.cloned()
|
||||
.ok_or(anyhow!("Invalid document provider response"))
|
||||
}
|
||||
|
||||
pub fn home() -> ResultType<Option<String>> {
|
||||
let value = request(json!({"op": "home"}))?;
|
||||
if value.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = value.as_str().ok_or(anyhow!("Invalid document home"))?;
|
||||
validate(path)?;
|
||||
Ok(Some(path.to_owned()))
|
||||
}
|
||||
|
||||
pub fn allowed(path: &str) -> ResultType<bool> {
|
||||
if !home()?.map_or(false, |home| Path::new(path).starts_with(home)) {
|
||||
return Ok(false);
|
||||
}
|
||||
request(json!({"op": "allowed", "path": path}))?
|
||||
.as_bool()
|
||||
.ok_or(anyhow!("Invalid document permission response"))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Metadata {
|
||||
name: String,
|
||||
directory: bool,
|
||||
size: i64,
|
||||
modified: i64,
|
||||
}
|
||||
|
||||
fn entry(value: Value) -> ResultType<FileEntry> {
|
||||
let meta: Metadata = serde_json::from_value(value)?;
|
||||
super::validate_file_name_no_traversal(&meta.name)?;
|
||||
if meta.name.contains('/') || (!meta.directory && meta.size < 0) {
|
||||
bail!("The provider did not supply a transferable file name or size");
|
||||
}
|
||||
Ok(FileEntry {
|
||||
entry_type: if meta.directory {
|
||||
FileType::Dir
|
||||
} else {
|
||||
FileType::File
|
||||
}
|
||||
.into(),
|
||||
is_hidden: meta.name.starts_with('.'),
|
||||
name: meta.name,
|
||||
size: if meta.directory { 0 } else { meta.size as u64 },
|
||||
modified_time: meta.modified.max(0) as u64,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stat(path: &str) -> ResultType<Option<FileEntry>> {
|
||||
let value = request(json!({"op": "stat", "path": path}))?;
|
||||
if value.is_null() {
|
||||
Ok(None)
|
||||
} else {
|
||||
entry(value).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_dir(path: &str, hidden: bool) -> ResultType<FileDirectory> {
|
||||
let values: Vec<Value> = serde_json::from_value(request(json!({"op": "list", "path": path}))?)?;
|
||||
let mut entries = Vec::new();
|
||||
for value in values {
|
||||
let entry = entry(value)?;
|
||||
if hidden || !entry.is_hidden {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
Ok(FileDirectory {
|
||||
path: path.to_owned(),
|
||||
entries,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn recursive_files(path: &str, hidden: bool) -> ResultType<Vec<FileEntry>> {
|
||||
let meta = stat(path)?.ok_or(anyhow!("Document does not exist"))?;
|
||||
if meta.entry_type.enum_value() == Ok(FileType::File) {
|
||||
return Ok(vec![FileEntry {
|
||||
name: String::new(),
|
||||
..meta
|
||||
}]);
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut pending = vec![(path.to_owned(), String::new())];
|
||||
while let Some((directory, prefix)) = pending.pop() {
|
||||
for mut entry in read_dir(&directory, hidden)?.entries {
|
||||
let path = format!("{}/{}", directory, entry.name);
|
||||
entry.name = if prefix.is_empty() {
|
||||
entry.name
|
||||
} else {
|
||||
format!("{}/{}", prefix, entry.name)
|
||||
};
|
||||
if entry.entry_type.enum_value() == Ok(FileType::Dir) {
|
||||
pending.push((path, entry.name));
|
||||
} else {
|
||||
files.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
pub fn empty_dirs(path: &str, hidden: bool) -> ResultType<Vec<FileDirectory>> {
|
||||
let mut result = Vec::new();
|
||||
let mut pending = vec![path.to_owned()];
|
||||
while let Some(path) = pending.pop() {
|
||||
let directory = read_dir(&path, hidden)?;
|
||||
if directory.entries.is_empty() {
|
||||
result.push(directory);
|
||||
continue;
|
||||
}
|
||||
for entry in directory.entries {
|
||||
if entry.entry_type.enum_value() == Ok(FileType::Dir) {
|
||||
pending.push(format!("{}/{}", path, entry.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn operation(op: &str, path: &str) -> ResultType<()> {
|
||||
request(json!({"op": op, "path": path}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_empty_dir(path: &str) -> ResultType<()> {
|
||||
if !read_dir(path, true)?.entries.is_empty() {
|
||||
bail!("Directory is not empty");
|
||||
}
|
||||
operation("delete", path)
|
||||
}
|
||||
|
||||
pub fn remove_file(path: &str) -> ResultType<()> {
|
||||
let entry = stat(path)?.ok_or(anyhow!("Document does not exist"))?;
|
||||
if entry.entry_type.enum_value() != Ok(FileType::File) {
|
||||
bail!("Cannot remove a directory as a file");
|
||||
}
|
||||
operation("delete", path)
|
||||
}
|
||||
|
||||
pub fn remove_empty_tree(path: &str) -> ResultType<()> {
|
||||
validate(path)?;
|
||||
let tree_prefix = Path::new(ROOT).join("tree");
|
||||
if Path::new(path).parent().and_then(Path::parent) == Some(tree_prefix.as_path()) {
|
||||
bail!("Cannot delete a shared root");
|
||||
}
|
||||
let mut directories = vec![path.to_owned()];
|
||||
let mut index = 0;
|
||||
while index < directories.len() {
|
||||
for entry in read_dir(&directories[index], true)?.entries {
|
||||
if entry.entry_type.enum_value() != Ok(FileType::Dir) {
|
||||
bail!("Directory is not empty");
|
||||
}
|
||||
directories.push(format!("{}/{}", directories[index], entry.name));
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
for directory in directories.into_iter().rev() {
|
||||
remove_empty_dir(&directory)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn rename(path: &str, name: &str) -> ResultType<()> {
|
||||
super::validate_file_name_no_traversal(name)?;
|
||||
request(json!({"op": "rename", "path": path, "name": name}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
pub fn take_file(value: &Value) -> ResultType<std::fs::File> {
|
||||
use std::convert::TryFrom;
|
||||
use std::os::fd::FromRawFd;
|
||||
let fd = value
|
||||
.as_i64()
|
||||
.and_then(|fd| i32::try_from(fd).ok())
|
||||
.filter(|fd| *fd >= 0)
|
||||
.ok_or(anyhow!("Invalid document descriptor"))?;
|
||||
// Android hands off a duplicate; Java retains the provider's close/error channel.
|
||||
Ok(unsafe { std::fs::File::from_raw_fd(fd) })
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "android", all(test, unix)))]
|
||||
pub(super) async fn open(
|
||||
path: String,
|
||||
) -> ResultType<(
|
||||
tokio::fs::File,
|
||||
super::android_descriptor::DocumentDescriptor,
|
||||
Option<(u64, u64)>,
|
||||
)> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
let (file, descriptor, digest) = tokio::task::spawn_blocking(move || {
|
||||
let token = request(json!({"op": "open", "path": path}))?;
|
||||
let file = take_file(&token["fd"])?;
|
||||
let descriptor = super::android_descriptor::DocumentDescriptor::new(&token)?;
|
||||
let metadata = file.metadata()?;
|
||||
// Stream inode timestamps do not identify the source document's version.
|
||||
let digest = metadata
|
||||
.is_file()
|
||||
.then(|| (metadata.mtime().max(0) as u64, metadata.len()));
|
||||
Ok::<_, hbb_common::anyhow::Error>((file, descriptor, digest))
|
||||
})
|
||||
.await??;
|
||||
Ok((tokio::fs::File::from_std(file), descriptor, digest))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/android_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod metadata_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn negative_modification_time_is_unknown() {
|
||||
for modified in [-1, 0, 1] {
|
||||
let metadata = entry(json!({
|
||||
"name": "notes.txt", "directory": false, "size": 12, "modified": modified
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(metadata.modified_time, modified.max(0) as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use super::android;
|
||||
use hbb_common::{anyhow::anyhow, ResultType};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::Duration;
|
||||
|
||||
const CLOSE_ERROR_LOG_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct DocumentDescriptor {
|
||||
id: Option<String>,
|
||||
}
|
||||
|
||||
impl DocumentDescriptor {
|
||||
pub(super) fn new(token: &Value) -> ResultType<Self> {
|
||||
let id = token["descriptor"]
|
||||
.as_str()
|
||||
.ok_or(anyhow!("Missing document descriptor"))?;
|
||||
Ok(Self {
|
||||
id: Some(id.to_owned()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn close(mut self, error: &str) -> ResultType<()> {
|
||||
let id = self.id.take().ok_or(anyhow!("Document already closed"))?;
|
||||
let error = error.to_owned();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
android::request(json!({
|
||||
"op": "close", "descriptor": id, "error": error
|
||||
}))
|
||||
})
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DocumentDescriptor {
|
||||
fn drop(&mut self) {
|
||||
let Some(id) = self.id.take() else {
|
||||
return;
|
||||
};
|
||||
// Aborted jobs must also release the provider's retained descriptor.
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if let Err(error) = android::request(json!({
|
||||
"op": "close", "descriptor": id, "error": "Document transfer interrupted"
|
||||
})) {
|
||||
hbb_common::throttled_log!(
|
||||
CLOSE_ERROR_LOG_INTERVAL,
|
||||
warn,
|
||||
"Unable to release document descriptor: {}",
|
||||
error
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
use super::{
|
||||
android, android_descriptor::DocumentDescriptor, file_transfer_send_confirm_request,
|
||||
DataSource, DataStream, FileTransferBlock, FileTransferSendConfirmRequest, TransferJob,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, compress::decompress, ResultType};
|
||||
use serde_json::{json, Value};
|
||||
use tokio::{
|
||||
fs::File,
|
||||
io::{AsyncSeekExt, AsyncWriteExt},
|
||||
task::spawn_blocking,
|
||||
};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct DocumentTransfer {
|
||||
reader: Option<DocumentDescriptor>,
|
||||
pending: Option<PendingWrite>,
|
||||
confirmed_file: Option<i32>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PendingWrite {
|
||||
file: File,
|
||||
descriptor: DocumentDescriptor,
|
||||
token: Value,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl TransferJob {
|
||||
pub fn is_document(&self) -> bool {
|
||||
matches!(&self.data_source, DataSource::FilePath(path) if android::is_path(path))
|
||||
}
|
||||
|
||||
pub(super) fn confirm_document(&mut self, request: &FileTransferSendConfirmRequest) {
|
||||
if request.id != self.id {
|
||||
return;
|
||||
}
|
||||
let overwrite = matches!(
|
||||
request.union,
|
||||
Some(file_transfer_send_confirm_request::Union::OffsetBlk(0))
|
||||
| Some(file_transfer_send_confirm_request::Union::Skip(false))
|
||||
);
|
||||
self.document_transfer.confirmed_file = (overwrite
|
||||
&& self.files.get(request.file_num as usize).is_some())
|
||||
.then_some(request.file_num);
|
||||
}
|
||||
|
||||
fn document_path(&self, file_num: usize) -> ResultType<String> {
|
||||
let DataSource::FilePath(base) = &self.data_source else {
|
||||
bail!("Not a document transfer");
|
||||
};
|
||||
let entry = self
|
||||
.files
|
||||
.get(file_num)
|
||||
.ok_or(anyhow!("Wrong file number"))?;
|
||||
super::validate_file_name_no_traversal(&entry.name)?;
|
||||
Ok(Self::join(base, &entry.name).to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
pub(super) async fn open_document_stream(&mut self) -> ResultType<bool> {
|
||||
if let Some(error) = &self.document_transfer.error {
|
||||
self.file_num = self.files.len() as i32;
|
||||
self.data_stream.take();
|
||||
bail!("{}", error);
|
||||
}
|
||||
if self.file_num as usize >= self.files.len() {
|
||||
self.data_stream.take();
|
||||
return Ok(true);
|
||||
}
|
||||
if self.data_stream.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let result = android::open(self.document_path(self.file_num as usize)?).await;
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
match result {
|
||||
Ok((file, descriptor, digest)) => {
|
||||
let entry = self
|
||||
.files
|
||||
.get_mut(self.file_num as usize)
|
||||
.ok_or(anyhow!("Wrong file number"))?;
|
||||
entry.modified_time = digest.map_or(0, |(modified, _)| modified);
|
||||
entry.size = digest.map_or(entry.size, |(_, size)| size);
|
||||
self.data_stream = Some(DataStream::FileStream(file));
|
||||
self.document_transfer.reader = Some(descriptor);
|
||||
}
|
||||
Err(error) => {
|
||||
self.fail_document_read(error.to_string());
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(super) async fn finish_document_read(&mut self) -> ResultType<()> {
|
||||
self.data_stream.take();
|
||||
let descriptor = self
|
||||
.document_transfer
|
||||
.reader
|
||||
.take()
|
||||
.ok_or(anyhow!("No open document reader"))?;
|
||||
let result = descriptor.close("").await;
|
||||
if let Err(error) = &result {
|
||||
self.fail_document_read(error.to_string());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn fail_document_read(&mut self, error: String) {
|
||||
self.document_transfer.error = Some(error);
|
||||
self.file_num = self.files.len() as i32;
|
||||
self.file_confirmed = false;
|
||||
self.file_is_waiting = false;
|
||||
self.document_transfer.reader.take();
|
||||
}
|
||||
|
||||
pub(super) async fn write_document(&mut self, block: FileTransferBlock) -> ResultType<()> {
|
||||
if let Some(error) = &self.document_transfer.error {
|
||||
bail!("{}", error);
|
||||
}
|
||||
let result = self.write_document_block(&block).await;
|
||||
if let Err(error) = &result {
|
||||
self.document_transfer.error = Some(error.to_string());
|
||||
if let Err(cleanup_error) = self.cancel_document().await {
|
||||
const CLEANUP_ERROR_LOG_INTERVAL: std::time::Duration =
|
||||
std::time::Duration::from_secs(60);
|
||||
hbb_common::throttled_log!(
|
||||
CLEANUP_ERROR_LOG_INTERVAL,
|
||||
warn,
|
||||
"Failed to clean up document transfer {}: {}",
|
||||
self.id,
|
||||
cleanup_error
|
||||
);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn write_document_block(&mut self, block: &FileTransferBlock) -> ResultType<()> {
|
||||
if self.is_resume {
|
||||
bail!("Document transfers must be restarted after interruption");
|
||||
}
|
||||
let path = self.document_path(block.file_num as usize)?;
|
||||
if self.document_transfer.pending.as_ref().map(|p| &p.path) != Some(&path) {
|
||||
self.finish_document().await?;
|
||||
// Upload senders handle confirmation when overwrite detection is supported.
|
||||
let overwrite = (!self.is_remote && self.enable_overwrite_detection)
|
||||
|| self.document_transfer.confirmed_file.take() == Some(block.file_num);
|
||||
self.document_transfer.pending = Some(begin_write(path, overwrite).await?);
|
||||
self.file_num = block.file_num;
|
||||
}
|
||||
let pending = self
|
||||
.document_transfer
|
||||
.pending
|
||||
.as_mut()
|
||||
.ok_or(anyhow!("No open document"))?;
|
||||
let data = if block.compressed {
|
||||
std::borrow::Cow::Owned(decompress(&block.data))
|
||||
} else {
|
||||
std::borrow::Cow::Borrowed(block.data.as_ref())
|
||||
};
|
||||
pending.file.write_all(&data).await?;
|
||||
self.finished_size += data.len() as u64;
|
||||
self.transferred += block.data.len() as u64;
|
||||
if block.data.is_empty() {
|
||||
self.finish_document().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn finish_document(&mut self) -> ResultType<()> {
|
||||
if let Some(error) = &self.document_transfer.error {
|
||||
bail!("{}", error);
|
||||
}
|
||||
let Some(pending) = self.document_transfer.pending.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
let result = finish_write(pending).await;
|
||||
if let Err(error) = &result {
|
||||
self.document_transfer.error = Some(error.to_string());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn cancel_document(&mut self) -> ResultType<()> {
|
||||
let Some(pending) = self.document_transfer.pending.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
let PendingWrite {
|
||||
file,
|
||||
descriptor,
|
||||
path,
|
||||
token,
|
||||
} = pending;
|
||||
drop(file);
|
||||
let result = descriptor.close("Document transfer canceled").await;
|
||||
discard_write(path, token, result).await
|
||||
}
|
||||
|
||||
pub(super) async fn seek_document(&mut self, offset: u64) -> ResultType<()> {
|
||||
let Some(DataStream::FileStream(file)) = self.data_stream.as_mut() else {
|
||||
bail!("Document receives must be restarted after interruption");
|
||||
};
|
||||
let entry = self
|
||||
.files
|
||||
.get(self.file_num as usize)
|
||||
.ok_or(anyhow!("Wrong file number"))?;
|
||||
if offset > 0 && entry.modified_time == 0 {
|
||||
bail!(
|
||||
"Cannot resume a document with an unknown modification time; restart the transfer"
|
||||
);
|
||||
}
|
||||
file.seek(std::io::SeekFrom::Start(offset)).await?;
|
||||
self.finished_size += offset;
|
||||
self.transferred += offset;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn begin_write(path: String, overwrite: bool) -> ResultType<PendingWrite> {
|
||||
spawn_blocking(move || {
|
||||
let token = android::request(json!({
|
||||
"op": "begin", "path": path, "overwrite": overwrite
|
||||
}))?;
|
||||
let file = android::take_file(&token["fd"])?;
|
||||
let descriptor = DocumentDescriptor::new(&token)?;
|
||||
Ok(PendingWrite {
|
||||
file: File::from_std(file),
|
||||
descriptor,
|
||||
token,
|
||||
path,
|
||||
})
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn finish_write(pending: PendingWrite) -> ResultType<()> {
|
||||
let PendingWrite {
|
||||
mut file,
|
||||
descriptor,
|
||||
path,
|
||||
token,
|
||||
} = pending;
|
||||
let written: ResultType<()> = async {
|
||||
file.flush().await?;
|
||||
file.sync_all().await?;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
drop(file);
|
||||
let message = written
|
||||
.as_ref()
|
||||
.err()
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default();
|
||||
let closed = descriptor.close(&message).await;
|
||||
let result = match (written, closed) {
|
||||
(Err(error), Err(close_error)) => Err(anyhow!(
|
||||
"{}; closing document failed: {}",
|
||||
error,
|
||||
close_error
|
||||
)),
|
||||
(Err(error), _) | (_, Err(error)) => Err(error),
|
||||
_ => Ok(()),
|
||||
};
|
||||
if result.is_err() {
|
||||
return discard_write(path, token, result).await;
|
||||
}
|
||||
spawn_blocking(move || {
|
||||
android::request(json!({
|
||||
"op": "finish", "path": path, "token": token
|
||||
}))
|
||||
})
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn discard_write(path: String, token: Value, result: ResultType<()>) -> ResultType<()> {
|
||||
let cleanup: ResultType<()> = async {
|
||||
spawn_blocking(move || {
|
||||
android::request(json!({
|
||||
"op": "discard", "path": path, "token": token
|
||||
}))
|
||||
})
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
match (result, cleanup) {
|
||||
(Err(error), Err(cleanup)) => {
|
||||
bail!("{}; temporary document cleanup failed: {}", error, cleanup)
|
||||
}
|
||||
(Err(error), _) | (_, Err(error)) => Err(error),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
use super::{
|
||||
get_string, is_write_need_confirmation, join_validated_path, validate_file_name_no_traversal,
|
||||
validate_no_symlink_components, DataSource, DataStream, DigestCheckResult, TransferJob,
|
||||
};
|
||||
use crate::message_proto::{
|
||||
file_transfer_send_confirm_request, FileEntry, FileTransferBlock, FileTransferDigest,
|
||||
FileTransferSendConfirmRequest, FileType,
|
||||
};
|
||||
use hbb_common::{anyhow::anyhow, bail, compress::decompress, ResultType};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
io::ErrorKind,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use tokio::{
|
||||
fs::{self, OpenOptions},
|
||||
io::{AsyncSeekExt, AsyncWriteExt},
|
||||
};
|
||||
|
||||
const SINGLE_LINK_COUNT: u64 = 1;
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct DownloadState {
|
||||
pub(super) confirmation: Option<(i32, u32)>,
|
||||
}
|
||||
|
||||
pub fn validate_listing(entries: &[FileEntry], peer_windows: bool) -> ResultType<()> {
|
||||
for entry in entries {
|
||||
let name = &entry.name;
|
||||
if entry.entry_type.enum_value() == Ok(FileType::DirDrive)
|
||||
&& matches!(name.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if name.is_empty()
|
||||
|| name == "."
|
||||
|| name == ".."
|
||||
|| name.contains('\0')
|
||||
|| name.contains('/')
|
||||
|| (peer_windows
|
||||
&& (name.contains('\\')
|
||||
|| matches!(name.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic())))
|
||||
{
|
||||
bail!("invalid file name in remote directory listing: {name}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_download_name(path: &str, peer_windows: bool) -> ResultType<()> {
|
||||
let separator = |c| c == '/' || (peer_windows && c == '\\');
|
||||
let path = path.trim_end_matches(separator);
|
||||
validate_component(path.rsplit(separator).next().unwrap_or(""))
|
||||
}
|
||||
|
||||
fn validate_component(name: &str) -> ResultType<()> {
|
||||
validate_file_name_no_traversal(name)?;
|
||||
if name.is_empty() || name == "." || name.contains('/') {
|
||||
bail!("invalid download file name: {name}");
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if name.contains(['\\', ':', '<', '>', '"', '|', '?', '*'])
|
||||
|| name.ends_with('.')
|
||||
|| name.ends_with(' ')
|
||||
{
|
||||
bail!("invalid Windows download file name: {name}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validated_target(base: &PathBuf, name: &str) -> ResultType<PathBuf> {
|
||||
let parent = base
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("download destination has no parent"))?;
|
||||
let leaf = base
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| anyhow!("invalid download destination"))?;
|
||||
validate_component(leaf)?;
|
||||
#[cfg(windows)]
|
||||
for component in name.split(['/', '\\']).filter(|part| !part.is_empty()) {
|
||||
validate_component(component)?;
|
||||
}
|
||||
validate_no_symlink_components(&parent.to_path_buf(), leaf)?;
|
||||
let target = join_validated_path(base, name)?;
|
||||
let parent = target
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("download file has no parent"))?;
|
||||
let leaf = target
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| anyhow!("invalid download file name"))?;
|
||||
for suffix in ["download", "digest"] {
|
||||
validate_no_symlink_components(&parent.to_path_buf(), &format!("{leaf}.{suffix}"))?;
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
fn remove_if_exists(path: &Path) -> ResultType<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn remove_if_exists_async(path: &Path) -> ResultType<()> {
|
||||
match fs::remove_file(path).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_resume_file(file: &tokio::fs::File) -> ResultType<()> {
|
||||
let metadata = file.metadata().await?;
|
||||
if !metadata.is_file() {
|
||||
bail!("download resume staging path is not a regular file");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let links = std::os::unix::fs::MetadataExt::nlink(&metadata);
|
||||
#[cfg(windows)]
|
||||
let links = {
|
||||
use std::{mem::MaybeUninit, os::windows::io::AsRawHandle};
|
||||
use winapi::{
|
||||
shared::minwindef::FALSE,
|
||||
um::fileapi::{GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION},
|
||||
};
|
||||
let file = file.try_clone().await?;
|
||||
tokio::task::spawn_blocking(move || -> ResultType<u64> {
|
||||
let mut information = MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
|
||||
if unsafe {
|
||||
GetFileInformationByHandle(file.as_raw_handle() as _, information.as_mut_ptr())
|
||||
} == FALSE
|
||||
{
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(u64::from(
|
||||
unsafe { information.assume_init() }.nNumberOfLinks,
|
||||
))
|
||||
})
|
||||
.await??
|
||||
};
|
||||
if links != SINGLE_LINK_COUNT {
|
||||
bail!("hard-linked download resume staging file is not allowed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl TransferJob {
|
||||
pub(super) fn is_download(&self) -> bool {
|
||||
self.download.is_some()
|
||||
}
|
||||
|
||||
pub fn download_target(&self, file_num: i32) -> ResultType<PathBuf> {
|
||||
let entry = self
|
||||
.files
|
||||
.get(file_num as usize)
|
||||
.ok_or_else(|| anyhow!("Wrong file number"))?;
|
||||
let DataSource::FilePath(base) = &self.data_source else {
|
||||
bail!("download destination is not a file path");
|
||||
};
|
||||
validated_target(base, &entry.name)
|
||||
}
|
||||
|
||||
pub fn download_digest(
|
||||
&mut self,
|
||||
can_resume: bool,
|
||||
digest: &FileTransferDigest,
|
||||
) -> ResultType<DigestCheckResult> {
|
||||
if self.file_num != digest.file_num && self.data_stream.is_some() {
|
||||
let result = self.finish_download();
|
||||
self.data_stream.take();
|
||||
result?;
|
||||
}
|
||||
let target = self.download_target(digest.file_num)?;
|
||||
let resume = can_resume && self.is_resume && !target.try_exists()?;
|
||||
let result = is_write_need_confirmation(resume, &get_string(&target), digest)?;
|
||||
if matches!(result, DigestCheckResult::NoSuchFile)
|
||||
&& (Path::new(&format!("{}.download", target.display())).try_exists()?
|
||||
|| Path::new(&format!("{}.digest", target.display())).try_exists()?)
|
||||
{
|
||||
return Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
|
||||
id: digest.id,
|
||||
file_num: digest.file_num,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) fn confirm_download(&mut self, request: &FileTransferSendConfirmRequest) {
|
||||
if request.id != self.id {
|
||||
return;
|
||||
}
|
||||
let Some(download) = self.download.as_mut() else {
|
||||
return;
|
||||
};
|
||||
download.confirmation = self.files.get(request.file_num as usize).and_then(|_| {
|
||||
let offset = match request.union {
|
||||
Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) => offset,
|
||||
Some(file_transfer_send_confirm_request::Union::Skip(false)) => 0,
|
||||
_ => return None,
|
||||
};
|
||||
Some((request.file_num, offset))
|
||||
});
|
||||
}
|
||||
|
||||
fn download_confirmation_offset(&self, file_num: i32) -> Option<u32> {
|
||||
let (confirmed, offset) = self.download.as_ref()?.confirmation.as_ref()?;
|
||||
(*confirmed == file_num).then_some(*offset)
|
||||
}
|
||||
|
||||
async fn start_download_file(&mut self, file_num: i32) -> ResultType<()> {
|
||||
let result = self.finish_download();
|
||||
self.data_stream.take();
|
||||
result?;
|
||||
let target = self.download_target(file_num)?;
|
||||
let staging = PathBuf::from(format!("{}.download", target.display()));
|
||||
let digest = PathBuf::from(format!("{}.digest", target.display()));
|
||||
let confirmation = self.download_confirmation_offset(file_num);
|
||||
if (fs::try_exists(&target).await?
|
||||
|| fs::try_exists(&staging).await?
|
||||
|| fs::try_exists(&digest).await?)
|
||||
&& confirmation.is_none()
|
||||
{
|
||||
bail!("download overwrite requires confirmation");
|
||||
}
|
||||
if let Some(offset) = confirmation.filter(|offset| *offset > 0) {
|
||||
return self.resume_download(file_num, offset).await;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
fs::create_dir_all(parent).await?;
|
||||
}
|
||||
remove_if_exists_async(&staging).await?;
|
||||
let file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&staging)
|
||||
.await?;
|
||||
self.file_num = file_num;
|
||||
self.data_stream = Some(DataStream::FileStream(file));
|
||||
remove_if_exists_async(&digest).await?;
|
||||
let mut metadata = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&digest)
|
||||
.await?;
|
||||
metadata
|
||||
.write_all(serde_json::to_string(&self.digest)?.as_bytes())
|
||||
.await?;
|
||||
metadata.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn resume_download(&mut self, file_num: i32, offset: u32) -> ResultType<()> {
|
||||
let target = self.download_target(file_num)?;
|
||||
if fs::try_exists(&target).await? {
|
||||
bail!("download overwrite requires confirmation");
|
||||
}
|
||||
let digest = fs::metadata(format!("{}.digest", target.display())).await?;
|
||||
if !digest.is_file() {
|
||||
bail!("download resume metadata is not a regular file");
|
||||
}
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(format!("{}.download", target.display()))
|
||||
.await?;
|
||||
validate_resume_file(&file).await?;
|
||||
if file.metadata().await?.len() != u64::from(offset) {
|
||||
bail!("download resume offset does not match staging file size");
|
||||
}
|
||||
file.seek(std::io::SeekFrom::Start(u64::from(offset)))
|
||||
.await?;
|
||||
self.file_num = file_num;
|
||||
self.data_stream = Some(DataStream::FileStream(file));
|
||||
self.transferred += u64::from(offset);
|
||||
self.finished_size += u64::from(offset);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn write_download(&mut self, block: FileTransferBlock) -> ResultType<()> {
|
||||
if block.id != self.id {
|
||||
bail!("Wrong id");
|
||||
}
|
||||
if block.file_num as usize >= self.files.len() {
|
||||
bail!("Wrong file number");
|
||||
}
|
||||
if block.file_num != self.file_num || self.data_stream.is_none() {
|
||||
self.start_download_file(block.file_num).await?;
|
||||
}
|
||||
let data = if block.compressed {
|
||||
Cow::Owned(decompress(&block.data))
|
||||
} else {
|
||||
Cow::Borrowed(block.data.as_ref())
|
||||
};
|
||||
let Some(DataStream::FileStream(stream)) = self.data_stream.as_mut() else {
|
||||
bail!("download file stream is missing");
|
||||
};
|
||||
stream.write_all(&data).await?;
|
||||
stream.flush().await?;
|
||||
self.finished_size += data.len() as u64;
|
||||
self.transferred += block.data.len() as u64;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn finish_download(&self) -> ResultType<()> {
|
||||
if !self.is_download() {
|
||||
self.modify_time();
|
||||
return Ok(());
|
||||
}
|
||||
if self.data_stream.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let target = self.download_target(self.file_num)?;
|
||||
if target.try_exists()? && self.download_confirmation_offset(self.file_num) != Some(0) {
|
||||
bail!("download overwrite requires confirmation");
|
||||
}
|
||||
std::fs::rename(format!("{}.download", target.display()), &target)?;
|
||||
remove_if_exists(&PathBuf::from(format!("{}.digest", target.display())))?;
|
||||
let entry = self
|
||||
.files
|
||||
.get(self.file_num as usize)
|
||||
.ok_or_else(|| anyhow!("Wrong file number"))?;
|
||||
filetime::set_file_mtime(
|
||||
&target,
|
||||
filetime::FileTime::from_unix_time(entry.modified_time as _, 0),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
use super::*;
|
||||
|
||||
struct DownloadDir(PathBuf);
|
||||
|
||||
impl DownloadDir {
|
||||
fn new() -> Self {
|
||||
static NEXT_DIRECTORY: AtomicI32 = AtomicI32::new(1);
|
||||
let sequence = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"rustdesk_download_{}_{nonce}_{sequence}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn job(&self) -> TransferJob {
|
||||
self.job_with_files(vec![FileEntry::default()])
|
||||
}
|
||||
|
||||
fn job_with_files(&self, files: Vec<FileEntry>) -> TransferJob {
|
||||
TransferJob::new_write(
|
||||
1,
|
||||
JobType::Generic,
|
||||
"/remote/file.txt".into(),
|
||||
DataSource::FilePath(self.0.join("file.txt")),
|
||||
0,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
)
|
||||
.with_files(files)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DownloadDir {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn block() -> FileTransferBlock {
|
||||
FileTransferBlock {
|
||||
id: 1,
|
||||
file_num: 0,
|
||||
data: b"received".to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn approval(file_num: i32, offset: u32) -> FileTransferSendConfirmRequest {
|
||||
FileTransferSendConfirmRequest {
|
||||
id: 1,
|
||||
file_num,
|
||||
union: Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_listing_rejects_unsafe_names_and_keeps_drive_rows() {
|
||||
for name in ["../outside", "/outside", ".", "..", "", "dir/file"] {
|
||||
let entry = FileEntry {
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(
|
||||
download::validate_listing(&[entry], false).is_err(),
|
||||
"{}",
|
||||
name
|
||||
);
|
||||
}
|
||||
let entries = [
|
||||
FileEntry {
|
||||
name: "report.txt".into(),
|
||||
..Default::default()
|
||||
},
|
||||
FileEntry {
|
||||
name: "report:notes".into(),
|
||||
..Default::default()
|
||||
},
|
||||
FileEntry {
|
||||
name: "C:".into(),
|
||||
entry_type: FileType::DirDrive.into(),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
download::validate_listing(&entries, true).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_requires_confirmation_to_overwrite() {
|
||||
let dir = DownloadDir::new();
|
||||
let target = dir.0.join("file.txt");
|
||||
std::fs::write(&target, b"original").unwrap();
|
||||
let mut job = dir.job();
|
||||
assert!(job.write(block()).await.is_err());
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"original");
|
||||
assert!(!dir.0.join("file.txt.download").exists());
|
||||
|
||||
job.confirm(&approval(0, 0)).await;
|
||||
job.write(block()).await.unwrap();
|
||||
assert!(job.set_files(vec![FileEntry::default()]).is_err());
|
||||
job.finish_download().unwrap();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"received");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_requires_separate_confirmation_for_each_existing_file() {
|
||||
let dir = DownloadDir::new();
|
||||
let mut job = dir.job_with_files(vec![
|
||||
FileEntry {
|
||||
name: "first.txt".into(),
|
||||
..Default::default()
|
||||
},
|
||||
FileEntry {
|
||||
name: "second.txt".into(),
|
||||
..Default::default()
|
||||
},
|
||||
]);
|
||||
job.write(block()).await.unwrap();
|
||||
let second = dir.0.join("file.txt/second.txt");
|
||||
std::fs::write(&second, b"original").unwrap();
|
||||
assert!(job
|
||||
.write(FileTransferBlock {
|
||||
file_num: 1,
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.is_err());
|
||||
assert_eq!(std::fs::read(&second).unwrap(), b"original");
|
||||
assert_eq!(
|
||||
std::fs::read(dir.0.join("file.txt/first.txt")).unwrap(),
|
||||
b"received"
|
||||
);
|
||||
job.confirm(&approval(1, 0)).await;
|
||||
job.write(FileTransferBlock {
|
||||
file_num: 1,
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job.finish_download().unwrap();
|
||||
assert_eq!(std::fs::read(&second).unwrap(), b"received");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_preserves_received_files_when_publication_fails() {
|
||||
for next_is_digest in [false, true] {
|
||||
let dir = DownloadDir::new();
|
||||
let files = ["first.txt", "second.txt"]
|
||||
.iter()
|
||||
.map(|&name| FileEntry {
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let mut job = dir.job_with_files(files);
|
||||
job.write(block()).await.unwrap();
|
||||
let target = dir.0.join("file.txt/first.txt");
|
||||
std::fs::write(&target, b"existing").unwrap();
|
||||
if next_is_digest {
|
||||
assert!(job
|
||||
.download_digest(
|
||||
true,
|
||||
&FileTransferDigest {
|
||||
id: 1,
|
||||
file_num: 1,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.is_err());
|
||||
} else {
|
||||
assert!(job
|
||||
.write(FileTransferBlock {
|
||||
file_num: 1,
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.is_err());
|
||||
}
|
||||
job.remove_download_file();
|
||||
assert_eq!(std::fs::read(target).unwrap(), b"existing");
|
||||
assert_eq!(
|
||||
std::fs::read(dir.0.join("file.txt/first.txt.download")).unwrap(),
|
||||
b"received"
|
||||
);
|
||||
assert!(dir.0.join("file.txt/first.txt.digest").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_recovers_interrupted_transfer() {
|
||||
for (resuming, changed) in [(false, false), (true, true), (true, false)] {
|
||||
let dir = DownloadDir::new();
|
||||
let mut digest = FileTransferDigest {
|
||||
id: 1,
|
||||
file_size: block().data.len() as _,
|
||||
last_modified: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let mut interrupted = dir.job();
|
||||
interrupted.set_digest(digest.file_size, digest.last_modified);
|
||||
let partial = FileTransferBlock {
|
||||
data: b"rec".to_vec().into(),
|
||||
..block()
|
||||
};
|
||||
interrupted.write(partial).await.unwrap();
|
||||
drop(interrupted);
|
||||
|
||||
let mut job = dir.job();
|
||||
job.is_resume = resuming;
|
||||
digest.last_modified += u64::from(changed);
|
||||
job.set_digest(digest.file_size, digest.last_modified);
|
||||
let confirmation = match job.download_digest(true, &digest).unwrap() {
|
||||
DigestCheckResult::NeedConfirm(confirmation) => confirmation,
|
||||
_ => panic!("interrupted download must require confirmation"),
|
||||
};
|
||||
let offset = if resuming && !changed {
|
||||
b"rec".len()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
assert_eq!(confirmation.is_identical, offset > 0);
|
||||
assert_eq!(confirmation.transferred_size, offset as u64);
|
||||
assert!(job.write(block()).await.is_err());
|
||||
assert_eq!(
|
||||
std::fs::read(dir.0.join("file.txt.download")).unwrap(),
|
||||
b"rec"
|
||||
);
|
||||
job.confirm(&approval(0, offset as _)).await;
|
||||
job.write(FileTransferBlock {
|
||||
data: block().data.slice(offset..),
|
||||
..block()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
job.finish_download().unwrap();
|
||||
assert_eq!(std::fs::read(dir.0.join("file.txt")).unwrap(), b"received");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_does_not_publish_or_remove_unreceived_staging_files() {
|
||||
let dir = DownloadDir::new();
|
||||
let target = dir.0.join("file.txt");
|
||||
let staging = dir.0.join("file.txt.download");
|
||||
std::fs::write(&target, b"original").unwrap();
|
||||
std::fs::write(&staging, b"another transfer").unwrap();
|
||||
let job = dir.job();
|
||||
job.modify_time();
|
||||
job.remove_download_file();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read(&staging).unwrap(), b"another transfer");
|
||||
|
||||
let metadata_only = DownloadDir::new();
|
||||
let metadata = metadata_only.0.join("file.txt.digest");
|
||||
std::fs::write(&metadata, b"unrelated file").unwrap();
|
||||
assert!(metadata_only.job().write(block()).await.is_err());
|
||||
assert_eq!(std::fs::read(metadata).unwrap(), b"unrelated file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn download_rejects_windows_streams_and_ambiguous_components() {
|
||||
let dir = DownloadDir::new();
|
||||
for name in ["nested/file:stream", "nested/.. /outside", "nested/file."] {
|
||||
assert!(
|
||||
download::validated_target(&dir.0.join("docs"), name).is_err(),
|
||||
"{}",
|
||||
name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg_attr(windows, ignore = "requires symlink privilege")]
|
||||
async fn download_refuses_symlink_destination_directory() {
|
||||
let dir = DownloadDir::new();
|
||||
let outside = dir.0.join("outside");
|
||||
let link = dir.0.join("file.txt");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&outside, &link).unwrap();
|
||||
#[cfg(windows)]
|
||||
std::os::windows::fs::symlink_dir(&outside, &link).unwrap();
|
||||
let mut job = dir.job_with_files(vec![FileEntry {
|
||||
name: "child.txt".into(),
|
||||
..Default::default()
|
||||
}]);
|
||||
assert!(job.write(block()).await.is_err());
|
||||
job.modify_time();
|
||||
assert!(!outside.join("child.txt").exists());
|
||||
assert!(!outside.join("child.txt.download").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg_attr(windows, ignore = "requires symlink privilege")]
|
||||
async fn download_refuses_linked_target_and_staging_files() {
|
||||
for suffix in ["", ".download", ".digest"] {
|
||||
let dir = DownloadDir::new();
|
||||
let outside = dir.0.join("outside.txt");
|
||||
let link = dir.0.join(format!("file.txt{suffix}"));
|
||||
std::fs::write(&outside, b"original").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&outside, &link).unwrap();
|
||||
#[cfg(windows)]
|
||||
std::os::windows::fs::symlink_file(&outside, &link).unwrap();
|
||||
let mut job = dir.job();
|
||||
assert!(job.write(block()).await.is_err());
|
||||
job.modify_time();
|
||||
job.remove_download_file();
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"original");
|
||||
assert!(std::fs::symlink_metadata(link)
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[path = "android_write_tests.rs"]
|
||||
mod write_tests;
|
||||
|
||||
#[cfg(unix)]
|
||||
use super::super::{
|
||||
DataSource, FileTransferBlock, FileTransferSendConfirmRequest, JobType, TransferJob,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
fn provider(output: &Path, request: &str) -> ResultType<String> {
|
||||
use std::{fs::File, os::fd::IntoRawFd};
|
||||
|
||||
let request: Value = serde_json::from_str(request)?;
|
||||
let modified = output.metadata().map_or(0, |m| std::os::unix::fs::MetadataExt::mtime(&m));
|
||||
let metadata = json!({"name": "notes.txt", "directory": false, "size": 12, "modified": modified});
|
||||
let value = match request["op"].as_str() {
|
||||
Some("home") => json!("/@rustdesk/tree/selected/Documents"),
|
||||
Some("allowed") => json!(true),
|
||||
Some("list") => json!([metadata]),
|
||||
Some("stat") if request["path"].as_str().unwrap().ends_with(".txt") => metadata,
|
||||
Some("stat") => json!({"name": "Documents", "directory": true, "size": 0, "modified": 0}),
|
||||
Some("begin") if request["path"].as_str().unwrap().contains("write-error") => {
|
||||
std::fs::write(output, b"partial")?;
|
||||
json!({"fd": File::open(output)?.into_raw_fd(), "descriptor": request["path"]})
|
||||
}
|
||||
Some("begin") => {
|
||||
if output.exists() && request["overwrite"].as_bool() == Some(false) {
|
||||
return Ok(json!({"error": "Document overwrite requires confirmation"}).to_string());
|
||||
}
|
||||
json!({"fd": File::create(output)?.into_raw_fd(), "descriptor": request["path"]})
|
||||
}
|
||||
Some("open") => write_tests::open_source(output, &request)?,
|
||||
Some("close")
|
||||
if request["descriptor"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.ends_with("broken.txt") =>
|
||||
{
|
||||
return Ok(json!({"error": "Provider read failed"}).to_string())
|
||||
}
|
||||
Some("close") => json!(true),
|
||||
Some("finish") if request["path"].as_str().unwrap().ends_with("failed.txt") => {
|
||||
return Ok(json!({"error": "Publishing failed"}).to_string())
|
||||
}
|
||||
Some("finish") => json!(true),
|
||||
Some("discard") => {
|
||||
if request["path"].as_str().unwrap().contains("discard-error") {
|
||||
bail!("Provider cleanup failed");
|
||||
}
|
||||
std::fs::remove_file(output)?;
|
||||
json!(true)
|
||||
}
|
||||
_ => bail!("Unexpected operation"),
|
||||
};
|
||||
Ok(json!({"value": value}).to_string())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn receiving(path: &str) -> TransferJob {
|
||||
receiving_files(path, vec![FileEntry::default()])
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn receiving_files(path: &str, files: Vec<FileEntry>) -> TransferJob {
|
||||
TransferJob::new_write(
|
||||
1,
|
||||
JobType::Generic,
|
||||
String::new(),
|
||||
DataSource::FilePath(path.into()),
|
||||
0,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.with_files(files)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn block(file_num: i32, data: &[u8]) -> FileTransferBlock {
|
||||
FileTransferBlock {
|
||||
id: 1,
|
||||
file_num,
|
||||
data: data.to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn sending(path: &str, overwrite_detection: bool) -> TransferJob {
|
||||
TransferJob::new_read(
|
||||
2,
|
||||
JobType::Generic,
|
||||
String::new(),
|
||||
DataSource::FilePath(path.into()),
|
||||
0,
|
||||
false,
|
||||
false,
|
||||
overwrite_detection,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn receive(path: &str, succeeds: bool, output: &Path) {
|
||||
let mut job = receiving(path);
|
||||
confirm_overwrite(&mut job, 0).await;
|
||||
job.write(block(0, b"hello, world")).await.unwrap();
|
||||
let eof = job.write(block(0, b"")).await;
|
||||
assert_eq!(eof.is_ok(), succeeds);
|
||||
assert_eq!(job.finish_document().await.is_ok(), succeeds);
|
||||
assert_eq!(job.job_error().is_some(), !succeeds);
|
||||
job.cancel_document().await.unwrap();
|
||||
assert_eq!(std::fs::read(output).unwrap(), b"hello, world");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn confirm_overwrite(job: &mut TransferJob, file_num: i32) {
|
||||
let mut confirmation = FileTransferSendConfirmRequest {
|
||||
id: job.id(),
|
||||
file_num,
|
||||
..Default::default()
|
||||
};
|
||||
confirmation.set_offset_blk(0);
|
||||
job.confirm(&confirmation).await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn overwrite_requires_matching_confirmation(path: &str, output: &Path) {
|
||||
std::fs::write(output, b"original").unwrap();
|
||||
let mut job = receiving(&format!("{path}/notes.txt"));
|
||||
assert!(job.write(block(0, b"")).await.is_err());
|
||||
assert_eq!(std::fs::read(output).unwrap(), b"original");
|
||||
|
||||
let files = ["first.txt", "second.txt"]
|
||||
.map(|name| FileEntry {
|
||||
name: name.into(),
|
||||
..Default::default()
|
||||
})
|
||||
.to_vec();
|
||||
let mut job = receiving_files(path, files.clone());
|
||||
confirm_overwrite(&mut job, 0).await;
|
||||
assert!(job.set_files(vec![files[1].clone()]).is_err());
|
||||
assert_eq!(job.files(), &files);
|
||||
job.write(block(0, b"")).await.unwrap();
|
||||
std::fs::write(output, b"second original").unwrap();
|
||||
assert!(job.write(block(1, b"")).await.is_err());
|
||||
assert_eq!(std::fs::read(output).unwrap(), b"second original");
|
||||
|
||||
let mut job = receiving_files(path, files);
|
||||
confirm_overwrite(&mut job, 1).await;
|
||||
job.write(block(1, b"")).await.unwrap();
|
||||
assert!(std::fs::read(output).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn host_upload_respects_overwrite_support(path: &str, output: &Path) {
|
||||
for (overwrite_detection, exists) in [(false, false), (false, true), (true, true)] {
|
||||
if exists {
|
||||
std::fs::write(output, b"original").unwrap();
|
||||
}
|
||||
let mut job = TransferJob::new_write(
|
||||
1,
|
||||
JobType::Generic,
|
||||
String::new(),
|
||||
DataSource::FilePath(format!("{path}/notes.txt").into()),
|
||||
0,
|
||||
false,
|
||||
false,
|
||||
overwrite_detection,
|
||||
)
|
||||
.with_files(vec![FileEntry::default()])
|
||||
.unwrap();
|
||||
let result = job.write(block(0, b"replacement")).await;
|
||||
if exists && !overwrite_detection {
|
||||
assert_eq!(
|
||||
result.unwrap_err().to_string(),
|
||||
"Document overwrite requires confirmation"
|
||||
);
|
||||
assert_eq!(std::fs::read(output).unwrap(), b"original");
|
||||
} else {
|
||||
result.unwrap();
|
||||
job.finish_document().await.unwrap();
|
||||
assert_eq!(std::fs::read(output).unwrap(), b"replacement");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn selected_folder_transfers_directly_and_preserves_data_on_publish_failure() {
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
let output = std::env::temp_dir().join(format!(
|
||||
"rustdesk-documents-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
let provider_output = output.clone();
|
||||
initialize(move |request| provider(&provider_output, request)).unwrap();
|
||||
let path = "/@rustdesk/tree/selected/Documents";
|
||||
assert!(allowed(path).unwrap() && allowed(&format!("{path}/notes.txt")).unwrap());
|
||||
assert!(!allowed(&format!("{path}-private/notes.txt")).unwrap());
|
||||
assert!(!allowed("/@rustdesk/tree/previous/Documents/notes.txt").unwrap());
|
||||
let directory = super::super::read_dir(Path::new(path), false).unwrap();
|
||||
assert_eq!(directory.path, path);
|
||||
assert_eq!(directory.entries[0].name, "notes.txt");
|
||||
let files = super::super::get_recursive_files(path, false).unwrap();
|
||||
assert_eq!(files[0].name, "notes.txt");
|
||||
assert_eq!(files[0].size, 12);
|
||||
assert!(remove_empty_tree(path).unwrap_err().to_string() == "Cannot delete a shared root");
|
||||
assert!(super::super::remove_file(path).is_err());
|
||||
host_upload_respects_overwrite_support(path, &output).await;
|
||||
overwrite_requires_matching_confirmation(path, &output).await;
|
||||
for (name, succeeds) in [("notes.txt", true), ("failed.txt", false)] {
|
||||
receive(&format!("{path}/{name}"), succeeds, &output).await;
|
||||
}
|
||||
let destination = format!("{path}/notes.txt");
|
||||
let entry = stat(&destination).unwrap().unwrap();
|
||||
let digest = super::super::FileTransferDigest {
|
||||
file_size: entry.size,
|
||||
last_modified: entry.modified_time,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
super::super::is_write_need_confirmation(false, &destination, &digest).unwrap(),
|
||||
super::super::DigestCheckResult::NeedConfirm(digest) if digest.is_identical
|
||||
));
|
||||
provider_error_at_eof(path).await;
|
||||
send_and_cancel(path, &output).await;
|
||||
write_tests::failed_block_cleans_pending_receive(path, &output).await;
|
||||
write_tests::failed_finalization_discards_partial_data(path, &output).await;
|
||||
write_tests::replacement_preserves_opened_digest(path, &output).await;
|
||||
write_tests::changed_source_without_timestamp_rejects_resume(path, &output).await;
|
||||
let mut empty = receiving(&format!("{path}/empty.txt"));
|
||||
empty.write(block(0, b"")).await.unwrap();
|
||||
assert_eq!(std::fs::metadata(&output).unwrap().len(), 0);
|
||||
std::fs::remove_file(output).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn send_and_cancel(path: &str, output: &Path) {
|
||||
let mut sender = sending(&format!("{path}/notes.txt"), false);
|
||||
sender.init_data_stream_for_cm().await.unwrap();
|
||||
assert_eq!(
|
||||
sender.read().await.unwrap().unwrap().data.as_ref(),
|
||||
b"hello, world"
|
||||
);
|
||||
assert!(sender.read().await.unwrap().unwrap().data.is_empty());
|
||||
let mut canceled = receiving(&format!("{path}/canceled.txt"));
|
||||
confirm_overwrite(&mut canceled, 0).await;
|
||||
canceled.write(block(0, b"partial")).await.unwrap();
|
||||
canceled.cancel_document().await.unwrap();
|
||||
assert!(!output.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn provider_error_at_eof(path: &str) {
|
||||
let mut sender = sending(&format!("{path}/broken.txt"), true);
|
||||
assert!(sender.init_data_stream_for_cm().await.unwrap().is_some());
|
||||
confirm_overwrite(&mut sender, 0).await;
|
||||
assert!(sender.read().await.unwrap().is_some());
|
||||
assert!(sender.read().await.is_err());
|
||||
assert!(sender.init_data_stream_for_cm().await.is_err());
|
||||
assert!(sender.read().await.unwrap().is_none());
|
||||
assert!(sender.job_completed());
|
||||
assert_eq!(sender.job_error().as_deref(), Some("Provider read failed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_paths_cannot_escape_the_selected_location() {
|
||||
for path in [
|
||||
"/@rustdesk/tree/id/folder/../secret",
|
||||
"/@rustdesk//Download",
|
||||
"/@rustdesk/tree/id/a\\b",
|
||||
"/@rustdesk/file/id/report.txt",
|
||||
"/@rustdesk/save/id/report.txt",
|
||||
"/@rustdesk/Download/report.txt",
|
||||
] {
|
||||
assert!(validate(path).is_err(), "{}", path);
|
||||
}
|
||||
assert!(validate("/@rustdesk/tree/id/folder/report.txt").is_ok());
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn open_source(output: &Path, request: &Value) -> ResultType<Value> {
|
||||
use std::{fs::File, io::Write, os::fd::IntoRawFd};
|
||||
|
||||
let fd = if request["path"].as_str().unwrap().ends_with("stream.txt") {
|
||||
let (reader, mut writer) = std::os::unix::net::UnixStream::pair()?;
|
||||
writer.write_all(&std::fs::read(output)?)?;
|
||||
reader.into_raw_fd()
|
||||
} else {
|
||||
let file = File::open(output)?;
|
||||
let replacement = output.with_extension("replacement");
|
||||
if replacement.exists() {
|
||||
std::fs::rename(replacement, output)?;
|
||||
}
|
||||
file.into_raw_fd()
|
||||
};
|
||||
Ok(json!({"fd": fd, "descriptor": request["path"]}))
|
||||
}
|
||||
|
||||
pub(super) async fn replacement_preserves_opened_digest(path: &str, output: &Path) {
|
||||
use filetime::{set_file_mtime, FileTime};
|
||||
|
||||
std::fs::write(output, b"old contents").unwrap();
|
||||
set_file_mtime(output, FileTime::from_unix_time(1, 0)).unwrap();
|
||||
let replacement = output.with_extension("replacement");
|
||||
std::fs::write(&replacement, b"new contents").unwrap();
|
||||
set_file_mtime(&replacement, FileTime::from_unix_time(2, 0)).unwrap();
|
||||
let path = format!("{path}/notes.txt");
|
||||
let mut sender = sending(&path, true);
|
||||
assert_eq!(
|
||||
sender.init_data_stream_for_cm().await.unwrap(),
|
||||
Some((1, 12))
|
||||
);
|
||||
confirm_overwrite(&mut sender, 0).await;
|
||||
assert_eq!(
|
||||
sender.read().await.unwrap().unwrap().data.as_ref(),
|
||||
b"old contents"
|
||||
);
|
||||
assert!(sender.read().await.unwrap().unwrap().data.is_empty());
|
||||
let mut next = sending(&path, true);
|
||||
assert_eq!(next.init_data_stream_for_cm().await.unwrap(), Some((2, 12)));
|
||||
}
|
||||
|
||||
pub(super) async fn failed_block_cleans_pending_receive(path: &str, output: &Path) {
|
||||
for name in ["write-error.txt", "write-error-broken.txt"] {
|
||||
let mut job = receiving(&format!("{path}/{name}"));
|
||||
job.is_remote = false;
|
||||
let block = block(0, b"more data");
|
||||
// Tokio queues the first write and reports its I/O failure on the next block.
|
||||
job.write(block.clone()).await.unwrap();
|
||||
assert_eq!(std::fs::read(output).unwrap(), b"partial");
|
||||
let error = job.write(block).await.unwrap_err();
|
||||
assert!(error.downcast_ref::<std::io::Error>().is_some());
|
||||
assert_eq!(job.job_error(), Some(error.to_string()));
|
||||
assert!(
|
||||
!output.exists(),
|
||||
"A failed receive must discard partial data"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn failed_finalization_discards_partial_data(path: &str, output: &Path) {
|
||||
for name in ["write-error.txt", "broken.txt", "discard-error-broken.txt"] {
|
||||
let mut job = receiving(&format!("{path}/{name}"));
|
||||
confirm_overwrite(&mut job, 0).await;
|
||||
job.write(block(0, b"partial data")).await.unwrap();
|
||||
let error = job.finish_document().await.unwrap_err();
|
||||
assert_eq!(job.job_error(), Some(error.to_string()));
|
||||
if name.ends_with("broken.txt") {
|
||||
assert!(error.to_string().contains("Provider read failed"));
|
||||
} else {
|
||||
assert!(error.downcast_ref::<std::io::Error>().is_some());
|
||||
}
|
||||
if name.starts_with("discard-error") {
|
||||
assert!(error.to_string().contains("Provider cleanup failed"));
|
||||
assert!(output.exists());
|
||||
std::fs::remove_file(output).unwrap();
|
||||
} else {
|
||||
assert!(
|
||||
!output.exists(),
|
||||
"A failed finalization must discard partial data"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn changed_source_without_timestamp_rejects_resume(path: &str, output: &Path) {
|
||||
std::fs::write(output, b"old contents").unwrap();
|
||||
filetime::set_file_mtime(output, filetime::FileTime::from_unix_time(0, 0)).unwrap();
|
||||
stale_metadata_uses_current_digest(&format!("{path}/notes.txt")).await;
|
||||
let path = format!("{path}/stream.txt");
|
||||
let mut sender = sending(&path, true);
|
||||
let original_digest = sender.init_data_stream_for_cm().await.unwrap();
|
||||
assert_eq!(original_digest, Some((0, b"old contents".len() as u64)));
|
||||
confirm_overwrite(&mut sender, 0).await;
|
||||
assert_eq!(
|
||||
sender.read().await.unwrap().unwrap().data.as_ref(),
|
||||
b"old contents"
|
||||
);
|
||||
drop(sender);
|
||||
|
||||
std::fs::write(output, b"new contents").unwrap();
|
||||
let mut resumed = sending(&path, true);
|
||||
assert_eq!(
|
||||
resumed.init_data_stream_for_cm().await.unwrap(),
|
||||
original_digest
|
||||
);
|
||||
let mut confirmation = FileTransferSendConfirmRequest {
|
||||
id: resumed.id(),
|
||||
..Default::default()
|
||||
};
|
||||
confirmation.set_offset_blk(b"old ".len() as u32);
|
||||
resumed.confirm(&confirmation).await;
|
||||
assert_eq!(
|
||||
resumed.job_error().as_deref(),
|
||||
Some("Cannot resume a document with an unknown modification time; restart the transfer")
|
||||
);
|
||||
assert!(resumed.read().await.unwrap().is_none());
|
||||
assert!(resumed.job_completed());
|
||||
|
||||
let mut fresh = sending(&path, true);
|
||||
fresh.init_data_stream_for_cm().await.unwrap();
|
||||
confirm_overwrite(&mut fresh, 0).await;
|
||||
assert_eq!(
|
||||
fresh.read().await.unwrap().unwrap().data.as_ref(),
|
||||
b"new contents"
|
||||
);
|
||||
assert!(fresh.read().await.unwrap().unwrap().data.is_empty());
|
||||
std::fs::remove_file(output).unwrap();
|
||||
}
|
||||
|
||||
async fn stale_metadata_uses_current_digest(path: &str) {
|
||||
for (size, modified_time) in [(12, 1), (13, 0)] {
|
||||
let mut sender = sending(path, true)
|
||||
.with_files(vec![FileEntry {
|
||||
size,
|
||||
modified_time,
|
||||
..Default::default()
|
||||
}])
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sender.init_data_stream_for_cm().await.unwrap(),
|
||||
Some((0, b"old contents".len() as u64))
|
||||
);
|
||||
confirm_overwrite(&mut sender, 0).await;
|
||||
assert_eq!(
|
||||
sender.read().await.unwrap().unwrap().data.as_ref(),
|
||||
b"old contents"
|
||||
);
|
||||
assert!(sender.read().await.unwrap().unwrap().data.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -515,48 +515,6 @@ pub fn get_home_dir_trusted() -> Option<PathBuf> {
|
||||
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() {
|
||||
@@ -584,20 +542,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
|
||||
@@ -288,11 +288,3 @@ fn send_data_to_all(data: ClipboardFile) {
|
||||
allow_err!(msg_channel.sender.send(data.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
// #[test]
|
||||
// fn test_cliprdr_run() {
|
||||
// super::cliprdr_run();
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -244,8 +244,6 @@ mod tests {
|
||||
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;
|
||||
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
|
||||
|
||||
fn descriptor_pdu(name: &str) -> Vec<u8> {
|
||||
@@ -291,18 +289,6 @@ mod tests {
|
||||
assert_eq!(files[0].name, PathBuf::from("folder/nested/file.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_data_after_null_terminator() {
|
||||
let name = "file.txt";
|
||||
let mut pdu = descriptor_pdu(name);
|
||||
let padding_offset = NAME_OFFSET + (name.encode_utf16().count() + 1) * size_of::<u16>();
|
||||
pdu[padding_offset..padding_offset + size_of::<u16>()]
|
||||
.copy_from_slice(&INVALID_UTF16_UNIT.to_le_bytes());
|
||||
|
||||
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
|
||||
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.
|
||||
@@ -319,15 +305,6 @@ mod tests {
|
||||
assert_eq!(files[0].clip_data_id, id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_terminated_file_name() {
|
||||
let name = "a".repeat(FILE_NAME_CODE_UNITS);
|
||||
assert!(matches!(
|
||||
parse_name(&name),
|
||||
Err(CliprdrError::InvalidRequest { .. })
|
||||
));
|
||||
}
|
||||
|
||||
fn parse_perm(attributes: u32) -> u16 {
|
||||
let mut pdu = descriptor_pdu("folder");
|
||||
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
|
||||
|
||||
@@ -966,35 +966,6 @@ mod fuse_test {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_single_file(prefix: &str) {
|
||||
let raw_name = "simple_test_file.txt";
|
||||
let f_name = if prefix == "" {
|
||||
raw_name.to_string()
|
||||
} else {
|
||||
prefix.to_string() + "/" + raw_name
|
||||
};
|
||||
let desc = desc_gen(&f_name, FileType::File);
|
||||
let tree = FuseNode::build_tree(vec![desc]).unwrap();
|
||||
|
||||
assert_eq!(tree.len(), 2);
|
||||
assert_eq!(tree[0].name, "/");
|
||||
assert_eq!(tree[0].children, vec![2]);
|
||||
|
||||
assert_eq!(tree[1].name, raw_name);
|
||||
assert_eq!(tree[1].index, 0);
|
||||
assert_eq!(tree[1].attributes.kind, FileType::File);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_single() {
|
||||
build_single_file("");
|
||||
build_single_file("/");
|
||||
build_single_file("test");
|
||||
build_single_file("/test");
|
||||
build_single_file("🗂");
|
||||
build_single_file("/🗂");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_tree() {
|
||||
build_tree("");
|
||||
|
||||
@@ -322,7 +322,7 @@ pub(super) fn construct_file_list(paths: &[PathBuf]) -> Result<Vec<LocalFile>, C
|
||||
mod file_list_test {
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
sync::atomic::AtomicU64,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
@@ -466,32 +466,6 @@ mod file_list_test {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_exact_at_reopens_after_read_failure() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let file_path = std::env::temp_dir().join(format!(
|
||||
"rustdesk-clipboard-local-file-{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::write(&file_path, b"")?;
|
||||
|
||||
let mut file = LocalFile::try_open(&std::env::temp_dir(), &file_path)?;
|
||||
file.size = 1;
|
||||
|
||||
let mut buf = [0u8; 1];
|
||||
assert!(file.read_exact_at(&mut buf, 0).is_err());
|
||||
assert!(file.handle.is_none());
|
||||
assert_eq!(file.offset.load(Ordering::Relaxed), 0);
|
||||
|
||||
std::fs::write(&file_path, [42u8])?;
|
||||
|
||||
file.read_exact_at(&mut buf, 0)?;
|
||||
assert_eq!(buf, [42u8]);
|
||||
assert!(file.handle.is_none());
|
||||
|
||||
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 {
|
||||
@@ -519,18 +493,4 @@ mod file_list_test {
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -809,18 +809,6 @@ mod tests {
|
||||
assert!(!Path::new(&task.progress.download_file_path).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finder_progress_rejects_unrepresentable_byte_count() {
|
||||
let (_temp, target, _) = test_directories();
|
||||
let file = file_description("large.bin", FileType::File, i64::MAX as u64 + 1);
|
||||
let mut task = paste_task_handle(target.clone(), vec![file]);
|
||||
let error = task.update_next(0).expect_err("byte count must not wrap");
|
||||
assert!(matches!(&error, CliprdrError::InvalidRequest { .. }));
|
||||
task.on_error(error);
|
||||
assert!(task.progress.finder_progress.is_none());
|
||||
assert!(std::fs::read_dir(target).unwrap().next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_all_paths_before_creating_files() {
|
||||
let (_temp, target, outside) = test_directories();
|
||||
@@ -866,18 +854,4 @@ mod tests {
|
||||
assert!(!download_path.exists());
|
||||
assert!(!outside.join("file.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlink_component_when_creating_directory() {
|
||||
let (_temp, target, outside) = test_directories();
|
||||
symlink(&outside, target.join("link")).unwrap();
|
||||
|
||||
let directory = file_description("link/escaped", FileType::Directory, 0);
|
||||
let mut task = paste_task_handle(target, vec![directory]);
|
||||
assert!(matches!(
|
||||
task.update_next(0),
|
||||
Err(CliprdrError::InvalidRequest { .. })
|
||||
));
|
||||
assert!(!outside.join("escaped").exists());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,31 +430,3 @@ pub fn create_pasteboard_context() -> ResultType<Box<PasteboardContext>> {
|
||||
context.init();
|
||||
Ok(context)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn test_temp_files_count() {
|
||||
let mut c = super::PasteboardContext::temp_files_count();
|
||||
|
||||
let mut created_files = vec![];
|
||||
for _ in 0..10 {
|
||||
let path = format!(
|
||||
"/tmp/{}{}",
|
||||
super::TEMP_FILE_PREFIX,
|
||||
uuid::Uuid::new_v4().to_string()
|
||||
);
|
||||
if std::fs::File::create(&path).is_ok() {
|
||||
created_files.push(path);
|
||||
c += 1;
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(c, super::PasteboardContext::temp_files_count());
|
||||
|
||||
// Clean up the created files.
|
||||
for file in created_files {
|
||||
std::fs::remove_file(&file).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -523,48 +523,6 @@ mod sig_test {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_missing_path_is_default() {
|
||||
let tmp = TmpDir::new("missing");
|
||||
let missing = path_str(&tmp.join("does_not_exist.bin"));
|
||||
let sigs = fingerprint(&[missing]);
|
||||
assert_eq!(sigs.len(), 1);
|
||||
// A path that can't be stat'd -> default sig, which forces a rebuild.
|
||||
assert_eq!(sigs[0], FileSig::default());
|
||||
assert_eq!(sigs[0].mtime, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_detects_inplace_edit() {
|
||||
let tmp = TmpDir::new("edit");
|
||||
let file = tmp.join("a.bin");
|
||||
fs::write(&file, b"small").unwrap();
|
||||
let p = path_str(&file);
|
||||
|
||||
let before = fingerprint(&[p.clone()]);
|
||||
// Same content, same path: fingerprint must be stable.
|
||||
let again = fingerprint(&[p.clone()]);
|
||||
assert_eq!(before, again);
|
||||
assert_eq!(before[0].size, 5);
|
||||
assert!(!before[0].is_dir);
|
||||
|
||||
// Edit in place so the file grows.
|
||||
fs::write(&file, b"much larger contents than before").unwrap();
|
||||
let after = fingerprint(&[p]);
|
||||
assert_ne!(before, after);
|
||||
assert!(after[0].size > before[0].size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_flags_directory() {
|
||||
let tmp = TmpDir::new("dir");
|
||||
let sub = tmp.join("subdir");
|
||||
fs::create_dir_all(&sub).unwrap();
|
||||
let sigs = fingerprint(&[path_str(&sub)]);
|
||||
assert_eq!(sigs.len(), 1);
|
||||
assert!(sigs[0].is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recopy_after_edit_refreshes_cached_size() {
|
||||
let tmp = TmpDir::new("recopy");
|
||||
@@ -597,37 +555,6 @@ mod sig_test {
|
||||
clear_files(); // leave the global clean for other tests
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_huge_length_is_clamped() {
|
||||
let tmp = TmpDir::new("range");
|
||||
let file = tmp.join("data.bin");
|
||||
fs::write(&file, b"0123456789").unwrap();
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
let mut clip = ClipFiles::default();
|
||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
||||
let file_idx = clip.first_file_index;
|
||||
|
||||
// offset + length used to wrap to 0, skip the clamp and ask for a u64::MAX buffer.
|
||||
let resp = clip
|
||||
.serve_file_contents(
|
||||
0,
|
||||
FileContentsRequest::Range {
|
||||
stream_id: 0,
|
||||
file_idx,
|
||||
offset: 1,
|
||||
length: u64::MAX,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match resp {
|
||||
ClipboardFile::FileContentsResponse { requested_data, .. } => {
|
||||
assert_eq!(requested_data, b"123456789");
|
||||
}
|
||||
_ => panic!("unexpected response"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_decodes_wire_fields_as_u32() {
|
||||
let tmp = TmpDir::new("decode");
|
||||
@@ -756,172 +683,6 @@ mod sig_test {
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_recopy_keeps_the_current_list() {
|
||||
let tmp = TmpDir::new("failed_recopy");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let missing = tmp.join("missing.bin");
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let pdu = get_file_list_pdu(1);
|
||||
|
||||
assert!(sync_files(&[path_str(&missing)]).is_err());
|
||||
assert_eq!(get_file_list_pdu(1), pdu);
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
fn file_index(path: &PathBuf) -> i32 {
|
||||
let files = CLIP_FILES.lock();
|
||||
files
|
||||
.file_list
|
||||
.iter()
|
||||
.position(|f| &f.path == path)
|
||||
.unwrap() as i32
|
||||
}
|
||||
|
||||
// Replaces `path` the way editors save: write aside, then rename over it.
|
||||
fn replace_atomically(path: &PathBuf, data: &[u8]) {
|
||||
let aside = path.with_extension("new");
|
||||
fs::write(&aside, data).unwrap();
|
||||
fs::rename(&aside, path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retired_list_closes_only_files_not_being_read() {
|
||||
let tmp = TmpDir::new("retired_handles");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAABBBB").unwrap();
|
||||
let next = tmp.join("next.bin");
|
||||
fs::write(&next, b"CCCCDDDD").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&next)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, next_idx) = (file_index(&first), file_index(&next));
|
||||
let read =
|
||||
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
|
||||
// Leaves `first` open at offset 4, and preloads `next`.
|
||||
assert_eq!(read(first_idx, 0), b"AAAA");
|
||||
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
{
|
||||
let retired = RETIRED_CLIP_FILES.lock();
|
||||
let open = |idx: i32| retired[0].file_list[idx as usize].handle.is_some();
|
||||
assert!(open(first_idx));
|
||||
assert!(!open(next_idx));
|
||||
}
|
||||
assert_eq!(read(first_idx, 4), b"BBBB");
|
||||
assert_eq!(read(next_idx, 0), b"CCCC");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_being_read_keep_their_content_when_their_paths_are_replaced() {
|
||||
let tmp = TmpDir::new("replaced_paths");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"1111aaaa").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"2222bbbb").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
|
||||
let read =
|
||||
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
|
||||
// Two files part-way through at once.
|
||||
assert_eq!(read(first_idx, 0), b"1111");
|
||||
assert_eq!(read(second_idx, 0), b"2222");
|
||||
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
replace_atomically(&first, b"3333cccc");
|
||||
replace_atomically(&second, b"4444dddd");
|
||||
|
||||
assert_eq!(read(first_idx, 4), b"aaaa");
|
||||
assert_eq!(read(second_idx, 4), b"bbbb");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_file_metadata_in_another_folder_is_another_list() {
|
||||
let tmp = TmpDir::new("same_metadata");
|
||||
let (dir_a, dir_b) = (tmp.join("a"), tmp.join("b"));
|
||||
fs::create_dir_all(&dir_a).unwrap();
|
||||
fs::create_dir_all(&dir_b).unwrap();
|
||||
let (first, second) = (dir_a.join("report.bin"), dir_b.join("report.bin"));
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
// Same name, size and mtime: the descriptors differ only by the nonce.
|
||||
let mtime = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
for path in [&first, &second] {
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_modified(mtime)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
let second_id = file_list_id(&get_file_list_pdu(1));
|
||||
assert_ne!(first_id, second_id);
|
||||
|
||||
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
|
||||
assert_eq!(read(first_id), b"AAAA");
|
||||
assert_eq!(read(second_id), b"BBBB");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retired_list_refuses_a_file_replaced_before_its_read() {
|
||||
let tmp = TmpDir::new("replaced_unread");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
|
||||
let read = |idx, offset| read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id));
|
||||
assert_eq!(range_data(read(first_idx, 0)), b"AAAA");
|
||||
|
||||
// Retiring closes `second`, which has not been read yet; it is then replaced.
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
replace_atomically(&second, b"CCCCCCCCCC");
|
||||
|
||||
assert!(matches!(
|
||||
read(second_idx, 0).last(),
|
||||
Some(Err(CliprdrError::InvalidRequest { .. }))
|
||||
));
|
||||
// The file part-way through is unaffected.
|
||||
assert_eq!(range_data(read(first_idx, 4)), b"AAAA");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
fn list_files(selection: &[&PathBuf]) -> ClipFiles {
|
||||
let files: Vec<String> = selection.iter().map(|p| path_str(p)).collect();
|
||||
let mut clip = ClipFiles::default();
|
||||
@@ -975,23 +736,6 @@ mod sig_test {
|
||||
assert_only_its_own_requests_fail(&mut clip, &second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_next_file_fails_only_its_own_requests() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = TmpDir::new("next_unreadable");
|
||||
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
let mut clip = list_files(&[&first, &second]);
|
||||
|
||||
fs::set_permissions(&second, fs::Permissions::from_mode(0o000)).unwrap();
|
||||
// Root opens it regardless of its mode.
|
||||
if fs::File::open(&second).is_ok() {
|
||||
return;
|
||||
}
|
||||
assert_only_its_own_requests_fail(&mut clip, &second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_next_file_is_preloaded_past_a_directory() {
|
||||
let tmp = TmpDir::new("next_preloaded");
|
||||
|
||||
@@ -146,39 +146,3 @@ fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
|
||||
|
||||
Ok(tokens)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn success() {
|
||||
assert_eq!(
|
||||
tokenize("{{Hello World!}} {+CTRL}hi{-CTRL}"),
|
||||
Ok(vec![
|
||||
Token::Sequence("{Hello World!} ".into()),
|
||||
Token::KeyDown(Key::Control),
|
||||
Token::Sequence("hi".into()),
|
||||
Token::KeyUp(Key::Control)
|
||||
])
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn unexpected_open() {
|
||||
assert_eq!(tokenize("{hello{}world}"), Err(ParseError::UnexpectedOpen));
|
||||
}
|
||||
#[test]
|
||||
fn unmatched_open() {
|
||||
assert_eq!(
|
||||
tokenize("{this is going to fail"),
|
||||
Err(ParseError::UnmatchedOpen)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn unmatched_close() {
|
||||
assert_eq!(
|
||||
tokenize("{+CTRL}{{this}} is going to fail}"),
|
||||
Err(ParseError::UnmatchedClose)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,28 +525,3 @@ impl fmt::Debug for Enigo {
|
||||
write!(f, "Enigo")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_get_key_state() {
|
||||
let mut enigo = Enigo::new();
|
||||
let keys = [Key::CapsLock, Key::NumLock];
|
||||
for k in keys.iter() {
|
||||
enigo.key_click(k.clone());
|
||||
let a = enigo.get_key_state(k.clone());
|
||||
enigo.key_click(k.clone());
|
||||
let b = enigo.get_key_state(k.clone());
|
||||
assert!(a != b);
|
||||
}
|
||||
let keys = [Key::Control, Key::Alt, Key::Shift];
|
||||
for k in keys.iter() {
|
||||
enigo.key_down(k.clone()).ok();
|
||||
let a = enigo.get_key_state(k.clone());
|
||||
enigo.key_up(k.clone());
|
||||
let b = enigo.get_key_state(k.clone());
|
||||
assert!(a != b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,13 +391,6 @@ fn convert_to_tfc_key(key: Key) -> Option<TFC_Key> {
|
||||
Some(key)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_key_seq() {
|
||||
// Get 6^ in French.
|
||||
let mut en = Enigo::new();
|
||||
en.key_sequence("^^");
|
||||
}
|
||||
|
||||
/// Both directions: the failure is silent, so a one-directional test passes against the bug.
|
||||
#[test]
|
||||
fn test_custom_mouse_dispatch_follows_is_x11() {
|
||||
|
||||
@@ -36,6 +36,7 @@ const kUCKeyActionDisplay: u16 = 3;
|
||||
#[allow(non_upper_case_globals)]
|
||||
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
|
||||
const BUF_LEN: usize = 4;
|
||||
const KEYBOARD_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
const MOUSE_EVENT_BUTTON_NUMBER_BACK: i64 = 3;
|
||||
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
|
||||
@@ -428,7 +429,19 @@ impl KeyboardControllable for Enigo {
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
|
||||
event.set_string(cluster);
|
||||
self.post(event, None);
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-sequence: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-sequence: event source is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -436,17 +449,40 @@ impl KeyboardControllable for Enigo {
|
||||
fn key_click(&mut self, key: Key) {
|
||||
let keycode = self.key_to_keycode(key);
|
||||
if keycode == u16::MAX {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-click: keycode mapping is unavailable"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(src) = self.event_source.as_ref() {
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
|
||||
self.post(event, Some(keycode));
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-down in key-click: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
|
||||
self.post(event, Some(keycode));
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-up in key-click: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-click: event source is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,10 +501,29 @@ impl KeyboardControllable for Enigo {
|
||||
|
||||
fn key_up(&mut self, key: Key) {
|
||||
let code = self.key_to_keycode(key);
|
||||
if code == u16::MAX {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Cannot map macOS Enigo key-up to a keycode"
|
||||
);
|
||||
}
|
||||
if let Some(src) = self.event_source.as_ref() {
|
||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
|
||||
self.post(event, Some(code));
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-up: could not create keyboard event"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
hbb_common::throttled_log!(
|
||||
KEYBOARD_ERROR_LOG_INTERVAL,
|
||||
error,
|
||||
"Failed to inject macOS Enigo key-up: event source is not initialized"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
Submodule libs/hbb_common updated: 229b904508...fae47e024d
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rustdesk-portable-packer"
|
||||
version = "1.5.0"
|
||||
version = "1.5.1"
|
||||
edition = "2021"
|
||||
description = "RustDesk Remote Desktop"
|
||||
|
||||
@@ -20,6 +20,7 @@ windows = { version = "0.61", features = [
|
||||
"Wdk_System",
|
||||
"Wdk_System_SystemServices",
|
||||
"Win32",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System",
|
||||
"Win32_System_SystemInformation",
|
||||
] }
|
||||
@@ -36,4 +37,3 @@ FileDescription = "RustDesk Remote Desktop"
|
||||
winres = "0.1"
|
||||
winapi = { version = "0.3", features = [ "winnt", "pdh", "synchapi" ] }
|
||||
|
||||
|
||||
|
||||
@@ -279,26 +279,6 @@ mod tests {
|
||||
.find(|file| normalize_path(&file.path) == normalize_path(path))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_the_generate_py_layout() {
|
||||
let (files, exe) = parse(blob(
|
||||
&[("./rustdesk.exe", b"app"), ("./custom.txt", b"cfg")],
|
||||
"./rustdesk.exe",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(exe, "./rustdesk.exe");
|
||||
assert_eq!(files.len(), 2);
|
||||
assert_eq!(entry(&files, "./custom.txt").unwrap().raw, b"cfg");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_blobs() {
|
||||
assert!(parse(b"".as_slice()).is_none());
|
||||
assert!(parse(b"notrustd".as_slice()).is_none());
|
||||
// Truncated mid-record rather than panicking on a slice out of range.
|
||||
assert!(parse(b"rustdesk\x00\x00\x00\x40partial".as_slice()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinguishes_an_absent_package_from_a_malformed_one() {
|
||||
assert!(parse_package_blob(None).unwrap().0.is_empty());
|
||||
@@ -372,34 +352,4 @@ mod tests {
|
||||
);
|
||||
assert_eq!(entry(&files, "./librustdesk.dll").unwrap().raw, b"core");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_paths_are_recorded_for_the_dropped_file_sweep() {
|
||||
let package = parse(blob(
|
||||
&[("./custom.txt", b"cfg"), ("./data/logo.png", b"img")],
|
||||
"./acme.exe",
|
||||
))
|
||||
.unwrap();
|
||||
let mut paths: Vec<String> = package.0.iter().map(|f| f.path.clone()).collect();
|
||||
paths.sort();
|
||||
assert_eq!(paths, vec!["./custom.txt", "./data/logo.png"]);
|
||||
|
||||
// Merging must not disturb them: the generic payload contributes none.
|
||||
let embedded = parse(blob(&[("./librustdesk.dll", b"core")], "./rustdesk.exe")).unwrap();
|
||||
let (files, _) = merge(embedded, package);
|
||||
assert!(entry(&files, "./data/logo.png").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_paths_across_separator_styles() {
|
||||
// generate.py emits backslashes when it runs on Windows.
|
||||
let embedded = parse(blob(&[(".\\rustdesk.exe", b"app")], ".\\rustdesk.exe")).unwrap();
|
||||
let package = parse(blob(&[("./custom.txt", b"cfg")], "./acme.exe")).unwrap();
|
||||
|
||||
let (files, exe) = merge(embedded, package);
|
||||
|
||||
assert_eq!(exe, "./acme.exe");
|
||||
assert!(entry(&files, "./acme.exe").is_some());
|
||||
assert!(entry(&files, ".\\rustdesk.exe").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ const APP_METADATA_CONFIG: &str = "meta.toml";
|
||||
const META_LINE_PREFIX_TIMESTAMP: &str = "timestamp = ";
|
||||
const META_LINE_PREFIX_FILE: &str = "file = ";
|
||||
const APP_PREFIX: &str = "rustdesk";
|
||||
#[cfg(windows)]
|
||||
const VERIFIED_UPDATE_FILE_PREFIX: &str = "rustdesk-verified-";
|
||||
const APPNAME_RUNTIME_ENV_KEY: &str = "RUSTDESK_APPNAME";
|
||||
#[cfg(windows)]
|
||||
const SET_FOREGROUND_WINDOW_ENV_KEY: &str = "SET_FOREGROUND_WINDOW";
|
||||
@@ -287,6 +289,13 @@ fn main() -> Result<(), String> {
|
||||
#[cfg(not(windows))]
|
||||
let quick_support = false;
|
||||
|
||||
#[cfg(windows)]
|
||||
if args.first().is_some_and(|arg| arg == "--update") {
|
||||
if let Err(err) = win::schedule_verified_update_cleanup() {
|
||||
eprintln!("Failed to schedule verified update file cleanup: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let mut ui = false;
|
||||
let reader = BinaryReader::new()?;
|
||||
if let Some(exe) = setup(
|
||||
@@ -314,6 +323,33 @@ mod win {
|
||||
pub const RUNTIME_BROKER_EXE: &'static str = "C:\\Windows\\System32\\RuntimeBroker.exe";
|
||||
pub const WIN_TOPMOST_INJECTED_PROCESS_EXE: &'static str = "RuntimeBroker_rustdesk.exe";
|
||||
|
||||
pub(super) fn schedule_verified_update_cleanup() -> std::io::Result<()> {
|
||||
use windows::{
|
||||
core::{HSTRING, PCWSTR},
|
||||
Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT},
|
||||
};
|
||||
|
||||
let current_exe = std::env::current_exe()?;
|
||||
let is_verified_update = current_exe
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| {
|
||||
name.starts_with(super::VERIFIED_UPDATE_FILE_PREFIX) && name.ends_with(".exe")
|
||||
});
|
||||
if !is_verified_update {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
unsafe {
|
||||
MoveFileExW(
|
||||
&HSTRING::from(current_exe.as_path()),
|
||||
PCWSTR::null(),
|
||||
MOVEFILE_DELAY_UNTIL_REBOOT,
|
||||
)
|
||||
}
|
||||
.map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
pub(super) fn copy_runtime_broker(dir: &Path) {
|
||||
let src = RUNTIME_BROKER_EXE;
|
||||
let tgt = WIN_TOPMOST_INJECTED_PROCESS_EXE;
|
||||
|
||||
@@ -5,7 +5,7 @@ use winapi::{
|
||||
shared::{
|
||||
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
|
||||
ntdef::HANDLE,
|
||||
winerror::ERROR_INVALID_PRINTER_NAME,
|
||||
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
|
||||
},
|
||||
um::winspool::{
|
||||
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
|
||||
@@ -42,20 +42,49 @@ fn enum_local_printer(
|
||||
|
||||
#[inline]
|
||||
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
|
||||
let r = common_enum(
|
||||
"EnumPrintersW",
|
||||
enum_local_printer,
|
||||
1,
|
||||
|info: &PRINTER_INFO_1W| {
|
||||
if is_name_equal(name, info.pName) {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
},
|
||||
|| None,
|
||||
)?;
|
||||
Ok(r.unwrap_or(false))
|
||||
const PRINTER_INFO_LEVEL: DWORD = 1;
|
||||
let mut needed = 0;
|
||||
let mut returned = 0;
|
||||
if enum_local_printer(
|
||||
PRINTER_INFO_LEVEL,
|
||||
null_mut(),
|
||||
0,
|
||||
&mut needed,
|
||||
&mut returned,
|
||||
) == FALSE
|
||||
{
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
|
||||
bail!("Failed to query EnumPrintersW buffer size: {error}");
|
||||
}
|
||||
}
|
||||
if needed == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u8; needed as usize];
|
||||
if enum_local_printer(
|
||||
PRINTER_INFO_LEVEL,
|
||||
buffer.as_mut_ptr(),
|
||||
needed,
|
||||
&mut needed,
|
||||
&mut returned,
|
||||
) == FALSE
|
||||
{
|
||||
bail!(
|
||||
"Failed to call EnumPrintersW, error: {}",
|
||||
io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
|
||||
let printers = buffer.as_ptr() as *const PRINTER_INFO_1W;
|
||||
for index in 0..returned {
|
||||
let printer = unsafe { &*printers.add(index as usize) };
|
||||
if is_name_equal(name, printer.pName) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
// Only return the first matched printer
|
||||
|
||||
@@ -14,7 +14,7 @@ wayland = ["gstreamer", "gstreamer-app", "gstreamer-video", "dbus", "tracing", "
|
||||
# `drm` is a pure runtime-dlopen backend: rustdesk loads `libdrmtap.so.0` at runtime (`drmtap_dl.rs`)
|
||||
# and NEVER link-time links it, so the graceful PipeWire fallback when the .so or EGL is absent is
|
||||
# preserved and the drm build pulls in no libdrm/seccomp/cap/EGL link-time deps. The .so is pinned by
|
||||
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.8). We deliberately do
|
||||
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.12). We deliberately do
|
||||
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
|
||||
# and a CAP_SYS_ADMIN helper and emits `-ldrm -lseccomp -lcap`, which would defeat the dlopen model.
|
||||
# Depends on `wayland`: the three drm modules live inside the `#[cfg(feature = "wayland")]` arm of
|
||||
|
||||
@@ -506,7 +506,43 @@ pub extern "system" fn Java_ffi_FFI_onAppStart(mut env: JNIEnv, _class: JClass,
|
||||
let java_vm = jvm.get_java_vm_pointer() as *mut c_void;
|
||||
let context_jobject = context.as_obj().as_raw() as *mut c_void;
|
||||
*APPLICATION_CONTEXT.write().unwrap() = Some(context);
|
||||
*JVM.write().unwrap() = Some(jvm);
|
||||
if let Err(error) = base::fs::android::initialize(call_document_storage) {
|
||||
log::error!("Unable to initialize document storage: {}", error);
|
||||
}
|
||||
try_init_rustls_platform_verifier(&mut env, context_jobject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn call_document_storage(request: &str) -> hbb_common::ResultType<String> {
|
||||
use hbb_common::anyhow::anyhow;
|
||||
|
||||
const LOCAL_REFS: i32 = 4;
|
||||
let context = APPLICATION_CONTEXT
|
||||
.read()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.ok_or(anyhow!("Android application context is unavailable"))?;
|
||||
let jvm = JVM.read().unwrap();
|
||||
let jvm = jvm.as_ref().ok_or(anyhow!("Android VM is unavailable"))?;
|
||||
let mut env = jvm.attach_current_thread_as_daemon()?;
|
||||
let result = env.with_local_frame(LOCAL_REFS, |env| -> JniResult<String> {
|
||||
let request = env.new_string(request)?;
|
||||
let value = env
|
||||
.call_method(
|
||||
&context,
|
||||
"rustDocumentStorage",
|
||||
"(Ljava/lang/String;)Ljava/lang/String;",
|
||||
&[JValue::Object(&JObject::from(request))],
|
||||
)?
|
||||
.l()?;
|
||||
let value = JString::from(value);
|
||||
let value = env.get_string(&value)?;
|
||||
Ok(value.into())
|
||||
});
|
||||
if result.is_err() && env.exception_check()? {
|
||||
env.exception_clear()?;
|
||||
}
|
||||
Ok(result?)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user