Compare commits
@@ -234,7 +234,7 @@ jobs:
|
|||||||
CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}"
|
CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
CARGO_TEST_OPTIONS="--workspace --no-fail-fast"
|
CARGO_TEST_OPTIONS="--workspace --no-fail-fast -- --skip test_get_cursor_pos --skip test_get_key_state"
|
||||||
;;
|
;;
|
||||||
esac;
|
esac;
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,6 @@ on:
|
|||||||
upload-tag:
|
upload-tag:
|
||||||
type: string
|
type: string
|
||||||
default: "nightly"
|
default: "nightly"
|
||||||
publish-update-metadata:
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
|
|
||||||
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
|
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
|
||||||
# variables from this workflow!
|
# variables from this workflow!
|
||||||
@@ -48,54 +45,16 @@ env:
|
|||||||
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
|
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
|
||||||
VCPKG_CMAKE_VERSION: "4.3.0"
|
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
|
ARMV7_VCPKG_COMMIT_ID: "6f29f12e82a8293156836ad81cc9bf5af41fe836" # 2025.01.13, got "/opt/artifacts/vcpkg/vcpkg: No such file or directory" with latest version
|
||||||
VERSION: "1.5.1"
|
VERSION: "1.5.0"
|
||||||
NDK_VERSION: "r28c"
|
NDK_VERSION: "r28c"
|
||||||
#signing keys env variable checks
|
#signing keys env variable checks
|
||||||
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
||||||
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
|
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
|
||||||
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
|
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
|
||||||
PUBLISH_UPDATE_METADATA: "${{ inputs.publish-update-metadata }}"
|
|
||||||
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
|
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
|
||||||
|
|
||||||
jobs:
|
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:
|
generate-sbom:
|
||||||
needs: [validate-update-metadata-keys]
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
@@ -124,11 +83,9 @@ jobs:
|
|||||||
rustdesk.sbom.json
|
rustdesk.sbom.json
|
||||||
|
|
||||||
generate-bridge:
|
generate-bridge:
|
||||||
needs: [validate-update-metadata-keys]
|
|
||||||
uses: ./.github/workflows/bridge.yml
|
uses: ./.github/workflows/bridge.yml
|
||||||
|
|
||||||
build-RustDeskTempTopMostWindow:
|
build-RustDeskTempTopMostWindow:
|
||||||
needs: [validate-update-metadata-keys]
|
|
||||||
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
|
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
@@ -366,17 +323,6 @@ jobs:
|
|||||||
Write-Host "Ingore the printer driver error."
|
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
|
- name: find Runner.res
|
||||||
# Windows: find Runner.res (compiled from ./flutter/windows/runner/Runner.rc), copy to ./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
|
# Runner.rc does not contain actual version, but Runner.res does
|
||||||
@@ -414,18 +360,6 @@ jobs:
|
|||||||
pip3 install requests argparse
|
pip3 install requests argparse
|
||||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./rustdesk/
|
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
|
- name: Build self-extracted executable
|
||||||
shell: bash
|
shell: bash
|
||||||
if: env.UPLOAD_ARTIFACT == 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
@@ -516,25 +450,9 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput
|
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
|
- name: Publish Release
|
||||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
with:
|
with:
|
||||||
prerelease: true
|
prerelease: true
|
||||||
tag_name: ${{ env.TAG_NAME }}
|
tag_name: ${{ env.TAG_NAME }}
|
||||||
@@ -545,7 +463,6 @@ jobs:
|
|||||||
# The fallback for the flutter version, we use Sciter for 32bit Windows.
|
# The fallback for the flutter version, we use Sciter for 32bit Windows.
|
||||||
build-for-windows-sciter:
|
build-for-windows-sciter:
|
||||||
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
|
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
|
||||||
needs: [validate-update-metadata-keys]
|
|
||||||
runs-on: ${{ matrix.job.os }}
|
runs-on: ${{ matrix.job.os }}
|
||||||
# Temporarily disable this action due to additional test is needed.
|
# Temporarily disable this action due to additional test is needed.
|
||||||
# if: false
|
# if: false
|
||||||
@@ -678,18 +595,6 @@ jobs:
|
|||||||
pip3 install requests argparse
|
pip3 install requests argparse
|
||||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./Release/
|
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
|
- name: Build self-extracted executable
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
@@ -707,17 +612,9 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput/
|
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
|
- name: Publish Release
|
||||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
with:
|
with:
|
||||||
prerelease: true
|
prerelease: true
|
||||||
tag_name: ${{ env.TAG_NAME }}
|
tag_name: ${{ env.TAG_NAME }}
|
||||||
@@ -858,7 +755,6 @@ jobs:
|
|||||||
target: x86_64-apple-darwin,
|
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
|
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-build-args: "",
|
||||||
extra-cargo-features: "",
|
|
||||||
arch: x86_64,
|
arch: x86_64,
|
||||||
vcpkg-triplet: x64-osx,
|
vcpkg-triplet: x64-osx,
|
||||||
}
|
}
|
||||||
@@ -867,7 +763,6 @@ jobs:
|
|||||||
os: macos-14,
|
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: "--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-build-args: "--screencapturekit",
|
||||||
extra-cargo-features: ",screencapturekit",
|
|
||||||
arch: aarch64,
|
arch: aarch64,
|
||||||
vcpkg-triplet: arm64-osx,
|
vcpkg-triplet: arm64-osx,
|
||||||
}
|
}
|
||||||
@@ -976,10 +871,10 @@ jobs:
|
|||||||
name: bridge-artifact
|
name: bridge-artifact
|
||||||
path: ./
|
path: ./
|
||||||
|
|
||||||
- name: Run the Dart tests
|
- name: Test cursor sizing
|
||||||
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
||||||
working-directory: flutter
|
working-directory: flutter
|
||||||
run: flutter test --timeout 60s
|
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
|
||||||
|
|
||||||
- name: Setup vcpkg with Github Actions binary cache
|
- name: Setup vcpkg with Github Actions binary cache
|
||||||
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
||||||
@@ -1021,28 +916,9 @@ jobs:
|
|||||||
sed -i -e "s/platform :osx, '.*'/platform :osx, '${MIN_MACOS_VERSION}'/" flutter/macos/Podfile
|
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/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
|
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
|
fi
|
||||||
./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }}
|
./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
|
- name: create unsigned dmg
|
||||||
if: env.UPLOAD_ARTIFACT == 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
run: |
|
run: |
|
||||||
@@ -1075,13 +951,6 @@ jobs:
|
|||||||
./flutter/build/macos/Build/Products/Release/RustDesk.app \
|
./flutter/build/macos/Build/Products/Release/RustDesk.app \
|
||||||
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
|
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
|
||||||
./flutter/macos/Runner/Release.entitlements
|
./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
|
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
|
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict rustdesk-${{ env.VERSION }}.dmg -vvv
|
||||||
# notarize the rustdesk-${{ env.VERSION }}.dmg
|
# notarize the rustdesk-${{ env.VERSION }}.dmg
|
||||||
@@ -1089,26 +958,13 @@ jobs:
|
|||||||
|
|
||||||
- name: Rename rustdesk
|
- name: Rename rustdesk
|
||||||
if: env.UPLOAD_ARTIFACT == 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
VERSION: ${{ env.VERSION }}
|
|
||||||
ARCH: ${{ matrix.job.arch }}
|
|
||||||
run: |
|
run: |
|
||||||
if [ -f "rustdesk-${VERSION}.dmg" ]; then
|
for name in rustdesk*??.dmg; do
|
||||||
mv "rustdesk-${VERSION}.dmg" "rustdesk-${VERSION}-${ARCH}.dmg"
|
mv "$name" "${name%%.dmg}-${{ matrix.job.arch }}.dmg"
|
||||||
fi
|
done
|
||||||
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
|
- name: Publish DMG package
|
||||||
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
|
||||||
with:
|
with:
|
||||||
prerelease: true
|
prerelease: true
|
||||||
@@ -1116,141 +972,6 @@ jobs:
|
|||||||
files: |
|
files: |
|
||||||
rustdesk*-${{ matrix.job.arch }}.dmg
|
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:
|
publish_unsigned:
|
||||||
needs:
|
needs:
|
||||||
- build-for-macOS
|
- build-for-macOS
|
||||||
@@ -2359,27 +2080,10 @@ jobs:
|
|||||||
cargo test --locked --lib --features drm drm_capturer_tests
|
cargo test --locked --lib --features drm drm_capturer_tests
|
||||||
run_drm_tests "rustdesk ipc::test" \
|
run_drm_tests "rustdesk ipc::test" \
|
||||||
cargo test --locked --lib --features drm ipc::test
|
cargo test --locked --lib --features drm ipc::test
|
||||||
run_drm_tests "rustdesk cursor_pos_tests" \
|
|
||||||
cargo test --locked --lib --features drm cursor_pos_tests
|
|
||||||
run_drm_tests "rustdesk peer_abs_sample_tests" \
|
|
||||||
cargo test --locked --lib --features drm peer_abs_sample_tests
|
|
||||||
run_drm_tests "rustdesk input_map_tests" \
|
|
||||||
cargo test --locked --lib --features drm input_map_tests
|
|
||||||
run_drm_tests "rustdesk drm_pacing_tests" \
|
|
||||||
cargo test --locked --lib --features drm drm_pacing_tests
|
|
||||||
run_drm_tests "scrap hotspot_provenance_tests" \
|
run_drm_tests "scrap hotspot_provenance_tests" \
|
||||||
cargo test --locked -p scrap --features drm hotspot_provenance_tests
|
cargo test --locked -p scrap --features drm hotspot_provenance_tests
|
||||||
run_drm_tests "scrap hotspot_guess_tests" \
|
run_drm_tests "scrap hotspot_guess_tests" \
|
||||||
cargo test --locked -p scrap --features drm 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
|
cargo build --locked --lib --features "$FEATURES" --release
|
||||||
rm -rf target/release/deps target/release/build
|
rm -rf target/release/deps target/release/build
|
||||||
rm -rf ~/.cargo
|
rm -rf ~/.cargo
|
||||||
@@ -2460,7 +2164,6 @@ jobs:
|
|||||||
|
|
||||||
build-rustdesk-linux-sciter:
|
build-rustdesk-linux-sciter:
|
||||||
if: ${{ inputs.upload-artifact }}
|
if: ${{ inputs.upload-artifact }}
|
||||||
needs: [validate-update-metadata-keys]
|
|
||||||
runs-on: ${{ matrix.job.on }}
|
runs-on: ${{ matrix.job.on }}
|
||||||
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
|
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
|
||||||
strategy:
|
strategy:
|
||||||
@@ -2741,9 +2444,7 @@ jobs:
|
|||||||
sudo pip3 install git+https://github.com/rustdesk-org/appimage-builder.git
|
sudo pip3 install git+https://github.com/rustdesk-org/appimage-builder.git
|
||||||
# run appimage-builder
|
# run appimage-builder
|
||||||
pushd appimage
|
pushd appimage
|
||||||
./build-apprun.sh ${{ matrix.job.arch }}
|
|
||||||
sudo appimage-builder --skip-tests --recipe ./AppImageBuilder-${{ matrix.job.arch }}.yml
|
sudo appimage-builder --skip-tests --recipe ./AppImageBuilder-${{ matrix.job.arch }}.yml
|
||||||
cmp AppDir/AppRun appimage-build/AppRun/v2.0.0/AppRun-Release-${{ matrix.job.arch }}
|
|
||||||
|
|
||||||
- name: Publish appimage package
|
- name: Publish appimage package
|
||||||
if: env.UPLOAD_ARTIFACT == 'true'
|
if: env.UPLOAD_ARTIFACT == 'true'
|
||||||
@@ -2841,7 +2542,6 @@ jobs:
|
|||||||
|
|
||||||
build-rustdesk-web:
|
build-rustdesk-web:
|
||||||
if: False
|
if: False
|
||||||
needs: [validate-update-metadata-keys]
|
|
||||||
name: build-rustdesk-web
|
name: build-rustdesk-web
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
permissions:
|
permissions:
|
||||||
|
|||||||
@@ -15,5 +15,4 @@ jobs:
|
|||||||
secrets: inherit
|
secrets: inherit
|
||||||
with:
|
with:
|
||||||
upload-artifact: true
|
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"
|
TAG_NAME: "nightly"
|
||||||
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
|
||||||
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
|
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
|
||||||
VERSION: "1.5.1"
|
VERSION: "1.5.0"
|
||||||
NDK_VERSION: "r26d"
|
NDK_VERSION: "r26d"
|
||||||
#signing keys env variable checks
|
#signing keys env variable checks
|
||||||
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
|
||||||
|
|||||||
@@ -58,5 +58,3 @@ libsciter.dylib
|
|||||||
flutter/web/
|
flutter/web/
|
||||||
# libdrmtap is cloned at build time by build.py (not a submodule)
|
# libdrmtap is cloned at build time by build.py (not a submodule)
|
||||||
/third_party/libdrmtap/
|
/third_party/libdrmtap/
|
||||||
# Local git worktrees
|
|
||||||
.worktrees/
|
|
||||||
|
|||||||
@@ -48,20 +48,6 @@ workspace member. `base::config::keys` re-exports the handful of keys
|
|||||||
* Do not add dependencies unless needed.
|
* Do not add dependencies unless needed.
|
||||||
* Keep code simple and idiomatic.
|
* Keep code simple and idiomatic.
|
||||||
|
|
||||||
### Logging
|
|
||||||
|
|
||||||
* `debug` and above are written to the log file. A log call that can fire
|
|
||||||
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
|
|
||||||
peer controls) must not use `debug` or higher unthrottled.
|
|
||||||
* For such a site, pick one:
|
|
||||||
|
|
||||||
* `log::trace!` when the event is expected and the line only helps while
|
|
||||||
actively debugging;
|
|
||||||
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
|
|
||||||
that should still show up in a user's log. It keeps one line per interval
|
|
||||||
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
|
|
||||||
directly only when the decision drives more than one log call.
|
|
||||||
|
|
||||||
## Tokio Rules
|
## Tokio Rules
|
||||||
|
|
||||||
* Assume a Tokio runtime already exists.
|
* Assume a Tokio runtime already exists.
|
||||||
@@ -73,30 +59,6 @@ workspace member. `base::config::keys` re-exports the handful of keys
|
|||||||
* Use `spawn_blocking` or dedicated threads for blocking work.
|
* Use `spawn_blocking` or dedicated threads for blocking work.
|
||||||
* Do not use `std::thread::sleep()` in async code.
|
* Do not use `std::thread::sleep()` in async code.
|
||||||
|
|
||||||
## Flutter Rust Bridge
|
|
||||||
|
|
||||||
* Do **not** run `flutter_rust_bridge_codegen` — it requires a specific pinned version that is not easy to set up locally.
|
|
||||||
* When adding new FFI functions in `src/flutter_ffi.rs`, hand-write the corresponding Dart wrappers instead of regenerating.
|
|
||||||
* Web bridge (committed): edit `flutter/lib/web/bridge.dart` directly. Follow the existing patterns there for `SyncReturn<T>` / `Future<T>` and the `dart:js` glue.
|
|
||||||
* Native bridge (`flutter/lib/generated_bridge.dart`, `src/bridge_generated.rs`, `src/bridge_generated.io.rs`): these are gitignored and regenerated by the project's CI codegen. Manually editing them locally is fine for development testing, but those edits do not persist into commits.
|
|
||||||
|
|
||||||
## Web (Flutter Web) Architecture
|
|
||||||
|
|
||||||
Flutter Web in this repo is **not** "Dart compiled to JS via Flutter alone". The runtime is split:
|
|
||||||
|
|
||||||
* **Native targets (Win/Mac/Linux/Android/iOS)**: Rust drives sessions via `flutter_rust_bridge`; Dart only renders UI.
|
|
||||||
* **Web target**: Rust does **not** run. There is a separate hand-written TypeScript / JavaScript client at `flutter/web/js/` (gitignored — not present in this repo, lives in the maintainer's local tree). It owns connection, codec, keyboard, clipboard, etc. — basically a JS port of the Rust client. The Dart UI talks to it through `flutter/lib/web/bridge.dart`, which uses `dart:js` to call JS-side functions and to register Dart-side callbacks on `window.*`.
|
|
||||||
|
|
||||||
Implications when adding any session-runtime feature (keyboard, clipboard, audio, …):
|
|
||||||
|
|
||||||
* The Rust implementation in `src/` is for **native only**. Don't try to compile it to wasm.
|
|
||||||
* The matching Web-side logic must be written in TS/JS under `flutter/web/js/src/`. It's a translation of the Rust logic, usually simpler — Web is single-window, so any per-session-id plumbing in Rust collapses to a single global on Web.
|
|
||||||
* `flutter/lib/web/bridge.dart` is the only place where Dart sees JS. Other Dart code stays platform-agnostic and goes through `bind`. Don't sprinkle `if (isWeb)` runtime branches in shared Dart files to call Web-specific logic — put the platform divergence in the bridge.
|
|
||||||
* For JS → Dart events (e.g., a Web matcher firing), the convention is: Dart sets `js.context['onFooBar'] = (...) {...}` once at startup (typically in `mainInit`); the JS side calls `window.onFooBar(...)`. See `onLoadAbFinished`, `onLoadGroupFinished` for reference.
|
|
||||||
* The maintainer cannot easily run `flutter_rust_bridge_codegen`, so when a new FFI function lands in `src/flutter_ffi.rs`:
|
|
||||||
1. add the Web counterpart to `flutter/lib/web/bridge.dart` by hand;
|
|
||||||
2. note that on the Web target it may need to be a no-op or a JS bridge call rather than a real Rust invocation.
|
|
||||||
|
|
||||||
## Editing Hygiene
|
## Editing Hygiene
|
||||||
|
|
||||||
* Change only what is required.
|
* Change only what is required.
|
||||||
@@ -165,40 +127,12 @@ Before considering any implementation complete, perform a minimization pass over
|
|||||||
* Before finalizing, explicitly report the regression surface: list the existing files and existing runtime paths whose behavior changed, and explain why each change is unavoidable.
|
* Before finalizing, explicitly report the regression surface: list the existing files and existing runtime paths whose behavior changed, and explain why each change is unavoidable.
|
||||||
* During review, treat an unnecessarily modified legacy path as a review finding even if tests pass and the rewritten behavior appears equivalent.
|
* During review, treat an unnecessarily modified legacy path as a review finding even if tests pass and the rewritten behavior appears equivalent.
|
||||||
|
|
||||||
### Corner cases raised in review
|
|
||||||
|
|
||||||
A refactor added to cover a corner case rarely converges. Each new counter, timestamp, cache or eviction/expiry rule interacts with state that existing code relies on, and the next review round finds the problems it introduced.
|
|
||||||
|
|
||||||
* A corner case is still worth fixing when the fix is easy and low-risk: a local change of a few lines that adds no state and changes no existing lookup, such as moving a check or refusing bad input earlier.
|
|
||||||
* When the only fix needs new state, a new lifecycle rule or a restructure, and the code already fails cleanly there or behaves as master does, document it as a known limit in the PR instead. Anything beyond the easy fix needs the maintainer's explicit go-ahead first.
|
|
||||||
* Before adding state that reorders, expires or reuses existing data, list every lookup that reads that data and check each one still holds.
|
|
||||||
* Prefer a clean failure, where the operation reports an error, over machinery that tries to make a rare case succeed.
|
|
||||||
* A severity label from any reviewer (P1, Critical, Major) is not a triage result. Apply the next rule by consequence, not by label.
|
|
||||||
* A corner case whose fix needs new state is fixed only when it crashes, loses data, weakens security, or a user has reported it. A rare cosmetic or layout glitch (e.g. rotation during an active drag, a feature that is off by default) is a known limit: reply once, list it under "Known limits" in the PR body, and leave the code alone.
|
|
||||||
* When a finding is about behavior an earlier commit of this same PR introduced, fix it by removing or simplifying that commit, not by adding a layer on top.
|
|
||||||
* Judge growth across all rounds, not per round. If review follow-ups have grown the non-test diff by more than half of the first fix, or added a new kind of state (handles into another component, cross-component references, deferred / post-frame callbacks, timers, caches, flags), stop and ask the maintainer before pushing.
|
|
||||||
* When keeping the user's preferred state is hard in a rare case, fall back to a deterministic default computed from the current inputs. Do not coordinate mutable state across components or frames to preserve the preference.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
* A fix gets regression tests for the reported behavior only: they fail on master and pass with the fix. One to three tests is normal.
|
|
||||||
* Assert what the user sees or what the API returns. Do not test private state, the order an algorithm runs its steps in, or each corner case raised in review.
|
|
||||||
* Do not add test infrastructure (browser runners, golden/screenshot harnesses, new mock layers, test-only hooks in production code) for a bug fix unless the maintainer asks.
|
|
||||||
* If the test diff is more than twice the fix, cut it back to the tests that pin the reported behavior. A state that needs long setup to reach is usually too rare to fix.
|
|
||||||
* When the number of tests needed to describe the behavior keeps growing, the implementation is too complex: simplify it instead of adding tests.
|
|
||||||
* 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
|
## Reviewing a PR
|
||||||
|
|
||||||
* Review only what the diff introduces. Verify ownership with `gh pr diff` before reporting a finding — if the offending lines are untouched context, it is a pre-existing problem, not this PR's.
|
* Review only what the diff introduces. Verify ownership with `gh pr diff` before reporting a finding — if the offending lines are untouched context, it is a pre-existing problem, not this PR's.
|
||||||
* List pre-existing problems in a separate section at the end, or leave out the ones that are not fatal. Never mix them into the findings the author has to fix.
|
* List pre-existing problems in a separate section at the end, or leave out the ones that are not fatal. Never mix them into the findings the author has to fix.
|
||||||
* Before re-reviewing, read the author's reply comments. Do not re-raise items they declined on scope grounds.
|
* Before re-reviewing, read the author's reply comments. Do not re-raise items they declined on scope grounds.
|
||||||
* State a finding's consequence exactly: distinguish "the value is lost" from "the shortcut is inert but the value still saves".
|
* State a finding's consequence exactly: distinguish "the value is lost" from "the shortcut is inert but the value still saves".
|
||||||
* Do not report a rare corner case as blocking when fixing it needs new state; mark it as a known limit the author may leave unfixed.
|
|
||||||
* Treat growth across review rounds as a finding: if the latest commits add more state than the original fix, say so instead of asking for more handling.
|
|
||||||
|
|
||||||
## Localization (`src/lang/*.rs`)
|
## Localization (`src/lang/*.rs`)
|
||||||
|
|
||||||
|
|||||||
Generated
+21
-16
@@ -1305,7 +1305,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "clipboard-master"
|
name = "clipboard-master"
|
||||||
version = "4.0.0-beta.6"
|
version = "4.0.0-beta.6"
|
||||||
source = "git+https://github.com/rustdesk-org/clipboard-master#522fafb65edfe7939cf63fa797f916569ecab595"
|
source = "git+https://github.com/rustdesk-org/clipboard-master#7762d74e38db37cfeb6ded88c964b9cdbddfb6db"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"objc",
|
"objc",
|
||||||
"objc-foundation",
|
"objc-foundation",
|
||||||
@@ -4163,6 +4163,16 @@ version = "2.11.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
|
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]]
|
[[package]]
|
||||||
name = "is-terminal"
|
name = "is-terminal"
|
||||||
version = "0.4.16"
|
version = "0.4.16"
|
||||||
@@ -6762,7 +6772,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "rdev"
|
name = "rdev"
|
||||||
version = "0.5.0-2"
|
version = "0.5.0-2"
|
||||||
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
|
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cocoa 0.24.1",
|
"cocoa 0.24.1",
|
||||||
"core-foundation 0.9.4",
|
"core-foundation 0.9.4",
|
||||||
@@ -6891,10 +6901,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "reqwest"
|
||||||
version = "0.12.28"
|
version = "0.12.24"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-compression",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
@@ -6923,6 +6934,7 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"tokio-native-tls",
|
"tokio-native-tls",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
|
"tokio-util",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
@@ -7075,7 +7087,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustdesk"
|
name = "rustdesk"
|
||||||
version = "1.5.1"
|
version = "1.5.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"android-wakelock",
|
"android-wakelock",
|
||||||
"android_logger",
|
"android_logger",
|
||||||
@@ -7175,7 +7187,6 @@ dependencies = [
|
|||||||
"uuid",
|
"uuid",
|
||||||
"virtual_display",
|
"virtual_display",
|
||||||
"wallpaper",
|
"wallpaper",
|
||||||
"wayland-client",
|
|
||||||
"winapi 0.3.9",
|
"winapi 0.3.9",
|
||||||
"windows 0.61.1",
|
"windows 0.61.1",
|
||||||
"windows-service",
|
"windows-service",
|
||||||
@@ -7185,14 +7196,13 @@ dependencies = [
|
|||||||
"wol-rs",
|
"wol-rs",
|
||||||
"x11-clipboard 0.8.1",
|
"x11-clipboard 0.8.1",
|
||||||
"x11rb 0.12.0",
|
"x11rb 0.12.0",
|
||||||
"xkbcommon-dl",
|
|
||||||
"xxhash-rust",
|
"xxhash-rust",
|
||||||
"zstd",
|
"zstd",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustdesk-portable-packer"
|
name = "rustdesk-portable-packer"
|
||||||
version = "1.5.1"
|
version = "1.5.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"brotli",
|
"brotli",
|
||||||
"dirs 5.0.1",
|
"dirs 5.0.1",
|
||||||
@@ -8734,25 +8744,20 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tower-http"
|
name = "tower-http"
|
||||||
version = "0.6.11"
|
version = "0.6.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-compression",
|
|
||||||
"bitflags 2.9.1",
|
"bitflags 2.9.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-core",
|
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"http-body-util",
|
"iri-string",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"tokio",
|
|
||||||
"tokio-util",
|
|
||||||
"tower",
|
"tower",
|
||||||
"tower-layer",
|
"tower-layer",
|
||||||
"tower-service",
|
"tower-service",
|
||||||
"url",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
+2
-4
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "rustdesk"
|
name = "rustdesk"
|
||||||
version = "1.5.1"
|
version = "1.5.0"
|
||||||
authors = ["rustdesk <info@rustdesk.com>"]
|
authors = ["rustdesk <info@rustdesk.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
build= "build.rs"
|
build= "build.rs"
|
||||||
@@ -202,8 +202,6 @@ gtk = "0.18"
|
|||||||
termios = "0.3"
|
termios = "0.3"
|
||||||
terminfo = "0.8"
|
terminfo = "0.8"
|
||||||
winit = "0.30"
|
winit = "0.30"
|
||||||
wayland-client = "0.31"
|
|
||||||
xkbcommon-dl = { version = "0.4", features = ["x11"] }
|
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
|
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
|
||||||
openssl = { version = "0.10", features = ["vendored"] }
|
openssl = { version = "0.10", features = ["vendored"] }
|
||||||
@@ -273,7 +271,7 @@ os-version = "0.2"
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
hound = "3.5"
|
hound = "3.5"
|
||||||
docopt = "1.1"
|
docopt = "1.1"
|
||||||
tokio = "1.44"
|
tokio = { version = "1.44", features = ["test-util"] }
|
||||||
|
|
||||||
[package.metadata.bundle]
|
[package.metadata.bundle]
|
||||||
name = "RustDesk"
|
name = "RustDesk"
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ AppDir:
|
|||||||
id: rustdesk
|
id: rustdesk
|
||||||
name: rustdesk
|
name: rustdesk
|
||||||
icon: rustdesk
|
icon: rustdesk
|
||||||
version: 1.5.1
|
version: 1.5.0
|
||||||
exec: usr/share/rustdesk/rustdesk
|
exec: usr/share/rustdesk/rustdesk
|
||||||
exec_args: $@
|
exec_args: $@
|
||||||
apt:
|
apt:
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ AppDir:
|
|||||||
id: rustdesk
|
id: rustdesk
|
||||||
name: rustdesk
|
name: rustdesk
|
||||||
icon: rustdesk
|
icon: rustdesk
|
||||||
version: 1.5.1
|
version: 1.5.0
|
||||||
exec: usr/share/rustdesk/rustdesk
|
exec: usr/share/rustdesk/rustdesk
|
||||||
exec_args: $@
|
exec_args: $@
|
||||||
apt:
|
apt:
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
--- a/src/common/shell_utils.c
|
|
||||||
+++ b/src/common/shell_utils.c
|
|
||||||
@@ -201,7 +201,8 @@
|
|
||||||
|
|
||||||
const char *begin = str;
|
|
||||||
const char *end = str;
|
|
||||||
- char buffer[1024] = {0x0};
|
|
||||||
+ size_t buffer_size = strlen(str) + 1;
|
|
||||||
+ char *buffer = calloc(buffer_size, sizeof(char));
|
|
||||||
|
|
||||||
while (*begin != '\0') {
|
|
||||||
begin = apprun_string_consume_spaces(begin);
|
|
||||||
@@ -209,7 +210,7 @@
|
|
||||||
|
|
||||||
if (*begin == '\\') {
|
|
||||||
strncat(buffer, begin + 1, 1);
|
|
||||||
- end = begin + 2;
|
|
||||||
+ end = begin[1] != '\0' ? begin + 2 : begin + 1;
|
|
||||||
consumed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -218,7 +219,8 @@
|
|
||||||
strncat(buffer, begin + 1, end - begin - 1);
|
|
||||||
consumed = true;
|
|
||||||
|
|
||||||
- end++;
|
|
||||||
+ if (*end != '\0')
|
|
||||||
+ end++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!consumed && *begin == '\"') {
|
|
||||||
@@ -226,7 +228,8 @@
|
|
||||||
strncat(buffer, begin + 1, end - begin - 1);
|
|
||||||
consumed = true;
|
|
||||||
|
|
||||||
- end++;
|
|
||||||
+ if (*end != '\0')
|
|
||||||
+ end++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!consumed && *begin != '\'' && *begin != '\"' && *begin != '\\') {
|
|
||||||
@@ -240,11 +243,12 @@
|
|
||||||
split_count++;
|
|
||||||
}
|
|
||||||
|
|
||||||
- memset(buffer, 0, 1024);
|
|
||||||
+ buffer[0] = '\0';
|
|
||||||
}
|
|
||||||
|
|
||||||
begin = end;
|
|
||||||
}
|
|
||||||
|
|
||||||
+ free(buffer);
|
|
||||||
return splits;
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
# AppRun v2.0.0, which appimage-builder downloads, splits every argument into a 1 KiB stack
|
|
||||||
# buffer, so any argument of 1024 bytes or more aborts the AppImage before RustDesk starts.
|
|
||||||
# Build it with apprun-split-arguments.patch into the path appimage-builder checks before
|
|
||||||
# downloading. ubuntu:16.04 is what upstream released from, so the host glibc floor is unchanged.
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
arch=$1
|
|
||||||
version=v2.0.0
|
|
||||||
commit=407700ccef58e1a64cc49856074aee4b1c75d599
|
|
||||||
sha256=05729f2ae0a744369d2d19d0f37acfbdcb1ee064172955b7576883ccef5113b3
|
|
||||||
image=ubuntu:16.04@sha256:1f1a2d56de1d604801a9671f301190704c25d604a416f59e03c04f5c6ffee0d6
|
|
||||||
here=$(cd "$(dirname "$0")" && pwd)
|
|
||||||
|
|
||||||
case $arch in
|
|
||||||
x86_64) packages="cmake make g++" ;;
|
|
||||||
aarch64) packages="cmake make g++ g++-aarch64-linux-gnu" ;;
|
|
||||||
*) echo "Unsupported arch: $arch" >&2; exit 1 ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
tmp=$(mktemp -d)
|
|
||||||
src=$tmp/src
|
|
||||||
curl -fsSL -o "$tmp/apprun.tar.gz" "https://github.com/AppImageCrafters/AppRun/archive/$commit.tar.gz"
|
|
||||||
echo "$sha256 $tmp/apprun.tar.gz" | sha256sum -c -
|
|
||||||
mkdir "$src"
|
|
||||||
tar -xzf "$tmp/apprun.tar.gz" -C "$src" --strip-components=1
|
|
||||||
patch -d "$src" -p1 < "$here/apprun-split-arguments.patch"
|
|
||||||
|
|
||||||
docker run --rm -v "$src:/src" -w /src -e DEBIAN_FRONTEND=noninteractive "$image" bash -c "
|
|
||||||
set -e
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends $packages
|
|
||||||
mkdir build && cd build
|
|
||||||
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=../cmake/$arch-toolchain.cmake
|
|
||||||
cmake --build . --target AppRun"
|
|
||||||
|
|
||||||
mkdir -p "$here/appimage-build/AppRun/$version"
|
|
||||||
cp "$src/build/src/apprun/AppRun" "$here/appimage-build/AppRun/$version/AppRun-Release-$arch"
|
|
||||||
@@ -390,9 +390,9 @@ def ffi_bindgen_function_refactor():
|
|||||||
# The commit is fetched directly by sha, so no branch or tag name takes part in the build: see
|
# 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
|
# 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
|
# 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.12.
|
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.6.
|
||||||
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
|
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
|
||||||
LIBDRMTAP_SHA_PINNED = '5936a7a88b94aa43516a3dd0eb509d2383f31e2d'
|
LIBDRMTAP_SHA_PINNED = '49b204f275af1a2d6dfead94effb4036c7d50a3a'
|
||||||
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
|
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
|
||||||
LIBDRMTAP_SHA = os.environ.get('DRMTAP_SHA', LIBDRMTAP_SHA_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
|
# Every way of getting a different .so than the pin needs the same explicit opt-in. Otherwise the
|
||||||
|
|||||||
@@ -199,7 +199,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
|
|||||||
context,
|
context,
|
||||||
Manifest.permission.RECORD_AUDIO
|
Manifest.permission.RECORD_AUDIO
|
||||||
) != PackageManager.PERMISSION_GRANTED) {
|
) != PackageManager.PERMISSION_GRANTED) {
|
||||||
"To start a voice call, enable \"Audio capture\" on the \"Share screen\" page."
|
"To start a voice call, enable \"Audio capture\" on the \"Screen share\" page."
|
||||||
} else {
|
} else {
|
||||||
"Failed to start voice call."
|
"Failed to start voice call."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import android.os.Bundle
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import android.view.KeyEvent
|
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
import android.media.MediaCodecInfo
|
import android.media.MediaCodecInfo
|
||||||
import android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
|
import android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
|
||||||
@@ -36,7 +35,6 @@ import org.json.JSONArray
|
|||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import com.hjq.permissions.XXPermissions
|
import com.hjq.permissions.XXPermissions
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
import io.flutter.embedding.android.FlutterView
|
|
||||||
import io.flutter.embedding.engine.FlutterEngine
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
import io.flutter.plugin.common.MethodChannel
|
import io.flutter.plugin.common.MethodChannel
|
||||||
import kotlin.concurrent.thread
|
import kotlin.concurrent.thread
|
||||||
@@ -109,15 +107,6 @@ class MainActivity : FlutterActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
|
||||||
if (event.action == KeyEvent.ACTION_DOWN &&
|
|
||||||
KeyEvent.isModifierKey(event.keyCode) && currentFocus == null) {
|
|
||||||
// Android can drop modifier-first input when the native view has no focus.
|
|
||||||
findViewById<FlutterView>(FlutterActivity.FLUTTER_VIEW_ID)?.requestFocus()
|
|
||||||
}
|
|
||||||
return super.dispatchKeyEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun requestMediaProjection() {
|
private fun requestMediaProjection() {
|
||||||
val intent = Intent(this, PermissionRequestTransparentActivity::class.java).apply {
|
val intent = Intent(this, PermissionRequestTransparentActivity::class.java).apply {
|
||||||
action = ACT_REQUEST_MEDIA_PROJECTION
|
action = ACT_REQUEST_MEDIA_PROJECTION
|
||||||
|
|||||||
+57
-66
@@ -154,7 +154,7 @@ prebuild)
|
|||||||
.github/workflows/bridge.yml)"
|
.github/workflows/bridge.yml)"
|
||||||
|
|
||||||
FLUTTER_BRIDGE_VERSION="$(yq -r \
|
FLUTTER_BRIDGE_VERSION="$(yq -r \
|
||||||
'.jobs.generate_bridge.strategy.matrix.job[] | select(.["artifact-name"] == "bridge-artifact") | .["flutter-version"]' \
|
.env.FLUTTER_VERSION \
|
||||||
.github/workflows/bridge.yml)"
|
.github/workflows/bridge.yml)"
|
||||||
|
|
||||||
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
|
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
|
||||||
@@ -306,69 +306,67 @@ prebuild)
|
|||||||
|
|
||||||
git apply res/fdroid/patches/*.patch
|
git apply res/fdroid/patches/*.patch
|
||||||
|
|
||||||
# Generate bridge files using `FLUTTER_BRIDGE_VERSION`, which may differ
|
# If Flutter version used to generate bridge files differs from Flutter
|
||||||
# from the Flutter version used to compile RustDesk library, and restore
|
# version used to compile Rustdesk library, generate bridge using the
|
||||||
# the pubspec later
|
# `FLUTTER_BRIDGE_VERSION` an restore the pubspec later
|
||||||
|
|
||||||
# Find first libclang.so and set BRIDGE_LLVM_PATH
|
if [ "${FLUTTER_VERSION}" != "${FLUTTER_BRIDGE_VERSION}" ]; then
|
||||||
|
# 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
|
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
|
||||||
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
|
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
|
||||||
exit 1
|
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
|
||||||
fi
|
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
|
|
||||||
|
|
||||||
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
|
# Install Flutter version for RustDesk library build
|
||||||
|
|
||||||
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
|
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
|
||||||
@@ -381,13 +379,6 @@ prebuild)
|
|||||||
flutter/android/build.gradle \
|
flutter/android/build.gradle \
|
||||||
flutter/android/app/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.
|
# `firebase_analytics` is not in these files now, but we still keep the following lines.
|
||||||
|
|
||||||
sed \
|
sed \
|
||||||
|
|||||||
@@ -271,6 +271,11 @@ class AllPeersLoader {
|
|||||||
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
|
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
|
||||||
_updateOnlineState(evt);
|
_updateOnlineState(evt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@visibleForTesting
|
||||||
|
bool applyLastOnlineStateForTesting(List<Peer> peers) {
|
||||||
|
return _applyLastOnlineState(peers);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class AutocompletePeerTile extends StatefulWidget {
|
class AutocompletePeerTile extends StatefulWidget {
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
// flutter/lib/common/widgets/keyboard_shortcuts/display.dart
|
|
||||||
import 'dart:convert';
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import '../../../consts.dart';
|
|
||||||
import '../../../models/platform_model.dart';
|
|
||||||
import 'shortcut_utils.dart';
|
|
||||||
|
|
||||||
/// Read the bindings JSON and produce a human-readable shortcut string for
|
|
||||||
/// `actionId`, formatted for the current OS. Returns null if unbound, or —
|
|
||||||
/// when [requireEnabled] is true (the default) — when the master toggle is
|
|
||||||
/// off. The configuration page passes `requireEnabled: false` so users still
|
|
||||||
/// see what they have bound while the feature is disabled.
|
|
||||||
class ShortcutDisplay {
|
|
||||||
// Cache parsed JSON keyed by the raw string — called per visible action on
|
|
||||||
// every menu rebuild, so the jsonDecode is the real cost. Invalidation is
|
|
||||||
// automatic: a write changes the raw and we re-parse.
|
|
||||||
static String? _cachedRaw;
|
|
||||||
static Map<String, dynamic>? _cachedParsed;
|
|
||||||
|
|
||||||
@visibleForTesting
|
|
||||||
static void resetCache() {
|
|
||||||
_cachedRaw = null;
|
|
||||||
_cachedParsed = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String? formatFor(String actionId, {bool requireEnabled = true}) {
|
|
||||||
final raw = bind.mainGetLocalOption(key: kShortcutLocalConfigKey);
|
|
||||||
if (raw.isEmpty) return null;
|
|
||||||
Map<String, dynamic>? parsed;
|
|
||||||
if (raw == _cachedRaw) {
|
|
||||||
parsed = _cachedParsed;
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
parsed = jsonDecode(raw) as Map<String, dynamic>;
|
|
||||||
} catch (_) {
|
|
||||||
parsed = null;
|
|
||||||
}
|
|
||||||
_cachedRaw = raw;
|
|
||||||
_cachedParsed = parsed;
|
|
||||||
}
|
|
||||||
if (parsed == null) return null;
|
|
||||||
if (requireEnabled && parsed['enabled'] != true) return null;
|
|
||||||
// When pass-through is on, the matcher returns early on every keystroke.
|
|
||||||
// Showing the bound combo next to a menu item would lie to the user — they
|
|
||||||
// would press it expecting the local action and instead the keys would go
|
|
||||||
// to the remote. Treat as unbound for display purposes.
|
|
||||||
if (requireEnabled && parsed['pass_through'] == true) return null;
|
|
||||||
final list = shortcutBindingMapsFrom(parsed['bindings']);
|
|
||||||
final found = list.firstWhere(
|
|
||||||
(b) => b['action'] == actionId,
|
|
||||||
orElse: () => {},
|
|
||||||
);
|
|
||||||
if (found.isEmpty) return null;
|
|
||||||
|
|
||||||
// Guard against a hand-edited / corrupt config where `key` is missing or
|
|
||||||
// not a string — silently treat the binding as unbound rather than
|
|
||||||
// crashing the toolbar render.
|
|
||||||
final keyValue = found['key'];
|
|
||||||
if (keyValue is! String) return null;
|
|
||||||
|
|
||||||
final isMac = defaultTargetPlatform == TargetPlatform.macOS ||
|
|
||||||
defaultTargetPlatform == TargetPlatform.iOS;
|
|
||||||
// `mods` similarly may be malformed; treat a non-list as no modifiers.
|
|
||||||
final modsRaw = found['mods'];
|
|
||||||
final mods = modsRaw is List
|
|
||||||
? modsRaw.whereType<String>().toList()
|
|
||||||
: const <String>[];
|
|
||||||
// Plain-text labels (Cmd / Ctrl / Alt / Shift) instead of Unicode glyphs
|
|
||||||
// (⌘ ⌃ ⌥ ⇧). Flutter Web's CanvasKit bundled fonts don't always carry the
|
|
||||||
// macOS modifier symbols, which renders as garbled boxes on Mac browsers;
|
|
||||||
// text is portable and readable on every platform.
|
|
||||||
//
|
|
||||||
// Order matches the canonical macOS order (Cmd, Control, Option, Shift)
|
|
||||||
// so the rendered hint reads naturally. `ctrl` only ever appears in
|
|
||||||
// saved bindings on macOS — Win/Linux collapses Ctrl into `primary`.
|
|
||||||
final parts = <String>[];
|
|
||||||
for (final m in ['primary', 'ctrl', 'alt', 'shift']) {
|
|
||||||
if (!mods.contains(m)) continue;
|
|
||||||
switch (m) {
|
|
||||||
case 'primary': parts.add(isMac ? 'Cmd' : 'Ctrl'); break;
|
|
||||||
case 'ctrl': parts.add(isMac ? 'Control' : 'Ctrl'); break;
|
|
||||||
case 'alt': parts.add(isMac ? 'Option' : 'Alt'); break;
|
|
||||||
case 'shift': parts.add('Shift'); break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
parts.add(_keyDisplay(keyValue));
|
|
||||||
return parts.join('+');
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _keyDisplay(String key) {
|
|
||||||
switch (key) {
|
|
||||||
case 'delete': return 'Del';
|
|
||||||
case 'backspace': return 'Backspace';
|
|
||||||
case 'enter': return 'Enter';
|
|
||||||
case 'tab': return 'Tab';
|
|
||||||
case 'space': return 'Space';
|
|
||||||
case 'arrow_left': return 'Left';
|
|
||||||
case 'arrow_right':return 'Right';
|
|
||||||
case 'arrow_up': return 'Up';
|
|
||||||
case 'arrow_down': return 'Down';
|
|
||||||
case 'home': return 'Home';
|
|
||||||
case 'end': return 'End';
|
|
||||||
case 'page_up': return 'PgUp';
|
|
||||||
case 'page_down': return 'PgDn';
|
|
||||||
case 'insert': return 'Ins';
|
|
||||||
}
|
|
||||||
if (key.startsWith('digit')) return key.substring(5);
|
|
||||||
// F-keys ("f1".."f12") and single letters fall through to uppercase.
|
|
||||||
return key.toUpperCase();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,481 +0,0 @@
|
|||||||
// flutter/lib/common/widgets/keyboard_shortcuts/page_body.dart
|
|
||||||
//
|
|
||||||
// Shared body widget for the Keyboard Shortcuts configuration page. Both the
|
|
||||||
// desktop (`desktop/pages/desktop_keyboard_shortcuts_page.dart`) and mobile
|
|
||||||
// (`mobile/pages/mobile_keyboard_shortcuts_page.dart`) pages render this
|
|
||||||
// widget inside their own platform-styled Scaffold + AppBar shell.
|
|
||||||
//
|
|
||||||
// The body owns:
|
|
||||||
// * the top-level enable/disable toggle (mirrors the General-tab toggle —
|
|
||||||
// same JSON key, same semantics);
|
|
||||||
// * a grouped list of actions, each with its current binding plus
|
|
||||||
// edit / clear icons;
|
|
||||||
// * the JSON read/write helpers under [kShortcutLocalConfigKey] in the
|
|
||||||
// canonical {enabled, bindings:[{action,mods,key}]} shape;
|
|
||||||
// * the recording-dialog round-trip and conflict-replace bookkeeping;
|
|
||||||
// * "Reset to defaults" (called from the platform AppBar).
|
|
||||||
//
|
|
||||||
// Platform shells supply only:
|
|
||||||
// * the AppBar (with a "Reset to defaults" action that calls
|
|
||||||
// [KeyboardShortcutsPageBodyState.resetToDefaultsWithConfirm]);
|
|
||||||
// * surrounding padding / list-tile vs. dense-row visuals via the
|
|
||||||
// [compact] flag.
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import '../../../common.dart';
|
|
||||||
import '../../../consts.dart';
|
|
||||||
import '../../../models/platform_model.dart';
|
|
||||||
import '../../../models/shortcut_model.dart';
|
|
||||||
import 'display.dart';
|
|
||||||
import 'recording_dialog.dart';
|
|
||||||
import 'shortcut_actions.dart';
|
|
||||||
import 'shortcut_utils.dart';
|
|
||||||
|
|
||||||
/// The shared body widget. Render this inside a platform-styled Scaffold.
|
|
||||||
///
|
|
||||||
/// [compact] toggles the desktop dense-row layout (`true`) versus the mobile
|
|
||||||
/// touch-friendly ListTile layout (`false`).
|
|
||||||
///
|
|
||||||
/// [editButtonHint] is shown as the tooltip on the Edit icon. Mobile shells
|
|
||||||
/// use this to clarify that recording requires a physical keyboard.
|
|
||||||
///
|
|
||||||
/// [headerBanner] is an optional widget rendered above the toggle. Mobile
|
|
||||||
/// uses this to show the "Recording requires a physical keyboard" hint.
|
|
||||||
class KeyboardShortcutsPageBody extends StatefulWidget {
|
|
||||||
final bool compact;
|
|
||||||
final String? editButtonHint;
|
|
||||||
final Widget? headerBanner;
|
|
||||||
|
|
||||||
/// Whether to render the master Enable + Pass-through toggles inside the
|
|
||||||
/// body. Desktop shells set this to false because the General settings tab
|
|
||||||
/// already exposes both checkboxes (and is the only entry point to this
|
|
||||||
/// page on desktop). Mobile defaults to true: its entry point is a plain
|
|
||||||
/// nav tile in Settings, so this page is the only place the user can
|
|
||||||
/// flip the master switches.
|
|
||||||
final bool showMasterToggles;
|
|
||||||
|
|
||||||
const KeyboardShortcutsPageBody({
|
|
||||||
Key? key,
|
|
||||||
this.compact = true,
|
|
||||||
this.editButtonHint,
|
|
||||||
this.headerBanner,
|
|
||||||
this.showMasterToggles = true,
|
|
||||||
}) : super(key: key);
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<KeyboardShortcutsPageBody> createState() =>
|
|
||||||
KeyboardShortcutsPageBodyState();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Public state so platform shells can call [resetToDefaultsWithConfirm] from
|
|
||||||
/// their AppBar action.
|
|
||||||
class KeyboardShortcutsPageBodyState extends State<KeyboardShortcutsPageBody> {
|
|
||||||
// ----- Persistence helpers -----
|
|
||||||
|
|
||||||
Map<String, dynamic> _readJson() {
|
|
||||||
final raw = bind.mainGetLocalOption(key: kShortcutLocalConfigKey);
|
|
||||||
if (raw.isEmpty) return {'enabled': false, 'bindings': <dynamic>[]};
|
|
||||||
try {
|
|
||||||
final parsed = jsonDecode(raw) as Map<String, dynamic>;
|
|
||||||
parsed['bindings'] ??= <dynamic>[];
|
|
||||||
parsed['enabled'] ??= false;
|
|
||||||
return parsed;
|
|
||||||
} catch (_) {
|
|
||||||
return {'enabled': false, 'bindings': <dynamic>[]};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _writeJson(Map<String, dynamic> json) async {
|
|
||||||
await bind.mainSetLocalOption(
|
|
||||||
key: kShortcutLocalConfigKey, value: jsonEncode(json));
|
|
||||||
// Refresh the matcher cache so writes take effect immediately. On native
|
|
||||||
// this hits the Rust matcher; on Web the bridge forwards to the JS-side
|
|
||||||
// matcher in flutter/web/js/.
|
|
||||||
bind.mainReloadKeyboardShortcuts();
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replace the bindings entry for [actionId] with [binding]. If [binding]
|
|
||||||
/// is null, removes the existing entry. If the user is replacing a
|
|
||||||
/// conflicting binding, [clearActionId] points at the action whose
|
|
||||||
/// (now-stale) binding should be removed in the same write.
|
|
||||||
Future<void> _setBinding(
|
|
||||||
String actionId, {
|
|
||||||
Map<String, dynamic>? binding,
|
|
||||||
String? clearActionId,
|
|
||||||
}) async {
|
|
||||||
final json = _readJson();
|
|
||||||
final list = shortcutBindingMapsFrom(json['bindings']);
|
|
||||||
list.removeWhere((b) {
|
|
||||||
final a = b['action'];
|
|
||||||
return a == actionId || (clearActionId != null && a == clearActionId);
|
|
||||||
});
|
|
||||||
if (binding != null) {
|
|
||||||
list.add(binding);
|
|
||||||
}
|
|
||||||
json['bindings'] = list;
|
|
||||||
await _writeJson(json);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _setEnabled(bool v) async {
|
|
||||||
await ShortcutModel.setEnabled(v);
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _setPassThrough(bool v) async {
|
|
||||||
await ShortcutModel.setPassThrough(v);
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _resetToDefaults() async {
|
|
||||||
final json = _readJson();
|
|
||||||
// Single source of truth lives in `ShortcutModel.currentPlatformCapabilities`
|
|
||||||
// — the same helper feeds the first-enable seed pass, this Reset action,
|
|
||||||
// and the action-list filter below, so the three can never disagree on
|
|
||||||
// which actions belong on this platform.
|
|
||||||
json['bindings'] = filterDefaultBindingsForPlatform(
|
|
||||||
jsonDecode(bind.mainGetDefaultKeyboardShortcuts()) as List,
|
|
||||||
ShortcutModel.currentPlatformCapabilities(),
|
|
||||||
);
|
|
||||||
await _writeJson(json);
|
|
||||||
}
|
|
||||||
|
|
||||||
String _labelFor(String actionId) {
|
|
||||||
// Intentionally walks the unfiltered list (via the recursive helper, so
|
|
||||||
// both direct entries and subgroup entries are covered) — a stale
|
|
||||||
// cross-platform binding (e.g. Toggle Toolbar carried over from
|
|
||||||
// desktop) should still resolve to its human-readable label in conflict
|
|
||||||
// warnings.
|
|
||||||
for (final entry in allActionEntries(kKeyboardShortcutActionGroups)) {
|
|
||||||
if (entry.id == actionId) return translate(entry.labelKey);
|
|
||||||
}
|
|
||||||
return actionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Action groups visible on the current platform. Reads the same
|
|
||||||
/// capability set as the seed-defaults / reset-to-defaults paths from
|
|
||||||
/// `ShortcutModel.currentPlatformCapabilities`, so the UI lists exactly
|
|
||||||
/// the actions whose handlers the matcher can dispatch here.
|
|
||||||
List<KeyboardShortcutActionGroup> _groupsForCurrentPlatform() {
|
|
||||||
return filterKeyboardShortcutActionGroupsForPlatform(
|
|
||||||
ShortcutModel.currentPlatformCapabilities(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- UI handlers -----
|
|
||||||
|
|
||||||
Future<void> _onEdit(KeyboardShortcutActionEntry entry) async {
|
|
||||||
final json = _readJson();
|
|
||||||
final bindings = shortcutBindingMapsFrom(json['bindings']);
|
|
||||||
final result = await showRecordingDialog(
|
|
||||||
context: context,
|
|
||||||
actionId: entry.id,
|
|
||||||
actionLabel: translate(entry.labelKey),
|
|
||||||
existingBindings: bindings,
|
|
||||||
actionLabelLookup: _labelFor,
|
|
||||||
);
|
|
||||||
if (result == null) return;
|
|
||||||
await _setBinding(
|
|
||||||
entry.id,
|
|
||||||
binding: result.binding,
|
|
||||||
clearActionId: result.clearActionId,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _onClear(KeyboardShortcutActionEntry entry) async {
|
|
||||||
await _setBinding(entry.id, binding: null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Public — invoked from the platform AppBar action.
|
|
||||||
Future<void> resetToDefaultsWithConfirm() async {
|
|
||||||
final confirmed = await showDialog<bool>(
|
|
||||||
context: context,
|
|
||||||
builder: (ctx) => AlertDialog(
|
|
||||||
title: Text(translate('Reset to defaults')),
|
|
||||||
content: Text(translate('shortcut-reset-confirm-tip')),
|
|
||||||
actions: [
|
|
||||||
dialogButton('Cancel',
|
|
||||||
onPressed: () => Navigator.of(ctx).pop(false), isOutline: true),
|
|
||||||
dialogButton('OK', onPressed: () => Navigator.of(ctx).pop(true)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (confirmed == true) {
|
|
||||||
await _resetToDefaults();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- Build -----
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final enabled = ShortcutModel.isEnabled();
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
|
|
||||||
return ListView(
|
|
||||||
padding: const EdgeInsets.all(16),
|
|
||||||
children: [
|
|
||||||
if (widget.headerBanner != null) ...[
|
|
||||||
widget.headerBanner!,
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
],
|
|
||||||
if (widget.showMasterToggles) ...[
|
|
||||||
_toggleRow(
|
|
||||||
enabled,
|
|
||||||
'Enable keyboard shortcuts in remote session',
|
|
||||||
(v) => _setEnabled(v),
|
|
||||||
),
|
|
||||||
if (enabled)
|
|
||||||
_toggleRow(
|
|
||||||
ShortcutModel.isPassThrough(),
|
|
||||||
'Pass-through to remote',
|
|
||||||
(v) => _setPassThrough(v),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
|
||||||
child: Text(
|
|
||||||
translate('shortcut-page-description'),
|
|
||||||
style: TextStyle(color: theme.hintColor),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
// Bindings list and configuration entry only show when shortcuts are
|
|
||||||
// enabled — there is nothing to configure while the matcher is off.
|
|
||||||
if (enabled)
|
|
||||||
Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
for (final group in _groupsForCurrentPlatform())
|
|
||||||
_buildGroup(context, group),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _toggleRow(
|
|
||||||
bool value, String labelKey, Future<void> Function(bool) onChanged,
|
|
||||||
{String? tooltipKey}) {
|
|
||||||
return Row(
|
|
||||||
children: [
|
|
||||||
Checkbox(
|
|
||||||
value: value,
|
|
||||||
onChanged: (v) async {
|
|
||||||
if (v == null) return;
|
|
||||||
await onChanged(v);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
Expanded(
|
|
||||||
child: GestureDetector(
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onTap: () => onChanged(!value),
|
|
||||||
child: Text(translate(labelKey)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
if (tooltipKey != null) InfoTooltipIcon(tipKey: tooltipKey),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// One indent unit per nesting level. Both "top item under top heading"
|
|
||||||
// and "subgroup heading under top group" are *one* level deeper than the
|
|
||||||
// top heading, so they share this indent — meaning a top-level direct
|
|
||||||
// item and a sibling subgroup heading line up at exactly the same x.
|
|
||||||
// Subgroup items are *two* levels deeper.
|
|
||||||
static const double _kIndentStep = 16.0;
|
|
||||||
|
|
||||||
/// Top-level group: heading at zero indent, then walk `children` in
|
|
||||||
/// declaration order. Direct entries get [_kIndentStep] of indent so
|
|
||||||
/// they read as "items under this heading"; subgroup headings sit at
|
|
||||||
/// the same indent (a subgroup is a sibling of the direct items, just
|
|
||||||
/// with its own nested entries below).
|
|
||||||
Widget _buildGroup(BuildContext context, KeyboardShortcutActionGroup group) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
_buildHeading(context, group.titleKey, isSub: false),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
for (final child in group.children)
|
|
||||||
switch (child) {
|
|
||||||
KeyboardShortcutActionEntry() => Padding(
|
|
||||||
padding: const EdgeInsets.only(left: _kIndentStep),
|
|
||||||
child: _buildEntryRow(context, child),
|
|
||||||
),
|
|
||||||
KeyboardShortcutActionSubgroup() =>
|
|
||||||
_buildSubgroup(context, child),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildSubgroup(
|
|
||||||
BuildContext context, KeyboardShortcutActionSubgroup subgroup) {
|
|
||||||
return Column(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
const SizedBox(height: 8),
|
|
||||||
_buildHeading(context, subgroup.titleKey, isSub: true),
|
|
||||||
const SizedBox(height: 4),
|
|
||||||
for (final entry in subgroup.entries)
|
|
||||||
Padding(
|
|
||||||
// Two indent steps: one for "subgroup heading is nested under
|
|
||||||
// top heading" (matches the heading's own indent) and one for
|
|
||||||
// "this entry is under the subgroup heading".
|
|
||||||
padding: const EdgeInsets.only(left: _kIndentStep * 2),
|
|
||||||
child: _buildEntryRow(context, entry),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildHeading(BuildContext context, String titleKey,
|
|
||||||
{required bool isSub}) {
|
|
||||||
// Subgroup heading nests one step under the top heading — same indent
|
|
||||||
// as a top-level direct item, so the two line up at the same x.
|
|
||||||
final indent = isSub ? _kIndentStep : 0.0;
|
|
||||||
return Padding(
|
|
||||||
padding: EdgeInsets.only(left: 8 + indent, right: 8),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Text(
|
|
||||||
translate(titleKey),
|
|
||||||
style: TextStyle(
|
|
||||||
fontWeight: isSub ? FontWeight.w500 : FontWeight.w600,
|
|
||||||
color: isSub
|
|
||||||
? Theme.of(context).hintColor
|
|
||||||
: Theme.of(context).colorScheme.primary,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(child: Divider(thickness: isSub ? 0.5 : 1)),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _buildEntryRow(
|
|
||||||
BuildContext context, KeyboardShortcutActionEntry entry) {
|
|
||||||
return widget.compact
|
|
||||||
? _buildCompactRow(context, entry)
|
|
||||||
: _buildTouchRow(context, entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Desktop dense row: label | shortcut | edit | clear, all in one Row.
|
|
||||||
Widget _buildCompactRow(
|
|
||||||
BuildContext context, KeyboardShortcutActionEntry entry) {
|
|
||||||
final shortcut = ShortcutDisplay.formatFor(entry.id, requireEnabled: false);
|
|
||||||
final hasBinding = shortcut != null;
|
|
||||||
return Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
flex: 5,
|
|
||||||
child: Text(translate(entry.labelKey)),
|
|
||||||
),
|
|
||||||
Expanded(
|
|
||||||
flex: 4,
|
|
||||||
child: Text(
|
|
||||||
shortcut ?? '—',
|
|
||||||
style: TextStyle(
|
|
||||||
fontFamily: defaultTargetPlatform == TargetPlatform.windows
|
|
||||||
? 'Consolas'
|
|
||||||
: 'monospace',
|
|
||||||
color: hasBinding ? null : Theme.of(context).hintColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
IconButton(
|
|
||||||
tooltip: widget.editButtonHint ?? translate('Edit'),
|
|
||||||
onPressed: () => _onEdit(entry),
|
|
||||||
icon: const Icon(Icons.edit_outlined, size: 18),
|
|
||||||
),
|
|
||||||
SizedBox(
|
|
||||||
width: 40,
|
|
||||||
child: hasBinding
|
|
||||||
? IconButton(
|
|
||||||
tooltip: translate('Clear'),
|
|
||||||
onPressed: () => _onClear(entry),
|
|
||||||
icon: const Icon(Icons.close, size: 18),
|
|
||||||
)
|
|
||||||
: const SizedBox.shrink(),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Mobile touch row: ListTile with title + subtitle + trailing icons.
|
|
||||||
Widget _buildTouchRow(
|
|
||||||
BuildContext context, KeyboardShortcutActionEntry entry) {
|
|
||||||
final shortcut = ShortcutDisplay.formatFor(entry.id, requireEnabled: false);
|
|
||||||
final hasBinding = shortcut != null;
|
|
||||||
return ListTile(
|
|
||||||
dense: false,
|
|
||||||
contentPadding: const EdgeInsets.symmetric(horizontal: 8),
|
|
||||||
title: Text(translate(entry.labelKey)),
|
|
||||||
subtitle: Text(
|
|
||||||
shortcut ?? '—',
|
|
||||||
style: TextStyle(
|
|
||||||
fontFamily: defaultTargetPlatform == TargetPlatform.windows
|
|
||||||
? 'Consolas'
|
|
||||||
: 'monospace',
|
|
||||||
color: hasBinding ? null : Theme.of(context).hintColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
trailing: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
IconButton(
|
|
||||||
tooltip: widget.editButtonHint ?? translate('Edit'),
|
|
||||||
onPressed: () => _onEdit(entry),
|
|
||||||
icon: const Icon(Icons.edit_outlined),
|
|
||||||
),
|
|
||||||
if (hasBinding)
|
|
||||||
IconButton(
|
|
||||||
tooltip: translate('Clear'),
|
|
||||||
onPressed: () => _onClear(entry),
|
|
||||||
icon: const Icon(Icons.close),
|
|
||||||
)
|
|
||||||
else
|
|
||||||
const SizedBox(width: 48),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Small help-icon tooltip used for inline explanations next to a checkbox /
|
|
||||||
/// row. Triggers on hover (desktop) and tap (mobile). Public so the desktop
|
|
||||||
/// General settings tab can reuse it.
|
|
||||||
class InfoTooltipIcon extends StatelessWidget {
|
|
||||||
final String tipKey;
|
|
||||||
const InfoTooltipIcon({Key? key, required this.tipKey}) : super(key: key);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return Tooltip(
|
|
||||||
message: translate(tipKey),
|
|
||||||
triggerMode: TooltipTriggerMode.tap,
|
|
||||||
preferBelow: false,
|
|
||||||
waitDuration: const Duration(milliseconds: 250),
|
|
||||||
showDuration: const Duration(seconds: 6),
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
|
||||||
child: Icon(
|
|
||||||
Icons.help_outline,
|
|
||||||
size: 16,
|
|
||||||
color: Theme.of(context).hintColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,418 +0,0 @@
|
|||||||
// flutter/lib/common/widgets/keyboard_shortcuts/recording_dialog.dart
|
|
||||||
//
|
|
||||||
// Modal dialog used by the Keyboard Shortcuts settings page to capture a new
|
|
||||||
// key combination for a given action. The dialog listens for KeyDown events,
|
|
||||||
// extracts the modifier set + non-modifier key, validates that at least one
|
|
||||||
// modifier is present, and reports any conflict with another already-bound
|
|
||||||
// action.
|
|
||||||
//
|
|
||||||
// On Save, returns the new binding map ({action, mods, key}) plus the
|
|
||||||
// optional id of the action whose binding should be cleared (the conflict
|
|
||||||
// "Replace" path). On Cancel, returns null.
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
|
|
||||||
import '../../../common.dart';
|
|
||||||
import 'shortcut_utils.dart';
|
|
||||||
|
|
||||||
/// Result of the recording dialog.
|
|
||||||
class RecordingResult {
|
|
||||||
/// The new binding map to write: {action, mods, key}.
|
|
||||||
final Map<String, dynamic> binding;
|
|
||||||
|
|
||||||
/// If the chosen combo conflicted with another action, the user chose
|
|
||||||
/// "Replace" — the caller must clear this action's binding before writing
|
|
||||||
/// the new one.
|
|
||||||
final String? clearActionId;
|
|
||||||
|
|
||||||
RecordingResult(this.binding, this.clearActionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Show the recording dialog.
|
|
||||||
///
|
|
||||||
/// [actionId] is the action being edited (used for the title and to detect
|
|
||||||
/// "binding to itself" — that's not a conflict).
|
|
||||||
/// [actionLabel] is the translated, user-facing action name.
|
|
||||||
/// [existingBindings] is the current bindings list (used for conflict detection).
|
|
||||||
/// [actionLabelLookup] resolves an actionId to its translated label, used in
|
|
||||||
/// the conflict warning.
|
|
||||||
Future<RecordingResult?> showRecordingDialog({
|
|
||||||
required BuildContext context,
|
|
||||||
required String actionId,
|
|
||||||
required String actionLabel,
|
|
||||||
required List<Map<String, dynamic>> existingBindings,
|
|
||||||
required String Function(String) actionLabelLookup,
|
|
||||||
}) {
|
|
||||||
return showDialog<RecordingResult>(
|
|
||||||
context: context,
|
|
||||||
barrierDismissible: false,
|
|
||||||
builder: (ctx) => _RecordingDialog(
|
|
||||||
actionId: actionId,
|
|
||||||
actionLabel: actionLabel,
|
|
||||||
existingBindings: existingBindings,
|
|
||||||
actionLabelLookup: actionLabelLookup,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
class _RecordingDialog extends StatefulWidget {
|
|
||||||
final String actionId;
|
|
||||||
final String actionLabel;
|
|
||||||
final List<Map<String, dynamic>> existingBindings;
|
|
||||||
final String Function(String) actionLabelLookup;
|
|
||||||
|
|
||||||
const _RecordingDialog({
|
|
||||||
required this.actionId,
|
|
||||||
required this.actionLabel,
|
|
||||||
required this.existingBindings,
|
|
||||||
required this.actionLabelLookup,
|
|
||||||
});
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<_RecordingDialog> createState() => _RecordingDialogState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _RecordingDialogState extends State<_RecordingDialog> {
|
|
||||||
final FocusNode _focusNode = FocusNode();
|
|
||||||
|
|
||||||
// Captured combo. null until the user presses something with a non-modifier.
|
|
||||||
Set<String> _mods = {};
|
|
||||||
String? _key;
|
|
||||||
|
|
||||||
// Human-readable label for the most recent press that we couldn't bind to
|
|
||||||
// (e.g. F13, media keys). null when the last press was either supported or
|
|
||||||
// a modifier-only press. Cleared whenever a supported key arrives, so a
|
|
||||||
// user who hits an unsupported key after a valid capture sees the warning
|
|
||||||
// until they press something else. Distinct from `_key == null` so the
|
|
||||||
// status line can tell the user *why* their press was ignored instead of
|
|
||||||
// silently doing nothing.
|
|
||||||
String? _unsupportedKey;
|
|
||||||
|
|
||||||
// Modifier LogicalKeyboardKeys we should *not* treat as "unsupported" when
|
|
||||||
// they fail to map to a key name. A modifier-only press is normal during
|
|
||||||
// combo capture (the user is building up their combo) — only non-modifier
|
|
||||||
// unmapped keys deserve the warning.
|
|
||||||
static final _modifierKeys = <LogicalKeyboardKey>{
|
|
||||||
LogicalKeyboardKey.shift,
|
|
||||||
LogicalKeyboardKey.shiftLeft,
|
|
||||||
LogicalKeyboardKey.shiftRight,
|
|
||||||
LogicalKeyboardKey.control,
|
|
||||||
LogicalKeyboardKey.controlLeft,
|
|
||||||
LogicalKeyboardKey.controlRight,
|
|
||||||
LogicalKeyboardKey.alt,
|
|
||||||
LogicalKeyboardKey.altLeft,
|
|
||||||
LogicalKeyboardKey.altRight,
|
|
||||||
LogicalKeyboardKey.meta,
|
|
||||||
LogicalKeyboardKey.metaLeft,
|
|
||||||
LogicalKeyboardKey.metaRight,
|
|
||||||
LogicalKeyboardKey.capsLock,
|
|
||||||
LogicalKeyboardKey.numLock,
|
|
||||||
LogicalKeyboardKey.scrollLock,
|
|
||||||
LogicalKeyboardKey.fn,
|
|
||||||
LogicalKeyboardKey.fnLock,
|
|
||||||
};
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
_focusNode.requestFocus();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void dispose() {
|
|
||||||
_focusNode.dispose();
|
|
||||||
super.dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool get _isMac =>
|
|
||||||
defaultTargetPlatform == TargetPlatform.macOS ||
|
|
||||||
defaultTargetPlatform == TargetPlatform.iOS;
|
|
||||||
|
|
||||||
/// True when the captured combo includes at least one modifier. Lower bound
|
|
||||||
/// for any sensible binding — pure single-key bindings would swallow normal
|
|
||||||
/// typing the moment shortcuts are enabled. Beyond one mod the user is on
|
|
||||||
/// their own; the in-session pass-through toggle is the escape hatch when
|
|
||||||
/// a chosen combo collides with something needed on the remote.
|
|
||||||
bool get _hasRequiredPrefix => _mods.isNotEmpty;
|
|
||||||
|
|
||||||
/// Return the actionId that this combo currently conflicts with, or null.
|
|
||||||
/// The action being edited is not a conflict with itself.
|
|
||||||
String? get _conflictActionId {
|
|
||||||
if (_key == null || !_hasRequiredPrefix) return null;
|
|
||||||
for (final b in widget.existingBindings) {
|
|
||||||
final otherAction = b['action'] as String?;
|
|
||||||
if (otherAction == null || otherAction == widget.actionId) continue;
|
|
||||||
final otherKey = b['key'] as String?;
|
|
||||||
final otherMods = shortcutModSetFrom(b['mods']);
|
|
||||||
if (otherKey == _key &&
|
|
||||||
otherMods.length == _mods.length &&
|
|
||||||
otherMods.containsAll(_mods)) {
|
|
||||||
return otherAction;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {
|
|
||||||
if (event is KeyDownEvent &&
|
|
||||||
event.logicalKey == LogicalKeyboardKey.escape) {
|
|
||||||
Navigator.of(context).pop();
|
|
||||||
return KeyEventResult.handled;
|
|
||||||
}
|
|
||||||
if (event is! KeyDownEvent) return KeyEventResult.handled;
|
|
||||||
|
|
||||||
final logical = event.logicalKey;
|
|
||||||
final keyName = shortcutKeyNameForEvent(event);
|
|
||||||
|
|
||||||
// Mirror of `normalize_modifiers` in src/keyboard/shortcuts.rs:
|
|
||||||
// * macOS: Cmd → primary, Ctrl → ctrl (distinct).
|
|
||||||
// * Win/Linux: Ctrl → primary, no separate Ctrl modifier.
|
|
||||||
// The two halves must agree on labels, otherwise saved bindings will not
|
|
||||||
// match the events the matcher sees at runtime.
|
|
||||||
final mods = <String>{};
|
|
||||||
if (HardwareKeyboard.instance.isAltPressed) mods.add('alt');
|
|
||||||
if (HardwareKeyboard.instance.isShiftPressed) mods.add('shift');
|
|
||||||
if (_isMac) {
|
|
||||||
if (HardwareKeyboard.instance.isMetaPressed) mods.add('primary');
|
|
||||||
if (HardwareKeyboard.instance.isControlPressed) mods.add('ctrl');
|
|
||||||
} else {
|
|
||||||
if (HardwareKeyboard.instance.isControlPressed) mods.add('primary');
|
|
||||||
}
|
|
||||||
|
|
||||||
setState(() {
|
|
||||||
_mods = mods;
|
|
||||||
if (!_isMac &&
|
|
||||||
HardwareKeyboard.instance.logicalKeysPressed
|
|
||||||
.contains(LogicalKeyboardKey.altGraph)) {
|
|
||||||
_key = null;
|
|
||||||
_unsupportedKey = LogicalKeyboardKey.altGraph.keyLabel;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Match runtime dispatch: modifiers added after a held letter do not
|
|
||||||
// produce a new shortcut key-down event.
|
|
||||||
_key = keyName;
|
|
||||||
_unsupportedKey = null;
|
|
||||||
if (keyName == null && !_modifierKeys.contains(logical)) {
|
|
||||||
// Non-modifier key we don't recognize (e.g. F13, media keys, IME
|
|
||||||
// compose keys). Surface a warning instead of silently dropping the
|
|
||||||
// press — the dialog otherwise looks unresponsive.
|
|
||||||
final label = logical.keyLabel.isNotEmpty
|
|
||||||
? logical.keyLabel
|
|
||||||
: (logical.debugName ?? 'this key');
|
|
||||||
_unsupportedKey = label;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return KeyEventResult.handled;
|
|
||||||
}
|
|
||||||
|
|
||||||
KeyEventResult _onRawKeyEvent(FocusNode node, RawKeyEvent event) {
|
|
||||||
final data = event.data;
|
|
||||||
const gtkMod5Mask = 1 << 7;
|
|
||||||
// GTK can expose AltGr only through Mod5, without a logical AltGraph key.
|
|
||||||
if (event is RawKeyDownEvent &&
|
|
||||||
data is RawKeyEventDataLinux &&
|
|
||||||
data.keyHelper is GtkKeyHelper &&
|
|
||||||
(data.modifiers & gtkMod5Mask) != 0) {
|
|
||||||
setState(() {
|
|
||||||
_key = null;
|
|
||||||
_unsupportedKey = LogicalKeyboardKey.altGraph.keyLabel;
|
|
||||||
});
|
|
||||||
return KeyEventResult.handled;
|
|
||||||
}
|
|
||||||
return KeyEventResult.ignored;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _onSave() {
|
|
||||||
if (_key == null || !_hasRequiredPrefix) return;
|
|
||||||
final ordered = canonicalShortcutModsForSave(_mods);
|
|
||||||
final binding = <String, dynamic>{
|
|
||||||
'action': widget.actionId,
|
|
||||||
'mods': ordered,
|
|
||||||
'key': _key!,
|
|
||||||
};
|
|
||||||
Navigator.of(context).pop(RecordingResult(binding, _conflictActionId));
|
|
||||||
}
|
|
||||||
|
|
||||||
String _formatPrefix() {
|
|
||||||
// Used in the "must include..." validation row; lists the modifier set
|
|
||||||
// a binding can pick from. Localised modifier glyphs aren't used here so
|
|
||||||
// the names stay greppable for users searching for "Option" / "Cmd".
|
|
||||||
if (_isMac) return 'Cmd / Control / Option / Shift';
|
|
||||||
return 'Ctrl / Alt / Shift';
|
|
||||||
}
|
|
||||||
|
|
||||||
String _formatCombo() {
|
|
||||||
// Plain-text labels (see same rationale in display.dart::_keyDisplay).
|
|
||||||
final parts = <String>[];
|
|
||||||
for (final m in ['primary', 'ctrl', 'alt', 'shift']) {
|
|
||||||
if (!_mods.contains(m)) continue;
|
|
||||||
switch (m) {
|
|
||||||
case 'primary':
|
|
||||||
parts.add(_isMac ? 'Cmd' : 'Ctrl');
|
|
||||||
break;
|
|
||||||
case 'ctrl':
|
|
||||||
parts.add(_isMac ? 'Control' : 'Ctrl');
|
|
||||||
break;
|
|
||||||
case 'alt':
|
|
||||||
parts.add(_isMac ? 'Option' : 'Alt');
|
|
||||||
break;
|
|
||||||
case 'shift':
|
|
||||||
parts.add('Shift');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (_key != null) {
|
|
||||||
parts.add(_keyDisplay(_key!));
|
|
||||||
}
|
|
||||||
if (parts.isEmpty) return translate('shortcut-recording-press-keys-tip');
|
|
||||||
return parts.join('+');
|
|
||||||
}
|
|
||||||
|
|
||||||
String _keyDisplay(String key) {
|
|
||||||
switch (key) {
|
|
||||||
case 'delete': return 'Del';
|
|
||||||
case 'backspace': return 'Backspace';
|
|
||||||
case 'enter': return 'Enter';
|
|
||||||
case 'tab': return 'Tab';
|
|
||||||
case 'space': return 'Space';
|
|
||||||
case 'arrow_left': return 'Left';
|
|
||||||
case 'arrow_right':return 'Right';
|
|
||||||
case 'arrow_up': return 'Up';
|
|
||||||
case 'arrow_down': return 'Down';
|
|
||||||
case 'home': return 'Home';
|
|
||||||
case 'end': return 'End';
|
|
||||||
case 'page_up': return 'PgUp';
|
|
||||||
case 'page_down': return 'PgDn';
|
|
||||||
case 'insert': return 'Ins';
|
|
||||||
}
|
|
||||||
if (key.startsWith('digit')) return key.substring(5);
|
|
||||||
return key.toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final hasKey = _key != null;
|
|
||||||
final conflictId = _conflictActionId;
|
|
||||||
final hasConflict = conflictId != null;
|
|
||||||
final canSave = hasKey && _hasRequiredPrefix;
|
|
||||||
|
|
||||||
Widget statusLine;
|
|
||||||
if (_unsupportedKey != null) {
|
|
||||||
// Most recent press was unsupported. Take precedence over the
|
|
||||||
// captured-combo states so the user gets explicit feedback that their
|
|
||||||
// last keystroke was ignored, regardless of whether a previous combo
|
|
||||||
// is still captured.
|
|
||||||
statusLine = Row(
|
|
||||||
children: [
|
|
||||||
const Icon(Icons.close, size: 16, color: Colors.red),
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Flexible(
|
|
||||||
child: Text(
|
|
||||||
translate('shortcut-key-not-supported')
|
|
||||||
.replaceAll('{}', _unsupportedKey!),
|
|
||||||
style: const TextStyle(color: Colors.red),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
} else if (!hasKey) {
|
|
||||||
statusLine = Text(
|
|
||||||
translate('shortcut-recording-press-keys-tip'),
|
|
||||||
style: TextStyle(color: Theme.of(context).hintColor),
|
|
||||||
);
|
|
||||||
} else if (!_hasRequiredPrefix) {
|
|
||||||
statusLine = Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.close, size: 16, color: Colors.red),
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Flexible(
|
|
||||||
child: Text(
|
|
||||||
translate('shortcut-must-include-modifiers')
|
|
||||||
.replaceAll('{}', _formatPrefix()),
|
|
||||||
style: const TextStyle(color: Colors.red),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
} else if (hasConflict) {
|
|
||||||
final otherLabel = widget.actionLabelLookup(conflictId);
|
|
||||||
statusLine = Row(
|
|
||||||
children: [
|
|
||||||
Icon(Icons.warning_amber_outlined,
|
|
||||||
size: 16, color: Colors.orange.shade700),
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Flexible(
|
|
||||||
child: Text(
|
|
||||||
'${translate('shortcut-already-bound-to')} "$otherLabel"',
|
|
||||||
style: TextStyle(color: Colors.orange.shade700),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
statusLine = Row(
|
|
||||||
children: [
|
|
||||||
const Icon(Icons.check, size: 16, color: Colors.green),
|
|
||||||
const SizedBox(width: 6),
|
|
||||||
Text(translate('Valid'), style: const TextStyle(color: Colors.green)),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
final saveLabel = hasConflict ? 'Replace' : 'Save';
|
|
||||||
|
|
||||||
return AlertDialog(
|
|
||||||
title: Text(
|
|
||||||
'${translate('Set shortcut')}: ${widget.actionLabel}',
|
|
||||||
),
|
|
||||||
content: Focus(
|
|
||||||
focusNode: _focusNode,
|
|
||||||
autofocus: true,
|
|
||||||
onKeyEvent: _onKeyEvent,
|
|
||||||
onKey: _onRawKeyEvent,
|
|
||||||
child: ConstrainedBox(
|
|
||||||
constraints: const BoxConstraints(minWidth: 380),
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Text(translate('shortcut-recording-instruction')),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
Container(
|
|
||||||
width: double.infinity,
|
|
||||||
padding:
|
|
||||||
const EdgeInsets.symmetric(vertical: 18, horizontal: 12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
border: Border.all(color: Theme.of(context).dividerColor),
|
|
||||||
borderRadius: BorderRadius.circular(4),
|
|
||||||
),
|
|
||||||
child: Text(
|
|
||||||
_formatCombo(),
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 18,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: hasKey
|
|
||||||
? Theme.of(context).textTheme.titleLarge?.color
|
|
||||||
: Theme.of(context).hintColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(height: 12),
|
|
||||||
statusLine,
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
dialogButton('Cancel',
|
|
||||||
onPressed: () => Navigator.of(context).pop(), isOutline: true),
|
|
||||||
dialogButton(saveLabel, onPressed: canSave ? _onSave : null),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,287 +0,0 @@
|
|||||||
import 'shortcut_constants.dart';
|
|
||||||
import 'shortcut_utils.dart';
|
|
||||||
|
|
||||||
/// Marker for the union of [KeyboardShortcutActionEntry] /
|
|
||||||
/// [KeyboardShortcutActionSubgroup] — anything a top-level
|
|
||||||
/// [KeyboardShortcutActionGroup] can directly contain. Sealed so renderers
|
|
||||||
/// and filters can `switch` on it without a default branch.
|
|
||||||
sealed class KeyboardShortcutActionGroupChild {
|
|
||||||
const KeyboardShortcutActionGroupChild();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One configurable action — id + i18n key for its label.
|
|
||||||
class KeyboardShortcutActionEntry extends KeyboardShortcutActionGroupChild {
|
|
||||||
final String id;
|
|
||||||
final String labelKey;
|
|
||||||
const KeyboardShortcutActionEntry(this.id, this.labelKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A nested subgroup (e.g. "View Mode" under "Display"). Renders with extra
|
|
||||||
/// indent so its items are visually distinguished from the parent group's
|
|
||||||
/// direct items.
|
|
||||||
class KeyboardShortcutActionSubgroup extends KeyboardShortcutActionGroupChild {
|
|
||||||
final String titleKey;
|
|
||||||
final List<KeyboardShortcutActionEntry> entries;
|
|
||||||
const KeyboardShortcutActionSubgroup(this.titleKey, this.entries);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A top-level group ("Display", "Keyboard", "Chat", …). `children` is an
|
|
||||||
/// *ordered* mix of direct entries and subgroups, so layouts like
|
|
||||||
/// "subgroups first → direct items → trailing subgroup" — exactly the
|
|
||||||
/// shape `_DisplayMenu` uses (Privacy mode lives after the cursor / display
|
|
||||||
/// toggles direct items) — are first-class instead of needing a wrapper
|
|
||||||
/// "Display Settings" subgroup just to insert the items.
|
|
||||||
class KeyboardShortcutActionGroup {
|
|
||||||
final String titleKey;
|
|
||||||
final List<KeyboardShortcutActionGroupChild> children;
|
|
||||||
const KeyboardShortcutActionGroup(this.titleKey, this.children);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Canonical action group definitions used by both the desktop and mobile
|
|
||||||
/// configuration pages. The order of groups, subgroups, and entries here
|
|
||||||
/// is the order the user sees in the UI, and mirrors the corresponding
|
|
||||||
/// toolbar submenu (`_DisplayMenu` / `_KeyboardMenu` in
|
|
||||||
/// `desktop/widgets/remote_toolbar.dart`) child order — modulo entries
|
|
||||||
/// without shortcut counterparts (e.g. `_screenAdjustor.adjustWindow`,
|
|
||||||
/// `scrollStyle`, `_ResolutionsMenu`, `localKeyboardType`).
|
|
||||||
final List<KeyboardShortcutActionGroup> kKeyboardShortcutActionGroups = [
|
|
||||||
KeyboardShortcutActionGroup('Monitor', [
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSwitchDisplayNext, 'Switch to next display'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSwitchDisplayPrev, 'Switch to previous display'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSwitchDisplayAll, 'All monitors'),
|
|
||||||
]),
|
|
||||||
KeyboardShortcutActionGroup('Control Actions', [
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSendClipboardKeystrokes, 'Send clipboard keystrokes'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionResetCanvas, 'Reset canvas'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSendCtrlAltDel, 'Insert Ctrl + Alt + Del'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionRestartRemote, 'Restart remote device'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionInsertLock, 'Insert Lock'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleBlockInput, 'Block user input'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionSwitchSides, 'Switch Sides'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionRefresh, 'Refresh'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleRecording, 'Toggle session recording'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionScreenshot, 'Take screenshot'),
|
|
||||||
]),
|
|
||||||
// Display: subgroups (View Mode → Image Quality → Codec → Virtual display)
|
|
||||||
// first, then the direct items (cursor toggles + display toggles), then
|
|
||||||
// Privacy mode subgroup last — matching `_DisplayMenu.menuChildrenGetter`
|
|
||||||
// exactly. Rebalancing this order should also rebalance the toolbar.
|
|
||||||
KeyboardShortcutActionGroup('Display', [
|
|
||||||
KeyboardShortcutActionSubgroup('View Mode', [
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionViewModeOriginal, 'Scale original'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionViewModeAdaptive, 'Scale adaptive'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionViewModeCustom, 'Scale custom'),
|
|
||||||
]),
|
|
||||||
KeyboardShortcutActionSubgroup('Image Quality', [
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionImageQualityBest, 'Good image quality'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionImageQualityBalanced, 'Balanced'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionImageQualityLow, 'Optimize reaction time'),
|
|
||||||
]),
|
|
||||||
KeyboardShortcutActionSubgroup('Codec', [
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCodecAuto, 'Auto'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCodecVp8, 'VP8'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCodecVp9, 'VP9'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCodecAv1, 'AV1'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCodecH264, 'H264'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCodecH265, 'H265'),
|
|
||||||
]),
|
|
||||||
KeyboardShortcutActionSubgroup('Virtual display', [
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionPlugOutAllVirtualDisplays, 'Plug out all'),
|
|
||||||
]),
|
|
||||||
// Direct items: cursorToggles + display toggles, in toolbar order.
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleShowRemoteCursor, 'Show remote cursor'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleFollowRemoteCursor, 'Follow remote cursor'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleFollowRemoteWindow, 'Follow remote window focus'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleZoomCursor, 'Zoom cursor'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleQualityMonitor, 'Show quality monitor'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionToggleMute, 'Mute'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleEnableFileCopyPaste, 'Enable file copy and paste'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleDisableClipboard, 'Disable clipboard'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleLockAfterSessionEnd, 'Lock after session end'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleTrueColor, 'True color (4:4:4)'),
|
|
||||||
// Privacy mode at the bottom — mirrors `_DisplayMenu` where it's the
|
|
||||||
// last submenu added (line ~1023 of remote_toolbar.dart, after toggles).
|
|
||||||
KeyboardShortcutActionSubgroup('Privacy mode', [
|
|
||||||
// Reuse toolbar's existing impl-name i18n keys. The handler at
|
|
||||||
// runtime matches `privacy_mode_impl_mag_tip` /
|
|
||||||
// `privacy_mode_impl_virtual_display_tip` against the peer's
|
|
||||||
// advertised impls — same logic the toolbar's `toolbarPrivacyMode`
|
|
||||||
// submenu uses.
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionPrivacyMode1, 'privacy_mode_impl_mag_tip'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionPrivacyMode2, 'privacy_mode_impl_virtual_display_tip'),
|
|
||||||
]),
|
|
||||||
]),
|
|
||||||
// Keyboard: Keyboard mode subgroup first, then direct items
|
|
||||||
// (inputSource → viewMode → showMyCursor → toolbarKeyboardToggles),
|
|
||||||
// matching `_KeyboardMenu.menuChildrenGetter`.
|
|
||||||
KeyboardShortcutActionGroup('Keyboard', [
|
|
||||||
KeyboardShortcutActionSubgroup('Keyboard mode', [
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionKeyboardModeLegacy, 'Legacy mode'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionKeyboardModeMap, 'Map mode'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionKeyboardModeTranslate, 'Translate mode'),
|
|
||||||
]),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionToggleViewOnly, 'View Mode'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleShowMyCursor, 'Show my cursor'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleSwapCtrlCmd, 'Swap control-command key'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleRelativeMouseMode, 'Relative mouse mode'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleReverseMouseWheel, 'Reverse mouse wheel'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleSwapLeftRightMouse, 'swap-left-right-mouse'),
|
|
||||||
]),
|
|
||||||
KeyboardShortcutActionGroup('Chat', [
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionToggleChat, 'Text chat'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionToggleVoiceCall, 'Voice call'),
|
|
||||||
]),
|
|
||||||
// "Other" collects single-icon toolbar buttons that have no dropdown
|
|
||||||
// (Pin, Close), plus actions with no toolbar entry at all (Fullscreen —
|
|
||||||
// driven by callback, not menu; Toggle Toolbar / tab navigation — tab
|
|
||||||
// right-click menu, not toolbar). Combined into one group rather than
|
|
||||||
// several 1-item groups for cleaner visual hierarchy.
|
|
||||||
KeyboardShortcutActionGroup('Other', [
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionPinToolbar, 'Pin Toolbar'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionToggleFullscreen, 'Toggle fullscreen'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionToggleToolbar, 'Toggle toolbar'),
|
|
||||||
KeyboardShortcutActionEntry(kShortcutActionCloseTab, 'Close tab'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSwitchTabNext, 'Switch to next tab'),
|
|
||||||
KeyboardShortcutActionEntry(
|
|
||||||
kShortcutActionSwitchTabPrev, 'Switch to previous tab'),
|
|
||||||
]),
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Walk the (filtered or unfiltered) group tree and yield every
|
|
||||||
/// [KeyboardShortcutActionEntry], regardless of whether it sits as a direct
|
|
||||||
/// child of a top-level group or inside a subgroup. Useful for label
|
|
||||||
/// lookups, ghost-action tests, and any consumer that just wants the flat
|
|
||||||
/// list of action ids.
|
|
||||||
Iterable<KeyboardShortcutActionEntry> allActionEntries(
|
|
||||||
Iterable<KeyboardShortcutActionGroup> groups,
|
|
||||||
) sync* {
|
|
||||||
for (final group in groups) {
|
|
||||||
for (final child in group.children) {
|
|
||||||
switch (child) {
|
|
||||||
case KeyboardShortcutActionEntry():
|
|
||||||
yield child;
|
|
||||||
case KeyboardShortcutActionSubgroup():
|
|
||||||
yield* child.entries;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Return [kKeyboardShortcutActionGroups] with actions that aren't supported
|
|
||||||
/// on the current platform stripped out. Subgroups whose every entry was
|
|
||||||
/// filtered are dropped; top-level groups whose every child (direct entry
|
|
||||||
/// or subgroup) was dropped are themselves dropped.
|
|
||||||
///
|
|
||||||
/// Mirrors the capability flags used by [filterDefaultBindingsForPlatform]
|
|
||||||
/// so the configuration UI shows only what the matcher can actually
|
|
||||||
/// dispatch on this platform.
|
|
||||||
///
|
|
||||||
/// Note: callers should still walk the unfiltered
|
|
||||||
/// [kKeyboardShortcutActionGroups] for label lookups (e.g. conflict
|
|
||||||
/// warnings about a stale cross-platform binding), so an action bound on
|
|
||||||
/// desktop and carried over to mobile still has a human-readable name in
|
|
||||||
/// dialogs.
|
|
||||||
List<KeyboardShortcutActionGroup> filterKeyboardShortcutActionGroupsForPlatform(
|
|
||||||
ShortcutPlatformCapabilities cap,
|
|
||||||
) {
|
|
||||||
bool allowed(String id) {
|
|
||||||
if (cap.excludedActions.contains(id)) return false;
|
|
||||||
if (!cap.includeFullscreenShortcut &&
|
|
||||||
id == kShortcutActionToggleFullscreen) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeScreenshotShortcut && id == kShortcutActionScreenshot) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeRelativeMouseModeShortcut &&
|
|
||||||
id == kShortcutActionToggleRelativeMouseMode) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeTabShortcuts && isSwitchTabShortcutAction(id)) return false;
|
|
||||||
if (!cap.includeToolbarShortcut && id == kShortcutActionToggleToolbar) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeCloseTabShortcut && id == kShortcutActionCloseTab) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeSwitchSidesShortcut && id == kShortcutActionSwitchSides) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeRecordingShortcut && id == kShortcutActionToggleRecording) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeResetCanvasShortcut && id == kShortcutActionResetCanvas) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includePinToolbarShortcut && id == kShortcutActionPinToolbar) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeViewModeShortcut &&
|
|
||||||
(id == kShortcutActionViewModeOriginal ||
|
|
||||||
id == kShortcutActionViewModeAdaptive ||
|
|
||||||
id == kShortcutActionViewModeCustom)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!cap.includeVoiceCallShortcut && id == kShortcutActionToggleVoiceCall) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
final out = <KeyboardShortcutActionGroup>[];
|
|
||||||
for (final group in kKeyboardShortcutActionGroups) {
|
|
||||||
final filteredChildren = <KeyboardShortcutActionGroupChild>[];
|
|
||||||
for (final child in group.children) {
|
|
||||||
switch (child) {
|
|
||||||
case KeyboardShortcutActionEntry():
|
|
||||||
if (allowed(child.id)) filteredChildren.add(child);
|
|
||||||
case KeyboardShortcutActionSubgroup():
|
|
||||||
final entries =
|
|
||||||
child.entries.where((e) => allowed(e.id)).toList();
|
|
||||||
if (entries.isNotEmpty) {
|
|
||||||
filteredChildren.add(
|
|
||||||
KeyboardShortcutActionSubgroup(child.titleKey, entries));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (filteredChildren.isNotEmpty) {
|
|
||||||
out.add(KeyboardShortcutActionGroup(group.titleKey, filteredChildren));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
/// Keyboard shortcut action IDs - must match
|
|
||||||
/// src/keyboard/shortcuts.rs::action_id.
|
|
||||||
const kShortcutActionSendCtrlAltDel = 'send_ctrl_alt_del';
|
|
||||||
const kShortcutActionToggleFullscreen = 'toggle_fullscreen';
|
|
||||||
const kShortcutActionSwitchDisplayNext = 'switch_display_next';
|
|
||||||
const kShortcutActionSwitchDisplayPrev = 'switch_display_prev';
|
|
||||||
const kShortcutActionSwitchDisplayAll = 'switch_display_all';
|
|
||||||
const kShortcutActionScreenshot = 'screenshot';
|
|
||||||
const kShortcutActionInsertLock = 'insert_lock';
|
|
||||||
const kShortcutActionRefresh = 'refresh';
|
|
||||||
const kShortcutActionToggleBlockInput = 'toggle_block_input';
|
|
||||||
const kShortcutActionToggleRecording = 'toggle_recording';
|
|
||||||
const kShortcutActionSwitchSides = 'switch_sides';
|
|
||||||
const kShortcutActionCloseTab = 'close_tab';
|
|
||||||
const kShortcutActionToggleToolbar = 'toggle_toolbar';
|
|
||||||
const kShortcutActionRestartRemote = 'restart_remote';
|
|
||||||
const kShortcutActionResetCanvas = 'reset_canvas';
|
|
||||||
const kShortcutActionSwitchTabNext = 'switch_tab_next';
|
|
||||||
const kShortcutActionSwitchTabPrev = 'switch_tab_prev';
|
|
||||||
|
|
||||||
/// Actions that move keyboard focus to another session or a dialog. They run when the
|
|
||||||
/// key that fired them is released, not when it is pressed, so the matcher
|
|
||||||
/// that consumed the press also sees its repeats and its release. On Linux a
|
|
||||||
/// legacy-mode session matches in Dart while a map-mode session matches in
|
|
||||||
/// Rust, and neither knows the other's fired keys. Mirrors `runs_on_release`
|
|
||||||
/// in `src/keyboard/shortcuts.rs`; both are checked against
|
|
||||||
/// `flutter/test/fixtures/key_up_shortcut_actions.json`.
|
|
||||||
const kShortcutActionsRunOnKeyUp = {
|
|
||||||
kShortcutActionCloseTab,
|
|
||||||
kShortcutActionSwitchTabNext,
|
|
||||||
kShortcutActionSwitchTabPrev,
|
|
||||||
kShortcutActionRestartRemote,
|
|
||||||
kShortcutActionSwitchSides,
|
|
||||||
kShortcutActionToggleChat,
|
|
||||||
};
|
|
||||||
const kShortcutActionToggleMute = 'toggle_mute';
|
|
||||||
const kShortcutActionPinToolbar = 'pin_toolbar';
|
|
||||||
const kShortcutActionViewModeOriginal = 'view_mode_original';
|
|
||||||
const kShortcutActionViewModeAdaptive = 'view_mode_adaptive';
|
|
||||||
const kShortcutActionToggleChat = 'toggle_chat';
|
|
||||||
const kShortcutActionToggleQualityMonitor = 'toggle_quality_monitor';
|
|
||||||
const kShortcutActionToggleShowRemoteCursor = 'toggle_show_remote_cursor';
|
|
||||||
const kShortcutActionToggleShowMyCursor = 'toggle_show_my_cursor';
|
|
||||||
const kShortcutActionToggleDisableClipboard = 'toggle_disable_clipboard';
|
|
||||||
const kShortcutActionPrivacyMode1 = 'privacy_mode_1';
|
|
||||||
const kShortcutActionPrivacyMode2 = 'privacy_mode_2';
|
|
||||||
// Keyboard mode (Map / Translate / Legacy).
|
|
||||||
const kShortcutActionKeyboardModeMap = 'keyboard_mode_map';
|
|
||||||
const kShortcutActionKeyboardModeTranslate = 'keyboard_mode_translate';
|
|
||||||
const kShortcutActionKeyboardModeLegacy = 'keyboard_mode_legacy';
|
|
||||||
// Codec preference (Auto + the four optional codecs the toolbar surfaces).
|
|
||||||
const kShortcutActionCodecAuto = 'codec_auto';
|
|
||||||
const kShortcutActionCodecVp8 = 'codec_vp8';
|
|
||||||
const kShortcutActionCodecVp9 = 'codec_vp9';
|
|
||||||
const kShortcutActionCodecAv1 = 'codec_av1';
|
|
||||||
const kShortcutActionCodecH264 = 'codec_h264';
|
|
||||||
const kShortcutActionCodecH265 = 'codec_h265';
|
|
||||||
// Plug out every virtual display in one shot — toolbar exposes this in
|
|
||||||
// both IDD modes (RustDesk and Amyuni). Per-index virtual-display toggles
|
|
||||||
// (RustDesk IDD's 4 checkboxes) and the +/- count buttons (Amyuni-only)
|
|
||||||
// are NOT exposed as shortcuts: per-index is too granular, and +/- has
|
|
||||||
// no toolbar counterpart on RustDesk IDD peers.
|
|
||||||
const kShortcutActionPlugOutAllVirtualDisplays =
|
|
||||||
'plug_out_all_virtual_displays';
|
|
||||||
const kShortcutActionToggleRelativeMouseMode = 'toggle_relative_mouse_mode';
|
|
||||||
const kShortcutActionToggleFollowRemoteCursor = 'toggle_follow_remote_cursor';
|
|
||||||
const kShortcutActionToggleFollowRemoteWindow = 'toggle_follow_remote_window';
|
|
||||||
const kShortcutActionToggleZoomCursor = 'toggle_zoom_cursor';
|
|
||||||
const kShortcutActionToggleReverseMouseWheel = 'toggle_reverse_mouse_wheel';
|
|
||||||
const kShortcutActionToggleSwapLeftRightMouse = 'toggle_swap_left_right_mouse';
|
|
||||||
const kShortcutActionToggleLockAfterSessionEnd = 'toggle_lock_after_session_end';
|
|
||||||
const kShortcutActionToggleTrueColor = 'toggle_true_color';
|
|
||||||
const kShortcutActionToggleSwapCtrlCmd = 'toggle_swap_ctrl_cmd';
|
|
||||||
const kShortcutActionToggleEnableFileCopyPaste = 'toggle_enable_file_copy_paste';
|
|
||||||
const kShortcutActionViewModeCustom = 'view_mode_custom';
|
|
||||||
const kShortcutActionImageQualityBest = 'image_quality_best';
|
|
||||||
const kShortcutActionImageQualityBalanced = 'image_quality_balanced';
|
|
||||||
const kShortcutActionImageQualityLow = 'image_quality_low';
|
|
||||||
const kShortcutActionSendClipboardKeystrokes = 'send_clipboard_keystrokes';
|
|
||||||
const kShortcutActionToggleVoiceCall = 'toggle_voice_call';
|
|
||||||
const kShortcutActionToggleViewOnly = 'toggle_view_only';
|
|
||||||
|
|
||||||
const kShortcutLocalConfigKey = 'keyboard-shortcuts';
|
|
||||||
const kShortcutEventName = 'shortcut_triggered';
|
|
||||||
|
|
||||||
/// Canonical default keyboard-shortcut bindings, mirroring Rust's
|
|
||||||
/// `default_bindings()` in `src/keyboard/shortcuts.rs`. Used by:
|
|
||||||
/// * the Web bridge (`flutter/lib/web/bridge.dart::mainGetDefaultKeyboardShortcuts`)
|
|
||||||
/// — Web has no Rust at runtime, so the seed list is read from this Dart
|
|
||||||
/// constant instead of going through FFI.
|
|
||||||
/// * the configuration page when seeding defaults on first enable, after
|
|
||||||
/// [filterDefaultBindingsForPlatform] has trimmed platform-specific
|
|
||||||
/// entries.
|
|
||||||
///
|
|
||||||
/// Parity with Rust is unit-tested on both sides against
|
|
||||||
/// `flutter/test/fixtures/default_keyboard_shortcuts.json` — see the
|
|
||||||
/// `kDefaultShortcutBindings matches fixture` test in
|
|
||||||
/// `flutter/test/keyboard_shortcuts_test.dart` and
|
|
||||||
/// `default_bindings_match_fixture_json` in `src/keyboard/shortcuts.rs`.
|
|
||||||
/// Any change here MUST also update the fixture and the Rust source, or CI
|
|
||||||
/// will fail in the side that drifted.
|
|
||||||
final List<Map<String, Object>> kDefaultShortcutBindings = [
|
|
||||||
for (final entry in <List<Object>>[
|
|
||||||
[kShortcutActionSendCtrlAltDel, 'delete'],
|
|
||||||
[kShortcutActionToggleFullscreen, 'enter'],
|
|
||||||
[kShortcutActionSwitchDisplayNext, 'arrow_right'],
|
|
||||||
[kShortcutActionSwitchDisplayPrev, 'arrow_left'],
|
|
||||||
[kShortcutActionScreenshot, 'p'],
|
|
||||||
[kShortcutActionToggleShowRemoteCursor, 'm'],
|
|
||||||
// The tested iPad/Bluetooth keyboard setup did not deliver the complete
|
|
||||||
// Cmd+Option+Shift+S chord, also in Safari. Other physical keyboards are
|
|
||||||
// unverified; Mute can be rebound to a chord that reaches the app.
|
|
||||||
[kShortcutActionToggleMute, 's'],
|
|
||||||
[kShortcutActionToggleBlockInput, 'i'],
|
|
||||||
[kShortcutActionToggleChat, 'c'],
|
|
||||||
])
|
|
||||||
{
|
|
||||||
'action': entry[0],
|
|
||||||
'mods': const ['primary', 'alt', 'shift'],
|
|
||||||
'key': entry[1],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
@@ -1,208 +0,0 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
|
|
||||||
import 'shortcut_constants.dart';
|
|
||||||
|
|
||||||
List<String> canonicalShortcutModsForSave(Set<String> mods) {
|
|
||||||
return <String>[
|
|
||||||
if (mods.contains('primary')) 'primary',
|
|
||||||
if (mods.contains('ctrl')) 'ctrl',
|
|
||||||
if (mods.contains('alt')) 'alt',
|
|
||||||
if (mods.contains('shift')) 'shift',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Map<String, dynamic>> shortcutBindingMapsFrom(dynamic rawBindings) {
|
|
||||||
if (rawBindings is! Iterable) return <Map<String, dynamic>>[];
|
|
||||||
final bindings = <Map<String, dynamic>>[];
|
|
||||||
for (final raw in rawBindings) {
|
|
||||||
if (raw is! Map) continue;
|
|
||||||
final mods = raw['mods'];
|
|
||||||
if (raw['action'] is! String ||
|
|
||||||
raw['key'] is! String ||
|
|
||||||
mods is! List ||
|
|
||||||
mods.any((mod) =>
|
|
||||||
!const {'primary', 'ctrl', 'alt', 'shift'}.contains(mod))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
final binding = <String, dynamic>{};
|
|
||||||
for (final entry in raw.entries) {
|
|
||||||
final key = entry.key;
|
|
||||||
if (key is String) {
|
|
||||||
binding[key] = entry.value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (binding.isNotEmpty) {
|
|
||||||
bindings.add(binding);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return bindings;
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> shortcutModSetFrom(dynamic rawMods) {
|
|
||||||
if (rawMods is! Iterable) return <String>{};
|
|
||||||
return rawMods.whereType<String>().toSet();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether enabling shortcuts should seed the default bindings. Only a config
|
|
||||||
/// that has never held a bindings list is seeded; an empty list means the
|
|
||||||
/// user cleared every binding and must stay empty.
|
|
||||||
bool shouldSeedDefaultShortcutBindings(Map<String, dynamic> config) =>
|
|
||||||
!config.containsKey('bindings');
|
|
||||||
|
|
||||||
bool isSwitchTabShortcutAction(String? actionId) {
|
|
||||||
return actionId == kShortcutActionSwitchTabNext ||
|
|
||||||
actionId == kShortcutActionSwitchTabPrev;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// USB HID usage (keyboard page 0x07) of every key accepted as a shortcut,
|
|
||||||
/// mapped to the canonical key name used in saved bindings.
|
|
||||||
const Map<int, String> _kUsbHidKeyNames = {
|
|
||||||
0x04: 'a', 0x05: 'b', 0x06: 'c', 0x07: 'd', 0x08: 'e', 0x09: 'f',
|
|
||||||
0x0A: 'g', 0x0B: 'h', 0x0C: 'i', 0x0D: 'j', 0x0E: 'k', 0x0F: 'l',
|
|
||||||
0x10: 'm', 0x11: 'n', 0x12: 'o', 0x13: 'p', 0x14: 'q', 0x15: 'r',
|
|
||||||
0x16: 's', 0x17: 't', 0x18: 'u', 0x19: 'v', 0x1A: 'w', 0x1B: 'x',
|
|
||||||
0x1C: 'y', 0x1D: 'z',
|
|
||||||
0x1E: 'digit1', 0x1F: 'digit2', 0x20: 'digit3', 0x21: 'digit4',
|
|
||||||
0x22: 'digit5', 0x23: 'digit6', 0x24: 'digit7', 0x25: 'digit8',
|
|
||||||
0x26: 'digit9', 0x27: 'digit0',
|
|
||||||
0x28: 'enter', 0x2A: 'backspace', 0x2B: 'tab', 0x2C: 'space',
|
|
||||||
0x3A: 'f1', 0x3B: 'f2', 0x3C: 'f3', 0x3D: 'f4', 0x3E: 'f5', 0x3F: 'f6',
|
|
||||||
0x40: 'f7', 0x41: 'f8', 0x42: 'f9', 0x43: 'f10', 0x44: 'f11', 0x45: 'f12',
|
|
||||||
0x49: 'insert', 0x4A: 'home', 0x4B: 'page_up', 0x4C: 'delete',
|
|
||||||
0x4D: 'end', 0x4E: 'page_down', 0x4F: 'arrow_right', 0x50: 'arrow_left',
|
|
||||||
0x51: 'arrow_down', 0x52: 'arrow_up',
|
|
||||||
// Numpad Enter shares the "enter" name with the main Return key, as in the
|
|
||||||
// Rust matcher (`Return | KpReturn`) and the Web matcher (`NumpadEnter`).
|
|
||||||
0x58: 'enter',
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Map a [PhysicalKeyboardKey] to the canonical key name used in saved
|
|
||||||
/// bindings, or `null` for keys we don't accept as shortcuts.
|
|
||||||
///
|
|
||||||
/// Bindings name physical key positions (US layout names), whatever the
|
|
||||||
/// active keyboard layout: the native matcher sees the key through its USB
|
|
||||||
/// HID usage (`rdev::usb_hid_key_from_code` -> `event_to_key_name` in
|
|
||||||
/// `src/keyboard/shortcuts.rs`) and the Web matcher through
|
|
||||||
/// `KeyboardEvent.code` (`flutter/web/js/src/shortcut_matcher.ts`). Parity
|
|
||||||
/// is enforced against `flutter/test/fixtures/shortcut_key_usb_hid.json` by
|
|
||||||
/// a Dart test and the Rust `usb_hid_keys_match_fixture` test.
|
|
||||||
String? physicalKeyName(PhysicalKeyboardKey k) {
|
|
||||||
final usage = k.usbHidUsage;
|
|
||||||
if (usage >> 16 != 0x07) return null;
|
|
||||||
return _kUsbHidKeyNames[usage & 0xFFFF];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The key name a [KeyEvent] records or matches as.
|
|
||||||
String? shortcutKeyNameForEvent(KeyEvent e) => physicalKeyName(e.physicalKey);
|
|
||||||
|
|
||||||
/// Bundle of "is this shortcut available on the current platform" flags.
|
|
||||||
///
|
|
||||||
/// Production code reaches a single source of truth via
|
|
||||||
/// [ShortcutModel.currentPlatformCapabilities] (which encodes the per-runtime
|
|
||||||
/// rules in one place); tests construct one directly with whichever flags
|
|
||||||
/// they want to exercise. Two filter functions consume this:
|
|
||||||
/// [filterDefaultBindingsForPlatform] (for trimming default-binding JSON
|
|
||||||
/// before it hits LocalConfig) and [filterKeyboardShortcutActionGroupsForPlatform]
|
|
||||||
/// (for trimming the configuration UI's action list). Both must agree on the
|
|
||||||
/// same capability set, otherwise a default binding could be seeded for an
|
|
||||||
/// action the user has no UI to manage.
|
|
||||||
class ShortcutPlatformCapabilities {
|
|
||||||
final bool includeFullscreenShortcut;
|
|
||||||
final bool includeScreenshotShortcut;
|
|
||||||
final bool includeRelativeMouseModeShortcut;
|
|
||||||
final bool includeTabShortcuts;
|
|
||||||
final bool includeToolbarShortcut;
|
|
||||||
final bool includeCloseTabShortcut;
|
|
||||||
final bool includeSwitchSidesShortcut;
|
|
||||||
final bool includeRecordingShortcut;
|
|
||||||
final bool includeResetCanvasShortcut;
|
|
||||||
final bool includePinToolbarShortcut;
|
|
||||||
final bool includeViewModeShortcut;
|
|
||||||
final bool includeVoiceCallShortcut;
|
|
||||||
final Set<String> excludedActions;
|
|
||||||
|
|
||||||
const ShortcutPlatformCapabilities({
|
|
||||||
required this.includeFullscreenShortcut,
|
|
||||||
required this.includeScreenshotShortcut,
|
|
||||||
required this.includeRelativeMouseModeShortcut,
|
|
||||||
required this.includeTabShortcuts,
|
|
||||||
required this.includeToolbarShortcut,
|
|
||||||
required this.includeCloseTabShortcut,
|
|
||||||
required this.includeSwitchSidesShortcut,
|
|
||||||
required this.includeRecordingShortcut,
|
|
||||||
required this.includeResetCanvasShortcut,
|
|
||||||
required this.includePinToolbarShortcut,
|
|
||||||
required this.includeViewModeShortcut,
|
|
||||||
required this.includeVoiceCallShortcut,
|
|
||||||
this.excludedActions = const {},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Map<String, dynamic>> filterDefaultBindingsForPlatform(
|
|
||||||
Iterable<dynamic> bindings,
|
|
||||||
ShortcutPlatformCapabilities cap,
|
|
||||||
) {
|
|
||||||
final filtered = <Map<String, dynamic>>[];
|
|
||||||
for (final binding in shortcutBindingMapsFrom(bindings)) {
|
|
||||||
final action = binding['action'] as String?;
|
|
||||||
if (cap.excludedActions.contains(action)) continue;
|
|
||||||
// Compact Apple keyboards can label Backspace as Delete, making this
|
|
||||||
// default ambiguous. Using Backspace also conflicts with Finder's
|
|
||||||
// "Empty Trash without confirmation" shortcut on macOS.
|
|
||||||
// Leave it unbound; users can still record their own shortcut.
|
|
||||||
if ((defaultTargetPlatform == TargetPlatform.macOS ||
|
|
||||||
defaultTargetPlatform == TargetPlatform.iOS) &&
|
|
||||||
action == kShortcutActionSendCtrlAltDel) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeFullscreenShortcut &&
|
|
||||||
action == kShortcutActionToggleFullscreen) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeScreenshotShortcut && action == kShortcutActionScreenshot) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeRelativeMouseModeShortcut &&
|
|
||||||
action == kShortcutActionToggleRelativeMouseMode) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeTabShortcuts && isSwitchTabShortcutAction(action)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeToolbarShortcut &&
|
|
||||||
action == kShortcutActionToggleToolbar) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeCloseTabShortcut && action == kShortcutActionCloseTab) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeSwitchSidesShortcut &&
|
|
||||||
action == kShortcutActionSwitchSides) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeRecordingShortcut &&
|
|
||||||
action == kShortcutActionToggleRecording) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeResetCanvasShortcut &&
|
|
||||||
action == kShortcutActionResetCanvas) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includePinToolbarShortcut && action == kShortcutActionPinToolbar) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeViewModeShortcut &&
|
|
||||||
(action == kShortcutActionViewModeOriginal ||
|
|
||||||
action == kShortcutActionViewModeAdaptive ||
|
|
||||||
action == kShortcutActionViewModeCustom)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!cap.includeVoiceCallShortcut &&
|
|
||||||
action == kShortcutActionToggleVoiceCall) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
filtered.add(binding);
|
|
||||||
}
|
|
||||||
return filtered;
|
|
||||||
}
|
|
||||||
@@ -11,7 +11,6 @@ import 'package:flutter_hbb/consts.dart';
|
|||||||
import 'package:flutter_hbb/desktop/widgets/remote_toolbar.dart';
|
import 'package:flutter_hbb/desktop/widgets/remote_toolbar.dart';
|
||||||
import 'package:flutter_hbb/models/model.dart';
|
import 'package:flutter_hbb/models/model.dart';
|
||||||
import 'package:flutter_hbb/models/platform_model.dart';
|
import 'package:flutter_hbb/models/platform_model.dart';
|
||||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
|
||||||
import 'package:flutter_hbb/utils/multi_window_manager.dart';
|
import 'package:flutter_hbb/utils/multi_window_manager.dart';
|
||||||
import 'package:get/get.dart';
|
import 'package:get/get.dart';
|
||||||
import 'package:url_launcher/url_launcher.dart';
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
@@ -93,77 +92,16 @@ bool allowDisplaySwitchInPrivacyMode(PeerInfo pi, String privacyModeImpl) {
|
|||||||
versionCmp(pi.version, '1.4.8') >= 0);
|
versionCmp(pi.version, '1.4.8') >= 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Action IDs that `toolbarControls` is the sole registrar for. Wiped on
|
|
||||||
/// every call so stale closures don't outlive the menu entry that owned
|
|
||||||
/// them. Actions registered by `registerSessionShortcutActions` MUST NOT
|
|
||||||
/// appear here. `kShortcutActionToggleRecording` is platform-conditional
|
|
||||||
/// and handled separately in the unregister pass below.
|
|
||||||
const _kToolbarOwnedActionIds = <String>[
|
|
||||||
kShortcutActionSendCtrlAltDel,
|
|
||||||
kShortcutActionRestartRemote,
|
|
||||||
kShortcutActionInsertLock,
|
|
||||||
kShortcutActionToggleBlockInput,
|
|
||||||
kShortcutActionSwitchSides,
|
|
||||||
kShortcutActionRefresh,
|
|
||||||
kShortcutActionScreenshot,
|
|
||||||
kShortcutActionResetCanvas,
|
|
||||||
kShortcutActionSendClipboardKeystrokes,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _kToolbarViewStyleActionIds = <String>[
|
|
||||||
kShortcutActionViewModeOriginal,
|
|
||||||
kShortcutActionViewModeAdaptive,
|
|
||||||
kShortcutActionViewModeCustom,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _kToolbarImageQualityActionIds = <String>[
|
|
||||||
kShortcutActionImageQualityBest,
|
|
||||||
kShortcutActionImageQualityBalanced,
|
|
||||||
kShortcutActionImageQualityLow,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _kToolbarCodecActionIds = <String>[
|
|
||||||
kShortcutActionCodecAuto,
|
|
||||||
kShortcutActionCodecVp8,
|
|
||||||
kShortcutActionCodecVp9,
|
|
||||||
kShortcutActionCodecAv1,
|
|
||||||
kShortcutActionCodecH264,
|
|
||||||
kShortcutActionCodecH265,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _kToolbarCursorActionIds = <String>[
|
|
||||||
kShortcutActionToggleShowRemoteCursor,
|
|
||||||
kShortcutActionToggleFollowRemoteCursor,
|
|
||||||
kShortcutActionToggleFollowRemoteWindow,
|
|
||||||
kShortcutActionToggleZoomCursor,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _kToolbarDisplayToggleActionIds = <String>[
|
|
||||||
kShortcutActionToggleQualityMonitor,
|
|
||||||
kShortcutActionToggleMute,
|
|
||||||
kShortcutActionToggleEnableFileCopyPaste,
|
|
||||||
kShortcutActionToggleDisableClipboard,
|
|
||||||
kShortcutActionToggleLockAfterSessionEnd,
|
|
||||||
kShortcutActionToggleTrueColor,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _kToolbarKeyboardToggleActionIds = <String>[
|
|
||||||
kShortcutActionToggleSwapCtrlCmd,
|
|
||||||
kShortcutActionToggleSwapLeftRightMouse,
|
|
||||||
];
|
|
||||||
|
|
||||||
class TTextMenu {
|
class TTextMenu {
|
||||||
final Widget child;
|
final Widget child;
|
||||||
final VoidCallback? onPressed;
|
final VoidCallback? onPressed;
|
||||||
Widget? trailingIcon;
|
Widget? trailingIcon;
|
||||||
bool divider;
|
bool divider;
|
||||||
final String? actionId;
|
|
||||||
TTextMenu(
|
TTextMenu(
|
||||||
{required this.child,
|
{required this.child,
|
||||||
required this.onPressed,
|
required this.onPressed,
|
||||||
this.trailingIcon,
|
this.trailingIcon,
|
||||||
this.divider = false,
|
this.divider = false});
|
||||||
this.actionId});
|
|
||||||
|
|
||||||
Widget getChild() {
|
Widget getChild() {
|
||||||
if (trailingIcon != null) {
|
if (trailingIcon != null) {
|
||||||
@@ -185,73 +123,20 @@ class TRadioMenu<T> {
|
|||||||
final T value;
|
final T value;
|
||||||
final T groupValue;
|
final T groupValue;
|
||||||
final ValueChanged<T?>? onChanged;
|
final ValueChanged<T?>? onChanged;
|
||||||
final String? actionId;
|
|
||||||
|
|
||||||
TRadioMenu(
|
TRadioMenu(
|
||||||
{required this.child,
|
{required this.child,
|
||||||
required this.value,
|
required this.value,
|
||||||
required this.groupValue,
|
required this.groupValue,
|
||||||
required this.onChanged,
|
required this.onChanged});
|
||||||
this.actionId});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class TToggleMenu {
|
class TToggleMenu {
|
||||||
final Widget child;
|
final Widget child;
|
||||||
final bool value;
|
final bool value;
|
||||||
final ValueChanged<bool?>? onChanged;
|
final ValueChanged<bool?>? onChanged;
|
||||||
final String? actionId;
|
|
||||||
TToggleMenu(
|
TToggleMenu(
|
||||||
{required this.child,
|
{required this.child, required this.value, required this.onChanged});
|
||||||
required this.value,
|
|
||||||
required this.onChanged,
|
|
||||||
this.actionId});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Register each tagged entry's `onChanged` with the session [ShortcutModel].
|
|
||||||
/// Passthrough — returns [menus] so a caller can wrap `return [...]` directly.
|
|
||||||
List<TToggleMenu> _registerToggleMenuShortcuts(
|
|
||||||
FFI ffi,
|
|
||||||
List<TToggleMenu> menus, {
|
|
||||||
List<String> ownedActionIds = const [],
|
|
||||||
}) {
|
|
||||||
for (final actionId in ownedActionIds) {
|
|
||||||
ffi.shortcutModel.unregister(actionId);
|
|
||||||
}
|
|
||||||
for (final menu in menus) {
|
|
||||||
final actionId = menu.actionId;
|
|
||||||
if (actionId == null) continue;
|
|
||||||
final onChanged = menu.onChanged;
|
|
||||||
if (onChanged == null) {
|
|
||||||
ffi.shortcutModel.unregister(actionId);
|
|
||||||
} else {
|
|
||||||
final value = menu.value;
|
|
||||||
ffi.shortcutModel.register(actionId, () => onChanged(!value));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return menus;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Radio variant of [_registerToggleMenuShortcuts].
|
|
||||||
List<TRadioMenu<T>> _registerRadioMenuShortcuts<T>(
|
|
||||||
FFI ffi,
|
|
||||||
List<TRadioMenu<T>> menus, {
|
|
||||||
List<String> ownedActionIds = const [],
|
|
||||||
}) {
|
|
||||||
for (final actionId in ownedActionIds) {
|
|
||||||
ffi.shortcutModel.unregister(actionId);
|
|
||||||
}
|
|
||||||
for (final menu in menus) {
|
|
||||||
final actionId = menu.actionId;
|
|
||||||
if (actionId == null) continue;
|
|
||||||
final onChanged = menu.onChanged;
|
|
||||||
if (onChanged == null) {
|
|
||||||
ffi.shortcutModel.unregister(actionId);
|
|
||||||
} else {
|
|
||||||
final value = menu.value;
|
|
||||||
ffi.shortcutModel.register(actionId, () => onChanged(value));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return menus;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
handleOsPasswordEditIcon(
|
handleOsPasswordEditIcon(
|
||||||
@@ -452,17 +337,6 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
final isDefaultConn = ffi.connType == ConnType.defaultConn;
|
final isDefaultConn = ffi.connType == ConnType.defaultConn;
|
||||||
final isWaylandPeer = pi.platform == kPeerPlatformLinux && pi.isWayland;
|
final isWaylandPeer = pi.platform == kPeerPlatformLinux && pi.isWayland;
|
||||||
|
|
||||||
// Wipe stale registrations from previous menu builds before re-registering
|
|
||||||
// below; runs unconditionally so mid-session enable works without reconnect.
|
|
||||||
for (final actionId in _kToolbarOwnedActionIds) {
|
|
||||||
ffi.shortcutModel.unregister(actionId);
|
|
||||||
}
|
|
||||||
// toggle_recording is mobile-only here; desktop's registration is owned by
|
|
||||||
// `registerSessionShortcutActions` and must not be touched.
|
|
||||||
if (!(isDesktop || isWeb)) {
|
|
||||||
ffi.shortcutModel.unregister(kShortcutActionToggleRecording);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<TTextMenu> v = [];
|
List<TTextMenu> v = [];
|
||||||
// elevation
|
// elevation
|
||||||
if (isDefaultConn &&
|
if (isDefaultConn &&
|
||||||
@@ -530,8 +404,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await sendClipboardKeystrokes();
|
await sendClipboardKeystrokes();
|
||||||
},
|
}));
|
||||||
actionId: kShortcutActionSendClipboardKeystrokes));
|
|
||||||
}
|
}
|
||||||
if (isDefaultConn &&
|
if (isDefaultConn &&
|
||||||
isWaylandPeer &&
|
isWaylandPeer &&
|
||||||
@@ -566,8 +439,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
if (isDefaultConn && isMobile) {
|
if (isDefaultConn && isMobile) {
|
||||||
v.add(TTextMenu(
|
v.add(TTextMenu(
|
||||||
child: Text(translate('Reset canvas')),
|
child: Text(translate('Reset canvas')),
|
||||||
onPressed: () => ffi.cursorModel.reset(),
|
onPressed: () => ffi.cursorModel.reset()));
|
||||||
actionId: kShortcutActionResetCanvas));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// https://github.com/rustdesk/rustdesk/pull/9731
|
// https://github.com/rustdesk/rustdesk/pull/9731
|
||||||
@@ -643,8 +515,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
v.add(
|
v.add(
|
||||||
TTextMenu(
|
TTextMenu(
|
||||||
child: Text('${translate("Insert Ctrl + Alt + Del")}'),
|
child: Text('${translate("Insert Ctrl + Alt + Del")}'),
|
||||||
onPressed: () => bind.sessionCtrlAltDel(sessionId: sessionId),
|
onPressed: () => bind.sessionCtrlAltDel(sessionId: sessionId)),
|
||||||
actionId: kShortcutActionSendCtrlAltDel),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// restart
|
// restart
|
||||||
@@ -657,8 +528,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
TTextMenu(
|
TTextMenu(
|
||||||
child: Text(translate('Restart remote device')),
|
child: Text(translate('Restart remote device')),
|
||||||
onPressed: () =>
|
onPressed: () =>
|
||||||
showRestartRemoteDevice(pi, id, sessionId, ffi.dialogManager),
|
showRestartRemoteDevice(pi, id, sessionId, ffi.dialogManager)),
|
||||||
actionId: kShortcutActionRestartRemote),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// insertLock
|
// insertLock
|
||||||
@@ -666,8 +536,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
v.add(
|
v.add(
|
||||||
TTextMenu(
|
TTextMenu(
|
||||||
child: Text(translate('Insert Lock')),
|
child: Text(translate('Insert Lock')),
|
||||||
onPressed: () => bind.sessionLockScreen(sessionId: sessionId),
|
onPressed: () => bind.sessionLockScreen(sessionId: sessionId)),
|
||||||
actionId: kShortcutActionInsertLock),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// blockUserInput
|
// blockUserInput
|
||||||
@@ -685,8 +554,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
sessionId: sessionId,
|
sessionId: sessionId,
|
||||||
value: '${blockInput.value ? 'un' : ''}block-input');
|
value: '${blockInput.value ? 'un' : ''}block-input');
|
||||||
blockInput.value = !blockInput.value;
|
blockInput.value = !blockInput.value;
|
||||||
},
|
}));
|
||||||
actionId: kShortcutActionToggleBlockInput));
|
|
||||||
}
|
}
|
||||||
// switchSides
|
// switchSides
|
||||||
if (isDefaultConn &&
|
if (isDefaultConn &&
|
||||||
@@ -698,15 +566,13 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
v.add(TTextMenu(
|
v.add(TTextMenu(
|
||||||
child: Text(translate('Switch Sides')),
|
child: Text(translate('Switch Sides')),
|
||||||
onPressed: () =>
|
onPressed: () =>
|
||||||
showConfirmSwitchSidesDialog(sessionId, id, ffi.dialogManager),
|
showConfirmSwitchSidesDialog(sessionId, id, ffi.dialogManager)));
|
||||||
actionId: kShortcutActionSwitchSides));
|
|
||||||
}
|
}
|
||||||
// refresh
|
// refresh
|
||||||
if (pi.version.isNotEmpty) {
|
if (pi.version.isNotEmpty) {
|
||||||
v.add(TTextMenu(
|
v.add(TTextMenu(
|
||||||
child: Text(translate('Refresh')),
|
child: Text(translate('Refresh')),
|
||||||
onPressed: () => sessionRefreshVideo(sessionId, pi),
|
onPressed: () => sessionRefreshVideo(sessionId, pi),
|
||||||
actionId: kShortcutActionRefresh,
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
// record
|
// record
|
||||||
@@ -729,8 +595,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
)
|
)
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
onPressed: () => ffi.recordingModel.toggle(),
|
onPressed: () => ffi.recordingModel.toggle()));
|
||||||
actionId: kShortcutActionToggleRecording));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// to-do:
|
// to-do:
|
||||||
@@ -747,14 +612,6 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
onPressed: ffi.ffiModel.timerScreenshot != null
|
onPressed: ffi.ffiModel.timerScreenshot != null
|
||||||
? null
|
? null
|
||||||
: () {
|
: () {
|
||||||
// Live cooldown check: the menu rebuilds onPressed=null
|
|
||||||
// whenever toolbarControls runs and finds timerScreenshot
|
|
||||||
// != null, but the keyboard-shortcut callback holds onto
|
|
||||||
// the originally-enabled closure across cooldown periods
|
|
||||||
// (toolbarControls only re-runs on menu open). Without
|
|
||||||
// this guard the second shortcut press during the 30s
|
|
||||||
// cooldown still fires sessionTakeScreenshot.
|
|
||||||
if (ffi.ffiModel.timerScreenshot != null) return;
|
|
||||||
if (pi.currentDisplay == kAllDisplayValue) {
|
if (pi.currentDisplay == kAllDisplayValue) {
|
||||||
msgBox(
|
msgBox(
|
||||||
sessionId,
|
sessionId,
|
||||||
@@ -772,7 +629,6 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
actionId: kShortcutActionScreenshot,
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -783,17 +639,6 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
|
|||||||
onPressed: () => onCopyFingerprint(FingerprintState.find(id).value),
|
onPressed: () => onCopyFingerprint(FingerprintState.find(id).value),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
// Register tagged TTextMenu callbacks. The else-unregister is defense in
|
|
||||||
// depth for actionIds tagged but missing from `_kToolbarOwnedActionIds`.
|
|
||||||
for (final menu in v) {
|
|
||||||
final actionId = menu.actionId;
|
|
||||||
if (actionId == null) continue;
|
|
||||||
if (menu.onPressed != null) {
|
|
||||||
ffi.shortcutModel.register(actionId, menu.onPressed!);
|
|
||||||
} else {
|
|
||||||
ffi.shortcutModel.unregister(actionId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -808,26 +653,23 @@ Future<List<TRadioMenu<String>>> toolbarViewStyle(
|
|||||||
.then((_) => ffi.canvasModel.updateViewStyle());
|
.then((_) => ffi.canvasModel.updateViewStyle());
|
||||||
}
|
}
|
||||||
|
|
||||||
return _registerRadioMenuShortcuts(ffi, [
|
return [
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Scale original')),
|
child: Text(translate('Scale original')),
|
||||||
value: kRemoteViewStyleOriginal,
|
value: kRemoteViewStyleOriginal,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged),
|
||||||
actionId: kShortcutActionViewModeOriginal),
|
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Scale adaptive')),
|
child: Text(translate('Scale adaptive')),
|
||||||
value: kRemoteViewStyleAdaptive,
|
value: kRemoteViewStyleAdaptive,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged),
|
||||||
actionId: kShortcutActionViewModeAdaptive),
|
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Scale custom')),
|
child: Text(translate('Scale custom')),
|
||||||
value: kRemoteViewStyleCustom,
|
value: kRemoteViewStyleCustom,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged)
|
||||||
actionId: kShortcutActionViewModeCustom)
|
];
|
||||||
], ownedActionIds: _kToolbarViewStyleActionIds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<TRadioMenu<String>>> toolbarImageQuality(
|
Future<List<TRadioMenu<String>>> toolbarImageQuality(
|
||||||
@@ -839,25 +681,22 @@ Future<List<TRadioMenu<String>>> toolbarImageQuality(
|
|||||||
await bind.sessionSetImageQuality(sessionId: ffi.sessionId, value: value);
|
await bind.sessionSetImageQuality(sessionId: ffi.sessionId, value: value);
|
||||||
}
|
}
|
||||||
|
|
||||||
return _registerRadioMenuShortcuts(ffi, [
|
return [
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Good image quality')),
|
child: Text(translate('Good image quality')),
|
||||||
value: kRemoteImageQualityBest,
|
value: kRemoteImageQualityBest,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged),
|
||||||
actionId: kShortcutActionImageQualityBest),
|
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Balanced')),
|
child: Text(translate('Balanced')),
|
||||||
value: kRemoteImageQualityBalanced,
|
value: kRemoteImageQualityBalanced,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged),
|
||||||
actionId: kShortcutActionImageQualityBalanced),
|
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Optimize reaction time')),
|
child: Text(translate('Optimize reaction time')),
|
||||||
value: kRemoteImageQualityLow,
|
value: kRemoteImageQualityLow,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: onChanged,
|
onChanged: onChanged),
|
||||||
actionId: kShortcutActionImageQualityLow),
|
|
||||||
TRadioMenu<String>(
|
TRadioMenu<String>(
|
||||||
child: Text(translate('Custom')),
|
child: Text(translate('Custom')),
|
||||||
value: kRemoteImageQualityCustom,
|
value: kRemoteImageQualityCustom,
|
||||||
@@ -867,7 +706,7 @@ Future<List<TRadioMenu<String>>> toolbarImageQuality(
|
|||||||
customImageQualityDialog(ffi.sessionId, id, ffi);
|
customImageQualityDialog(ffi.sessionId, id, ffi);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
], ownedActionIds: _kToolbarImageQualityActionIds);
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<TRadioMenu<String>>> toolbarCodec(
|
Future<List<TRadioMenu<String>>> toolbarCodec(
|
||||||
@@ -894,10 +733,7 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
|
|||||||
}
|
}
|
||||||
final visible =
|
final visible =
|
||||||
codecs.length == 4 && (codecs[0] || codecs[1] || codecs[2] || codecs[3]);
|
codecs.length == 4 && (codecs[0] || codecs[1] || codecs[2] || codecs[3]);
|
||||||
if (!visible) {
|
if (!visible) return [];
|
||||||
return _registerRadioMenuShortcuts<String>(ffi, [],
|
|
||||||
ownedActionIds: _kToolbarCodecActionIds);
|
|
||||||
}
|
|
||||||
onChanged(String? value) async {
|
onChanged(String? value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
await bind.sessionPeerOption(
|
await bind.sessionPeerOption(
|
||||||
@@ -905,14 +741,12 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
|
|||||||
bind.sessionChangePreferCodec(sessionId: sessionId);
|
bind.sessionChangePreferCodec(sessionId: sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
TRadioMenu<String> radio(
|
TRadioMenu<String> radio(String label, String value, bool enabled) {
|
||||||
String label, String value, bool enabled, String actionId) {
|
|
||||||
return TRadioMenu<String>(
|
return TRadioMenu<String>(
|
||||||
child: Text(label),
|
child: Text(label),
|
||||||
value: value,
|
value: value,
|
||||||
groupValue: groupValue,
|
groupValue: groupValue,
|
||||||
onChanged: enabled ? onChanged : null,
|
onChanged: enabled ? onChanged : null);
|
||||||
actionId: actionId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var autoLabel = translate('Auto');
|
var autoLabel = translate('Auto');
|
||||||
@@ -920,14 +754,14 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
|
|||||||
ffi.qualityMonitorModel.data.codecFormat != null) {
|
ffi.qualityMonitorModel.data.codecFormat != null) {
|
||||||
autoLabel = '$autoLabel (${ffi.qualityMonitorModel.data.codecFormat})';
|
autoLabel = '$autoLabel (${ffi.qualityMonitorModel.data.codecFormat})';
|
||||||
}
|
}
|
||||||
return _registerRadioMenuShortcuts(ffi, [
|
return [
|
||||||
radio(autoLabel, 'auto', true, kShortcutActionCodecAuto),
|
radio(autoLabel, 'auto', true),
|
||||||
if (codecs[0]) radio('VP8', 'vp8', codecs[0], kShortcutActionCodecVp8),
|
if (codecs[0]) radio('VP8', 'vp8', codecs[0]),
|
||||||
radio('VP9', 'vp9', true, kShortcutActionCodecVp9),
|
radio('VP9', 'vp9', true),
|
||||||
if (codecs[1]) radio('AV1', 'av1', codecs[1], kShortcutActionCodecAv1),
|
if (codecs[1]) radio('AV1', 'av1', codecs[1]),
|
||||||
if (codecs[2]) radio('H264', 'h264', codecs[2], kShortcutActionCodecH264),
|
if (codecs[2]) radio('H264', 'h264', codecs[2]),
|
||||||
if (codecs[3]) radio('H265', 'h265', codecs[3], kShortcutActionCodecH265),
|
if (codecs[3]) radio('H265', 'h265', codecs[3]),
|
||||||
], ownedActionIds: _kToolbarCodecActionIds);
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<TToggleMenu>> toolbarCursor(
|
Future<List<TToggleMenu>> toolbarCursor(
|
||||||
@@ -952,7 +786,6 @@ Future<List<TToggleMenu>> toolbarCursor(
|
|||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
child: Text(translate('Show remote cursor')),
|
child: Text(translate('Show remote cursor')),
|
||||||
value: state.value,
|
value: state.value,
|
||||||
actionId: kShortcutActionToggleShowRemoteCursor,
|
|
||||||
onChanged: enabled && !lockState.value
|
onChanged: enabled && !lockState.value
|
||||||
? (value) async {
|
? (value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
@@ -989,7 +822,6 @@ Future<List<TToggleMenu>> toolbarCursor(
|
|||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
child: Text(translate('Follow remote cursor')),
|
child: Text(translate('Follow remote cursor')),
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleFollowRemoteCursor,
|
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
||||||
@@ -1018,7 +850,6 @@ Future<List<TToggleMenu>> toolbarCursor(
|
|||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
child: Text(translate('Follow remote window focus')),
|
child: Text(translate('Follow remote window focus')),
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleFollowRemoteWindow,
|
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
||||||
@@ -1036,7 +867,6 @@ Future<List<TToggleMenu>> toolbarCursor(
|
|||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
child: Text(translate('Zoom cursor')),
|
child: Text(translate('Zoom cursor')),
|
||||||
value: peerState.value,
|
value: peerState.value,
|
||||||
actionId: kShortcutActionToggleZoomCursor,
|
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
||||||
@@ -1045,8 +875,7 @@ Future<List<TToggleMenu>> toolbarCursor(
|
|||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
return _registerToggleMenuShortcuts(ffi, v,
|
return v;
|
||||||
ownedActionIds: _kToolbarCursorActionIds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<List<TToggleMenu>> toolbarDisplayToggle(
|
Future<List<TToggleMenu>> toolbarDisplayToggle(
|
||||||
@@ -1062,7 +891,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
final option = 'show-quality-monitor';
|
final option = 'show-quality-monitor';
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option),
|
value: bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option),
|
||||||
actionId: kShortcutActionToggleQualityMonitor,
|
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
||||||
@@ -1076,7 +904,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
|
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleMute,
|
|
||||||
onChanged: (value) {
|
onChanged: (value) {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
bind.sessionToggleOption(sessionId: sessionId, value: option);
|
bind.sessionToggleOption(sessionId: sessionId, value: option);
|
||||||
@@ -1101,7 +928,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
sessionId: sessionId, arg: kOptionEnableFileCopyPaste);
|
sessionId: sessionId, arg: kOptionEnableFileCopyPaste);
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleEnableFileCopyPaste,
|
|
||||||
onChanged: enabled
|
onChanged: enabled
|
||||||
? (value) {
|
? (value) {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
@@ -1120,7 +946,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
if (ffiModel.viewOnly) value = true;
|
if (ffiModel.viewOnly) value = true;
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleDisableClipboard,
|
|
||||||
onChanged: enabled
|
onChanged: enabled
|
||||||
? (value) {
|
? (value) {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
@@ -1137,7 +962,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
|
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleLockAfterSessionEnd,
|
|
||||||
onChanged: enabled
|
onChanged: enabled
|
||||||
? (value) {
|
? (value) {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
@@ -1190,7 +1014,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
|
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleTrueColor,
|
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
if (value == null) return;
|
if (value == null) return;
|
||||||
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
await bind.sessionToggleOption(sessionId: sessionId, value: option);
|
||||||
@@ -1215,8 +1038,7 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
|
|||||||
},
|
},
|
||||||
child: Text(translate('View Mode'))));
|
child: Text(translate('View Mode'))));
|
||||||
}
|
}
|
||||||
return _registerToggleMenuShortcuts(ffi, v,
|
return v;
|
||||||
ownedActionIds: _kToolbarDisplayToggleActionIds);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var togglePrivacyModeTime = DateTime.now().subtract(const Duration(hours: 1));
|
var togglePrivacyModeTime = DateTime.now().subtract(const Duration(hours: 1));
|
||||||
@@ -1344,7 +1166,6 @@ List<TToggleMenu> toolbarKeyboardToggles(FFI ffi) {
|
|||||||
final enabled = !ffi.ffiModel.viewOnly;
|
final enabled = !ffi.ffiModel.viewOnly;
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleSwapCtrlCmd,
|
|
||||||
onChanged: enabled ? onChanged : null,
|
onChanged: enabled ? onChanged : null,
|
||||||
child: Text(translate('Swap control-command key'))));
|
child: Text(translate('Swap control-command key'))));
|
||||||
}
|
}
|
||||||
@@ -1410,52 +1231,10 @@ List<TToggleMenu> toolbarKeyboardToggles(FFI ffi) {
|
|||||||
final enabled = !ffi.ffiModel.viewOnly;
|
final enabled = !ffi.ffiModel.viewOnly;
|
||||||
v.add(TToggleMenu(
|
v.add(TToggleMenu(
|
||||||
value: value,
|
value: value,
|
||||||
actionId: kShortcutActionToggleSwapLeftRightMouse,
|
|
||||||
onChanged: enabled ? onChanged : null,
|
onChanged: enabled ? onChanged : null,
|
||||||
child: Text(translate('swap-left-right-mouse'))));
|
child: Text(translate('swap-left-right-mouse'))));
|
||||||
}
|
}
|
||||||
return _registerToggleMenuShortcuts(ffi, v,
|
return v;
|
||||||
ownedActionIds: _kToolbarKeyboardToggleActionIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drive each toolbar helper for its registration side effect, so a shortcut
|
|
||||||
/// fires from the first keystroke without needing the user to open the
|
|
||||||
/// matching submenu. Mobile gets `toolbarKeyboardToggles` via
|
|
||||||
/// `toolbarDisplayToggle`'s `isMobile` branch — calling it explicitly there
|
|
||||||
/// would double-register.
|
|
||||||
void registerToolbarShortcuts(BuildContext context, String id, FFI ffi) {
|
|
||||||
// Rebuild only the triggered action's menu, so permission/capability changes
|
|
||||||
// and temporary disabled states take effect without opening the toolbar.
|
|
||||||
void register(List<String> actions, FutureOr<Object> Function() refresh) {
|
|
||||||
ffi.shortcutModel.registerRefresher(actions, () async {
|
|
||||||
if (!context.mounted || ffi.closed) {
|
|
||||||
ffi.shortcutModel.clear();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await refresh();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
register([
|
|
||||||
..._kToolbarOwnedActionIds,
|
|
||||||
if (!(isDesktop || isWeb)) kShortcutActionToggleRecording,
|
|
||||||
], () => toolbarControls(context, id, ffi));
|
|
||||||
register(_kToolbarKeyboardToggleActionIds, () => toolbarKeyboardToggles(ffi));
|
|
||||||
register(_kToolbarCursorActionIds, () => toolbarCursor(context, id, ffi));
|
|
||||||
register(_kToolbarDisplayToggleActionIds,
|
|
||||||
() => toolbarDisplayToggle(context, id, ffi));
|
|
||||||
register(_kToolbarViewStyleActionIds, () => toolbarViewStyle(context, id, ffi));
|
|
||||||
register(_kToolbarImageQualityActionIds,
|
|
||||||
() => toolbarImageQuality(context, id, ffi));
|
|
||||||
register(_kToolbarCodecActionIds, () => toolbarCodec(context, id, ffi));
|
|
||||||
|
|
||||||
if (isDesktop) toolbarKeyboardToggles(ffi);
|
|
||||||
unawaited(toolbarCursor(context, id, ffi));
|
|
||||||
unawaited(toolbarDisplayToggle(context, id, ffi));
|
|
||||||
unawaited(toolbarViewStyle(context, id, ffi));
|
|
||||||
unawaited(toolbarImageQuality(context, id, ffi));
|
|
||||||
unawaited(toolbarCodec(context, id, ffi));
|
|
||||||
toolbarPrivacyMode(PrivacyModeState.find(id), context, id, ffi);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool showVirtualDisplayMenu(FFI ffi) {
|
bool showVirtualDisplayMenu(FFI ffi) {
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ import 'package:flutter_hbb/common.dart';
|
|||||||
import 'package:flutter_hbb/models/state_model.dart';
|
import 'package:flutter_hbb/models/state_model.dart';
|
||||||
import 'package:get/get.dart';
|
import 'package:get/get.dart';
|
||||||
|
|
||||||
export 'common/widgets/keyboard_shortcuts/shortcut_constants.dart';
|
|
||||||
|
|
||||||
const int kMaxVirtualDisplayCount = 4;
|
const int kMaxVirtualDisplayCount = 4;
|
||||||
const int kAllVirtualDisplay = -1;
|
const int kAllVirtualDisplay = -1;
|
||||||
|
|
||||||
|
|||||||
@@ -480,10 +480,6 @@ class _DesktopHomePageState extends State<DesktopHomePage>
|
|||||||
return buildInstallCard("Permissions", "config_screen", "Configure",
|
return buildInstallCard("Permissions", "config_screen", "Configure",
|
||||||
() async {
|
() async {
|
||||||
bind.mainIsCanScreenRecording(prompt: true);
|
bind.mainIsCanScreenRecording(prompt: true);
|
||||||
// macOS shows the request prompt only once per app, so later
|
|
||||||
// presses would do nothing without opening the settings pane.
|
|
||||||
launchUrl(Uri.parse(
|
|
||||||
'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'));
|
|
||||||
watchIsCanScreenRecording = true;
|
watchIsCanScreenRecording = true;
|
||||||
}, help: 'Help', link: translate("doc_mac_permission"));
|
}, help: 'Help', link: translate("doc_mac_permission"));
|
||||||
} else if (!isOutgoingOnly && !bind.mainIsProcessTrusted(prompt: false)) {
|
} else if (!isOutgoingOnly && !bind.mainIsProcessTrusted(prompt: false)) {
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
// flutter/lib/desktop/pages/desktop_keyboard_shortcuts_page.dart
|
|
||||||
//
|
|
||||||
// Desktop shell for the Keyboard Shortcuts configuration page. Users land
|
|
||||||
// here from the General settings tab. The page exposes:
|
|
||||||
// * A top-level enable/disable toggle (mirrors the General-tab toggle —
|
|
||||||
// same JSON key, same semantics).
|
|
||||||
// * A grouped, scrollable list of actions, each with a current binding and
|
|
||||||
// edit / clear icons.
|
|
||||||
// * An AppBar "Reset to defaults" action with a confirmation dialog.
|
|
||||||
//
|
|
||||||
// All edits write back to LocalConfig under [kShortcutLocalConfigKey] in the
|
|
||||||
// canonical {enabled, bindings:[{action,mods,key}]} shape that the Rust and
|
|
||||||
// Web matchers consume.
|
|
||||||
//
|
|
||||||
// The body — group definitions, JSON I/O, conflict-replace flow,
|
|
||||||
// recording-dialog round-trip — lives in
|
|
||||||
// `common/widgets/keyboard_shortcuts/page_body.dart` and is shared with the
|
|
||||||
// mobile shell at `mobile/pages/mobile_keyboard_shortcuts_page.dart`.
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
import 'package:get/get.dart';
|
|
||||||
|
|
||||||
import '../../common.dart';
|
|
||||||
import '../../common/widgets/keyboard_shortcuts/page_body.dart';
|
|
||||||
|
|
||||||
class DesktopKeyboardShortcutsPage extends StatefulWidget {
|
|
||||||
const DesktopKeyboardShortcutsPage({Key? key}) : super(key: key);
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<DesktopKeyboardShortcutsPage> createState() =>
|
|
||||||
_DesktopKeyboardShortcutsPageState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _DesktopKeyboardShortcutsPageState
|
|
||||||
extends State<DesktopKeyboardShortcutsPage> {
|
|
||||||
final GlobalKey<KeyboardShortcutsPageBodyState> _bodyKey = GlobalKey();
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final foregroundColor =
|
|
||||||
AppBarTheme.of(context).titleTextStyle?.color ?? Colors.white;
|
|
||||||
return Scaffold(
|
|
||||||
appBar: AppBar(
|
|
||||||
title: Text(translate('Keyboard shortcuts')),
|
|
||||||
actions: [
|
|
||||||
TextButton.icon(
|
|
||||||
style: TextButton.styleFrom(foregroundColor: foregroundColor),
|
|
||||||
onPressed: () =>
|
|
||||||
_bodyKey.currentState?.resetToDefaultsWithConfirm(),
|
|
||||||
icon: const Icon(Icons.restore),
|
|
||||||
label: Text(translate('Reset to defaults')),
|
|
||||||
).marginOnly(right: 12),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
body: KeyboardShortcutsPageBody(
|
|
||||||
key: _bodyKey,
|
|
||||||
compact: true,
|
|
||||||
// Desktop's General settings tab already exposes the Enable +
|
|
||||||
// Pass-through checkboxes (it's the only entry point to this page),
|
|
||||||
// so we hide the duplicates here. Mobile shells keep the default
|
|
||||||
// (true) because their entry tile doesn't carry the toggles.
|
|
||||||
showMasterToggles: false,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,15 +10,12 @@ import 'package:flutter_hbb/common/widgets/audio_input.dart';
|
|||||||
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
|
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
|
||||||
import 'package:flutter_hbb/consts.dart';
|
import 'package:flutter_hbb/consts.dart';
|
||||||
import 'package:flutter_hbb/desktop/pages/desktop_home_page.dart';
|
import 'package:flutter_hbb/desktop/pages/desktop_home_page.dart';
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/page_body.dart';
|
|
||||||
import 'package:flutter_hbb/desktop/pages/desktop_keyboard_shortcuts_page.dart';
|
|
||||||
import 'package:flutter_hbb/desktop/pages/desktop_tab_page.dart';
|
import 'package:flutter_hbb/desktop/pages/desktop_tab_page.dart';
|
||||||
import 'package:flutter_hbb/desktop/widgets/remote_toolbar.dart';
|
import 'package:flutter_hbb/desktop/widgets/remote_toolbar.dart';
|
||||||
import 'package:flutter_hbb/mobile/widgets/dialog.dart';
|
import 'package:flutter_hbb/mobile/widgets/dialog.dart';
|
||||||
import 'package:flutter_hbb/models/platform_model.dart';
|
import 'package:flutter_hbb/models/platform_model.dart';
|
||||||
import 'package:flutter_hbb/models/printer_model.dart';
|
import 'package:flutter_hbb/models/printer_model.dart';
|
||||||
import 'package:flutter_hbb/models/server_model.dart';
|
import 'package:flutter_hbb/models/server_model.dart';
|
||||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
|
||||||
import 'package:flutter_hbb/models/state_model.dart';
|
import 'package:flutter_hbb/models/state_model.dart';
|
||||||
import 'package:get/get.dart';
|
import 'package:get/get.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
@@ -422,50 +419,11 @@ class _GeneralState extends State<_General> {
|
|||||||
if (!isWeb) audio(context),
|
if (!isWeb) audio(context),
|
||||||
if (!isWeb) record(context),
|
if (!isWeb) record(context),
|
||||||
if (!isWeb) WaylandCard(),
|
if (!isWeb) WaylandCard(),
|
||||||
other(),
|
other()
|
||||||
if (!bind.isIncomingOnly()) keyboardShortcuts(),
|
|
||||||
],
|
],
|
||||||
).marginOnly(bottom: _kListViewBottomMargin);
|
).marginOnly(bottom: _kListViewBottomMargin);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget keyboardShortcuts() {
|
|
||||||
// The bindings JSON (LocalConfig key `keyboard-shortcuts`) holds three
|
|
||||||
// flags + the bindings list: {enabled, pass_through, bindings}. When the
|
|
||||||
// master is off, the pass-through toggle and the Configure entry are
|
|
||||||
// hidden — both are meaningless without an active matcher.
|
|
||||||
return StatefulBuilder(builder: (context, setLocalState) {
|
|
||||||
final enabled = ShortcutModel.isEnabled();
|
|
||||||
return _Card(title: 'Keyboard shortcuts', children: [
|
|
||||||
_OptionCheckBox(
|
|
||||||
context,
|
|
||||||
'Enable keyboard shortcuts in remote session',
|
|
||||||
kShortcutLocalConfigKey,
|
|
||||||
isServer: false,
|
|
||||||
optGetter: ShortcutModel.isEnabled,
|
|
||||||
optSetter: (_, v) async {
|
|
||||||
await ShortcutModel.setEnabled(v);
|
|
||||||
setLocalState(() {});
|
|
||||||
},
|
|
||||||
),
|
|
||||||
if (enabled) ...[
|
|
||||||
_OptionCheckBox(
|
|
||||||
context,
|
|
||||||
'Pass-through to remote',
|
|
||||||
kShortcutLocalConfigKey,
|
|
||||||
isServer: false,
|
|
||||||
optGetter: ShortcutModel.isPassThrough,
|
|
||||||
optSetter: (_, v) async {
|
|
||||||
await ShortcutModel.setPassThrough(v);
|
|
||||||
setLocalState(() {});
|
|
||||||
},
|
|
||||||
trailing: const InfoTooltipIcon(tipKey: 'shortcut-passthrough-tip'),
|
|
||||||
),
|
|
||||||
_ShortcutsConfigureRow(),
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget theme() {
|
Widget theme() {
|
||||||
final current = MyTheme.getThemeModePreference().toShortString();
|
final current = MyTheme.getThemeModePreference().toShortString();
|
||||||
onChanged(String value) async {
|
onChanged(String value) async {
|
||||||
@@ -2699,8 +2657,6 @@ Widget _OptionCheckBox(
|
|||||||
bool isServer = true,
|
bool isServer = true,
|
||||||
bool Function()? optGetter,
|
bool Function()? optGetter,
|
||||||
Future<void> Function(String, bool)? optSetter,
|
Future<void> Function(String, bool)? optSetter,
|
||||||
// Optional widget rendered between the label and the trailing space.
|
|
||||||
Widget? trailing,
|
|
||||||
}) {
|
}) {
|
||||||
getOpt() => optGetter != null
|
getOpt() => optGetter != null
|
||||||
? optGetter()
|
? optGetter()
|
||||||
@@ -2744,23 +2700,11 @@ Widget _OptionCheckBox(
|
|||||||
offstage: !ref.value || checkedIcon == null,
|
offstage: !ref.value || checkedIcon == null,
|
||||||
child: checkedIcon?.marginOnly(right: 5),
|
child: checkedIcon?.marginOnly(right: 5),
|
||||||
),
|
),
|
||||||
// Without `trailing`, keep the original Expanded(Text) layout.
|
Expanded(
|
||||||
if (trailing == null)
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
translate(label),
|
|
||||||
style: TextStyle(color: disabledTextColor(context, enabled)),
|
|
||||||
))
|
|
||||||
else ...[
|
|
||||||
Flexible(
|
|
||||||
child: Text(
|
child: Text(
|
||||||
translate(label),
|
translate(label),
|
||||||
style: TextStyle(color: disabledTextColor(context, enabled)),
|
style: TextStyle(color: disabledTextColor(context, enabled)),
|
||||||
),
|
))
|
||||||
),
|
|
||||||
trailing,
|
|
||||||
const Spacer(),
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
).marginOnly(left: _kCheckBoxLeftMargin),
|
).marginOnly(left: _kCheckBoxLeftMargin),
|
||||||
@@ -3167,37 +3111,6 @@ class _CountDownButtonState extends State<_CountDownButton> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tappable row that pushes the shortcut configuration page.
|
|
||||||
class _ShortcutsConfigureRow extends StatelessWidget {
|
|
||||||
// ignore: unused_element
|
|
||||||
const _ShortcutsConfigureRow({Key? key}) : super(key: key);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return InkWell(
|
|
||||||
onTap: () {
|
|
||||||
Navigator.of(context).push(MaterialPageRoute(
|
|
||||||
builder: (_) => const DesktopKeyboardShortcutsPage(),
|
|
||||||
));
|
|
||||||
},
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
Expanded(
|
|
||||||
child: Text(translate('Configure shortcuts...')),
|
|
||||||
),
|
|
||||||
Icon(Icons.arrow_forward_ios,
|
|
||||||
size: 16, color: disabledTextColor(context, true))
|
|
||||||
.marginOnly(right: 4),
|
|
||||||
],
|
|
||||||
).marginOnly(
|
|
||||||
left: _kCheckBoxLeftMargin,
|
|
||||||
top: 6,
|
|
||||||
bottom: 6,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//#endregion
|
//#endregion
|
||||||
|
|
||||||
//#region dialogs
|
//#region dialogs
|
||||||
|
|||||||
@@ -62,15 +62,12 @@ class _InstallPageBody extends StatefulWidget {
|
|||||||
|
|
||||||
class _InstallPageBodyState extends State<_InstallPageBody>
|
class _InstallPageBodyState extends State<_InstallPageBody>
|
||||||
with WindowListener {
|
with WindowListener {
|
||||||
static const _printerStatusTimeout = Duration(seconds: 5);
|
|
||||||
|
|
||||||
late final TextEditingController controller;
|
late final TextEditingController controller;
|
||||||
final RxBool startmenu = true.obs;
|
final RxBool startmenu = true.obs;
|
||||||
final RxBool desktopicon = true.obs;
|
final RxBool desktopicon = true.obs;
|
||||||
final RxBool printer = false.obs;
|
final RxBool printer = false.obs;
|
||||||
final RxBool showProgress = false.obs;
|
final RxBool showProgress = false.obs;
|
||||||
final RxBool btnEnabled = true.obs;
|
final RxBool btnEnabled = true.obs;
|
||||||
final RxBool cancelEnabled = true.obs;
|
|
||||||
|
|
||||||
// todo move to theme.
|
// todo move to theme.
|
||||||
final buttonStyle = OutlinedButton.styleFrom(
|
final buttonStyle = OutlinedButton.styleFrom(
|
||||||
@@ -86,33 +83,10 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
|||||||
printer.value = installOptions['PRINTER'] == '1';
|
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
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
windowManager.addListener(this);
|
windowManager.addListener(this);
|
||||||
super.initState();
|
super.initState();
|
||||||
if (printer.value) {
|
|
||||||
_loadPrinterStatus();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -243,9 +217,8 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
|||||||
() => OutlinedButton.icon(
|
() => OutlinedButton.icon(
|
||||||
icon: Icon(Icons.close_rounded, size: 16),
|
icon: Icon(Icons.close_rounded, size: 16),
|
||||||
label: Text(translate('Cancel')),
|
label: Text(translate('Cancel')),
|
||||||
onPressed: cancelEnabled.value
|
onPressed:
|
||||||
? () => windowManager.close()
|
btnEnabled.value ? () => windowManager.close() : null,
|
||||||
: null,
|
|
||||||
style: buttonStyle,
|
style: buttonStyle,
|
||||||
).marginOnly(right: 10),
|
).marginOnly(right: 10),
|
||||||
),
|
),
|
||||||
@@ -280,7 +253,6 @@ class _InstallPageBodyState extends State<_InstallPageBody>
|
|||||||
void install() {
|
void install() {
|
||||||
do_install() {
|
do_install() {
|
||||||
btnEnabled.value = false;
|
btnEnabled.value = false;
|
||||||
cancelEnabled.value = false;
|
|
||||||
showProgress.value = true;
|
showProgress.value = true;
|
||||||
String args = '';
|
String args = '';
|
||||||
if (startmenu.value) args += ' startmenu';
|
if (startmenu.value) args += ' startmenu';
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import '../../common/widgets/toolbar.dart';
|
|||||||
import '../../models/model.dart';
|
import '../../models/model.dart';
|
||||||
import '../../models/input_model.dart';
|
import '../../models/input_model.dart';
|
||||||
import '../../models/platform_model.dart';
|
import '../../models/platform_model.dart';
|
||||||
import '../../models/shortcut_model.dart';
|
|
||||||
import '../../common/shared_state.dart';
|
import '../../common/shared_state.dart';
|
||||||
import '../../utils/image.dart';
|
import '../../utils/image.dart';
|
||||||
import '../widgets/remote_toolbar.dart';
|
import '../widgets/remote_toolbar.dart';
|
||||||
@@ -163,18 +162,6 @@ class _RemotePageState extends State<RemotePage>
|
|||||||
_ffi.ffiModel.pi.platform, _ffi.dialogManager);
|
_ffi.ffiModel.pi.platform, _ffi.dialogManager);
|
||||||
_ffi.recordingModel
|
_ffi.recordingModel
|
||||||
.updateStatus(bind.sessionGetIsRecording(sessionId: _ffi.sessionId));
|
.updateStatus(bind.sessionGetIsRecording(sessionId: _ffi.sessionId));
|
||||||
// Seed shortcut action callbacks once the session is ready, so that
|
|
||||||
// global keyboard shortcuts work even if the user never opens the
|
|
||||||
// toolbar menu. The returned list is intentionally discarded — the
|
|
||||||
// side effect of registering callbacks (inside toolbarControls) is
|
|
||||||
// what we want here.
|
|
||||||
if (mounted) {
|
|
||||||
toolbarControls(context, widget.id, _ffi);
|
|
||||||
registerSessionShortcutActions(_ffi,
|
|
||||||
tabController: widget.tabController,
|
|
||||||
toolbarState: widget.toolbarState);
|
|
||||||
registerToolbarShortcuts(context, widget.id, _ffi);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
_ffi.canvasModel.initializeEdgeScrollFallback(this);
|
_ffi.canvasModel.initializeEdgeScrollFallback(this);
|
||||||
_ffi.start(
|
_ffi.start(
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:flutter_hbb/common/widgets/audio_input.dart';
|
import 'package:flutter_hbb/common/widgets/audio_input.dart';
|
||||||
import 'package:flutter_hbb/common/widgets/dialog.dart';
|
import 'package:flutter_hbb/common/widgets/dialog.dart';
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/display.dart';
|
|
||||||
import 'package:flutter_hbb/common/widgets/toolbar.dart';
|
import 'package:flutter_hbb/common/widgets/toolbar.dart';
|
||||||
import 'package:flutter_hbb/models/chat_model.dart';
|
import 'package:flutter_hbb/models/chat_model.dart';
|
||||||
import 'package:flutter_hbb/models/state_model.dart';
|
import 'package:flutter_hbb/models/state_model.dart';
|
||||||
@@ -1319,35 +1318,8 @@ class _ControlMenu extends StatelessWidget {
|
|||||||
if (e.divider) {
|
if (e.divider) {
|
||||||
return Divider();
|
return Divider();
|
||||||
} else {
|
} else {
|
||||||
final hint = e.actionId == null
|
|
||||||
? null
|
|
||||||
: ShortcutDisplay.formatFor(e.actionId!);
|
|
||||||
final child = hint == null
|
|
||||||
? e.child
|
|
||||||
: Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Flexible(child: e.child),
|
|
||||||
Flexible(
|
|
||||||
child: Padding(
|
|
||||||
padding: const EdgeInsets.only(left: 16),
|
|
||||||
child: Text(
|
|
||||||
hint,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: Theme.of(context)
|
|
||||||
.textTheme
|
|
||||||
.bodySmall
|
|
||||||
?.copyWith(
|
|
||||||
color: Theme.of(context).hintColor,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
return MenuButton(
|
return MenuButton(
|
||||||
child: child,
|
child: e.child,
|
||||||
onPressed: e.onPressed,
|
onPressed: e.onPressed,
|
||||||
ffi: ffi,
|
ffi: ffi,
|
||||||
trailingIcon: e.trailingIcon);
|
trailingIcon: e.trailingIcon);
|
||||||
|
|||||||
@@ -418,13 +418,6 @@ 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
|
@override
|
||||||
void onWindowMoved() {
|
void onWindowMoved() {
|
||||||
_saveFrame();
|
_saveFrame();
|
||||||
@@ -472,8 +465,6 @@ class _DesktopTabState extends State<DesktopTab>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await _isLinuxWindowClosed()) return;
|
|
||||||
|
|
||||||
await _saveFrame(flush: true);
|
await _saveFrame(flush: true);
|
||||||
|
|
||||||
// hide window on close
|
// hide window on close
|
||||||
@@ -481,7 +472,6 @@ class _DesktopTabState extends State<DesktopTab>
|
|||||||
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
|
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
|
||||||
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
|
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
|
||||||
}
|
}
|
||||||
if (await _isLinuxWindowClosed()) return;
|
|
||||||
// macOS specific workaround, the window is not hiding when in fullscreen.
|
// macOS specific workaround, the window is not hiding when in fullscreen.
|
||||||
if (isMacOS && await windowManager.isFullScreen()) {
|
if (isMacOS && await windowManager.isFullScreen()) {
|
||||||
await windowManager.setFullScreen(false);
|
await windowManager.setFullScreen(false);
|
||||||
|
|||||||
@@ -7,49 +7,36 @@ import 'package:flutter_hbb/models/platform_model.dart';
|
|||||||
import 'package:get/get.dart';
|
import 'package:get/get.dart';
|
||||||
import 'package:url_launcher/url_launcher.dart';
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
|
||||||
const _eventKeyUpdateMe = 'update-me';
|
final _isExtracting = false.obs;
|
||||||
|
|
||||||
Future<void> _handleUpdateMe(
|
void handleUpdate(String releasePageUrl) {
|
||||||
String releasePageUrl, Map<String, dynamic> evt) async {
|
_isExtracting.value = false;
|
||||||
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
|
String downloadUrl = releasePageUrl.replaceAll('tag', 'download');
|
||||||
if (evt.containsKey('error')) {
|
String version = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
|
||||||
_showUpdateError(releasePageUrl, evt['error'] as String);
|
final String downloadFile =
|
||||||
}
|
bind.mainGetCommonSync(key: 'download-file-$version');
|
||||||
}
|
if (downloadFile.startsWith('error:')) {
|
||||||
|
final error = downloadFile.replaceFirst('error:', '');
|
||||||
Future<void> handleUpdate(String releasePageUrl) async {
|
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
|
||||||
final dialogClosed = _showVerifyingUpdate();
|
releasePageUrl, gFFI.dialogManager);
|
||||||
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;
|
return;
|
||||||
}
|
}
|
||||||
|
downloadUrl = '$downloadUrl/$downloadFile';
|
||||||
|
|
||||||
SimpleWrapper downloadId = SimpleWrapper('');
|
SimpleWrapper downloadId = SimpleWrapper('');
|
||||||
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
|
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
|
||||||
gFFI.dialogManager.dismissAll();
|
gFFI.dialogManager.dismissAll();
|
||||||
gFFI.dialogManager.show((setState, close, context) {
|
gFFI.dialogManager.show((setState, close, context) {
|
||||||
return CustomAlertDialog(
|
return CustomAlertDialog(
|
||||||
title: Text(translate('Downloading {$appName}')),
|
title: Obx(() => Text(translate(_isExtracting.isTrue
|
||||||
content: UpdateProgress(
|
? 'Preparing for installation ...'
|
||||||
releasePageUrl, verifiedDownloadUrl, downloadId, onCanceled)
|
: 'Downloading {$appName}'))),
|
||||||
.marginSymmetric(horizontal: 8)
|
content:
|
||||||
.paddingOnly(top: 12),
|
UpdateProgress(releasePageUrl, downloadUrl, downloadId, onCanceled)
|
||||||
|
.marginSymmetric(horizontal: 8)
|
||||||
|
.paddingOnly(top: 12),
|
||||||
actions: [
|
actions: [
|
||||||
dialogButton('Cancel', onPressed: () async {
|
if (_isExtracting.isFalse) dialogButton(translate('Cancel'), onPressed: () async {
|
||||||
onCanceled.value();
|
onCanceled.value();
|
||||||
await bind.mainSetCommon(
|
await bind.mainSetCommon(
|
||||||
key: 'cancel-downloader', value: downloadId.value);
|
key: 'cancel-downloader', value: downloadId.value);
|
||||||
@@ -69,40 +56,6 @@ Future<void> handleUpdate(String releasePageUrl) async {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
class UpdateProgress extends StatefulWidget {
|
||||||
final String releasePageUrl;
|
final String releasePageUrl;
|
||||||
final String downloadUrl;
|
final String downloadUrl;
|
||||||
@@ -121,9 +74,9 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
Timer? _timer;
|
Timer? _timer;
|
||||||
int? _totalSize;
|
int? _totalSize;
|
||||||
int _downloadedSize = 0;
|
int _downloadedSize = 0;
|
||||||
bool _downloadFinished = false;
|
|
||||||
int _getDataFailedCount = 0;
|
int _getDataFailedCount = 0;
|
||||||
final String _eventKeyDownloadNewVersion = 'download-new-version';
|
final String _eventKeyDownloadNewVersion = 'download-new-version';
|
||||||
|
final String _eventKeyExtractUpdateDmg = 'extract-update-dmg';
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -135,6 +88,11 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
|
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
|
||||||
replace: true);
|
replace: true);
|
||||||
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
|
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
|
||||||
|
if (isMacOS) {
|
||||||
|
platformFFI.registerEventHandler(_eventKeyExtractUpdateDmg,
|
||||||
|
_eventKeyExtractUpdateDmg, handleExtractUpdateDmg,
|
||||||
|
replace: true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -142,7 +100,10 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
cancelQueryTimer();
|
cancelQueryTimer();
|
||||||
platformFFI.unregisterEventHandler(
|
platformFFI.unregisterEventHandler(
|
||||||
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
|
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
|
||||||
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
|
if (isMacOS) {
|
||||||
|
platformFFI.unregisterEventHandler(
|
||||||
|
_eventKeyExtractUpdateDmg, _eventKeyExtractUpdateDmg);
|
||||||
|
}
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,33 +128,35 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onError(String error) {
|
// `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}) {
|
||||||
cancelQueryTimer();
|
cancelQueryTimer();
|
||||||
|
|
||||||
debugPrint('Download new version error: $error');
|
debugPrint(
|
||||||
|
'${isExtractDmg ? "Extract" : "Download"} new version error: $error');
|
||||||
final msgBoxType = 'custom-nocancel-nook-hasclose';
|
final msgBoxType = 'custom-nocancel-nook-hasclose';
|
||||||
final msgBoxTitle = 'Error';
|
final msgBoxTitle = 'Error';
|
||||||
final msgBoxText = 'download-new-version-failed-tip';
|
final msgBoxText = 'download-new-version-failed-tip';
|
||||||
final dialogManager = gFFI.dialogManager;
|
final dialogManager = gFFI.dialogManager;
|
||||||
final releasePageUrl = widget.releasePageUrl;
|
|
||||||
|
|
||||||
close() {
|
close() {
|
||||||
dialogManager.dismissAll();
|
dialogManager.dismissAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
jumplink() {
|
jumplink() {
|
||||||
launchUrl(Uri.parse(releasePageUrl));
|
launchUrl(Uri.parse(widget.releasePageUrl));
|
||||||
dialogManager.dismissAll();
|
dialogManager.dismissAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
retry() {
|
retry() {
|
||||||
dialogManager.dismissAll();
|
dialogManager.dismissAll();
|
||||||
handleUpdate(releasePageUrl);
|
handleUpdate(widget.releasePageUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
final List<Widget> buttons = [
|
final List<Widget> buttons = [
|
||||||
dialogButton('Download', onPressed: jumplink),
|
dialogButton('Download', onPressed: jumplink),
|
||||||
dialogButton('Retry', onPressed: retry),
|
if (!isExtractDmg) dialogButton('Retry', onPressed: retry),
|
||||||
dialogButton('Close', onPressed: close),
|
dialogButton('Close', onPressed: close),
|
||||||
];
|
];
|
||||||
dialogManager.dismissAll();
|
dialogManager.dismissAll();
|
||||||
@@ -223,8 +186,6 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
}
|
}
|
||||||
} else if (key == 'downloaded_size') {
|
} else if (key == 'downloaded_size') {
|
||||||
_downloadedSize = value as int;
|
_downloadedSize = value as int;
|
||||||
} else if (key == 'finished') {
|
|
||||||
_downloadFinished = value as bool;
|
|
||||||
} else if (key == 'error') {
|
} else if (key == 'error') {
|
||||||
if (value != null) {
|
if (value != null) {
|
||||||
err = value.toString();
|
err = value.toString();
|
||||||
@@ -243,9 +204,7 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
if (err != '') {
|
if (err != '') {
|
||||||
_onError(err);
|
_onError(err);
|
||||||
} else {
|
} else {
|
||||||
if (_downloadFinished &&
|
if (_totalSize != null && _downloadedSize >= _totalSize!) {
|
||||||
_totalSize != null &&
|
|
||||||
_downloadedSize >= _totalSize!) {
|
|
||||||
cancelQueryTimer();
|
cancelQueryTimer();
|
||||||
bind.mainSetCommon(
|
bind.mainSetCommon(
|
||||||
key: 'remove-downloader', value: widget.downloadId.value);
|
key: 'remove-downloader', value: widget.downloadId.value);
|
||||||
@@ -253,7 +212,13 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
_onError('The download file size is 0.');
|
_onError('The download file size is 0.');
|
||||||
} else {
|
} else {
|
||||||
setState(() {});
|
setState(() {});
|
||||||
updateMsgBox();
|
if (isMacOS) {
|
||||||
|
bind.mainSetCommon(
|
||||||
|
key: 'extract-update-dmg', value: widget.downloadUrl);
|
||||||
|
_isExtracting.value = true;
|
||||||
|
} else {
|
||||||
|
updateMsgBox();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setState(() {});
|
setState(() {});
|
||||||
@@ -262,8 +227,6 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void updateMsgBox() {
|
void updateMsgBox() {
|
||||||
final releasePageUrl = widget.releasePageUrl;
|
|
||||||
final downloadUrl = widget.downloadUrl;
|
|
||||||
msgBox(
|
msgBox(
|
||||||
gFFI.sessionId,
|
gFFI.sessionId,
|
||||||
'custom-nocancel',
|
'custom-nocancel',
|
||||||
@@ -271,30 +234,30 @@ class UpdateProgressState extends State<UpdateProgress> {
|
|||||||
'{$appName}-to-update-tip',
|
'{$appName}-to-update-tip',
|
||||||
'',
|
'',
|
||||||
gFFI.dialogManager,
|
gFFI.dialogManager,
|
||||||
onSubmit: () async {
|
onSubmit: () {
|
||||||
debugPrint('Downloaded, update to new version now');
|
debugPrint('Downloaded, update to new version now');
|
||||||
platformFFI.registerEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe,
|
bind.mainSetCommon(key: 'update-me', value: widget.downloadUrl);
|
||||||
(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,
|
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
getValue() => _totalSize == null
|
getValue() => _totalSize == null
|
||||||
? 0.0
|
? 0.0
|
||||||
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
|
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
|
||||||
return LinearProgressIndicator(
|
return LinearProgressIndicator(
|
||||||
value: getValue(),
|
value: _isExtracting.isTrue ? null : getValue(),
|
||||||
minHeight: 20,
|
minHeight: 20,
|
||||||
borderRadius: BorderRadius.circular(5),
|
borderRadius: BorderRadius.circular(5),
|
||||||
backgroundColor: Colors.grey[300],
|
backgroundColor: Colors.grey[300],
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
// flutter/lib/mobile/pages/mobile_keyboard_shortcuts_page.dart
|
|
||||||
//
|
|
||||||
// Mobile shell for the Keyboard Shortcuts configuration page. Mirrors
|
|
||||||
// `desktop/pages/desktop_keyboard_shortcuts_page.dart` but with a touch-
|
|
||||||
// friendly layout (ListTile rows instead of dense rows) and a hint banner
|
|
||||||
// that explains the recording flow only works with a physical keyboard.
|
|
||||||
//
|
|
||||||
// All actual logic — group definitions, JSON I/O, conflict-replace flow,
|
|
||||||
// recording-dialog round-trip, "Reset to defaults" — lives in the shared
|
|
||||||
// `common/widgets/keyboard_shortcuts/page_body.dart`. This file only
|
|
||||||
// supplies the AppBar, the AppBar action, and the platform hint banner.
|
|
||||||
//
|
|
||||||
// Mobile keyboard detection limitation: Flutter has no reliable
|
|
||||||
// "is a physical keyboard attached?" API on iOS or Android. Soft keyboards
|
|
||||||
// don't generate the `KeyDownEvent`s the recording dialog listens for, so
|
|
||||||
// in practice the dialog only does anything useful when the user actually
|
|
||||||
// has a hardware keyboard plugged in (USB / Bluetooth / Smart Connector).
|
|
||||||
// For V1 we don't try to detect attachment — we just surface the
|
|
||||||
// requirement as an in-page hint instead of disabling the Edit button.
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
|
||||||
|
|
||||||
import '../../common.dart';
|
|
||||||
import '../../common/widgets/keyboard_shortcuts/page_body.dart';
|
|
||||||
|
|
||||||
class MobileKeyboardShortcutsPage extends StatefulWidget {
|
|
||||||
const MobileKeyboardShortcutsPage({Key? key}) : super(key: key);
|
|
||||||
|
|
||||||
@override
|
|
||||||
State<MobileKeyboardShortcutsPage> createState() =>
|
|
||||||
_MobileKeyboardShortcutsPageState();
|
|
||||||
}
|
|
||||||
|
|
||||||
class _MobileKeyboardShortcutsPageState
|
|
||||||
extends State<MobileKeyboardShortcutsPage> {
|
|
||||||
final GlobalKey<KeyboardShortcutsPageBodyState> _bodyKey = GlobalKey();
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final theme = Theme.of(context);
|
|
||||||
return Scaffold(
|
|
||||||
appBar: AppBar(
|
|
||||||
title: Text(translate('Keyboard shortcuts')),
|
|
||||||
actions: [
|
|
||||||
IconButton(
|
|
||||||
tooltip: translate('Reset to defaults'),
|
|
||||||
onPressed: () =>
|
|
||||||
_bodyKey.currentState?.resetToDefaultsWithConfirm(),
|
|
||||||
icon: const Icon(Icons.restore),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
body: KeyboardShortcutsPageBody(
|
|
||||||
key: _bodyKey,
|
|
||||||
compact: false,
|
|
||||||
editButtonHint: translate('shortcut-mobile-physical-keyboard-tip'),
|
|
||||||
headerBanner: _PhysicalKeyboardHintBanner(theme: theme),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A muted info banner shown above the master toggle on mobile. We can't
|
|
||||||
/// reliably detect whether a physical keyboard is attached, so instead of
|
|
||||||
/// disabling the Edit button we surface the requirement up front.
|
|
||||||
class _PhysicalKeyboardHintBanner extends StatelessWidget {
|
|
||||||
final ThemeData theme;
|
|
||||||
const _PhysicalKeyboardHintBanner({required this.theme});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
final color = theme.colorScheme.primary.withOpacity(0.08);
|
|
||||||
return Container(
|
|
||||||
padding: const EdgeInsets.all(12),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: color,
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Row(
|
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
|
||||||
Icon(Icons.info_outline,
|
|
||||||
size: 18, color: theme.colorScheme.primary),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
translate('shortcut-mobile-physical-keyboard-tip'),
|
|
||||||
style: TextStyle(color: theme.colorScheme.onSurface),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,6 @@ import '../../common/widgets/remote_input.dart';
|
|||||||
import '../../models/input_model.dart';
|
import '../../models/input_model.dart';
|
||||||
import '../../models/model.dart';
|
import '../../models/model.dart';
|
||||||
import '../../models/platform_model.dart';
|
import '../../models/platform_model.dart';
|
||||||
import '../../models/shortcut_model.dart';
|
|
||||||
import '../../utils/image.dart';
|
import '../../utils/image.dart';
|
||||||
import '../widgets/dialog.dart';
|
import '../widgets/dialog.dart';
|
||||||
import '../widgets/custom_scale_widget.dart';
|
import '../widgets/custom_scale_widget.dart';
|
||||||
@@ -41,32 +40,6 @@ void _disableAndroidSoftKeyboard({bool? isKeyboardVisible}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool handleMobileLocalKeyEvent(KeyEvent event,
|
|
||||||
{required bool remoteFocused, required InputModel inputModel}) {
|
|
||||||
if (event is KeyUpEvent && inputModel.isViewOnly) {
|
|
||||||
// View-only skips normal modifier cleanup; stale physical keys would
|
|
||||||
// otherwise look like touch selections in the input helper.
|
|
||||||
inputModel.handleKeyUpEventModifiers(event);
|
|
||||||
}
|
|
||||||
if (!remoteFocused &&
|
|
||||||
event is KeyUpEvent &&
|
|
||||||
const [
|
|
||||||
PhysicalKeyboardKey.controlLeft,
|
|
||||||
PhysicalKeyboardKey.controlRight,
|
|
||||||
PhysicalKeyboardKey.altLeft,
|
|
||||||
PhysicalKeyboardKey.altRight,
|
|
||||||
PhysicalKeyboardKey.shiftLeft,
|
|
||||||
PhysicalKeyboardKey.shiftRight,
|
|
||||||
PhysicalKeyboardKey.metaLeft,
|
|
||||||
PhysicalKeyboardKey.metaRight,
|
|
||||||
].contains(event.physicalKey)) {
|
|
||||||
// Local UI may consume key-ups while the remote input path still owns
|
|
||||||
// the modifiers pressed before focus moved.
|
|
||||||
inputModel.handleKeyEvent(event);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
class RemotePage extends StatefulWidget {
|
class RemotePage extends StatefulWidget {
|
||||||
RemotePage(
|
RemotePage(
|
||||||
{Key? key,
|
{Key? key,
|
||||||
@@ -134,7 +107,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
});
|
});
|
||||||
WakelockManager.enable(_uniqueKey);
|
WakelockManager.enable(_uniqueKey);
|
||||||
_physicalFocusNode.requestFocus();
|
_physicalFocusNode.requestFocus();
|
||||||
HardwareKeyboard.instance.addHandler(_handleLocalKeyEvent);
|
|
||||||
gFFI.inputModel.listenToMouse(true);
|
gFFI.inputModel.listenToMouse(true);
|
||||||
gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId);
|
gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId);
|
||||||
keyboardSubscription =
|
keyboardSubscription =
|
||||||
@@ -150,19 +122,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
}
|
}
|
||||||
_disableAndroidSoftKeyboard(
|
_disableAndroidSoftKeyboard(
|
||||||
isKeyboardVisible: keyboardVisibilityController.isVisible);
|
isKeyboardVisible: keyboardVisibilityController.isVisible);
|
||||||
// Seed shortcut action callbacks once the session is ready, so that
|
|
||||||
// global keyboard shortcuts work even if the user never opens the
|
|
||||||
// toolbar menu. The returned list is intentionally discarded — the
|
|
||||||
// side effect of registering callbacks (inside toolbarControls) is
|
|
||||||
// what we want here.
|
|
||||||
if (mounted) {
|
|
||||||
toolbarControls(context, widget.id, gFFI);
|
|
||||||
// Mobile has no DesktopTabController, so tab-switch shortcuts will
|
|
||||||
// log a no-handler debug line if a user binds one.
|
|
||||||
registerSessionShortcutActions(gFFI);
|
|
||||||
_registerMobileChatShortcut();
|
|
||||||
registerToolbarShortcuts(context, widget.id, gFFI);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
|
|
||||||
@@ -183,7 +142,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> dispose() async {
|
Future<void> dispose() async {
|
||||||
HardwareKeyboard.instance.removeHandler(_handleLocalKeyEvent);
|
|
||||||
WidgetsBinding.instance.removeObserver(this);
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
// Close the session up-front. `gFFI.close()` below only calls `sessionClose`
|
// Close the session up-front. `gFFI.close()` below only calls `sessionClose`
|
||||||
// after several awaits (canvas save, image update, the `enable_soft_keyboard`
|
// after several awaits (canvas save, image update, the `enable_soft_keyboard`
|
||||||
@@ -295,10 +253,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
if (isIOS) {
|
if (isIOS) {
|
||||||
_iosKeyboardWorkaroundTimer?.cancel();
|
_iosKeyboardWorkaroundTimer?.cancel();
|
||||||
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 100), () {
|
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 100), () {
|
||||||
if (!mounted || gFFI.chatModel.inputNode.hasFocus) return;
|
if (!mounted) return;
|
||||||
_physicalFocusNode.unfocus();
|
_physicalFocusNode.unfocus();
|
||||||
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 50), () {
|
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 50), () {
|
||||||
if (!mounted || gFFI.chatModel.inputNode.hasFocus) return;
|
if (!mounted) return;
|
||||||
_physicalFocusNode.requestFocus();
|
_physicalFocusNode.requestFocus();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -377,10 +335,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
// clipboard
|
// clipboard
|
||||||
oldValue = '';
|
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) {
|
if (newValue.length == oldValue.length) {
|
||||||
// ?
|
// ?
|
||||||
} else if (newValue.length < oldValue.length) {
|
} else if (newValue.length < oldValue.length) {
|
||||||
@@ -580,9 +534,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _handleLocalKeyEvent(KeyEvent event) => handleMobileLocalKeyEvent(event,
|
|
||||||
remoteFocused: _physicalFocusNode.hasPrimaryFocus, inputModel: inputModel);
|
|
||||||
|
|
||||||
Widget getRawPointerAndKeyBody(Widget child) {
|
Widget getRawPointerAndKeyBody(Widget child) {
|
||||||
final ffiModel = Provider.of<FfiModel>(context);
|
final ffiModel = Provider.of<FfiModel>(context);
|
||||||
return RawPointerMouseRegion(
|
return RawPointerMouseRegion(
|
||||||
@@ -704,6 +655,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
!gFFI.inputModel.relativeMouseMode.value;
|
!gFFI.inputModel.relativeMouseMode.value;
|
||||||
|
|
||||||
Widget getBodyForMobile() {
|
Widget getBodyForMobile() {
|
||||||
|
final keyboardIsVisible = keyboardVisibilityController.isVisible;
|
||||||
return Container(
|
return Container(
|
||||||
color: MyTheme.canvasColor,
|
color: MyTheme.canvasColor,
|
||||||
child: Stack(children: () {
|
child: Stack(children: () {
|
||||||
@@ -714,14 +666,9 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
right: 10,
|
right: 10,
|
||||||
child: QualityMonitor(gFFI.qualityMonitorModel),
|
child: QualityMonitor(gFFI.qualityMonitorModel),
|
||||||
),
|
),
|
||||||
Obx(() {
|
KeyHelpTools(
|
||||||
final chatKeyboardRequested =
|
keyboardIsVisible: keyboardIsVisible,
|
||||||
gFFI.chatModel.softKeyboardRequested.value;
|
showGestureHelp: _showGestureHelp),
|
||||||
return KeyHelpTools(
|
|
||||||
keyboardIsVisible: keyboardVisibilityController.isVisible &&
|
|
||||||
(_showEdit || chatKeyboardRequested),
|
|
||||||
showGestureHelp: _showGestureHelp);
|
|
||||||
}),
|
|
||||||
SizedBox(
|
SizedBox(
|
||||||
width: 0,
|
width: 0,
|
||||||
height: 0,
|
height: 0,
|
||||||
@@ -858,18 +805,9 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
|
|||||||
}();
|
}();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _registerMobileChatShortcut() {
|
onPressedTextChat(String id) {
|
||||||
if (!isMobile) return;
|
|
||||||
gFFI.shortcutModel.register(kShortcutActionToggleChat,
|
|
||||||
() => onPressedTextChat(widget.id, requestSoftKeyboard: false));
|
|
||||||
}
|
|
||||||
|
|
||||||
onPressedTextChat(String id, {bool requestSoftKeyboard = true}) {
|
|
||||||
if (gFFI.chatModel.chatWindowOverlayEntry == null) {
|
|
||||||
setState(() => _showEdit = false);
|
|
||||||
}
|
|
||||||
gFFI.chatModel.changeCurrentKey(MessageKey(id, ChatModel.clientModeID));
|
gFFI.chatModel.changeCurrentKey(MessageKey(id, ChatModel.clientModeID));
|
||||||
gFFI.chatModel.toggleChatOverlay(requestSoftKeyboard: requestSoftKeyboard);
|
gFFI.chatModel.toggleChatOverlay();
|
||||||
}
|
}
|
||||||
|
|
||||||
showChatOptions(String id) async {
|
showChatOptions(String id) async {
|
||||||
@@ -1037,13 +975,12 @@ class _KeyHelpToolsState extends State<KeyHelpTools> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final keyboard = HardwareKeyboard.instance;
|
final hasModifierOn = inputModel.ctrl ||
|
||||||
// Keep touch selections visible without physical modifiers opening the bar.
|
inputModel.alt ||
|
||||||
final hasTouchModifier = (inputModel.ctrl && !keyboard.isControlPressed) ||
|
inputModel.shift ||
|
||||||
(inputModel.alt && !keyboard.isAltPressed) ||
|
inputModel.command;
|
||||||
(inputModel.shift && !keyboard.isShiftPressed) ||
|
|
||||||
(inputModel.command && !keyboard.isMetaPressed);
|
if (!_pin && !hasModifierOn && !widget.requestShow) {
|
||||||
if (!_pin && !hasTouchModifier && !widget.requestShow) {
|
|
||||||
gFFI.cursorModel
|
gFFI.cursorModel
|
||||||
.keyHelpToolsVisibilityChanged(null, widget.keyboardIsVisible);
|
.keyHelpToolsVisibilityChanged(null, widget.keyboardIsVisible);
|
||||||
return Offstage();
|
return Offstage();
|
||||||
|
|||||||
@@ -18,10 +18,8 @@ import '../../consts.dart';
|
|||||||
import '../../models/model.dart';
|
import '../../models/model.dart';
|
||||||
import '../../models/platform_model.dart';
|
import '../../models/platform_model.dart';
|
||||||
import '../widgets/deploy_dialog.dart';
|
import '../widgets/deploy_dialog.dart';
|
||||||
import '../../models/shortcut_model.dart';
|
|
||||||
import '../widgets/dialog.dart';
|
import '../widgets/dialog.dart';
|
||||||
import 'home_page.dart';
|
import 'home_page.dart';
|
||||||
import 'mobile_keyboard_shortcuts_page.dart';
|
|
||||||
import 'scan_page.dart';
|
import 'scan_page.dart';
|
||||||
|
|
||||||
class SettingsPage extends StatefulWidget implements PageShape {
|
class SettingsPage extends StatefulWidget implements PageShape {
|
||||||
@@ -899,24 +897,6 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
|
|||||||
showThemeSettings(gFFI.dialogManager);
|
showThemeSettings(gFFI.dialogManager);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
if (!disabledSettings)
|
|
||||||
SettingsTile.navigation(
|
|
||||||
leading: Icon(Icons.keyboard_outlined),
|
|
||||||
title: Text(translate('Keyboard shortcuts')),
|
|
||||||
description: Text(ShortcutModel.isEnabled()
|
|
||||||
? translate('On')
|
|
||||||
: translate('Off')),
|
|
||||||
trailing: Icon(Icons.arrow_forward_ios),
|
|
||||||
onPressed: (context) {
|
|
||||||
Navigator.push(
|
|
||||||
context,
|
|
||||||
MaterialPageRoute(
|
|
||||||
builder: (_) => const MobileKeyboardShortcutsPage(),
|
|
||||||
)).then((_) {
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
});
|
|
||||||
},
|
|
||||||
),
|
|
||||||
if (!bind.isDisableAccount())
|
if (!bind.isDisableAccount())
|
||||||
SettingsTile.switchTile(
|
SettingsTile.switchTile(
|
||||||
title: Text(translate('note-at-conn-end-tip')),
|
title: Text(translate('note-at-conn-end-tip')),
|
||||||
|
|||||||
@@ -11,3 +11,10 @@ const terminalKeyboardKeySpacing = 2.0;
|
|||||||
|
|
||||||
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
|
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
|
||||||
const terminalKeyboardRow3TrailingPlaceholderCount = 2;
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -372,8 +372,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
Offset _position = Offset.zero;
|
Offset _position = Offset.zero;
|
||||||
bool _isInitialized = false;
|
bool _isInitialized = false;
|
||||||
bool _isDown = false;
|
bool _isDown = false;
|
||||||
Object? _activePress;
|
|
||||||
bool _remoteButtonDown = false;
|
|
||||||
Rect? _lastBlockedRect;
|
Rect? _lastBlockedRect;
|
||||||
|
|
||||||
Orientation? _previousOrientation;
|
Orientation? _previousOrientation;
|
||||||
@@ -400,11 +398,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_activePress = null;
|
|
||||||
if (_remoteButtonDown) {
|
|
||||||
_remoteButtonDown = false;
|
|
||||||
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
|
||||||
}
|
|
||||||
if (_lastBlockedRect != null) {
|
if (_lastBlockedRect != null) {
|
||||||
_cursorModel.removeBlockedRect(_lastBlockedRect!);
|
_cursorModel.removeBlockedRect(_lastBlockedRect!);
|
||||||
}
|
}
|
||||||
@@ -576,8 +569,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
child: Listener(
|
child: Listener(
|
||||||
onPointerMove: _onBodyPointerMoveUpdate,
|
onPointerMove: _onBodyPointerMoveUpdate,
|
||||||
onPointerDown: (event) async {
|
onPointerDown: (event) async {
|
||||||
final press = Object();
|
|
||||||
_activePress = press;
|
|
||||||
_isDragging = false;
|
_isDragging = false;
|
||||||
setState(() {
|
setState(() {
|
||||||
_isDown = true;
|
_isDown = true;
|
||||||
@@ -588,8 +579,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
isSpecialHoldDragActive = true;
|
isSpecialHoldDragActive = true;
|
||||||
() async {
|
() async {
|
||||||
await _cursorModel.syncCursorPosition();
|
await _cursorModel.syncCursorPosition();
|
||||||
if (!mounted || !identical(_activePress, press)) return;
|
|
||||||
_remoteButtonDown = true;
|
|
||||||
await _inputModel
|
await _inputModel
|
||||||
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
|
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||||
}();
|
}();
|
||||||
@@ -597,8 +586,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
onPointerUp: (event) {
|
onPointerUp: (event) {
|
||||||
if (!mounted) return;
|
|
||||||
_activePress = null;
|
|
||||||
_cursorModel.blockEvents = false;
|
_cursorModel.blockEvents = false;
|
||||||
setState(() {
|
setState(() {
|
||||||
_isDown = false;
|
_isDown = false;
|
||||||
@@ -617,8 +604,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
}));
|
}));
|
||||||
} else {
|
} else {
|
||||||
// If it's not a quick tap, it could be a hold or drag.
|
// If it's not a quick tap, it could be a hold or drag.
|
||||||
if (_remoteButtonDown) {
|
// If it was a hold, isSpecialHoldDragActive is true.
|
||||||
_remoteButtonDown = false;
|
if (isSpecialHoldDragActive) {
|
||||||
_inputModel
|
_inputModel
|
||||||
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||||
}
|
}
|
||||||
@@ -630,16 +617,13 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
|
|||||||
isSpecialHoldDragActive = false;
|
isSpecialHoldDragActive = false;
|
||||||
},
|
},
|
||||||
onPointerCancel: (event) {
|
onPointerCancel: (event) {
|
||||||
if (!mounted) return;
|
|
||||||
_activePress = null;
|
|
||||||
_cursorModel.blockEvents = false;
|
_cursorModel.blockEvents = false;
|
||||||
setState(() {
|
setState(() {
|
||||||
_isDown = false;
|
_isDown = false;
|
||||||
});
|
});
|
||||||
_tapDownTimer?.cancel();
|
_tapDownTimer?.cancel();
|
||||||
_tapDownTimer = null;
|
_tapDownTimer = null;
|
||||||
if (_remoteButtonDown) {
|
if (isSpecialHoldDragActive) {
|
||||||
_remoteButtonDown = false;
|
|
||||||
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
|
||||||
}
|
}
|
||||||
isSpecialHoldDragActive = false;
|
isSpecialHoldDragActive = false;
|
||||||
|
|||||||
@@ -64,11 +64,8 @@ class ChatModel with ChangeNotifier {
|
|||||||
RxBool isWindowFocus = true.obs;
|
RxBool isWindowFocus = true.obs;
|
||||||
BlockableOverlayState _blockableOverlayState = BlockableOverlayState();
|
BlockableOverlayState _blockableOverlayState = BlockableOverlayState();
|
||||||
final Rx<VoiceCallStatus> _voiceCallStatus = Rx(VoiceCallStatus.notStarted);
|
final Rx<VoiceCallStatus> _voiceCallStatus = Rx(VoiceCallStatus.notStarted);
|
||||||
final RxBool _softKeyboardRequested = false.obs;
|
|
||||||
bool _usingPhysicalChatInput = false;
|
|
||||||
|
|
||||||
Rx<VoiceCallStatus> get voiceCallStatus => _voiceCallStatus;
|
Rx<VoiceCallStatus> get voiceCallStatus => _voiceCallStatus;
|
||||||
RxBool get softKeyboardRequested => _softKeyboardRequested;
|
|
||||||
|
|
||||||
TextEditingController textController = TextEditingController();
|
TextEditingController textController = TextEditingController();
|
||||||
RxInt mobileUnreadSum = 0.obs;
|
RxInt mobileUnreadSum = 0.obs;
|
||||||
@@ -83,8 +80,6 @@ class ChatModel with ChangeNotifier {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
inputNode.removeListener(_updateChatInputControl);
|
|
||||||
_restoreChatInputControl();
|
|
||||||
textController.dispose();
|
textController.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
@@ -199,18 +194,13 @@ class ChatModel with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
showChatWindowOverlay(
|
showChatWindowOverlay({Offset? chatInitPos}) {
|
||||||
{Offset? chatInitPos, bool requestSoftKeyboard = true}) {
|
|
||||||
if (chatWindowOverlayEntry != null) return;
|
if (chatWindowOverlayEntry != null) return;
|
||||||
isWindowFocus.value = true;
|
isWindowFocus.value = true;
|
||||||
_blockableOverlayState.setMiddleBlocked(true);
|
_blockableOverlayState.setMiddleBlocked(true);
|
||||||
|
|
||||||
final overlayState = _blockableOverlayState.state;
|
final overlayState = _blockableOverlayState.state;
|
||||||
if (overlayState == null) return;
|
if (overlayState == null) return;
|
||||||
if (isMobile) {
|
|
||||||
_softKeyboardRequested.value = requestSoftKeyboard;
|
|
||||||
gFFI.invokeMethod("enable_soft_keyboard", true);
|
|
||||||
}
|
|
||||||
if (isMobile &&
|
if (isMobile &&
|
||||||
!gFFI.chatModel.currentKey.isOut && // not in remote page
|
!gFFI.chatModel.currentKey.isOut && // not in remote page
|
||||||
gFFI.chatModel.latestReceivedKey != null) {
|
gFFI.chatModel.latestReceivedKey != null) {
|
||||||
@@ -219,8 +209,7 @@ class ChatModel with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
final overlay = OverlayEntry(builder: (context) {
|
final overlay = OverlayEntry(builder: (context) {
|
||||||
return Listener(
|
return Listener(
|
||||||
onPointerDown: (event) {
|
onPointerDown: (_) {
|
||||||
_requestChatSoftKeyboard(event);
|
|
||||||
if (!isWindowFocus.value) {
|
if (!isWindowFocus.value) {
|
||||||
isWindowFocus.value = true;
|
isWindowFocus.value = true;
|
||||||
_blockableOverlayState.setMiddleBlocked(true);
|
_blockableOverlayState.setMiddleBlocked(true);
|
||||||
@@ -234,10 +223,6 @@ class ChatModel with ChangeNotifier {
|
|||||||
});
|
});
|
||||||
overlayState.insert(overlay);
|
overlayState.insert(overlay);
|
||||||
chatWindowOverlayEntry = overlay;
|
chatWindowOverlayEntry = overlay;
|
||||||
if (isMobile && !requestSoftKeyboard) {
|
|
||||||
inputNode.addListener(_updateChatInputControl);
|
|
||||||
_updateChatInputControl();
|
|
||||||
}
|
|
||||||
requestChatInputFocus();
|
requestChatInputFocus();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,9 +231,6 @@ class ChatModel with ChangeNotifier {
|
|||||||
_blockableOverlayState.setMiddleBlocked(false);
|
_blockableOverlayState.setMiddleBlocked(false);
|
||||||
chatWindowOverlayEntry!.remove();
|
chatWindowOverlayEntry!.remove();
|
||||||
chatWindowOverlayEntry = null;
|
chatWindowOverlayEntry = null;
|
||||||
_softKeyboardRequested.value = false;
|
|
||||||
inputNode.removeListener(_updateChatInputControl);
|
|
||||||
_restoreChatInputControl();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -257,14 +239,13 @@ class ChatModel with ChangeNotifier {
|
|||||||
((!(isDesktop || isWebDesktop) && chatIconOverlayEntry == null) ||
|
((!(isDesktop || isWebDesktop) && chatIconOverlayEntry == null) ||
|
||||||
chatWindowOverlayEntry == null);
|
chatWindowOverlayEntry == null);
|
||||||
|
|
||||||
toggleChatOverlay({Offset? chatInitPos, bool requestSoftKeyboard = true}) {
|
toggleChatOverlay({Offset? chatInitPos}) {
|
||||||
if (_isChatOverlayHide()) {
|
if (_isChatOverlayHide()) {
|
||||||
if (!isMobile) gFFI.invokeMethod("enable_soft_keyboard", true);
|
gFFI.invokeMethod("enable_soft_keyboard", true);
|
||||||
if (!(isDesktop || isWebDesktop)) {
|
if (!(isDesktop || isWebDesktop)) {
|
||||||
showChatIconOverlay();
|
showChatIconOverlay();
|
||||||
}
|
}
|
||||||
showChatWindowOverlay(
|
showChatWindowOverlay(chatInitPos: chatInitPos);
|
||||||
chatInitPos: chatInitPos, requestSoftKeyboard: requestSoftKeyboard);
|
|
||||||
} else {
|
} else {
|
||||||
hideChatIconOverlay();
|
hideChatIconOverlay();
|
||||||
hideChatWindowOverlay();
|
hideChatWindowOverlay();
|
||||||
@@ -541,47 +522,6 @@ class ChatModel with ChangeNotifier {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _requestChatSoftKeyboard(PointerDownEvent event) {
|
|
||||||
if (!isMobile || _softKeyboardRequested.value) return;
|
|
||||||
inputNode.context?.visitAncestorElements((element) {
|
|
||||||
if (element.widget is! TextField) return true;
|
|
||||||
final box = element.findRenderObject();
|
|
||||||
if (box is! RenderBox) return false;
|
|
||||||
final bounds = box.localToGlobal(Offset.zero) & box.size;
|
|
||||||
if (!bounds.contains(event.position)) return false;
|
|
||||||
_softKeyboardRequested.value = true;
|
|
||||||
_restoreChatInputControl();
|
|
||||||
// Reconnect so the platform receives the keyboard type instead of none.
|
|
||||||
inputNode.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild);
|
|
||||||
scheduleMicrotask(() {
|
|
||||||
if (chatWindowOverlayEntry != null && _softKeyboardRequested.value) {
|
|
||||||
inputNode.requestFocus();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void _updateChatInputControl() {
|
|
||||||
final physicalChatFocused = chatWindowOverlayEntry != null &&
|
|
||||||
inputNode.hasFocus &&
|
|
||||||
!_softKeyboardRequested.value;
|
|
||||||
if (!physicalChatFocused) {
|
|
||||||
_restoreChatInputControl();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (_usingPhysicalChatInput) return;
|
|
||||||
_usingPhysicalChatInput = true;
|
|
||||||
// Keep the platform text-input connection for physical editing, without IME UI.
|
|
||||||
TextInput.setInputControl(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _restoreChatInputControl() {
|
|
||||||
if (!_usingPhysicalChatInput) return;
|
|
||||||
_usingPhysicalChatInput = false;
|
|
||||||
TextInput.restorePlatformInputControl();
|
|
||||||
}
|
|
||||||
|
|
||||||
void onVoiceCallWaiting() {
|
void onVoiceCallWaiting() {
|
||||||
_voiceCallStatus.value = VoiceCallStatus.waitingForResponse;
|
_voiceCallStatus.value = VoiceCallStatus.waitingForResponse;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,11 +15,8 @@ import 'package:get/get.dart';
|
|||||||
|
|
||||||
import '../../models/model.dart';
|
import '../../models/model.dart';
|
||||||
import '../../models/platform_model.dart';
|
import '../../models/platform_model.dart';
|
||||||
import '../../models/shortcut_model.dart';
|
|
||||||
import '../../models/state_model.dart';
|
import '../../models/state_model.dart';
|
||||||
import '../common/widgets/keyboard_shortcuts/shortcut_utils.dart';
|
|
||||||
import 'input_modifier_utils.dart';
|
import 'input_modifier_utils.dart';
|
||||||
import 'local_flutter_shortcuts.dart';
|
|
||||||
import 'relative_mouse_model.dart';
|
import 'relative_mouse_model.dart';
|
||||||
import '../common.dart';
|
import '../common.dart';
|
||||||
import '../consts.dart';
|
import '../consts.dart';
|
||||||
@@ -419,14 +416,6 @@ class InputModel {
|
|||||||
|
|
||||||
final ToReleaseRawKeys toReleaseRawKeys = ToReleaseRawKeys();
|
final ToReleaseRawKeys toReleaseRawKeys = ToReleaseRawKeys();
|
||||||
final ToReleaseKeys toReleaseKeys = ToReleaseKeys();
|
final ToReleaseKeys toReleaseKeys = ToReleaseKeys();
|
||||||
late final _localFlutterShortcuts = LocalFlutterShortcutDispatcher(
|
|
||||||
onTriggered: (action) {
|
|
||||||
final ffi = parent.target;
|
|
||||||
if (ffi != null && !ffi.closed) {
|
|
||||||
ffi.shortcutModel.onTriggered(action);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// trackpad
|
// trackpad
|
||||||
var _trackpadLastDelta = Offset.zero;
|
var _trackpadLastDelta = Offset.zero;
|
||||||
@@ -459,7 +448,6 @@ class InputModel {
|
|||||||
// mouse
|
// mouse
|
||||||
final isPhysicalMouse = false.obs;
|
final isPhysicalMouse = false.obs;
|
||||||
int _lastButtons = 0;
|
int _lastButtons = 0;
|
||||||
int _pressedMouseButtons = 0;
|
|
||||||
Offset lastMousePos = Offset.zero;
|
Offset lastMousePos = Offset.zero;
|
||||||
int _lastWheelTsUs = 0;
|
int _lastWheelTsUs = 0;
|
||||||
|
|
||||||
@@ -748,12 +736,7 @@ class InputModel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
KeyEventResult handleRawKeyEvent(RawKeyEvent e) {
|
KeyEventResult handleRawKeyEvent(RawKeyEvent e) {
|
||||||
if (_localFlutterShortcuts.tryDispatchRaw(e)) return KeyEventResult.handled;
|
if (isViewOnly) return KeyEventResult.handled;
|
||||||
if (isViewOnly) {
|
|
||||||
if (isWeb && !isInputSourceFlutter) return KeyEventResult.ignored;
|
|
||||||
_tryDispatchRawFlutterShortcut(e, releaseModifiers: false);
|
|
||||||
return KeyEventResult.handled;
|
|
||||||
}
|
|
||||||
if (isViewCamera) return KeyEventResult.handled;
|
if (isViewCamera) return KeyEventResult.handled;
|
||||||
if (!isInputSourceFlutter) {
|
if (!isInputSourceFlutter) {
|
||||||
if (isDesktop) {
|
if (isDesktop) {
|
||||||
@@ -762,7 +745,6 @@ class InputModel {
|
|||||||
return KeyEventResult.ignored;
|
return KeyEventResult.ignored;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey, raw: true);
|
|
||||||
|
|
||||||
if (_relativeMouse.handleRawKeyEvent(e)) {
|
if (_relativeMouse.handleRawKeyEvent(e)) {
|
||||||
return KeyEventResult.handled;
|
return KeyEventResult.handled;
|
||||||
@@ -830,13 +812,8 @@ class InputModel {
|
|||||||
|
|
||||||
// * Currently mobile does not enable map mode
|
// * Currently mobile does not enable map mode
|
||||||
if ((isDesktop || isWebDesktop) && keyboardMode == kKeyMapMode) {
|
if ((isDesktop || isWebDesktop) && keyboardMode == kKeyMapMode) {
|
||||||
_restoreRawFlutterShortcutModifiers(e);
|
|
||||||
mapKeyboardModeRaw(e, iosCapsLock);
|
mapKeyboardModeRaw(e, iosCapsLock);
|
||||||
} else {
|
} else {
|
||||||
if (_tryDispatchRawFlutterShortcut(e)) return KeyEventResult.handled;
|
|
||||||
_restoreRawFlutterShortcutModifiers(e, mapMode: false);
|
|
||||||
_trackFlutterShortcutKey(e.physicalKey, e.logicalKey,
|
|
||||||
down: e is RawKeyDownEvent && !e.repeat, up: e is RawKeyUpEvent);
|
|
||||||
legacyKeyboardModeRaw(e);
|
legacyKeyboardModeRaw(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -844,12 +821,7 @@ class InputModel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
KeyEventResult handleKeyEvent(KeyEvent e) {
|
KeyEventResult handleKeyEvent(KeyEvent e) {
|
||||||
if (_localFlutterShortcuts.tryDispatch(e)) return KeyEventResult.handled;
|
if (isViewOnly) return KeyEventResult.handled;
|
||||||
if (isViewOnly) {
|
|
||||||
if (isWeb && !isInputSourceFlutter) return KeyEventResult.ignored;
|
|
||||||
_tryDispatchFlutterShortcut(e, releaseModifiers: false);
|
|
||||||
return KeyEventResult.handled;
|
|
||||||
}
|
|
||||||
if (isViewCamera) return KeyEventResult.handled;
|
if (isViewCamera) return KeyEventResult.handled;
|
||||||
if (!isInputSourceFlutter) {
|
if (!isInputSourceFlutter) {
|
||||||
if (isDesktop) {
|
if (isDesktop) {
|
||||||
@@ -858,10 +830,6 @@ class InputModel {
|
|||||||
return KeyEventResult.ignored;
|
return KeyEventResult.ignored;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey);
|
|
||||||
if (isWeb && _tryDispatchFlutterShortcut(e)) {
|
|
||||||
return KeyEventResult.handled;
|
|
||||||
}
|
|
||||||
if (isWindows || isLinux) {
|
if (isWindows || isLinux) {
|
||||||
// Ignore meta keys. Because flutter window will loose focus if meta key is pressed.
|
// Ignore meta keys. Because flutter window will loose focus if meta key is pressed.
|
||||||
if (e.physicalKey == PhysicalKeyboardKey.metaLeft ||
|
if (e.physicalKey == PhysicalKeyboardKey.metaLeft ||
|
||||||
@@ -942,14 +910,6 @@ class InputModel {
|
|||||||
final isDesktopAndMapMode =
|
final isDesktopAndMapMode =
|
||||||
isDesktop || (isWebDesktop && keyboardMode == kKeyMapMode);
|
isDesktop || (isWebDesktop && keyboardMode == kKeyMapMode);
|
||||||
if (isMobileAndMapMode || isDesktopAndMapMode) {
|
if (isMobileAndMapMode || isDesktopAndMapMode) {
|
||||||
_restoreFlutterShortcutModifiers(e);
|
|
||||||
// Native map input is matched and tracked by Rust before forwarding.
|
|
||||||
if (isWeb) {
|
|
||||||
_trackFlutterShortcutKey(e.physicalKey, e.logicalKey,
|
|
||||||
down: e is KeyDownEvent || e is KeyRepeatEvent,
|
|
||||||
up: e is KeyUpEvent,
|
|
||||||
mapMode: true);
|
|
||||||
}
|
|
||||||
// FIXME: e.character is wrong for dead keys, eg: ^ in de
|
// FIXME: e.character is wrong for dead keys, eg: ^ in de
|
||||||
newKeyboardMode(
|
newKeyboardMode(
|
||||||
e.character ?? '',
|
e.character ?? '',
|
||||||
@@ -958,285 +918,12 @@ class InputModel {
|
|||||||
e is KeyDownEvent || e is KeyRepeatEvent,
|
e is KeyDownEvent || e is KeyRepeatEvent,
|
||||||
iosCapsLock);
|
iosCapsLock);
|
||||||
} else {
|
} else {
|
||||||
if (!isWeb && _tryDispatchFlutterShortcut(e)) return KeyEventResult.handled;
|
|
||||||
_restoreFlutterShortcutModifiers(e, mapMode: false);
|
|
||||||
_trackFlutterShortcutKey(e.physicalKey, e.logicalKey,
|
|
||||||
down: e is KeyDownEvent, up: e is KeyUpEvent);
|
|
||||||
legacyKeyboardMode(e);
|
legacyKeyboardMode(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
return KeyEventResult.handled;
|
return KeyEventResult.handled;
|
||||||
}
|
}
|
||||||
|
|
||||||
void _trackFlutterShortcutKey(
|
|
||||||
PhysicalKeyboardKey physical, LogicalKeyboardKey logical,
|
|
||||||
{required bool down, required bool up, bool mapMode = false}) {
|
|
||||||
if ((!down && !up) || (down && !keyboardPerm)) return;
|
|
||||||
_localFlutterShortcuts.recordForwardedKey(physical,
|
|
||||||
down: down,
|
|
||||||
release: () => mapMode
|
|
||||||
? bind.sessionHandleFlutterKeyEvent(
|
|
||||||
sessionId: sessionId,
|
|
||||||
character: '',
|
|
||||||
usbHid: physical.usbHidUsage & 0xFFFF,
|
|
||||||
lockModes: _buildLockModes(false),
|
|
||||||
downOrUp: false,
|
|
||||||
)
|
|
||||||
: bind.sessionInputKey(
|
|
||||||
sessionId: sessionId,
|
|
||||||
name: physicalKeyMap[physical.usbHidUsage] ??
|
|
||||||
logicalKeyMap[logical.keyId] ??
|
|
||||||
logical.keyLabel,
|
|
||||||
down: false,
|
|
||||||
press: false,
|
|
||||||
alt: false,
|
|
||||||
ctrl: false,
|
|
||||||
shift: false,
|
|
||||||
command: false,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _tryDispatchFlutterShortcut(KeyEvent e, {bool releaseModifiers = true}) {
|
|
||||||
final keyboard = HardwareKeyboard.instance;
|
|
||||||
return _localFlutterShortcuts.tryDispatch(
|
|
||||||
e,
|
|
||||||
viewOnly: isViewOnly,
|
|
||||||
match: () {
|
|
||||||
// AltGraph is text input on Windows/Linux; Apple Option stays bindable.
|
|
||||||
if (!(isMacOS || isIOS || isWebOnMacOs) &&
|
|
||||||
keyboard.logicalKeysPressed.contains(LogicalKeyboardKey.altGraph)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return _matchFlutterShortcut(e.physicalKey,
|
|
||||||
ctrlPressed: keyboard.isControlPressed,
|
|
||||||
altPressed: keyboard.isAltPressed,
|
|
||||||
shiftPressed: keyboard.isShiftPressed,
|
|
||||||
commandPressed: keyboard.isMetaPressed);
|
|
||||||
},
|
|
||||||
releaseModifiers:
|
|
||||||
releaseModifiers ? _releaseFlutterShortcutModifiers : null,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _tryDispatchRawFlutterShortcut(RawKeyEvent e,
|
|
||||||
{bool releaseModifiers = true}) {
|
|
||||||
return _localFlutterShortcuts.tryDispatchRaw(
|
|
||||||
e,
|
|
||||||
viewOnly: isViewOnly,
|
|
||||||
match: () {
|
|
||||||
final data = e.data;
|
|
||||||
const gtkMod5Mask = 1 << 7;
|
|
||||||
// GTK's Mod5 (used by AltGr) is missing from the ordinary modifier flags.
|
|
||||||
if (data is RawKeyEventDataLinux &&
|
|
||||||
data.keyHelper is GtkKeyHelper &&
|
|
||||||
(data.modifiers & gtkMod5Mask) != 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return _matchFlutterShortcut(e.physicalKey,
|
|
||||||
ctrlPressed: e.isControlPressed,
|
|
||||||
altPressed: e.isAltPressed,
|
|
||||||
shiftPressed: e.isShiftPressed,
|
|
||||||
commandPressed: e.isMetaPressed);
|
|
||||||
},
|
|
||||||
releaseModifiers: releaseModifiers
|
|
||||||
? () => _releaseFlutterShortcutModifiers(raw: true)
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _releaseFlutterShortcutModifiers({bool raw = false}) async {
|
|
||||||
final releases = <Future<void>>[];
|
|
||||||
// Release only on the remote: the modifiers are still physically held.
|
|
||||||
final pressed = raw
|
|
||||||
? RawKeyboard.instance.keysPressed
|
|
||||||
: HardwareKeyboard.instance.logicalKeysPressed;
|
|
||||||
final swapCtrlCmd = peerPlatform == kPeerPlatformWindows &&
|
|
||||||
bind.sessionGetToggleOptionSync(
|
|
||||||
sessionId: sessionId, arg: 'allow_swap_key');
|
|
||||||
final neutralizeMenu = _needsShortcutMenuGuard(pressed, swapCtrlCmd);
|
|
||||||
if (neutralizeMenu)
|
|
||||||
await _sendShortcutMenuControl(true, pressed, swapCtrlCmd);
|
|
||||||
for (final entry in {
|
|
||||||
LogicalKeyboardKey.controlLeft: PhysicalKeyboardKey.controlLeft,
|
|
||||||
LogicalKeyboardKey.controlRight: PhysicalKeyboardKey.controlRight,
|
|
||||||
LogicalKeyboardKey.altLeft: PhysicalKeyboardKey.altLeft,
|
|
||||||
LogicalKeyboardKey.altRight: PhysicalKeyboardKey.altRight,
|
|
||||||
LogicalKeyboardKey.shiftLeft: PhysicalKeyboardKey.shiftLeft,
|
|
||||||
LogicalKeyboardKey.shiftRight: PhysicalKeyboardKey.shiftRight,
|
|
||||||
LogicalKeyboardKey.metaLeft: PhysicalKeyboardKey.metaLeft,
|
|
||||||
LogicalKeyboardKey.metaRight: PhysicalKeyboardKey.metaRight,
|
|
||||||
}.entries) {
|
|
||||||
if (!pressed.contains(entry.key)) continue;
|
|
||||||
if (isWebDesktop) {
|
|
||||||
// The action can switch from Legacy to Map while modifiers stay held.
|
|
||||||
_localFlutterShortcuts.recordReleasedModifiers([entry.value]);
|
|
||||||
}
|
|
||||||
if (isWebDesktop && keyboardMode == kKeyMapMode) {
|
|
||||||
releases.add(bind.sessionHandleFlutterKeyEvent(
|
|
||||||
sessionId: sessionId,
|
|
||||||
character: '',
|
|
||||||
usbHid: entry.value.usbHidUsage & 0xFFFF,
|
|
||||||
lockModes: _buildLockModes(false),
|
|
||||||
downOrUp: false,
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
final label = physicalKeyMap[entry.value.usbHidUsage] ?? entry.key.keyLabel;
|
|
||||||
releases.add(bind.sessionInputKey(
|
|
||||||
sessionId: sessionId,
|
|
||||||
name: label,
|
|
||||||
down: false,
|
|
||||||
press: false,
|
|
||||||
alt: false,
|
|
||||||
ctrl: false,
|
|
||||||
shift: false,
|
|
||||||
command: false,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await Future.wait(releases).whenComplete(() => neutralizeMenu
|
|
||||||
? _sendShortcutMenuControl(false, pressed, swapCtrlCmd)
|
|
||||||
: null);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _needsShortcutMenuGuard(
|
|
||||||
Set<LogicalKeyboardKey> pressed, bool swapCtrlCmd) {
|
|
||||||
if (peerPlatform != kPeerPlatformWindows) return false;
|
|
||||||
// Web's legacy key-name API does not swap the key itself.
|
|
||||||
final swapped =
|
|
||||||
swapCtrlCmd && (!isWebDesktop || keyboardMode == kKeyMapMode);
|
|
||||||
return pressed.any({
|
|
||||||
LogicalKeyboardKey.altLeft,
|
|
||||||
LogicalKeyboardKey.altRight,
|
|
||||||
swapped
|
|
||||||
? LogicalKeyboardKey.controlLeft
|
|
||||||
: LogicalKeyboardKey.metaLeft,
|
|
||||||
swapped
|
|
||||||
? LogicalKeyboardKey.controlRight
|
|
||||||
: LogicalKeyboardKey.metaRight,
|
|
||||||
}.contains) &&
|
|
||||||
!pressed.any({
|
|
||||||
swapped
|
|
||||||
? LogicalKeyboardKey.metaLeft
|
|
||||||
: LogicalKeyboardKey.controlLeft,
|
|
||||||
swapped
|
|
||||||
? LogicalKeyboardKey.metaRight
|
|
||||||
: LogicalKeyboardKey.controlRight,
|
|
||||||
LogicalKeyboardKey.shiftLeft,
|
|
||||||
LogicalKeyboardKey.shiftRight,
|
|
||||||
}.contains);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _sendShortcutMenuControl(
|
|
||||||
bool down, Set<LogicalKeyboardKey> pressed, bool swapCtrlCmd) {
|
|
||||||
// Choose the pre-swap key that reaches Windows as Ctrl.
|
|
||||||
if (isWebDesktop) {
|
|
||||||
return bind.sessionHandleFlutterKeyEvent(
|
|
||||||
sessionId: sessionId,
|
|
||||||
character: '',
|
|
||||||
usbHid: (swapCtrlCmd
|
|
||||||
? PhysicalKeyboardKey.metaLeft
|
|
||||||
: PhysicalKeyboardKey.controlLeft)
|
|
||||||
.usbHidUsage &
|
|
||||||
0xFFFF,
|
|
||||||
lockModes: _buildLockModes(false),
|
|
||||||
downOrUp: down,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return bind.sessionInputKey(
|
|
||||||
sessionId: sessionId,
|
|
||||||
name: swapCtrlCmd ? 'Meta' : 'VK_CONTROL',
|
|
||||||
down: down,
|
|
||||||
press: false,
|
|
||||||
// Legacy reconciles modifiers before key-down. Keep Alt/Meta held until
|
|
||||||
// Ctrl is down, otherwise reconciliation can activate menus or Start.
|
|
||||||
alt: down &&
|
|
||||||
pressed.any({LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altRight}
|
|
||||||
.contains),
|
|
||||||
ctrl: down &&
|
|
||||||
pressed.any({
|
|
||||||
LogicalKeyboardKey.controlLeft,
|
|
||||||
LogicalKeyboardKey.controlRight
|
|
||||||
}.contains),
|
|
||||||
shift: false,
|
|
||||||
command: down &&
|
|
||||||
pressed.any({
|
|
||||||
LogicalKeyboardKey.metaLeft,
|
|
||||||
LogicalKeyboardKey.metaRight
|
|
||||||
}.contains),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _syncFlutterShortcutModifiersAfterViewOnly(PhysicalKeyboardKey incoming,
|
|
||||||
{bool raw = false}) {
|
|
||||||
if (!isInputSourceFlutter) return;
|
|
||||||
final pressed = raw
|
|
||||||
? RawKeyboard.instance.physicalKeysPressed
|
|
||||||
: HardwareKeyboard.instance.physicalKeysPressed;
|
|
||||||
if (!_localFlutterShortcuts.resumeModifiersAfterViewOnly(incoming, pressed)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ctrl = pressed.contains(PhysicalKeyboardKey.controlLeft) ||
|
|
||||||
pressed.contains(PhysicalKeyboardKey.controlRight);
|
|
||||||
alt = pressed.contains(PhysicalKeyboardKey.altLeft) ||
|
|
||||||
pressed.contains(PhysicalKeyboardKey.altRight);
|
|
||||||
shift = pressed.contains(PhysicalKeyboardKey.shiftLeft) ||
|
|
||||||
pressed.contains(PhysicalKeyboardKey.shiftRight);
|
|
||||||
command = pressed.contains(PhysicalKeyboardKey.metaLeft) ||
|
|
||||||
pressed.contains(PhysicalKeyboardKey.metaRight);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _restoreFlutterShortcutModifiers(KeyEvent e, {bool mapMode = true}) {
|
|
||||||
final keys = _localFlutterShortcuts.takeModifiersToRestore(
|
|
||||||
e, HardwareKeyboard.instance.physicalKeysPressed);
|
|
||||||
if (!mapMode) return;
|
|
||||||
for (final key in keys) {
|
|
||||||
newKeyboardMode('', key.usbHidUsage & 0xFFFF, true, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _restoreRawFlutterShortcutModifiers(RawKeyEvent e, {bool mapMode = true}) {
|
|
||||||
final keys = _localFlutterShortcuts.takeRawModifiersToRestore(
|
|
||||||
e, RawKeyboard.instance.physicalKeysPressed);
|
|
||||||
if (!mapMode) return;
|
|
||||||
for (final key in keys) {
|
|
||||||
newKeyboardMode('', key.usbHidUsage & 0xFFFF, true, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String? _matchFlutterShortcut(PhysicalKeyboardKey key,
|
|
||||||
{required bool ctrlPressed,
|
|
||||||
required bool altPressed,
|
|
||||||
required bool shiftPressed,
|
|
||||||
required bool commandPressed}) {
|
|
||||||
if (isViewCamera) return null;
|
|
||||||
final keyName = physicalKeyName(key);
|
|
||||||
if (keyName == null) return null;
|
|
||||||
final config = ShortcutModel.config(active: true);
|
|
||||||
if (!config.enabled || config.passThrough) return null;
|
|
||||||
final mods = <String>[];
|
|
||||||
if (isMacOS || isIOS || isWebOnMacOs) {
|
|
||||||
if (commandPressed) mods.add('primary');
|
|
||||||
if (ctrlPressed) mods.add('ctrl');
|
|
||||||
} else if (ctrlPressed) {
|
|
||||||
mods.add('primary');
|
|
||||||
}
|
|
||||||
if (altPressed) mods.add('alt');
|
|
||||||
if (shiftPressed) mods.add('shift');
|
|
||||||
for (final binding in config.bindings) {
|
|
||||||
final action = binding['action'];
|
|
||||||
final key = binding['key'];
|
|
||||||
final bindingMods =
|
|
||||||
canonicalShortcutModsForSave(shortcutModSetFrom(binding['mods']));
|
|
||||||
if (action is String &&
|
|
||||||
key == keyName &&
|
|
||||||
bindingMods.isNotEmpty &&
|
|
||||||
listEquals(bindingMods, mods)) {
|
|
||||||
return action;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send Key Event
|
/// Send Key Event
|
||||||
void newKeyboardMode(
|
void newKeyboardMode(
|
||||||
String character, int usbHid, bool down, bool iosCapsLock) {
|
String character, int usbHid, bool down, bool iosCapsLock) {
|
||||||
@@ -1389,10 +1076,6 @@ class InputModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
_lastButtons = hasStaleButtonsOnMouseUp ? 0 : evt.buttons;
|
_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['buttons'] = buttons;
|
||||||
out['type'] = type;
|
out['type'] = type;
|
||||||
@@ -1425,7 +1108,6 @@ class InputModel {
|
|||||||
/// Reset key modifiers to false, including [shift], [ctrl], [alt] and [command].
|
/// Reset key modifiers to false, including [shift], [ctrl], [alt] and [command].
|
||||||
void resetModifiers() {
|
void resetModifiers() {
|
||||||
shift = ctrl = alt = command = false;
|
shift = ctrl = alt = command = false;
|
||||||
if (parent.target?.closed == true) _localFlutterShortcuts.clear();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Modify the given modifier map [evt] based on current modifier key status.
|
/// Modify the given modifier map [evt] based on current modifier key status.
|
||||||
@@ -2139,16 +1821,9 @@ class InputModel {
|
|||||||
bool edgeScroll = false,
|
bool edgeScroll = false,
|
||||||
}) {
|
}) {
|
||||||
if (isViewCamera) return null;
|
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 x = offset.dx;
|
||||||
double y = max(0.0, offset.dy);
|
double y = max(0.0, offset.dy);
|
||||||
// Cursor ownership may change between a forwarded down and its up.
|
if (_checkPeerControlProtected(x, y)) {
|
||||||
if (_checkPeerControlProtected(x, y) && !isMatchingMouseUp) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2190,9 +1865,6 @@ class InputModel {
|
|||||||
if (pos == null) {
|
if (pos == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (isMatchingMouseUp) {
|
|
||||||
_pressedMouseButtons &= ~buttons;
|
|
||||||
}
|
|
||||||
if (type != '') {
|
if (type != '') {
|
||||||
evt['x'] = '0';
|
evt['x'] = '0';
|
||||||
evt['y'] = '0';
|
evt['y'] = '0';
|
||||||
@@ -2201,13 +1873,9 @@ class InputModel {
|
|||||||
evt['y'] = '${pos.y.toInt()}';
|
evt['y'] = '${pos.y.toInt()}';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final buttons = evt['buttons'];
|
||||||
if (buttons is int) {
|
if (buttons is int) {
|
||||||
evt['buttons'] = mouseButtonsToPeer(buttons);
|
evt['buttons'] = mouseButtonsToPeer(buttons);
|
||||||
if ((isDesktop || isWebDesktop) &&
|
|
||||||
type == kMouseEventTypeDown &&
|
|
||||||
evt['buttons'] != '') {
|
|
||||||
_pressedMouseButtons |= buttons;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// Log warning if buttons exists but is not an int (unexpected caller).
|
// Log warning if buttons exists but is not an int (unexpected caller).
|
||||||
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
|
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
|
||||||
|
|||||||
@@ -1,211 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
|
|
||||||
import '../common/widgets/keyboard_shortcuts/shortcut_constants.dart';
|
|
||||||
|
|
||||||
class LocalFlutterShortcutDispatcher {
|
|
||||||
final void Function(String) onTriggered;
|
|
||||||
// Keys whose press fired a shortcut and whose release has not arrived yet.
|
|
||||||
// Ownership is physical: it is shared by every session, because a shortcut
|
|
||||||
// can switch focus or close its own session before the key is released, and
|
|
||||||
// it is never dropped with a session. A key whose release is missed heals
|
|
||||||
// itself: its next press is consumed as a repeat and that release removes it.
|
|
||||||
static final _firedKeys = <PhysicalKeyboardKey>{};
|
|
||||||
// Actions waiting for the release of the key that fired them, with the
|
|
||||||
// session that fired them. See [kShortcutActionsRunOnKeyUp].
|
|
||||||
static final _keyUpActions =
|
|
||||||
<PhysicalKeyboardKey, (LocalFlutterShortcutDispatcher, String)>{};
|
|
||||||
static final _clipboardModifierReleases =
|
|
||||||
<PhysicalKeyboardKey, (LocalFlutterShortcutDispatcher, Future<void>)>{};
|
|
||||||
final _releasedModifiers = <PhysicalKeyboardKey>{};
|
|
||||||
final _forwardedKeyReleases =
|
|
||||||
<PhysicalKeyboardKey, Future<void> Function()>{};
|
|
||||||
bool _viewOnlyShortcutPending = false;
|
|
||||||
int _generation = 0;
|
|
||||||
|
|
||||||
LocalFlutterShortcutDispatcher({required this.onTriggered});
|
|
||||||
|
|
||||||
/// Drops this session's pending actions and modifier replay. Fired keys
|
|
||||||
/// stay owned until their release, whichever session receives it.
|
|
||||||
void clear() {
|
|
||||||
_keyUpActions.removeWhere((_, pending) => identical(pending.$1, this));
|
|
||||||
_clipboardModifierReleases
|
|
||||||
.removeWhere((_, pending) => identical(pending.$1, this));
|
|
||||||
_releasedModifiers.clear();
|
|
||||||
_forwardedKeyReleases.clear();
|
|
||||||
_viewOnlyShortcutPending = false;
|
|
||||||
_generation++;
|
|
||||||
}
|
|
||||||
|
|
||||||
@visibleForTesting
|
|
||||||
static void resetFiredKeys() {
|
|
||||||
_firedKeys.clear();
|
|
||||||
_keyUpActions.clear();
|
|
||||||
_clipboardModifierReleases.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
void recordReleasedModifiers(Iterable<PhysicalKeyboardKey> keys) {
|
|
||||||
_releasedModifiers.addAll(keys);
|
|
||||||
}
|
|
||||||
|
|
||||||
void recordForwardedKey(PhysicalKeyboardKey key,
|
|
||||||
{required bool down, required Future<void> Function() release}) {
|
|
||||||
if (_isModifier(key)) return;
|
|
||||||
if (down) {
|
|
||||||
_forwardedKeyReleases.putIfAbsent(key, () => release);
|
|
||||||
} else {
|
|
||||||
_forwardedKeyReleases.remove(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool resumeModifiersAfterViewOnly(
|
|
||||||
PhysicalKeyboardKey incoming, Set<PhysicalKeyboardKey> pressed) {
|
|
||||||
if (!_viewOnlyShortcutPending) return false;
|
|
||||||
_viewOnlyShortcutPending = false;
|
|
||||||
_releasedModifiers
|
|
||||||
.addAll(pressed.where((key) => key != incoming && _isModifier(key)));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<PhysicalKeyboardKey> takeModifiersToRestore(
|
|
||||||
KeyEvent event, Set<PhysicalKeyboardKey> pressed) =>
|
|
||||||
_takeModifiersToRestore(event.physicalKey,
|
|
||||||
event is KeyDownEvent || event is KeyRepeatEvent, pressed);
|
|
||||||
|
|
||||||
List<PhysicalKeyboardKey> takeRawModifiersToRestore(
|
|
||||||
RawKeyEvent event, Set<PhysicalKeyboardKey> pressed) =>
|
|
||||||
_takeModifiersToRestore(
|
|
||||||
event.physicalKey, event is RawKeyDownEvent, pressed);
|
|
||||||
|
|
||||||
List<PhysicalKeyboardKey> _takeModifiersToRestore(
|
|
||||||
PhysicalKeyboardKey incoming,
|
|
||||||
bool down,
|
|
||||||
Set<PhysicalKeyboardKey> pressed) {
|
|
||||||
_releasedModifiers.removeWhere((key) => !pressed.contains(key));
|
|
||||||
if (!down || _isModifier(incoming)) return [];
|
|
||||||
final keys = _releasedModifiers.toList();
|
|
||||||
_releasedModifiers.clear();
|
|
||||||
return keys;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _isModifier(PhysicalKeyboardKey key) {
|
|
||||||
// HID keyboard modifier usages are contiguous.
|
|
||||||
return key.usbHidUsage >= PhysicalKeyboardKey.controlLeft.usbHidUsage &&
|
|
||||||
key.usbHidUsage <= PhysicalKeyboardKey.metaRight.usbHidUsage;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool tryDispatch(
|
|
||||||
KeyEvent event, {
|
|
||||||
bool viewOnly = false,
|
|
||||||
String? Function()? match,
|
|
||||||
Future<void> Function()? releaseModifiers,
|
|
||||||
}) =>
|
|
||||||
_tryDispatch(
|
|
||||||
event.physicalKey,
|
|
||||||
down: event is KeyDownEvent,
|
|
||||||
up: event is KeyUpEvent,
|
|
||||||
viewOnly: viewOnly,
|
|
||||||
match: match,
|
|
||||||
releaseModifiers: releaseModifiers,
|
|
||||||
);
|
|
||||||
|
|
||||||
bool tryDispatchRaw(
|
|
||||||
RawKeyEvent event, {
|
|
||||||
bool viewOnly = false,
|
|
||||||
String? Function()? match,
|
|
||||||
Future<void> Function()? releaseModifiers,
|
|
||||||
}) =>
|
|
||||||
_tryDispatch(
|
|
||||||
event.physicalKey,
|
|
||||||
down: event is RawKeyDownEvent && !event.repeat,
|
|
||||||
up: event is RawKeyUpEvent,
|
|
||||||
viewOnly: viewOnly,
|
|
||||||
match: match,
|
|
||||||
releaseModifiers: releaseModifiers,
|
|
||||||
);
|
|
||||||
|
|
||||||
bool _tryDispatch(
|
|
||||||
PhysicalKeyboardKey key, {
|
|
||||||
required bool down,
|
|
||||||
required bool up,
|
|
||||||
required bool viewOnly,
|
|
||||||
String? Function()? match,
|
|
||||||
Future<void> Function()? releaseModifiers,
|
|
||||||
}) {
|
|
||||||
if (up) {
|
|
||||||
if (!_firedKeys.remove(key)) return false;
|
|
||||||
final pending = _keyUpActions.remove(key);
|
|
||||||
final release = _clipboardModifierReleases.remove(key)?.$2;
|
|
||||||
if (pending != null) {
|
|
||||||
final (owner, action) = pending;
|
|
||||||
unawaited(
|
|
||||||
owner._trigger(action, release == null ? null : () => release));
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// Safari can omit the previous Cmd-held keyup. A fresh browser keydown
|
|
||||||
// starts a new press; KeyRepeatEvent must still belong to the old chord.
|
|
||||||
if (kIsWeb && defaultTargetPlatform == TargetPlatform.macOS && down) {
|
|
||||||
_firedKeys.remove(key);
|
|
||||||
}
|
|
||||||
if (_firedKeys.contains(key)) return true;
|
|
||||||
if (!down) return false;
|
|
||||||
final action = match?.call();
|
|
||||||
if (action == null) return false;
|
|
||||||
_firedKeys.add(key);
|
|
||||||
if (viewOnly) _viewOnlyShortcutPending = true;
|
|
||||||
// macOS browsers can omit letter keyups while Cmd is held. Like the JS
|
|
||||||
// input source, dispatch on keydown there; remote cleanup still runs first.
|
|
||||||
// Web clipboard reads also need the key-down's browser user activation.
|
|
||||||
final runOnKeyUp =
|
|
||||||
!(kIsWeb && defaultTargetPlatform == TargetPlatform.macOS) &&
|
|
||||||
(kShortcutActionsRunOnKeyUp.contains(action) ||
|
|
||||||
(!kIsWeb && action == kShortcutActionSendClipboardKeystrokes));
|
|
||||||
if (runOnKeyUp) {
|
|
||||||
_keyUpActions[key] = (this, action);
|
|
||||||
} else {
|
|
||||||
_keyUpActions.remove(key);
|
|
||||||
}
|
|
||||||
if (runOnKeyUp &&
|
|
||||||
action == kShortcutActionSendClipboardKeystrokes &&
|
|
||||||
releaseModifiers != null) {
|
|
||||||
// The release can precede completion of the asynchronous FFI calls.
|
|
||||||
final release = Future<void>.sync(releaseModifiers);
|
|
||||||
_clipboardModifierReleases[key] = (this, release);
|
|
||||||
unawaited(_trigger(null, () => release));
|
|
||||||
} else {
|
|
||||||
unawaited(_trigger(runOnKeyUp ? null : action, releaseModifiers));
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Releases the remote modifiers, then runs [action] unless it is null or
|
|
||||||
/// this session was cleared meanwhile.
|
|
||||||
Future<void> _trigger(
|
|
||||||
String? action, Future<void> Function()? releaseModifiers) async {
|
|
||||||
final generation = _generation;
|
|
||||||
try {
|
|
||||||
if (releaseModifiers != null) await releaseModifiers();
|
|
||||||
if (action == null || generation != _generation) return;
|
|
||||||
if ((action == kShortcutActionToggleViewOnly ||
|
|
||||||
action == kShortcutActionToggleShowMyCursor ||
|
|
||||||
action == kShortcutActionKeyboardModeMap ||
|
|
||||||
action == kShortcutActionKeyboardModeTranslate ||
|
|
||||||
action == kShortcutActionKeyboardModeLegacy ||
|
|
||||||
kShortcutActionsRunOnKeyUp.contains(action) ||
|
|
||||||
(!kIsWeb && action == kShortcutActionSendClipboardKeystrokes)) &&
|
|
||||||
_forwardedKeyReleases.isNotEmpty) {
|
|
||||||
// Focus changes and view-only can keep physical keyups from the peer.
|
|
||||||
// Mode changes can encode later keyups differently from their keydowns.
|
|
||||||
final releases = _forwardedKeyReleases.values.toList();
|
|
||||||
_forwardedKeyReleases.clear();
|
|
||||||
await Future.wait(releases.map((release) => Future<void>.sync(release)));
|
|
||||||
}
|
|
||||||
if (generation == _generation) onTriggered(action);
|
|
||||||
} catch (e, st) {
|
|
||||||
debugPrint('Local shortcut failed for $action: $e\n$st');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,6 @@ import 'package:flutter_hbb/models/peer_model.dart';
|
|||||||
import 'package:flutter_hbb/models/peer_tab_model.dart';
|
import 'package:flutter_hbb/models/peer_tab_model.dart';
|
||||||
import 'package:flutter_hbb/models/printer_model.dart';
|
import 'package:flutter_hbb/models/printer_model.dart';
|
||||||
import 'package:flutter_hbb/models/server_model.dart';
|
import 'package:flutter_hbb/models/server_model.dart';
|
||||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
|
||||||
import 'package:flutter_hbb/models/user_model.dart';
|
import 'package:flutter_hbb/models/user_model.dart';
|
||||||
import 'package:flutter_hbb/models/state_model.dart';
|
import 'package:flutter_hbb/models/state_model.dart';
|
||||||
import 'package:flutter_hbb/models/desktop_render_texture.dart';
|
import 'package:flutter_hbb/models/desktop_render_texture.dart';
|
||||||
@@ -470,11 +469,6 @@ class FfiModel with ChangeNotifier {
|
|||||||
} else if (name == 'exit_relative_mouse_mode') {
|
} else if (name == 'exit_relative_mouse_mode') {
|
||||||
// Handle exit shortcut from rdev grab loop (Ctrl+Alt on Win/Linux, Cmd+G on macOS)
|
// Handle exit shortcut from rdev grab loop (Ctrl+Alt on Win/Linux, Cmd+G on macOS)
|
||||||
parent.target?.inputModel.exitRelativeMouseModeWithKeyRelease();
|
parent.target?.inputModel.exitRelativeMouseModeWithKeyRelease();
|
||||||
} else if (name == kShortcutEventName) {
|
|
||||||
final action = evt['action'];
|
|
||||||
if (action is String) {
|
|
||||||
parent.target?.shortcutModel.onTriggered(action);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
debugPrint('Event is not handled in the fixed branch: $name');
|
debugPrint('Event is not handled in the fixed branch: $name');
|
||||||
}
|
}
|
||||||
@@ -1433,9 +1427,9 @@ class FfiModel with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
// After reconnecting, restore the last selected monitor once the canvas is ready.
|
// After reconnecting, restore the last selected monitor once the canvas is ready.
|
||||||
// Switching earlier can offset the view if the monitor sizes differ.
|
// Switching earlier can offset the view if the monitor sizes differ.
|
||||||
// New monitor windows keep their selection in currentDisplay.
|
final last = lastUserDisplay;
|
||||||
final last = lastUserDisplay ?? _pi.currentDisplay;
|
|
||||||
pendingMonitorRestore = (!isCache &&
|
pendingMonitorRestore = (!isCache &&
|
||||||
|
last != null &&
|
||||||
last != currentDisplay &&
|
last != currentDisplay &&
|
||||||
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
|
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
|
||||||
sessionId: sessionId) !=
|
sessionId: sessionId) !=
|
||||||
@@ -4054,7 +4048,6 @@ class FFI {
|
|||||||
late final ElevationModel elevationModel; // session
|
late final ElevationModel elevationModel; // session
|
||||||
late final CmFileModel cmFileModel; // cm
|
late final CmFileModel cmFileModel; // cm
|
||||||
late final TextureModel textureModel; //session
|
late final TextureModel textureModel; //session
|
||||||
late final ShortcutModel shortcutModel; // session
|
|
||||||
late final Peers recentPeersModel; // global
|
late final Peers recentPeersModel; // global
|
||||||
late final Peers favoritePeersModel; // global
|
late final Peers favoritePeersModel; // global
|
||||||
late final Peers lanPeersModel; // global
|
late final Peers lanPeersModel; // global
|
||||||
@@ -4084,7 +4077,6 @@ class FFI {
|
|||||||
elevationModel = ElevationModel(WeakReference(this));
|
elevationModel = ElevationModel(WeakReference(this));
|
||||||
cmFileModel = CmFileModel(WeakReference(this));
|
cmFileModel = CmFileModel(WeakReference(this));
|
||||||
textureModel = TextureModel(WeakReference(this));
|
textureModel = TextureModel(WeakReference(this));
|
||||||
shortcutModel = ShortcutModel(WeakReference(this));
|
|
||||||
recentPeersModel = Peers(
|
recentPeersModel = Peers(
|
||||||
name: PeersModelName.recent,
|
name: PeersModelName.recent,
|
||||||
loadEvent: LoadEvent.recent,
|
loadEvent: LoadEvent.recent,
|
||||||
@@ -4394,7 +4386,6 @@ class FFI {
|
|||||||
ffiModel.pi.currentDisplay);
|
ffiModel.pi.currentDisplay);
|
||||||
}
|
}
|
||||||
imageModel.callbacksOnFirstImage.clear();
|
imageModel.callbacksOnFirstImage.clear();
|
||||||
shortcutModel.clear();
|
|
||||||
await imageModel.update(null);
|
await imageModel.update(null);
|
||||||
cursorModel.clear();
|
cursorModel.clear();
|
||||||
ffiModel.clear();
|
ffiModel.clear();
|
||||||
|
|||||||
@@ -59,9 +59,6 @@ class PlatformFFI {
|
|||||||
final _toAndroidChannel = const MethodChannel('mChannel');
|
final _toAndroidChannel = const MethodChannel('mChannel');
|
||||||
|
|
||||||
RustdeskImpl get ffiBind => _ffiBind;
|
RustdeskImpl get ffiBind => _ffiBind;
|
||||||
@visibleForTesting
|
|
||||||
void setBindingForTesting(RustdeskImpl binding) => _ffiBind = binding;
|
|
||||||
|
|
||||||
F3? _session_get_rgba;
|
F3? _session_get_rgba;
|
||||||
|
|
||||||
static get localeName => Platform.localeName;
|
static get localeName => Platform.localeName;
|
||||||
|
|||||||
@@ -1,669 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
|
|
||||||
import '../common.dart';
|
|
||||||
import '../common/shared_state.dart' show PrivacyModeState;
|
|
||||||
import '../common/widgets/dialog.dart'
|
|
||||||
show desktopTryShowTabAuditDialogCloseCancelled;
|
|
||||||
import '../common/widgets/keyboard_shortcuts/shortcut_utils.dart';
|
|
||||||
import '../common/widgets/keyboard_shortcuts/shortcut_actions.dart';
|
|
||||||
import '../common/widgets/toolbar.dart'
|
|
||||||
show allowDisplaySwitchInPrivacyMode, showVirtualDisplayMenu;
|
|
||||||
import '../consts.dart';
|
|
||||||
import '../desktop/widgets/remote_toolbar.dart' show ToolbarState;
|
|
||||||
import 'chat_model.dart' show ChatModel, MessageKey, VoiceCallStatus;
|
|
||||||
import '../desktop/widgets/tabbar_widget.dart' show DesktopTabController;
|
|
||||||
import '../models/model.dart';
|
|
||||||
import '../models/platform_model.dart';
|
|
||||||
import '../models/state_model.dart';
|
|
||||||
|
|
||||||
typedef ShortcutCallback = FutureOr<void> Function();
|
|
||||||
|
|
||||||
/// Per-session shortcut dispatcher. Attached to FFI when a session is created.
|
|
||||||
///
|
|
||||||
/// The Rust matcher (src/keyboard/shortcuts.rs) emits `shortcut_triggered`
|
|
||||||
/// session events containing the matched `action` id. The session event
|
|
||||||
/// listener in [FfiModel.startEventListener] forwards those to this model
|
|
||||||
/// via [onTriggered], which runs whatever callback the toolbar / menu
|
|
||||||
/// builders previously registered for that action id.
|
|
||||||
class ShortcutModel {
|
|
||||||
static WeakReference<ShortcutModel>? _activeWebModel;
|
|
||||||
|
|
||||||
final WeakReference<FFI> parent;
|
|
||||||
final Map<String, ShortcutCallback> _callbacks = {};
|
|
||||||
final Map<String, ShortcutCallback> _refreshers = {};
|
|
||||||
|
|
||||||
ShortcutModel(this.parent);
|
|
||||||
|
|
||||||
/// Called by toolbar / menu builders to register what to do when the
|
|
||||||
/// matched shortcut fires.
|
|
||||||
void register(String actionId, ShortcutCallback callback) {
|
|
||||||
if (parent.target?.closed != false) return;
|
|
||||||
_callbacks[actionId] = callback;
|
|
||||||
_activeWebModel = WeakReference(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
void unregister(String actionId) {
|
|
||||||
_callbacks.remove(actionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
void registerRefresher(List<String> actionIds, ShortcutCallback refresh) {
|
|
||||||
if (parent.target?.closed != false) return;
|
|
||||||
for (final actionId in actionIds) {
|
|
||||||
_refreshers[actionId] = refresh;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void clear() {
|
|
||||||
_callbacks.clear();
|
|
||||||
_refreshers.clear();
|
|
||||||
if (identical(_activeWebModel?.target, this)) {
|
|
||||||
_activeWebModel = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void onWebTriggered(String actionId) {
|
|
||||||
final model = _activeWebModel?.target;
|
|
||||||
if (model != null) {
|
|
||||||
model.onTriggered(actionId);
|
|
||||||
} else {
|
|
||||||
debugPrint('shortcut_triggered: no active web shortcut model');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Called by the session event listener when a `shortcut_triggered` event
|
|
||||||
/// arrives for this session.
|
|
||||||
///
|
|
||||||
/// The matcher has already consumed the chord. With no handler the action
|
|
||||||
/// is unavailable in this session (e.g. screenshot on a peer without
|
|
||||||
/// support), and the chord is a deliberate no-op: a bound chord always
|
|
||||||
/// belongs to RustDesk and is never forwarded to the remote.
|
|
||||||
void onTriggered(String actionId) {
|
|
||||||
if (parent.target?.closed != false) return;
|
|
||||||
unawaited(Future.sync(() async {
|
|
||||||
final refresh = _refreshers[actionId];
|
|
||||||
if (refresh != null) {
|
|
||||||
await refresh();
|
|
||||||
if (!identical(_refreshers[actionId], refresh)) return;
|
|
||||||
}
|
|
||||||
if (parent.target?.closed != false) return;
|
|
||||||
final cb = _callbacks[actionId];
|
|
||||||
if (cb != null) {
|
|
||||||
await cb();
|
|
||||||
} else {
|
|
||||||
debugPrint('shortcut_triggered: no handler for $actionId');
|
|
||||||
}
|
|
||||||
}).catchError((e, st) {
|
|
||||||
debugPrint('shortcut_triggered: handler failed for $actionId: $e\n$st');
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _configRaw = '';
|
|
||||||
static ShortcutConfig _config = ShortcutConfig.parse('');
|
|
||||||
static ShortcutConfig _activeConfig = _config;
|
|
||||||
|
|
||||||
/// The stored config, parsed once per distinct stored value. The Flutter
|
|
||||||
/// matcher reads it on every key press, so a key press costs one config
|
|
||||||
/// read and no JSON parsing while the config is unchanged.
|
|
||||||
/// Runtime matching requests [active] to exclude platform-hidden bindings
|
|
||||||
/// while retaining the stored config for other platforms.
|
|
||||||
static ShortcutConfig config({bool active = false}) {
|
|
||||||
final raw = bind.mainGetLocalOption(key: kShortcutLocalConfigKey);
|
|
||||||
if (raw != _configRaw) {
|
|
||||||
_config = ShortcutConfig.parse(raw);
|
|
||||||
_activeConfig = _config.forPlatform(currentPlatformCapabilities());
|
|
||||||
_configRaw = raw;
|
|
||||||
}
|
|
||||||
return active ? _activeConfig : _config;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Read the bindings JSON from LocalConfig. Returns a copy the caller may
|
|
||||||
/// edit.
|
|
||||||
static List<Map<String, dynamic>> readBindings() => [
|
|
||||||
for (final binding in config().bindings)
|
|
||||||
Map<String, dynamic>.of(binding)
|
|
||||||
];
|
|
||||||
|
|
||||||
static bool isEnabled() => config().enabled;
|
|
||||||
|
|
||||||
static bool isPassThrough() => config().passThrough;
|
|
||||||
|
|
||||||
/// Persistent companion to [isEnabled]: when on, the matchers return early
|
|
||||||
/// and every keystroke flows through to the remote (i.e. all bindings are
|
|
||||||
/// suspended). Stored in the same JSON blob so a single reload refreshes
|
|
||||||
/// both flags on every active matcher.
|
|
||||||
static Future<void> setPassThrough(bool v) async {
|
|
||||||
final raw = bind.mainGetLocalOption(key: kShortcutLocalConfigKey);
|
|
||||||
Map<String, dynamic> json = {};
|
|
||||||
if (raw.isNotEmpty) {
|
|
||||||
try {
|
|
||||||
json = jsonDecode(raw) as Map<String, dynamic>;
|
|
||||||
} catch (_) {
|
|
||||||
json = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
json['pass_through'] = v;
|
|
||||||
await bind.mainSetLocalOption(
|
|
||||||
key: kShortcutLocalConfigKey, value: jsonEncode(json));
|
|
||||||
bind.mainReloadKeyboardShortcuts();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Flip the master `enabled` flag and persist. On the first enable we seed
|
|
||||||
/// the default bindings so common combos work out of the box; otherwise we
|
|
||||||
/// preserve whatever the user already has, an empty list included. Refreshes the matcher cache so
|
|
||||||
/// the change takes effect immediately (Rust on native, JS via the bridge
|
|
||||||
/// on Web).
|
|
||||||
static Future<void> setEnabled(bool v) async {
|
|
||||||
final raw = bind.mainGetLocalOption(key: kShortcutLocalConfigKey);
|
|
||||||
Map<String, dynamic> json = {};
|
|
||||||
if (raw.isNotEmpty) {
|
|
||||||
try {
|
|
||||||
json = jsonDecode(raw) as Map<String, dynamic>;
|
|
||||||
} catch (_) {
|
|
||||||
json = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
json['enabled'] = v;
|
|
||||||
if (v && shouldSeedDefaultShortcutBindings(json)) {
|
|
||||||
json['bindings'] = filterDefaultBindingsForPlatform(
|
|
||||||
jsonDecode(bind.mainGetDefaultKeyboardShortcuts()) as List,
|
|
||||||
currentPlatformCapabilities(),
|
|
||||||
);
|
|
||||||
} else if (json.containsKey('bindings')) {
|
|
||||||
json['bindings'] = shortcutBindingMapsFrom(json['bindings']);
|
|
||||||
}
|
|
||||||
await bind.mainSetLocalOption(
|
|
||||||
key: kShortcutLocalConfigKey, value: jsonEncode(json));
|
|
||||||
bind.mainReloadKeyboardShortcuts();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Single source of truth for the per-platform "is this shortcut applicable"
|
|
||||||
/// decisions. Both [setEnabled]'s default-seeding pass and the configuration
|
|
||||||
/// page's reset / list-rendering paths read from here, so the seed list and
|
|
||||||
/// the visible action list can never disagree on which platform a given
|
|
||||||
/// action belongs to.
|
|
||||||
///
|
|
||||||
/// Capability rationale:
|
|
||||||
/// * Fullscreen / Toolbar / Pin: rendered wherever the
|
|
||||||
/// desktop layout applies (native desktop + Web). Native mobile is
|
|
||||||
/// permanently full-screen and doesn't have a desktop-style toolbar.
|
|
||||||
/// * Screenshot / Switch Sides: native desktop only. The Web bridge
|
|
||||||
/// throws UnimplementedError for `sessionTakeScreenshot`; mobile
|
|
||||||
/// toolbars don't surface either action.
|
|
||||||
/// * Tab navigation / Close Tab: only native desktop ships
|
|
||||||
/// `DesktopTabController`; Web's `RemotePage` is invoked without one.
|
|
||||||
/// * Recording: native desktop has the `_RecordMenu` widget +
|
|
||||||
/// `registerSessionShortcutActions` registration; native Android has
|
|
||||||
/// the `toolbarControls` entry; iOS short-circuits inside
|
|
||||||
/// `recordingModel.toggle()`; Web has no implementation.
|
|
||||||
/// * Reset Canvas: only the mobile toolbar builds the menu entry
|
|
||||||
/// (`isDefaultConn && isMobile` in `toolbarControls`).
|
|
||||||
/// * Voice Call: iOS has no audio capture implementation; Web bridge throws
|
|
||||||
/// `UnimplementedError` for both `sessionRequestVoiceCall` and
|
|
||||||
/// `sessionCloseVoiceCall`.
|
|
||||||
static ShortcutPlatformCapabilities currentPlatformCapabilities() {
|
|
||||||
final desktopLayout = isDesktop || isWeb;
|
|
||||||
return ShortcutPlatformCapabilities(
|
|
||||||
includeFullscreenShortcut: desktopLayout,
|
|
||||||
includeScreenshotShortcut: isDesktop,
|
|
||||||
includeRelativeMouseModeShortcut:
|
|
||||||
isDesktop && !(isLinux && bind.mainCurrentIsWayland()),
|
|
||||||
includeTabShortcuts: isDesktop,
|
|
||||||
includeToolbarShortcut: desktopLayout,
|
|
||||||
includeCloseTabShortcut: isDesktop,
|
|
||||||
includeSwitchSidesShortcut: isDesktop,
|
|
||||||
includeRecordingShortcut: !isWeb && !isIOS,
|
|
||||||
includeResetCanvasShortcut: isMobile,
|
|
||||||
includePinToolbarShortcut: desktopLayout,
|
|
||||||
includeViewModeShortcut: true,
|
|
||||||
includeVoiceCallShortcut: !isWeb && !isIOS,
|
|
||||||
excludedActions: Set.unmodifiable({
|
|
||||||
if (!isDesktop) ...[
|
|
||||||
kShortcutActionSwitchDisplayAll,
|
|
||||||
kShortcutActionToggleEnableFileCopyPaste,
|
|
||||||
],
|
|
||||||
if (isMobile) ...[
|
|
||||||
kShortcutActionKeyboardModeLegacy,
|
|
||||||
kShortcutActionKeyboardModeMap,
|
|
||||||
kShortcutActionKeyboardModeTranslate,
|
|
||||||
kShortcutActionToggleShowMyCursor,
|
|
||||||
kShortcutActionToggleZoomCursor,
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One parsed view of the `keyboard-shortcuts` LocalConfig value. Malformed
|
|
||||||
/// or missing input parses as disabled with no bindings.
|
|
||||||
class ShortcutConfig {
|
|
||||||
final bool enabled;
|
|
||||||
final bool passThrough;
|
|
||||||
final List<Map<String, dynamic>> bindings;
|
|
||||||
|
|
||||||
const ShortcutConfig._(this.enabled, this.passThrough, this.bindings);
|
|
||||||
|
|
||||||
ShortcutConfig forPlatform(ShortcutPlatformCapabilities capabilities) {
|
|
||||||
final visible = allActionEntries(
|
|
||||||
filterKeyboardShortcutActionGroupsForPlatform(capabilities))
|
|
||||||
.map((entry) => entry.id)
|
|
||||||
.toSet();
|
|
||||||
final hidden = allActionEntries(kKeyboardShortcutActionGroups)
|
|
||||||
.map((entry) => entry.id)
|
|
||||||
.where((id) => !visible.contains(id))
|
|
||||||
.toSet();
|
|
||||||
return ShortcutConfig._(
|
|
||||||
enabled,
|
|
||||||
passThrough,
|
|
||||||
List.unmodifiable(bindings.where((b) => !hidden.contains(b['action']))),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static ShortcutConfig parse(String raw) {
|
|
||||||
if (raw.isEmpty) return const ShortcutConfig._(false, false, []);
|
|
||||||
try {
|
|
||||||
final parsed = jsonDecode(raw) as Map<String, dynamic>;
|
|
||||||
return ShortcutConfig._(
|
|
||||||
parsed['enabled'] == true,
|
|
||||||
parsed['pass_through'] == true,
|
|
||||||
List.unmodifiable(shortcutBindingMapsFrom(parsed['bindings'])),
|
|
||||||
);
|
|
||||||
} catch (_) {
|
|
||||||
return const ShortcutConfig._(false, false, []);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Register the default-bound shortcut actions that aren't already wired by
|
|
||||||
/// `toolbarControls(...)` (which handles things like Ctrl+Alt+Shift+Del and the
|
|
||||||
/// screenshot action). Called once per session from the desktop / mobile
|
|
||||||
/// remote page, after the toolbar registrations have run.
|
|
||||||
///
|
|
||||||
/// We register unconditionally — even when shortcuts are master-disabled —
|
|
||||||
/// because the matcher (Rust + JS) gates dispatch via the `enabled` flag,
|
|
||||||
/// so registered closures are functionally invisible until the user flips
|
|
||||||
/// shortcuts on. This keeps the wiring simple (no rebind callbacks across
|
|
||||||
/// sessions) and lets the user toggle shortcuts mid-session without
|
|
||||||
/// reconnecting.
|
|
||||||
///
|
|
||||||
/// [tabController] is the desktop window's tab controller; `null` on mobile /
|
|
||||||
/// web (where tab-switch shortcuts don't apply).
|
|
||||||
///
|
|
||||||
/// Each callback below is a no-op when the underlying state required to
|
|
||||||
/// service the action isn't available (e.g. only one display, only one tab).
|
|
||||||
void registerSessionShortcutActions(
|
|
||||||
FFI ffi, {
|
|
||||||
DesktopTabController? tabController,
|
|
||||||
ToolbarState? toolbarState,
|
|
||||||
}) {
|
|
||||||
final sessionId = ffi.sessionId;
|
|
||||||
|
|
||||||
// Note on disposal: every closure registered below captures `ffi` via
|
|
||||||
// closure environment, so the FFI object stays alive for the duration of
|
|
||||||
// the closure's execution — even across awaits, even if the session is
|
|
||||||
// closed mid-execution. We therefore don't add per-closure liveness
|
|
||||||
// guards: a `WeakReference<FFI>` check would never go null while the
|
|
||||||
// closure is on the call stack, and the underlying `bind.session*` /
|
|
||||||
// model setters tolerate stale-session calls (they no-op on torn-down
|
|
||||||
// sessions). ShortcutModel.onTriggered's existing entry guard
|
|
||||||
// (`_callbacks` lookup returning null after disposal) is the actual
|
|
||||||
// liveness gate.
|
|
||||||
|
|
||||||
// Toggle Fullscreen — available wherever the desktop layout renders
|
|
||||||
// (native desktop + every Web browser, since Web uses the desktop
|
|
||||||
// RemotePage). `stateGlobal.setFullscreen` handles native window vs.
|
|
||||||
// browser fullscreen. Native mobile is permanently full-screen, so the
|
|
||||||
// action is intentionally not registered there.
|
|
||||||
if (isDesktop || isWeb) {
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleFullscreen, () {
|
|
||||||
stateGlobal.setFullscreen(!stateGlobal.fullscreen.value);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle Recording — desktop only here. Mobile already wires this through
|
|
||||||
// `toolbarControls` (which adds a recording entry on `!(isDesktop||isWeb)`),
|
|
||||||
// but the desktop toolbar uses a separate `_RecordMenu` widget that has no
|
|
||||||
// `actionId`. Without this explicit registration a desktop user could bind
|
|
||||||
// Toggle Recording in settings and the press would have no handler.
|
|
||||||
// `recordingModel.toggle()` itself short-circuits on iOS and on sessions
|
|
||||||
// without recording permission.
|
|
||||||
if (isDesktop) {
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleRecording, () {
|
|
||||||
ffi.recordingModel.toggle();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void openDisplay(int display, PeerInfo pi, {bool updateCursorPos = true}) {
|
|
||||||
if (isDesktop &&
|
|
||||||
pi.isSupportMultiDisplay &&
|
|
||||||
bind.sessionGetDisplaysAsIndividualWindows(sessionId: sessionId) ==
|
|
||||||
'Y') {
|
|
||||||
openMonitorInNewTabOrWindow(display, ffi.id, pi);
|
|
||||||
} else {
|
|
||||||
openMonitorInTheSameTab(display, ffi, pi,
|
|
||||||
updateCursorPos: updateCursorPos);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Switch Display Next / Prev — requires the peer to have at least 2
|
|
||||||
// displays. From the "All displays" merged view, Next jumps to display 0
|
|
||||||
// and Prev to the last display, so the user can always escape the merged
|
|
||||||
// view via these shortcuts.
|
|
||||||
void switchDisplayBy(int delta) {
|
|
||||||
final pi = ffi.ffiModel.pi;
|
|
||||||
final privacyMode = PrivacyModeState.find(ffi.id).value;
|
|
||||||
if (privacyMode.isNotEmpty &&
|
|
||||||
!allowDisplaySwitchInPrivacyMode(pi, privacyMode)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final count = pi.displays.length;
|
|
||||||
if (count <= 1) return;
|
|
||||||
final current = pi.currentDisplay;
|
|
||||||
final int next;
|
|
||||||
if (current == kAllDisplayValue) {
|
|
||||||
next = delta > 0 ? 0 : count - 1;
|
|
||||||
} else {
|
|
||||||
next = ((current + delta) % count + count) % count;
|
|
||||||
}
|
|
||||||
openDisplay(next, pi, updateCursorPos: isMobile);
|
|
||||||
}
|
|
||||||
|
|
||||||
ffi.shortcutModel.register(kShortcutActionSwitchDisplayNext, () {
|
|
||||||
switchDisplayBy(1);
|
|
||||||
});
|
|
||||||
ffi.shortcutModel.register(kShortcutActionSwitchDisplayPrev, () {
|
|
||||||
switchDisplayBy(-1);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Switch to all-monitors view — mirrors the toolbar Monitor menu's
|
|
||||||
// "all monitors" button (only built when peer has >1 display). Not a
|
|
||||||
// toggle: the toolbar button just sets the merged view; another action
|
|
||||||
// (Switch to next/previous display, or another monitor button) takes
|
|
||||||
// you back to a single display.
|
|
||||||
//
|
|
||||||
// For same-tab view, use `openMonitorInTheSameTab` rather than calling
|
|
||||||
// `sessionSwitchDisplay` with `[kAllDisplayValue]` directly — the toolbar
|
|
||||||
// path treats `kAllDisplayValue` as a UI sentinel and expands it to the
|
|
||||||
// real display index list (`[0, 1, ...]`) before sending, then updates
|
|
||||||
// local FfiModel state. Sending `[-1]` raw produces a wire value the
|
|
||||||
// remote can't act on and skips the local state update, so the merged
|
|
||||||
// view never engages.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionSwitchDisplayAll, () {
|
|
||||||
final pi = ffi.ffiModel.pi;
|
|
||||||
final privacyMode = PrivacyModeState.find(ffi.id).value;
|
|
||||||
if (privacyMode.isNotEmpty &&
|
|
||||||
!allowDisplaySwitchInPrivacyMode(pi, privacyMode)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!pi.isSupportMultiDisplay || pi.displays.length <= 1) return;
|
|
||||||
if (pi.currentDisplay == kAllDisplayValue) return;
|
|
||||||
openDisplay(kAllDisplayValue, pi);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Switch tab next / prev — desktop only. The remote-screen tabs live in
|
|
||||||
// the window-scoped DesktopTabController, not on the FFI itself, so we
|
|
||||||
// need the controller from the page that owns this session. We
|
|
||||||
// intentionally don't expose positional ("Switch to tab N") shortcuts:
|
|
||||||
// counting tabs in a long list is impractical, and AnyDesk / Chrome
|
|
||||||
// standard practice is to favour next/prev navigation.
|
|
||||||
if (tabController != null) {
|
|
||||||
void switchTabBy(int delta) {
|
|
||||||
final tabs = tabController.state.value.tabs;
|
|
||||||
if (tabs.length <= 1) return;
|
|
||||||
final cur = tabs.indexWhere((t) => t.key == ffi.id);
|
|
||||||
if (cur < 0) return;
|
|
||||||
final next = (cur + delta + tabs.length) % tabs.length;
|
|
||||||
tabController.jumpTo(next);
|
|
||||||
}
|
|
||||||
|
|
||||||
ffi.shortcutModel
|
|
||||||
.register(kShortcutActionSwitchTabNext, () => switchTabBy(1));
|
|
||||||
ffi.shortcutModel
|
|
||||||
.register(kShortcutActionSwitchTabPrev, () => switchTabBy(-1));
|
|
||||||
|
|
||||||
// Close Tab — desktop only. Mirrors the tab right-click "Close" entry,
|
|
||||||
// including the audit-log confirmation dialog so a shortcut close goes
|
|
||||||
// through the same path as a menu close.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionCloseTab, () async {
|
|
||||||
if (await desktopTryShowTabAuditDialogCloseCancelled(
|
|
||||||
id: ffi.id,
|
|
||||||
tabController: tabController,
|
|
||||||
)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
tabController.closeBy(ffi.id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle Toolbar — desktop only. ToolbarState is window/session-scoped,
|
|
||||||
// owned by the RemotePage that hosts this session.
|
|
||||||
if (toolbarState != null) {
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleToolbar, () {
|
|
||||||
toolbarState.switchHide(sessionId);
|
|
||||||
});
|
|
||||||
ffi.shortcutModel.register(kShortcutActionPinToolbar, () {
|
|
||||||
toolbarState.switchPin();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Toggle Chat overlay (open/close the chat panel for this session).
|
|
||||||
// _ChatMenu is a standalone toolbar icon — not part of any toolbar
|
|
||||||
// helper that returns a TToggleMenu list — so its handler is wired
|
|
||||||
// here rather than picked up by helper auto-register.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleChat, () {
|
|
||||||
ffi.chatModel.changeCurrentKey(MessageKey(ffi.id, ChatModel.clientModeID));
|
|
||||||
ffi.chatModel.toggleChatOverlay();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Toggle Voice Call — start when idle, hang up when active. Mirrors the
|
|
||||||
// toolbar's `_VoiceCallMenu` state-driven button. Web bridge throws
|
|
||||||
// UnimplementedError on both sessionRequestVoiceCall and
|
|
||||||
// sessionCloseVoiceCall; iOS has no audio capture implementation.
|
|
||||||
if (!isWeb && !isIOS) {
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleVoiceCall, () {
|
|
||||||
final status = ffi.chatModel.voiceCallStatus.value;
|
|
||||||
if (status == VoiceCallStatus.connected ||
|
|
||||||
status == VoiceCallStatus.waitingForResponse) {
|
|
||||||
bind.sessionCloseVoiceCall(sessionId: sessionId);
|
|
||||||
} else {
|
|
||||||
bind.sessionRequestVoiceCall(sessionId: sessionId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Inline _KeyboardMenu items + actions with no toolbar TToggleMenu/TRadioMenu ─
|
|
||||||
// The toolbar's TToggleMenu / TRadioMenu helpers (toolbarDisplayToggle,
|
|
||||||
// toolbarCursor, toolbarKeyboardToggles, toolbarCodec, toolbarPrivacyMode,
|
|
||||||
// toolbarViewStyle, toolbarImageQuality) auto-register their tagged entries
|
|
||||||
// from the bottom of each helper. The handlers below cover what those
|
|
||||||
// helpers DON'T own:
|
|
||||||
// * Show my cursor / Keyboard mode (Map/Translate/Legacy) / View Only
|
|
||||||
// (desktop) — built as widgets directly in `_KeyboardMenu`, not as
|
|
||||||
// TToggleMenu lists. (Mobile View Only IS in toolbarDisplayToggle and
|
|
||||||
// auto-registers; the desktop session-start handler below registers
|
|
||||||
// first and the helper's auto-register on mobile takes over after its
|
|
||||||
// unawaited future resolves.)
|
|
||||||
// * Plug out all virtual displays — built in `getVirtualDisplayMenuChildren`
|
|
||||||
// as a MenuButton, not a TToggleMenu.
|
|
||||||
// * Toggle Input Source — cycle action; the toolbar exposes per-source
|
|
||||||
// radios but no single "cycle to next source" entry.
|
|
||||||
|
|
||||||
// Show my cursor — toolbar (`_KeyboardMenu.showMyCursor`) pushes the new
|
|
||||||
// value into FfiModel.setShowMyCursor and auto-enables view-only when the
|
|
||||||
// toggle goes on, so the user can never control the remote with their own
|
|
||||||
// cursor visible.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleShowMyCursor, () async {
|
|
||||||
await bind.sessionToggleOption(
|
|
||||||
sessionId: sessionId, value: kOptionToggleShowMyCursor);
|
|
||||||
final showMyCursor = await bind.sessionGetToggleOption(
|
|
||||||
sessionId: sessionId, arg: kOptionToggleShowMyCursor) ??
|
|
||||||
false;
|
|
||||||
ffi.ffiModel.setShowMyCursor(showMyCursor);
|
|
||||||
if (showMyCursor && !ffi.ffiModel.viewOnly) {
|
|
||||||
await bind.sessionToggleOption(
|
|
||||||
sessionId: sessionId, value: kOptionToggleViewOnly);
|
|
||||||
final viewOnly = await bind.sessionGetToggleOption(
|
|
||||||
sessionId: sessionId, arg: kOptionToggleViewOnly) ??
|
|
||||||
false;
|
|
||||||
ffi.ffiModel.setViewOnly(ffi.id, viewOnly);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Keyboard mode (Map / Translate / Legacy). Mirrors the radio buttons in
|
|
||||||
// `_KeyboardMenu.keyboardMode()` (built as RdoMenuButton, not TRadioMenu).
|
|
||||||
void registerKeyboardMode(String actionId, String mode) {
|
|
||||||
ffi.shortcutModel.register(actionId, () async {
|
|
||||||
if (!ffi.ffiModel.keyboard ||
|
|
||||||
ffi.ffiModel.viewOnly ||
|
|
||||||
!bind.sessionIsKeyboardModeSupported(
|
|
||||||
sessionId: sessionId, mode: mode) ||
|
|
||||||
(ffi.ffiModel.pi.isWayland && mode != kKeyMapMode)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (isInputSourceFlutter && isDesktop) {
|
|
||||||
final modeOnly = bind.sessionIsKeyboardModeSupported(
|
|
||||||
sessionId: sessionId, mode: kKeyMapMode)
|
|
||||||
? kKeyMapMode
|
|
||||||
: kKeyLegacyMode;
|
|
||||||
if (mode != modeOnly) return;
|
|
||||||
}
|
|
||||||
await bind.sessionSetKeyboardMode(sessionId: sessionId, value: mode);
|
|
||||||
await ffi.inputModel.updateKeyboardMode();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
registerKeyboardMode(kShortcutActionKeyboardModeMap, kKeyMapMode);
|
|
||||||
registerKeyboardMode(kShortcutActionKeyboardModeTranslate, kKeyTranslateMode);
|
|
||||||
registerKeyboardMode(kShortcutActionKeyboardModeLegacy, kKeyLegacyMode);
|
|
||||||
|
|
||||||
// Plug out all virtual displays (Windows + IDD only). Mirrors the toolbar's
|
|
||||||
// "Plug out all" button — present in both IDD modes (RustDesk + Amyuni),
|
|
||||||
// built as a MenuButton inside `getVirtualDisplayMenuChildren`.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionPlugOutAllVirtualDisplays, () {
|
|
||||||
if (ffi.connType != ConnType.defaultConn ||
|
|
||||||
!showVirtualDisplayMenu(ffi) ||
|
|
||||||
PrivacyModeState.find(ffi.id).value.isNotEmpty ||
|
|
||||||
(ffi.ffiModel.pi.isAmyuniIdd &&
|
|
||||||
ffi.ffiModel.pi.amyuniVirtualDisplayCount == 0)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
bind.sessionToggleVirtualDisplay(
|
|
||||||
sessionId: sessionId,
|
|
||||||
index: kAllVirtualDisplay,
|
|
||||||
on: false,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Privacy mode 1 / 2 — fallback handlers for the single-impl and null-impls
|
|
||||||
// branches of `toolbarPrivacyMode`. The multi-impl branch tags each entry
|
|
||||||
// with the matching actionId and `_registerToggleMenuShortcuts` overrides
|
|
||||||
// these closures with the toolbar's own onChanged. But when the peer only
|
|
||||||
// advertises a single impl (older Linux peers, certain platform configs)
|
|
||||||
// toolbarPrivacyMode returns a `getDefaultMenu` entry without an actionId,
|
|
||||||
// so the auto-register pass skips it — these fallbacks are what actually
|
|
||||||
// wire the shortcut in that case.
|
|
||||||
String? findPrivacyImpl(String nameKey) {
|
|
||||||
final impls = ffi.ffiModel.pi
|
|
||||||
.platformAdditions[kPlatformAdditionsSupportedPrivacyModeImpl]
|
|
||||||
as List<dynamic>?;
|
|
||||||
if (impls == null) return null;
|
|
||||||
for (final e in impls) {
|
|
||||||
if (e is List && e.length >= 2 && e[1] == nameKey) return e[0] as String;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool checkPrivacyModeAllowed(String implKey) {
|
|
||||||
final ffiModel = ffi.ffiModel;
|
|
||||||
final pi = ffiModel.pi;
|
|
||||||
final privacyMode = PrivacyModeState.find(ffi.id).value;
|
|
||||||
if (ffi.connType != ConnType.defaultConn ||
|
|
||||||
ffiModel.viewOnly ||
|
|
||||||
(privacyMode.isEmpty &&
|
|
||||||
(!pi.features.privacyMode || !ffiModel.keyboard))) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (privacyMode == implKey) return true;
|
|
||||||
if (ffiModel.permissions['privacy_mode'] == false) return false;
|
|
||||||
if (allowDisplaySwitchInPrivacyMode(pi, implKey) ||
|
|
||||||
(pi.currentDisplay == 0 &&
|
|
||||||
!bind.sessionIsMultiUiSession(sessionId: sessionId))) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
msgBox(sessionId, 'custom-nook-nocancel-hasclose', 'info',
|
|
||||||
'Please switch to Display 1 first', '', ffi.dialogManager);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Match the multi-impl branch of `toolbarPrivacyMode`: turn this impl on iff
|
|
||||||
// the active impl isn't already this one. Comparing `.value == implKey`
|
|
||||||
// (rather than `.value.isEmpty`) means pressing the mode-1 shortcut while
|
|
||||||
// mode 2 is on correctly turns mode 1 ON, instead of misreading the
|
|
||||||
// "any-mode-active" state as "this-mode-active" and toggling OFF.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionPrivacyMode1, () {
|
|
||||||
if (ffi.ffiModel.pi
|
|
||||||
.platformAdditions[kPlatformAdditionsSupportedPrivacyModeImpl] ==
|
|
||||||
null) {
|
|
||||||
// Older peers use the legacy option instead of a named implementation.
|
|
||||||
if (!checkPrivacyModeAllowed(kPrivacyModeImplMag)) return;
|
|
||||||
bind.sessionToggleOption(sessionId: sessionId, value: 'privacy-mode');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final implKey = findPrivacyImpl('privacy_mode_impl_mag_tip');
|
|
||||||
if (implKey == null) return;
|
|
||||||
if (!checkPrivacyModeAllowed(implKey)) return;
|
|
||||||
bind.sessionTogglePrivacyMode(
|
|
||||||
sessionId: sessionId,
|
|
||||||
implKey: implKey,
|
|
||||||
on: PrivacyModeState.find(ffi.id).value != implKey,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
ffi.shortcutModel.register(kShortcutActionPrivacyMode2, () {
|
|
||||||
final implKey = findPrivacyImpl('privacy_mode_impl_virtual_display_tip');
|
|
||||||
if (implKey == null) return;
|
|
||||||
if (!checkPrivacyModeAllowed(implKey)) return;
|
|
||||||
bind.sessionTogglePrivacyMode(
|
|
||||||
sessionId: sessionId,
|
|
||||||
implKey: implKey,
|
|
||||||
on: PrivacyModeState.find(ffi.id).value != implKey,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// View Only — desktop toolbar exposes this inline in `_KeyboardMenu.viewMode`
|
|
||||||
// (mobile is in toolbarDisplayToggle and goes through helper auto-register).
|
|
||||||
// Mirrors the desktop callback: toggle + sync FfiModel.viewOnly +
|
|
||||||
// FfiModel.showMyCursor (the toolbar keeps these in step).
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleViewOnly, () async {
|
|
||||||
await bind.sessionToggleOption(
|
|
||||||
sessionId: sessionId, value: kOptionToggleViewOnly);
|
|
||||||
final viewOnly = await bind.sessionGetToggleOption(
|
|
||||||
sessionId: sessionId, arg: kOptionToggleViewOnly) ??
|
|
||||||
false;
|
|
||||||
ffi.ffiModel.setViewOnly(ffi.id, viewOnly);
|
|
||||||
final showMyCursor = await bind.sessionGetToggleOption(
|
|
||||||
sessionId: sessionId, arg: kOptionToggleShowMyCursor) ??
|
|
||||||
false;
|
|
||||||
ffi.ffiModel.setShowMyCursor(showMyCursor);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Toggle Reverse mouse wheel — read current 'Y'/'N' (falling back to user
|
|
||||||
// default), flip, write back.
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleReverseMouseWheel, () async {
|
|
||||||
if (!ffi.ffiModel.keyboard || ffi.ffiModel.viewOnly) return;
|
|
||||||
var cur = bind.sessionGetReverseMouseWheelSync(sessionId: sessionId) ?? '';
|
|
||||||
if (cur == '') {
|
|
||||||
cur = bind.mainGetUserDefaultOption(key: kKeyReverseMouseWheel);
|
|
||||||
}
|
|
||||||
final next = cur == 'Y' ? 'N' : 'Y';
|
|
||||||
await bind.sessionSetReverseMouseWheel(sessionId: sessionId, value: next);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Toggle Relative mouse mode (gaming mode). Desktop only.
|
|
||||||
if (isDesktop && !isWeb) {
|
|
||||||
ffi.shortcutModel.register(kShortcutActionToggleRelativeMouseMode, () {
|
|
||||||
ffi.inputModel.toggleRelativeMouseMode();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -70,6 +70,10 @@ class TerminalModel with ChangeNotifier {
|
|||||||
|
|
||||||
final _inputBuffer = <String>[];
|
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.
|
// Buffer for output data received before terminal view has valid dimensions.
|
||||||
// This prevents NaN errors when writing to terminal before layout is complete.
|
// This prevents NaN errors when writing to terminal before layout is complete.
|
||||||
final _pendingOutputChunks = <String>[];
|
final _pendingOutputChunks = <String>[];
|
||||||
|
|||||||
@@ -153,7 +153,6 @@ class PlatformFFI {
|
|||||||
gFFI.dialogManager.dismissAll();
|
gFFI.dialogManager.dismissAll();
|
||||||
closeConnection();
|
closeConnection();
|
||||||
};
|
};
|
||||||
await _ffiBind.mainInit(appDir: '');
|
|
||||||
context.callMethod('init');
|
context.callMethod('init');
|
||||||
version = getByName('version');
|
version = getByName('version');
|
||||||
window.onContextMenu.listen((event) {
|
window.onContextMenu.listen((event) {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import 'package:uuid/uuid.dart';
|
|||||||
import 'dart:html' as html;
|
import 'dart:html' as html;
|
||||||
|
|
||||||
import 'package:flutter_hbb/consts.dart';
|
import 'package:flutter_hbb/consts.dart';
|
||||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
|
||||||
|
|
||||||
final _privateConstructorUsedError = UnsupportedError(
|
final _privateConstructorUsedError = UnsupportedError(
|
||||||
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
|
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
|
||||||
@@ -992,28 +991,6 @@ class RustdeskImpl {
|
|||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tell the JS-side matcher (flutter/web/js/src/shortcut_matcher.ts) to
|
|
||||||
// use the same platform-filtered bindings as the Flutter matcher, while
|
|
||||||
// keeping unsupported saved bindings in LocalStorage.
|
|
||||||
void mainReloadKeyboardShortcuts({dynamic hint}) {
|
|
||||||
final config = ShortcutModel.config(active: true);
|
|
||||||
js.context.callMethod('reloadShortcuts', [
|
|
||||||
jsonEncode({
|
|
||||||
'enabled': config.enabled,
|
|
||||||
'pass_through': config.passThrough,
|
|
||||||
'bindings': config.bindings,
|
|
||||||
})
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Web has no Rust at runtime, so the defaults seed comes from the
|
|
||||||
// [kDefaultShortcutBindings] canonical in shortcut_constants.dart. Parity
|
|
||||||
// with Rust's `default_bindings()` is enforced by tests on both sides
|
|
||||||
// against `flutter/test/fixtures/default_keyboard_shortcuts.json`.
|
|
||||||
String mainGetDefaultKeyboardShortcuts({dynamic hint}) {
|
|
||||||
return jsonEncode(kDefaultShortcutBindings);
|
|
||||||
}
|
|
||||||
|
|
||||||
String mainGetInputSource({dynamic hint}) {
|
String mainGetInputSource({dynamic hint}) {
|
||||||
final inputSource =
|
final inputSource =
|
||||||
js.context.callMethod('getByName', ['option:local', 'input-source']);
|
js.context.callMethod('getByName', ['option:local', 'input-source']);
|
||||||
@@ -1260,17 +1237,6 @@ class RustdeskImpl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> mainInit({required String appDir, dynamic hint}) {
|
Future<void> mainInit({required String appDir, dynamic hint}) {
|
||||||
// JS -> Dart shortcut bridge. The matcher in flutter/web/js/src/
|
|
||||||
// shortcut_matcher.ts calls `window.onShortcutTriggered(actionId)` when a
|
|
||||||
// binding fires; route it to the active session's ShortcutModel.
|
|
||||||
// Web uses a JS-side connection, so the event does not arrive through the
|
|
||||||
// native session event stream.
|
|
||||||
js.context['onShortcutTriggered'] = (dynamic action) {
|
|
||||||
if (action is String) {
|
|
||||||
ShortcutModel.onWebTriggered(action);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
mainReloadKeyboardShortcuts();
|
|
||||||
return Future.value();
|
return Future.value();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -339,8 +339,8 @@ packages:
|
|||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
path: "."
|
path: "."
|
||||||
ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
|
ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
|
||||||
resolved-ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
|
resolved-ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
|
||||||
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
|
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
|
||||||
source: git
|
source: git
|
||||||
version: "0.1.0"
|
version: "0.1.0"
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
|
|||||||
# Read more about iOS versioning at
|
# Read more about iOS versioning at
|
||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# 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
|
# 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.1+68
|
version: 1.5.0+68
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: '^3.1.0'
|
sdk: '^3.1.0'
|
||||||
@@ -58,7 +58,7 @@ dependencies:
|
|||||||
desktop_multi_window:
|
desktop_multi_window:
|
||||||
git:
|
git:
|
||||||
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
|
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
|
||||||
ref: cddc2e64f8fefce4f80db87b20bcda2dd019bed6
|
ref: 8b774a66671cbb9bcb2631af6ac28f9bdd469ce3
|
||||||
freezed_annotation: ^2.0.3
|
freezed_annotation: ^2.0.3
|
||||||
flutter_custom_cursor:
|
flutter_custom_cursor:
|
||||||
git:
|
git:
|
||||||
|
|||||||
@@ -48,6 +48,74 @@ void main() {
|
|||||||
expect(peers.single.online, isTrue);
|
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 {
|
test('online callback updates currently displayed options', () async {
|
||||||
final loader = AllPeersLoader(
|
final loader = AllPeersLoader(
|
||||||
queryOnlines: (ids) async {},
|
queryOnlines: (ids) async {},
|
||||||
@@ -64,4 +132,17 @@ void main() {
|
|||||||
expect(displayedOptions.single.online, isTrue);
|
expect(displayedOptions.single.online, isTrue);
|
||||||
await Future.delayed(Duration(milliseconds: 2));
|
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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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,3 +1,4 @@
|
|||||||
|
import 'dart:async';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
@@ -14,14 +15,36 @@ class _Cursor extends CursorModel {
|
|||||||
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
||||||
final core = <String, CursorShape>{};
|
final core = <String, CursorShape>{};
|
||||||
final fetched = <String>[];
|
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
|
@override
|
||||||
Future<CursorShape?> fetchCursorShape(String id) {
|
Future<CursorShape?> fetchCursorShape(String id) {
|
||||||
fetched.add(id);
|
fetched.add(id);
|
||||||
return Future.value(core[id]);
|
if (throwAtOnce) throw StateError('no core');
|
||||||
|
if (!holdFetches) return Future.value(core[id]);
|
||||||
|
final answer = Completer<CursorShape?>();
|
||||||
|
_held[answer] = id;
|
||||||
|
return answer.future;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void answerFetches() {
|
||||||
|
final held = Map.of(_held);
|
||||||
|
_held.clear();
|
||||||
|
held.forEach((answer, id) => answer.complete(core[id]));
|
||||||
|
}
|
||||||
|
|
||||||
|
void failFetches() {
|
||||||
|
final held = Map.of(_held);
|
||||||
|
_held.clear();
|
||||||
|
held.forEach((answer, _) => answer.completeError(StateError('failed')));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool showRemoteCursor = false;
|
||||||
@override
|
@override
|
||||||
bool get showsRemoteCursor => false;
|
bool get showsRemoteCursor => showRemoteCursor;
|
||||||
}
|
}
|
||||||
|
|
||||||
String? _key(MouseCursor cursor) =>
|
String? _key(MouseCursor cursor) =>
|
||||||
@@ -158,6 +181,28 @@ void main() {
|
|||||||
expect(registered.length, 100);
|
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',
|
test('a new raster of a shape without pixels keeps the cursor shown before',
|
||||||
() async {
|
() async {
|
||||||
final cursor = ffi.cursorModel;
|
final cursor = ffi.cursorModel;
|
||||||
@@ -175,6 +220,134 @@ void main() {
|
|||||||
cursor.nativeKey(cursor.cache!, 0.5));
|
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',
|
test('a shape painted again is decoded again, the last one shown meanwhile',
|
||||||
() async {
|
() async {
|
||||||
await _feed(ffi, '1', size: 16);
|
await _feed(ffi, '1', size: 16);
|
||||||
@@ -187,6 +360,89 @@ void main() {
|
|||||||
expect(ffi.cursorModel.shapeIds, ['1']);
|
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',
|
test('a moved tab carries the id in use, and its window asks the core',
|
||||||
() async {
|
() async {
|
||||||
await _feed(ffi, '1', size: 16);
|
await _feed(ffi, '1', size: 16);
|
||||||
@@ -207,6 +463,30 @@ void main() {
|
|||||||
expect(moved.cursorModel.image?.width, 16);
|
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 {
|
test('a tab closing does not delete the cursors of another tab', () async {
|
||||||
final other = _FFI();
|
final other = _FFI();
|
||||||
addTearDown(other.cursorModel.disposeImages);
|
addTearDown(other.cursorModel.disposeImages);
|
||||||
@@ -222,4 +502,182 @@ void main() {
|
|||||||
await _settle();
|
await _settle();
|
||||||
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
|
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,11 +108,17 @@ void main() {
|
|||||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
|
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
|
||||||
for (final scenario in [
|
for (final scenario in [
|
||||||
((4, 64), 0.5, (2, 32)),
|
((4, 64), 0.5, (2, 32)),
|
||||||
|
((64, 4), 0.5, (32, 2)),
|
||||||
|
((1, 64), 0.25, (1, 16)),
|
||||||
((8, 8), 0.5, (12, 12)),
|
((8, 8), 0.5, (12, 12)),
|
||||||
|
((4, 64), 1.0, (4, 64)),
|
||||||
|
((1, 512), 10.0, (1, 512)),
|
||||||
]) {
|
]) {
|
||||||
test('native cursor size $scenario',
|
test('native cursor size $scenario',
|
||||||
() => _checkSize(scenario, registrations));
|
() => _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 {
|
test('cursor resize limits preserve the last valid raster', () async {
|
||||||
for (final size in [(30, 20), (20, 30)]) {
|
for (final size in [(30, 20), (20, 30)]) {
|
||||||
await _checkResizeLimits(size, registrations);
|
await _checkResizeLimits(size, registrations);
|
||||||
@@ -126,15 +132,15 @@ void main() {
|
|||||||
test('Windows peer cursor alpha survives resizing $pattern',
|
test('Windows peer cursor alpha survives resizing $pattern',
|
||||||
() => _checkWindowsPeerAlpha(pattern, registrations));
|
() => _checkWindowsPeerAlpha(pattern, registrations));
|
||||||
}
|
}
|
||||||
for (final (style, zoom) in [
|
for (final style in [
|
||||||
(kRemoteViewStyleOriginal, false),
|
kRemoteViewStyleOriginal,
|
||||||
(kRemoteViewStyleAdaptive, false),
|
kRemoteViewStyleAdaptive,
|
||||||
(kRemoteViewStyleAdaptive, true),
|
kRemoteViewStyleCustom
|
||||||
(kRemoteViewStyleCustom, false),
|
|
||||||
(kRemoteViewStyleCustom, true),
|
|
||||||
]) {
|
]) {
|
||||||
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
|
for (final zoom in [false, true]) {
|
||||||
(tester) => _checkView(tester, (style, zoom), registrations));
|
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
|
||||||
|
(tester) => _checkView(tester, (style, zoom), registrations));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +241,31 @@ 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(
|
Future<void> _checkResizeLimits(
|
||||||
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
|
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
|
||||||
const maxSide = 512;
|
const maxSide = 512;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:flutter_hbb/models/file_model.dart';
|
import 'package:flutter_hbb/models/file_model.dart';
|
||||||
@@ -61,6 +62,19 @@ void main() {
|
|||||||
expect(directory.path, '/fast');
|
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 {
|
test('a resolved Home path completes the sole empty-path request', () async {
|
||||||
final sent = <_SentRead>[];
|
final sent = <_SentRead>[];
|
||||||
final fileFetcher = FileFetcher(
|
final fileFetcher = FileFetcher(
|
||||||
@@ -93,6 +107,35 @@ void main() {
|
|||||||
expect(controller.directory.value.path, '/home/user');
|
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 {
|
test('a read error completes the sole pending request', () async {
|
||||||
final fileFetcher = FileFetcher(
|
final fileFetcher = FileFetcher(
|
||||||
() => _sessionId,
|
() => _sessionId,
|
||||||
@@ -187,6 +230,35 @@ void main() {
|
|||||||
expect((await replacement).path, '/same');
|
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 {
|
test('navigation ignores stale directory responses', () async {
|
||||||
final fileFetcher = FileFetcher(
|
final fileFetcher = FileFetcher(
|
||||||
() => _sessionId,
|
() => _sessionId,
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
[
|
|
||||||
{"action": "send_ctrl_alt_del", "mods": ["primary", "alt", "shift"], "key": "delete"},
|
|
||||||
{"action": "toggle_fullscreen", "mods": ["primary", "alt", "shift"], "key": "enter"},
|
|
||||||
{"action": "switch_display_next", "mods": ["primary", "alt", "shift"], "key": "arrow_right"},
|
|
||||||
{"action": "switch_display_prev", "mods": ["primary", "alt", "shift"], "key": "arrow_left"},
|
|
||||||
{"action": "screenshot", "mods": ["primary", "alt", "shift"], "key": "p"},
|
|
||||||
{"action": "toggle_show_remote_cursor", "mods": ["primary", "alt", "shift"], "key": "m"},
|
|
||||||
{"action": "toggle_mute", "mods": ["primary", "alt", "shift"], "key": "s"},
|
|
||||||
{"action": "toggle_block_input", "mods": ["primary", "alt", "shift"], "key": "i"},
|
|
||||||
{"action": "toggle_chat", "mods": ["primary", "alt", "shift"], "key": "c"}
|
|
||||||
]
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
[
|
|
||||||
"close_tab",
|
|
||||||
"switch_tab_next",
|
|
||||||
"switch_tab_prev",
|
|
||||||
"restart_remote",
|
|
||||||
"switch_sides",
|
|
||||||
"toggle_chat"
|
|
||||||
]
|
|
||||||
-65
@@ -1,65 +0,0 @@
|
|||||||
[
|
|
||||||
["a", 4],
|
|
||||||
["b", 5],
|
|
||||||
["c", 6],
|
|
||||||
["d", 7],
|
|
||||||
["e", 8],
|
|
||||||
["f", 9],
|
|
||||||
["g", 10],
|
|
||||||
["h", 11],
|
|
||||||
["i", 12],
|
|
||||||
["j", 13],
|
|
||||||
["k", 14],
|
|
||||||
["l", 15],
|
|
||||||
["m", 16],
|
|
||||||
["n", 17],
|
|
||||||
["o", 18],
|
|
||||||
["p", 19],
|
|
||||||
["q", 20],
|
|
||||||
["r", 21],
|
|
||||||
["s", 22],
|
|
||||||
["t", 23],
|
|
||||||
["u", 24],
|
|
||||||
["v", 25],
|
|
||||||
["w", 26],
|
|
||||||
["x", 27],
|
|
||||||
["y", 28],
|
|
||||||
["z", 29],
|
|
||||||
["digit1", 30],
|
|
||||||
["digit2", 31],
|
|
||||||
["digit3", 32],
|
|
||||||
["digit4", 33],
|
|
||||||
["digit5", 34],
|
|
||||||
["digit6", 35],
|
|
||||||
["digit7", 36],
|
|
||||||
["digit8", 37],
|
|
||||||
["digit9", 38],
|
|
||||||
["digit0", 39],
|
|
||||||
["f1", 58],
|
|
||||||
["f2", 59],
|
|
||||||
["f3", 60],
|
|
||||||
["f4", 61],
|
|
||||||
["f5", 62],
|
|
||||||
["f6", 63],
|
|
||||||
["f7", 64],
|
|
||||||
["f8", 65],
|
|
||||||
["f9", 66],
|
|
||||||
["f10", 67],
|
|
||||||
["f11", 68],
|
|
||||||
["f12", 69],
|
|
||||||
["delete", 76],
|
|
||||||
["backspace", 42],
|
|
||||||
["tab", 43],
|
|
||||||
["space", 44],
|
|
||||||
["enter", 40],
|
|
||||||
["enter", 88],
|
|
||||||
["arrow_left", 80],
|
|
||||||
["arrow_right", 79],
|
|
||||||
["arrow_up", 82],
|
|
||||||
["arrow_down", 81],
|
|
||||||
["home", 74],
|
|
||||||
["end", 77],
|
|
||||||
["page_up", 75],
|
|
||||||
["page_down", 78],
|
|
||||||
["insert", 73]
|
|
||||||
]
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
[
|
|
||||||
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
|
|
||||||
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
|
|
||||||
"digit0", "digit1", "digit2", "digit3", "digit4",
|
|
||||||
"digit5", "digit6", "digit7", "digit8", "digit9",
|
|
||||||
"f1", "f2", "f3", "f4", "f5", "f6",
|
|
||||||
"f7", "f8", "f9", "f10", "f11", "f12",
|
|
||||||
"delete", "backspace", "tab", "space", "enter",
|
|
||||||
"arrow_left", "arrow_right", "arrow_up", "arrow_down",
|
|
||||||
"home", "end", "page_up", "page_down", "insert"
|
|
||||||
]
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
@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,6 +4,19 @@ import 'package:flutter_hbb/models/input_modifier_utils.dart';
|
|||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
group('shouldReleaseStaleMobileShift', () {
|
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', () {
|
test('releases one-shot mobile shift after a text key', () {
|
||||||
expect(
|
expect(
|
||||||
shouldReleaseStaleMobileShift(
|
shouldReleaseStaleMobileShift(
|
||||||
@@ -17,6 +30,20 @@ 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', () {
|
test('does not release when shift is still physically pressed', () {
|
||||||
expect(
|
expect(
|
||||||
shouldReleaseStaleMobileShift(
|
shouldReleaseStaleMobileShift(
|
||||||
@@ -29,9 +56,84 @@ void main() {
|
|||||||
isFalse,
|
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', () {
|
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', () {
|
test('rejects terminal control bytes and multi-character sequences', () {
|
||||||
for (final input in ['\x00', '\x03', '\t', '\n', '\r', '\x1B', '\x7F']) {
|
for (final input in ['\x00', '\x03', '\t', '\n', '\r', '\x1B', '\x7F']) {
|
||||||
expect(
|
expect(
|
||||||
@@ -45,6 +147,43 @@ void main() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
group('applyTerminalInputModifiers', () {
|
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', () {
|
test('maps the complete Ctrl symbol range', () {
|
||||||
const mappings = {
|
const mappings = {
|
||||||
'[': '\x1B',
|
'[': '\x1B',
|
||||||
@@ -80,6 +219,22 @@ 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', () {
|
group('prepareTerminalInputPayload', () {
|
||||||
test('normalizes a mobile keyboard Enter to carriage return', () {
|
test('normalizes a mobile keyboard Enter to carriage return', () {
|
||||||
expect(
|
expect(
|
||||||
@@ -123,9 +278,26 @@ 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',
|
test('keeps decomposed graphemes intact with locked keyboard modifiers',
|
||||||
() {
|
() {
|
||||||
const decomposedEAcute = 'é';
|
const decomposedEAcute = 'e\u0301';
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
prepareTerminalInputPayload(
|
prepareTerminalInputPayload(
|
||||||
@@ -140,6 +312,20 @@ 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', () {
|
test('wraps paste without applying locked modifiers', () {
|
||||||
expect(
|
expect(
|
||||||
prepareTerminalInputPayload(
|
prepareTerminalInputPayload(
|
||||||
@@ -187,6 +373,25 @@ 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',
|
test('handles Ctrl+V and Meta+V when a virtual modifier lock is active',
|
||||||
() {
|
() {
|
||||||
expect(
|
expect(
|
||||||
@@ -218,6 +423,95 @@ void main() {
|
|||||||
isTrue,
|
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', () {
|
group('shouldClearTerminalModifiersWhenRow3Collapses', () {
|
||||||
@@ -232,5 +526,29 @@ void main() {
|
|||||||
isTrue,
|
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,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,507 +0,0 @@
|
|||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_actions.dart';
|
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart';
|
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_utils.dart';
|
|
||||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
|
||||||
|
|
||||||
ShortcutPlatformCapabilities capabilities({
|
|
||||||
bool includeFullscreenShortcut = true,
|
|
||||||
bool includeScreenshotShortcut = true,
|
|
||||||
bool includeRelativeMouseModeShortcut = true,
|
|
||||||
bool includeTabShortcuts = true,
|
|
||||||
bool includeToolbarShortcut = true,
|
|
||||||
bool includeCloseTabShortcut = true,
|
|
||||||
bool includeSwitchSidesShortcut = true,
|
|
||||||
bool includeRecordingShortcut = true,
|
|
||||||
bool includeResetCanvasShortcut = true,
|
|
||||||
bool includePinToolbarShortcut = true,
|
|
||||||
bool includeViewModeShortcut = true,
|
|
||||||
bool includeVoiceCallShortcut = true,
|
|
||||||
Set<String> excludedActions = const {},
|
|
||||||
}) {
|
|
||||||
return ShortcutPlatformCapabilities(
|
|
||||||
includeFullscreenShortcut: includeFullscreenShortcut,
|
|
||||||
includeScreenshotShortcut: includeScreenshotShortcut,
|
|
||||||
includeRelativeMouseModeShortcut: includeRelativeMouseModeShortcut,
|
|
||||||
includeTabShortcuts: includeTabShortcuts,
|
|
||||||
includeToolbarShortcut: includeToolbarShortcut,
|
|
||||||
includeCloseTabShortcut: includeCloseTabShortcut,
|
|
||||||
includeSwitchSidesShortcut: includeSwitchSidesShortcut,
|
|
||||||
includeRecordingShortcut: includeRecordingShortcut,
|
|
||||||
includeResetCanvasShortcut: includeResetCanvasShortcut,
|
|
||||||
includePinToolbarShortcut: includePinToolbarShortcut,
|
|
||||||
includeViewModeShortcut: includeViewModeShortcut,
|
|
||||||
includeVoiceCallShortcut: includeVoiceCallShortcut,
|
|
||||||
excludedActions: excludedActions,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
test('kDefaultShortcutBindings matches fixture', () {
|
|
||||||
// The fixture is the cross-language source of truth for default
|
|
||||||
// bindings. Rust has its own parity test against the same file
|
|
||||||
// (`default_bindings_match_fixture_json` in src/keyboard/shortcuts.rs),
|
|
||||||
// so a drift on either side breaks CI.
|
|
||||||
final fixturePath = 'test/fixtures/default_keyboard_shortcuts.json';
|
|
||||||
final fixture =
|
|
||||||
jsonDecode(File(fixturePath).readAsStringSync()) as List<dynamic>;
|
|
||||||
expect(kDefaultShortcutBindings, equals(fixture),
|
|
||||||
reason: 'kDefaultShortcutBindings drifted from $fixturePath — update '
|
|
||||||
'shortcut_constants.dart, the fixture, and Rust default_bindings() '
|
|
||||||
'together');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('save order preserves macOS control modifier', () {
|
|
||||||
expect(canonicalShortcutModsForSave({'ctrl'}), ['ctrl']);
|
|
||||||
expect(canonicalShortcutModsForSave({'shift', 'ctrl', 'primary', 'alt'}),
|
|
||||||
['primary', 'ctrl', 'alt', 'shift']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('shortcutBindingMapsFrom ignores malformed bindings', () {
|
|
||||||
expect(shortcutBindingMapsFrom('not a list'), isEmpty);
|
|
||||||
|
|
||||||
final bindings = shortcutBindingMapsFrom([
|
|
||||||
{
|
|
||||||
'action': kShortcutActionScreenshot,
|
|
||||||
'mods': ['primary'],
|
|
||||||
'key': 'p',
|
|
||||||
},
|
|
||||||
'bad',
|
|
||||||
1,
|
|
||||||
{
|
|
||||||
'action': kShortcutActionToggleMute,
|
|
||||||
'mods': ['alt'],
|
|
||||||
'key': 's',
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(bindings, hasLength(2));
|
|
||||||
expect(bindings.map((binding) => binding['action']), [
|
|
||||||
kShortcutActionScreenshot,
|
|
||||||
kShortcutActionToggleMute,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('shortcutBindingMapsFrom ignores malformed binding fields', () {
|
|
||||||
final valid = {
|
|
||||||
'action': kShortcutActionScreenshot,
|
|
||||||
'mods': ['primary', 'ctrl', 'alt', 'shift'],
|
|
||||||
'key': 'p',
|
|
||||||
};
|
|
||||||
final malformed = [
|
|
||||||
for (final field in ['action', 'mods', 'key'])
|
|
||||||
{...valid}..remove(field),
|
|
||||||
for (final fields in [
|
|
||||||
{'action': 1},
|
|
||||||
{'action': null},
|
|
||||||
{'key': 1},
|
|
||||||
{'key': null},
|
|
||||||
{'mods': null},
|
|
||||||
{'mods': 'primary'},
|
|
||||||
{'mods': ['primary', 1]},
|
|
||||||
{'mods': ['primary', null]},
|
|
||||||
{'mods': ['primary', 'unknown']},
|
|
||||||
])
|
|
||||||
{...valid, ...fields},
|
|
||||||
];
|
|
||||||
|
|
||||||
for (final binding in malformed) {
|
|
||||||
expect(shortcutBindingMapsFrom([binding, valid]), [valid],
|
|
||||||
reason: 'malformed binding should be ignored: $binding');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('shortcutBindingMapsFrom preserves unbound and unknown bindings', () {
|
|
||||||
expect(
|
|
||||||
shortcutBindingMapsFrom([
|
|
||||||
{'action': kShortcutActionScreenshot, 'mods': [], 'key': ''},
|
|
||||||
{'action': 'future_action', 'mods': ['ctrl'], 'key': 'future_key'},
|
|
||||||
]),
|
|
||||||
[
|
|
||||||
{'action': kShortcutActionScreenshot, 'mods': [], 'key': ''},
|
|
||||||
{'action': 'future_action', 'mods': ['ctrl'], 'key': 'future_key'},
|
|
||||||
],
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('platform filtering ignores malformed binding fields', () {
|
|
||||||
final filtered = filterDefaultBindingsForPlatform([
|
|
||||||
{'action': 1, 'mods': ['primary'], 'key': 'p'},
|
|
||||||
{'action': kShortcutActionScreenshot, 'mods': ['primary'], 'key': 1},
|
|
||||||
{'action': kShortcutActionToggleMute, 'mods': ['alt'], 'key': 's'},
|
|
||||||
{
|
|
||||||
'action': kShortcutActionToggleFullscreen,
|
|
||||||
'mods': ['primary'],
|
|
||||||
'key': 'enter',
|
|
||||||
},
|
|
||||||
], capabilities(includeFullscreenShortcut: false));
|
|
||||||
|
|
||||||
expect(filtered, [
|
|
||||||
{'action': kShortcutActionToggleMute, 'mods': ['alt'], 'key': 's'},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('shortcutModSetFrom ignores malformed modifiers', () {
|
|
||||||
expect(shortcutModSetFrom('not a list'), isEmpty);
|
|
||||||
expect(shortcutModSetFrom(['primary', 1, 'alt', null, 'primary']), {
|
|
||||||
'primary',
|
|
||||||
'alt',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('non-desktop defaults exclude desktop-only and tab shortcuts', () {
|
|
||||||
final defaults = [
|
|
||||||
{
|
|
||||||
'action': kShortcutActionSendCtrlAltDel,
|
|
||||||
'mods': ['primary', 'alt', 'shift'],
|
|
||||||
'key': 'delete',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'action': kShortcutActionToggleFullscreen,
|
|
||||||
'mods': ['primary', 'alt', 'shift'],
|
|
||||||
'key': 'enter',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'action': kShortcutActionSwitchDisplayNext,
|
|
||||||
'mods': ['primary', 'alt', 'shift'],
|
|
||||||
'key': 'arrow_right',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'action': kShortcutActionScreenshot,
|
|
||||||
'mods': ['primary', 'alt', 'shift'],
|
|
||||||
'key': 'p',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'action': kShortcutActionSwitchTabNext,
|
|
||||||
'mods': ['primary', 'alt', 'shift'],
|
|
||||||
'key': 'right_bracket',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
'action': kShortcutActionToggleRelativeMouseMode,
|
|
||||||
'mods': ['primary', 'alt', 'shift'],
|
|
||||||
'key': 'g',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
final filtered = filterDefaultBindingsForPlatform(
|
|
||||||
defaults,
|
|
||||||
capabilities(
|
|
||||||
includeFullscreenShortcut: false,
|
|
||||||
includeScreenshotShortcut: false,
|
|
||||||
includeRelativeMouseModeShortcut: false,
|
|
||||||
includeTabShortcuts: false,
|
|
||||||
includeToolbarShortcut: false,
|
|
||||||
includeCloseTabShortcut: false,
|
|
||||||
includeSwitchSidesShortcut: false,
|
|
||||||
includeRecordingShortcut: false,
|
|
||||||
includeResetCanvasShortcut: false,
|
|
||||||
includePinToolbarShortcut: false,
|
|
||||||
includeViewModeShortcut: false,
|
|
||||||
includeVoiceCallShortcut: false,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(filtered.map((binding) => binding['action']), [
|
|
||||||
kShortcutActionSendCtrlAltDel,
|
|
||||||
kShortcutActionSwitchDisplayNext,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
Set<String> idSet(Iterable<KeyboardShortcutActionGroup> groups) =>
|
|
||||||
{for (final e in allActionEntries(groups)) e.id};
|
|
||||||
|
|
||||||
test('filterKeyboardShortcutActionGroupsForPlatform strips desktop-only', () {
|
|
||||||
final groups = filterKeyboardShortcutActionGroupsForPlatform(
|
|
||||||
capabilities(
|
|
||||||
includeFullscreenShortcut: false,
|
|
||||||
includeScreenshotShortcut: false,
|
|
||||||
includeRelativeMouseModeShortcut: false,
|
|
||||||
includeTabShortcuts: false,
|
|
||||||
includeToolbarShortcut: false,
|
|
||||||
includeCloseTabShortcut: false,
|
|
||||||
includeSwitchSidesShortcut: false,
|
|
||||||
// Recording / Reset Canvas are intentionally still included here —
|
|
||||||
// they have non-desktop platforms (mobile Android / mobile both).
|
|
||||||
includeRecordingShortcut: true,
|
|
||||||
includeResetCanvasShortcut: true,
|
|
||||||
includePinToolbarShortcut: false,
|
|
||||||
includeViewModeShortcut: false,
|
|
||||||
includeVoiceCallShortcut: false,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
final ids = idSet(groups);
|
|
||||||
// Desktop-only actions are stripped.
|
|
||||||
expect(ids, isNot(contains(kShortcutActionToggleFullscreen)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionToggleRelativeMouseMode)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionScreenshot)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionToggleToolbar)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionCloseTab)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionSwitchSides)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionPinToolbar)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionViewModeOriginal)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionViewModeAdaptive)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionSwitchTabNext)));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionSwitchTabPrev)));
|
|
||||||
// Cross-platform actions survive.
|
|
||||||
expect(ids, contains(kShortcutActionSendCtrlAltDel));
|
|
||||||
expect(ids, contains(kShortcutActionInsertLock));
|
|
||||||
expect(ids, contains(kShortcutActionRestartRemote));
|
|
||||||
expect(ids, contains(kShortcutActionSwitchDisplayNext));
|
|
||||||
expect(ids, contains(kShortcutActionToggleRecording));
|
|
||||||
expect(ids, contains(kShortcutActionResetCanvas));
|
|
||||||
expect(ids, contains(kShortcutActionToggleMute));
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'filterKeyboardShortcutActionGroupsForPlatform hides Toggle Recording on Web/iOS',
|
|
||||||
() {
|
|
||||||
final groups = filterKeyboardShortcutActionGroupsForPlatform(
|
|
||||||
capabilities(includeRecordingShortcut: false),
|
|
||||||
);
|
|
||||||
final ids = idSet(groups);
|
|
||||||
expect(ids, isNot(contains(kShortcutActionToggleRecording)));
|
|
||||||
// Other Session Control entries unaffected.
|
|
||||||
expect(ids, contains(kShortcutActionSendCtrlAltDel));
|
|
||||||
expect(ids, contains(kShortcutActionInsertLock));
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'filterKeyboardShortcutActionGroupsForPlatform keeps full set on desktop',
|
|
||||||
() {
|
|
||||||
final groups =
|
|
||||||
filterKeyboardShortcutActionGroupsForPlatform(capabilities());
|
|
||||||
expect(idSet(groups), equals(idSet(kKeyboardShortcutActionGroups)));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Wayland hides relative mouse mode but keeps screenshot', () {
|
|
||||||
final ids = idSet(filterKeyboardShortcutActionGroupsForPlatform(
|
|
||||||
capabilities(includeRelativeMouseModeShortcut: false),
|
|
||||||
));
|
|
||||||
expect(ids, isNot(contains(kShortcutActionToggleRelativeMouseMode)));
|
|
||||||
expect(ids, contains(kShortcutActionScreenshot));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('filterKeyboardShortcutActionGroupsForPlatform drops empty groups', () {
|
|
||||||
// With every capability flag off, groups whose items are all behind
|
|
||||||
// those flags get dropped. Display / Keyboard parent groups still carry
|
|
||||||
// cross-platform direct items so they survive even when the gated
|
|
||||||
// subgroups thin out.
|
|
||||||
final groups = filterKeyboardShortcutActionGroupsForPlatform(
|
|
||||||
capabilities(
|
|
||||||
includeFullscreenShortcut: false,
|
|
||||||
includeScreenshotShortcut: false,
|
|
||||||
includeRelativeMouseModeShortcut: false,
|
|
||||||
includeTabShortcuts: false,
|
|
||||||
includeToolbarShortcut: false,
|
|
||||||
includeCloseTabShortcut: false,
|
|
||||||
includeSwitchSidesShortcut: false,
|
|
||||||
includeRecordingShortcut: false,
|
|
||||||
includeResetCanvasShortcut: false,
|
|
||||||
includePinToolbarShortcut: false,
|
|
||||||
includeViewModeShortcut: false,
|
|
||||||
includeVoiceCallShortcut: false,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
final titles = groups.map((g) => g.titleKey).toList();
|
|
||||||
// "Other" has nothing but platform-gated entries → dropped entirely.
|
|
||||||
expect(titles, isNot(contains('Other')));
|
|
||||||
// Parent groups with cross-platform direct items survive.
|
|
||||||
expect(titles, contains('Display'));
|
|
||||||
expect(titles, contains('Keyboard'));
|
|
||||||
// The "View Mode" subgroup under Display is gated by includeViewModeShortcut,
|
|
||||||
// so it must be absent from Display's surviving children.
|
|
||||||
final displayChildren =
|
|
||||||
groups.firstWhere((g) => g.titleKey == 'Display').children;
|
|
||||||
final subgroupTitles = displayChildren
|
|
||||||
.whereType<KeyboardShortcutActionSubgroup>()
|
|
||||||
.map((s) => s.titleKey)
|
|
||||||
.toList();
|
|
||||||
expect(subgroupTitles, isNot(contains('View Mode')));
|
|
||||||
// No surviving group is empty either way.
|
|
||||||
expect(groups.every((g) => g.children.isNotEmpty), isTrue);
|
|
||||||
// No surviving subgroup is empty.
|
|
||||||
for (final group in groups) {
|
|
||||||
for (final child in group.children) {
|
|
||||||
if (child is KeyboardShortcutActionSubgroup) {
|
|
||||||
expect(child.entries, isNotEmpty,
|
|
||||||
reason: 'subgroup "${child.titleKey}" should not be empty');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('physicalKeyName covers the supported-keys fixture', () {
|
|
||||||
// `shortcut_key_usb_hid.json` pins every key name to the USB HID usage
|
|
||||||
// it is recorded and matched from. Rust has a mirror test against the
|
|
||||||
// same file (`usb_hid_keys_match_fixture` in src/keyboard/shortcuts.rs),
|
|
||||||
// and the set of names must equal `supported_shortcut_keys.json`.
|
|
||||||
final supported = (jsonDecode(
|
|
||||||
File('test/fixtures/supported_shortcut_keys.json')
|
|
||||||
.readAsStringSync()) as List<dynamic>)
|
|
||||||
.cast<String>()
|
|
||||||
.toSet();
|
|
||||||
final pairs = (jsonDecode(File('test/fixtures/shortcut_key_usb_hid.json')
|
|
||||||
.readAsStringSync()) as List<dynamic>)
|
|
||||||
.cast<List<dynamic>>();
|
|
||||||
|
|
||||||
for (final pair in pairs) {
|
|
||||||
final name = pair[0] as String;
|
|
||||||
final usage = pair[1] as int;
|
|
||||||
expect(physicalKeyName(PhysicalKeyboardKey(0x00070000 | usage)),
|
|
||||||
equals(name),
|
|
||||||
reason: 'USB HID 0x${usage.toRadixString(16)} should be "$name"');
|
|
||||||
}
|
|
||||||
expect(pairs.map((p) => p[0] as String).toSet(), equals(supported));
|
|
||||||
|
|
||||||
// Modifier-only / unsupported keys must return null.
|
|
||||||
expect(physicalKeyName(PhysicalKeyboardKey.shiftLeft), isNull);
|
|
||||||
expect(physicalKeyName(PhysicalKeyboardKey.escape), isNull);
|
|
||||||
expect(physicalKeyName(PhysicalKeyboardKey.f13), isNull);
|
|
||||||
expect(physicalKeyName(PhysicalKeyboardKey.numpad1), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('enable seeds defaults only for a config without bindings', () {
|
|
||||||
expect(shouldSeedDefaultShortcutBindings(<String, dynamic>{}), isTrue);
|
|
||||||
expect(
|
|
||||||
shouldSeedDefaultShortcutBindings(
|
|
||||||
<String, dynamic>{'enabled': false, 'pass_through': true}),
|
|
||||||
isTrue);
|
|
||||||
// The user cleared every binding: re-enabling must not bring defaults back.
|
|
||||||
expect(
|
|
||||||
shouldSeedDefaultShortcutBindings(
|
|
||||||
<String, dynamic>{'enabled': false, 'bindings': <dynamic>[]}),
|
|
||||||
isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('ShortcutConfig.parse reads the flags and bindings once', () {
|
|
||||||
final config = ShortcutConfig.parse(jsonEncode({
|
|
||||||
'enabled': true,
|
|
||||||
'pass_through': false,
|
|
||||||
'bindings': [
|
|
||||||
{'action': 'screenshot', 'mods': ['primary'], 'key': 'p'},
|
|
||||||
'not a binding',
|
|
||||||
],
|
|
||||||
}));
|
|
||||||
expect(config.enabled, isTrue);
|
|
||||||
expect(config.passThrough, isFalse);
|
|
||||||
expect(config.bindings, [
|
|
||||||
{'action': 'screenshot', 'mods': ['primary'], 'key': 'p'},
|
|
||||||
]);
|
|
||||||
|
|
||||||
for (final raw in ['', 'not json', '[]', '{"bindings": "x"}']) {
|
|
||||||
final broken = ShortcutConfig.parse(raw);
|
|
||||||
expect(broken.enabled, isFalse, reason: raw);
|
|
||||||
expect(broken.passThrough, isFalse, reason: raw);
|
|
||||||
expect(broken.bindings, isEmpty, reason: raw);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Wayland active config preserves stored bindings and flags', () {
|
|
||||||
const relative = {
|
|
||||||
'action': kShortcutActionToggleRelativeMouseMode,
|
|
||||||
'mods': ['primary'],
|
|
||||||
'key': 'r',
|
|
||||||
};
|
|
||||||
const mute = {
|
|
||||||
'action': kShortcutActionToggleMute,
|
|
||||||
'mods': ['primary'],
|
|
||||||
'key': 'm',
|
|
||||||
};
|
|
||||||
for (final flags in [(true, false), (false, false), (true, true)]) {
|
|
||||||
final stored = ShortcutConfig.parse(jsonEncode({
|
|
||||||
'enabled': flags.$1,
|
|
||||||
'pass_through': flags.$2,
|
|
||||||
'bindings': [relative, mute],
|
|
||||||
}));
|
|
||||||
final active = stored.forPlatform(
|
|
||||||
capabilities(includeRelativeMouseModeShortcut: false));
|
|
||||||
expect(active.bindings, [mute]);
|
|
||||||
expect(active.enabled, flags.$1);
|
|
||||||
expect(active.passThrough, flags.$2);
|
|
||||||
expect(stored.bindings, [relative, mute]);
|
|
||||||
expect(stored.forPlatform(capabilities()).bindings, [relative, mute]);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('active saved bindings follow Settings capabilities without reseeding', () {
|
|
||||||
final actions = [
|
|
||||||
kShortcutActionSwitchDisplayAll,
|
|
||||||
kShortcutActionKeyboardModeMap,
|
|
||||||
kShortcutActionToggleShowMyCursor,
|
|
||||||
kShortcutActionToggleZoomCursor,
|
|
||||||
kShortcutActionToggleRecording,
|
|
||||||
kShortcutActionToggleVoiceCall,
|
|
||||||
kShortcutActionResetCanvas,
|
|
||||||
kShortcutActionToggleMute,
|
|
||||||
kShortcutActionSendCtrlAltDel,
|
|
||||||
];
|
|
||||||
final saved = ShortcutConfig.parse(jsonEncode({
|
|
||||||
'enabled': true,
|
|
||||||
'bindings': [
|
|
||||||
for (final action in actions)
|
|
||||||
{'action': action, 'mods': ['primary'], 'key': 'm'},
|
|
||||||
],
|
|
||||||
}));
|
|
||||||
final cap = capabilities(
|
|
||||||
includeRecordingShortcut: false,
|
|
||||||
includeVoiceCallShortcut: false,
|
|
||||||
includeResetCanvasShortcut: false,
|
|
||||||
excludedActions: {
|
|
||||||
kShortcutActionSwitchDisplayAll,
|
|
||||||
kShortcutActionKeyboardModeMap,
|
|
||||||
kShortcutActionToggleShowMyCursor,
|
|
||||||
kShortcutActionToggleZoomCursor,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(saved.forPlatform(cap).bindings.map((b) => b['action']),
|
|
||||||
[kShortcutActionToggleMute, kShortcutActionSendCtrlAltDel]);
|
|
||||||
expect(saved.bindings.map((b) => b['action']), actions);
|
|
||||||
expect(saved.forPlatform(capabilities()).bindings, saved.bindings);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('non-US layouts record and match the physical key', () {
|
|
||||||
// AZERTY: the key labelled "A" sits where US QWERTY has Q. The native
|
|
||||||
// matcher only sees the physical position (USB HID usage), so the
|
|
||||||
// binding must name that position too.
|
|
||||||
const azertyA = KeyDownEvent(
|
|
||||||
physicalKey: PhysicalKeyboardKey.keyQ,
|
|
||||||
logicalKey: LogicalKeyboardKey.keyA,
|
|
||||||
character: 'a',
|
|
||||||
timeStamp: Duration.zero,
|
|
||||||
);
|
|
||||||
expect(shortcutKeyNameForEvent(azertyA), 'q');
|
|
||||||
|
|
||||||
// QWERTZ: the key labelled "Z" sits where US QWERTY has Y.
|
|
||||||
const qwertzZ = KeyDownEvent(
|
|
||||||
physicalKey: PhysicalKeyboardKey.keyY,
|
|
||||||
logicalKey: LogicalKeyboardKey.keyZ,
|
|
||||||
character: 'z',
|
|
||||||
timeStamp: Duration.zero,
|
|
||||||
);
|
|
||||||
expect(shortcutKeyNameForEvent(qwertzZ), 'y');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('kShortcutActionsRunOnKeyUp matches the fixture and names real actions',
|
|
||||||
() {
|
|
||||||
// Rust has a mirror test against the same file
|
|
||||||
// (`key_up_actions_match_fixture` in src/keyboard/shortcuts.rs).
|
|
||||||
final fixture = (jsonDecode(
|
|
||||||
File('test/fixtures/key_up_shortcut_actions.json')
|
|
||||||
.readAsStringSync()) as List<dynamic>)
|
|
||||||
.cast<String>()
|
|
||||||
.toSet();
|
|
||||||
expect(kShortcutActionsRunOnKeyUp, equals(fixture),
|
|
||||||
reason: 'kShortcutActionsRunOnKeyUp drifted from the fixture — update '
|
|
||||||
'shortcut_constants.dart, the fixture, and Rust runs_on_release '
|
|
||||||
'together');
|
|
||||||
final actions = idSet(kKeyboardShortcutActionGroups);
|
|
||||||
for (final id in kShortcutActionsRunOnKeyUp) {
|
|
||||||
expect(actions, contains(id), reason: '"$id" is not a configurable action');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,566 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart';
|
|
||||||
import 'package:flutter_hbb/models/local_flutter_shortcuts.dart';
|
|
||||||
|
|
||||||
LocalFlutterShortcutDispatcher dispatcherFor(
|
|
||||||
void Function(String) onTriggered) {
|
|
||||||
final dispatcher = LocalFlutterShortcutDispatcher(onTriggered: onTriggered);
|
|
||||||
addTearDown(dispatcher.clear);
|
|
||||||
addTearDown(LocalFlutterShortcutDispatcher.resetFiredKeys);
|
|
||||||
return dispatcher;
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ShortcutHarness {
|
|
||||||
final String? Function(KeyEvent) match;
|
|
||||||
final Future<void> Function() releaseModifiers;
|
|
||||||
final LocalFlutterShortcutDispatcher dispatcher;
|
|
||||||
|
|
||||||
_ShortcutHarness({
|
|
||||||
required this.match,
|
|
||||||
required this.releaseModifiers,
|
|
||||||
required void Function(String) onTriggered,
|
|
||||||
}) : dispatcher = dispatcherFor(onTriggered);
|
|
||||||
|
|
||||||
bool tryDispatch(KeyEvent event) => dispatcher.tryDispatch(
|
|
||||||
event,
|
|
||||||
match: () => match(event),
|
|
||||||
releaseModifiers: releaseModifiers,
|
|
||||||
);
|
|
||||||
|
|
||||||
void clear() => dispatcher.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
KeyEvent down(PhysicalKeyboardKey key,
|
|
||||||
{LogicalKeyboardKey logicalKey = LogicalKeyboardKey.keyP}) =>
|
|
||||||
KeyDownEvent(
|
|
||||||
physicalKey: key,
|
|
||||||
logicalKey: logicalKey,
|
|
||||||
timeStamp: Duration.zero,
|
|
||||||
);
|
|
||||||
|
|
||||||
KeyEvent repeat(PhysicalKeyboardKey key) => KeyRepeatEvent(
|
|
||||||
physicalKey: key,
|
|
||||||
logicalKey: LogicalKeyboardKey.keyP,
|
|
||||||
timeStamp: Duration.zero,
|
|
||||||
);
|
|
||||||
|
|
||||||
KeyEvent up(PhysicalKeyboardKey key,
|
|
||||||
{LogicalKeyboardKey logicalKey = LogicalKeyboardKey.keyP}) =>
|
|
||||||
KeyUpEvent(
|
|
||||||
physicalKey: key,
|
|
||||||
logicalKey: logicalKey,
|
|
||||||
timeStamp: Duration.zero,
|
|
||||||
);
|
|
||||||
|
|
||||||
RawKeyEvent rawP({required bool down, bool repeat = false, bool ctrl = false}) {
|
|
||||||
final data = RawKeyEventDataLinux(
|
|
||||||
keyHelper: GtkKeyHelper(),
|
|
||||||
scanCode: 33,
|
|
||||||
keyCode: 112,
|
|
||||||
unicodeScalarValues: 112,
|
|
||||||
modifiers: ctrl ? GtkKeyHelper.modifierControl : 0,
|
|
||||||
isDown: down,
|
|
||||||
);
|
|
||||||
return down
|
|
||||||
? RawKeyDownEvent(data: data, repeat: repeat)
|
|
||||||
: RawKeyUpEvent(data: data);
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
for (final action in [
|
|
||||||
kShortcutActionToggleViewOnly,
|
|
||||||
kShortcutActionToggleShowMyCursor,
|
|
||||||
kShortcutActionToggleMute,
|
|
||||||
...kShortcutActionsRunOnKeyUp,
|
|
||||||
kShortcutActionSendClipboardKeystrokes,
|
|
||||||
]) {
|
|
||||||
test('forwarded W retains correct ownership across $action', () async {
|
|
||||||
final events = <String>['W down'];
|
|
||||||
final released = Completer<void>();
|
|
||||||
final dispatcher = dispatcherFor(events.add);
|
|
||||||
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyW,
|
|
||||||
down: true, release: () {
|
|
||||||
events.add('W up');
|
|
||||||
return released.future;
|
|
||||||
});
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
|
||||||
match: () => action), isTrue);
|
|
||||||
await pumpEventQueue();
|
|
||||||
if (kShortcutActionsRunOnKeyUp.contains(action) ||
|
|
||||||
(!kIsWeb && action == kShortcutActionSendClipboardKeystrokes)) {
|
|
||||||
expect(events, ['W down']);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
await pumpEventQueue();
|
|
||||||
}
|
|
||||||
if (action == kShortcutActionToggleMute ||
|
|
||||||
(kIsWeb && action == kShortcutActionSendClipboardKeystrokes)) {
|
|
||||||
expect(events, ['W down', action]);
|
|
||||||
} else {
|
|
||||||
expect(events, ['W down', 'W up']);
|
|
||||||
}
|
|
||||||
released.complete();
|
|
||||||
await pumpEventQueue();
|
|
||||||
expect(events.last, action);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (final action in [
|
|
||||||
kShortcutActionToggleViewOnly,
|
|
||||||
kShortcutActionToggleChat,
|
|
||||||
if (!kIsWeb) kShortcutActionSendClipboardKeystrokes,
|
|
||||||
]) {
|
|
||||||
test('$action cleanup skips released keys and cancels after session close',
|
|
||||||
() async {
|
|
||||||
final events = <String>[];
|
|
||||||
final released = Completer<void>();
|
|
||||||
final dispatcher = dispatcherFor(events.add);
|
|
||||||
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyW,
|
|
||||||
down: true, release: () {
|
|
||||||
events.add('W up');
|
|
||||||
return released.future;
|
|
||||||
});
|
|
||||||
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyC,
|
|
||||||
down: true, release: () async => events.add('C up'));
|
|
||||||
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyC,
|
|
||||||
down: false, release: () async => events.add('C up'));
|
|
||||||
dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP), match: () => action);
|
|
||||||
dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP));
|
|
||||||
await pumpEventQueue();
|
|
||||||
expect(events, ['W up']);
|
|
||||||
dispatcher.clear();
|
|
||||||
released.complete();
|
|
||||||
await pumpEventQueue();
|
|
||||||
expect(events, ['W up']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('owns each overlapping shortcut key until its own release', () async {
|
|
||||||
var modifiersPressed = true;
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (event) => modifiersPressed
|
|
||||||
? event.physicalKey == PhysicalKeyboardKey.keyP
|
|
||||||
? 'screenshot'
|
|
||||||
: 'chat'
|
|
||||||
: null,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
modifiersPressed = false;
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, ['screenshot', 'chat']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('binding changes do not forward a previously consumed key', () async {
|
|
||||||
var enabled = true;
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => enabled ? 'screenshot' : null,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
enabled = false;
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, ['screenshot']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('unmatched key stays forwarded when modifiers change during repeat',
|
|
||||||
() async {
|
|
||||||
var modifiersPressed = false;
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => modifiersPressed ? 'screenshot' : null,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
modifiersPressed = true;
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('auto-repeat cannot trigger an action again', () async {
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => 'screenshot',
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, ['screenshot', 'screenshot']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('releases remote modifiers before running the action', () async {
|
|
||||||
final released = Completer<void>();
|
|
||||||
final actions = <String>[];
|
|
||||||
var releases = 0;
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => 'screenshot',
|
|
||||||
releaseModifiers: () {
|
|
||||||
releases++;
|
|
||||||
return released.future;
|
|
||||||
},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(releases, 1);
|
|
||||||
expect(actions, isEmpty);
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(releases, 1);
|
|
||||||
released.complete();
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, ['screenshot']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('native clipboard prompt can be repeated immediately after cancelling',
|
|
||||||
() async {
|
|
||||||
var dialogOpen = false;
|
|
||||||
var prompts = 0;
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionSendClipboardKeystrokes,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: (_) {
|
|
||||||
dialogOpen = true;
|
|
||||||
prompts++;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
bool route(KeyEvent event) => !dialogOpen && dispatcher.tryDispatch(event);
|
|
||||||
|
|
||||||
for (var attempt = 1; attempt <= 2; attempt++) {
|
|
||||||
expect(route(down(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(dialogOpen, isFalse,
|
|
||||||
reason: 'the local dialog must not consume the trigger release');
|
|
||||||
expect(route(repeat(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
expect(route(up(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(dialogOpen, isTrue);
|
|
||||||
expect(prompts, attempt);
|
|
||||||
dialogOpen = false;
|
|
||||||
}
|
|
||||||
}, skip: kIsWeb);
|
|
||||||
|
|
||||||
test('native clipboard waits for outstanding remote modifier releases',
|
|
||||||
() async {
|
|
||||||
final released = Completer<void>();
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionSendClipboardKeystrokes,
|
|
||||||
releaseModifiers: () => released.future,
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, isEmpty,
|
|
||||||
reason: 'clipboard input must follow the remote modifier releases');
|
|
||||||
released.complete();
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, [kShortcutActionSendClipboardKeystrokes]);
|
|
||||||
}, skip: kIsWeb);
|
|
||||||
|
|
||||||
test('Web clipboard still runs on key down for browser activation', () async {
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionSendClipboardKeystrokes,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, [kShortcutActionSendClipboardKeystrokes]);
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
expect(actions, [kShortcutActionSendClipboardKeystrokes]);
|
|
||||||
}, skip: !kIsWeb);
|
|
||||||
|
|
||||||
test('closing a clipboard owner preserves another session release', () async {
|
|
||||||
final closingRelease = Completer<void>();
|
|
||||||
final nextRelease = Completer<void>();
|
|
||||||
final actions = <String>[];
|
|
||||||
final closing = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionSendClipboardKeystrokes,
|
|
||||||
releaseModifiers: () => closingRelease.future,
|
|
||||||
onTriggered: (_) => actions.add('closing'),
|
|
||||||
);
|
|
||||||
final next = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionSendClipboardKeystrokes,
|
|
||||||
releaseModifiers: () => nextRelease.future,
|
|
||||||
onTriggered: (_) => actions.add('next'),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(closing.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
expect(next.tryDispatch(down(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
closing.clear();
|
|
||||||
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
closingRelease.complete();
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, isEmpty,
|
|
||||||
reason: 'the live session still awaits its own modifier release');
|
|
||||||
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue);
|
|
||||||
nextRelease.complete();
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, ['next']);
|
|
||||||
}, skip: kIsWeb);
|
|
||||||
|
|
||||||
test('closing the session drops its pending action but keeps the fired key',
|
|
||||||
() async {
|
|
||||||
// Close tab is itself a shortcut: the session that matched the key is
|
|
||||||
// gone before the key is released, and the next session gets the rest.
|
|
||||||
final released = Completer<void>();
|
|
||||||
final actions = <String>[];
|
|
||||||
var enabled = true;
|
|
||||||
final closing = _ShortcutHarness(
|
|
||||||
match: (_) => enabled ? 'close_tab' : null,
|
|
||||||
releaseModifiers: () => released.future,
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
final next = _ShortcutHarness(
|
|
||||||
match: (_) => enabled ? 'close_tab' : null,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(closing.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
closing.clear();
|
|
||||||
released.complete();
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, isEmpty, reason: 'a closed session runs nothing');
|
|
||||||
|
|
||||||
expect(next.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
enabled = false;
|
|
||||||
expect(next.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('focus-changing actions run when the key is released', () async {
|
|
||||||
// Close tab moves focus before the key is released; the release may then
|
|
||||||
// land in a session whose keys go through the other matcher.
|
|
||||||
var releases = 0;
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionCloseTab,
|
|
||||||
releaseModifiers: () async => releases++,
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyW)), isTrue);
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyW)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(releases, 1, reason: 'remote modifiers are released on the press');
|
|
||||||
expect(actions, isEmpty, reason: 'the action waits for the release');
|
|
||||||
|
|
||||||
final other = dispatcherFor(actions.add);
|
|
||||||
expect(other.tryDispatch(up(PhysicalKeyboardKey.keyW)), isTrue);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, [kShortcutActionCloseTab]);
|
|
||||||
expect(other.tryDispatch(up(PhysicalKeyboardKey.keyW)), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('closing the session drops its action pending on key release',
|
|
||||||
() async {
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = _ShortcutHarness(
|
|
||||||
match: (_) => kShortcutActionSwitchTabNext,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
onTriggered: actions.add,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyW)), isTrue);
|
|
||||||
dispatcher.clear();
|
|
||||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyW)), isTrue,
|
|
||||||
reason: 'the key stays owned');
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('raw legacy shortcuts own repeats and release after modifiers change',
|
|
||||||
() async {
|
|
||||||
addTearDown(RawKeyboard.instance.clearKeysPressed);
|
|
||||||
final actions = <String>[];
|
|
||||||
final dispatcher = dispatcherFor(actions.add);
|
|
||||||
bool dispatch(RawKeyEvent event) {
|
|
||||||
RawKeyboard.instance.handleRawKeyEvent(event);
|
|
||||||
return dispatcher.tryDispatchRaw(
|
|
||||||
event,
|
|
||||||
match: () => event.isControlPressed ? 'screenshot' : null,
|
|
||||||
releaseModifiers: () async {},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(dispatch(rawP(down: true, ctrl: true)), isTrue);
|
|
||||||
expect(dispatch(rawP(down: true, repeat: true)), isTrue);
|
|
||||||
expect(dispatch(rawP(down: false)), isTrue);
|
|
||||||
expect(dispatch(rawP(down: true)), isFalse);
|
|
||||||
expect(dispatch(rawP(down: true, repeat: true, ctrl: true)), isFalse);
|
|
||||||
expect(dispatch(rawP(down: false, ctrl: true)), isFalse);
|
|
||||||
await Future<void>.value();
|
|
||||||
expect(actions, ['screenshot']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('shortcut key ownership follows focus to another session', () {
|
|
||||||
final actions = <String>[];
|
|
||||||
final first = dispatcherFor(actions.add);
|
|
||||||
final second = dispatcherFor(actions.add);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
|
||||||
match: () => 'next_tab'),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(second.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(second.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(
|
|
||||||
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
|
||||||
match: () => 'next_tab'),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(actions, ['next_tab', 'next_tab']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('closing another session keeps every fired key owned', () {
|
|
||||||
final first = dispatcherFor((_) {});
|
|
||||||
final second = dispatcherFor((_) {});
|
|
||||||
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
|
||||||
match: () => 'screenshot');
|
|
||||||
second.tryDispatch(down(PhysicalKeyboardKey.keyC), match: () => 'chat');
|
|
||||||
|
|
||||||
second.clear();
|
|
||||||
expect(second.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(first.tryDispatch(repeat(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
expect(second.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
expect(first.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
|
|
||||||
expect(first.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
|
||||||
expect(first.tryDispatch(down(PhysicalKeyboardKey.keyC)), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('restores released modifiers before the next ordinary map key', () {
|
|
||||||
final dispatcher = dispatcherFor((_) {});
|
|
||||||
dispatcher.recordReleasedModifiers([
|
|
||||||
PhysicalKeyboardKey.controlLeft,
|
|
||||||
PhysicalKeyboardKey.altRight,
|
|
||||||
]);
|
|
||||||
final pressed = {PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.keyC};
|
|
||||||
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(
|
|
||||||
down(PhysicalKeyboardKey.keyC), pressed),
|
|
||||||
[PhysicalKeyboardKey.controlLeft],
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(
|
|
||||||
repeat(PhysicalKeyboardKey.keyC), pressed),
|
|
||||||
isEmpty,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('modifier events do not replay previously released modifiers', () {
|
|
||||||
final dispatcher = dispatcherFor((_) {});
|
|
||||||
dispatcher.recordReleasedModifiers([PhysicalKeyboardKey.controlLeft]);
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.shiftLeft),
|
|
||||||
{PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.shiftLeft}),
|
|
||||||
isEmpty,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(
|
|
||||||
up(PhysicalKeyboardKey.controlLeft), {PhysicalKeyboardKey.shiftLeft}),
|
|
||||||
isEmpty,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.keyC),
|
|
||||||
{PhysicalKeyboardKey.shiftLeft, PhysicalKeyboardKey.keyC}),
|
|
||||||
isEmpty,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('session closure drops pending modifier replay', () {
|
|
||||||
final dispatcher = dispatcherFor((_) {});
|
|
||||||
dispatcher.recordReleasedModifiers([PhysicalKeyboardKey.controlLeft]);
|
|
||||||
dispatcher.clear();
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.keyC),
|
|
||||||
{PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.keyC}),
|
|
||||||
isEmpty,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
for (final releaseControl in [false, true]) {
|
|
||||||
test(
|
|
||||||
'view-only resume restores only still-held modifiers '
|
|
||||||
'(releaseControl=$releaseControl)', () {
|
|
||||||
final keyboard = HardwareKeyboard();
|
|
||||||
var viewOnly = true;
|
|
||||||
final dispatcher = dispatcherFor((_) => viewOnly = false);
|
|
||||||
final controlDown = down(PhysicalKeyboardKey.controlLeft,
|
|
||||||
logicalKey: LogicalKeyboardKey.controlLeft);
|
|
||||||
keyboard.handleKeyEvent(controlDown);
|
|
||||||
expect(dispatcher.tryDispatch(controlDown, viewOnly: true), isFalse);
|
|
||||||
|
|
||||||
final shortcutDown = down(PhysicalKeyboardKey.keyP);
|
|
||||||
keyboard.handleKeyEvent(shortcutDown);
|
|
||||||
expect(
|
|
||||||
dispatcher.tryDispatch(shortcutDown,
|
|
||||||
viewOnly: true, match: () => 'toggle_view_only'),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(viewOnly, isFalse);
|
|
||||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
|
||||||
final shortcutUp = up(PhysicalKeyboardKey.keyP);
|
|
||||||
keyboard.handleKeyEvent(shortcutUp);
|
|
||||||
expect(dispatcher.tryDispatch(shortcutUp), isTrue);
|
|
||||||
if (releaseControl) {
|
|
||||||
final controlUp = up(PhysicalKeyboardKey.controlLeft,
|
|
||||||
logicalKey: LogicalKeyboardKey.controlLeft);
|
|
||||||
keyboard.handleKeyEvent(controlUp);
|
|
||||||
}
|
|
||||||
|
|
||||||
final copyDown =
|
|
||||||
down(PhysicalKeyboardKey.keyC, logicalKey: LogicalKeyboardKey.keyC);
|
|
||||||
keyboard.handleKeyEvent(copyDown);
|
|
||||||
expect(dispatcher.tryDispatch(copyDown), isFalse);
|
|
||||||
expect(
|
|
||||||
dispatcher.resumeModifiersAfterViewOnly(
|
|
||||||
copyDown.physicalKey, keyboard.physicalKeysPressed),
|
|
||||||
isTrue,
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
dispatcher.takeModifiersToRestore(
|
|
||||||
copyDown, keyboard.physicalKeysPressed),
|
|
||||||
releaseControl ? isEmpty : [PhysicalKeyboardKey.controlLeft],
|
|
||||||
);
|
|
||||||
expect(keyboard.isControlPressed, !releaseControl);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,277 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'package:dash_chat_2/dash_chat_2.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
|
||||||
import 'package:flutter_hbb/common.dart' show SessionID;
|
|
||||||
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart';
|
|
||||||
import 'package:flutter_hbb/generated_bridge.dart';
|
|
||||||
import 'package:flutter_hbb/consts.dart';
|
|
||||||
import 'package:flutter_hbb/models/chat_model.dart';
|
|
||||||
import 'package:flutter_hbb/models/input_model.dart';
|
|
||||||
import 'package:flutter_hbb/models/local_flutter_shortcuts.dart';
|
|
||||||
import 'package:flutter_hbb/models/model.dart';
|
|
||||||
import 'package:flutter_hbb/models/platform_model.dart';
|
|
||||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
class _ChatBinding extends Fake implements RustdeskImpl {
|
|
||||||
final sent = <(SessionID, String)>[];
|
|
||||||
final cmSent = <(int, String)>[];
|
|
||||||
|
|
||||||
@override
|
|
||||||
String translate(
|
|
||||||
{required String name, required String locale, dynamic hint}) =>
|
|
||||||
name;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> sessionSendChat(
|
|
||||||
{required SessionID sessionId,
|
|
||||||
required String text,
|
|
||||||
dynamic hint}) async {
|
|
||||||
sent.add((sessionId, text));
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> cmSendChat(
|
|
||||||
{required int connId, required String msg, dynamic hint}) async {
|
|
||||||
cmSent.add((connId, msg));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _Chat extends ChatModel {
|
|
||||||
_Chat(FFI session) : super(WeakReference(session));
|
|
||||||
|
|
||||||
final opened = <MessageKey>[];
|
|
||||||
|
|
||||||
@override
|
|
||||||
void toggleChatOverlay(
|
|
||||||
{Offset? chatInitPos, bool requestSoftKeyboard = true}) {
|
|
||||||
opened.add(currentKey);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _LegacyBinding extends _ChatBinding {
|
|
||||||
final keys = <(String, bool, bool)>[];
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool sessionGetToggleOptionSync(
|
|
||||||
{required SessionID sessionId, required String arg, dynamic hint}) =>
|
|
||||||
false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
String mainGetInputSource({dynamic hint}) => 'Input source 2';
|
|
||||||
@override
|
|
||||||
bool mainCurrentIsWayland({dynamic hint}) => false;
|
|
||||||
@override
|
|
||||||
String mainGetLocalOption({required String key, dynamic hint}) =>
|
|
||||||
'{"enabled":true,"bindings":[{"action":"toggle_mute",'
|
|
||||||
'"key":"s","mods":["alt"]}]}';
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> sessionInputKey(
|
|
||||||
{required SessionID sessionId,
|
|
||||||
required String name,
|
|
||||||
required bool down,
|
|
||||||
required bool press,
|
|
||||||
required bool alt,
|
|
||||||
required bool ctrl,
|
|
||||||
required bool shift,
|
|
||||||
required bool command,
|
|
||||||
dynamic hint}) async {
|
|
||||||
expect([press, ctrl, shift, command], [false, false, false, false]);
|
|
||||||
keys.add((name, down, alt));
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> sessionSendMouse(
|
|
||||||
{required SessionID sessionId, required String msg, dynamic hint}) async {
|
|
||||||
expect(jsonDecode(msg)['relative_mouse_mode'], '0');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _rawKey(InputModel input,
|
|
||||||
{required int scan,
|
|
||||||
required int key,
|
|
||||||
bool down = true,
|
|
||||||
bool alt = true}) async {
|
|
||||||
final data = RawKeyEventDataLinux(
|
|
||||||
keyHelper: GtkKeyHelper(),
|
|
||||||
scanCode: scan,
|
|
||||||
keyCode: key,
|
|
||||||
unicodeScalarValues: key < 256 ? key : 0,
|
|
||||||
modifiers: alt ? GtkKeyHelper.modifierMod1 : 0,
|
|
||||||
isDown: down);
|
|
||||||
final event = down ? RawKeyDownEvent(data: data) : RawKeyUpEvent(data: data);
|
|
||||||
RawKeyboard.instance.handleRawKeyEvent(event);
|
|
||||||
input.handleRawKeyEvent(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
class _Session extends Fake implements FFI {
|
|
||||||
@override
|
|
||||||
bool closed = false;
|
|
||||||
@override
|
|
||||||
final String id = 'test-peer';
|
|
||||||
@override
|
|
||||||
final SessionID sessionId = const Uuid().v4obj();
|
|
||||||
@override
|
|
||||||
late final FfiModel ffiModel = FfiModel(WeakReference(this));
|
|
||||||
@override
|
|
||||||
late final _Chat chatModel = _Chat(this);
|
|
||||||
@override
|
|
||||||
late ShortcutModel shortcutModel;
|
|
||||||
@override
|
|
||||||
ConnType get connType => ConnType.defaultConn;
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
|
||||||
TestWidgetsFlutterBinding.ensureInitialized();
|
|
||||||
late _Session session;
|
|
||||||
late ShortcutModel model;
|
|
||||||
|
|
||||||
setUp(() {
|
|
||||||
session = _Session();
|
|
||||||
model = ShortcutModel(WeakReference(session));
|
|
||||||
session.shortcutModel = model;
|
|
||||||
});
|
|
||||||
|
|
||||||
tearDown(() => model.clear());
|
|
||||||
|
|
||||||
for (final peer in [
|
|
||||||
kPeerPlatformWindows,
|
|
||||||
kPeerPlatformLinux,
|
|
||||||
kPeerPlatformMacOS
|
|
||||||
]) {
|
|
||||||
for (final alt in [(64, 0xffe9, 'VK_MENU'), (108, 0xffea, 'RAlt')]) {
|
|
||||||
test('Legacy $peer ${alt.$3} shortcut releases modifiers before dispatch',
|
|
||||||
() async {
|
|
||||||
final binding = _LegacyBinding();
|
|
||||||
platformFFI.setBindingForTesting(binding);
|
|
||||||
session.ffiModel.pi.platform = peer;
|
|
||||||
final input = InputModel(WeakReference(session))
|
|
||||||
..keyboardMode = kKeyLegacyMode;
|
|
||||||
addTearDown(() {
|
|
||||||
session.closed = true;
|
|
||||||
input.resetModifiers();
|
|
||||||
input.disposeRelativeMouseMode();
|
|
||||||
RawKeyboard.instance.clearKeysPressed();
|
|
||||||
LocalFlutterShortcutDispatcher.resetFiredKeys();
|
|
||||||
session.ffiModel.dispose();
|
|
||||||
});
|
|
||||||
final firedAt = <int>[];
|
|
||||||
model.register(
|
|
||||||
kShortcutActionToggleMute, () => firedAt.add(binding.keys.length));
|
|
||||||
await _rawKey(input, scan: alt.$1, key: alt.$2);
|
|
||||||
await _rawKey(input, scan: 39, key: 0x73);
|
|
||||||
await pumpEventQueue();
|
|
||||||
|
|
||||||
expect(binding.keys, [
|
|
||||||
(alt.$3, true, true),
|
|
||||||
if (peer == kPeerPlatformWindows) ('VK_CONTROL', true, true),
|
|
||||||
// GTK reports Alt without a side on the letter event.
|
|
||||||
('VK_MENU', false, false),
|
|
||||||
('RAlt', false, false),
|
|
||||||
if (peer == kPeerPlatformWindows) ('VK_CONTROL', false, false),
|
|
||||||
]);
|
|
||||||
expect(firedAt, [binding.keys.length]);
|
|
||||||
await _rawKey(input, scan: 39, key: 0x73, down: false);
|
|
||||||
await _rawKey(input, scan: 38, key: 0x61);
|
|
||||||
expect(binding.keys.last, ('VK_A', true, true));
|
|
||||||
await _rawKey(input, scan: 38, key: 0x61, down: false);
|
|
||||||
await _rawKey(input,
|
|
||||||
scan: alt.$1, key: alt.$2, down: false, alt: false);
|
|
||||||
await _rawKey(input, scan: 38, key: 0x61, alt: false);
|
|
||||||
expect(binding.keys.last, ('VK_A', true, false));
|
|
||||||
await _rawKey(input, scan: 38, key: 0x61, down: false, alt: false);
|
|
||||||
expect(binding.keys.where((key) => key.$1 == 'VK_S'), isEmpty);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test('fresh Chat shortcut sends through its outgoing session', () async {
|
|
||||||
final binding = _ChatBinding();
|
|
||||||
platformFFI.setBindingForTesting(binding);
|
|
||||||
final chat = session.chatModel;
|
|
||||||
addTearDown(() {
|
|
||||||
chat.dispose();
|
|
||||||
chat.inputNode.dispose();
|
|
||||||
session.ffiModel.dispose();
|
|
||||||
});
|
|
||||||
expect(chat.currentKey.isOut, isFalse);
|
|
||||||
expect(chat.messages, isEmpty);
|
|
||||||
registerSessionShortcutActions(session);
|
|
||||||
|
|
||||||
model.onTriggered(kShortcutActionToggleChat);
|
|
||||||
await pumpEventQueue();
|
|
||||||
chat.send(ChatMessage(
|
|
||||||
text: 'first message', user: chat.me, createdAt: DateTime.now()));
|
|
||||||
await pumpEventQueue();
|
|
||||||
|
|
||||||
expect(binding.sent, [(session.sessionId, 'first message')]);
|
|
||||||
expect(binding.cmSent, isEmpty);
|
|
||||||
expect(chat.opened, [MessageKey(session.id, ChatModel.clientModeID)]);
|
|
||||||
expect(
|
|
||||||
chat.messages.keys, [MessageKey(session.id, ChatModel.clientModeID)]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a removed menu action cannot run its cached callback', () async {
|
|
||||||
var calls = 0;
|
|
||||||
model.register('mute', () => calls++);
|
|
||||||
model.registerRefresher(['mute'], () => model.unregister('mute'));
|
|
||||||
|
|
||||||
model.onTriggered('mute');
|
|
||||||
await pumpEventQueue();
|
|
||||||
|
|
||||||
expect(calls, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('an action becomes available without reopening its menu', () async {
|
|
||||||
var calls = 0;
|
|
||||||
model.registerRefresher(['screenshot'], () {
|
|
||||||
model.register('screenshot', () => calls++);
|
|
||||||
});
|
|
||||||
|
|
||||||
model.onTriggered('screenshot');
|
|
||||||
await pumpEventQueue();
|
|
||||||
|
|
||||||
expect(calls, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('refresh finishes before invoking the current callback', () async {
|
|
||||||
final ready = Completer<void>();
|
|
||||||
final calls = <String>[];
|
|
||||||
model.register('cursor', () => calls.add('stale'));
|
|
||||||
model.registerRefresher(['cursor'], () async {
|
|
||||||
await ready.future;
|
|
||||||
model.register('cursor', () => calls.add('current'));
|
|
||||||
});
|
|
||||||
|
|
||||||
model.onTriggered('cursor');
|
|
||||||
expect(calls, isEmpty);
|
|
||||||
ready.complete();
|
|
||||||
await pumpEventQueue();
|
|
||||||
|
|
||||||
expect(calls, ['current']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('closing during a refresh prevents late registration and dispatch',
|
|
||||||
() async {
|
|
||||||
final ready = Completer<void>();
|
|
||||||
var calls = 0;
|
|
||||||
model.registerRefresher(['mute'], () async {
|
|
||||||
await ready.future;
|
|
||||||
model.register('mute', () => calls++);
|
|
||||||
});
|
|
||||||
|
|
||||||
model.onTriggered('mute');
|
|
||||||
session.closed = true;
|
|
||||||
model.clear();
|
|
||||||
ready.complete();
|
|
||||||
await pumpEventQueue();
|
|
||||||
model.onTriggered('mute');
|
|
||||||
await pumpEventQueue();
|
|
||||||
|
|
||||||
expect(calls, 0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -50,20 +50,54 @@ void main() {
|
|||||||
await tester.pump();
|
await tester.pump();
|
||||||
}
|
}
|
||||||
|
|
||||||
testWidgets('alternate screen reports trackpad after main-screen history',
|
for (final trackpad in [false, true]) {
|
||||||
|
final device = trackpad ? 'trackpad' : 'wheel';
|
||||||
|
testWidgets('alternate screen reports $device after main-screen history',
|
||||||
|
(tester) async {
|
||||||
|
final view = await mount(tester);
|
||||||
|
terminal.write('\x1b[?1049h$_captureMouse');
|
||||||
|
await tester.pump();
|
||||||
|
final render = view.renderTerminal;
|
||||||
|
final point = render.localToGlobal(
|
||||||
|
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
|
||||||
|
if (trackpad) {
|
||||||
|
await scrollTrackpad(tester, point, render.lineHeight * 3);
|
||||||
|
} else {
|
||||||
|
await tester.sendEventToBinding(PointerScrollEvent(
|
||||||
|
position: point,
|
||||||
|
scrollDelta: Offset(0, -render.lineHeight * 3),
|
||||||
|
));
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(output, isNotEmpty);
|
||||||
|
expect(output, everyElement('\x1b[<64;3;2M'));
|
||||||
|
expect(view.widget.scrollController!.offset, 0);
|
||||||
|
expect(controller.selection, isNull);
|
||||||
|
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('trackpad scrolling keeps subsequent drag coordinates aligned',
|
||||||
(tester) async {
|
(tester) async {
|
||||||
final view = await mount(tester);
|
final view = await mount(tester);
|
||||||
terminal.write('\x1b[?1049h$_captureMouse');
|
terminal.write('\x1b[?1049h$_captureMouse');
|
||||||
await tester.pump();
|
await tester.pump();
|
||||||
final render = view.renderTerminal;
|
final render = view.renderTerminal;
|
||||||
final point = render.localToGlobal(
|
final start = render.localToGlobal(
|
||||||
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
|
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
|
||||||
await scrollTrackpad(tester, point, render.lineHeight * 3);
|
final end = render.localToGlobal(
|
||||||
|
Offset(render.cellSize.width * 6.5, render.lineHeight * 2.5));
|
||||||
|
await scrollTrackpad(tester, start, render.lineHeight * 3);
|
||||||
|
output.clear();
|
||||||
|
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||||
|
await mouse.down(start);
|
||||||
|
await mouse.moveTo(end);
|
||||||
|
await mouse.up();
|
||||||
|
await tester.pump(kDoubleTapTimeout);
|
||||||
|
|
||||||
expect(output, isNotEmpty);
|
expect(output, ['\x1b[<0;3;2M', '\x1b[<32;7;3M', '\x1b[<0;7;3m']);
|
||||||
expect(output, everyElement('\x1b[<64;3;2M'));
|
|
||||||
expect(view.widget.scrollController!.offset, 0);
|
|
||||||
expect(controller.selection, isNull);
|
expect(controller.selection, isNull);
|
||||||
|
expect(controller.suspendedPointerInputs, isFalse);
|
||||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||||
|
|
||||||
testWidgets('leaving alternate screen restores local trackpad scrollback',
|
testWidgets('leaving alternate screen restores local trackpad scrollback',
|
||||||
|
|||||||
@@ -17,5 +17,24 @@ void main() {
|
|||||||
['Ctrl', 'Alt', '-', 'PgUp', 'PgDn'],
|
['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,3 +1,5 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter_hbb/models/model.dart';
|
import 'package:flutter_hbb/models/model.dart';
|
||||||
import 'package:flutter_hbb/models/terminal_model.dart';
|
import 'package:flutter_hbb/models/terminal_model.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
@@ -12,6 +14,42 @@ class _FakeFFI implements FFI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void main() {
|
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', () {
|
test('builds its terminal with the wheel button fix', () {
|
||||||
final model = TerminalModel(_FakeFFI());
|
final model = TerminalModel(_FakeFFI());
|
||||||
addTearDown(model.dispose);
|
addTearDown(model.dispose);
|
||||||
|
|||||||
@@ -71,9 +71,10 @@ void main() {
|
|||||||
String? report(
|
String? report(
|
||||||
TerminalMouseButton button, [
|
TerminalMouseButton button, [
|
||||||
TerminalMouseButtonState state = TerminalMouseButtonState.down,
|
TerminalMouseButtonState state = TerminalMouseButtonState.down,
|
||||||
|
CellOffset position = const CellOffset(10, 5),
|
||||||
]) {
|
]) {
|
||||||
output.clear();
|
output.clear();
|
||||||
terminal.mouseInput(button, state, const CellOffset(10, 5));
|
terminal.mouseInput(button, state, position);
|
||||||
return output.isEmpty ? null : output.single;
|
return output.isEmpty ? null : output.single;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +102,40 @@ 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', () {
|
test('leaves non-wheel buttons to the upstream handler', () {
|
||||||
terminal.write('\x1b[?1000h\x1b[?1006h');
|
terminal.write('\x1b[?1000h\x1b[?1006h');
|
||||||
|
|
||||||
@@ -112,6 +147,27 @@ 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 {
|
testWidgets('dragging below scrolls and extends selection', (tester) async {
|
||||||
final controller = TerminalController();
|
final controller = TerminalController();
|
||||||
_writeLines(terminal, 80);
|
_writeLines(terminal, 80);
|
||||||
@@ -202,4 +258,42 @@ void main() {
|
|||||||
expect(output.last, '\x1b[<0;${endCell.x + 1};${endCell.y + 1}m');
|
expect(output.last, '\x1b[<0;${endCell.x + 1};${endCell.y + 1}m');
|
||||||
expect(controller.suspendedPointerInputs, isFalse);
|
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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,22 +59,19 @@ constexpr UINT kForceRedrawMaxTries = 25;
|
|||||||
// per call (each nudge re-enters the 100ms resize wait).
|
// per call (each nudge re-enters the 100ms resize wait).
|
||||||
constexpr UINT kForceRedrawCheapTries = 2;
|
constexpr UINT kForceRedrawCheapTries = 2;
|
||||||
|
|
||||||
// A nonzero intermediate width can time out before Flutter resizes its surface.
|
// Re-enters the embedder's OnWindowSizeChanged by nudging the Flutter child
|
||||||
// Restoring the old width then leaves that intermediate resize pending. Zero
|
// window by 1px and back: this resets the resize target and resends the window
|
||||||
// width resends metrics without creating a new resize target, as in the plugin.
|
// metrics. Same as BaseFlutterWindow::ForceChildRefresh() on the
|
||||||
|
// rustdesk_desktop_multi_window side.
|
||||||
void ForceChildRefresh(HWND child) {
|
void ForceChildRefresh(HWND child) {
|
||||||
if (!child) {
|
if (!child) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// FancyZones can queue a hide before the Flutter view is reparented.
|
|
||||||
if ((GetWindowLongPtr(child, GWL_STYLE) & WS_VISIBLE) == 0) {
|
|
||||||
ShowWindow(child, SW_SHOWNA);
|
|
||||||
}
|
|
||||||
RECT rect;
|
RECT rect;
|
||||||
GetWindowRect(child, &rect);
|
GetWindowRect(child, &rect);
|
||||||
LONG width = rect.right - rect.left;
|
LONG width = rect.right - rect.left;
|
||||||
LONG height = rect.bottom - rect.top;
|
LONG height = rect.bottom - rect.top;
|
||||||
SetWindowPos(child, nullptr, 0, 0, 0, height,
|
SetWindowPos(child, nullptr, 0, 0, width + 1, height,
|
||||||
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
|
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
|
||||||
SetWindowPos(child, nullptr, 0, 0, width, height,
|
SetWindowPos(child, nullptr, 0, 0, width, height,
|
||||||
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
|
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
|
||||||
|
|||||||
@@ -104,14 +104,6 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
|||||||
}
|
}
|
||||||
if (!allow_multiple_instances) {
|
if (!allow_multiple_instances) {
|
||||||
if (!command_line_arguments.empty()) {
|
if (!command_line_arguments.empty()) {
|
||||||
// The process launched by the browser owns the foreground permission.
|
|
||||||
// Transfer it to the existing RustDesk process before dispatching the
|
|
||||||
// URI so that it can bring an existing session to the foreground.
|
|
||||||
DWORD pid = 0;
|
|
||||||
::GetWindowThreadProcessId(hwnd, &pid);
|
|
||||||
if (pid != 0) {
|
|
||||||
::AllowSetForegroundWindow(pid);
|
|
||||||
}
|
|
||||||
// Dispatch command line arguments
|
// Dispatch command line arguments
|
||||||
DispatchToUniLinksDesktop(hwnd);
|
DispatchToUniLinksDesktop(hwnd);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1030,7 +1030,5 @@ message Message {
|
|||||||
TerminalAction terminal_action = 31;
|
TerminalAction terminal_action = 31;
|
||||||
TerminalResponse terminal_response = 32;
|
TerminalResponse terminal_response = 32;
|
||||||
PortForwardChannel port_forward_channel = 33;
|
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1677,6 +1677,15 @@ mod tests {
|
|||||||
assert_err_contains(err, "empty file name");
|
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]
|
#[test]
|
||||||
fn set_files_rejects_mixed_entries_when_one_is_traversal() {
|
fn set_files_rejects_mixed_entries_when_one_is_traversal() {
|
||||||
let mut job = new_validation_job(104);
|
let mut job = new_validation_job(104);
|
||||||
@@ -1699,6 +1708,39 @@ mod tests {
|
|||||||
assert_err_contains(err, "absolute path");
|
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]
|
#[test]
|
||||||
fn rename_file_rejects_invalid_new_name() {
|
fn rename_file_rejects_invalid_new_name() {
|
||||||
let tmp_root = TestTempDir::new("rustdesk_rename_invalid");
|
let tmp_root = TestTempDir::new("rustdesk_rename_invalid");
|
||||||
@@ -1748,4 +1790,24 @@ mod tests {
|
|||||||
assert!(!src.exists());
|
assert!(!src.exists());
|
||||||
assert!(dst.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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -515,6 +515,48 @@ pub fn get_home_dir_trusted() -> Option<PathBuf> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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 get_home_dir_trusted: returns valid path and ignores HOME env var
|
||||||
#[test]
|
#[test]
|
||||||
fn test_get_home_dir_trusted() {
|
fn test_get_home_dir_trusted() {
|
||||||
@@ -542,6 +584,20 @@ 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 shell_quote with single quotes (the tricky case)
|
||||||
#[test]
|
#[test]
|
||||||
fn test_shell_quote_single_quotes() {
|
fn test_shell_quote_single_quotes() {
|
||||||
|
|||||||
@@ -288,3 +288,11 @@ fn send_data_to_all(data: ClipboardFile) {
|
|||||||
allow_err!(msg_channel.sender.send(data.clone()));
|
allow_err!(msg_channel.sender.send(data.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
// #[test]
|
||||||
|
// fn test_cliprdr_run() {
|
||||||
|
// super::cliprdr_run();
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|||||||
@@ -48,19 +48,6 @@ pub struct FileDescription {
|
|||||||
pub creation_time: SystemTime,
|
pub creation_time: SystemTime,
|
||||||
pub size: u64,
|
pub size: u64,
|
||||||
pub perm: u16,
|
pub perm: u16,
|
||||||
/// `file_list_id()` of the list this file came from, sent back in file contents requests
|
|
||||||
#[serde(default)]
|
|
||||||
pub clip_data_id: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Identifies a file list by its descriptor PDU, which both peers hold, so file contents
|
|
||||||
/// requests can name the list they read from. FNV-1a, same as `wf_cliprdr_file_list_id()`.
|
|
||||||
pub fn file_list_id(file_descriptor_pdu: &[u8]) -> i32 {
|
|
||||||
file_descriptor_pdu
|
|
||||||
.iter()
|
|
||||||
.fold(0x811c_9dc5_u32, |id, byte| {
|
|
||||||
(id ^ *byte as u32).wrapping_mul(0x0100_0193)
|
|
||||||
}) as i32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
|
pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
|
||||||
@@ -82,7 +69,6 @@ impl FileDescription {
|
|||||||
fn parse_file_descriptor(
|
fn parse_file_descriptor(
|
||||||
bytes: &mut Bytes,
|
bytes: &mut Bytes,
|
||||||
conn_id: i32,
|
conn_id: i32,
|
||||||
clip_data_id: i32,
|
|
||||||
) -> Result<FileDescription, CliprdrError> {
|
) -> Result<FileDescription, CliprdrError> {
|
||||||
let flags = bytes.get_u32_le();
|
let flags = bytes.get_u32_le();
|
||||||
// skip reserved 32 bytes
|
// skip reserved 32 bytes
|
||||||
@@ -140,13 +126,12 @@ impl FileDescription {
|
|||||||
// cannot set as is...
|
// cannot set as is...
|
||||||
} else if normal {
|
} else if normal {
|
||||||
PERM_RWX
|
PERM_RWX
|
||||||
} else if directory {
|
|
||||||
// Windows ignores read-only and hidden on a directory; without `x` it cannot be entered.
|
|
||||||
PERM_RWX
|
|
||||||
} else if readonly {
|
} else if readonly {
|
||||||
PERM_READ
|
PERM_READ
|
||||||
} else if hidden {
|
} else if hidden {
|
||||||
PERM_SELF_RO
|
PERM_SELF_RO
|
||||||
|
} else if directory {
|
||||||
|
PERM_RWX
|
||||||
} else {
|
} else {
|
||||||
PERM_RW
|
PERM_RW
|
||||||
};
|
};
|
||||||
@@ -169,11 +154,8 @@ impl FileDescription {
|
|||||||
|
|
||||||
let valid_write_time = flags & FLAGS_FD_LAST_WRITE != 0;
|
let valid_write_time = flags & FLAGS_FD_LAST_WRITE != 0;
|
||||||
let last_modified = if valid_write_time && last_write_time >= LDAP_EPOCH_DELTA {
|
let last_modified = if valid_write_time && last_write_time >= LDAP_EPOCH_DELTA {
|
||||||
let last_write_time = last_write_time - LDAP_EPOCH_DELTA;
|
let last_write_time = (last_write_time - LDAP_EPOCH_DELTA) * 100;
|
||||||
let last_write_time = Duration::new(
|
let last_write_time = Duration::from_nanos(last_write_time);
|
||||||
last_write_time / 10_000_000,
|
|
||||||
(last_write_time % 10_000_000) as u32 * 100,
|
|
||||||
);
|
|
||||||
SystemTime::UNIX_EPOCH + last_write_time
|
SystemTime::UNIX_EPOCH + last_write_time
|
||||||
} else {
|
} else {
|
||||||
SystemTime::UNIX_EPOCH
|
SystemTime::UNIX_EPOCH
|
||||||
@@ -193,7 +175,6 @@ impl FileDescription {
|
|||||||
creation_time: last_modified,
|
creation_time: last_modified,
|
||||||
size,
|
size,
|
||||||
perm,
|
perm,
|
||||||
clip_data_id,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(desc)
|
Ok(desc)
|
||||||
@@ -205,7 +186,6 @@ impl FileDescription {
|
|||||||
file_descriptor_pdu: Vec<u8>,
|
file_descriptor_pdu: Vec<u8>,
|
||||||
conn_id: i32,
|
conn_id: i32,
|
||||||
) -> Result<Vec<Self>, CliprdrError> {
|
) -> Result<Vec<Self>, CliprdrError> {
|
||||||
let clip_data_id = file_list_id(&file_descriptor_pdu);
|
|
||||||
let mut data = Bytes::from(file_descriptor_pdu);
|
let mut data = Bytes::from(file_descriptor_pdu);
|
||||||
if data.remaining() < 4 {
|
if data.remaining() < 4 {
|
||||||
return Err(CliprdrError::InvalidRequest {
|
return Err(CliprdrError::InvalidRequest {
|
||||||
@@ -226,7 +206,7 @@ impl FileDescription {
|
|||||||
|
|
||||||
let mut files = Vec::with_capacity(count);
|
let mut files = Vec::with_capacity(count);
|
||||||
for _ in 0..count {
|
for _ in 0..count {
|
||||||
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
|
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
|
||||||
files.push(desc);
|
files.push(desc);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,8 +222,9 @@ mod tests {
|
|||||||
const PDU_HEADER_SIZE: usize = size_of::<u32>();
|
const PDU_HEADER_SIZE: usize = size_of::<u32>();
|
||||||
const DESCRIPTOR_SIZE: usize = 592;
|
const DESCRIPTOR_SIZE: usize = 592;
|
||||||
const ATTRIBUTES_OFFSET: usize = PDU_HEADER_SIZE + 36;
|
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 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;
|
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
|
||||||
|
|
||||||
fn descriptor_pdu(name: &str) -> Vec<u8> {
|
fn descriptor_pdu(name: &str) -> Vec<u8> {
|
||||||
@@ -290,71 +271,23 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn file_list_id_is_fnv1a() {
|
fn ignores_data_after_null_terminator() {
|
||||||
// Reference vectors; the Windows side computes the same id in C.
|
let name = "file.txt";
|
||||||
assert_eq!(file_list_id(b"") as u32, 0x811c_9dc5);
|
let mut pdu = descriptor_pdu(name);
|
||||||
assert_eq!(file_list_id(b"a") as u32, 0xe40c_292c);
|
let padding_offset = NAME_OFFSET + (name.encode_utf16().count() + 1) * size_of::<u16>();
|
||||||
assert_eq!(file_list_id(b"foobar") as u32, 0xbf9c_f968);
|
pdu[padding_offset..padding_offset + size_of::<u16>()]
|
||||||
}
|
.copy_from_slice(&INVALID_UTF16_UNIT.to_le_bytes());
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parsed_files_carry_their_list_id() {
|
|
||||||
let pdu = descriptor_pdu("file.txt");
|
|
||||||
let id = file_list_id(&pdu);
|
|
||||||
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
|
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
|
||||||
assert_eq!(files[0].clip_data_id, id);
|
assert_eq!(files[0].name, PathBuf::from("file.txt"));
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_perm(attributes: u32) -> u16 {
|
|
||||||
let mut pdu = descriptor_pdu("folder");
|
|
||||||
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
|
|
||||||
.copy_from_slice(&attributes.to_le_bytes());
|
|
||||||
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].perm
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn windows_directories_stay_searchable() {
|
fn rejects_non_terminated_file_name() {
|
||||||
const FILE_ATTRIBUTE_READONLY: u32 = 0x01;
|
let name = "a".repeat(FILE_NAME_CODE_UNITS);
|
||||||
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x02;
|
assert!(matches!(
|
||||||
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
|
parse_name(&name),
|
||||||
for attributes in [
|
Err(CliprdrError::InvalidRequest { .. })
|
||||||
FILE_ATTRIBUTE_DIRECTORY,
|
));
|
||||||
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_READONLY,
|
|
||||||
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN,
|
|
||||||
] {
|
|
||||||
assert_eq!(
|
|
||||||
parse_perm(attributes),
|
|
||||||
PERM_RWX,
|
|
||||||
"attributes {attributes:#x}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_last_write_time(filetime: u64) -> SystemTime {
|
|
||||||
let mut pdu = descriptor_pdu("file.txt");
|
|
||||||
pdu[PDU_HEADER_SIZE..PDU_HEADER_SIZE + size_of::<u32>()]
|
|
||||||
.copy_from_slice(&(FLAGS_FD_ATTRIBUTES | FLAGS_FD_LAST_WRITE).to_le_bytes());
|
|
||||||
pdu[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + size_of::<u64>()]
|
|
||||||
.copy_from_slice(&filetime.to_le_bytes());
|
|
||||||
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].last_modified
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn decodes_last_write_time_from_windows_filetime() {
|
|
||||||
// 2023-11-14 22:13:20 UTC
|
|
||||||
assert_eq!(
|
|
||||||
parse_last_write_time(133_444_736_000_000_000),
|
|
||||||
SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000)
|
|
||||||
);
|
|
||||||
// 3000-01-01 00:00:00 UTC
|
|
||||||
assert_eq!(
|
|
||||||
parse_last_write_time(441_481_536_000_000_000),
|
|
||||||
SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000)
|
|
||||||
);
|
|
||||||
// 1969-12-31 23:59:59 UTC falls back to the Unix epoch.
|
|
||||||
assert_eq!(
|
|
||||||
parse_last_write_time(116_444_736_000_000_000 - 10_000_000),
|
|
||||||
SystemTime::UNIX_EPOCH
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -549,8 +549,8 @@ impl FuseServer {
|
|||||||
n_position_low,
|
n_position_low,
|
||||||
n_position_high,
|
n_position_high,
|
||||||
cb_requested,
|
cb_requested,
|
||||||
have_clip_data_id: true,
|
have_clip_data_id: false,
|
||||||
clip_data_id: node.clip_data_id,
|
clip_data_id: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
send_data(node.conn_id, request.clone()).map_err(|e| {
|
send_data(node.conn_id, request.clone()).map_err(|e| {
|
||||||
@@ -611,9 +611,6 @@ struct FuseNode {
|
|||||||
/// connection id
|
/// connection id
|
||||||
pub conn_id: i32,
|
pub conn_id: i32,
|
||||||
|
|
||||||
/// id of the peer's file list this node came from
|
|
||||||
pub clip_data_id: i32,
|
|
||||||
|
|
||||||
/// file index in peer's file list
|
/// file index in peer's file list
|
||||||
/// NOTE:
|
/// NOTE:
|
||||||
/// it is NOT the same as inode, this is the index in the file list
|
/// it is NOT the same as inode, this is the index in the file list
|
||||||
@@ -637,7 +634,6 @@ impl FuseNode {
|
|||||||
pub fn from_description(inode: Inode, desc: FileDescription) -> Self {
|
pub fn from_description(inode: Inode, desc: FileDescription) -> Self {
|
||||||
Self {
|
Self {
|
||||||
conn_id: desc.conn_id,
|
conn_id: desc.conn_id,
|
||||||
clip_data_id: desc.clip_data_id,
|
|
||||||
index: inode as usize - 2,
|
index: inode as usize - 2,
|
||||||
name: desc
|
name: desc
|
||||||
.name
|
.name
|
||||||
@@ -654,7 +650,6 @@ impl FuseNode {
|
|||||||
pub fn new_root() -> Self {
|
pub fn new_root() -> Self {
|
||||||
Self {
|
Self {
|
||||||
conn_id: 0,
|
conn_id: 0,
|
||||||
clip_data_id: 0,
|
|
||||||
index: 0,
|
index: 0,
|
||||||
name: String::from("/"),
|
name: String::from("/"),
|
||||||
parent: None,
|
parent: None,
|
||||||
@@ -903,7 +898,6 @@ mod fuse_test {
|
|||||||
|
|
||||||
size: 0,
|
size: 0,
|
||||||
perm: 0,
|
perm: 0,
|
||||||
clip_data_id: 0,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
|
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
|
||||||
@@ -966,6 +960,35 @@ 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]
|
#[test]
|
||||||
fn test_parse_tree() {
|
fn test_parse_tree() {
|
||||||
build_tree("");
|
build_tree("");
|
||||||
|
|||||||
@@ -160,12 +160,12 @@ impl LocalFile {
|
|||||||
| archive_flag
|
| archive_flag
|
||||||
| normal_flag;
|
| normal_flag;
|
||||||
|
|
||||||
let win32_time = (self
|
let win32_time = self
|
||||||
.last_write_time
|
.last_write_time
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.as_nanos()
|
.as_nanos() as u64
|
||||||
/ 100) as u64
|
/ 100
|
||||||
+ LDAP_EPOCH_DELTA;
|
+ LDAP_EPOCH_DELTA;
|
||||||
|
|
||||||
let size_high = (self.size >> 32) as u32;
|
let size_high = (self.size >> 32) as u32;
|
||||||
@@ -322,8 +322,7 @@ pub(super) fn construct_file_list(paths: &[PathBuf]) -> Result<Vec<LocalFile>, C
|
|||||||
mod file_list_test {
|
mod file_list_test {
|
||||||
use std::{
|
use std::{
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
sync::atomic::AtomicU64,
|
sync::atomic::{AtomicU64, Ordering},
|
||||||
time::{Duration, SystemTime},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use hbb_common::bytes::{BufMut, BytesMut};
|
use hbb_common::bytes::{BufMut, BytesMut};
|
||||||
@@ -466,31 +465,29 @@ mod file_list_test {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
const LAST_WRITE_TIME_OFFSET: usize = 56;
|
|
||||||
|
|
||||||
fn file_with_last_write_time(last_write_time: SystemTime) -> LocalFile {
|
|
||||||
let mut file = generate_tree("").remove(1);
|
|
||||||
file.last_write_time = last_write_time;
|
|
||||||
file
|
|
||||||
}
|
|
||||||
|
|
||||||
fn encoded_last_write_time(last_write_time: SystemTime) -> Result<u64, CliprdrError> {
|
|
||||||
let descriptor = file_with_last_write_time(last_write_time).as_bin()?;
|
|
||||||
let field = &descriptor[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + 8];
|
|
||||||
Ok(u64::from_le_bytes(field.try_into().unwrap()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn encodes_last_write_time_as_windows_filetime() -> Result<(), CliprdrError> {
|
fn read_exact_at_reopens_after_read_failure() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
// 2023-11-14 22:13:20 UTC
|
let file_path = std::env::temp_dir().join(format!(
|
||||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
|
"rustdesk-clipboard-local-file-{}",
|
||||||
assert_eq!(encoded_last_write_time(time)?, 133_444_736_000_000_000);
|
std::process::id()
|
||||||
// 3000-01-01 00:00:00 UTC
|
));
|
||||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000);
|
std::fs::write(&file_path, b"")?;
|
||||||
assert_eq!(encoded_last_write_time(time)?, 441_481_536_000_000_000);
|
|
||||||
// Times before 1970 are sent as 1970-01-01 00:00:00 UTC.
|
let mut file = LocalFile::try_open(&std::env::temp_dir(), &file_path)?;
|
||||||
let time = SystemTime::UNIX_EPOCH - Duration::from_secs(1);
|
file.size = 1;
|
||||||
assert_eq!(encoded_last_write_time(time)?, 116_444_736_000_000_000);
|
|
||||||
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use base::fs::join_validated_path;
|
use base::fs::join_validated_path;
|
||||||
use hbb_common::{allow_err, log, tokio::time::Instant};
|
use hbb_common::{allow_err, log, tokio::time::Instant};
|
||||||
use objc2::rc::Id;
|
|
||||||
use objc2_foundation::NSProgress;
|
|
||||||
use std::{
|
use std::{
|
||||||
cmp::min,
|
cmp::min,
|
||||||
fs::{File, FileTimes, OpenOptions},
|
fs::{File, FileTimes, OpenOptions},
|
||||||
@@ -17,7 +15,7 @@ use std::{
|
|||||||
Arc, Mutex,
|
Arc, Mutex,
|
||||||
},
|
},
|
||||||
thread,
|
thread,
|
||||||
time::Duration,
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
const RECV_RETRY_TIMES: usize = 3;
|
const RECV_RETRY_TIMES: usize = 3;
|
||||||
@@ -25,16 +23,15 @@ const RECV_RETRY_TIMES: usize = 3;
|
|||||||
const DOWNLOAD_EXTENSION: &str = "rddownload";
|
const DOWNLOAD_EXTENSION: &str = "rddownload";
|
||||||
const RECEIVE_WAIT_TIMEOUT: Duration = Duration::from_millis(5_000);
|
const RECEIVE_WAIT_TIMEOUT: Duration = Duration::from_millis(5_000);
|
||||||
|
|
||||||
|
// https://stackoverflow.com/a/15112784/1926020
|
||||||
|
// "1984-01-24 08:00:00 +0000"
|
||||||
|
const TIMESTAMP_FOR_FILE_PROGRESS_COMPLETED: u64 = 443779200;
|
||||||
|
const ATTR_PROGRESS_FRACTION_COMPLETED: &str = "com.apple.progress.fractionCompleted";
|
||||||
|
|
||||||
fn create_new_file(path: impl AsRef<Path>) -> std::io::Result<File> {
|
fn create_new_file(path: impl AsRef<Path>) -> std::io::Result<File> {
|
||||||
OpenOptions::new().write(true).create_new(true).open(path)
|
OpenOptions::new().write(true).create_new(true).open(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn finder_progress_byte_count(bytes: u64) -> Result<i64, CliprdrError> {
|
|
||||||
i64::try_from(bytes).map_err(|_| CliprdrError::InvalidRequest {
|
|
||||||
description: format!("File progress byte count exceeds i64::MAX: {bytes}"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct FileContentsResponse {
|
pub struct FileContentsResponse {
|
||||||
pub conn_id: i32,
|
pub conn_id: i32,
|
||||||
pub msg_flags: i32,
|
pub msg_flags: i32,
|
||||||
@@ -56,7 +53,6 @@ struct PasteTaskProgress {
|
|||||||
download_file_path: String,
|
download_file_path: String,
|
||||||
download_file_current_size: u64,
|
download_file_current_size: u64,
|
||||||
file_handle: Option<BufWriter<File>>,
|
file_handle: Option<BufWriter<File>>,
|
||||||
finder_progress: Option<Id<NSProgress>>,
|
|
||||||
error: Option<CliprdrError>,
|
error: Option<CliprdrError>,
|
||||||
is_canceled: bool,
|
is_canceled: bool,
|
||||||
}
|
}
|
||||||
@@ -120,7 +116,6 @@ impl PasteTask {
|
|||||||
download_file_path: "".to_owned(),
|
download_file_path: "".to_owned(),
|
||||||
download_file_current_size: 0,
|
download_file_current_size: 0,
|
||||||
file_handle: None,
|
file_handle: None,
|
||||||
finder_progress: None,
|
|
||||||
error: None,
|
error: None,
|
||||||
is_canceled: false,
|
is_canceled: false,
|
||||||
},
|
},
|
||||||
@@ -323,7 +318,7 @@ impl PasteTaskHandle {
|
|||||||
} else {
|
} else {
|
||||||
self.progress.offset += size;
|
self.progress.offset += size;
|
||||||
self.progress.download_file_current_size += size;
|
self.progress.download_file_current_size += size;
|
||||||
self.update_progress_completed(None)?;
|
self.update_progress_completed(None);
|
||||||
}
|
}
|
||||||
if self.progress.file_handle.is_none() {
|
if self.progress.file_handle.is_none() {
|
||||||
self.progress.list_index = self.files.len() as i32;
|
self.progress.list_index = self.files.len() as i32;
|
||||||
@@ -334,52 +329,44 @@ impl PasteTaskHandle {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_progress_completed(&mut self) -> Result<(), CliprdrError> {
|
fn start_progress_completed(&self) {
|
||||||
use objc2::rc::autoreleasepool;
|
if let Some(file) = self.progress.file_handle.as_ref() {
|
||||||
use objc2_foundation::{
|
let creation_time =
|
||||||
NSProgressFileOperationKindDownloading, NSProgressKindFile, NSString, NSURL,
|
SystemTime::UNIX_EPOCH + Duration::from_secs(TIMESTAMP_FOR_FILE_PROGRESS_COMPLETED);
|
||||||
};
|
file.get_ref()
|
||||||
|
.set_times(FileTimes::new().set_created(creation_time))
|
||||||
let total_bytes = finder_progress_byte_count(self.progress.download_file_size)?;
|
.ok();
|
||||||
// Finder can retain the legacy timestamp/xattr indicator after a single-chunk transfer.
|
xattr::set(
|
||||||
autoreleasepool(|_| unsafe {
|
&self.progress.download_file_path,
|
||||||
let progress = NSProgress::discreteProgressWithTotalUnitCount(total_bytes);
|
ATTR_PROGRESS_FRACTION_COMPLETED,
|
||||||
let url =
|
"0.0".as_bytes(),
|
||||||
NSURL::fileURLWithPath(&NSString::from_str(&self.progress.download_file_path));
|
)
|
||||||
progress.setKind(Some(NSProgressKindFile));
|
.ok();
|
||||||
progress.setFileOperationKind(Some(NSProgressFileOperationKindDownloading));
|
}
|
||||||
progress.setFileURL(Some(&url));
|
|
||||||
progress.setCancellable(false);
|
|
||||||
progress.setPausable(false);
|
|
||||||
progress.publish();
|
|
||||||
self.progress.finder_progress = Some(progress);
|
|
||||||
});
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_progress_completed(
|
fn update_progress_completed(&mut self, fraction_completed: Option<f64>) {
|
||||||
&mut self,
|
let fraction_completed = fraction_completed.unwrap_or_else(|| {
|
||||||
completed_bytes: Option<u64>,
|
let current_size = self.progress.download_file_current_size as f64;
|
||||||
) -> Result<(), CliprdrError> {
|
let total_size = self.progress.download_file_size as f64;
|
||||||
use objc2::rc::autoreleasepool;
|
if total_size > 0.0 {
|
||||||
|
current_size / total_size
|
||||||
let completed_bytes = finder_progress_byte_count(
|
} else {
|
||||||
completed_bytes.unwrap_or(self.progress.download_file_current_size),
|
1.0
|
||||||
)?;
|
}
|
||||||
if let Some(progress) = self.progress.finder_progress.as_ref() {
|
});
|
||||||
autoreleasepool(|_| unsafe {
|
xattr::set(
|
||||||
progress.setCompletedUnitCount(completed_bytes);
|
&self.progress.download_file_path,
|
||||||
});
|
ATTR_PROGRESS_FRACTION_COMPLETED,
|
||||||
}
|
&fraction_completed.to_string().as_bytes(),
|
||||||
Ok(())
|
)
|
||||||
|
.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn remove_progress_completed(&mut self) {
|
fn remove_progress_completed(path: &str) {
|
||||||
use objc2::rc::autoreleasepool;
|
if !path.is_empty() {
|
||||||
|
xattr::remove(path, ATTR_PROGRESS_FRACTION_COMPLETED).ok();
|
||||||
if let Some(progress) = self.progress.finder_progress.take() {
|
|
||||||
autoreleasepool(|_| unsafe { progress.unpublish() });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -429,7 +416,7 @@ impl PasteTaskHandle {
|
|||||||
self.progress.download_file_path = download_file_path;
|
self.progress.download_file_path = download_file_path;
|
||||||
self.progress.download_file_current_size = 0;
|
self.progress.download_file_current_size = 0;
|
||||||
self.progress.file_handle = Some(writer);
|
self.progress.file_handle = Some(writer);
|
||||||
self.start_progress_completed()?;
|
self.start_progress_completed();
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
self.progress.error = Some(CliprdrError::FileError {
|
self.progress.error = Some(CliprdrError::FileError {
|
||||||
@@ -535,12 +522,14 @@ impl PasteTaskHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn on_cancelled(&mut self) {
|
fn on_cancelled(&mut self) {
|
||||||
self.remove_progress_completed();
|
|
||||||
self.progress.file_handle = None;
|
self.progress.file_handle = None;
|
||||||
std::fs::remove_file(&self.progress.download_file_path).ok();
|
std::fs::remove_file(&self.progress.download_file_path).ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_done(&mut self) -> Result<(), CliprdrError> {
|
fn on_done(&mut self) -> Result<(), CliprdrError> {
|
||||||
|
self.update_progress_completed(Some(1.0));
|
||||||
|
Self::remove_progress_completed(&self.progress.download_file_path);
|
||||||
|
|
||||||
let Some(file) = self.progress.file_handle.as_mut() else {
|
let Some(file) = self.progress.file_handle.as_mut() else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@@ -553,11 +542,6 @@ impl PasteTaskHandle {
|
|||||||
log::error!("Failed to flush file: {:?}", e);
|
log::error!("Failed to flush file: {:?}", e);
|
||||||
}
|
}
|
||||||
self.progress.file_handle = None;
|
self.progress.file_handle = None;
|
||||||
// Updating or unpublishing after rename can leave stale Finder/Dock progress.
|
|
||||||
// https://crbug.com/40217637
|
|
||||||
// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/download/download_status_updater_mac.mm
|
|
||||||
self.update_progress_completed(Some(self.progress.download_file_size))?;
|
|
||||||
self.remove_progress_completed();
|
|
||||||
|
|
||||||
let Some(file_desc) = self.files.get(self.progress.download_file_index as usize) else {
|
let Some(file_desc) = self.files.get(self.progress.download_file_index as usize) else {
|
||||||
// unreachable
|
// unreachable
|
||||||
@@ -633,7 +617,6 @@ impl PasteTaskHandle {
|
|||||||
};
|
};
|
||||||
let cb_requested = min(BLOCK_SIZE as u64, file.size - self.progress.offset);
|
let cb_requested = min(BLOCK_SIZE as u64, file.size - self.progress.offset);
|
||||||
let conn_id = file.conn_id;
|
let conn_id = file.conn_id;
|
||||||
let clip_data_id = file.clip_data_id;
|
|
||||||
|
|
||||||
let (n_position_high, n_position_low) = (
|
let (n_position_high, n_position_low) = (
|
||||||
(self.progress.offset >> 32) as i32,
|
(self.progress.offset >> 32) as i32,
|
||||||
@@ -646,8 +629,8 @@ impl PasteTaskHandle {
|
|||||||
n_position_low,
|
n_position_low,
|
||||||
n_position_high,
|
n_position_high,
|
||||||
cb_requested: cb_requested as _,
|
cb_requested: cb_requested as _,
|
||||||
have_clip_data_id: true,
|
have_clip_data_id: false,
|
||||||
clip_data_id,
|
clip_data_id: 0,
|
||||||
};
|
};
|
||||||
allow_err!(send_data(conn_id, request));
|
allow_err!(send_data(conn_id, request));
|
||||||
self.progress.last_sent_time = Instant::now();
|
self.progress.last_sent_time = Instant::now();
|
||||||
@@ -686,16 +669,10 @@ impl PasteTaskHandle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for PasteTaskHandle {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.remove_progress_completed();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::{os::unix::fs::symlink, time::SystemTime};
|
use std::os::unix::fs::symlink;
|
||||||
|
|
||||||
struct TestDirectory(PathBuf);
|
struct TestDirectory(PathBuf);
|
||||||
|
|
||||||
@@ -726,7 +703,6 @@ mod tests {
|
|||||||
creation_time: SystemTime::UNIX_EPOCH,
|
creation_time: SystemTime::UNIX_EPOCH,
|
||||||
size,
|
size,
|
||||||
perm: 0,
|
perm: 0,
|
||||||
clip_data_id: 0,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -743,7 +719,6 @@ mod tests {
|
|||||||
download_file_path: String::new(),
|
download_file_path: String::new(),
|
||||||
download_file_current_size: 0,
|
download_file_current_size: 0,
|
||||||
file_handle: None,
|
file_handle: None,
|
||||||
finder_progress: None,
|
|
||||||
error: None,
|
error: None,
|
||||||
is_canceled: false,
|
is_canceled: false,
|
||||||
},
|
},
|
||||||
@@ -752,63 +727,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn finder_progress_completes_single_response_transfer() {
|
|
||||||
let (_temp, target, _) = test_directories();
|
|
||||||
let data = b"single response";
|
|
||||||
let file = file_description("small.txt", FileType::File, data.len() as u64);
|
|
||||||
let mut task = paste_task_handle(target.clone(), vec![file]);
|
|
||||||
task.update_next(0).unwrap();
|
|
||||||
let download_path = PathBuf::from(&task.progress.download_file_path);
|
|
||||||
let progress = task.progress.finder_progress.as_ref().unwrap().clone();
|
|
||||||
assert_eq!(unsafe { progress.completedUnitCount() }, 0);
|
|
||||||
|
|
||||||
task.handle_file_contents_response(FileContentsResponse {
|
|
||||||
conn_id: 0,
|
|
||||||
msg_flags: 1,
|
|
||||||
stream_id: 0,
|
|
||||||
requested_data: data.to_vec(),
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
assert_eq!(progress.totalUnitCount(), data.len() as i64);
|
|
||||||
assert_eq!(progress.completedUnitCount(), progress.totalUnitCount());
|
|
||||||
assert!(progress.isFinished());
|
|
||||||
}
|
|
||||||
assert!(task.progress.finder_progress.is_none());
|
|
||||||
assert!(task.progress.file_handle.is_none());
|
|
||||||
assert!(task.is_finished());
|
|
||||||
assert!(task.progress.error.is_none());
|
|
||||||
assert!(!download_path.exists());
|
|
||||||
assert_eq!(std::fs::read(target.join("small.txt")).unwrap(), data);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn finder_progress_reports_bytes_below_one_percent() {
|
|
||||||
let (_temp, target, _) = test_directories();
|
|
||||||
let size = u32::MAX as u64 + 1;
|
|
||||||
let file = file_description("large.bin", FileType::File, size);
|
|
||||||
let mut task = paste_task_handle(target, vec![file]);
|
|
||||||
task.update_next(0).unwrap();
|
|
||||||
task.handle_file_contents_response(FileContentsResponse {
|
|
||||||
conn_id: 0,
|
|
||||||
msg_flags: 1,
|
|
||||||
stream_id: 0,
|
|
||||||
requested_data: vec![1],
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let progress = task.progress.finder_progress.as_ref().unwrap();
|
|
||||||
unsafe {
|
|
||||||
assert_eq!(progress.totalUnitCount(), size as i64);
|
|
||||||
assert_eq!(progress.completedUnitCount(), 1);
|
|
||||||
}
|
|
||||||
task.on_cancelled();
|
|
||||||
assert!(task.progress.finder_progress.is_none());
|
|
||||||
assert!(!Path::new(&task.progress.download_file_path).exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn validates_all_paths_before_creating_files() {
|
fn validates_all_paths_before_creating_files() {
|
||||||
let (_temp, target, outside) = test_directories();
|
let (_temp, target, outside) = test_directories();
|
||||||
@@ -854,4 +772,18 @@ mod tests {
|
|||||||
assert!(!download_path.exists());
|
assert!(!download_path.exists());
|
||||||
assert!(!outside.join("file.txt").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,3 +430,31 @@ pub fn create_pasteboard_context() -> ResultType<Box<PasteboardContext>> {
|
|||||||
context.init();
|
context.init();
|
||||||
Ok(context)
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -40,8 +40,7 @@ pub(super) const FILE_NAME_FIELD_SIZE: usize = FILE_NAME_CODE_UNITS * std::mem::
|
|||||||
|
|
||||||
// begin of epoch used by microsoft
|
// begin of epoch used by microsoft
|
||||||
// 1601-01-01 00:00:00 + LDAP_EPOCH_DELTA*(100 ns) = 1970-01-01 00:00:00
|
// 1601-01-01 00:00:00 + LDAP_EPOCH_DELTA*(100 ns) = 1970-01-01 00:00:00
|
||||||
// 134_774 days (369 years, 89 leap days) * 86_400 s * 10_000_000 per s
|
const LDAP_EPOCH_DELTA: u64 = 116444772610000000;
|
||||||
const LDAP_EPOCH_DELTA: u64 = 116_444_736_000_000_000;
|
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref REMOTE_FORMAT_MAP: DashMap<i32, String> = DashMap::from_iter(
|
static ref REMOTE_FORMAT_MAP: DashMap<i32, String> = DashMap::from_iter(
|
||||||
|
|||||||
@@ -1,27 +1,11 @@
|
|||||||
use crate::{
|
use super::local_file::LocalFile;
|
||||||
platform::unix::{
|
use crate::{platform::unix::local_file::construct_file_list, ClipboardFile, CliprdrError};
|
||||||
filetype::file_list_id,
|
|
||||||
local_file::{construct_file_list, LocalFile},
|
|
||||||
},
|
|
||||||
ClipboardFile, CliprdrError,
|
|
||||||
};
|
|
||||||
use hbb_common::{
|
use hbb_common::{
|
||||||
bytes::{BufMut, BytesMut},
|
bytes::{BufMut, BytesMut},
|
||||||
log,
|
log,
|
||||||
};
|
};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::{
|
use std::{path::PathBuf, sync::Arc, time::SystemTime, usize};
|
||||||
collections::VecDeque,
|
|
||||||
path::PathBuf,
|
|
||||||
sync::{atomic::Ordering, Arc},
|
|
||||||
time::SystemTime,
|
|
||||||
usize,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Our clients request at most this much per range: macOS 4 MiB, FUSE less, and Windows
|
|
||||||
// splits larger reads (WF_CLIPRDR_MAX_RANGE_READ). A larger read is refused, not shortened:
|
|
||||||
// a short response reads as end of file to IStream callers on Windows.
|
|
||||||
const MAX_RANGE_READ: u64 = 16 * 1024 * 1024;
|
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
// local files are cached, this value should not be changed when copying files
|
// local files are cached, this value should not be changed when copying files
|
||||||
@@ -29,18 +13,8 @@ lazy_static::lazy_static! {
|
|||||||
// We need to keep the file list in the same order as the remote side.
|
// We need to keep the file list in the same order as the remote side.
|
||||||
// We may add a `FileId` field to `CliprdrFileContentsRequest` in the future.
|
// We may add a `FileId` field to `CliprdrFileContentsRequest` in the future.
|
||||||
static ref CLIP_FILES: Arc<Mutex<ClipFiles>> = Default::default();
|
static ref CLIP_FILES: Arc<Mutex<ClipFiles>> = Default::default();
|
||||||
// Lists replaced by a newer copy after a peer was sent them, oldest first. The peer's
|
|
||||||
// streams keep reading the list they came from. Lock after `CLIP_FILES`.
|
|
||||||
static ref RETIRED_CLIP_FILES: Mutex<VecDeque<ClipFiles>> = Default::default();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_RETIRED_CLIP_FILES: usize = 4;
|
|
||||||
|
|
||||||
// The first descriptor's `clsid`, inside the 32 reserved bytes every peer skips. A random
|
|
||||||
// nonce there makes each copy's list id distinct, even when two copies have identical
|
|
||||||
// names, sizes and times (the same file in two folders).
|
|
||||||
const LIST_NONCE: std::ops::Range<usize> = 8..24;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
enum FileContentsRequest {
|
enum FileContentsRequest {
|
||||||
Size {
|
Size {
|
||||||
@@ -88,10 +62,6 @@ struct ClipFiles {
|
|||||||
file_list: Vec<LocalFile>,
|
file_list: Vec<LocalFile>,
|
||||||
first_file_index: usize,
|
first_file_index: usize,
|
||||||
files_pdu: Vec<u8>,
|
files_pdu: Vec<u8>,
|
||||||
// `file_list_id(files_pdu)`, which peers send back as `clip_data_id`.
|
|
||||||
id: i32,
|
|
||||||
// Connections that were sent `files_pdu`.
|
|
||||||
served_to: Vec<i32>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClipFiles {
|
impl ClipFiles {
|
||||||
@@ -101,8 +71,6 @@ impl ClipFiles {
|
|||||||
self.file_list.clear();
|
self.file_list.clear();
|
||||||
self.first_file_index = usize::MAX;
|
self.first_file_index = usize::MAX;
|
||||||
self.files_pdu.clear();
|
self.files_pdu.clear();
|
||||||
self.id = 0;
|
|
||||||
self.served_to.clear();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sync_files(
|
fn sync_files(
|
||||||
@@ -132,54 +100,9 @@ impl ClipFiles {
|
|||||||
data.put(file.as_bin()?.as_slice());
|
data.put(file.as_bin()?.as_slice());
|
||||||
}
|
}
|
||||||
self.files_pdu = data.to_vec();
|
self.files_pdu = data.to_vec();
|
||||||
if let Some(nonce) = self.files_pdu.get_mut(LIST_NONCE) {
|
|
||||||
nonce.copy_from_slice(&rand::random::<[u8; 16]>());
|
|
||||||
}
|
|
||||||
self.id = file_list_id(&self.files_pdu);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close files that are not being read, such as the preloaded next file; `read_exact_at`
|
|
||||||
// reopens them on the next read. A file part-way through keeps its handle and offset, so
|
|
||||||
// its remaining bytes come from the same file even if its path is replaced meanwhile.
|
|
||||||
fn release_handles(&mut self) {
|
|
||||||
for file in self.file_list.iter_mut() {
|
|
||||||
if file.offset.load(Ordering::Relaxed) == 0 {
|
|
||||||
file.handle = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A retired list's file is reopened by path once its handle was closed, and the path may now
|
|
||||||
// name a replacement. Check size and modified time on the handle the read will use, and refuse
|
|
||||||
// a file that no longer matches the list.
|
|
||||||
fn check_retired_file(&mut self, request: &FileContentsRequest) -> Result<(), CliprdrError> {
|
|
||||||
let FileContentsRequest::Range { file_idx, .. } = request else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let Some(file) = self.file_list.get_mut(*file_idx) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
if file.is_dir {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
file.load_handle()?;
|
|
||||||
let unchanged = file
|
|
||||||
.handle
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|handle| handle.get_ref().metadata().ok())
|
|
||||||
.map_or(false, |md| {
|
|
||||||
md.len() == file.size && md.modified().ok() == Some(file.last_write_time)
|
|
||||||
});
|
|
||||||
if unchanged {
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Err(CliprdrError::InvalidRequest {
|
|
||||||
description: format!("file {} changed since its list was sent", file.name),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_files_for_audit(&self, request: &FileContentsRequest) -> Option<ClipboardFile> {
|
fn get_files_for_audit(&self, request: &FileContentsRequest) -> Option<ClipboardFile> {
|
||||||
if let FileContentsRequest::Range {
|
if let FileContentsRequest::Range {
|
||||||
file_idx, offset, ..
|
file_idx, offset, ..
|
||||||
@@ -290,21 +213,12 @@ impl ClipFiles {
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let read_size = if length > file.size - offset {
|
let read_size = if offset + length > file.size {
|
||||||
file.size - offset
|
file.size - offset
|
||||||
} else {
|
} else {
|
||||||
length
|
length
|
||||||
};
|
};
|
||||||
|
|
||||||
if read_size > MAX_RANGE_READ {
|
|
||||||
return Err(CliprdrError::InvalidRequest {
|
|
||||||
description: format!(
|
|
||||||
"file contents request of {} bytes exceeds the {} byte limit, conn: {}",
|
|
||||||
read_size, MAX_RANGE_READ, conn_id
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut buf = vec![0u8; read_size as usize];
|
let mut buf = vec![0u8; read_size as usize];
|
||||||
|
|
||||||
file.read_exact_at(&mut buf, offset)?;
|
file.read_exact_at(&mut buf, offset)?;
|
||||||
@@ -324,10 +238,7 @@ impl ClipFiles {
|
|||||||
// hot reload next file
|
// hot reload next file
|
||||||
for next_file in self.file_list.iter_mut().skip(file_idx + 1) {
|
for next_file in self.file_list.iter_mut().skip(file_idx + 1) {
|
||||||
if !next_file.is_dir {
|
if !next_file.is_dir {
|
||||||
// Best-effort: if it still cannot be opened, its own request reports that.
|
next_file.load_handle()?;
|
||||||
if let Err(e) = next_file.load_handle() {
|
|
||||||
log::trace!("failed to preload the next file: {:?}", e);
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,44 +249,6 @@ impl ClipFiles {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn clear_files() {
|
pub fn clear_files() {
|
||||||
CLIP_FILES.lock().clear();
|
CLIP_FILES.lock().clear();
|
||||||
RETIRED_CLIP_FILES.lock().clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// The list a request reads from: the one its `clip_data_id` names, else the one last sent to
|
|
||||||
// the connection. A named list that is gone yields `None`. A peer that sends no id and was
|
|
||||||
// never sent a list reads the current one, as before.
|
|
||||||
fn select_clip_files<'a>(
|
|
||||||
current: &'a mut ClipFiles,
|
|
||||||
retired: &'a mut VecDeque<ClipFiles>,
|
|
||||||
conn_id: i32,
|
|
||||||
clip_data_id: Option<i32>,
|
|
||||||
) -> Option<&'a mut ClipFiles> {
|
|
||||||
match clip_data_id {
|
|
||||||
Some(id) if current.id == id => Some(current),
|
|
||||||
Some(id) => retired
|
|
||||||
.iter_mut()
|
|
||||||
.rev()
|
|
||||||
.find(|files| files.id == id && files.served_to.contains(&conn_id)),
|
|
||||||
None if current.served_to.contains(&conn_id) => Some(current),
|
|
||||||
None => retired
|
|
||||||
.iter_mut()
|
|
||||||
.rev()
|
|
||||||
.find(|files| files.served_to.contains(&conn_id))
|
|
||||||
.or(Some(current)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep a list a peer was sent, so its streams do not read the new copy at the same indexes.
|
|
||||||
fn retire_if_served(mut replaced: ClipFiles) {
|
|
||||||
if replaced.served_to.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
replaced.release_handles();
|
|
||||||
let mut retired = RETIRED_CLIP_FILES.lock();
|
|
||||||
if retired.len() == MAX_RETIRED_CLIP_FILES {
|
|
||||||
retired.pop_front();
|
|
||||||
}
|
|
||||||
retired.push_back(replaced);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_file_contents(
|
pub fn read_file_contents(
|
||||||
@@ -386,7 +259,6 @@ pub fn read_file_contents(
|
|||||||
n_position_low: i32,
|
n_position_low: i32,
|
||||||
n_position_high: i32,
|
n_position_high: i32,
|
||||||
cb_requested: i32,
|
cb_requested: i32,
|
||||||
clip_data_id: Option<i32>,
|
|
||||||
) -> Vec<Result<ClipboardFile, CliprdrError>> {
|
) -> Vec<Result<ClipboardFile, CliprdrError>> {
|
||||||
let fcr = if dw_flags == 0x1 {
|
let fcr = if dw_flags == 0x1 {
|
||||||
FileContentsRequest::Size {
|
FileContentsRequest::Size {
|
||||||
@@ -394,11 +266,8 @@ pub fn read_file_contents(
|
|||||||
file_idx: list_index as usize,
|
file_idx: list_index as usize,
|
||||||
}
|
}
|
||||||
} else if dw_flags == 0x2 {
|
} else if dw_flags == 0x2 {
|
||||||
// nPositionLow and cbRequested are UINT32s carried in i32 fields. Sign-extending
|
let offset = (n_position_high as u64) << 32 | n_position_low as u64;
|
||||||
// them rejects offsets whose low word is >= 2 GiB and turns a negative length
|
let length = cb_requested as u64;
|
||||||
// into a near-u64::MAX read.
|
|
||||||
let offset = (n_position_high as u64) << 32 | n_position_low as u32 as u64;
|
|
||||||
let length = cb_requested as u32 as u64;
|
|
||||||
|
|
||||||
FileContentsRequest::Range {
|
FileContentsRequest::Range {
|
||||||
stream_id,
|
stream_id,
|
||||||
@@ -412,23 +281,7 @@ pub fn read_file_contents(
|
|||||||
})];
|
})];
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut current = CLIP_FILES.lock();
|
let mut clip_files = CLIP_FILES.lock();
|
||||||
let mut retired = RETIRED_CLIP_FILES.lock();
|
|
||||||
let current_ptr: *const ClipFiles = &*current;
|
|
||||||
let Some(clip_files) = select_clip_files(&mut current, &mut retired, conn_id, clip_data_id)
|
|
||||||
else {
|
|
||||||
return vec![Err(CliprdrError::InvalidRequest {
|
|
||||||
description: format!(
|
|
||||||
"file list {:?} is not available to conn: {}",
|
|
||||||
clip_data_id, conn_id
|
|
||||||
),
|
|
||||||
})];
|
|
||||||
};
|
|
||||||
if !std::ptr::eq(&*clip_files, current_ptr) {
|
|
||||||
if let Err(e) = clip_files.check_retired_file(&fcr) {
|
|
||||||
return vec![Err(e)];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut res = vec![];
|
let mut res = vec![];
|
||||||
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
|
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
|
||||||
res.push(Ok(files_res));
|
res.push(Ok(files_res));
|
||||||
@@ -448,21 +301,12 @@ pub fn sync_files(files: &[String]) -> Result<(), CliprdrError> {
|
|||||||
{
|
{
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
// Build aside, so a failure leaves the current list in place.
|
files_lock.sync_files(files, current)?;
|
||||||
let mut next = ClipFiles::default();
|
files_lock.build_file_list_pdu()
|
||||||
next.sync_files(files, current)?;
|
|
||||||
next.build_file_list_pdu()?;
|
|
||||||
let replaced = std::mem::replace(&mut *files_lock, next);
|
|
||||||
retire_if_served(replaced);
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_file_list_pdu(conn_id: i32) -> Vec<u8> {
|
pub fn get_file_list_pdu() -> Vec<u8> {
|
||||||
let mut clip_files = CLIP_FILES.lock();
|
CLIP_FILES.lock().files_pdu.clone()
|
||||||
if !clip_files.files_pdu.is_empty() && !clip_files.served_to.contains(&conn_id) {
|
|
||||||
clip_files.served_to.push(conn_id);
|
|
||||||
}
|
|
||||||
clip_files.files_pdu.clone()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -499,28 +343,46 @@ mod sig_test {
|
|||||||
p.to_string_lossy().to_string()
|
p.to_string_lossy().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tests that drive the global CLIP_FILES must not interleave.
|
#[test]
|
||||||
static CLIP_FILES_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
fn fingerprint_missing_path_is_default() {
|
||||||
|
let tmp = TmpDir::new("missing");
|
||||||
fn lock_clip_files() -> std::sync::MutexGuard<'static, ()> {
|
let missing = path_str(&tmp.join("does_not_exist.bin"));
|
||||||
CLIP_FILES_TEST_LOCK
|
let sigs = fingerprint(&[missing]);
|
||||||
.lock()
|
assert_eq!(sigs.len(), 1);
|
||||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
// 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sparse, so a multi-GiB file costs no disk space.
|
#[test]
|
||||||
fn write_at(path: &PathBuf, offset: u64, data: &[u8]) {
|
fn fingerprint_detects_inplace_edit() {
|
||||||
use std::io::{Seek, SeekFrom, Write};
|
let tmp = TmpDir::new("edit");
|
||||||
let mut f = fs::File::create(path).unwrap();
|
let file = tmp.join("a.bin");
|
||||||
f.seek(SeekFrom::Start(offset)).unwrap();
|
fs::write(&file, b"small").unwrap();
|
||||||
f.write_all(data).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);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn range_data(res: Vec<Result<ClipboardFile, CliprdrError>>) -> Vec<u8> {
|
#[test]
|
||||||
match res.into_iter().last() {
|
fn fingerprint_flags_directory() {
|
||||||
Some(Ok(ClipboardFile::FileContentsResponse { requested_data, .. })) => requested_data,
|
let tmp = TmpDir::new("dir");
|
||||||
other => panic!("unexpected response: {:?}", other),
|
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]
|
#[test]
|
||||||
@@ -531,8 +393,7 @@ mod sig_test {
|
|||||||
let files = vec![path_str(&file)];
|
let files = vec![path_str(&file)];
|
||||||
|
|
||||||
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
|
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
|
||||||
// reset first.
|
// reset first (this is the only test that touches the global).
|
||||||
let _guard = lock_clip_files();
|
|
||||||
clear_files();
|
clear_files();
|
||||||
|
|
||||||
sync_files(&files).unwrap();
|
sync_files(&files).unwrap();
|
||||||
@@ -554,206 +415,4 @@ mod sig_test {
|
|||||||
|
|
||||||
clear_files(); // leave the global clean for other tests
|
clear_files(); // leave the global clean for other tests
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn range_request_decodes_wire_fields_as_u32() {
|
|
||||||
let tmp = TmpDir::new("decode");
|
|
||||||
let small = tmp.join("small.bin");
|
|
||||||
fs::write(&small, b"0123456789").unwrap();
|
|
||||||
let large = tmp.join("large.bin");
|
|
||||||
write_at(&large, 0x8000_0000, b"tail");
|
|
||||||
|
|
||||||
let _guard = lock_clip_files();
|
|
||||||
clear_files();
|
|
||||||
sync_files(&[path_str(&small), path_str(&large)]).unwrap();
|
|
||||||
let small_idx = CLIP_FILES.lock().first_file_index as i32;
|
|
||||||
let large_idx = small_idx + 1;
|
|
||||||
|
|
||||||
// A negative cbRequested is a UINT32 length, clamped to the rest of the file.
|
|
||||||
let res = read_file_contents(0, 0, small_idx, 0x2, 1, 0, -1, None);
|
|
||||||
assert_eq!(range_data(res), b"123456789");
|
|
||||||
|
|
||||||
// An nPositionLow with bit 31 set is an offset past 2 GiB, not a huge one.
|
|
||||||
let res = read_file_contents(0, 0, large_idx, 0x2, 0x8000_0000u32 as i32, 0, 4, None);
|
|
||||||
assert_eq!(range_data(res), b"tail");
|
|
||||||
|
|
||||||
clear_files();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn range_request_over_limit_is_rejected() {
|
|
||||||
let tmp = TmpDir::new("limit");
|
|
||||||
let file = tmp.join("big.bin");
|
|
||||||
let size = MAX_RANGE_READ + 1;
|
|
||||||
write_at(&file, size - 1, b"x");
|
|
||||||
let files = vec![path_str(&file)];
|
|
||||||
|
|
||||||
let mut clip = ClipFiles::default();
|
|
||||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
|
||||||
let file_idx = clip.first_file_index;
|
|
||||||
|
|
||||||
let res = clip.serve_file_contents(
|
|
||||||
0,
|
|
||||||
FileContentsRequest::Range {
|
|
||||||
stream_id: 0,
|
|
||||||
file_idx,
|
|
||||||
offset: 0,
|
|
||||||
length: u32::MAX as u64,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert!(matches!(res, Err(CliprdrError::InvalidRequest { .. })));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn host_copy_during_transfer_keeps_serving_the_sent_list() {
|
|
||||||
let tmp = TmpDir::new("recopy_in_flight");
|
|
||||||
let first = tmp.join("first.bin");
|
|
||||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
|
||||||
let second = tmp.join("second.bin");
|
|
||||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
|
||||||
|
|
||||||
let _guard = lock_clip_files();
|
|
||||||
clear_files();
|
|
||||||
sync_files(&[path_str(&first)]).unwrap();
|
|
||||||
get_file_list_pdu(1);
|
|
||||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
|
||||||
let read = |offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, None));
|
|
||||||
assert_eq!(read(0), b"AAAA");
|
|
||||||
|
|
||||||
// Copying another file on this side must not redirect the peer's stream.
|
|
||||||
sync_files(&[path_str(&second)]).unwrap();
|
|
||||||
assert_eq!(read(4), b"AAAA");
|
|
||||||
|
|
||||||
clear_files();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stream_keeps_its_list_after_a_second_paste() {
|
|
||||||
let tmp = TmpDir::new("repaste_in_flight");
|
|
||||||
let first = tmp.join("first.bin");
|
|
||||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
|
||||||
let second = tmp.join("second.bin");
|
|
||||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
|
||||||
|
|
||||||
let _guard = lock_clip_files();
|
|
||||||
clear_files();
|
|
||||||
sync_files(&[path_str(&first)]).unwrap();
|
|
||||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
|
||||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
|
||||||
|
|
||||||
// The peer copies the second file on this side and pastes it while the first
|
|
||||||
// transfer is still reading.
|
|
||||||
sync_files(&[path_str(&second)]).unwrap();
|
|
||||||
let second_id = file_list_id(&get_file_list_pdu(1));
|
|
||||||
assert_ne!(first_id, second_id);
|
|
||||||
|
|
||||||
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
|
|
||||||
assert_eq!(read(first_id), b"AAAA");
|
|
||||||
assert_eq!(read(second_id), b"BBBB");
|
|
||||||
|
|
||||||
clear_files();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn named_list_must_have_been_sent_to_the_conn() {
|
|
||||||
let tmp = TmpDir::new("foreign_list");
|
|
||||||
let first = tmp.join("first.bin");
|
|
||||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
|
||||||
let second = tmp.join("second.bin");
|
|
||||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
|
||||||
|
|
||||||
let _guard = lock_clip_files();
|
|
||||||
clear_files();
|
|
||||||
sync_files(&[path_str(&first)]).unwrap();
|
|
||||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
|
||||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
|
||||||
sync_files(&[path_str(&second)]).unwrap();
|
|
||||||
|
|
||||||
let refused = |conn_id, id| {
|
|
||||||
matches!(
|
|
||||||
read_file_contents(conn_id, 7, idx, 0x2, 0, 0, 4, Some(id)).last(),
|
|
||||||
Some(Err(CliprdrError::InvalidRequest { .. }))
|
|
||||||
)
|
|
||||||
};
|
|
||||||
// Retired list, asked for by a connection it was never sent to.
|
|
||||||
assert!(refused(2, first_id));
|
|
||||||
// A list id this side never sent.
|
|
||||||
assert!(refused(1, first_id ^ 1));
|
|
||||||
|
|
||||||
clear_files();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list_files(selection: &[&PathBuf]) -> ClipFiles {
|
|
||||||
let files: Vec<String> = selection.iter().map(|p| path_str(p)).collect();
|
|
||||||
let mut clip = ClipFiles::default();
|
|
||||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
|
||||||
clip
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_head(clip: &mut ClipFiles, file_idx: usize) -> Result<Vec<u8>, CliprdrError> {
|
|
||||||
let request = FileContentsRequest::Range {
|
|
||||||
stream_id: 0,
|
|
||||||
file_idx,
|
|
||||||
offset: 0,
|
|
||||||
length: 4,
|
|
||||||
};
|
|
||||||
match clip.serve_file_contents(0, request)? {
|
|
||||||
ClipboardFile::FileContentsResponse { requested_data, .. } => Ok(requested_data),
|
|
||||||
other => panic!("unexpected response: {:?}", other),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Preloading the file after the requested one is best-effort: a file that can no longer
|
|
||||||
// be opened fails its own requests, not those of the file before it.
|
|
||||||
fn assert_only_its_own_requests_fail(clip: &mut ClipFiles, broken: &PathBuf) {
|
|
||||||
let first_idx = clip.first_file_index;
|
|
||||||
let broken_idx = clip
|
|
||||||
.file_list
|
|
||||||
.iter()
|
|
||||||
.position(|f| &f.path == broken)
|
|
||||||
.unwrap();
|
|
||||||
let size = FileContentsRequest::Size {
|
|
||||||
stream_id: 0,
|
|
||||||
file_idx: first_idx,
|
|
||||||
};
|
|
||||||
clip.serve_file_contents(0, size).unwrap();
|
|
||||||
assert_eq!(read_head(clip, first_idx).unwrap(), b"AAAA");
|
|
||||||
assert!(matches!(
|
|
||||||
read_head(clip, broken_idx),
|
|
||||||
Err(CliprdrError::FileError { .. })
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_deleted_next_file_fails_only_its_own_requests() {
|
|
||||||
let tmp = TmpDir::new("next_deleted");
|
|
||||||
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
|
|
||||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
|
||||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
|
||||||
let mut clip = list_files(&[&first, &second]);
|
|
||||||
|
|
||||||
fs::remove_file(&second).unwrap();
|
|
||||||
assert_only_its_own_requests_fail(&mut clip, &second);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_next_file_is_preloaded_past_a_directory() {
|
|
||||||
let tmp = TmpDir::new("next_preloaded");
|
|
||||||
let first = tmp.join("first.bin");
|
|
||||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
|
||||||
let dir = tmp.join("dir");
|
|
||||||
fs::create_dir(&dir).unwrap();
|
|
||||||
let inner = dir.join("inner.bin");
|
|
||||||
fs::write(&inner, b"BBBBBBBB").unwrap();
|
|
||||||
// Listed as first.bin, dir, dir/inner.bin.
|
|
||||||
let mut clip = list_files(&[&first, &dir]);
|
|
||||||
let first_idx = clip.first_file_index;
|
|
||||||
let inner_idx = clip.file_list.len() - 1;
|
|
||||||
assert_eq!(clip.file_list[inner_idx].path, inner);
|
|
||||||
|
|
||||||
assert_eq!(read_head(&mut clip, first_idx).unwrap(), b"AAAA");
|
|
||||||
assert!(clip.file_list[inner_idx].handle.is_some());
|
|
||||||
// The last file has no next file to preload.
|
|
||||||
assert_eq!(read_head(&mut clip, inner_idx).unwrap(), b"BBBB");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,12 +54,6 @@
|
|||||||
/* File clipboard redirection always advertises the descriptor and contents formats. */
|
/* File clipboard redirection always advertises the descriptor and contents formats. */
|
||||||
#define WF_CLIPRDR_FILE_FORMAT_COUNT 2u
|
#define WF_CLIPRDR_FILE_FORMAT_COUNT 2u
|
||||||
#define WF_CLIPRDR_COM_LPT_PREFIX_LENGTH 3u
|
#define WF_CLIPRDR_COM_LPT_PREFIX_LENGTH 3u
|
||||||
/* File lists kept after they were sent, so a transfer still in flight keeps reading its own
|
|
||||||
* files after a later copy or paste replaces them. */
|
|
||||||
#define WF_CLIPRDR_SERVED_FILE_LISTS 4u
|
|
||||||
/* Largest range served in one request, here and by the unix file server (MAX_RANGE_READ in
|
|
||||||
* serv_files.rs). Larger IStream reads are split into requests of this size. */
|
|
||||||
#define WF_CLIPRDR_MAX_RANGE_READ (16u * 1024u * 1024u)
|
|
||||||
static const WCHAR WF_CLIPRDR_SUPERSCRIPT_DIGITS[] = L"\x00B9\x00B2\x00B3";
|
static const WCHAR WF_CLIPRDR_SUPERSCRIPT_DIGITS[] = L"\x00B9\x00B2\x00B3";
|
||||||
static const WCHAR WF_CLIPRDR_INVALID_FILE_NAME_CHARS[] = L"<>:\"|?*";
|
static const WCHAR WF_CLIPRDR_INVALID_FILE_NAME_CHARS[] = L"<>:\"|?*";
|
||||||
|
|
||||||
@@ -219,21 +213,6 @@ static BOOL wf_cliprdr_bounded_strlen(const char *value, size_t max_len, size_t
|
|||||||
return FALSE;
|
return FALSE;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Identifies a file list by its FILEGROUPDESCRIPTORW bytes, which both peers hold, and is
|
|
||||||
* carried as FileContentsRequest.clipDataId. FNV-1a, same as `file_list_id()` on unix. */
|
|
||||||
static UINT32 wf_cliprdr_file_list_id(const BYTE *data, SIZE_T size)
|
|
||||||
{
|
|
||||||
UINT32 id = 2166136261u;
|
|
||||||
SIZE_T i;
|
|
||||||
|
|
||||||
for (i = 0; i < size; i++)
|
|
||||||
{
|
|
||||||
id ^= data[i];
|
|
||||||
id *= 16777619u;
|
|
||||||
}
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clipboard Formats
|
* Clipboard Formats
|
||||||
*/
|
*/
|
||||||
@@ -379,7 +358,6 @@ struct _CliprdrStream
|
|||||||
void *m_pData;
|
void *m_pData;
|
||||||
UINT32 m_connID;
|
UINT32 m_connID;
|
||||||
UINT32 m_streamId; // unique CLIPRDR streamId; avoids leaking a heap pointer
|
UINT32 m_streamId; // unique CLIPRDR streamId; avoids leaking a heap pointer
|
||||||
UINT32 m_clipDataId; // id of the file list this stream was created from
|
|
||||||
};
|
};
|
||||||
typedef struct _CliprdrStream CliprdrStream;
|
typedef struct _CliprdrStream CliprdrStream;
|
||||||
|
|
||||||
@@ -399,21 +377,6 @@ struct _CliprdrDataObject
|
|||||||
};
|
};
|
||||||
typedef struct _CliprdrDataObject CliprdrDataObject;
|
typedef struct _CliprdrDataObject CliprdrDataObject;
|
||||||
|
|
||||||
struct wf_served_file_list
|
|
||||||
{
|
|
||||||
UINT32 id;
|
|
||||||
UINT32 *connIDs; // connections the list was sent to
|
|
||||||
size_t nConnIDs;
|
|
||||||
UINT64 last_served; // served_file_list_seq when last sent; the lowest is evicted first
|
|
||||||
size_t nFiles;
|
|
||||||
size_t first_file_index;
|
|
||||||
WCHAR **file_names;
|
|
||||||
UINT64 *file_sizes;
|
|
||||||
BYTE *descriptors; // the FILEGROUPDESCRIPTORW sent, nonce included
|
|
||||||
SIZE_T descriptorsSize;
|
|
||||||
};
|
|
||||||
typedef struct wf_served_file_list wfServedFileList;
|
|
||||||
|
|
||||||
struct wf_clipboard
|
struct wf_clipboard
|
||||||
{
|
{
|
||||||
// wfContext* wfc;
|
// wfContext* wfc;
|
||||||
@@ -461,10 +424,6 @@ struct wf_clipboard
|
|||||||
WCHAR **file_names;
|
WCHAR **file_names;
|
||||||
size_t first_file_index;
|
size_t first_file_index;
|
||||||
FILEDESCRIPTORW **fileDescriptor;
|
FILEDESCRIPTORW **fileDescriptor;
|
||||||
DWORD file_list_seq; // clipboard sequence number the file list was read at
|
|
||||||
UINT32 file_list_id; // wf_cliprdr_file_list_id() of the file list, 0 while none is valid
|
|
||||||
wfServedFileList served_file_lists[WF_CLIPRDR_SERVED_FILE_LISTS];
|
|
||||||
UINT64 served_file_list_seq;
|
|
||||||
|
|
||||||
BOOL legacyApi;
|
BOOL legacyApi;
|
||||||
HMODULE hUser32;
|
HMODULE hUser32;
|
||||||
@@ -492,8 +451,8 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
|
|||||||
static UINT cliprdr_send_lock(wfClipboard *clipboard);
|
static UINT cliprdr_send_lock(wfClipboard *clipboard);
|
||||||
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
|
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
|
||||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
||||||
UINT32 clipDataId, ULONG index, UINT32 flag,
|
ULONG index, UINT32 flag, DWORD positionhigh,
|
||||||
DWORD positionhigh, DWORD positionlow, ULONG request);
|
DWORD positionlow, ULONG request);
|
||||||
|
|
||||||
static BOOL is_file_descriptor_from_remote();
|
static BOOL is_file_descriptor_from_remote();
|
||||||
static BOOL is_set_by_instance(wfClipboard *clipboard);
|
static BOOL is_set_by_instance(wfClipboard *clipboard);
|
||||||
@@ -505,7 +464,6 @@ static HRESULT CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC *pFormatEtc,
|
|||||||
static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC *instance);
|
static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC *instance);
|
||||||
|
|
||||||
static void CliprdrStream_Delete(CliprdrStream *instance);
|
static void CliprdrStream_Delete(CliprdrStream *instance);
|
||||||
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead);
|
|
||||||
|
|
||||||
static BOOL try_open_clipboard(HWND hwnd)
|
static BOOL try_open_clipboard(HWND hwnd)
|
||||||
{
|
{
|
||||||
@@ -592,11 +550,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
|
|||||||
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
|
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
|
||||||
return S_FALSE;
|
return S_FALSE;
|
||||||
|
|
||||||
if (cb > WF_CLIPRDR_MAX_RANGE_READ)
|
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId, instance->m_lIndex,
|
||||||
return wf_cliprdr_stream_read_split(This, (BYTE *)pv, cb, pcbRead);
|
|
||||||
|
|
||||||
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
|
||||||
instance->m_clipDataId, instance->m_lIndex,
|
|
||||||
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
|
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
|
||||||
instance->m_lOffset.LowPart, cb);
|
instance->m_lOffset.LowPart, cb);
|
||||||
|
|
||||||
@@ -637,26 +591,6 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
|
|||||||
return S_OK;
|
return S_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead)
|
|
||||||
{
|
|
||||||
HRESULT hr = S_OK;
|
|
||||||
ULONG total = 0;
|
|
||||||
ULONG chunk;
|
|
||||||
ULONG n;
|
|
||||||
|
|
||||||
while (total < cb && hr == S_OK)
|
|
||||||
{
|
|
||||||
chunk = cb - total < WF_CLIPRDR_MAX_RANGE_READ ? cb - total : WF_CLIPRDR_MAX_RANGE_READ;
|
|
||||||
n = 0;
|
|
||||||
hr = CliprdrStream_Read(This, pv + total, chunk, &n);
|
|
||||||
total += n;
|
|
||||||
}
|
|
||||||
*pcbRead = total;
|
|
||||||
if (FAILED(hr))
|
|
||||||
return hr;
|
|
||||||
return total < cb ? S_FALSE : S_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream *This, const void *pv, ULONG cb,
|
static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream *This, const void *pv, ULONG cb,
|
||||||
ULONG *pcbWritten)
|
ULONG *pcbWritten)
|
||||||
{
|
{
|
||||||
@@ -802,8 +736,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Clone(IStream *This, IStream **pp
|
|||||||
return E_NOTIMPL;
|
return E_NOTIMPL;
|
||||||
}
|
}
|
||||||
|
|
||||||
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc,
|
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc)
|
||||||
UINT32 clipDataId)
|
|
||||||
{
|
{
|
||||||
IStream *iStream = NULL;
|
IStream *iStream = NULL;
|
||||||
BOOL success = FALSE;
|
BOOL success = FALSE;
|
||||||
@@ -846,7 +779,6 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
|
|||||||
instance->m_lOffset.QuadPart = 0;
|
instance->m_lOffset.QuadPart = 0;
|
||||||
instance->m_connID = connID;
|
instance->m_connID = connID;
|
||||||
instance->m_streamId = (UINT32)InterlockedIncrement(&clipboard->req_f_stream_id_seq);
|
instance->m_streamId = (UINT32)InterlockedIncrement(&clipboard->req_f_stream_id_seq);
|
||||||
instance->m_clipDataId = clipDataId;
|
|
||||||
|
|
||||||
if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES)
|
if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES)
|
||||||
{
|
{
|
||||||
@@ -858,8 +790,8 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
|
|||||||
{
|
{
|
||||||
/* get content size of this stream */
|
/* get content size of this stream */
|
||||||
if (cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
if (cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
||||||
instance->m_clipDataId, instance->m_lIndex,
|
instance->m_lIndex, FILECONTENTS_SIZE, 0, 0,
|
||||||
FILECONTENTS_SIZE, 0, 0, 8) == CHANNEL_RC_OK)
|
8) == CHANNEL_RC_OK)
|
||||||
{
|
{
|
||||||
success = TRUE;
|
success = TRUE;
|
||||||
}
|
}
|
||||||
@@ -1075,7 +1007,6 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
|
|||||||
IStream **streams = NULL;
|
IStream **streams = NULL;
|
||||||
UINT stream_count = 0;
|
UINT stream_count = 0;
|
||||||
SIZE_T hmem_size;
|
SIZE_T hmem_size;
|
||||||
UINT32 clipDataId;
|
|
||||||
// DWORD remote_format_id = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat);
|
// DWORD remote_format_id = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat);
|
||||||
// FIXME: origin code may be failed here???
|
// FIXME: origin code may be failed here???
|
||||||
if (cliprdr_send_data_request(instance->m_connID, clipboard, instance->m_pFormatEtc[idx].cfFormat) != 0)
|
if (cliprdr_send_data_request(instance->m_connID, clipboard, instance->m_pFormatEtc[idx].cfFormat) != 0)
|
||||||
@@ -1122,11 +1053,10 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
|
|||||||
return wf_cliprdr_fail_locked_file_descriptor_data(
|
return wf_cliprdr_fail_locked_file_descriptor_data(
|
||||||
clipboard, pMedium, instance, NULL, 0, E_OUTOFMEMORY);
|
clipboard, pMedium, instance, NULL, 0, E_OUTOFMEMORY);
|
||||||
|
|
||||||
clipDataId = wf_cliprdr_file_list_id((const BYTE *)dsc, hmem_size);
|
|
||||||
for (i = 0; i < stream_count; i++)
|
for (i = 0; i < stream_count; i++)
|
||||||
{
|
{
|
||||||
streams[i] = (IStream *)CliprdrStream_New(instance->m_connID, i, clipboard,
|
streams[i] =
|
||||||
&dsc->fgd[i], clipDataId);
|
(IStream *)CliprdrStream_New(instance->m_connID, i, clipboard, &dsc->fgd[i]);
|
||||||
if (!streams[i])
|
if (!streams[i])
|
||||||
{
|
{
|
||||||
return wf_cliprdr_fail_locked_file_descriptor_data(
|
return wf_cliprdr_fail_locked_file_descriptor_data(
|
||||||
@@ -2066,9 +1996,9 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
|
|||||||
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
|
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
|
||||||
}
|
}
|
||||||
|
|
||||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId, ULONG index,
|
||||||
UINT32 clipDataId, ULONG index, UINT32 flag,
|
UINT32 flag, DWORD positionhigh, DWORD positionlow,
|
||||||
DWORD positionhigh, DWORD positionlow, ULONG nreq)
|
ULONG nreq)
|
||||||
{
|
{
|
||||||
UINT rc;
|
UINT rc;
|
||||||
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
|
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
|
||||||
@@ -2093,8 +2023,7 @@ static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 con
|
|||||||
fileContentsRequest.nPositionLow = positionlow;
|
fileContentsRequest.nPositionLow = positionlow;
|
||||||
fileContentsRequest.nPositionHigh = positionhigh;
|
fileContentsRequest.nPositionHigh = positionhigh;
|
||||||
fileContentsRequest.cbRequested = nreq;
|
fileContentsRequest.cbRequested = nreq;
|
||||||
fileContentsRequest.haveClipDataId = TRUE;
|
fileContentsRequest.clipDataId = 0;
|
||||||
fileContentsRequest.clipDataId = clipDataId;
|
|
||||||
fileContentsRequest.msgFlags = 0;
|
fileContentsRequest.msgFlags = 0;
|
||||||
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
|
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
|
||||||
if (rc != ERROR_SUCCESS)
|
if (rc != ERROR_SUCCESS)
|
||||||
@@ -2495,242 +2424,6 @@ error:
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void wf_cliprdr_free_served_file_list(wfServedFileList *list)
|
|
||||||
{
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
if (list->file_names)
|
|
||||||
{
|
|
||||||
for (i = 0; i < list->nFiles; i++)
|
|
||||||
free(list->file_names[i]);
|
|
||||||
free(list->file_names);
|
|
||||||
}
|
|
||||||
free(list->file_sizes);
|
|
||||||
free(list->connIDs);
|
|
||||||
free(list->descriptors);
|
|
||||||
ZeroMemory(list, sizeof(*list));
|
|
||||||
}
|
|
||||||
|
|
||||||
static BOOL wf_cliprdr_served_to(const wfServedFileList *list, UINT32 connID)
|
|
||||||
{
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
for (i = 0; i < list->nConnIDs; i++)
|
|
||||||
{
|
|
||||||
if (list->connIDs[i] == connID)
|
|
||||||
return TRUE;
|
|
||||||
}
|
|
||||||
return FALSE;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void wf_cliprdr_forget_served_file_lists(wfClipboard *clipboard)
|
|
||||||
{
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
|
||||||
wf_cliprdr_free_served_file_list(&clipboard->served_file_lists[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Whether a kept list has the current file_names and the same descriptors as dsc, apart
|
|
||||||
* from the nonce in fgd[0].clsid. */
|
|
||||||
static BOOL wf_cliprdr_is_same_file_list(wfClipboard *clipboard, const wfServedFileList *list,
|
|
||||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
|
||||||
{
|
|
||||||
SIZE_T nonce_start = offsetof(FILEGROUPDESCRIPTORW, fgd) + offsetof(FILEDESCRIPTORW, clsid);
|
|
||||||
SIZE_T nonce_end = nonce_start + sizeof(CLSID);
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
if (!list->file_names || list->nFiles != clipboard->nFiles ||
|
|
||||||
list->descriptorsSize != size || size < nonce_end)
|
|
||||||
return FALSE;
|
|
||||||
for (i = 0; i < list->nFiles; i++)
|
|
||||||
{
|
|
||||||
if (!clipboard->file_names[i] || wcscmp(list->file_names[i], clipboard->file_names[i]) != 0)
|
|
||||||
return FALSE;
|
|
||||||
}
|
|
||||||
return memcmp(list->descriptors, dsc, nonce_start) == 0 &&
|
|
||||||
memcmp(list->descriptors + nonce_end, (const BYTE *)dsc + nonce_end,
|
|
||||||
size - nonce_end) == 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Puts a nonce in fgd[0].clsid, which peers ignore without FD_CLSID. The list id hashes it,
|
|
||||||
* so each copy gets its own id even when two copies have identical names, sizes and times
|
|
||||||
* (the same file in two folders). Re-sending unchanged files keeps their nonce, and id. */
|
|
||||||
static void wf_cliprdr_stamp_file_list(wfClipboard *clipboard, FILEGROUPDESCRIPTORW *dsc,
|
|
||||||
SIZE_T size)
|
|
||||||
{
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
|
||||||
{
|
|
||||||
if (wf_cliprdr_is_same_file_list(clipboard, &clipboard->served_file_lists[i], dsc, size))
|
|
||||||
{
|
|
||||||
dsc->fgd[0].clsid =
|
|
||||||
((const FILEGROUPDESCRIPTORW *)clipboard->served_file_lists[i].descriptors)
|
|
||||||
->fgd[0]
|
|
||||||
.clsid;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (FAILED(CoCreateGuid(&dsc->fgd[0].clsid)))
|
|
||||||
ZeroMemory(&dsc->fgd[0].clsid, sizeof(CLSID));
|
|
||||||
}
|
|
||||||
|
|
||||||
static BOOL wf_cliprdr_copy_file_list(wfClipboard *clipboard, wfServedFileList *list,
|
|
||||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
|
||||||
{
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
list->file_names = (WCHAR **)calloc(clipboard->nFiles, sizeof(WCHAR *));
|
|
||||||
list->file_sizes = (UINT64 *)calloc(clipboard->nFiles, sizeof(UINT64));
|
|
||||||
list->descriptors = (BYTE *)malloc(size);
|
|
||||||
if (!list->file_names || !list->file_sizes || !list->descriptors)
|
|
||||||
return FALSE;
|
|
||||||
CopyMemory(list->descriptors, dsc, size);
|
|
||||||
list->descriptorsSize = size;
|
|
||||||
list->nFiles = clipboard->nFiles;
|
|
||||||
for (i = 0; i < clipboard->nFiles; i++)
|
|
||||||
{
|
|
||||||
if (!clipboard->file_names[i] ||
|
|
||||||
!(list->file_names[i] = _wcsdup(clipboard->file_names[i])))
|
|
||||||
return FALSE;
|
|
||||||
if (clipboard->fileDescriptor[i])
|
|
||||||
list->file_sizes[i] = ((UINT64)clipboard->fileDescriptor[i]->nFileSizeHigh << 32) |
|
|
||||||
clipboard->fileDescriptor[i]->nFileSizeLow;
|
|
||||||
}
|
|
||||||
list->id = clipboard->file_list_id;
|
|
||||||
list->first_file_index = clipboard->first_file_index;
|
|
||||||
return TRUE;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* One slot per list, shared by every connection it was sent to. A full table evicts the list
|
|
||||||
* sent least recently, so a list a transfer has just started on is kept. */
|
|
||||||
static void wf_cliprdr_remember_served_file_list(wfClipboard *clipboard, UINT32 connID,
|
|
||||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
|
||||||
{
|
|
||||||
wfServedFileList *list = NULL;
|
|
||||||
UINT32 *connIDs;
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
|
||||||
{
|
|
||||||
if (clipboard->served_file_lists[i].file_names &&
|
|
||||||
clipboard->served_file_lists[i].id == clipboard->file_list_id)
|
|
||||||
{
|
|
||||||
list = &clipboard->served_file_lists[i];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!list)
|
|
||||||
{
|
|
||||||
// An empty slot has last_served 0, so it is taken first.
|
|
||||||
list = &clipboard->served_file_lists[0];
|
|
||||||
for (i = 1; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
|
||||||
{
|
|
||||||
if (clipboard->served_file_lists[i].last_served < list->last_served)
|
|
||||||
list = &clipboard->served_file_lists[i];
|
|
||||||
}
|
|
||||||
wf_cliprdr_free_served_file_list(list);
|
|
||||||
if (!wf_cliprdr_copy_file_list(clipboard, list, dsc, size))
|
|
||||||
{
|
|
||||||
wf_cliprdr_free_served_file_list(list);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
list->last_served = ++clipboard->served_file_list_seq;
|
|
||||||
|
|
||||||
if (wf_cliprdr_served_to(list, connID))
|
|
||||||
return;
|
|
||||||
connIDs = (UINT32 *)realloc(list->connIDs, (list->nConnIDs + 1) * sizeof(UINT32));
|
|
||||||
if (!connIDs)
|
|
||||||
return;
|
|
||||||
connIDs[list->nConnIDs++] = connID;
|
|
||||||
list->connIDs = connIDs;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Reads like wf_cliprdr_get_file_contents, but only from the file the list was sent with: a
|
|
||||||
* different size or last-write time means the path now names another file, and the read fails
|
|
||||||
* rather than continuing a transfer with its bytes. */
|
|
||||||
static BOOL wf_cliprdr_get_served_file_contents(const WCHAR *file_name, const FILEDESCRIPTORW *dsc,
|
|
||||||
BYTE *buffer, DWORD positionLow, DWORD positionHigh,
|
|
||||||
DWORD nRequested, DWORD *puSize)
|
|
||||||
{
|
|
||||||
BOOL res = FALSE;
|
|
||||||
HANDLE hFile;
|
|
||||||
LARGE_INTEGER size;
|
|
||||||
LARGE_INTEGER position;
|
|
||||||
FILETIME lastWrite;
|
|
||||||
DWORD nGet;
|
|
||||||
|
|
||||||
hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
|
|
||||||
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
|
|
||||||
if (hFile == INVALID_HANDLE_VALUE)
|
|
||||||
return FALSE;
|
|
||||||
|
|
||||||
if (GetFileSizeEx(hFile, &size) &&
|
|
||||||
(UINT64)size.QuadPart == (((UINT64)dsc->nFileSizeHigh << 32) | dsc->nFileSizeLow) &&
|
|
||||||
(!(dsc->dwFlags & FD_WRITESTIME) ||
|
|
||||||
(GetFileTime(hFile, NULL, NULL, &lastWrite) &&
|
|
||||||
CompareFileTime(&lastWrite, &dsc->ftLastWriteTime) == 0)))
|
|
||||||
{
|
|
||||||
position.LowPart = positionLow;
|
|
||||||
position.HighPart = (LONG)positionHigh;
|
|
||||||
if (SetFilePointerEx(hFile, position, NULL, FILE_BEGIN) &&
|
|
||||||
ReadFile(hFile, buffer, nRequested, &nGet, NULL))
|
|
||||||
{
|
|
||||||
*puSize = nGet;
|
|
||||||
res = TRUE;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CloseHandle(hFile);
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Serves a request by path from the file list it names, if that list was sent to the same
|
|
||||||
* connection. An unknown list fails the request rather than falling back to other files. */
|
|
||||||
static BOOL wf_cliprdr_read_served_file_list(wfClipboard *clipboard,
|
|
||||||
const CLIPRDR_FILE_CONTENTS_REQUEST *request,
|
|
||||||
BYTE *data, UINT32 cbRequested, DWORD *puSize)
|
|
||||||
{
|
|
||||||
wfServedFileList *list = NULL;
|
|
||||||
size_t i;
|
|
||||||
|
|
||||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
|
||||||
{
|
|
||||||
if (clipboard->served_file_lists[i].file_names &&
|
|
||||||
clipboard->served_file_lists[i].id == request->clipDataId &&
|
|
||||||
wf_cliprdr_served_to(&clipboard->served_file_lists[i], request->connID))
|
|
||||||
{
|
|
||||||
list = &clipboard->served_file_lists[i];
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!list || request->listIndex >= list->nFiles)
|
|
||||||
return FALSE;
|
|
||||||
|
|
||||||
if (request->dwFlags == FILECONTENTS_SIZE)
|
|
||||||
{
|
|
||||||
CopyMemory(data, &list->file_sizes[request->listIndex], sizeof(UINT64));
|
|
||||||
*puSize = sizeof(UINT64);
|
|
||||||
return TRUE;
|
|
||||||
}
|
|
||||||
if (request->dwFlags != FILECONTENTS_RANGE)
|
|
||||||
return FALSE;
|
|
||||||
|
|
||||||
if (clipboard->context->HandleClipboardFiles &&
|
|
||||||
request->listIndex == (UINT32)list->first_file_index &&
|
|
||||||
request->nPositionLow == 0 && request->nPositionHigh == 0)
|
|
||||||
{
|
|
||||||
clipboard->context->HandleClipboardFiles(request->connID, list->nFiles, list->file_names);
|
|
||||||
}
|
|
||||||
return wf_cliprdr_get_served_file_contents(
|
|
||||||
list->file_names[request->listIndex],
|
|
||||||
&((const FILEGROUPDESCRIPTORW *)list->descriptors)->fgd[request->listIndex], data,
|
|
||||||
request->nPositionLow, request->nPositionHigh, cbRequested, puSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */
|
/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */
|
||||||
static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t pathLen)
|
static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t pathLen)
|
||||||
{
|
{
|
||||||
@@ -3335,8 +3028,6 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
|
|||||||
STGMEDIUM stg_medium;
|
STGMEDIUM stg_medium;
|
||||||
DROPFILES *dropFiles;
|
DROPFILES *dropFiles;
|
||||||
FILEGROUPDESCRIPTORW *groupDsc;
|
FILEGROUPDESCRIPTORW *groupDsc;
|
||||||
clipboard->file_list_seq = GetClipboardSequenceNumber();
|
|
||||||
clipboard->file_list_id = 0;
|
|
||||||
result = OleGetClipboard(&dataObj);
|
result = OleGetClipboard(&dataObj);
|
||||||
|
|
||||||
if (FAILED(result))
|
if (FAILED(result))
|
||||||
@@ -3473,10 +3164,6 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
|
|||||||
|
|
||||||
buff = groupDsc;
|
buff = groupDsc;
|
||||||
rc = ERROR_SUCCESS;
|
rc = ERROR_SUCCESS;
|
||||||
wf_cliprdr_stamp_file_list(clipboard, groupDsc, size);
|
|
||||||
clipboard->file_list_id = wf_cliprdr_file_list_id((const BYTE *)groupDsc, size);
|
|
||||||
wf_cliprdr_remember_served_file_list(clipboard, formatDataRequest->connID, groupDsc,
|
|
||||||
size);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -3689,18 +3376,6 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
|||||||
return ERROR_INTERNAL_ERROR;
|
return ERROR_INTERNAL_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refuse an unknown request type, or a range over the cap, before allocating for it. Clients
|
|
||||||
// of this version split larger reads; an older Windows client reading more in one
|
|
||||||
// IStream::Read fails, as with unix owners.
|
|
||||||
if ((fileContentsRequest->dwFlags != FILECONTENTS_SIZE &&
|
|
||||||
fileContentsRequest->dwFlags != FILECONTENTS_RANGE) ||
|
|
||||||
(fileContentsRequest->dwFlags == FILECONTENTS_RANGE &&
|
|
||||||
fileContentsRequest->cbRequested > WF_CLIPRDR_MAX_RANGE_READ))
|
|
||||||
{
|
|
||||||
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
|
|
||||||
goto exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the clipboard is set by the instance, or the file descriptor is from remote,
|
// If the clipboard is set by the instance, or the file descriptor is from remote,
|
||||||
// we should not process the request.
|
// we should not process the request.
|
||||||
// Because this may be the following cases:
|
// Because this may be the following cases:
|
||||||
@@ -3726,22 +3401,6 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
|||||||
goto exit;
|
goto exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A stream whose list is no longer the current one reads by path from the list it came from.
|
|
||||||
// Only lists sent to this connection are served.
|
|
||||||
if (fileContentsRequest->haveClipDataId &&
|
|
||||||
fileContentsRequest->clipDataId != clipboard->file_list_id)
|
|
||||||
{
|
|
||||||
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
|
|
||||||
cbRequested = fileContentsRequest->dwFlags == FILECONTENTS_SIZE
|
|
||||||
? sizeof(UINT64)
|
|
||||||
: fileContentsRequest->cbRequested;
|
|
||||||
pData = (BYTE *)calloc(1, cbRequested);
|
|
||||||
if (pData && wf_cliprdr_read_served_file_list(clipboard, fileContentsRequest, pData,
|
|
||||||
cbRequested, &uSize))
|
|
||||||
rc = CHANNEL_RC_OK;
|
|
||||||
goto exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
cbRequested = fileContentsRequest->cbRequested;
|
cbRequested = fileContentsRequest->cbRequested;
|
||||||
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
|
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
|
||||||
cbRequested = sizeof(UINT64);
|
cbRequested = sizeof(UINT64);
|
||||||
@@ -3771,13 +3430,7 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
|||||||
vFormatEtc.lindex = fileContentsRequest->listIndex;
|
vFormatEtc.lindex = fileContentsRequest->listIndex;
|
||||||
vFormatEtc.ptd = NULL;
|
vFormatEtc.ptd = NULL;
|
||||||
|
|
||||||
if (GetClipboardSequenceNumber() != clipboard->file_list_seq)
|
if ((uStreamIdStc != fileContentsRequest->streamId) ||
|
||||||
{
|
|
||||||
// The clipboard changed after the peer got its file list. The live FileContents
|
|
||||||
// belongs to the new copy, so reading it would splice another file into this one.
|
|
||||||
bIsStreamFile = FALSE;
|
|
||||||
}
|
|
||||||
else if ((uStreamIdStc != fileContentsRequest->streamId) ||
|
|
||||||
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
|
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
|
||||||
{
|
{
|
||||||
LPENUMFORMATETC pEnumFormatEtc;
|
LPENUMFORMATETC pEnumFormatEtc;
|
||||||
@@ -4189,7 +3842,6 @@ BOOL wf_cliprdr_uninit(wfClipboard *clipboard, CliprdrClientContext *cliprdr)
|
|||||||
CloseHandle(clipboard->req_fevent);
|
CloseHandle(clipboard->req_fevent);
|
||||||
|
|
||||||
clear_file_array(clipboard);
|
clear_file_array(clipboard);
|
||||||
wf_cliprdr_forget_served_file_lists(clipboard);
|
|
||||||
clear_format_map(clipboard);
|
clear_format_map(clipboard);
|
||||||
free(clipboard->format_mappings);
|
free(clipboard->format_mappings);
|
||||||
return TRUE;
|
return TRUE;
|
||||||
|
|||||||
@@ -146,3 +146,39 @@ fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
|
|||||||
|
|
||||||
Ok(tokens)
|
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,3 +525,28 @@ impl fmt::Debug for Enigo {
|
|||||||
write!(f, "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,6 +391,13 @@ fn convert_to_tfc_key(key: Key) -> Option<TFC_Key> {
|
|||||||
Some(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.
|
/// Both directions: the failure is silent, so a one-directional test passes against the bug.
|
||||||
#[test]
|
#[test]
|
||||||
fn test_custom_mouse_dispatch_follows_is_x11() {
|
fn test_custom_mouse_dispatch_follows_is_x11() {
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ const kUCKeyActionDisplay: u16 = 3;
|
|||||||
#[allow(non_upper_case_globals)]
|
#[allow(non_upper_case_globals)]
|
||||||
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
|
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
|
||||||
const BUF_LEN: usize = 4;
|
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_BACK: i64 = 3;
|
||||||
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
|
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
|
||||||
@@ -429,19 +428,7 @@ impl KeyboardControllable for Enigo {
|
|||||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
|
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
|
||||||
event.set_string(cluster);
|
event.set_string(cluster);
|
||||||
self.post(event, None);
|
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"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -449,40 +436,17 @@ impl KeyboardControllable for Enigo {
|
|||||||
fn key_click(&mut self, key: Key) {
|
fn key_click(&mut self, key: Key) {
|
||||||
let keycode = self.key_to_keycode(key);
|
let keycode = self.key_to_keycode(key);
|
||||||
if keycode == u16::MAX {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(src) = self.event_source.as_ref() {
|
if let Some(src) = self.event_source.as_ref() {
|
||||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
|
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
|
||||||
self.post(event, Some(keycode));
|
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) {
|
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
|
||||||
self.post(event, Some(keycode));
|
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"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -501,29 +465,10 @@ impl KeyboardControllable for Enigo {
|
|||||||
|
|
||||||
fn key_up(&mut self, key: Key) {
|
fn key_up(&mut self, key: Key) {
|
||||||
let code = self.key_to_keycode(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 Some(src) = self.event_source.as_ref() {
|
||||||
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
|
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
|
||||||
self.post(event, Some(code));
|
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"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,17 +39,6 @@ fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) -> DWORD {
|
|||||||
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
|
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
|
||||||
}
|
}
|
||||||
|
|
||||||
// `v` comes from the remote peer unchecked, so scale in i64 to avoid overflow, and clamp to
|
|
||||||
// the 0..=65535 range MOUSEEVENTF_ABSOLUTE takes.
|
|
||||||
// `extent` is 0 when the virtual screen metrics are unavailable.
|
|
||||||
fn to_absolute(v: i32, origin: i32, extent: i32) -> Option<i32> {
|
|
||||||
if extent <= 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let abs = (v as i64 - origin as i64) * 65535 / extent as i64;
|
|
||||||
Some(abs.clamp(0, 65535) as i32)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keybd_event(mut flags: u32, vk: u16, scan: u16) -> DWORD {
|
fn keybd_event(mut flags: u32, vk: u16, scan: u16) -> DWORD {
|
||||||
let mut scan = scan;
|
let mut scan = scan;
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -137,28 +126,13 @@ impl MouseControllable for Enigo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn mouse_move_to(&mut self, x: i32, y: i32) {
|
fn mouse_move_to(&mut self, x: i32, y: i32) {
|
||||||
let (left, top, width, height) = unsafe {
|
|
||||||
(
|
|
||||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
|
||||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
|
||||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
|
||||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let (Some(dx), Some(dy)) = (to_absolute(x, left, width), to_absolute(y, top, height))
|
|
||||||
else {
|
|
||||||
hbb_common::throttled_log!(
|
|
||||||
std::time::Duration::from_secs(60),
|
|
||||||
warn,
|
|
||||||
"mouse_move_to skipped: virtual screen size unavailable"
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
mouse_event(
|
mouse_event(
|
||||||
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
|
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
|
||||||
0,
|
0,
|
||||||
dx,
|
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535
|
||||||
dy,
|
/ unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
|
||||||
|
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535
|
||||||
|
/ unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
Submodule libs/hbb_common updated: 5d52530b63...229b904508
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "rustdesk-portable-packer"
|
name = "rustdesk-portable-packer"
|
||||||
version = "1.5.1"
|
version = "1.5.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "RustDesk Remote Desktop"
|
description = "RustDesk Remote Desktop"
|
||||||
|
|
||||||
@@ -20,7 +20,6 @@ windows = { version = "0.61", features = [
|
|||||||
"Wdk_System",
|
"Wdk_System",
|
||||||
"Wdk_System_SystemServices",
|
"Wdk_System_SystemServices",
|
||||||
"Win32",
|
"Win32",
|
||||||
"Win32_Storage_FileSystem",
|
|
||||||
"Win32_System",
|
"Win32_System",
|
||||||
"Win32_System_SystemInformation",
|
"Win32_System_SystemInformation",
|
||||||
] }
|
] }
|
||||||
@@ -37,3 +36,4 @@ FileDescription = "RustDesk Remote Desktop"
|
|||||||
winres = "0.1"
|
winres = "0.1"
|
||||||
winapi = { version = "0.3", features = [ "winnt", "pdh", "synchapi" ] }
|
winapi = { version = "0.3", features = [ "winnt", "pdh", "synchapi" ] }
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -279,6 +279,26 @@ mod tests {
|
|||||||
.find(|file| normalize_path(&file.path) == normalize_path(path))
|
.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]
|
#[test]
|
||||||
fn distinguishes_an_absent_package_from_a_malformed_one() {
|
fn distinguishes_an_absent_package_from_a_malformed_one() {
|
||||||
assert!(parse_package_blob(None).unwrap().0.is_empty());
|
assert!(parse_package_blob(None).unwrap().0.is_empty());
|
||||||
@@ -352,4 +372,34 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(entry(&files, "./librustdesk.dll").unwrap().raw, b"core");
|
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,8 +19,6 @@ const APP_METADATA_CONFIG: &str = "meta.toml";
|
|||||||
const META_LINE_PREFIX_TIMESTAMP: &str = "timestamp = ";
|
const META_LINE_PREFIX_TIMESTAMP: &str = "timestamp = ";
|
||||||
const META_LINE_PREFIX_FILE: &str = "file = ";
|
const META_LINE_PREFIX_FILE: &str = "file = ";
|
||||||
const APP_PREFIX: &str = "rustdesk";
|
const APP_PREFIX: &str = "rustdesk";
|
||||||
#[cfg(windows)]
|
|
||||||
const VERIFIED_UPDATE_FILE_PREFIX: &str = "rustdesk-verified-";
|
|
||||||
const APPNAME_RUNTIME_ENV_KEY: &str = "RUSTDESK_APPNAME";
|
const APPNAME_RUNTIME_ENV_KEY: &str = "RUSTDESK_APPNAME";
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
const SET_FOREGROUND_WINDOW_ENV_KEY: &str = "SET_FOREGROUND_WINDOW";
|
const SET_FOREGROUND_WINDOW_ENV_KEY: &str = "SET_FOREGROUND_WINDOW";
|
||||||
@@ -289,13 +287,6 @@ fn main() -> Result<(), String> {
|
|||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let quick_support = false;
|
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 mut ui = false;
|
||||||
let reader = BinaryReader::new()?;
|
let reader = BinaryReader::new()?;
|
||||||
if let Some(exe) = setup(
|
if let Some(exe) = setup(
|
||||||
@@ -323,33 +314,6 @@ mod win {
|
|||||||
pub const RUNTIME_BROKER_EXE: &'static str = "C:\\Windows\\System32\\RuntimeBroker.exe";
|
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 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) {
|
pub(super) fn copy_runtime_broker(dir: &Path) {
|
||||||
let src = RUNTIME_BROKER_EXE;
|
let src = RUNTIME_BROKER_EXE;
|
||||||
let tgt = WIN_TOPMOST_INJECTED_PROCESS_EXE;
|
let tgt = WIN_TOPMOST_INJECTED_PROCESS_EXE;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use winapi::{
|
|||||||
shared::{
|
shared::{
|
||||||
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
|
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
|
||||||
ntdef::HANDLE,
|
ntdef::HANDLE,
|
||||||
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
|
winerror::ERROR_INVALID_PRINTER_NAME,
|
||||||
},
|
},
|
||||||
um::winspool::{
|
um::winspool::{
|
||||||
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
|
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
|
||||||
@@ -42,49 +42,20 @@ fn enum_local_printer(
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
|
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
|
||||||
const PRINTER_INFO_LEVEL: DWORD = 1;
|
let r = common_enum(
|
||||||
let mut needed = 0;
|
"EnumPrintersW",
|
||||||
let mut returned = 0;
|
enum_local_printer,
|
||||||
if enum_local_printer(
|
1,
|
||||||
PRINTER_INFO_LEVEL,
|
|info: &PRINTER_INFO_1W| {
|
||||||
null_mut(),
|
if is_name_equal(name, info.pName) {
|
||||||
0,
|
Some(true)
|
||||||
&mut needed,
|
} else {
|
||||||
&mut returned,
|
None
|
||||||
) == FALSE
|
}
|
||||||
{
|
},
|
||||||
let error = io::Error::last_os_error();
|
|| None,
|
||||||
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
|
)?;
|
||||||
bail!("Failed to query EnumPrintersW buffer size: {error}");
|
Ok(r.unwrap_or(false))
|
||||||
}
|
|
||||||
}
|
|
||||||
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
|
// 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`)
|
# `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
|
# 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
|
# 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.12). We deliberately do
|
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.6). We deliberately do
|
||||||
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
|
# 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.
|
# 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
|
# Depends on `wayland`: the three drm modules live inside the `#[cfg(feature = "wayland")]` arm of
|
||||||
|
|||||||
@@ -199,6 +199,23 @@ mod webrtc {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::os::raw::c_uint;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tile_log2_uses_c_uint_and_rounds_up() {
|
||||||
|
let one_thread: c_uint = tile_log2(1);
|
||||||
|
let three_threads: c_uint = tile_log2(3);
|
||||||
|
let max_threads: c_uint = tile_log2(64);
|
||||||
|
|
||||||
|
assert_eq!(one_thread, 0);
|
||||||
|
assert_eq!(three_threads, 2);
|
||||||
|
assert_eq!(max_threads, 6);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EncoderApi for AomEncoder {
|
impl EncoderApi for AomEncoder {
|
||||||
|
|||||||
+123
-141
@@ -36,9 +36,6 @@ pub struct CursorSnapshot {
|
|||||||
/// so the consumer must re-guess on the upright one.
|
/// so the consumer must re-guess on the upright one.
|
||||||
pub hot_measured: bool,
|
pub hot_measured: bool,
|
||||||
pub colors: Vec<u8>,
|
pub colors: Vec<u8>,
|
||||||
/// Cursor plane position (CRTC_X/CRTC_Y), in this reader's scanout pixels.
|
|
||||||
pub x: i32,
|
|
||||||
pub y: i32,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fold everything that makes a cursor a DIFFERENT cursor into its id.
|
/// Fold everything that makes a cursor a DIFFERENT cursor into its id.
|
||||||
@@ -309,8 +306,6 @@ pub struct DisplaySnapshot {
|
|||||||
pub y: i32,
|
pub y: i32,
|
||||||
pub width: u32,
|
pub width: u32,
|
||||||
pub height: u32,
|
pub height: u32,
|
||||||
/// The kernel's whole-hertz vrefresh: 59.94 reads 60. `DrmReader::crtc_refresh` is exact.
|
|
||||||
pub refresh_hz: u32,
|
|
||||||
pub active: bool,
|
pub active: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,9 +374,6 @@ pub struct DrmReader {
|
|||||||
/// alternation and log on every sample, which is the per-frame logging this was written to
|
/// alternation and log on every sample, which is the per-frame logging this was written to
|
||||||
/// avoid. -1 is "nothing reported yet".
|
/// avoid. -1 is "nothing reported yet".
|
||||||
last_provenance: i8,
|
last_provenance: i8,
|
||||||
/// The plane rotation read right after the last successful grab, before any copy: libdrmtap
|
|
||||||
/// reads the property when asked, so a read after the copies could describe the next frame.
|
|
||||||
last_plane_rotation: Option<u32>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DrmReader {
|
impl DrmReader {
|
||||||
@@ -419,7 +411,6 @@ impl DrmReader {
|
|||||||
lib,
|
lib,
|
||||||
ctx,
|
ctx,
|
||||||
buf: Vec::new(),
|
buf: Vec::new(),
|
||||||
last_plane_rotation: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -443,7 +434,6 @@ impl DrmReader {
|
|||||||
format!("drmtap_grab_mapped failed: errno {errno}"),
|
format!("drmtap_grab_mapped failed: errno {errno}"),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
self.last_plane_rotation = self.read_plane_rotation();
|
|
||||||
if frame.data.is_null() || frame.width == 0 || frame.height == 0 {
|
if frame.data.is_null() || frame.width == 0 || frame.height == 0 {
|
||||||
(self.lib.frame_release)(self.ctx, &mut frame);
|
(self.lib.frame_release)(self.ctx, &mut frame);
|
||||||
return Err(io::ErrorKind::WouldBlock.into());
|
return Err(io::ErrorKind::WouldBlock.into());
|
||||||
@@ -538,40 +528,6 @@ impl DrmReader {
|
|||||||
.map(|s| s.to_owned())
|
.map(|s| s.to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The DRM `rotation` bitmask of the plane the last successful grab read from, as it was right
|
|
||||||
/// after that grab. A plane without the property answers rotate-0: it cannot have turned
|
|
||||||
/// anything, so the compositor drew the scanout already turned and the whole output transform
|
|
||||||
/// is still to be undone. `None` only when the library cannot say: it predates the call
|
|
||||||
/// (0.5.8), no plane is bound, or the property set could not be read.
|
|
||||||
pub fn plane_rotation(&self) -> Option<u32> {
|
|
||||||
self.last_plane_rotation
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The refresh of the captured CRTC in hertz as the reduced fraction `(num, den)` of its
|
|
||||||
/// current mode, read now. `None` when the library predates the call (0.5.9) or the CRTC has
|
|
||||||
/// no mode.
|
|
||||||
pub fn crtc_refresh(&mut self) -> Option<(u64, u64)> {
|
|
||||||
let f = self.lib.crtc_refresh?;
|
|
||||||
let (mut num, mut den) = (0u64, 0u64);
|
|
||||||
// SAFETY: self.ctx is a live context and both outputs outlive the call.
|
|
||||||
let rc = unsafe { f(self.ctx, &mut num, &mut den) };
|
|
||||||
(rc == 0 && num != 0 && den != 0).then_some((num, den))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_plane_rotation(&mut self) -> Option<u32> {
|
|
||||||
let f = self.lib.plane_rotation?;
|
|
||||||
let mut rotation: u32 = 0;
|
|
||||||
// SAFETY: self.ctx is a live context and `rotation` outlives the call.
|
|
||||||
let rc = unsafe { f(self.ctx, &mut rotation) };
|
|
||||||
plane_rotation_answer(rc, rotation)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The primary plane's rotation read NOW, for a caller that has not grabbed (enumeration):
|
|
||||||
/// `plane_rotation()` only reflects the last grab.
|
|
||||||
pub fn query_plane_rotation(&mut self) -> Option<u32> {
|
|
||||||
self.read_plane_rotation()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
|
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
|
||||||
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
|
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
|
||||||
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
|
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
|
||||||
@@ -603,7 +559,6 @@ impl DrmReader {
|
|||||||
format!("drmtap_grab_desc failed: errno {errno}"),
|
format!("drmtap_grab_desc failed: errno {errno}"),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
self.last_plane_rotation = self.read_plane_rotation();
|
|
||||||
// `desc.dma_buf_fd` is the canonical fd (what split_capture.c sends); `frame` owns it too and `frame_release` closes the library's copy.
|
// `desc.dma_buf_fd` is the canonical fd (what split_capture.c sends); `frame` owns it too and `frame_release` closes the library's copy.
|
||||||
let raw_fd = if desc.dma_buf_fd >= 0 {
|
let raw_fd = if desc.dma_buf_fd >= 0 {
|
||||||
desc.dma_buf_fd
|
desc.dma_buf_fd
|
||||||
@@ -684,8 +639,6 @@ impl DrmReader {
|
|||||||
hoty: 0,
|
hoty: 0,
|
||||||
hot_measured: false,
|
hot_measured: false,
|
||||||
colors: vec![0, 0, 0, 0],
|
colors: vec![0, 0, 0, 0],
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
})
|
})
|
||||||
} else if !c.pixels.is_null()
|
} else if !c.pixels.is_null()
|
||||||
&& c.width > 0
|
&& c.width > 0
|
||||||
@@ -738,8 +691,6 @@ impl DrmReader {
|
|||||||
hoty,
|
hoty,
|
||||||
hot_measured,
|
hot_measured,
|
||||||
colors,
|
colors,
|
||||||
x: c.x,
|
|
||||||
y: c.y,
|
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -774,7 +725,6 @@ impl DrmReader {
|
|||||||
y: raw[i].y as i32,
|
y: raw[i].y as i32,
|
||||||
width: raw[i].width,
|
width: raw[i].width,
|
||||||
height: raw[i].height,
|
height: raw[i].height,
|
||||||
refresh_hz: raw[i].refresh_hz,
|
|
||||||
active: raw[i].active != 0,
|
active: raw[i].active != 0,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -795,7 +745,47 @@ impl Drop for DrmReader {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod hotspot_provenance_tests {
|
mod hotspot_provenance_tests {
|
||||||
use super::hot_measured_from;
|
use super::{cursor_id, hot_measured_from, provenance_code, provenance_is_news};
|
||||||
|
|
||||||
|
/// The log this makes observable is one line per CHANGE, not one per cursor read. A cursor is
|
||||||
|
/// read far more often than its provenance changes, and a per-sample line here would be the
|
||||||
|
/// same defect libdrmtap already had once.
|
||||||
|
#[test]
|
||||||
|
fn provenance_is_logged_once_and_then_only_on_a_change() {
|
||||||
|
let (none, guessed, measured) = (
|
||||||
|
provenance_code(None),
|
||||||
|
provenance_code(Some(false)),
|
||||||
|
provenance_code(Some(true)),
|
||||||
|
);
|
||||||
|
assert_ne!(none, guessed);
|
||||||
|
assert_ne!(guessed, measured);
|
||||||
|
assert_ne!(none, measured);
|
||||||
|
// First sample of a run: -1 is the unset sentinel, so anything is news.
|
||||||
|
assert!(provenance_is_news(-1, measured));
|
||||||
|
// The same state again is not.
|
||||||
|
assert!(!provenance_is_news(measured, measured));
|
||||||
|
assert!(!provenance_is_news(guessed, guessed));
|
||||||
|
// A real transition is.
|
||||||
|
assert!(provenance_is_news(guessed, measured));
|
||||||
|
assert!(provenance_is_news(measured, none));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The dedup key has to move when the provenance does, or the consumer is never told that the
|
||||||
|
/// same picture now means something different. This is the transition that produces it: the
|
||||||
|
/// properties become readable, the driver's answer is the corner, and the bitmap is unchanged.
|
||||||
|
#[test]
|
||||||
|
fn provenance_changes_the_cursor_identity() {
|
||||||
|
let guessed = cursor_id(0xabc, 24, 24, 0, 0, false);
|
||||||
|
let measured = cursor_id(0xabc, 24, 24, 0, 0, true);
|
||||||
|
assert_ne!(
|
||||||
|
guessed, measured,
|
||||||
|
"same pixels, same (0, 0), different meaning: the producer must not dedupe this away"
|
||||||
|
);
|
||||||
|
// And the pre-existing parts still count, so this did not trade one blind spot for another.
|
||||||
|
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 32, 24, 0, 0, true));
|
||||||
|
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 24, 24, 1, 0, true));
|
||||||
|
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xdef, 24, 24, 0, 0, true));
|
||||||
|
}
|
||||||
|
|
||||||
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
|
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
|
||||||
/// para-virtualized driver that really publishes the hotspot at the image's top-left corner.
|
/// para-virtualized driver that really publishes the hotspot at the image's top-left corner.
|
||||||
@@ -805,6 +795,25 @@ mod hotspot_provenance_tests {
|
|||||||
fn a_measured_zero_hotspot_is_measured() {
|
fn a_measured_zero_hotspot_is_measured() {
|
||||||
assert!(hot_measured_from(Some(true), 0, 0));
|
assert!(hot_measured_from(Some(true), 0, 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// And the mirror: when the library says it was NOT measured, that is the answer even if the
|
||||||
|
/// coordinates happen to be non-zero. The old test would have trusted them.
|
||||||
|
#[test]
|
||||||
|
fn the_librarys_no_beats_the_coordinates() {
|
||||||
|
assert!(!hot_measured_from(Some(false), 12, 11));
|
||||||
|
assert!(!hot_measured_from(Some(false), 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// No answer available: either the symbol is absent (a library older than 0.5.6) or nothing
|
||||||
|
/// recorded one for this sample (a cursor read through an older privileged helper). Neither
|
||||||
|
/// is "it was a guess", so the pre-existing behaviour is kept rather than resolved either way
|
||||||
|
/// -- an older deployed .so must keep behaving as it used to.
|
||||||
|
#[test]
|
||||||
|
fn without_an_answer_the_old_heuristic_stands() {
|
||||||
|
assert!(!hot_measured_from(None, 0, 0));
|
||||||
|
assert!(hot_measured_from(None, 12, 11));
|
||||||
|
assert!(hot_measured_from(None, 0, 5));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -865,6 +874,45 @@ mod hotspot_guess_tests {
|
|||||||
assert_eq!(infer_hotspot(&px, w, h), (4, 4));
|
assert_eq!(infer_hotspot(&px, w, h), (4, 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Each axis is decided by its OWN mirror. This shape is symmetric left-to-right and not
|
||||||
|
/// top-to-bottom, which is the single-direction resize family: the click point is centred
|
||||||
|
/// across the axis that mirrors and stays at the edge on the axis that does not.
|
||||||
|
#[test]
|
||||||
|
fn one_symmetric_axis_centres_that_axis_only() {
|
||||||
|
let (px, w, h) = sprite(&[
|
||||||
|
"....#....",
|
||||||
|
"...###...",
|
||||||
|
"..#####..",
|
||||||
|
".#######.",
|
||||||
|
"....#....",
|
||||||
|
"....#....",
|
||||||
|
"....#....",
|
||||||
|
"....#....",
|
||||||
|
"....#....",
|
||||||
|
]);
|
||||||
|
assert_eq!(infer_hotspot(&px, w, h), (4, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A two-headed DIAGONAL arrow mirrors onto the other diagonal about either axis alone, so
|
||||||
|
/// neither axis reads as symmetric - and it is still a shape with no tip. The half turn is
|
||||||
|
/// what catches it.
|
||||||
|
#[test]
|
||||||
|
fn a_diagonal_two_headed_arrow_is_held_by_its_middle_too() {
|
||||||
|
let (px, w, h) = sprite(&[
|
||||||
|
"###......",
|
||||||
|
"##.......",
|
||||||
|
"#.#......",
|
||||||
|
"...#.....",
|
||||||
|
"....#....",
|
||||||
|
".....#...",
|
||||||
|
"......#.#",
|
||||||
|
".......##",
|
||||||
|
"......###",
|
||||||
|
]);
|
||||||
|
let (hx, hy) = infer_hotspot(&px, w, h);
|
||||||
|
assert_eq!((hx, hy), (4, 4), "a half turn maps this shape onto itself");
|
||||||
|
}
|
||||||
|
|
||||||
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
|
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
|
||||||
/// theme puts the click point on the BAR. The bar is the heavy end, and it is the only thing
|
/// theme puts the click point on the BAR. The bar is the heavy end, and it is the only thing
|
||||||
/// that separates `e-resize` from `w-resize`: they are the same picture reflected, so a rule
|
/// that separates `e-resize` from `w-resize`: they are the same picture reflected, so a rule
|
||||||
@@ -894,6 +942,25 @@ mod hotspot_guess_tests {
|
|||||||
assert_eq!(infer_hotspot(&px, w, h), (0, 3));
|
assert_eq!(infer_hotspot(&px, w, h), (0, 3));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A corner resize cursor is a bracket hugging one corner, and it mirrors onto itself about a
|
||||||
|
/// DIAGONAL rather than about either axis, so neither per-axis test sees it. The click point
|
||||||
|
/// is the inner corner of the bracket, which is the heavy end on both axes.
|
||||||
|
///
|
||||||
|
/// A real one's box is usually not square, and a diagonal reflection only lines up inside a
|
||||||
|
/// square, so which corner of that square the box is placed against decides the answer:
|
||||||
|
/// `ne-resize` scores 0.62 anchored one way and 0.98 the other, and `nw-resize` is the
|
||||||
|
/// reverse. Both anchorings are therefore tried. That case cannot be built as a small
|
||||||
|
/// picture - a non-square box can never be exactly diagonal-symmetric - so it is covered by
|
||||||
|
/// the theme corpus instead, where dropping the second anchoring sends `ne-resize` back past
|
||||||
|
/// master.
|
||||||
|
#[test]
|
||||||
|
fn a_corner_bracket_is_held_by_its_inner_corner() {
|
||||||
|
let (px, w, h) = sprite(&[
|
||||||
|
".....##", ".....##", ".....##", ".....##", ".....##", "#######", "#######",
|
||||||
|
]);
|
||||||
|
assert_eq!(infer_hotspot(&px, w, h), (6, 6));
|
||||||
|
}
|
||||||
|
|
||||||
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
|
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
|
||||||
/// keeps its centre. Nothing in the installed theme is shaped like this - its two I-beams are
|
/// keeps its centre. Nothing in the installed theme is shaped like this - its two I-beams are
|
||||||
/// both symmetric - but a custom cursor can be, and this is the rustdesk#16242 round-one fix.
|
/// both symmetric - but a custom cursor can be, and this is the rustdesk#16242 round-one fix.
|
||||||
@@ -902,97 +969,12 @@ mod hotspot_guess_tests {
|
|||||||
let (px, w, h) = sprite(&["##########.", "#####......", "##########."]);
|
let (px, w, h) = sprite(&["##########.", "#####......", "##########."]);
|
||||||
assert_eq!(infer_hotspot(&px, w, h), (4, 1));
|
assert_eq!(infer_hotspot(&px, w, h), (4, 1));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// DRM_MODE_ROTATE_0: the `rotation` bitmask of a plane that turned nothing.
|
|
||||||
const DRM_MODE_ROTATE_0: u32 = 1 << 0;
|
|
||||||
|
|
||||||
/// What a `drmtap_plane_rotation` return means to the consumer. Success is the mask. `-ENOTSUP`
|
|
||||||
/// (the plane has no `rotation` property) is rotate-0, not "unknown": such a plane cannot have
|
|
||||||
/// turned the scanout, so the frame arrives turned by the whole output transform, which is the
|
|
||||||
/// virtio-gpu and vmwgfx case this exists for. Anything else (`-ENOENT` with no plane bound, a
|
|
||||||
/// failed property read) is `None`, and the consumer keeps its pre-0.5.8 rule.
|
|
||||||
fn plane_rotation_answer(rc: c_int, rotation: u32) -> Option<u32> {
|
|
||||||
if rc == 0 {
|
|
||||||
Some(rotation)
|
|
||||||
} else if rc == -hbb_common::libc::ENOTSUP {
|
|
||||||
Some(DRM_MODE_ROTATE_0)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod plane_rotation_tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
|
/// Nothing opaque is not a shape, and must not read as a box at the origin with a hotspot in
|
||||||
|
/// the middle of it.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_plane_without_the_property_turned_nothing() {
|
fn a_blank_sprite_has_no_hotspot_to_guess() {
|
||||||
assert_eq!(plane_rotation_answer(0, 0x4), Some(0x4));
|
let (px, w, h) = sprite(&["...", "...", "..."]);
|
||||||
assert_eq!(plane_rotation_answer(0, 0x1), Some(0x1));
|
assert_eq!(infer_hotspot(&px, w, h), (0, 0));
|
||||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::ENOTSUP, 0), Some(0x1));
|
|
||||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::ENOENT, 0), None);
|
|
||||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::EINVAL, 0), None);
|
|
||||||
assert_eq!(plane_rotation_answer(-hbb_common::libc::EIO, 7), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod crtc_refresh_tests {
|
|
||||||
use super::*;
|
|
||||||
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
|
|
||||||
|
|
||||||
static RC: AtomicI32 = AtomicI32::new(0);
|
|
||||||
static NUM: AtomicU64 = AtomicU64::new(0);
|
|
||||||
static DEN: AtomicU64 = AtomicU64::new(0);
|
|
||||||
|
|
||||||
unsafe extern "C" fn crtc_refresh(_: *mut drmtap_ctx, num: *mut u64, den: *mut u64) -> c_int {
|
|
||||||
*num = NUM.load(Ordering::SeqCst);
|
|
||||||
*den = DEN.load(Ordering::SeqCst);
|
|
||||||
RC.load(Ordering::SeqCst)
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn grab_mapped(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) -> c_int {
|
|
||||||
-1
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {}
|
|
||||||
unsafe extern "C" fn grab_desc(
|
|
||||||
_: *mut drmtap_ctx,
|
|
||||||
_: *mut drmtap_dmabuf_desc,
|
|
||||||
_: *mut drmtap_frame_info,
|
|
||||||
) -> c_int {
|
|
||||||
-1
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, _: *mut u32) -> c_int {
|
|
||||||
-1
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reader(with_call: bool) -> DrmReader {
|
|
||||||
let mut lib = DrmtapLib::fake(grab_mapped, frame_release, grab_desc, plane_rotation);
|
|
||||||
if with_call {
|
|
||||||
lib.crtc_refresh = Some(crtc_refresh);
|
|
||||||
}
|
|
||||||
DrmReader {
|
|
||||||
lib: Box::leak(Box::new(lib)),
|
|
||||||
ctx: std::ptr::null_mut(),
|
|
||||||
buf: Vec::new(),
|
|
||||||
last_provenance: -1,
|
|
||||||
last_plane_rotation: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// rustdesk#16175: the exact refresh paces the producer; an older library has no answer.
|
|
||||||
#[test]
|
|
||||||
fn the_crtc_refresh_is_a_fraction_or_nothing() {
|
|
||||||
assert_eq!(reader(false).crtc_refresh(), None, "a library before 0.5.9");
|
|
||||||
let mut r = reader(true);
|
|
||||||
RC.store(0, Ordering::SeqCst);
|
|
||||||
NUM.store(148352, Ordering::SeqCst);
|
|
||||||
DEN.store(2475, Ordering::SeqCst);
|
|
||||||
assert_eq!(r.crtc_refresh(), Some((148352, 2475)));
|
|
||||||
RC.store(-hbb_common::libc::ENODATA, Ordering::SeqCst);
|
|
||||||
assert_eq!(r.crtc_refresh(), None, "a CRTC with no mode");
|
|
||||||
RC.store(0, Ordering::SeqCst);
|
|
||||||
DEN.store(0, Ordering::SeqCst);
|
|
||||||
assert_eq!(r.crtc_refresh(), None, "a zero denominator is no answer");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,16 +140,6 @@ type FnGrabDesc =
|
|||||||
type FnOpenRender = unsafe extern "C" fn(*const c_char) -> *mut drmtap_ctx;
|
type FnOpenRender = unsafe extern "C" fn(*const c_char) -> *mut drmtap_ctx;
|
||||||
// libdrmtap >= 0.4.15; returns a ctx-owned string, or NULL if it has none.
|
// libdrmtap >= 0.4.15; returns a ctx-owned string, or NULL if it has none.
|
||||||
type FnRenderNode = unsafe extern "C" fn(*mut drmtap_ctx) -> *const c_char;
|
type FnRenderNode = unsafe extern "C" fn(*mut drmtap_ctx) -> *const c_char;
|
||||||
/// `drmtap_plane_rotation`, added in libdrmtap 0.5.8: the DRM `rotation` bitmask the primary
|
|
||||||
/// plane scans out with, read now (0x1 = 0, 0x2 = 90, 0x4 = 180, 0x8 = 270, plus 0x10/0x20 for
|
|
||||||
/// a reflection). 0 with `*rotation` set; `-ENOTSUP` when the plane has no such property, which
|
|
||||||
/// means the compositor can only have rotated in software; `-ENOENT` with no plane bound;
|
|
||||||
/// `-EINVAL` on a null argument.
|
|
||||||
type FnPlaneRotation = unsafe extern "C" fn(*mut drmtap_ctx, *mut u32) -> c_int;
|
|
||||||
/// `drmtap_crtc_refresh`, added in libdrmtap 0.5.9: the refresh of the captured CRTC in hertz as
|
|
||||||
/// the reduced fraction `*num / *den` of its current mode. 0 on success; `-ENODATA` for a CRTC
|
|
||||||
/// with no mode; `-ENOENT` with none to pick; `-EINVAL` on a null argument.
|
|
||||||
type FnCrtcRefresh = unsafe extern "C" fn(*mut drmtap_ctx, *mut u64, *mut u64) -> c_int;
|
|
||||||
type FnConvertDmabuf =
|
type FnConvertDmabuf =
|
||||||
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
|
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
|
||||||
|
|
||||||
@@ -172,68 +162,9 @@ pub struct DrmtapLib {
|
|||||||
pub open_render: FnOpenRender,
|
pub open_render: FnOpenRender,
|
||||||
pub convert_dmabuf: FnConvertDmabuf,
|
pub convert_dmabuf: FnConvertDmabuf,
|
||||||
pub render_node: Option<FnRenderNode>,
|
pub render_node: Option<FnRenderNode>,
|
||||||
/// Optional: it only exists from libdrmtap 0.5.8. Absent means the library cannot say whether
|
|
||||||
/// the plane rotated the scanout, and the consumer keeps the pre-0.5.8 rule for that case.
|
|
||||||
pub plane_rotation: Option<FnPlaneRotation>,
|
|
||||||
/// Optional: it only exists from libdrmtap 0.5.9. Absent means the producer takes the
|
|
||||||
/// whole-hertz refresh of the enumeration as its pacing floor.
|
|
||||||
pub crtc_refresh: Option<FnCrtcRefresh>,
|
|
||||||
pub version: (c_int, c_int, c_int),
|
pub version: (c_int, c_int, c_int),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A library whose capture entry points are the given fakes and whose others do nothing, for the
|
|
||||||
/// tests of the reader.
|
|
||||||
#[cfg(test)]
|
|
||||||
impl DrmtapLib {
|
|
||||||
pub(crate) fn fake(
|
|
||||||
grab_mapped: FnGrabMapped,
|
|
||||||
frame_release: FnFrameRelease,
|
|
||||||
grab_desc: FnGrabDesc,
|
|
||||||
plane_rotation: FnPlaneRotation,
|
|
||||||
) -> Self {
|
|
||||||
unsafe extern "C" fn open(_: *const drmtap_config) -> *mut drmtap_ctx {
|
|
||||||
std::ptr::null_mut()
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn close(_: *mut drmtap_ctx) {}
|
|
||||||
unsafe extern "C" fn list_displays(_: *mut drmtap_ctx, _: *mut drmtap_display, _: c_int) -> c_int {
|
|
||||||
0
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn get_cursor(_: *mut drmtap_ctx, _: *mut drmtap_cursor_info) -> c_int {
|
|
||||||
-1
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn cursor_release(_: *mut drmtap_ctx, _: *mut drmtap_cursor_info) {}
|
|
||||||
unsafe extern "C" fn open_render(_: *const c_char) -> *mut drmtap_ctx {
|
|
||||||
std::ptr::null_mut()
|
|
||||||
}
|
|
||||||
unsafe extern "C" fn convert_dmabuf(
|
|
||||||
_: *mut drmtap_ctx,
|
|
||||||
_: *const drmtap_dmabuf_desc,
|
|
||||||
_: *mut drmtap_frame_info,
|
|
||||||
) -> c_int {
|
|
||||||
-1
|
|
||||||
}
|
|
||||||
DrmtapLib {
|
|
||||||
_lib: hbb_common::libloading::os::unix::Library::this().into(),
|
|
||||||
open,
|
|
||||||
close,
|
|
||||||
list_displays,
|
|
||||||
list_devices: None,
|
|
||||||
grab_mapped,
|
|
||||||
frame_release,
|
|
||||||
get_cursor,
|
|
||||||
cursor_release,
|
|
||||||
cursor_hotspot_valid: None,
|
|
||||||
grab_desc,
|
|
||||||
open_render,
|
|
||||||
convert_dmabuf,
|
|
||||||
render_node: None,
|
|
||||||
plane_rotation: Some(plane_rotation),
|
|
||||||
crtc_refresh: None,
|
|
||||||
version: (0, 5, 8),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SAFETY: the resolved fn pointers are plain C entry points with no interior mutability;
|
// SAFETY: the resolved fn pointers are plain C entry points with no interior mutability;
|
||||||
// libdrmtap contexts are used single-threaded by the caller. The Library handle is never moved out.
|
// libdrmtap contexts are used single-threaded by the caller. The Library handle is never moved out.
|
||||||
unsafe impl Send for DrmtapLib {}
|
unsafe impl Send for DrmtapLib {}
|
||||||
@@ -359,10 +290,6 @@ impl DrmtapLib {
|
|||||||
lib.get(b"drmtap_render_node").ok().map(|s| *s);
|
lib.get(b"drmtap_render_node").ok().map(|s| *s);
|
||||||
let cursor_hotspot_valid: Option<FnCursorHotspotValid> =
|
let cursor_hotspot_valid: Option<FnCursorHotspotValid> =
|
||||||
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
|
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
|
||||||
let plane_rotation: Option<FnPlaneRotation> =
|
|
||||||
lib.get(b"drmtap_plane_rotation").ok().map(|s| *s);
|
|
||||||
let crtc_refresh: Option<FnCrtcRefresh> =
|
|
||||||
lib.get(b"drmtap_crtc_refresh").ok().map(|s| *s);
|
|
||||||
// Log the load only now that every required symbol resolved: this fn still returns None on a missing one.
|
// Log the load only now that every required symbol resolved: this fn still returns None on a missing one.
|
||||||
let loaded_from = real
|
let loaded_from = real
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -406,22 +333,6 @@ impl DrmtapLib {
|
|||||||
a driver that really puts the hotspot at (0, 0)."
|
a driver that really puts the hotspot at (0, 0)."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (minor, patch) >= (5, 8) && plane_rotation.is_none() {
|
|
||||||
log::warn!(
|
|
||||||
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
|
|
||||||
drmtap_plane_rotation: it is a stale or pre-release build. Check what the \
|
|
||||||
soname symlink points at. A 180-degree output rotated by the compositor in \
|
|
||||||
software will be captured upside down."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (minor, patch) >= (5, 9) && crtc_refresh.is_none() {
|
|
||||||
log::warn!(
|
|
||||||
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
|
|
||||||
drmtap_crtc_refresh: it is a stale or pre-release build. Check what the \
|
|
||||||
soname symlink points at. Capture paces to the whole-hertz refresh, so a \
|
|
||||||
59.94 Hz panel is sampled as if it were 60."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Some(DrmtapLib {
|
Some(DrmtapLib {
|
||||||
_lib: lib,
|
_lib: lib,
|
||||||
open,
|
open,
|
||||||
@@ -437,8 +348,6 @@ impl DrmtapLib {
|
|||||||
open_render,
|
open_render,
|
||||||
convert_dmabuf,
|
convert_dmabuf,
|
||||||
render_node,
|
render_node,
|
||||||
plane_rotation,
|
|
||||||
crtc_refresh,
|
|
||||||
version: (major, minor, patch),
|
version: (major, minor, patch),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -464,6 +373,41 @@ pub fn get() -> Option<&'static DrmtapLib> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{abi_accepted, DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, DRMTAP_MIN_MINOR_PATCH};
|
use super::{abi_accepted, DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, DRMTAP_MIN_MINOR_PATCH};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn abi_gate_rejects_a_library_from_before_the_split() {
|
||||||
|
// These are refused because their MINOR differs from the verified one, which is the only
|
||||||
|
// reason the gate needs. Naming the pre-split releases keeps the intent readable, but do
|
||||||
|
// not read this as the floor doing the work: see the test below.
|
||||||
|
for (minor, patch) in [(3, 3), (4, 0), (4, 8), (4, 9)] {
|
||||||
|
assert!(
|
||||||
|
!abi_accepted(DRMTAP_ABI_MAJOR, minor, patch),
|
||||||
|
"v0.{minor}.{patch} is not the verified minor and must be refused"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_patch_floor_is_currently_vacuous_and_that_is_deliberate() {
|
||||||
|
// With MIN_MINOR_PATCH.0 == DRMTAP_ABI_MINOR the floor can never reject anything: the
|
||||||
|
// minor equality already forces `(minor, patch) >= (minor, 0)`. It is kept because it is
|
||||||
|
// the mechanism that WOULD do the work the next time a floor lands mid-minor, as (4, 10)
|
||||||
|
// did for the split API. This test exists so nobody reads the pre-split test above as
|
||||||
|
// evidence that the floor is live -- if that ever matters, this assert is the tripwire.
|
||||||
|
let (floor_minor, floor_patch) = DRMTAP_MIN_MINOR_PATCH;
|
||||||
|
assert_eq!(
|
||||||
|
floor_minor, DRMTAP_ABI_MINOR,
|
||||||
|
"the floor is inside the verified minor; a floor in a DIFFERENT minor is unreachable"
|
||||||
|
);
|
||||||
|
if floor_patch == 0 {
|
||||||
|
assert!(
|
||||||
|
abi_accepted(DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, 0),
|
||||||
|
"patch 0 of the verified minor must be accepted while the floor is 0"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
assert!(!abi_accepted(DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, floor_patch - 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn abi_gate_accepts_the_floor_and_later_patches_of_the_same_minor() {
|
fn abi_gate_accepts_the_floor_and_later_patches_of_the_same_minor() {
|
||||||
let (min_minor, min_patch) = DRMTAP_MIN_MINOR_PATCH;
|
let (min_minor, min_patch) = DRMTAP_MIN_MINOR_PATCH;
|
||||||
@@ -493,4 +437,10 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn abi_gate_rejects_another_major_in_both_directions() {
|
||||||
|
assert!(!abi_accepted(DRMTAP_ABI_MAJOR + 1, 0, 0));
|
||||||
|
assert!(!abi_accepted(DRMTAP_ABI_MAJOR + 1, 99, 99));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -176,3 +176,38 @@ impl Drop for CapturerGDI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::super::*;
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn test() {
|
||||||
|
match Displays::new().unwrap().next() {
|
||||||
|
Some(d) => {
|
||||||
|
let w = d.width();
|
||||||
|
let h = d.height();
|
||||||
|
let c = CapturerGDI::new(d.name(), w, h).unwrap();
|
||||||
|
let mut data = Vec::new();
|
||||||
|
c.frame(&mut data).unwrap();
|
||||||
|
let mut bitflipped = Vec::with_capacity((w * h * 4) as usize);
|
||||||
|
for y in 0..h {
|
||||||
|
for x in 0..w {
|
||||||
|
let i = (w * 4 * y + 4 * x) as usize;
|
||||||
|
bitflipped.extend_from_slice(&[data[i + 2], data[i + 1], data[i], 255]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repng::encode(
|
||||||
|
std::fs::File::create("gdi_screen.png").unwrap(),
|
||||||
|
d.width() as u32,
|
||||||
|
d.height() as u32,
|
||||||
|
&bitflipped,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
assert!(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -692,3 +692,17 @@ impl CapturerMag {
|
|||||||
TRUE
|
TRUE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn test() {
|
||||||
|
let mut capture_mag = CapturerMag::new((0, 0), 1920, 1080).unwrap();
|
||||||
|
capture_mag.exclude("", "RustDeskPrivacyWindow").unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(1000 * 10));
|
||||||
|
let mut data = Vec::new();
|
||||||
|
capture_mag.frame(&mut data).unwrap();
|
||||||
|
println!("capture data len: {}", data.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ const COMMAND_TIMEOUT: Duration = Duration::from_millis(1000);
|
|||||||
|
|
||||||
// drm builds only: an unnamed-endpoint failure there forks the probe child, and the pollers
|
// drm builds only: an unnamed-endpoint failure there forks the probe child, and the pollers
|
||||||
// turn every few hundred milliseconds. Every other failure is one cheap in-process error.
|
// turn every few hundred milliseconds. Every other failure is one cheap in-process error.
|
||||||
#[cfg(feature = "drm")]
|
#[cfg(any(test, feature = "drm"))]
|
||||||
const FAILED_LOOKUP_BACKOFF: Duration = Duration::from_secs(5);
|
const FAILED_LOOKUP_BACKOFF: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
#[cfg(feature = "drm")]
|
#[cfg(any(test, feature = "drm"))]
|
||||||
static LAST_FAILED_LOOKUP: Mutex<Option<Instant>> = Mutex::new(None);
|
static LAST_FAILED_LOOKUP: Mutex<Option<Instant>> = Mutex::new(None);
|
||||||
|
|
||||||
#[cfg(feature = "drm")]
|
#[cfg(feature = "drm")]
|
||||||
@@ -183,7 +183,8 @@ fn get_primary_monitor() -> Option<String> {
|
|||||||
.or_else(try_gdbus_primary)
|
.or_else(try_gdbus_primary)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "drm")]
|
// Pure, so the backoff policy is testable without a compositor.
|
||||||
|
#[cfg(any(test, feature = "drm"))]
|
||||||
fn lookup_allowed(failed_at: Option<Instant>, now: Instant) -> bool {
|
fn lookup_allowed(failed_at: Option<Instant>, now: Instant) -> bool {
|
||||||
failed_at.map_or(true, |at| {
|
failed_at.map_or(true, |at| {
|
||||||
now.saturating_duration_since(at) >= FAILED_LOOKUP_BACKOFF
|
now.saturating_duration_since(at) >= FAILED_LOOKUP_BACKOFF
|
||||||
@@ -301,7 +302,6 @@ pub fn clear_wayland_displays_cache() {
|
|||||||
// every OTHER live capturer on a multi-display session. A capturer records this at build and
|
// every OTHER live capturer on a multi-display session. A capturer records this at build and
|
||||||
// treats a later bump as "the layout changed under me, rebuild" — the only trigger a rotation
|
// treats a later bump as "the layout changed under me, rebuild" — the only trigger a rotation
|
||||||
// has, since it changes neither the CRTC mode nor the framebuffer size (rustdesk#15886).
|
// has, since it changes neither the CRTC mode nor the framebuffer size (rustdesk#15886).
|
||||||
#[cfg(feature = "drm")]
|
|
||||||
static SNAPSHOT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
static SNAPSHOT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
|
||||||
/// Whether no snapshot has been cached: the signature of an enumeration that failed at session
|
/// Whether no snapshot has been cached: the signature of an enumeration that failed at session
|
||||||
@@ -311,7 +311,7 @@ pub fn wayland_snapshot_missing() -> bool {
|
|||||||
DISPLAYS.lock().unwrap().is_none()
|
DISPLAYS.lock().unwrap().is_none()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "drm")]
|
#[cfg(any(test, feature = "drm"))]
|
||||||
pub fn bump_layout_generation() {
|
pub fn bump_layout_generation() {
|
||||||
SNAPSHOT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Release);
|
SNAPSHOT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Release);
|
||||||
}
|
}
|
||||||
@@ -516,6 +516,40 @@ fn map_axis(v: i32, base_origin: i32, base_extent: i32, live_origin: i32, live_e
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_lookup_backoff_boundaries() {
|
||||||
|
// Future `now`s sidestep Instant subtraction, which can panic near boot.
|
||||||
|
let failed_at = Instant::now();
|
||||||
|
assert!(lookup_allowed(None, failed_at));
|
||||||
|
assert!(!lookup_allowed(
|
||||||
|
Some(failed_at),
|
||||||
|
failed_at + FAILED_LOOKUP_BACKOFF / 2
|
||||||
|
));
|
||||||
|
assert!(lookup_allowed(
|
||||||
|
Some(failed_at),
|
||||||
|
failed_at + FAILED_LOOKUP_BACKOFF
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_lookup_stamp_from_the_future_only_waits() {
|
||||||
|
// saturating_duration_since answers zero rather than underflowing.
|
||||||
|
let now = Instant::now();
|
||||||
|
assert!(!lookup_allowed(Some(now + FAILED_LOOKUP_BACKOFF), now));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_clear_keeps_the_failure_stamp() {
|
||||||
|
// The stamp describes the seat, not the cache: the ~1/s capturer rebuild loop clears,
|
||||||
|
// and dropping the stamp with it would defeat the backoff. The generation test also
|
||||||
|
// calls clear now; both only assert monotonic/unchanged state, so they can interleave.
|
||||||
|
*LAST_FAILED_LOOKUP.lock().unwrap() = Some(Instant::now());
|
||||||
|
clear_wayland_displays_cache();
|
||||||
|
let stamp = *LAST_FAILED_LOOKUP.lock().unwrap();
|
||||||
|
assert!(stamp.is_some());
|
||||||
|
*LAST_FAILED_LOOKUP.lock().unwrap() = None;
|
||||||
|
}
|
||||||
|
|
||||||
fn display(
|
fn display(
|
||||||
x: i32,
|
x: i32,
|
||||||
y: i32,
|
y: i32,
|
||||||
@@ -535,6 +569,11 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_desktop_rect_empty() {
|
||||||
|
assert_eq!(desktop_rect_of(&[]), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_desktop_rect_single_display_uses_physical_size() {
|
fn test_desktop_rect_single_display_uses_physical_size() {
|
||||||
let displays = [display(0, 0, 2880, 1800, Some((1859, 1162)))];
|
let displays = [display(0, 0, 2880, 1800, Some((1859, 1162)))];
|
||||||
@@ -552,6 +591,15 @@ mod tests {
|
|||||||
assert_eq!(desktop_rect_of(&displays), Some((0, 3779, 0, 2160)));
|
assert_eq!(desktop_rect_of(&displays), Some((0, 3779, 0, 2160)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_desktop_rect_missing_logical_size_falls_back_to_physical() {
|
||||||
|
let displays = [
|
||||||
|
display(0, 0, 2560, 1440, None),
|
||||||
|
display(2560, 0, 2560, 1440, Some((2560, 1440))),
|
||||||
|
];
|
||||||
|
assert_eq!(desktop_rect_of(&displays), Some((0, 5120, 0, 1440)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_single_rotated_display_swaps_the_uinput_rect() {
|
fn a_single_rotated_display_swaps_the_uinput_rect() {
|
||||||
// Review finding 1 on rustdesk#15889: the single-display branch served the unrotated
|
// Review finding 1 on rustdesk#15889: the single-display branch served the unrotated
|
||||||
@@ -563,6 +611,31 @@ mod tests {
|
|||||||
assert_eq!((rects[0].w, rects[0].h), (1080, 1920));
|
assert_eq!((rects[0].w, rects[0].h), (1080, 1920));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_transform_flip_is_visible_to_the_drift_comparison() {
|
||||||
|
// Review finding 5: 0<->180 and 90<->270 leave every rect identical; the transform
|
||||||
|
// field is what lets `baseline != live` fire on them.
|
||||||
|
let mut a = display(0, 0, 1920, 1080, Some((1920, 1080)));
|
||||||
|
let mut b = a.clone();
|
||||||
|
a.transform = 90;
|
||||||
|
b.transform = 270;
|
||||||
|
assert_ne!(logical_rects_of(&[a.clone(), a.clone()]), logical_rects_of(&[b.clone(), b]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_explicit_bump_moves_the_generation() {
|
||||||
|
// A cache clear must NOT bump: session inits clear too, and a bump there rebuilds
|
||||||
|
// every other live capturer (adversarial finding on the first version of this).
|
||||||
|
let before = SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire);
|
||||||
|
clear_wayland_displays_cache();
|
||||||
|
assert_eq!(
|
||||||
|
SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire),
|
||||||
|
before
|
||||||
|
);
|
||||||
|
bump_layout_generation();
|
||||||
|
assert!(SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire) > before);
|
||||||
|
}
|
||||||
|
|
||||||
fn rect(name: &str, x: i32, y: i32, w: i32, h: i32) -> DisplayRect {
|
fn rect(name: &str, x: i32, y: i32, w: i32, h: i32) -> DisplayRect {
|
||||||
DisplayRect {
|
DisplayRect {
|
||||||
name: name.to_owned(),
|
name: name.to_owned(),
|
||||||
@@ -598,6 +671,16 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A point on the rescaled display itself is squeezed to its new logical width.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_scales_within_resized_display() {
|
||||||
|
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
|
||||||
|
let live = [rect("DP-1", 0, 0, 2048, 1440), rect("DP-2", 2048, 0, 2560, 1440)];
|
||||||
|
// x=1280 across the 2560-wide baseline DP-1 -> proportionally across the 2048-wide
|
||||||
|
// live DP-1 (endpoint-preserving scale, so ~1px off the naive midpoint).
|
||||||
|
assert_eq!(remap_to_live_layout(1280, 500, &baseline, &live), (1023, 500));
|
||||||
|
}
|
||||||
|
|
||||||
// The far edge of the followed display stays reachable when it is enlarged, so hot
|
// The far edge of the followed display stays reachable when it is enlarged, so hot
|
||||||
// corners keep working. Baseline DP-1 is 2048 wide, live DP-1 is 2560 wide; the
|
// corners keep working. Baseline DP-1 is 2048 wide, live DP-1 is 2560 wide; the
|
||||||
// client's last column (2047) must map to the live last column (2559), not 2558.
|
// client's last column (2047) must map to the live last column (2559), not 2558.
|
||||||
@@ -609,6 +692,57 @@ mod tests {
|
|||||||
assert_eq!(remap_to_live_layout(0, 0, &baseline, &live), (0, 0));
|
assert_eq!(remap_to_live_layout(0, 0, &baseline, &live), (0, 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// No drift: identical layouts map every point to itself.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_identity_when_unchanged() {
|
||||||
|
let layout = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
|
||||||
|
assert_eq!(remap_to_live_layout(3000, 700, &layout, &layout), (3000, 700));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Point outside every baseline display is left untouched.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_point_outside_all_displays_unchanged() {
|
||||||
|
let baseline = [rect("DP-1", 0, 0, 2560, 1440)];
|
||||||
|
let live = [rect("DP-1", 0, 0, 2048, 1440)];
|
||||||
|
assert_eq!(remap_to_live_layout(9000, 9000, &baseline, &live), (9000, 9000));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matched display gone from the live layout (e.g. unplugged): leave the point be
|
||||||
|
// rather than mapping it somewhere wrong.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_display_removed_unchanged() {
|
||||||
|
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
|
||||||
|
let live = [rect("DP-1", 0, 0, 2560, 1440)];
|
||||||
|
assert_eq!(remap_to_live_layout(2600, 100, &baseline, &live), (2600, 100));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nameless compositor: fall back to index matching while the count is unchanged.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_nameless_index_fallback() {
|
||||||
|
let baseline = [rect("", 0, 0, 2560, 1440), rect("", 2560, 0, 2560, 1440)];
|
||||||
|
let live = [rect("", 0, 0, 2048, 1440), rect("", 2048, 0, 2560, 1440)];
|
||||||
|
assert_eq!(remap_to_live_layout(2560, 0, &baseline, &live), (2048, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nameless compositor with a changed count: cannot index-match safely, so no-op.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_nameless_count_changed_unchanged() {
|
||||||
|
let baseline = [rect("", 0, 0, 2560, 1440), rect("", 2560, 0, 2560, 1440)];
|
||||||
|
let live = [rect("", 0, 0, 2048, 1440)];
|
||||||
|
assert_eq!(remap_to_live_layout(2560, 0, &baseline, &live), (2560, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A named display absent from the live layout, but the count is unchanged (e.g. a
|
||||||
|
// monitor was swapped for a different one at the same index): the index fallback is
|
||||||
|
// for nameless layouts only, so a named miss stays unchanged rather than mapping to
|
||||||
|
// whatever now occupies that index.
|
||||||
|
#[test]
|
||||||
|
fn test_remap_named_miss_equal_count_unchanged() {
|
||||||
|
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
|
||||||
|
let live = [rect("DP-1", 0, 0, 2048, 1440), rect("HDMI-1", 2048, 0, 1920, 1080)];
|
||||||
|
assert_eq!(remap_to_live_layout(2600, 100, &baseline, &live), (2600, 100));
|
||||||
|
}
|
||||||
|
|
||||||
// A single display uses physical size in both baseline and live (scale reported as
|
// A single display uses physical size in both baseline and live (scale reported as
|
||||||
// 1.0), so it never drifts and the remap is a no-op even across a rescale.
|
// 1.0), so it never drifts and the remap is a no-op even across a rescale.
|
||||||
#[test]
|
#[test]
|
||||||
@@ -619,4 +753,17 @@ mod tests {
|
|||||||
vec![rect("", 0, 0, 2560, 1440)]
|
vec![rect("", 0, 0, 2560, 1440)]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Multiple displays use logical size, falling back to physical when absent.
|
||||||
|
#[test]
|
||||||
|
fn test_logical_rects_multi_display_uses_logical() {
|
||||||
|
let displays = [
|
||||||
|
display(0, 0, 2560, 1440, Some((2048, 1152))),
|
||||||
|
display(2048, 0, 1920, 1080, None),
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
logical_rects_of(&displays),
|
||||||
|
vec![rect("", 0, 0, 2048, 1152), rect("", 2048, 0, 1920, 1080)]
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use gstreamer_app::AppSink;
|
|||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use base::platform::linux::{WaylandDisplayInfo, CMD_SH};
|
use base::platform::linux::CMD_SH;
|
||||||
use hbb_common::{anyhow::anyhow, bail, config, serde_json, tokio, ResultType};
|
use hbb_common::{anyhow::anyhow, bail, config, serde_json, tokio, ResultType};
|
||||||
|
|
||||||
use super::capturable::PixelProvider;
|
use super::capturable::PixelProvider;
|
||||||
@@ -77,9 +77,7 @@ pub fn close_session() {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn is_rdp_session_hold() -> bool {
|
pub fn is_rdp_session_hold() -> bool {
|
||||||
// try_lock: a request waiting for the user holds the slot (no session yet), and so do the short
|
RDP_SESSION_INFO.lock().unwrap().is_some()
|
||||||
// looks while a session is set up. Busy answers no session rather than wait.
|
|
||||||
matches!(RDP_SESSION_INFO.try_lock(), Ok(info) if info.is_some())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn try_close_session() {
|
pub fn try_close_session() {
|
||||||
@@ -159,9 +157,6 @@ pub struct PipeWireCapturable {
|
|||||||
pub position: (i32, i32),
|
pub position: (i32, i32),
|
||||||
pub logical_size: (usize, usize),
|
pub logical_size: (usize, usize),
|
||||||
pub physical_size: (usize, usize),
|
pub physical_size: (usize, usize),
|
||||||
// False when `physical_size` is the portal size standing in for a resolution get_res() could
|
|
||||||
// not read.
|
|
||||||
physical_size_measured: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PipeWireCapturable {
|
impl PipeWireCapturable {
|
||||||
@@ -173,7 +168,7 @@ impl PipeWireCapturable {
|
|||||||
) -> Self {
|
) -> Self {
|
||||||
// alternative to get screen resolution as stream.size is not always correct ex: on fractional scaling
|
// alternative to get screen resolution as stream.size is not always correct ex: on fractional scaling
|
||||||
// https://github.com/rustdesk/rustdesk/issues/6116#issuecomment-1817724244
|
// https://github.com/rustdesk/rustdesk/issues/6116#issuecomment-1817724244
|
||||||
let measured = get_res(Self {
|
let physical_size = get_res(Self {
|
||||||
dbus_conn: conn.clone(),
|
dbus_conn: conn.clone(),
|
||||||
fd: fd.clone(),
|
fd: fd.clone(),
|
||||||
path: stream.path,
|
path: stream.path,
|
||||||
@@ -182,10 +177,8 @@ impl PipeWireCapturable {
|
|||||||
position: stream.position,
|
position: stream.position,
|
||||||
logical_size: stream.size,
|
logical_size: stream.size,
|
||||||
physical_size: (0, 0),
|
physical_size: (0, 0),
|
||||||
physical_size_measured: false,
|
})
|
||||||
});
|
.unwrap_or(stream.size);
|
||||||
let physical_size_measured = measured.is_ok();
|
|
||||||
let physical_size = measured.unwrap_or(stream.size);
|
|
||||||
*resolution.lock().unwrap() = Some(physical_size);
|
*resolution.lock().unwrap() = Some(physical_size);
|
||||||
Self {
|
Self {
|
||||||
dbus_conn: conn,
|
dbus_conn: conn,
|
||||||
@@ -196,7 +189,6 @@ impl PipeWireCapturable {
|
|||||||
position: stream.position,
|
position: stream.position,
|
||||||
logical_size: stream.size,
|
logical_size: stream.size,
|
||||||
physical_size,
|
physical_size,
|
||||||
physical_size_measured,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -285,8 +277,6 @@ fn gst_element(name: &str) -> ResultType<gst::Element> {
|
|||||||
impl PipeWireRecorder {
|
impl PipeWireRecorder {
|
||||||
pub fn new(capturable: PipeWireCapturable) -> ResultType<Self> {
|
pub fn new(capturable: PipeWireCapturable) -> ResultType<Self> {
|
||||||
let pipeline = gst::Pipeline::new(None);
|
let pipeline = gst::Pipeline::new(None);
|
||||||
// Clock waits on stale capture timestamps can exhaust the compositor's buffers.
|
|
||||||
pipeline.use_clock(None::<&gst::Clock>);
|
|
||||||
|
|
||||||
let src = gst_element("pipewiresrc")?;
|
let src = gst_element("pipewiresrc")?;
|
||||||
src.set_property("fd", &capturable.fd.as_raw_fd())?;
|
src.set_property("fd", &capturable.fd.as_raw_fd())?;
|
||||||
@@ -1299,26 +1289,6 @@ pub fn fill_displays(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if all_displays.displays.len() > 1 {
|
if all_displays.displays.len() > 1 {
|
||||||
for (i, sd) in shared_displays.iter_mut().enumerate() {
|
|
||||||
if let crate::Display::WAYLAND(d) = sd {
|
|
||||||
let capturable = &mut d.0;
|
|
||||||
if let Some(origin) = reconciled_origin(
|
|
||||||
capturable.position,
|
|
||||||
capturable.physical_size,
|
|
||||||
capturable.physical_size_measured,
|
|
||||||
&all_displays.displays,
|
|
||||||
) {
|
|
||||||
warn!(
|
|
||||||
"Position {:?} names no output of size {:?}, using {:?}.",
|
|
||||||
capturable.position, capturable.physical_size, origin
|
|
||||||
);
|
|
||||||
capturable.position = origin;
|
|
||||||
if let Some(pw_stream) = rdp_info.streams.get_mut(i) {
|
|
||||||
pw_stream.position = origin;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort_streams(&all_displays, shared_displays, &mut rdp_info.streams);
|
sort_streams(&all_displays, shared_displays, &mut rdp_info.streams);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1331,50 +1301,6 @@ pub fn fill_displays(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// The origin a stream takes when its position names no output of its size. Only a measured size
|
|
||||||
// moves a position: when get_res() failed, the size is the portal size, which can be the mode of
|
|
||||||
// another output and says less than the position does, whether the portal sent that position or
|
|
||||||
// try_fill_positions restored it from its cache.
|
|
||||||
fn reconciled_origin(
|
|
||||||
position: (i32, i32),
|
|
||||||
size: (usize, usize),
|
|
||||||
size_measured: bool,
|
|
||||||
outputs: &[WaylandDisplayInfo],
|
|
||||||
) -> Option<(i32, i32)> {
|
|
||||||
if !size_measured {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
corrected_origin(position, size, outputs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The origin for a stream whose position names no output of the stream's size (a rotated output
|
|
||||||
// counts in either orientation), when exactly one output has that size. xdg-desktop-portal-hyprland reports every stream at (0, 0):
|
|
||||||
// with no output there `sort_streams` dropped the stream, and with another output there the
|
|
||||||
// stream took its origin and missed `try_fix_logical_size`, so the pointer landed on the wrong
|
|
||||||
// output (#15731). With several outputs of that size the position is kept.
|
|
||||||
fn corrected_origin(
|
|
||||||
position: (i32, i32),
|
|
||||||
size: (usize, usize),
|
|
||||||
outputs: &[WaylandDisplayInfo],
|
|
||||||
) -> Option<(i32, i32)> {
|
|
||||||
let has_size = |o: &&WaylandDisplayInfo| {
|
|
||||||
let mode = (o.width as usize, o.height as usize);
|
|
||||||
mode == size || (o.transform % 180 != 0 && (mode.1, mode.0) == size)
|
|
||||||
};
|
|
||||||
if outputs
|
|
||||||
.iter()
|
|
||||||
.filter(has_size)
|
|
||||||
.any(|o| (o.x, o.y) == position)
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let mut same_size = outputs.iter().filter(has_size);
|
|
||||||
match (same_size.next(), same_size.next()) {
|
|
||||||
(Some(o), None) => Some((o.x, o.y)),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_fill_positions(
|
fn try_fill_positions(
|
||||||
mouse_move_to: impl Fn(i32, i32),
|
mouse_move_to: impl Fn(i32, i32),
|
||||||
get_cursor_pos: fn() -> Option<(i32, i32)>,
|
get_cursor_pos: fn() -> Option<(i32, i32)>,
|
||||||
@@ -1677,7 +1603,6 @@ fn fill_multi_matched_positions_cursor(
|
|||||||
position: pw_stream_with_cursor.position,
|
position: pw_stream_with_cursor.position,
|
||||||
logical_size: pw_stream_with_cursor.size,
|
logical_size: pw_stream_with_cursor.size,
|
||||||
physical_size: (0, 0),
|
physical_size: (0, 0),
|
||||||
physical_size_measured: false,
|
|
||||||
})?;
|
})?;
|
||||||
// Take first frame and copy owned buffer to avoid borrow across second capture
|
// Take first frame and copy owned buffer to avoid borrow across second capture
|
||||||
let (is_bgr, w, first_buf): (bool, usize, Vec<u8>) =
|
let (is_bgr, w, first_buf): (bool, usize, Vec<u8>) =
|
||||||
@@ -1804,69 +1729,26 @@ fn sort_streams(
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{corrected_origin, WaylandDisplayInfo};
|
use super::stage_err;
|
||||||
|
|
||||||
fn output(x: i32, y: i32, mode: (i32, i32)) -> WaylandDisplayInfo {
|
|
||||||
WaylandDisplayInfo {
|
|
||||||
name: String::new(),
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
width: mode.0,
|
|
||||||
height: mode.1,
|
|
||||||
logical_size: None,
|
|
||||||
refresh_rate: 60,
|
|
||||||
transform: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_portal_position_naming_no_output_of_its_size_moves_to_the_only_one() {
|
fn stage_err_keeps_the_detail_safe_for_a_placeholder() {
|
||||||
// 1920x1080 at the origin, 2880x1800 to its right: xdph puts the right one at (0, 0).
|
|
||||||
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
corrected_origin((0, 0), (2880, 1800), &pair),
|
stage_err("start", "declined", ""),
|
||||||
Some((1920, 0))
|
"wl-stage:start:declined:"
|
||||||
);
|
);
|
||||||
// A real origin is kept.
|
// Braces of its own would break the placeholder lookup on the peer.
|
||||||
assert_eq!(corrected_origin((1920, 0), (2880, 1800), &pair), None);
|
|
||||||
// Nothing starts at the origin (the hyprland layout in #15731).
|
|
||||||
let three = [
|
|
||||||
output(0, 120, (1920, 1200)),
|
|
||||||
output(1920, 0, (3440, 1440)),
|
|
||||||
output(5360, 180, (1920, 1080)),
|
|
||||||
];
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
corrected_origin((0, 0), (3440, 1440), &three),
|
stage_err("create-session", "dbus", "org.freedesktop.{Error}"),
|
||||||
Some((1920, 0))
|
"wl-stage:create-session:dbus:org.freedesktop.Error"
|
||||||
);
|
);
|
||||||
// Two outputs of that size cannot be told apart: the position is kept.
|
|
||||||
let twins = [
|
|
||||||
output(0, 0, (2560, 1600)),
|
|
||||||
output(2560, 0, (1920, 1080)),
|
|
||||||
output(4480, 0, (1920, 1080)),
|
|
||||||
];
|
|
||||||
assert_eq!(corrected_origin((0, 0), (1920, 1080), &twins), None);
|
|
||||||
// A portrait panel turned to landscape keeps its position next to a 1920x1080 output.
|
|
||||||
let turned = [
|
|
||||||
WaylandDisplayInfo {
|
|
||||||
transform: 90,
|
|
||||||
..output(0, 0, (1080, 1920))
|
|
||||||
},
|
|
||||||
output(1920, 0, (1920, 1080)),
|
|
||||||
];
|
|
||||||
assert_eq!(corrected_origin((0, 0), (1920, 1080), &turned), None);
|
|
||||||
// A rotated output that try_fill_positions could not match by its mode is found in its
|
|
||||||
// delivered orientation.
|
|
||||||
let turned_right = [
|
|
||||||
output(0, 0, (2560, 1440)),
|
|
||||||
WaylandDisplayInfo {
|
|
||||||
transform: 90,
|
|
||||||
..output(2560, 0, (1080, 1920))
|
|
||||||
},
|
|
||||||
];
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
corrected_origin((0, 0), (1920, 1080), &turned_right),
|
stage_err("select-sources", "internal", "one\ntwo"),
|
||||||
Some((2560, 0))
|
"wl-stage:select-sources:internal:one two"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
stage_err("start", "internal", &"x".repeat(300)),
|
||||||
|
format!("wl-stage:start:internal:{}", "x".repeat(200))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
pkgname=rustdesk
|
pkgname=rustdesk
|
||||||
pkgver=1.5.1
|
pkgver=1.5.0
|
||||||
pkgrel=0
|
pkgrel=0
|
||||||
epoch=
|
epoch=
|
||||||
pkgdesc=""
|
pkgdesc=""
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user