Compare commits

..
Author SHA1 Message Date
fufesou f487aaed99 Preserve thin cursor proportions at the visibility minimum 2026-09-14 13:54:04 +08:00
fufesou 70e345a76d Fix Wayland cursor density in physical desktop layouts 2026-09-14 12:32:16 +08:00
fufesou 6a62b7bbd9 Fix cursor alignment when a scrollbar axis stops overflowing 2026-09-14 11:18:03 +08:00
fufesou 74c818bef9 Validate cursor source metadata before UI dispatch 2026-09-14 10:50:08 +08:00
fufesou 8f499c2eb5 Keep browser cursor validation coverage in the existing Web fixture 2026-09-14 10:43:05 +08:00
fufesou 2d5d11282b Trim redundant cursor density and alpha test combinations 2026-09-14 10:40:32 +08:00
fufesou f6c89aa06c Validate and decode cursor packets at the Rust receive boundary 2026-09-14 10:00:54 +08:00
fufesou c142cba450 Declare existing Zstd dependency for bounded cursor decoding 2026-09-14 09:52:05 +08:00
fufesou ee8c843bc4 Validate raw cursor geometry and RGBA length before decoding 2026-09-14 09:37:40 +08:00
fufesou 2cfbbd56b4 Update cursor plugin to preserve sparse artwork when downscaling 2026-09-14 08:53:07 +08:00
fufesou e7f307bb80 test: remove import superseded by shared cursor fixtures 2026-09-14 08:41:09 +08:00
fufesou a0f24abe80 docs: shorten cursor scaling comments 2026-09-14 08:39:06 +08:00
fufesou 6137be5414 test: reuse native cursor registration recorder 2026-09-14 08:38:39 +08:00
fufesou e76b7e7bc2 test: share cursor painting recorders 2026-09-14 08:37:57 +08:00
fufesou 1982bb3abd test: reuse cursor fixtures for Web and alpha coverage 2026-09-14 08:36:46 +08:00
fufesou 8cf138e2cc test: share cursor density policy fixtures 2026-09-14 08:32:09 +08:00
fufesou 19040f3eef fix: preserve unzoomed cursor size for hosts without density 2026-09-14 00:00:25 +08:00
fufesou c02f17212a Reject unusable cursor density and oversized raster requests 2026-09-13 23:17:40 +08:00
fufesou fbfa37c8fd Preserve legacy macOS cursor dimensions with optional Retina artwork 2026-09-13 23:17:21 +08:00
fufesou 819535f1db Bump cursor plugin to preserve same-name recreation 2026-09-13 18:18:36 +08:00
fufesou 110ddb9a6c Report Linux cursor density independently of the host UI 2026-09-13 17:48:03 +08:00
fufesou 9a1c1a1a36 Preserve DRM cursor density during display cache contention 2026-09-13 17:25:11 +08:00
fufesou 3629db2aa0 Keep one macOS cursor density snapshot and retry failed captures 2026-09-13 17:15:28 +08:00
fufesou 8869a440da fix(cursor): comments
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-13 16:52:29 +08:00
fufesou 777407e72e Bump cursor plugin to invalidate activation after pointer removal 2026-09-13 16:45:28 +08:00
fufesou 20ede1a85f Activate native cursors after successful registration retries 2026-09-13 15:52:24 +08:00
fufesou a87d9c1082 Use key-stable native cursor sessions during local movement 2026-09-13 15:05:31 +08:00
fufesou bb06f54070 Keep rounded Retina cursor hotspots inside the bitmap 2026-09-13 15:01:18 +08:00
fufesou 16088cfc80 Synchronize custom-scrollbar cursor geometry after relayout 2026-09-13 14:53:47 +08:00
fufesou b630f14483 Synchronize edge-scroll cursor geometry after relayout
Refresh edge-scroll fractions from laid-out scroll positions and repaint when
they differ from the values used by the frame. Preserve the repaint when a
deferred settings refresh has already changed the model.

Cover DPR changes, viewport clamping, detached scroll axes and restoration
with the actual video and cursor widgets in Original and Custom modes.

Verified 87 native Flutter cursor tests on each of macOS and Linux, plus
17 Chrome Web cursor tests.
2026-09-13 13:27:46 +08:00
fufesou d2d7c83602 Keep edge-scroll fractions valid after clamped jumps 2026-09-13 12:04:05 +08:00
fufesou d2561f7f6b Align remote cursor overlays with edge-scrolled video 2026-09-13 11:04:55 +08:00
fufesou 70c50402a2 Keep resized Web cursors within a proportional minimum 2026-09-13 10:58:34 +08:00
fufesou bbc8ee3bdb Align painted cursors with Linux texture origins
Use the truncated Linux texture origin while preserving fractional cursor positions and hotspots. Compare painted cursor geometry with the actual video widget in the existing regression tests.
2026-09-13 10:04:12 +08:00
fufesou 32e9895294 Fix predefined cursor density and scrollbar centering 2026-09-13 00:18:06 +08:00
fufesou feff308f11 test: reduce duplicate cursor fixtures and geometry checks 2026-09-12 23:32:26 +08:00
fufesou 5a89aa8c58 Resolve DRM cursor density from the complete display mapping 2026-09-12 23:02:12 +08:00
fufesou 6e2d838bf1 Keep density-aware cursor IDs compatible with legacy Web clients 2026-09-12 22:56:13 +08:00
fufesou 1fabdd6a9c Preserve Windows cursor alpha during native image decoding 2026-09-12 22:52:36 +08:00
fufesou afdd1d5c9d Preserve the macOS cursor wire alpha format for older controllers 2026-09-12 21:47:08 +08:00
fufesou 371e5e8f2d Fix native cursor display selection during local movement 2026-09-12 21:46:28 +08:00
fufesou 4d064a8445 docs(cursor): explain outline alignment and Linux density scope 2026-09-12 20:51:59 +08:00
fufesou 02e4f02815 docs(cursor): explain image decoding and Retina sampling 2026-09-12 20:51:58 +08:00
fufesou bbf86259e9 fix(cursor): encode macOS cursor alpha correctly in Sciter 2026-09-12 20:10:57 +08:00
fufesou 8dfff101f8 fix(cursor): align painted and native minimum sizes 2026-09-12 20:01:26 +08:00
fufesou 6934b3cb14 fix(cursor): follow Linux video pixel scale 2026-09-12 19:56:55 +08:00
fufesou 8f3beba2d1 fix(cursor): decode legacy macOS alpha for native cursors 2026-09-12 18:40:27 +08:00
fufesou be1f4e0a33 fix(cursor): isolate optional X11 density failures 2026-09-12 18:30:27 +08:00
fufesou cb068ba5df fix(cursor): decode predefined PNG images with correct alpha
Use Flutter's PNG codec before native rasterization and retain the straight-alpha image cache. Cover both bundled assets through PNG and Windows BGRA registration.
2026-09-12 17:46:57 +08:00
fufesou 1d98d1a647 fix(cursor): keep DRM density lookup off the polling path
Read optional Wayland metadata from the cache without starting discovery or waiting on a refresh. Keep delivering cursor shapes with unknown density when metadata is unavailable, and cover lock contention and repeated empty-cache reads.
2026-09-12 16:56:48 +08:00
fufesou 944f93ba7b fix(cursor): use plugin with nonzero raster dimensions 2026-09-12 15:54:38 +08:00
fufesou aea8e2a4a6 fix(cursor): preserve macOS alpha through Web decode and resize 2026-09-12 15:51:22 +08:00
fufesou d65faca21f fix(cursor): preserve unzoomed Web size across browser DPRs 2026-09-12 15:42:47 +08:00
fufesou 85e7c72ccd test(cursor): clarify scale constraints and isolate DPR checks 2026-09-12 14:32:15 +08:00
fufesou a3bfe075d5 test(cursor): reuse painting and web fixtures 2026-09-12 14:28:41 +08:00
fufesou 7e2e9b68da test(cursor): consolidate native DPI and bridge coverage 2026-09-12 14:26:00 +08:00
fufesou 6871ae130e docs(cursor): clarify optional capture metadata and rendering scope 2026-09-12 10:46:05 +08:00
fufesou 54881092b7 refactor(cursor): separate native capture from rendering fixes 2026-09-12 10:40:23 +08:00
fufesou 34ceb16b63 fix(cursor): align the remote cursor with scrollbar offsets 2026-09-12 06:57:15 +08:00
fufesou d95c3f2ec9 fix(cursor): preserve full cursor IDs in Web clients 2026-09-12 03:43:32 +08:00
fufesou daafa09318 fix(cursor): keep the Windows minimum in logical pixels 2026-09-12 03:33:38 +08:00
fufesou 96cd5cd1e2 fix(cursor): align Web hotspots with rounded cursor images 2026-09-12 03:29:27 +08:00
fufesou d876ea0ce4 fix(cursor): report X11 and Wayland cursor density 2026-09-12 03:27:53 +08:00
fufesou 2a61a0955a fix(cursor): capture the physical Windows cursor across DPI changes 2026-09-12 03:26:52 +08:00
fufesou db7c48e1a7 fix(cursor): normalize native cursor density in scaled views 2026-09-12 02:57:37 +08:00
fufesou e72e7fb8ba fix(cursor): capture complete macOS Retina cursor images 2026-09-12 02:47:37 +08:00
fufesou 4f0f784532 feat(cursor): carry the remote bitmap pixel density 2026-09-12 02:47:37 +08:00
fufesou 844bf40703 fix(cursor): align the painted cursor with the remote image 2026-09-12 02:24:31 +08:00
fufesou f8bfc4eb56 chore(cursor): pin plugin with legacy platform routing preserved 2026-09-12 02:06:41 +08:00
fufesou 1061670368 fix(cursor): delegate native image scaling to cursor plugin
Use the original Flutter image and source hotspot with explicit DPR, retaining the existing view and minimum-size policies. Pin the plugin implementation from rustdesk-org/flutter_custom_cursor#1.
2026-09-12 01:40:26 +08:00
fufesou 8da629c57d revert(cursor): return to f5b98b32 before splitting plugin changes 2026-09-12 00:32:58 +08:00
fufesou 650a6e21cc fix(web): preserve full precision in cursor identifiers 2026-09-12 00:20:47 +08:00
fufesou 5f4bb00007 fix(web): align cursor bitmap and hotspot rounding 2026-09-12 00:20:28 +08:00
fufesou a7f1eb4c25 fix(cursor): address sizing and capture review findings 2026-09-12 00:19:10 +08:00
fufesou be5fb304d4 fix(flutter): align painted cursor with the software image origin 2026-09-11 17:54:56 +08:00
fufesou fdd67a875b test(flutter): cover local cursor sizing and mode switches 2026-09-11 16:02:52 +08:00
fufesou 39940b717a fix(flutter): size unzoomed remote cursors to the local system 2026-09-11 16:02:52 +08:00
fufesou 67b94c7906 feat(windows): measure the native system cursor size 2026-09-11 16:02:52 +08:00
fufesou eeff9eb121 feat(linux): measure the active system cursor size 2026-09-11 16:02:52 +08:00
fufesou c983d00437 feat(macos): expose the local system cursor size 2026-09-11 16:02:52 +08:00
fufesou 7bb3fe6b5a fix(flutter): preserve cursor minimum sizes and native hotspots 2026-09-11 13:51:24 +08:00
fufesou d202a2fba4 fix(flutter): scale the remote cursor with its image 2026-09-11 13:51:24 +08:00
fufesou 72ea38ca4f fix(cursor): preserve native pixels and hotspots across display scales
Capture actual Mutter and DXGI cursor metadata, preserve Retina artwork, and invalidate cursor identities when physical pixels or DPI change. Keep straight-alpha colors during native cursor resizing and correct the Windows XOR outline offset.

Verified all six Mac/Linux/Windows directions with real pointer movement, arrow/I-beam/crosshair transitions, adaptive zoom off/on/off, Original view, and live DPI changes. Requested debug builds and focused native/Flutter regressions pass.
2026-09-11 11:49:04 +08:00
fufesou f96d00d9d1 fix(flutter): correct cursor scaling and Linux cursor clipping
Keep Linux/macOS bitmap sizing and painted cursor DPI
conversion consistent, and derive hotspots from the actual scaled bitmap.

Pad tall Linux native cursor buffers with transparency to
preserve the lower half in the hardware cursor plane.
Cover bitmap sizing, hotspots, artwork preservation,
and painting with focused regression tests.
2026-09-10 21:56:25 +08:00
rustdeskandClaude Fable 5.1 f5b98b32f2 fix(flutter): read the live DPR and clamp the painted cursor like the native one
CanvasModel caches devicePixelRatio and only refreshes it when the view
style changes, so after the window moves to a monitor with a different
DPR the unzoomed cursor kept the previous monitor's scale. Read it from
MediaQuery instead, which also rebuilds the cursor when it changes.

The native path clamps the scaled bitmap to kMinCursorSize; apply the
same clamp to the painted cursor so a small cursor does not change size
when the peer moves the mouse.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP
2026-09-10 14:25:51 +08:00
rustdeskandClaude Fable 5.1 8aee2a442e fix(flutter): keep the painted cursor hotspot in place when zoom cursor is off
`CursorPaint` subtracted the hotspot in remote pixels and then scaled it
by the canvas scale, but drew the image at scale 1.0, so the hotspot
landed hotx * (1 - scale) logical pixels away from the remote cursor
position. Cursors with a centered hotspot (I-beam, crosshair) were off
by up to half their size in Adaptive view. Subtract the hotspot after
scaling the position instead.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP
2026-09-10 14:09:39 +08:00
rustdeskandClaude Fable 5.1 12eaf2cc75 fix(flutter): check the cursor height against the min cursor size
`_checkUpdateScale` computed the scaled height from `width`, so the
min-size clamp never looked at the height.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP
2026-09-10 14:09:39 +08:00
rustdeskandClaude Fable 5.1 7194743a30 fix(flutter): shrink the unzoomed remote cursor by DPR on macOS and Linux
With "Zoom cursor" off in Adaptive or Custom view, the remote cursor
bitmap was registered at scale 1.0. NSCursor and GdkCursor treat the
bitmap size as logical pixels, so on a HiDPI controller the cursor was
drawn DPR times larger than in Original view (which already passes
1/DPR) and than on Windows (whose cursor path is in physical pixels).
A HiDPI remote such as KDE Wayland sends a 48-64 px bitmap, which then
showed up 3-4x too big on a Retina Mac.

Scale the bitmap by 1/DPR in that case, and scale the Flutter-painted
cursor used while the peer moves the mouse the same way so its size
does not jump. The new branch is an identity at DPR 1 and the Windows
paths are untouched.

Fixes https://github.com/rustdesk/rustdesk/discussions/15363

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K8HSHTEHo27mDcJXVyVfSP
2026-09-10 14:08:42 +08:00
381 changed files with 12461 additions and 41324 deletions
+1 -1
View File
@@ -234,7 +234,7 @@ jobs:
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;
+12 -370
View File
@@ -9,9 +9,6 @@ on:
upload-tag:
type: string
default: "nightly"
publish-update-metadata:
type: boolean
default: false
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
# variables from this workflow!
@@ -48,54 +45,16 @@ env:
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VCPKG_CMAKE_VERSION: "4.3.0"
ARMV7_VCPKG_COMMIT_ID: "6f29f12e82a8293156836ad81cc9bf5af41fe836" # 2025.01.13, got "/opt/artifacts/vcpkg/vcpkg: No such file or directory" with latest version
VERSION: "1.5.1"
VERSION: "1.5.0"
NDK_VERSION: "r28c"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
PUBLISH_UPDATE_METADATA: "${{ inputs.publish-update-metadata }}"
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
jobs:
validate-update-metadata-keys:
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- name: Checkout source code
if: ${{ inputs.publish-update-metadata }}
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
if: ${{ inputs.publish-update-metadata }}
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
if: ${{ inputs.publish-update-metadata }}
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Test update metadata signer
if: ${{ inputs.publish-update-metadata }}
run: |
python -m unittest \
res/update/test_generate_update_metadata.py \
res/update/test_update_metadata_cli.py \
res/update/test_macos_update_scripts.py
- name: Validate update metadata keys
if: ${{ inputs.publish-update-metadata }}
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: python res/update/generate_update_metadata.py check-key
generate-sbom:
needs: [validate-update-metadata-keys]
runs-on: ubuntu-latest
permissions:
@@ -124,11 +83,9 @@ jobs:
rustdesk.sbom.json
generate-bridge:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/bridge.yml
build-RustDeskTempTopMostWindow:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
strategy:
fail-fast: false
@@ -366,17 +323,6 @@ jobs:
Write-Host "Ingore the printer driver error."
}
- name: Run the Rust tests
# x86_64 only: the tests are the same code on arm64, and that runner is the slow one.
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'x86_64' }}
shell: bash
run: |
# The build's own features, so the tests see the code that ships.
FEATURES=$(python3 ./build.py --portable --flutter --skip-portable-pack --hwcodec ${{ matrix.job.build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Its Windows tests run nowhere else.
cargo test --locked --release -p clipboard
- name: find Runner.res
# Windows: find Runner.res (compiled from ./flutter/windows/runner/Runner.rc), copy to ./Runner.res
# Runner.rc does not contain actual version, but Runner.res does
@@ -414,18 +360,6 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./rustdesk/
- name: Verify Windows Flutter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\rustdesk\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
if: env.UPLOAD_ARTIFACT == 'true'
@@ -440,12 +374,6 @@ jobs:
- name: Add MSBuild to PATH
uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # v2
with:
# Select the MSBuild process architecture; -p:Platform sets the MSI target.
# Native ARM64 tools give the compiler more address space for PCH files
# (C3859/C1076 were reported by HostX86\arm64\CL.exe).
# Keep the action's default x86 MSBuild for the existing x64 MSI job.
msbuild-architecture: ${{ matrix.job.arch == 'aarch64' && 'arm64' || 'x86' }}
- name: Build msi
# Builds the MSI for the matrix arch. res/msi (WiX v4 + native CustomActions) carries
@@ -516,25 +444,9 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput
- name: Upload signed Windows Flutter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.exe
if-no-files-found: error
- name: Upload signed Windows Flutter MSI
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-msi
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.msi
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
if: env.UPLOAD_ARTIFACT == 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -545,7 +457,6 @@ jobs:
# The fallback for the flutter version, we use Sciter for 32bit Windows.
build-for-windows-sciter:
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.os }}
# Temporarily disable this action due to additional test is needed.
# if: false
@@ -581,20 +492,11 @@ jobs:
version: ${{ env.LLVM_VERSION }}
- name: Install Rust toolchain
shell: bash
run: |
# Sciter's abi_thiscall feature requires nightly Rust.
# Use an i686 host toolchain so build scripts can load the 32-bit LLVM installed above.
# Since rustup 1.29.1, i686 toolchains on x64 Windows require --force-non-host
# for both installation and default selection, even though WOW64 can run them.
# See https://github.com/rust-lang/rustup/pull/4935.
# Alternatively, an x64 compiler could use cargo build --target i686-pc-windows-msvc.
# This requires 64-bit LLVM for host build scripts and updated packaging paths,
# and has not been manually verified for RustDesk.
rustup toolchain install nightly-2023-10-13-${{ matrix.job.target }} \
--target ${{ matrix.job.target }} --component rustfmt \
--profile minimal --no-self-update --force-non-host
rustup default nightly-2023-10-13-${{ matrix.job.target }} --force-non-host
uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 # v1
with:
toolchain: nightly-2023-10-13-${{ matrix.job.target }} # must use nightly here, because of abi_thiscall feature required
targets: ${{ matrix.job.target }}
components: "rustfmt"
- uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
with:
@@ -678,18 +580,6 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./Release/
- name: Verify Windows Sciter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\Release\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
run: |
@@ -707,17 +597,9 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput/
- name: Upload signed Windows Sciter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-sciter-x86-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}-sciter.exe
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
if: env.UPLOAD_ARTIFACT == 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -858,7 +740,6 @@ jobs:
target: x86_64-apple-darwin,
os: macos-15-intel, #macos-latest or macos-14 use M1 now, https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#:~:text=14%20GB-,macos%2Dlatest%20or%20macos%2D14,-The%20macos%2Dlatestlabel
extra-build-args: "",
extra-cargo-features: "",
arch: x86_64,
vcpkg-triplet: x64-osx,
}
@@ -867,7 +748,6 @@ jobs:
os: macos-14,
# extra-build-args: "--disable-flutter-texture-render", # disable this for mac, because we see a lot of users reporting flickering both on arm and x64, and we can not confirm if texture rendering has better performance if htere is no vram, https://github.com/rustdesk/rustdesk/issues/6296
extra-build-args: "--screencapturekit",
extra-cargo-features: ",screencapturekit",
arch: aarch64,
vcpkg-triplet: arm64-osx,
}
@@ -976,11 +856,6 @@ jobs:
name: bridge-artifact
path: ./
- name: Run the Dart tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
working-directory: flutter
run: flutter test --timeout 60s
- name: Setup vcpkg with Github Actions binary cache
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
with:
@@ -1021,28 +896,9 @@ jobs:
sed -i -e "s/platform :osx, '.*'/platform :osx, '${MIN_MACOS_VERSION}'/" flutter/macos/Podfile
sed -i -e "s/osx_minimum_system_version = \"[0-9]*.[0-9]*\"/osx_minimum_system_version = \"${MIN_MACOS_VERSION}\"/" Cargo.toml
sed -i -e "s/MACOSX_DEPLOYMENT_TARGET = [0-9]*.[0-9]*;/MACOSX_DEPLOYMENT_TARGET = ${MIN_MACOS_VERSION};/" flutter/macos/Runner.xcodeproj/project.pbxproj
echo "MACOSX_DEPLOYMENT_TARGET=${MIN_MACOS_VERSION}" >> "$GITHUB_ENV"
fi
./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }}
- name: Test verified updates
if: env.PUBLISH_UPDATE_METADATA == 'true'
run: |
python3 -m unittest res/update/test_macos_update_scripts.py
cargo test --locked --release --lib platform::macos::update_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib verified_dmg_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib update_metadata::tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
- name: Run the Rust tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
run: |
# The build's own features, so the tests see the code that ships. MACOSX_DEPLOYMENT_TARGET
# comes from the build step's export.
FEATURES=$(./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Opt-in, and its macOS tests run nowhere else.
cargo test --locked --release -p clipboard --features unix-file-copy-paste
- name: create unsigned dmg
if: env.UPLOAD_ARTIFACT == 'true'
run: |
@@ -1075,13 +931,6 @@ jobs:
./flutter/build/macos/Build/Products/Release/RustDesk.app \
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
./flutter/macos/Runner/Release.entitlements
if [ "$PUBLISH_UPDATE_METADATA" = "true" ]; then
reported_version="$(./flutter/build/macos/Build/Products/Release/RustDesk.app/Contents/MacOS/RustDesk --version)"
if [ "$reported_version" != "$VERSION" ]; then
echo "::error::RustDesk reports version '$reported_version', expected '$VERSION'"
exit 1
fi
fi
create-dmg --icon "RustDesk.app" 200 190 --hide-extension "RustDesk.app" --window-size 800 400 --app-drop-link 600 185 rustdesk-${{ env.VERSION }}.dmg ./flutter/build/macos/Build/Products/Release/RustDesk.app
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict rustdesk-${{ env.VERSION }}.dmg -vvv
# notarize the rustdesk-${{ env.VERSION }}.dmg
@@ -1089,26 +938,13 @@ jobs:
- name: Rename rustdesk
if: env.UPLOAD_ARTIFACT == 'true'
shell: bash
env:
VERSION: ${{ env.VERSION }}
ARCH: ${{ matrix.job.arch }}
run: |
if [ -f "rustdesk-${VERSION}.dmg" ]; then
mv "rustdesk-${VERSION}.dmg" "rustdesk-${VERSION}-${ARCH}.dmg"
fi
test -f "rustdesk-${VERSION}-${ARCH}.dmg"
- name: Upload signed macOS DMG
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.MACOS_P12_BASE64 != null
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: macos-${{ matrix.job.arch }}-dmg
path: ./rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.dmg
if-no-files-found: error
for name in rustdesk*??.dmg; do
mv "$name" "${name%%.dmg}-${{ matrix.job.arch }}.dmg"
done
- 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
with:
prerelease: true
@@ -1116,141 +952,6 @@ jobs:
files: |
rustdesk*-${{ matrix.job.arch }}.dmg
publish-signed-update-metadata:
needs: [build-for-windows-flutter, build-for-windows-sciter, build-for-macOS]
runs-on: ubuntu-22.04
if: ${{ inputs.upload-artifact && inputs.publish-update-metadata && github.repository == 'rustdesk/rustdesk' }}
concurrency:
group: signed-update-${{ inputs.upload-tag }}
cancel-in-progress: false
permissions:
# Required to inspect and publish signed release assets for the target tag.
contents: write
steps:
- name: Refuse to replace published update metadata
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TAG_NAME: ${{ env.TAG_NAME }}
run: |
set -euo pipefail
releases="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases?per_page=100")"
release_id="$(
jq -r --arg tag "$TAG_NAME" '
[.[][] | select(.tag_name == $tag)] |
if length == 0 then ""
elif length == 1 then .[0].id
else error("multiple releases found for tag")
end
' <<<"$releases"
)"
if [ -z "$release_id" ]; then
exit 0
fi
assets="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases/${release_id}/assets?per_page=100")"
if jq -e 'any(.[][]; .name == "rustdesk-update.json")' <<<"$assets" >/dev/null; then
echo "::error::Signed update metadata is already published for ${TAG_NAME}; use a new release tag for corrected artifacts."
exit 1
fi
- name: Checkout source code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Download Windows artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: windows-*
path: ./artifacts/
merge-multiple: true
- name: Download macOS artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: macos-*
path: ./artifacts/
merge-multiple: true
- name: Sign update metadata
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
run: |
python res/update/generate_update_metadata.py sign \
--artifact windows x86_64 exe "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact windows x86_64 msi "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact windows aarch64 exe "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact windows aarch64 msi "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact windows x86 exe "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact macos aarch64 dmg "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact macos x86_64 dmg "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download \
--published-at "$(git log -1 --format=%cI)" \
--metadata-out ./rustdesk-update.json \
--signature-out ./rustdesk-update.json.sig
- name: Verify update metadata
env:
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: |
python res/update/generate_update_metadata.py verify \
--metadata ./rustdesk-update.json \
--signature ./rustdesk-update.json.sig \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download
- name: Upload signed update artifacts
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: |
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.exe
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.msi
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.msi
./artifacts/rustdesk-${{ env.VERSION }}-x86-sciter.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.dmg
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.dmg
# The release action replaces same-name assets, so keep published sidecars
# until replacements are ready.
- name: Upload signed update metadata signature
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json.sig
# Clients discover the release through metadata, so publish it only after every referenced asset.
- name: Publish signed update metadata
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json
publish_unsigned:
needs:
- build-for-macOS
@@ -2325,61 +2026,6 @@ jobs:
*) echo "::error::build.py returned no '$want' feature: $FEATURES"; exit 1 ;;
esac
done
# Run the drm-gated unit tests HERE, because nowhere else does. The ordinary linux CI
# runs the suite, but `drm` is opt-in, so every test behind that feature -- the cursor
# rotation and hotspot ones especially -- has no continuous coverage at all otherwise.
# Debug rather than --release: these are pure logic tests and the release build is
# already the slow part of this job.
# A MINIMAL feature set, not the production $FEATURES: these are pure logic tests of
# the drm paths, and pulling hwcodec in makes the test binary fail to link at all
# (undefined reference to fcntl64 in this container), so the tests never run.
#
# Two packages, because `cargo test --lib` at the root builds the ROOT package only:
# the provenance tests live in libs/scrap and would never be selected from here. The
# ordinary linux CI runs --workspace but without the drm feature, so these are not
# covered there either.
#
# awk sums the counts rather than bc, which this container does not install.
#
# A cargo test FILTER that matches nothing exits 0, so a rename would turn this into a
# green no-op. Assert each command actually ran something.
run_drm_tests() {
local desc="$1"; shift
local out
out=$("$@" 2>&1) || { echo "$out"; echo "::error::drm tests failed: $desc"; exit 1; }
local ran
ran=$(echo "$out" | awk '/^running [0-9]+ tests?$/ { n += $2 } END { print n+0 }')
echo "$desc ran $ran tests"
if [ "$ran" -lt 1 ]; then
echo "::error::$desc selected no tests; it was renamed or removed"
exit 1
fi
}
run_drm_tests "rustdesk drm_capturer_tests" \
cargo test --locked --lib --features drm drm_capturer_tests
run_drm_tests "rustdesk ipc::test" \
cargo test --locked --lib --features drm ipc::test
run_drm_tests "rustdesk cursor_pos_tests" \
cargo test --locked --lib --features drm cursor_pos_tests
run_drm_tests "rustdesk peer_abs_sample_tests" \
cargo test --locked --lib --features drm peer_abs_sample_tests
run_drm_tests "rustdesk input_map_tests" \
cargo test --locked --lib --features drm input_map_tests
run_drm_tests "rustdesk drm_pacing_tests" \
cargo test --locked --lib --features drm drm_pacing_tests
run_drm_tests "scrap hotspot_provenance_tests" \
cargo test --locked -p scrap --features drm hotspot_provenance_tests
run_drm_tests "scrap hotspot_guess_tests" \
cargo test --locked -p scrap --features drm hotspot_guess_tests
run_drm_tests "scrap crtc_refresh_tests" \
cargo test --locked -p scrap --features drm crtc_refresh_tests
run_drm_tests "scrap plane_rotation_tests" \
cargo test --locked -p scrap --features drm plane_rotation_tests
run_drm_tests "scrap drmtap_dl::tests" \
cargo test --locked -p scrap --features drm drmtap_dl::tests
# Opt-in like drm, and this container already builds with it.
run_drm_tests "clipboard unix-file-copy-paste" \
cargo test --locked -p clipboard --features unix-file-copy-paste
cargo build --locked --lib --features "$FEATURES" --release
rm -rf target/release/deps target/release/build
rm -rf ~/.cargo
@@ -2460,7 +2106,6 @@ jobs:
build-rustdesk-linux-sciter:
if: ${{ inputs.upload-artifact }}
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.on }}
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
strategy:
@@ -2741,9 +2386,7 @@ jobs:
sudo pip3 install git+https://github.com/rustdesk-org/appimage-builder.git
# run appimage-builder
pushd appimage
./build-apprun.sh ${{ matrix.job.arch }}
sudo appimage-builder --skip-tests --recipe ./AppImageBuilder-${{ matrix.job.arch }}.yml
cmp AppDir/AppRun appimage-build/AppRun/v2.0.0/AppRun-Release-${{ matrix.job.arch }}
- name: Publish appimage package
if: env.UPLOAD_ARTIFACT == 'true'
@@ -2841,7 +2484,6 @@ jobs:
build-rustdesk-web:
if: False
needs: [validate-update-metadata-keys]
name: build-rustdesk-web
runs-on: ubuntu-22.04
permissions:
+1 -2
View File
@@ -15,5 +15,4 @@ jobs:
secrets: inherit
with:
upload-artifact: true
upload-tag: ${{ github.ref_name }}
publish-update-metadata: ${{ github.repository == 'rustdesk/rustdesk' }}
upload-tag: ${{ github.ref_name }}
+1 -1
View File
@@ -17,7 +17,7 @@ env:
TAG_NAME: "nightly"
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VERSION: "1.5.1"
VERSION: "1.5.0"
NDK_VERSION: "r26d"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
-2
View File
@@ -58,5 +58,3 @@ libsciter.dylib
flutter/web/
# libdrmtap is cloned at build time by build.py (not a submodule)
/third_party/libdrmtap/
# Local git worktrees
.worktrees/
-66
View File
@@ -48,20 +48,6 @@ workspace member. `base::config::keys` re-exports the handful of keys
* Do not add dependencies unless needed.
* Keep code simple and idiomatic.
### Logging
* `debug` and above are written to the log file. A log call that can fire
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
peer controls) must not use `debug` or higher unthrottled.
* For such a site, pick one:
* `log::trace!` when the event is expected and the line only helps while
actively debugging;
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
that should still show up in a user's log. It keeps one line per interval
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
directly only when the decision drives more than one log call.
## Tokio Rules
* Assume a Tokio runtime already exists.
@@ -73,30 +59,6 @@ workspace member. `base::config::keys` re-exports the handful of keys
* Use `spawn_blocking` or dedicated threads for blocking work.
* 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
* 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.
* 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
* Review only what the diff introduces. Verify ownership with `gh pr diff` before reporting a finding — if the offending lines are untouched context, it is a pre-existing problem, not this PR's.
* List pre-existing problems in a separate section at the end, or leave out the ones that are not fatal. Never mix them into the findings the author has to fix.
* Before re-reviewing, read the author's reply comments. Do not re-raise items they declined on scope grounds.
* State a finding's consequence exactly: distinguish "the value is lost" from "the shortcut is inert but the value still saves".
* Do not report a rare corner case as blocking when fixing it needs new state; mark it as a known limit the author may leave unfixed.
* Treat growth across review rounds as a finding: if the latest commits add more state than the original fix, say so instead of asking for more handling.
## Localization (`src/lang/*.rs`)
Generated
+84 -67
View File
@@ -985,9 +985,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
version = "1.11.1"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
dependencies = [
"serde 1.0.228",
]
@@ -1305,7 +1305,7 @@ dependencies = [
[[package]]
name = "clipboard-master"
version = "4.0.0-beta.6"
source = "git+https://github.com/rustdesk-org/clipboard-master#522fafb65edfe7939cf63fa797f916569ecab595"
source = "git+https://github.com/rustdesk-org/clipboard-master#7762d74e38db37cfeb6ded88c964b9cdbddfb6db"
dependencies = [
"objc",
"objc-foundation",
@@ -1717,7 +1717,7 @@ dependencies = [
[[package]]
name = "cpal"
version = "0.15.3"
source = "git+https://github.com/rustdesk-org/cpal?branch=osx-screencapturekit#96d4da121b7d949677ac5b6887413a9185fd7f39"
source = "git+https://github.com/rustdesk-org/cpal?branch=osx-screencapturekit#69ad2578adc9200093fc81cdfbdad63dbc4274f9"
dependencies = [
"alsa",
"cidre",
@@ -1791,9 +1791,9 @@ dependencies = [
[[package]]
name = "crossbeam-epoch"
version = "0.9.20"
version = "0.9.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
dependencies = [
"crossbeam-utils",
]
@@ -3737,7 +3737,7 @@ dependencies = [
"url",
"users",
"uuid",
"webpki-roots 1.0.11",
"webpki-roots 1.0.9",
"webrtc",
"whoami",
"x11 2.21.0",
@@ -3888,8 +3888,8 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "hwcodec"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/hwcodec#ec38ebaf2454269d4c5668a57e3813c6e5541be7"
version = "0.7.1"
source = "git+https://github.com/rustdesk-org/hwcodec#778df1f99597722473b29443bac22ae6c23946fe"
dependencies = [
"bindgen 0.59.2",
"cc",
@@ -3935,7 +3935,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots 1.0.11",
"webpki-roots 1.0.9",
]
[[package]]
@@ -4121,7 +4121,8 @@ dependencies = [
[[package]]
name = "interceptor"
version = "0.14.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ac0781c825d602095113772e389ef0607afcb869ae0e68a590d8e0799cdcef8"
dependencies = [
"async-trait",
"bytes",
@@ -4163,6 +4164,16 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "iri-string"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
dependencies = [
"memchr",
"serde 1.0.228",
]
[[package]]
name = "is-terminal"
version = "0.4.16"
@@ -6485,9 +6496,9 @@ dependencies = [
[[package]]
name = "quinn-proto"
version = "0.11.15"
version = "0.11.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
dependencies = [
"bytes",
"getrandom 0.3.2",
@@ -6762,7 +6773,7 @@ dependencies = [
[[package]]
name = "rdev"
version = "0.5.0-2"
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
source = "git+https://github.com/rustdesk-org/rdev#23e24dd6b35452a495dae0ae6d99395e9755ab0f"
dependencies = [
"cocoa 0.24.1",
"core-foundation 0.9.4",
@@ -6891,10 +6902,11 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.12.28"
version = "0.12.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
dependencies = [
"async-compression",
"base64 0.22.1",
"bytes",
"futures-channel",
@@ -6923,6 +6935,7 @@ dependencies = [
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
@@ -6930,7 +6943,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots 1.0.11",
"webpki-roots 1.0.9",
]
[[package]]
@@ -6995,7 +7008,8 @@ dependencies = [
[[package]]
name = "rtcp"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9689528bf3a9eb311fd938d05516dd546412f9ce4fffc8acfc1db27cc3dbf72"
dependencies = [
"bytes",
"thiserror 1.0.61",
@@ -7005,7 +7019,8 @@ dependencies = [
[[package]]
name = "rtp"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54733451a67d76caf9caa07a7a2cec6871ea9dda92a7847f98063d459200f4b"
dependencies = [
"bytes",
"memchr",
@@ -7041,7 +7056,7 @@ dependencies = [
[[package]]
name = "rust-pulsectl"
version = "0.2.12"
source = "git+https://github.com/rustdesk-org/pulsectl#d2ec086b5770dce934a66956364d09df8cc9484c"
source = "git+https://github.com/rustdesk-org/pulsectl#aa34dde499aa912a3abc5289cc0b547bd07dd6e2"
dependencies = [
"libpulse-binding",
]
@@ -7075,7 +7090,7 @@ dependencies = [
[[package]]
name = "rustdesk"
version = "1.5.1"
version = "1.5.0"
dependencies = [
"android-wakelock",
"android_logger",
@@ -7124,7 +7139,6 @@ dependencies = [
"lazy_static",
"libpulse-binding",
"libpulse-simple-binding",
"libsamplerate-sys",
"libxdo-sys",
"mac_address",
"magnum-opus",
@@ -7175,7 +7189,6 @@ dependencies = [
"uuid",
"virtual_display",
"wallpaper",
"wayland-client",
"winapi 0.3.9",
"windows 0.61.1",
"windows-service",
@@ -7185,14 +7198,12 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xkbcommon-dl",
"xxhash-rust",
"zstd",
]
[[package]]
name = "rustdesk-portable-packer"
version = "1.5.1"
version = "1.5.0"
dependencies = [
"brotli",
"dirs 5.0.1",
@@ -7296,12 +7307,11 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
@@ -7333,9 +7343,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.16"
version = "0.103.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435"
dependencies = [
"ring",
"rustls-pki-types",
@@ -7455,7 +7465,8 @@ dependencies = [
[[package]]
name = "sdp"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cd277015eada44a0bb810a4b84d3bf6e810573fa62fb442f457edf6a1087a69"
dependencies = [
"rand 0.8.5",
"substring",
@@ -8027,7 +8038,8 @@ dependencies = [
[[package]]
name = "stun"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dbc2bab375524093c143dc362a03fb6a1fb79e938391cdb21665688f88a088a"
dependencies = [
"base64 0.22.1",
"crc",
@@ -8601,8 +8613,9 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
version = "0.29.0"
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=c241b11b03de4881faf1ecd2fe6e867c92f3013b#c241b11b03de4881faf1ecd2fe6e867c92f3013b"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
dependencies = [
"futures-util",
"log",
@@ -8735,25 +8748,20 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.11"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
dependencies = [
"async-compression",
"bitflags 2.9.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"iri-string",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
@@ -8890,8 +8898,9 @@ dependencies = [
[[package]]
name = "tungstenite"
version = "0.29.0"
source = "git+https://github.com/rustdesk-org/tungstenite-rs?rev=efce47e5364f00a63302cf07ab1fb13ded478914#efce47e5364f00a63302cf07ab1fb13ded478914"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
dependencies = [
"bytes",
"data-encoding",
@@ -8905,13 +8914,15 @@ dependencies = [
"rustls-pki-types",
"sha1",
"thiserror 2.0.17",
"utf-8",
"webpki-roots 0.26.11",
]
[[package]]
name = "turn"
version = "0.10.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f5aea1116456e1da71c45586b87c72e3b43164fbf435eb93ff6aa475416a9a4"
dependencies = [
"async-trait",
"base64 0.22.1",
@@ -9134,6 +9145,12 @@ dependencies = [
"log",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf16string"
version = "0.2.0"
@@ -9540,9 +9557,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.10"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
checksum = "05d651ec480de84b762e7be71e6efa7461699c19d9e2c272c8d93455f567786e"
dependencies = [
"rustls-pki-types",
]
@@ -9553,14 +9570,14 @@ version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.11",
"webpki-roots 1.0.9",
]
[[package]]
name = "webpki-roots"
version = "1.0.11"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
dependencies = [
"rustls-pki-types",
]
@@ -9568,7 +9585,8 @@ dependencies = [
[[package]]
name = "webrtc"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24bab7195998d605c862772f90a452ba655b90a2f463c850ac032038890e367a"
dependencies = [
"arc-swap",
"async-trait",
@@ -9611,7 +9629,8 @@ dependencies = [
[[package]]
name = "webrtc-data"
version = "0.11.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e97b932854da633a767eff0cc805425a2222fc6481e96f463e57b015d949d1d"
dependencies = [
"bytes",
"log",
@@ -9625,7 +9644,8 @@ dependencies = [
[[package]]
name = "webrtc-dtls"
version = "0.12.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ccbe4d9049390ab52695c3646c1395c877e16c15fb05d3bda8eee0c7351711c"
dependencies = [
"aes",
"aes-gcm",
@@ -9661,12 +9681,12 @@ dependencies = [
[[package]]
name = "webrtc-ice"
version = "0.13.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb51bde0d790f109a15bfe4d04f1b56fb51d567da231643cb3f21bb74d678997"
dependencies = [
"arc-swap",
"async-trait",
"crc",
"ipnet",
"log",
"portable-atomic",
"rand 0.8.5",
@@ -9686,7 +9706,8 @@ dependencies = [
[[package]]
name = "webrtc-mdns"
version = "0.9.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "979cc85259c53b7b620803509d10d35e2546fa505d228850cbe3f08765ea6ea8"
dependencies = [
"log",
"socket2 0.5.10",
@@ -9698,7 +9719,8 @@ dependencies = [
[[package]]
name = "webrtc-media"
version = "0.10.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80041211deccda758a3e19aa93d6b10bc1d37c9183b519054b40a83691d13810"
dependencies = [
"byteorder",
"bytes",
@@ -9710,7 +9732,7 @@ dependencies = [
[[package]]
name = "webrtc-sctp"
version = "0.12.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "git+https://github.com/rustdesk-org/webrtc?rev=db3b07a9dd8f195916c89c2e62a8911402b11d27#db3b07a9dd8f195916c89c2e62a8911402b11d27"
dependencies = [
"arc-swap",
"async-trait",
@@ -9727,7 +9749,8 @@ dependencies = [
[[package]]
name = "webrtc-srtp"
version = "0.15.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01e773f79b09b057ffbda6b03fe7b43403b012a240cf8d05d630674c3723b5bb"
dependencies = [
"aead",
"aes",
@@ -9749,7 +9772,7 @@ dependencies = [
[[package]]
name = "webrtc-util"
version = "0.11.0"
source = "git+https://github.com/rustdesk-org/webrtc?rev=49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63#49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63"
source = "git+https://github.com/rustdesk-org/webrtc?rev=db3b07a9dd8f195916c89c2e62a8911402b11d27#db3b07a9dd8f195916c89c2e62a8911402b11d27"
dependencies = [
"async-trait",
"bitflags 1.3.2",
@@ -10803,12 +10826,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]]
name = "xxhash-rust"
version = "0.8.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
[[package]]
name = "yasna"
version = "0.5.2"
+8 -30
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk"
version = "1.5.1"
version = "1.5.0"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2021"
build= "build.rs"
@@ -22,7 +22,7 @@ path = "src/service.rs"
[features]
inline = []
use_samplerate = ["samplerate", "libsamplerate-sys"]
use_samplerate = ["samplerate"]
use_rubato = ["rubato"]
use_dasp = ["dasp"]
flutter = ["flutter_rust_bridge"]
@@ -40,7 +40,6 @@ drm-wake = ["drm"]
linux-pkg-config = ["magnum-opus/linux-pkg-config", "scrap/linux-pkg-config"]
unix-file-copy-paste = [
"dep:x11-clipboard",
"dep:x11rb",
"dep:percent-encoding",
"dep:once_cell",
"clipboard/unix-file-copy-paste",
@@ -63,13 +62,11 @@ lazy_static = "1.4"
sha2 = "0.10"
repng = "0.2"
zstd = "0.13"
xxhash-rust = { version = "0.8", features = ["xxh3"] }
parity-tokio-ipc = { git = "https://github.com/rustdesk-org/parity-tokio-ipc" }
magnum-opus = { git = "https://github.com/rustdesk-org/magnum-opus" }
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
rubato = { version = "0.12", optional = true }
samplerate = { version = "0.2", optional = true }
libsamplerate-sys = { version = "0.1.12", optional = true }
uuid = { version = "1.3", features = ["v4"] }
num_cpus = "1.15"
bytes = { version = "1.4", features = ["serde"] }
@@ -194,7 +191,7 @@ evdev = { git="https://github.com/rustdesk-org/evdev" }
dbus = "0.9"
dbus-crossroads = "0.5"
x11-clipboard = {git="https://github.com/clslaid/x11-clipboard", branch = "feat/store-batch", optional = true}
x11rb = {version = "0.12", features = ["all-extensions"], optional = true}
x11rb = {version = "0.12", features = ["all-extensions"]}
percent-encoding = {version = "2.3", optional = true}
once_cell = {version = "1.18", optional = true}
nix = { version = "0.29", features = ["term", "process"]}
@@ -202,8 +199,6 @@ gtk = "0.18"
termios = "0.3"
terminfo = "0.8"
winit = "0.30"
wayland-client = "0.31"
xkbcommon-dl = { version = "0.4", features = ["x11"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
@@ -221,21 +216,9 @@ exclude = ["vdi/host"]
# This allows building and running on systems without libxdo installed (e.g., Wayland-only)
[patch.crates-io]
libxdo-sys = { path = "libs/libxdo-sys-stub" }
# Upstream reserves a frame's whole declared length as soon as its header is in, so a header alone
# buys an allocation the size it names, bounded only by max_frame_size. This fork grows the read
# buffer one read_buffer_size chunk at a time as the bytes actually arrive. Patched rather than
# depended on directly, so tokio-tungstenite's own tungstenite resolves to the same copy.
tungstenite = { git = "https://github.com/rustdesk-org/tungstenite-rs", rev = "efce47e5364f00a63302cf07ab1fb13ded478914" }
# One branch off upstream v0.13.0, the tag whose crate versions match this stack.
# webrtc-util: reads the Windows adapter list's IPv6 addresses as host-order u16 groups, so every
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows;
# and names every Windows adapter "" with no mask, so ICE cannot tell one adapter's addresses
# from another's; and lays the adapter struct out in nested parts, whose padding on x64 shifts
# every field after OperStatus, Ipv6IfIndex first.
# webrtc-ice: best effort, one IPv6 host candidate per interface and prefix - the one the OS
# sends from when that is one of the group's, else all of them - since the stable address beside
# the temporary one is an identifier that outlives every rotation and that nothing else this
# machine sends out ever shows.
# one comes out byte-swapped, fails to bind, and ICE gathers no IPv6 host candidate on Windows.
# webrtc-sctp: RFC 4960's 1s RTO floor makes a single loss cost 1-3s on a link whose RTT is 24-64ms,
# and fast retransmit cannot cover a request/response exchange; INITIAL_MTU 1228 also fragments on
# IPv6; and its AIMD pins a lossy long-haul link to MSS/(RTT*sqrt(p)), so a switch sends without
@@ -245,15 +228,10 @@ tungstenite = { git = "https://github.com/rustdesk-org/tungstenite-rs", rev = "e
# RTT at KCP's RTO floors, and bundles of small chunks stay within the MTU. A T3-rtx resends
# everything outstanding when it packs into four packets and otherwise probes with one and lets
# the SACK settle the rest (F-RTO), timed from the latest send, so a stall no longer resends the
# whole backlog behind itself while a short lost tail still comes back at once. A DATA chunk
# received again is listed in the SACK, which never happened - the sender widens its reordering
# window on that - and the SACK keeps to the MTU too, the lowest gap blocks first.
# whole backlog behind itself while a short lost tail still comes back at once.
# Pinned by rev, not branch: a fork branch can be rewritten out from under the lockfile.
# webrtc: SettingEngine cannot reach the ICE agent's max_binding_requests, which decides how
# long the answerer keeps checking a pair that has not answered yet.
webrtc = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "49c89bd8d30e6e62e4c1a96cee38fdc11f79ef63" }
webrtc-util = { git = "https://github.com/rustdesk-org/webrtc", rev = "db3b07a9dd8f195916c89c2e62a8911402b11d27" }
webrtc-sctp = { git = "https://github.com/rustdesk-org/webrtc", rev = "db3b07a9dd8f195916c89c2e62a8911402b11d27" }
[package.metadata.winres]
LegalCopyright = "Copyright © 2026 Purslane Tech Pte. Ltd. All rights reserved."
@@ -273,7 +251,7 @@ os-version = "0.2"
[dev-dependencies]
hound = "3.5"
docopt = "1.1"
tokio = "1.44"
tokio = { version = "1.44", features = ["test-util"] }
[package.metadata.bundle]
name = "RustDesk"
+1 -1
View File
@@ -1,4 +1,4 @@
FROM debian:trixie-slim
FROM debian:bullseye-slim
WORKDIR /
ARG DEBIAN_FRONTEND=noninteractive
+1 -1
View File
@@ -4,7 +4,7 @@
<a href="#how-to-build-with-docker">Docker</a> •
<a href="#file-structure">Structure</a> •
<a href="#screenshots">Screenshots</a><br>
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTPT.md">Português (Portugal)</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
<b>We need your help to translate this README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> and <a href="https://github.com/rustdesk/doc.rustdesk.com">RustDesk Doc</a> to your native language</b>
</p>
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.1
version: 1.5.0
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.1
version: 1.5.0
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
-55
View File
@@ -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;
}
-38
View File
@@ -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"
+5 -45
View File
@@ -390,9 +390,9 @@ def ffi_bindgen_function_refactor():
# The commit is fetched directly by sha, so no branch or tag name takes part in the build: see
# build_libdrmtap_so(). This is the SINGLE source of truth for the pin, deliberately not duplicated in
# any workflow, so a bump is one edit here (plus the informational version comment in
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.12.
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.4.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '5936a7a88b94aa43516a3dd0eb509d2383f31e2d'
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
LIBDRMTAP_SHA = os.environ.get('DRMTAP_SHA', LIBDRMTAP_SHA_PINNED)
# Every way of getting a different .so than the pin needs the same explicit opt-in. Otherwise the
@@ -489,10 +489,8 @@ def build_libdrmtap_so():
# override of the three -- no fetch, no sha verification, an object built by something this
# script cannot see -- so it is the likeliest to hand over a CPU-only build, and skipping the
# assertion on exactly this path would leave the check guarding only the case that was
# already trustworthy. The helper check rides along for the same reason, and it matters
# more here than anywhere: this is the branch the packaging workflow takes.
# already trustworthy.
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
return so
# Fetch the pinned source if it is not already present. third_party/libdrmtap is not a submodule
# anymore; it is git-ignored. The commit is fetched BY SHA rather than by cloning a branch:
@@ -523,22 +521,8 @@ def build_libdrmtap_so():
f'libdrmtap at {src} is {got_sha}, expected {LIBDRMTAP_SHA} '
f'(stale checkout from a different pin; removed, re-run to re-fetch)')
build_dir = os.path.join(src, 'build-pkg')
# Configure a fresh dir, or RE-configure one an earlier build left behind. Without the second
# branch a build-pkg created before this option was added keeps its old configuration, meson
# skips setup, and the compile produces a helper-enabled .so. The assertion below then fails
# the build rather than shipping it, so this is a developer-build correctness fix and not a
# security one -- but it turns a confusing failure into no failure at all.
if not os.path.exists(os.path.join(build_dir, 'build.ninja')):
# -Dhelper=disabled: rustdesk never uses the privileged helper. The capture context is
# opened only in the root service (every drmtap_open lives in src/ipc/drm.rs), which
# already has CAP_SYS_ADMIN, and the unprivileged side opens a render node instead. Without
# this the library still carries the fallback: a fork/exec that walks six hardcoded paths,
# two of them under /usr/local, and execs the first that passes access(X_OK) with no check
# of its owner or mode -- inside the ROOT process. The option compiles that path out
# entirely. Requested by the maintainer on rustdesk#16242.
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release -Dhelper=disabled')
else:
system2(f'meson configure "{build_dir}" -Dhelper=disabled')
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release')
# Build only the shared library, not the bundled helper binary or the static archive. Since
# libdrmtap 0.4.11 the project is `both_libraries` (a version-scripted .so + a static .a), so the
# bare `drmtap` target is ambiguous ("drmtap:shared_library" vs "drmtap:static_library"); ask for
@@ -549,31 +533,9 @@ def build_libdrmtap_so():
# require exactly one so a stale object from an earlier build is never silently picked.
so = _single_real_so(sos, f'the libdrmtap meson build dir {build_dir}')
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
return so
def _assert_so_has_no_helper(so_path):
# Asserted on the ARTIFACT for the same reason the EGL check is: a build flag cannot notice a
# stale object left by an earlier build, or one substituted by hand, and `-Dhelper=disabled` is
# silently accepted by meson versions that predate the option. What the option removes is the
# whole fork/exec path, so the produced .so imports no socketpair and carries none of the
# helper search paths; both go to zero, measured on libdrmtap 0.5.6 (4 -> 0 and 3 -> 0).
#
# This matters because the object is loaded by the ROOT service. With the path compiled in, a
# caller that ever lost CAP_SYS_ADMIN would exec whatever sits at the first of six hardcoded
# locations that passes access(X_OK), without checking its owner or its mode.
with open(so_path, 'rb') as f:
blob = f.read()
found = [m.decode() for m in (b'socketpair', b'/usr/libexec/drmtap-helper') if m in blob]
if found:
raise Exception(
f'{so_path} still carries the privileged-helper fallback ({", ".join(found)}). '
f'It must be built with -Dhelper=disabled: rustdesk captures as root and never uses '
f'the helper, so this is a fork/exec path in the privileged process that nothing '
f'reaches. Delete third_party/libdrmtap/build-pkg and rebuild.')
def _assert_so_has_egl(so_path):
# libdrmtap treats egl/glesv2 as OPTIONAL dependencies: without their headers and pkg-config
# files, meson silently builds a CPU-only stub. That stub still exports every symbol the loader
@@ -901,10 +863,8 @@ def build_deb_from_folder(version, binary_folder, want_drm=False):
# takes the .so straight out of a bundle somebody else produced, so it has the same
# exposure as DRMTAP_PREBUILT_DIR (see the comment on that branch). A CPU-only stub
# would ship, the loader would accept it, and capture would degrade to PipeWire
# without a word. A bundle produced before the helper was disabled is caught here too,
# which is the point: it must not be repackaged into a deb.
# without a word.
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
stage_libdrmtap_into_deb(so)
system2(f'rm -f "{so}"')
system2('rm -f tmpdeb/usr/share/rustdesk/libdrmtap.so tmpdeb/usr/share/rustdesk/libdrmtap.so.0')
+1 -6
View File
@@ -2,12 +2,7 @@
fn build_windows() {
let file = "src/platform/windows.cc";
let file2 = "src/platform/windows_delete_test_cert.cc";
let mut build = cc::Build::new();
if !cfg!(feature = "flutter") {
build.cpp(true).std("c++17").define("RUSTDESK_SCITER", None);
println!("cargo:rerun-if-changed=flutter/windows/runner/service_control.h");
}
build.file(file).file(file2).compile("windows");
cc::Build::new().file(file).file(file2).compile("windows");
println!("cargo:rustc-link-lib=WtsApi32");
println!("cargo:rerun-if-changed={}", file);
println!("cargo:rerun-if-changed={}", file2);
+1 -8
View File
@@ -9,10 +9,6 @@
<b>Kami membutuhkan bantuanmu untuk menterjemahkan file README dan <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> ke Bahasa Indonesia</b>
</p>
> [!Caution]
> **Peringatan Penyalahgunaan:** <br>
> Pengembang RustDesk tidak membenarkan atau mendukung penggunaan perangkat lunak ini yang tidak etis atau melanggar hukum. Penyalahgunaan, seperti akses tanpa izin, pengambilalihan kendali, atau pelanggaran privasi, sangat dilarang berdasarkan pedoman kami. Para pengembang tidak bertanggung jawab atas penyalahgunaan aplikasi ini.
Mari mengobrol bersama kami: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Fitur%20Lanjutan-blue)](https://rustdesk.com/pricing.html)
@@ -34,9 +30,6 @@ RustDesk mengajak semua orang untuk ikut berkontribusi. Lihat [`docs/CONTRIBUTIN
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Get it on Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Dependensi
@@ -161,7 +154,7 @@ Harap pastikan bahwa kamu menjalankan perintah ini dari repositori root RustDesk
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikasi dengan [rustdesk-server](https://github.com/rustdesk/rustdesk-server), menunggu untuk remote direct (TCP hole punching) atau relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: kode khusus platform
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: kode Flutter untuk platform desktop dan perangkat seluler
## Snapshots
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
-179
View File
@@ -1,179 +0,0 @@
<p align="center">
<img src="../res/logo-header.svg" alt="RustDesk - O seu ambiente de trabalho remoto"><br>
<a href="#compilar">Compilar</a> •
<a href="#como-compilar-com-o-docker">Docker</a> •
<a href="#estrutura-de-ficheiros">Estrutura</a> •
<a href="#capturas-de-ecrã">Capturas de Ecrã</a><br>
[<a href="../README.md">Inglês</a>] | [<a href="README-UA.md">Ucraniano</a>] | [<a href="README-CS.md">Checo</a>] | [<a href="README-ZH.md">Chinês</a>] | [<a href="README-HU.md">Húngaro</a>] | [<a href="README-ES.md">Espanhol</a>] | [<a href="README-FA.md">Persa</a>] | [<a href="README-FR.md">Francês</a>] | [<a href="README-DE.md">Alemão</a>] | [<a href="README-PL.md">Polaco</a>] | [<a href="README-ID.md">Indonésio</a>] | [<a href="README-FI.md">Finlandês</a>] | [<a href="README-ML.md">Malaiala</a>] | [<a href="README-JP.md">Japonês</a>] | [<a href="README-NL.md">Holandês</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Russo</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">Coreano</a>] | [<a href="README-AR.md">Árabe</a>] | [<a href="README-VN.md">Vietnamita</a>] | [<a href="README-DA.md">Dinamarquês</a>] | [<a href="README-GR.md">Grego</a>] | [<a href="README-TR.md">Turco</a>] | [<a href="README-NO.md">Norueguês</a>] | [<a href="README-RO.md">Romeno</a>]<br>
<b>Precisamos da sua ajuda para traduzir este README, a <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">Interface do RustDesk</a> e a <a href="https://github.com/rustdesk/doc.rustdesk.com">Documentação do RustDesk</a> para o seu idioma nativo</b>
</p>
> [!Caution]
> **Aviso de Isenção de Responsabilidade por Uso Indevido:** <br>
> Os programadores do RustDesk não toleram ou apoiam qualquer uso antiético ou ilegal deste software. O uso indevido, como acesso não autorizado, controlo ou invasão de privacidade, é estritamente contrário às nossas diretrizes. Os autores não se responsabilizam por qualquer uso indevido da aplicação.
Converse connosco: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Advanced%20Features-blue)](https://rustdesk.com/pricing.html)
Mais uma solução de ambiente de trabalho remoto, escrita em Rust. Funciona imediatamente, sem necessidade de configuração. Tem controlo total dos seus dados, sem preocupações com a segurança. Pode usar o nosso servidor de ligação/retransmissão (rendezvous/relay), [configurar o seu próprio](https://rustdesk.com/server) ou [escrever o seu próprio servidor de ligação/retransmissão](https://github.com/rustdesk/rustdesk-server-demo).
![image](https://user-images.githubusercontent.com/71636191/171661982-430285f0-2e12-4b1d-9957-4a58e375304d.png)
O RustDesk agradece as contribuições de todos. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para obter ajuda para começar.
[**Perguntas Frequentes (FAQ)**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**DOWNLOAD DOS BINÁRIOS**](https://github.com/rustdesk/rustdesk/releases)
[**VERSÕES NIGHTLY (EM DESENVOLVIMENTO)**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
[<img src="https://f-droid.org/badge/get-it-on.png"
alt="Transfira no F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Transfira no Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Dependências
As versões para ambiente de trabalho usam Flutter ou Sciter (descontinuado) para a interface gráfica (GUI). Este tutorial é apenas para o Sciter, por ser mais fácil e acessível para começar. Consulte o nosso [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) para instruções de compilação da versão Flutter.
Por favor transfira a biblioteca dinâmica do Sciter por conta própria.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Passos básicos para compilar
- Prepare o seu ambiente de desenvolvimento Rust e o ambiente de compilação C++
- Instale o [vcpkg](https://github.com/microsoft/vcpkg) e configure a variável de ambiente `VCPKG_ROOT` corretamente
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static`
- Linux/macOS: `vcpkg install libvpx libyuv opus aom`
- Execute `cargo run`
## [Compilar](https://rustdesk.com/docs/en/dev/build/)
## Como Compilar no Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y zip g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake make libclang-dev ninja-build libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
```
### openSUSE Tumbleweed
```sh
sudo zypper install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libXfixes-devel cmake alsa-lib-devel gstreamer-devel gstreamer-plugins-base-devel xdotool-devel
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel gstreamer1-devel gstreamer1-plugins-base-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pipewire
```
### Instalar o vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2023.04.15
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus aom
```
### Corrigir o libvpx (Para Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Compilar
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
## Como compilar com o Docker
Comece por clonar o repositório e construir o contentor Docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .
```
Depois, cada vez que precisar de compilar a aplicação, execute o seguinte comando:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Note que a primeira compilação pode demorar mais até que as dependências sejam armazenadas em cache, as compilações subsequentes serão mais rápidas. Além disso, se precisar especificar argumentos diferentes para o comando de compilação, poderá fazê-lo no final do comando na posição `<ARGUMENTOS-OPCIONAIS>`. Por exemplo, se quiser compilar uma versão de lançamento (release) otimizada, executaria o comando acima seguido de `--release`. O executável resultante estará disponível na pasta `target` do seu sistema e pode ser executado com:
```sh
target/debug/rustdesk
```
Ou, se estiver a correr o executável de lançamento:
```sh
target/release/rustdesk
```
Certifique-se de que executa estes comandos a partir da raiz do repositório do RustDesk, caso contrário a aplicação poderá não encontrar os recursos necessários. Note também que outros subcomandos do cargo, como `install` ou `run`, não são suportados atualmente por este método, pois instalariam ou executariam o programa dentro do contentor em vez de o fazerem no host.
## Estrutura de Ficheiros
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: codec de vídeo, configuração, wrapper TCP/UDP e algumas outras funções utilitárias partilhadas com o servidor
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, funções fs para transferência de ficheiros, código relacionado com o teclado e com a plataforma utilizado exclusivamente por esta aplicação
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de ecrã
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: controlo de teclado/rato específico da plataforma.
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: implementação de copiar e colar ficheiros para Windows, Linux e macOS.
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: interface Sciter obsoleta (descontinuada).
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: serviços de áudio, área de transferência, entrada e vídeo, e ligações de rede
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: inicia uma ligação entre pares
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunica com o [rustdesk-server](https://github.com/rustdesk/rustdesk-server), aguarda por uma ligação direta remota (TCP hole punching) ou uma ligação retransmitida
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico da plataforma
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: código Flutter para ambiente de trabalho e dispositivos móveis
## Capturas de Ecrã
![Gestor de Ligações](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Ligado a um PC Windows](https://github.com/rustdesk/rustdesk/assets/28412477/9baa91e9-3362-4d06-aa1a-7518edcbd7ea)
![Transferência de Ficheiros](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![Túnel TCP](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
+35 -43
View File
@@ -1,45 +1,39 @@
<p align="center">
<img src="../res/logo-header.svg" alt="RustDesk - Ваш віддалений робочий стіл"><br>
<a href="#кроки-для-збірки">Збірка</a> •
<img src="../res/logo-header.svg" alt="RustDesk - Ваша віддалена стільниця"><br>
<a href="#публічні-сервери">Сервери</a> •
<a href="#кроки-для-збірки">Збирання</a> •
<a href="#як-зібрати-за-допомогою-docker">Docker</a> •
<a href="#структура-файлів">Структура</a> •
<a href="#знімки-екрана">Знімки екрана</a><br>
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>] | [<a href="README-NO.md">Norsk</a>] | [<a href="README-RO.md">Română</a>]<br>
<b>Нам потрібна ваша допомога з перекладом цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу RustDesk</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації RustDesk</a> вашою рідною мовою</b>
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>]<br>
<b>Нам потрібна ваша допомога для перекладу цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації</a> RustDesk вашою рідною мовою</B>
</p>
> [!CAUTION]
> **Застереження щодо неналежного використання:** <br>
> Розробники RustDesk не схвалюють і не підтримують неетичне або незаконне використання цього програмного забезпечення. Неналежне використання, зокрема несанкціонований доступ, керування або втручання в приватність, суворо суперечить нашим правилам. Автори не несуть відповідальності за неналежне використання застосунку.
Спілкування з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
Спілкуйтеся з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-%D0%A0%D0%BE%D0%B7%D1%88%D0%B8%D1%80%D0%B5%D0%BD%D1%96%20%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D1%96%D1%97-blue)](https://rustdesk.com/pricing.html)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Advanced%20Features-blue)](https://rustdesk.com/pricing.html)
RustDesk — ще одне рішення для віддаленого робочого столу, написане на Rust. Працює одразу після запуску й не потребує налаштування. Ви повністю контролюєте свої дані та їхню безпеку. Можна використовувати наш rendezvous/relay-сервер, [налаштувати власний](https://rustdesk.com/server) або [написати власний rendezvous/relay-сервер](https://github.com/rustdesk/rustdesk-server-demo).
Ще один застосунок для віддаленого керування стільницею, написаний на Rust. Працює з коробки, не потребує налаштування. Ви повністю контролюєте свої дані, не турбуючись про безпеку. Ви можете використовувати наш сервер ретрансляції, [налаштувати свій власний](https://rustdesk.com/server), або [написати свій власний сервер ретрансляції](https://github.com/rustdesk/rustdesk-server-demo).
![image](https://user-images.githubusercontent.com/71636191/171661982-430285f0-2e12-4b1d-9957-4a58e375304d.png)
RustDesk вітає внески від усіх охочих. Дивіться [CONTRIBUTING.md](CONTRIBUTING.md), щоб дізнатися, з чого почати.
RustDesk вітає внесок кожного. Ознайомтеся з [CONTRIBUTING.md](CONTRIBUTING.md), щоб отримати допомогу на початковому етапі.
[**FAQ**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**ЧаПи**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**ЗАВАНТАЖИТИ ГОТОВУ ЗБІРКУ**](https://github.com/rustdesk/rustdesk/releases)
[**ЗАВАНТАЖЕННЯ ЗАСТОСУНКУ**](https://github.com/rustdesk/rustdesk/releases)
[**НІЧНІ ЗБІРКИ**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
[<img src="https://f-droid.org/badge/get-it-on.png"
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Get it on Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Залежності
Версії для настільних ОС використовують Flutter або Sciter (застарілий) для графічного інтерфейсу. Ця інструкція стосується лише Sciter, оскільки з ним простіше почати. Для збірки версії на Flutter дивіться наш [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml).
Стільничні версії використовують Flutter чи Sciter (застаріле) для графічного інтерфейсу. Ця інструкція лише для Sciter, оскільки він є більш простим та дружнім для початківців. Перегляньте [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) для збірки версії на Flutter.
Динамічну бібліотеку Sciter потрібно завантажити окремо.
Будь ласка, завантажте динамічну бібліотеку Sciter самостійно.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
@@ -47,14 +41,14 @@ RustDesk вітає внески від усіх охочих. Дивіться
## Кроки для збірки
- Підготуйте середовище розробки Rust і середовище для збирання C++.
- Підготуйте середовище розробки Rust і середовище збирання C++.
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg) і правильно задайте змінну середовища `VCPKG_ROOT`.
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg), і правильно встановіть змінну `VCPKG_ROOT`.
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static
- Linux/macOS: vcpkg install libvpx libyuv opus aom
- Запустіть `cargo run`.
- Запустіть `cargo run`
## [Збирання](https://rustdesk.com/docs/en/dev/build/)
@@ -116,7 +110,7 @@ cd
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
@@ -126,56 +120,54 @@ VCPKG_ROOT=$HOME/vcpkg cargo run
## Як зібрати за допомогою Docker
Спочатку клонуйте репозиторій і зберіть Docker-контейнер:
Почніть з клонування сховища та створення docker-контейнера:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .
```
Після цього щоразу, коли потрібно зібрати застосунок, запускайте таку команду:
Надалі щоразу, коли вам буде потрібно зібрати застосунок, запускайте таку команду:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Перша збірка може тривати довше, доки залежності не буде кешовано. Наступні збірки виконуватимуться швидше. Якщо потрібно передати додаткові аргументи команді збірки, додайте їх після `rustdesk-builder` у кінці команди `docker run`. Наприклад, для оптимізованої release-збірки додайте `--release`. Отриманий виконуваний файл буде доступний у каталозі `target` вашої системи та його можна запустити так:
Зверніть увагу, що перша збірка може зайняти більше часу, перш ніж залежності будуть кешовані, але наступні збірки будуть виконуватися швидше. Крім того, якщо вам потрібно вказати інші аргументи для команди збірки, ви можете зробити це в кінці команди у змінній `<OPTIONAL-ARGS>`. Наприклад, якщо ви хочете створити оптимізовану версію, ви маєте запустити наведену вище команду і в кінці рядка додати `--release`. Отриманий виконуваний файл буде доступний у цільовій папці вашої системи і може бути запущений за допомогою:
```sh
target/debug/rustdesk
```
Або, якщо використовується release-збірка:
Або, якщо ви використовуєте виконуваний файл релізу:
```sh
target/release/rustdesk
```
Запускайте ці команди з кореневого каталогу репозиторію RustDesk, інакше застосунок може не знайти потрібні ресурси. Також зверніть увагу, що інші підкоманди cargo, наприклад `install` або `run`, наразі не підтримуються цим способом, оскільки вони встановлюватимуть або запускатимуть програму всередині контейнера, а не на хост-системі.
Будь ласка, переконайтеся, що ви запускаєте ці команди з кореня сховища RustDesk, інакше додаток не зможе знайти необхідні ресурси. Також зверніть увагу, що інші cargo підкоманди, такі як `install` або `run`, наразі не підтримуються цим методом, оскільки вони будуть встановлювати або запускати програму всередині контейнера, а не на хості.
## Структура файлів
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфігурація, обгортка tcp/udp та інші допоміжні функції, спільні із сервером
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, функції файлової системи для передавання файлів, код клавіатури та платформоспецифічний код, що використовуються лише цим застосунком
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфіг, обгортка tcp/udp, protobuf, функції fs для передавання файлів і деякі інші службові функції
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: захоплення екрана
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: платформоспецифічне керування клавіатурою та мишею
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux і macOS
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: застарілий інтерфейс Sciter (deprecated)
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: служби аудіо, буфера обміну, введення та відео, а також мережеві з'єднання
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: встановлення однорангового з'єднання
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: зв'язок із [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування прямого віддаленого з'єднання (TCP hole punching) або з'єднання через ретранслятор
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: платформоспецифічний код
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для настільних і мобільних платформ
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: специфічне для платформи керування клавіатурою/мишею
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux, macOS.
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: графічний інтерфейс користувача
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: сервіси аудіо/буфера обміну/вводу/відео та мережевих підключень
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: однорангове зʼєднання
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: комунікація з [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування віддаленого прямого (обхід TCP NAT) або ретрансльованого зʼєднання
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: специфічний для платформи код
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для мобільних пристроїв
## Знімки екрана
![Менеджер підключень](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Менеджер зʼєднань](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Підключення до ПК з Windows](https://github.com/rustdesk/rustdesk/assets/28412477/9baa91e9-3362-4d06-aa1a-7518edcbd7ea)
![Передавання файлів](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![Передача файлів](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![TCP-тунелювання](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
![Тунелювання TCP](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
@@ -1,11 +0,0 @@
Applicazione open source per desktop remoto, l'alternativa open source a TeamViewer.
Codice sorgente: https://github.com/rustdesk/rustdesk
Documentazione: https://rustdesk.com/docs/it/client/android/
Per consentire a un dispositivo remoto di controllare il tuo Android tramite mouse o tocco, devi permettere a RustDesk di utilizzare il servizio "Accessibilità". RustDesk utilizza l'API AccessibilityService per implementare il controllo remoto su Android.
Oltre al controllo remoto, puoi anche trasferire facilmente file tra dispositivi Android e PC con RustDesk.
Hai il controllo totale dei tuoi dati, senza preoccupazioni per la sicurezza. Puoi usare il nostro server rendezvous/relay, optare per l'hosting autonomo, o scrivere il tuo server rendezvous/relay. Il server auto-ospitato è gratuito e open source: https://github.com/rustdesk/rustdesk-server
Scarica e installa la versione per desktop da: https://rustdesk.com — potrai quindi accedere e controllare il tuo computer dal cellulare, o controllare il tuo cellulare dal computer.
@@ -1 +0,0 @@
App open source per desktop remoto, alternativa a TeamViewer.
@@ -51,7 +51,6 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
private var minBufferSize = 0
private var audioRecordStat = false
private var audioThread: Thread? = null
private var playbackCapturePending = false
@RequiresApi(Build.VERSION_CODES.M)
fun createAudioRecorder(inVoiceCall: Boolean, mediaProjection: MediaProjection?): Boolean {
@@ -194,17 +193,6 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
return audioRecorder?.audioSource == MediaRecorder.AudioSource.VOICE_COMMUNICATION
}
fun getVoiceCallStartError(): String {
return if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.RECORD_AUDIO
) != PackageManager.PERMISSION_GRANTED) {
"To start a voice call, enable \"Audio capture\" on the \"Share screen\" page."
} else {
"Failed to start voice call."
}
}
fun onVoiceCallStarted(mediaProjection: MediaProjection?): Boolean {
if (!isSupportVoiceCall()) {
return false
@@ -232,7 +220,6 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
if (it.getAudioSource() == MediaRecorder.AudioSource.VOICE_COMMUNICATION) {
return true
}
playbackCapturePending = true
}
audioRecordStat = false
audioThread?.join()
@@ -247,10 +234,11 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
@RequiresApi(Build.VERSION_CODES.M)
fun switchOutVoiceCall(mediaProjection: MediaProjection?): Boolean {
if (!isVoiceCallActive() && !playbackCapturePending) {
return true
audioRecorder?.let {
if (it.getAudioSource() != MediaRecorder.AudioSource.VOICE_COMMUNICATION) {
return true
}
}
playbackCapturePending = true
audioRecordStat = false
audioThread?.join()
@@ -258,11 +246,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
Log.e(logTag, "createAudioRecorder fail")
return false
}
val started = startAudioRecorder()
if (started) {
playbackCapturePending = false
}
return started
return startAudioRecorder()
}
fun tryReleaseAudio() {
@@ -272,7 +256,6 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
audioRecordStat = false
audioThread?.join()
audioThread = null
playbackCapturePending = false
}
fun destroy() {
@@ -1,41 +0,0 @@
package com.carriez.flutter_hbb
import android.os.ParcelFileDescriptor
import org.json.JSONObject
import java.io.IOException
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
internal class DocumentDescriptors {
private val descriptors = ConcurrentHashMap<String, ParcelFileDescriptor>()
fun open(descriptor: ParcelFileDescriptor): JSONObject {
val id = UUID.randomUUID().toString()
try {
// Only detach the duplicate: the original carries the provider's close/error channel.
val duplicate = ParcelFileDescriptor.dup(descriptor.fileDescriptor)
descriptors[id] = descriptor
return JSONObject().put("fd", duplicate.detachFd()).put("descriptor", id)
} catch (error: Exception) {
descriptors.remove(id)
try {
descriptor.closeWithError(error.message ?: "Unable to open document")
} catch (closeError: Exception) {
error.addSuppressed(closeError)
}
throw error
}
}
fun close(request: JSONObject): Boolean {
val descriptor = descriptors.remove(request.getString("descriptor"))
?: throw IOException("Document descriptor was already closed")
val error = request.optString("error", "")
if (error.isNotEmpty()) {
descriptor.closeWithError(error)
} else {
descriptor.use { if (it.canDetectErrors()) it.checkError() }
}
return true
}
}
@@ -1,261 +0,0 @@
package com.carriez.flutter_hbb
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Document
import android.util.Log
import java.io.FileNotFoundException
import java.io.IOException
import java.util.UUID
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
internal class DocumentLogs(private val context: Context) {
private val resolver = context.contentResolver
private val prefs = context.getSharedPreferences(DOCUMENT_PREFS, Context.MODE_PRIVATE)
private val appName = context.applicationInfo.loadLabel(context.packageManager).toString()
private val appDirectoryId = "$PARENT_ID/$appName"
private val directoryId = "$appDirectoryId/Logs"
val directoryPath = directoryId.substringAfter(':')
private var output: ParcelFileDescriptor.AutoCloseOutputStream? = null
private var written = 0L
private var openedDay = 0L
private var failure: Exception? = null
private val lock = ReentrantLock()
init {
setEnabled(grant() != null)
}
@androidx.annotation.Keep
private external fun setEnabled(enabled: Boolean)
private fun grant(): Uri? = prefs.getString(LOG_GRANT, null)?.let(Uri::parse)
fun hasPermission(): Boolean {
val uri = grant() ?: return false
if (!isLogGrant(uri)) return false
return resolver.persistedUriPermissions.any {
it.uri == uri && it.isReadPermission && it.isWritePermission
}
}
private fun isLogGrant(uri: Uri): Boolean =
uri.authority == AUTHORITY && DocumentsContract.isTreeUri(uri) &&
DocumentsContract.getTreeDocumentId(uri) in listOf(PARENT_ID, appDirectoryId, directoryId)
private fun isDirectory(uri: Uri): Boolean = try {
resolver.query(uri, arrayOf(Document.COLUMN_MIME_TYPE), null, null, null)?.use {
it.moveToFirst() && it.getString(it.getColumnIndexOrThrow(
Document.COLUMN_MIME_TYPE)) == Document.MIME_TYPE_DIR
} ?: false
} catch (_: FileNotFoundException) {
false
}
private fun containsDirectory(grant: Uri, parentId: String, id: String): Boolean {
val children = DocumentsContract.buildChildDocumentsUriUsingTree(grant, parentId)
val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE)
return resolver.query(children, columns, null, null, null)?.use { cursor ->
checkDocumentListing(cursor, "Unable to list ${parentId.substringAfter(':')}",
"${parentId.substringAfter(':')} is still loading")
while (cursor.moveToNext()) {
if (cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DOCUMENT_ID)) != id) continue
check(cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE)) ==
Document.MIME_TYPE_DIR) { "${id.substringAfter(':')} is not a directory" }
return@use true
}
false
} ?: throw IOException("Unable to list ${parentId.substringAfter(':')}")
}
private fun ensureDirectory(grant: Uri): Uri {
checkDocumentName(appName)
val rootId = DocumentsContract.getTreeDocumentId(grant)
var parent = DocumentsContract.buildDocumentUriUsingTree(grant, rootId)
check(isDirectory(parent)) { "The authorized log folder is unavailable" }
val children = when (rootId) {
PARENT_ID -> listOf(appDirectoryId, directoryId)
appDirectoryId -> listOf(directoryId)
directoryId -> emptyList()
else -> throw IOException("The selected folder does not contain $directoryPath")
}
for (id in children) {
val child = DocumentsContract.buildDocumentUriUsingTree(grant, id)
if (!containsDirectory(grant, DocumentsContract.getDocumentId(parent), id)) {
closeOutput()
val created = DocumentsContract.createDocument(
resolver, parent, Document.MIME_TYPE_DIR, id.substringAfterLast('/'))
?: throw IOException("Unable to create ${id.substringAfter(':')}")
check(DocumentsContract.getDocumentId(created) == id) {
"${id.substringAfter(':')} is not available as a directory"
}
}
parent = child
}
return parent
}
fun select(uri: Uri, flags: Int) = lock.withLock {
require(isLogGrant(uri)) {
"Please select Android → media."
}
val permissions = flags and GRANT_FLAGS
require(permissions == GRANT_FLAGS) { "Read and write access is required for logs" }
setEnabled(false)
resolver.takePersistableUriPermission(uri, permissions)
ensureDirectory(uri)
closeOutput()
check(prefs.edit().putString(LOG_GRANT, uri.toString()).commit()) {
"Unable to remember the log directory"
}
check(ensureReady()) { "Log directory access was revoked" }
}
fun ensureReady(): Boolean = lock.withLock {
setEnabled(false)
if (!hasPermission()) return false
val uri = grant() ?: return false
val root = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri))
if (!isDirectory(root)) return false
ensureDirectory(uri)
failure = null
if (output == null) openNext(uri)
setEnabled(true)
return true
}
fun write(message: String): Boolean {
if (!lock.tryLock()) return false
return try {
writeLocked(message)
} finally {
lock.unlock()
}
}
private fun writeLocked(message: String): Boolean {
val uri = grant() ?: return false
failure?.let { throw IOException("File logging stopped: ${it.message}", it) }
try {
if (output == null && !hasPermission()) {
throw IOException("Log directory access was revoked")
}
if (output == null || written >= MAX_LOG_BYTES || openedDay != currentDay()) {
openNext(uri)
}
val bytes = message.toByteArray(Charsets.UTF_8)
val stream = output ?: throw IOException("The log file is not open")
stream.write(bytes)
written += bytes.size
return true
} catch (error: Exception) {
setEnabled(false)
failure = error
try {
closeOutput()
} catch (closeError: Exception) {
error.addSuppressed(closeError)
}
Log.e("DocumentLogs", "File logging stopped", error)
throw error
}
}
private fun closeOutput() {
val stream = output
output = null
stream?.close()
}
private fun openNext(grant: Uri) {
closeOutput()
val name = "rustdesk-${System.currentTimeMillis()}-${UUID.randomUUID()}.txt"
val document = DocumentsContract.createDocument(
resolver, ensureDirectory(grant), "text/plain", name)
?: throw IOException("Unable to create a log file")
try {
val descriptor = resolver.openFileDescriptor(document, "w")
?: throw IOException("Unable to open the log file")
output = ParcelFileDescriptor.AutoCloseOutputStream(descriptor)
} catch (error: Exception) {
try {
if (!DocumentsContract.deleteDocument(resolver, document)) {
throw IOException("Unable to remove the unopened log file")
}
} catch (cleanupError: Exception) {
error.addSuppressed(cleanupError)
}
throw error
}
written = 0L
openedDay = currentDay()
val logs = files(grant).sortedBy { it.second }
for ((uri, _) in logs.filter { it.first != document }
.take((logs.size - MAX_LOG_FILES).coerceAtLeast(0))) {
try {
if (!DocumentsContract.deleteDocument(resolver, uri)) {
throw IOException("Unable to remove an expired log file")
}
} catch (error: Exception) {
Log.w("DocumentLogs", "Unable to remove an expired log file", error)
}
}
}
private fun files(grant: Uri): List<Pair<Uri, String>> {
val children = DocumentsContract.buildChildDocumentsUriUsingTree(grant, directoryId)
val columns = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_MIME_TYPE)
return resolver.query(children, columns, null, null, null)?.use { cursor ->
checkDocumentListing(cursor, "Unable to list logs", "The log directory is still loading")
val entries = mutableListOf<Pair<Uri, String>>()
while (cursor.moveToNext()) {
if (cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE)) ==
Document.MIME_TYPE_DIR) continue
val name = cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DISPLAY_NAME))
if (!LOG_NAME.matches(name)) continue
val id = cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_DOCUMENT_ID))
entries.add(DocumentsContract.buildDocumentUriUsingTree(grant, id) to name)
}
entries
} ?: throw IOException("Unable to list logs")
}
fun exportTo(destination: Uri): Int {
val uri = grant() ?: return 0
check(hasPermission()) { "Log directory access was revoked" }
val parent = DocumentsContract.buildDocumentUriUsingTree(
destination, DocumentsContract.getTreeDocumentId(destination))
val logs = files(uri)
for ((source, name) in logs) {
val target = DocumentsContract.createDocument(resolver, parent, "text/plain", name)
?: throw IOException("Unable to create an exported log")
val input = resolver.openInputStream(source)
?: throw IOException("Unable to read log $name")
input.use {
val output = resolver.openOutputStream(target, "w")
?: throw IOException("Unable to write log $name")
output.use { destinationStream -> it.copyTo(destinationStream) }
}
}
return logs.size
}
private fun currentDay(): Long = System.currentTimeMillis() / TimeUnit.DAYS.toMillis(1)
companion object {
const val AUTHORITY = "com.android.externalstorage.documents"
const val PARENT_ID = "primary:Android/media"
private const val LOG_GRANT = "log-folder"
private const val GRANT_FLAGS = Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
private const val MAX_LOG_BYTES = 16L * 1024 * 1024
private const val MAX_LOG_FILES = 90
private val LOG_NAME = Regex("rustdesk-[0-9]+-[0-9a-f-]{36}\\.txt")
}
}
@@ -1,143 +0,0 @@
package com.carriez.flutter_hbb
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.provider.DocumentsContract
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import kotlin.concurrent.thread
internal class DocumentPicker(private val activity: Activity) {
private var pending: Pair<MethodChannel.Result, Boolean>? = null
private var pendingLogFolder: MethodChannel.Result? = null
private val storage = (activity.application as MainApplication).documentStorage
fun handle(call: MethodCall, result: MethodChannel.Result): Boolean {
when (call.method) {
"document_require_log_folder" ->
requireLogFolder(result, call.argument<Boolean>("checkOnly") == true)
"document_workspace" -> if (call.argument<Boolean>("share") == true) {
run(result) { storage.shareWorkspace() }
} else {
result.success((activity.getExternalFilesDir(null) ?: activity.filesDir).path)
}
"document_folder" -> pick(result, call.argument<Boolean>("share") == true)
else -> return false
}
return true
}
private fun pick(result: MethodChannel.Result, share: Boolean) {
if (pending != null || pendingLogFolder != null) {
result.error("picker_in_progress", "Another document picker is already open", null)
return
}
try {
val intent = treePickerIntent("primary:Documents")
pending = result to share
activity.startActivityForResult(intent, REQUEST_DOCUMENT)
} catch (error: Exception) {
pending = null
result.error("picker_unavailable", error.message, null)
}
}
fun onResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode == REQUEST_LOG_FOLDER) {
val result = pendingLogFolder ?: return true
pendingLogFolder = null
if (resultCode != Activity.RESULT_OK || data?.data == null) {
result.success(false)
} else {
run(result) {
storage.logs.select(requireNotNull(data.data), data.flags)
true
}
}
return true
}
if (requestCode != REQUEST_DOCUMENT) return false
val (result, share) = pending ?: return true
pending = null
if (resultCode != Activity.RESULT_OK || data == null) {
result.success(null)
return true
}
run(result) {
storage.select(requireNotNull(data.data), data.flags, share).toString()
}
return true
}
fun close() {
pendingLogFolder?.error("picker_closed", "Log directory selection was interrupted", null)
pendingLogFolder = null
pending?.first?.error("picker_closed", "Document selection was interrupted", null)
pending = null
}
private fun run(result: MethodChannel.Result, action: () -> Any?) {
thread {
try {
val value = action()
activity.runOnUiThread { result.success(value) }
} catch (error: Exception) {
activity.runOnUiThread { result.error("document_failed", error.message, null) }
}
}
}
private fun requireLogFolder(result: MethodChannel.Result, checkOnly: Boolean) {
if (pending != null || pendingLogFolder != null) {
result.error("picker_in_progress", "Another document picker is already open", null)
return
}
pendingLogFolder = result
thread {
val ready = runCatching { storage.logs.ensureReady() }
activity.runOnUiThread { completeLogFolderCheck(result, ready, checkOnly) }
}
}
private fun completeLogFolderCheck(
result: MethodChannel.Result, ready: Result<Boolean>, checkOnly: Boolean
) {
if (pendingLogFolder !== result) return
ready.fold(onSuccess = {
if (it || checkOnly) {
pendingLogFolder = null
result.success(it)
} else {
pickLogFolder(result)
}
}, onFailure = {
pendingLogFolder = null
result.error("log_directory_failed", it.message, null)
})
}
private fun treePickerIntent(initialId: String): Intent =
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
putExtra(DocumentsContract.EXTRA_INITIAL_URI,
DocumentsContract.buildDocumentUri(DocumentLogs.AUTHORITY, initialId))
}
}
private fun pickLogFolder(result: MethodChannel.Result) {
try {
activity.startActivityForResult(treePickerIntent(DocumentLogs.PARENT_ID), REQUEST_LOG_FOLDER)
} catch (error: Exception) {
pendingLogFolder = null
result.error("picker_unavailable", error.message, null)
}
}
companion object {
private const val REQUEST_DOCUMENT = 4251
private const val REQUEST_LOG_FOLDER = 4252
}
}
@@ -1,124 +0,0 @@
package com.carriez.flutter_hbb
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Base64
import org.json.JSONObject
import java.io.IOException
private const val TREE_ROOT = "/@rustdesk/tree/"
internal const val DOCUMENT_PREFS = "document-storage"
internal const val DEFAULT_LOCATION = "default-location"
private const val URI_FLAGS = Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
private const val MIN_LOCATION_COMPONENTS = 2
internal fun documentRoot(uri: Uri): String =
"$TREE_ROOT${Base64.encodeToString(uri.toString().toByteArray(Charsets.UTF_8), URI_FLAGS)}"
internal fun checkDocumentName(name: String): String {
require(name.isNotEmpty() && name != "." && name != ".." &&
!name.contains('/') && !name.contains('\\') && !name.contains('\u0000')) {
"Invalid document name"
}
return name
}
internal fun checkDocumentListing(cursor: Cursor, errorMessage: String, loadingMessage: String) {
val extras = cursor.extras
extras.getString(DocumentsContract.EXTRA_ERROR)?.let {
throw IOException("$errorMessage: $it")
}
if (extras.getBoolean(DocumentsContract.EXTRA_LOADING)) {
throw IOException(loadingMessage)
}
}
internal fun documentEntry(name: String, directory: Boolean, size: Long = 0): JSONObject =
JSONObject().put("name", name).put("directory", directory)
.put("size", size).put("modified", 0)
internal class DocumentStorage(private val context: Context) {
private val prefs = context.getSharedPreferences(DOCUMENT_PREFS, Context.MODE_PRIVATE)
private val descriptors = DocumentDescriptors()
val logs = DocumentLogs(context)
fun home(): String? = prefs.getString(DEFAULT_LOCATION, null)
fun shareWorkspace(): String {
check(prefs.edit().remove(DEFAULT_LOCATION).commit()) {
"Unable to remember the shared folder"
}
return (context.getExternalFilesDir(null) ?: context.filesDir).path
}
fun select(uri: Uri, flags: Int, share: Boolean): JSONObject {
require(uri.scheme == "content") { "Invalid document selection" }
val grants = flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
require(grants != 0) { "The selected location has no access grant" }
context.contentResolver.takePersistableUriPermission(uri, grants)
val root = documentRoot(uri)
val backend = DocumentTree(context, uri, descriptors)
val name = checkDocumentName(backend.rootName())
val path = "$root/$name"
if (share) {
check(prefs.edit().putString(DEFAULT_LOCATION, path).commit()) {
"Unable to remember the shared folder"
}
}
return JSONObject().put("path", path).put("name", name)
}
fun backend(path: String): DocumentTree {
require(path.startsWith(TREE_ROOT)) { "Invalid document location" }
val parts = path.removePrefix(TREE_ROOT).split('/')
require(parts.size >= MIN_LOCATION_COMPONENTS) { "Invalid document location" }
parts.forEach(::checkDocumentName)
val uri = Uri.parse(String(Base64.decode(parts.first(), URI_FLAGS), Charsets.UTF_8))
require(uri.scheme == "content") { "Invalid document URI" }
val authorized =
context.contentResolver.persistedUriPermissions.any { it.uri == uri && it.isReadPermission }
check(authorized) {
"Access to this location was revoked. Select it again on the Android device."
}
return DocumentTree(context, uri, descriptors)
}
fun request(request: String): String = try {
JSONObject().put("value", execute(JSONObject(request)) ?: JSONObject.NULL).toString()
} catch (error: Exception) {
JSONObject().put("error", error.message ?: error.javaClass.simpleName).toString()
}
private fun execute(request: JSONObject): Any? {
val operation = request.getString("op")
if (operation == "home") return home()
if (operation == "log_write") return logs.write(request.getString("message"))
if (operation == "close") return descriptors.close(request)
val path = request.getString("path")
val backend = backend(path)
return when (operation) {
"allowed" -> true
"list" -> backend.list(path)
"stat" -> backend.stat(path)
"open" -> backend.open(path)
else -> mutate(request, backend)
}
}
private fun mutate(request: JSONObject, backend: DocumentTree): Any {
val path = request.getString("path")
return when (val operation = request.getString("op")) {
"begin" -> backend.begin(path, request.getBoolean("overwrite"))
"finish" -> backend.finish(request.getJSONObject("token")).let { true }
"discard" -> backend.discard(request.getJSONObject("token")).let { true }
"delete" -> backend.delete(path).let { true }
"mkdir" -> backend.mkdir(path).let { true }
"rename" -> backend.rename(path, checkDocumentName(request.getString("name"))).let { true }
else -> throw IOException("Unsupported document operation: $operation")
}
}
}
@@ -1,197 +0,0 @@
package com.carriez.flutter_hbb
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import android.provider.DocumentsContract.Document
import android.webkit.MimeTypeMap
import org.json.JSONArray
import org.json.JSONObject
import java.io.FileNotFoundException
import java.io.IOException
import java.util.UUID
internal class DocumentTree(
context: Context,
private val grant: Uri,
private val descriptors: DocumentDescriptors
) {
private val root = documentRoot(grant)
private val resolver = context.contentResolver
private val rootUri: Uri get() = DocumentsContract.buildDocumentUriUsingTree(
grant, DocumentsContract.getTreeDocumentId(grant))
private val projection = arrayOf(Document.COLUMN_DOCUMENT_ID, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_MIME_TYPE, Document.COLUMN_SIZE, Document.COLUMN_LAST_MODIFIED)
fun rootName(): String = metadata(rootUri)?.getString("name")
?: throw FileNotFoundException("The selected document no longer exists")
private fun metadata(uri: Uri): JSONObject? = resolver.query(uri, projection, null, null, null)?.use {
if (!it.moveToFirst()) return@use null
val directory = it.getString(MIME_COLUMN) == Document.MIME_TYPE_DIR
val size = if (it.isNull(SIZE_COLUMN)) -1 else it.getLong(SIZE_COLUMN)
documentEntry(it.getString(NAME_COLUMN), directory, size)
.put("modified", it.getLong(MODIFIED_COLUMN) / MILLIS_PER_SECOND).put("uri", uri.toString())
} ?: throw IOException("Unable to query the selected document")
private fun children(uri: Uri): List<Pair<Uri, JSONObject>> {
val query = DocumentsContract.buildChildDocumentsUriUsingTree(
grant, DocumentsContract.getDocumentId(uri))
return resolver.query(query, projection, null, null, null)?.use { cursor ->
checkDocumentListing(cursor, "Unable to list the selected folder",
"The selected folder is still loading. Try again.")
val entries = mutableListOf<Pair<Uri, JSONObject>>()
while (cursor.moveToNext()) {
val child = DocumentsContract.buildDocumentUriUsingTree(grant, cursor.getString(ID_COLUMN))
val name = checkDocumentName(cursor.getString(NAME_COLUMN))
val entry = documentEntry(name, cursor.getString(MIME_COLUMN) == Document.MIME_TYPE_DIR,
if (cursor.isNull(SIZE_COLUMN)) -1 else cursor.getLong(SIZE_COLUMN))
.put("modified", cursor.getLong(MODIFIED_COLUMN) / MILLIS_PER_SECOND)
.put("uri", child.toString())
entries.add(child to entry)
}
entries
} ?: throw IOException("Unable to list the selected folder")
}
private fun relative(path: String): List<String> {
val parts = path.removePrefix("$root/").split('/')
require(path.startsWith("$root/") && parts.first() == rootName()) {
"The selected document was moved or renamed. Select it again."
}
parts.forEach(::checkDocumentName)
return parts.drop(1)
}
private fun resolve(path: String, createParents: Boolean = false): Uri? {
var current = rootUri
for (name in relative(path)) {
val matches = children(current).filter { it.second.getString("name") == name }
check(matches.size <= 1) { "The provider returned multiple documents named $name" }
val child = matches.singleOrNull()
current = child?.first ?: if (createParents) {
val created = DocumentsContract.createDocument(resolver, current, Document.MIME_TYPE_DIR, name)
?: throw IOException("Unable to create folder $name")
check(metadata(created)?.getString("name") == name) {
"The provider cannot preserve folder name: $name"
}
created
} else return null
}
return current
}
fun uri(path: String): Uri = resolve(path)
?: throw FileNotFoundException("Document does not exist: $path")
fun list(path: String): JSONArray = JSONArray(children(uri(path)).map { it.second })
fun stat(path: String): JSONObject? = resolve(path)?.let(::metadata)
fun open(path: String): JSONObject = descriptors.open(
resolver.openFileDescriptor(uri(path), "r") ?: throw IOException("Unable to open document"))
fun begin(path: String, overwrite: Boolean): JSONObject {
val original = resolve(path)
check(original == null || overwrite) { "Document overwrite requires confirmation" }
require(original == null || metadata(original)?.getBoolean("directory") == false) {
"Cannot replace a folder with a file"
}
val parent = resolve(path.substringBeforeLast('/'), true)
?: throw FileNotFoundException("Destination folder no longer exists")
val name = checkDocumentName(path.substringAfterLast('/'))
val temporary = DocumentsContract.createDocument(resolver, parent, mime(name),
temporaryName(name, "download"))
?: throw IOException("Unable to create the receiving file")
try {
val descriptor = resolver.openFileDescriptor(temporary, "rw")
?: throw IOException("Unable to open the receiving file")
return descriptors.open(descriptor).put("uri", temporary.toString())
.put("path", path).put("original", original?.toString() ?: JSONObject.NULL)
} catch (error: Exception) {
try {
check(DocumentsContract.deleteDocument(resolver, temporary)) {
"Unable to remove the receiving file"
}
} catch (cleanup: Exception) {
error.addSuppressed(cleanup)
throw IOException("${error.message ?: error.javaClass.simpleName}; " +
"temporary file cleanup failed: ${cleanup.message}", error)
}
throw error
}
}
fun finish(token: JSONObject) {
val path = token.getString("path")
val name = checkDocumentName(path.substringAfterLast('/'))
val original = resolve(path)
val expected = if (token.isNull("original")) null else token.getString("original")
check(original?.toString() == expected) {
"The destination changed during the transfer; the received data was retained"
}
val backup = original?.let { renameChecked(it, temporaryName(name, "backup")) }
try {
renameChecked(Uri.parse(token.getString("uri")), name)
} catch (error: Exception) {
if (backup != null) {
try { renameChecked(backup, name) } catch (restore: Exception) {
error.addSuppressed(restore)
throw IOException("Publishing failed and the original remains in $backup: ${restore.message}", error)
}
}
throw error
}
if (backup != null && !DocumentsContract.deleteDocument(resolver, backup)) {
throw IOException("File saved, but the previous copy could not be removed: $backup")
}
}
private fun renameChecked(uri: Uri, name: String): Uri {
val renamed = DocumentsContract.renameDocument(resolver, uri, name)
?: throw IOException("Unable to publish the received file; the partial file was retained")
check(metadata(renamed)?.getString("name") == name) { "The provider changed the saved filename" }
return renamed
}
fun discard(token: JSONObject) {
check(DocumentsContract.deleteDocument(resolver, Uri.parse(token.getString("uri")))) {
"Unable to remove the canceled transfer"
}
}
fun delete(path: String) {
require(relative(path).isNotEmpty()) { "Cannot delete a shared root" }
check(DocumentsContract.deleteDocument(resolver, uri(path))) { "Unable to delete document" }
}
fun mkdir(path: String) {
val created = resolve(path, true) ?: throw IOException("Unable to create folder")
check(metadata(created)?.getBoolean("directory") == true) { "The destination is not a folder" }
}
fun rename(path: String, name: String) {
require(relative(path).isNotEmpty()) { "Cannot rename a shared root" }
if (resolve(path.substringBeforeLast('/') + "/" + name) != null) throw IOException(EXISTS_MESSAGE)
renameChecked(uri(path), name)
}
companion object {
private const val ID_COLUMN = 0
private const val NAME_COLUMN = 1
private const val MIME_COLUMN = 2
private const val SIZE_COLUMN = 3
private const val MODIFIED_COLUMN = 4
private const val MILLIS_PER_SECOND = 1000L
const val EXISTS_MESSAGE = "A file already exists at the destination. Rename the file or select another folder."
fun temporaryName(name: String, purpose: String): String {
// Providers can append the MIME extension when renaming; preserve it for temporary files.
val extension = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }
return ".rustdesk-${UUID.randomUUID()}.$purpose$extension"
}
fun mime(name: String): String = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase())
?: "application/octet-stream"
}
}
@@ -50,15 +50,6 @@ const val WHEEL_BUTTON_UP = 34
const val WHEEL_DOWN = 523331
const val WHEEL_UP = 963
// src/common.rs MOUSE_TYPE_WHEEL: the controller sends a wheel tick as a
// MouseEvent with these type bits and the scroll delta in y (y < 0 = down).
const val MOUSE_TYPE_WHEEL = 3
// Wheel-tick travel for MOUSE_TYPE_WHEEL events. Three quarters of the legacy
// WHEEL_STEP; tuned on real devices during review (the full 120px felt too
// far per tick).
const val MOUSE_WHEEL_STEP = 90
const val TOUCH_SCALE_START = 1
const val TOUCH_SCALE = 2
const val TOUCH_SCALE_END = 3
@@ -111,12 +102,6 @@ class InputService : AccessibilityService() {
private val volumeController: VolumeController by lazy { VolumeController(applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager) }
/**
* Handles a remote mouse event on the gesture path. [mask] is the
* button/phase mask of the mouse protocol ([MOUSE_TYPE_WHEEL] ticks carry
* the scroll delta in [_y] instead of a position), x/y the screen-space
* position. Requires API 24 for the gesture APIs.
*/
@RequiresApi(Build.VERSION_CODES.N)
fun onMouseInput(mask: Int, _x: Int, _y: Int) {
val x = max(0, _x)
@@ -199,38 +184,6 @@ class InputService : AccessibilityService() {
return
}
// The controller sends a wheel tick as a MouseEvent with the type bits
// MOUSE_TYPE_WHEEL (src/common.rs) and the scroll delta in _y
// (y < 0 = wheel down); the WHEEL_DOWN/WHEEL_UP masks below are legacy
// values that current controllers never send. Gated to API 24+ like
// the rest of the gesture path - below that, legacy devices take the
// Shizuku backend or a no-op, not this class.
if (mask == MOUSE_TYPE_WHEEL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// A horizontal tick (the controller sends y = 0 when the
// horizontal delta dominates) or a delta truncated to zero is not
// a vertical swipe.
if (_y == 0) {
return
}
if (mouseY < MOUSE_WHEEL_STEP) {
return
}
val path = Path()
path.moveTo(mouseX.toFloat(), mouseY.toFloat())
val deltaY = if (_y < 0) -MOUSE_WHEEL_STEP else MOUSE_WHEEL_STEP
path.lineTo(mouseX.toFloat(), (mouseY + deltaY).toFloat())
val stroke = GestureDescription.StrokeDescription(
path,
0,
WHEEL_DURATION
)
val builder = GestureDescription.Builder()
builder.addStroke(stroke)
wheelActionsQueue.offer(builder.build())
consumeWheelActions()
return
}
if (mask == WHEEL_DOWN) {
if (mouseY < WHEEL_STEP) {
return
@@ -19,7 +19,6 @@ import android.os.Bundle
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import android.media.MediaCodecInfo
import android.media.MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
@@ -36,7 +35,6 @@ import org.json.JSONArray
import org.json.JSONObject
import com.hjq.permissions.XXPermissions
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import kotlin.concurrent.thread
@@ -63,8 +61,7 @@ class MainActivity : FlutterActivity() {
data class ExportFiles(
val sources: List<File>,
val rejected: Int,
val result: MethodChannel.Result,
val documentLogs: Boolean = false
val result: MethodChannel.Result
) : PendingPicker()
}
@@ -74,7 +71,6 @@ class MainActivity : FlutterActivity() {
)
private var pendingPicker: PendingPicker? = null
private val documentPicker by lazy { DocumentPicker(this) }
private var isAudioStart = false
private val audioRecordHandle = AudioRecordHandle(this, { false }, { isAudioStart })
@@ -111,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() {
val intent = Intent(this, PermissionRequestTransparentActivity::class.java).apply {
action = ACT_REQUEST_MEDIA_PROJECTION
@@ -129,7 +116,6 @@ class MainActivity : FlutterActivity() {
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (documentPicker.onResult(requestCode, resultCode, data)) return
if (requestCode == REQ_IMPORT_FILES) {
val pending = pendingPicker as? PendingPicker.ImportFiles ?: return
pendingPicker = null
@@ -226,14 +212,6 @@ class MainActivity : FlutterActivity() {
Log.e(logTag, "Failed to export selected files", e)
failed += pending.sources.size - processed
}
if (pending.documentLogs) {
try {
exported += (application as MainApplication).documentStorage.logs.exportTo(treeUri)
} catch (error: Exception) {
Log.e(logTag, "Failed to export document logs", error)
failed++
}
}
runOnUiThread {
pending.result.success(mapOf("exported" to exported, "failed" to failed))
}
@@ -254,7 +232,6 @@ class MainActivity : FlutterActivity() {
}
override fun onDestroy() {
documentPicker.close()
Log.e(logTag, "onDestroy")
// The process can outlive the UI whenever something keeps it alive:
// MainService, or the accessibility InputService on its own. Only the
@@ -287,7 +264,6 @@ class MainActivity : FlutterActivity() {
private fun initFlutterChannel(flutterMethodChannel: MethodChannel) {
flutterMethodChannel.setMethodCallHandler { call, result ->
if (documentPicker.handle(call, result)) return@setMethodCallHandler
// make sure result will be invoked, otherwise flutter will await forever
when (call.method) {
"init_service" -> {
@@ -627,22 +603,19 @@ class MainActivity : FlutterActivity() {
}
EXPORT_FILES -> {
val paths = (call.arguments as? Map<*, *>)?.get("paths") as? List<*>
val documentLogs = (call.arguments as? Map<*, *>)?.get("documentLogs") == true
if (paths == null || (paths.isEmpty() && !documentLogs)) {
if (paths.isNullOrEmpty()) {
result.error("invalid_source", "The selected files are outside app-scoped storage", null)
} else {
val sources = paths.mapNotNull {
(it as? String)?.let(::canonicalExportSource)
}
val rejected = paths.size - sources.size
if (sources.isEmpty() && (!documentLogs ||
!(application as MainApplication).documentStorage.logs.hasPermission())) {
if (sources.isEmpty()) {
result.success(mapOf("exported" to 0, "failed" to rejected))
} else if (pendingPicker != null) {
result.error("picker_in_progress", "Another document picker is already open", null)
} else {
pendingPicker = PendingPicker.ExportFiles(
sources, rejected, result, documentLogs = documentLogs)
pendingPicker = PendingPicker.ExportFiles(sources, rejected, result)
try {
startActivityForResult(
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
@@ -996,7 +969,7 @@ class MainActivity : FlutterActivity() {
flutterMethodChannel?.invokeMethod("msgbox", mapOf(
"type" to "custom-nook-nocancel-hasclose-error",
"title" to "Voice call",
"text" to audioRecordHandle.getVoiceCallStartError()))
"text" to "Failed to start voice call."))
} else {
Log.d(logTag, "onVoiceCallStarted success")
}
@@ -5,11 +5,6 @@ import android.util.Log
import ffi.FFI
class MainApplication : Application() {
internal val documentStorage by lazy { DocumentStorage(this) }
@androidx.annotation.Keep
fun rustDocumentStorage(request: String): String = documentStorage.request(request)
companion object {
private const val TAG = "MainApplication"
}
@@ -153,13 +153,19 @@ class MainService : Service() {
} else {
if (!switchOutVoiceCall()) {
Log.e(logTag, "switchOutVoiceCall fail")
showVoiceCallError("Failed to switch out voice call.")
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
"type" to "custom-nook-nocancel-hasclose-error",
"title" to "Voice call",
"text" to "Failed to switch out voice call."))
}
}
} else {
if (!switchToVoiceCall()) {
Log.e(logTag, "switchToVoiceCall fail")
showVoiceCallError(audioRecordHandle.getVoiceCallStartError())
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
"type" to "custom-nook-nocancel-hasclose-error",
"title" to "Voice call",
"text" to "Failed to switch to voice call."))
}
}
} catch (e: JSONException) {
@@ -501,15 +507,6 @@ class MainService : Service() {
}
}
private fun showVoiceCallError(message: String) {
Handler(Looper.getMainLooper()).post {
MainActivity.flutterMethodChannel?.invokeMethod("msgbox", mapOf(
"type" to "custom-nook-nocancel-hasclose-error",
"title" to "Voice call",
"text" to message))
}
}
@Synchronized
private fun startMicrophoneCapture(startAudio: () -> Boolean): Boolean {
if (!setMicrophoneForegroundService(true)) {
@@ -2,7 +2,6 @@ package com.carriez.flutter_hbb
import android.app.Activity
import android.content.Intent
import android.media.projection.MediaProjectionConfig
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
@@ -20,13 +19,7 @@ class PermissionRequestTransparentActivity: Activity() {
ACT_REQUEST_MEDIA_PROJECTION -> {
val mediaProjectionManager =
getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
mediaProjectionManager.createScreenCaptureIntent(
MediaProjectionConfig.createConfigForDefaultDisplay()
)
} else {
mediaProjectionManager.createScreenCaptureIntent()
}
val intent = mediaProjectionManager.createScreenCaptureIntent()
startActivityForResult(intent, REQ_REQUEST_MEDIA_PROJECTION)
}
else -> finish()
+57 -66
View File
@@ -154,7 +154,7 @@ prebuild)
.github/workflows/bridge.yml)"
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)"
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
@@ -306,69 +306,67 @@ prebuild)
git apply res/fdroid/patches/*.patch
# Generate bridge files using `FLUTTER_BRIDGE_VERSION`, which may differ
# from the Flutter version used to compile RustDesk library, and restore
# the pubspec later
# If Flutter version used to generate bridge files differs from Flutter
# version used to compile Rustdesk library, generate bridge using the
# `FLUTTER_BRIDGE_VERSION` an restore the pubspec later
# 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
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
prepare_flutter "${FLUTTER_BRIDGE_VERSION}" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
# Unbraced on purpose: F-Droid recipes rewrite the braced form with sed to
# pin a version, but the bridge generator only works with the Flutter
# version bridge.yml uses
prepare_flutter "$FLUTTER_BRIDGE_VERSION" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get --enforce-lockfile
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
# Install Flutter version for RustDesk library build
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
@@ -381,13 +379,6 @@ prebuild)
flutter/android/build.gradle \
flutter/android/app/build.gradle
# Gradle 8 / AGP 8 thrash in the default 1 GiB heap; raise it as CI does
sed \
-i \
-e 's/org.gradle.jvmargs=-Xmx1024M/org.gradle.jvmargs=-Xmx2g/g' \
flutter/android/gradle.properties
# `firebase_analytics` is not in these files now, but we still keep the following lines.
sed \
-7
View File
@@ -1,6 +1,5 @@
import UIKit
import Flutter
import AVFoundation
@main
@objc class AppDelegate: FlutterAppDelegate {
@@ -9,12 +8,6 @@ import AVFoundation
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
do {
// Mix remote audio with other apps while still respecting silent mode.
try AVAudioSession.sharedInstance().setCategory(.ambient)
} catch {
NSLog("Failed to configure audio mixing: %@", error.localizedDescription)
}
dummyMethodToEnforceBundling();
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
@@ -1,72 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/models/platform_model.dart';
String _resolveApiServer({required String api, required String custom}) {
final key = 'resolve-api-server:${jsonEncode([api, custom])}';
final response = jsonDecode(bind.mainGetCommonSync(key: key));
if (response['error'] != null) {
throw FormatException('Failed to resolve API server: ${response['error']}');
}
return response['url'] as String;
}
bool shouldWarnApiServer(String? apiServer) {
final uri = Uri.tryParse(apiServer?.trim() ?? '');
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
return false;
}
return !const {'localhost', '127.0.0.1', '::1'}.contains(uri.host);
}
class ApiServerWarning extends StatelessWidget {
final TextEditingController controller;
final TextEditingController idController;
final String message;
final String emptyMessage;
final String Function({required String api, required String custom})
resolveApiServer;
const ApiServerWarning({
super.key,
required this.controller,
required this.idController,
required this.message,
required this.emptyMessage,
this.resolveApiServer = _resolveApiServer,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: Listenable.merge([controller, idController]),
builder: (context, child) {
final apiServer = controller.text;
final idServer = idController.text;
final String effectiveApiServer;
try {
effectiveApiServer =
resolveApiServer(api: apiServer.trim(), custom: idServer.trim());
} catch (error, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: error,
stack: stack,
context: ErrorDescription('while resolving the API server warning'),
));
return const SizedBox.shrink();
}
if (!shouldWarnApiServer(effectiveApiServer)) {
return const SizedBox.shrink();
}
return Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
controller.text.trim().isEmpty ? emptyMessage : message,
style: TextStyle(color: Colors.orange.shade700),
),
);
},
);
}
}
@@ -271,6 +271,11 @@ class AllPeersLoader {
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
_updateOnlineState(evt);
}
@visibleForTesting
bool applyLastOnlineStateForTesting(List<Peer> peers) {
return _applyLastOnlineState(peers);
}
}
class AutocompletePeerTile extends StatefulWidget {
+38 -110
View File
@@ -2278,12 +2278,9 @@ void changeBot({Function()? callback}) async {
void change2fa({Function()? callback}) async {
if (bind.mainHasValid2FaSync()) {
try {
await bind.mainSetOption(key: "2fa", value: "");
callback?.call();
} catch (error) {
showToast(error.toString());
}
await bind.mainSetOption(key: "2fa", value: "");
await bind.mainClearTrustedDevices();
callback?.call();
return;
}
var new2fa = (await bind.mainGenerate2Fa());
@@ -2798,48 +2795,23 @@ void confrimDeleteTrustedDevicesDialog(
CommonConfirmDialog(gFFI.dialogManager, '${translate('Confirm Delete')}?',
() async {
if (selectedDevices.isEmpty) return;
try {
if (selectedDevices.length == trustedDevices.length) {
await bind.mainClearTrustedDevices();
trustedDevices.clear();
selectedDevices.clear();
} else {
final json = jsonEncode(selectedDevices.map((e) => e.toList()).toList());
await bind.mainRemoveTrustedDevices(json: json);
trustedDevices.removeWhere((element) {
return selectedDevices.contains(element.recordId);
});
selectedDevices.clear();
}
} catch (error) {
showToast(error.toString());
if (selectedDevices.length == trustedDevices.length) {
await bind.mainClearTrustedDevices();
trustedDevices.clear();
selectedDevices.clear();
} else {
final json = jsonEncode(selectedDevices.map((e) => e.toList()).toList());
await bind.mainRemoveTrustedDevices(json: json);
trustedDevices.removeWhere((element) {
return selectedDevices.contains(element.hwid);
});
selectedDevices.clear();
}
});
}
Future<void> renewTrustedDevice(
TrustedDevice device,
RxList<TrustedDevice> trustedDevices,
RxList<Uint8List> selectedDevices) async {
try {
final json = jsonEncode([device.recordId.toList()]);
await bind.mainRenewTrustedDevices(json: json);
final result = await TrustedDevice.get();
selectedDevices.clear();
trustedDevices.assignAll(result);
} catch (error) {
showToast(error.toString());
}
}
void manageTrustedDeviceDialog() async {
late final RxList<TrustedDevice> trustedDevices;
try {
trustedDevices = (await TrustedDevice.get()).obs;
} catch (error) {
showToast(error.toString());
return;
}
RxList<TrustedDevice> trustedDevices = (await TrustedDevice.get()).obs;
RxList<Uint8List> selectedDevices = RxList.empty();
gFFI.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
@@ -2865,67 +2837,25 @@ void manageTrustedDeviceDialog() async {
});
}
Widget trustedDeviceExpiration({
required bool enabled,
required VoidCallback onChanged,
bool showLabel = true,
}) {
final period = bind.mainGetOptionSync(key: kOptionTrustedDeviceExpiration);
const periods = ['1', '7', '30', '90', '0'];
const dropdownHeight = 36.0;
return Align(
alignment: AlignmentDirectional.centerStart,
child: Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (showLabel) Text(translate('Trust duration (days)')),
SizedBox(
width: isDesktop || isWebDesktop ? 140 : 100,
height: dropdownHeight,
child: ComboBox(
keys: periods,
values: ['1', '7', '30', '90', translate('Never')],
initialKey: periods.contains(period) ? period : '90',
enabled: enabled && !isOptionFixed(kOptionTrustedDeviceExpiration),
onChanged: (value) async {
try {
await bind.mainSetOption(
key: kOptionTrustedDeviceExpiration, value: value);
} catch (error) {
showToast(error.toString());
}
onChanged();
},
),
),
],
),
);
}
class TrustedDevice {
late final Uint8List recordId;
late final Uint8List hwid;
late final int time;
late final int expiresAt;
late final String id;
late final String name;
late final String platform;
TrustedDevice.fromJson(Map<String, dynamic> json) {
final recordIdList = json['record_id'] as List<dynamic>;
recordId = Uint8List.fromList(recordIdList.cast<int>());
final hwidList = json['hwid'] as List<dynamic>;
hwid = Uint8List.fromList(hwidList.cast<int>());
time = json['time'];
expiresAt = json['expires_at'];
id = json['id'];
name = json['name'];
platform = json['platform'];
}
String daysRemaining() {
if (expiresAt == 0) return translate('Never');
final remaining = expiresAt - DateTime.now().millisecondsSinceEpoch;
final expiry = time + 90 * 24 * 60 * 60 * 1000;
final remaining = expiry - DateTime.now().millisecondsSinceEpoch;
if (remaining < 0) {
return '0';
}
@@ -2934,11 +2864,18 @@ class TrustedDevice {
static Future<List<TrustedDevice>> get() async {
final List<TrustedDevice> devices = List.empty(growable: true);
final devicesJson = await bind.mainGetTrustedDevices();
final result = json.decode(devicesJson) as Map<String, dynamic>;
final devicesList = result['devices'] as List;
for (final device in devicesList) {
devices.add(TrustedDevice.fromJson(device));
try {
final devicesJson = await bind.mainGetTrustedDevices();
if (devicesJson.isNotEmpty) {
final devicesList = json.decode(devicesJson);
if (devicesList is List) {
for (var device in devicesList) {
devices.add(TrustedDevice.fromJson(device));
}
}
}
} catch (e) {
print(e.toString());
}
devices.sort((a, b) => b.time.compareTo(a.time));
return devices;
@@ -2972,7 +2909,7 @@ Widget trustedDevicesTable(
onChanged: (value) {
if (value == true) {
selectedDevices.clear();
selectedDevices.addAll(devices.map((e) => e.recordId));
selectedDevices.addAll(devices.map((e) => e.hwid));
} else {
selectedDevices.clear();
}
@@ -2986,30 +2923,21 @@ Widget trustedDevicesTable(
rows: devices.map((device) {
return DataRow(cells: [
DataCell(Checkbox(
value: selectedDevices.contains(device.recordId),
value: selectedDevices.contains(device.hwid),
onChanged: (value) {
if (value == null) return;
if (value) {
selectedDevices.remove(device.recordId);
selectedDevices.add(device.recordId);
selectedDevices.remove(device.hwid);
selectedDevices.add(device.hwid);
} else {
selectedDevices.remove(device.recordId);
selectedDevices.remove(device.hwid);
}
},
)),
DataCell(Text(device.platform)),
DataCell(Text(device.id)),
DataCell(Text(device.name)),
DataCell(Row(mainAxisSize: MainAxisSize.min, children: [
Text(device.daysRemaining()),
if (device.expiresAt != 0)
IconButton(
icon: Icon(Icons.refresh),
tooltip: translate('Renew trust'),
onPressed: () =>
renewTrustedDevice(device, devices, selectedDevices),
),
])),
DataCell(Text(device.daysRemaining())),
]);
}).toList(),
)),
@@ -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;
}
+7 -55
View File
@@ -1,5 +1,4 @@
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common/widgets/dialog.dart';
@@ -63,8 +62,6 @@ class _PeerCardState extends State<_PeerCard>
final PeerTabModel peerTabModel = Provider.of(context);
final peer = super.widget.peer;
return GestureDetector(
// Web card actions have their own semantics; preserve pointer double-clicks.
excludeFromSemantics: isWebDesktop,
onDoubleTap: peerTabModel.multiSelectionMode
? null
: () => widget.connect(context, peer.id),
@@ -426,7 +423,7 @@ class _PeerCardState extends State<_PeerCard>
final PeerTabModel peerTabModel = Provider.of(context);
final selected = peerTabModel.isPeerSelected(peer.id);
if (peerTabModel.multiSelectionMode) {
final checkbox = Padding(
return Padding(
padding: const EdgeInsets.all(12),
child: selected
? Icon(
@@ -435,16 +432,7 @@ class _PeerCardState extends State<_PeerCard>
)
: Icon(Icons.check_box_outline_blank),
);
return isWebDesktop
? Semantics(
container: true,
label: formatID(peer.id),
checked: selected,
onTap: () => peerTabModel.select(peer),
child: checkbox)
: checkbox;
} else {
if (isWebDesktop) return _actionMoreWeb(peer);
return InkWell(
child: const Padding(
padding: EdgeInsets.all(12), child: Icon(Icons.more_vert)),
@@ -469,27 +457,19 @@ class _PeerCardState extends State<_PeerCard>
color: MyTheme.accent,
)
: Icon(Icons.check_box_outline_blank);
final checkbox = isWebDesktop
? Semantics(
container: true,
label: formatID(peer.id),
checked: selected,
onTap: () => peerTabModel.select(peer),
child: icon)
: icon;
bool last = peerTabModel.isShiftDown && peer.id == peerTabModel.lastId;
double right = isTile ? 4 : 0;
if (last) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: MyTheme.accent, width: 1)),
child: checkbox,
child: icon,
).marginOnly(right: right);
} else {
return checkbox.marginOnly(right: right);
return icon.marginOnly(right: right);
}
} else {
return isWebDesktop ? _actionMoreWeb(peer) : _actionMore(peer);
return _actionMore(peer);
}
}
@@ -502,20 +482,6 @@ class _PeerCardState extends State<_PeerCard>
onPointerUp: (_) => _showPeerMenu(peer.id),
child: build_more(context));
Widget _actionMoreWeb(Peer peer) => Semantics(
container: true,
button: true,
label: translate('More'),
child: Builder(
builder: (context) => build_more(context, onTap: () {
final box = context.findRenderObject() as RenderBox;
final position =
box.localToGlobal(box.size.center(Offset.zero));
_menuPos = RelativeRect.fromLTRB(
position.dx, position.dy, position.dx, position.dy);
_showPeerMenu(peer.id);
})));
bool _shouldBuildPasswordIcon(Peer peer) {
if (gFFI.peerTabModel.currentTab != PeerTabIndex.ab.index) return false;
if (gFFI.abModel.current.isPersonal()) return false;
@@ -1508,12 +1474,11 @@ Widget getOnline(double rightPadding, bool online) {
radius: 3, backgroundColor: online ? Colors.green : kColorWarn)));
}
Widget build_more(BuildContext context,
{bool invert = false, VoidCallback? onTap}) {
Widget build_more(BuildContext context, {bool invert = false}) {
final RxBool hover = false.obs;
final button = InkWell(
return InkWell(
borderRadius: BorderRadius.circular(14),
onTap: onTap ?? () {},
onTap: () {},
onHover: (value) => hover.value = value,
child: Obx(() => CircleAvatar(
radius: 14,
@@ -1533,19 +1498,6 @@ Widget build_more(BuildContext context,
.titleLarge
?.color
?.withOpacity(0.5)))));
if (onTap == null) return button;
// Serial taps preserve cancellation without waiting for the card's double tap.
return RawGestureDetector(
excludeFromSemantics: true,
gestures: {
SerialTapGestureRecognizer:
GestureRecognizerFactoryWithHandlers<SerialTapGestureRecognizer>(
() => SerialTapGestureRecognizer(
allowedButtonsFilter: (buttons) =>
buttons == kPrimaryButton),
(recognizer) => recognizer.onSerialTapUp = (_) => onTap()),
},
child: button);
}
class TagPainter extends CustomPainter {
@@ -21,7 +21,6 @@ import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:pull_down_button/pull_down_button.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../../common.dart';
import '../../models/platform_model.dart';
@@ -550,28 +549,6 @@ class _PeerTabPageState extends State<PeerTabPage>
});
}
Widget _openWebConsole() {
return _hoverAction(
context: context,
toolTip: translate('ab_web_console_tip'),
child: Icon(
Icons.open_in_new,
size: 18,
),
onTap: () async {
final url = await bind.mainGetApiServer();
if (await canLaunchUrlString(url)) {
launchUrlString(url);
}
});
}
bool _showWebConsole(PeerTabModel model) =>
model.currentTab == PeerTabIndex.ab.index &&
gFFI.userModel.isLogin &&
!gFFI.abModel.legacyMode.value &&
gFFI.abModel.current.canWrite();
List<Widget> _landscapeRightActions(BuildContext context) {
final model = Provider.of<PeerTabModel>(context);
return [
@@ -589,10 +566,6 @@ class _PeerTabPageState extends State<PeerTabPage>
offstage: model.currentTab == PeerTabIndex.recent.index,
child: PeerSortDropdown(),
),
Offstage(
offstage: !_showWebConsole(model),
child: _openWebConsole(),
),
Offstage(
offstage: model.currentTab != PeerTabIndex.ab.index,
child: _toggleTags(),
@@ -657,7 +630,6 @@ class _PeerTabPageState extends State<PeerTabPage>
final List<Widget> dynamicActions = [
if (model.currentTabCachedPeers.isNotEmpty) _createMultiSelection(),
if (model.currentTab != PeerTabIndex.recent.index) PeerSortDropdown(),
if (_showWebConsole(model)) _openWebConsole(),
if (model.currentTab == PeerTabIndex.ab.index) _toggleTags()
];
final rightWidth = availableWidth -
+35 -256
View File
@@ -11,7 +11,6 @@ import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/widgets/remote_toolbar.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:flutter_hbb/utils/multi_window_manager.dart';
import 'package:get/get.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);
}
/// 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 {
final Widget child;
final VoidCallback? onPressed;
Widget? trailingIcon;
bool divider;
final String? actionId;
TTextMenu(
{required this.child,
required this.onPressed,
this.trailingIcon,
this.divider = false,
this.actionId});
this.divider = false});
Widget getChild() {
if (trailingIcon != null) {
@@ -185,73 +123,20 @@ class TRadioMenu<T> {
final T value;
final T groupValue;
final ValueChanged<T?>? onChanged;
final String? actionId;
TRadioMenu(
{required this.child,
required this.value,
required this.groupValue,
required this.onChanged,
this.actionId});
required this.onChanged});
}
class TToggleMenu {
final Widget child;
final bool value;
final ValueChanged<bool?>? onChanged;
final String? actionId;
TToggleMenu(
{required this.child,
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;
{required this.child, required this.value, required this.onChanged});
}
handleOsPasswordEditIcon(
@@ -452,17 +337,6 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
final isDefaultConn = ffi.connType == ConnType.defaultConn;
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 = [];
// elevation
if (isDefaultConn &&
@@ -530,8 +404,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
return;
}
await sendClipboardKeystrokes();
},
actionId: kShortcutActionSendClipboardKeystrokes));
}));
}
if (isDefaultConn &&
isWaylandPeer &&
@@ -566,8 +439,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
if (isDefaultConn && isMobile) {
v.add(TTextMenu(
child: Text(translate('Reset canvas')),
onPressed: () => ffi.cursorModel.reset(),
actionId: kShortcutActionResetCanvas));
onPressed: () => ffi.cursorModel.reset()));
}
// https://github.com/rustdesk/rustdesk/pull/9731
@@ -643,8 +515,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
v.add(
TTextMenu(
child: Text('${translate("Insert Ctrl + Alt + Del")}'),
onPressed: () => bind.sessionCtrlAltDel(sessionId: sessionId),
actionId: kShortcutActionSendCtrlAltDel),
onPressed: () => bind.sessionCtrlAltDel(sessionId: sessionId)),
);
}
// restart
@@ -657,8 +528,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
TTextMenu(
child: Text(translate('Restart remote device')),
onPressed: () =>
showRestartRemoteDevice(pi, id, sessionId, ffi.dialogManager),
actionId: kShortcutActionRestartRemote),
showRestartRemoteDevice(pi, id, sessionId, ffi.dialogManager)),
);
}
// insertLock
@@ -666,8 +536,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
v.add(
TTextMenu(
child: Text(translate('Insert Lock')),
onPressed: () => bind.sessionLockScreen(sessionId: sessionId),
actionId: kShortcutActionInsertLock),
onPressed: () => bind.sessionLockScreen(sessionId: sessionId)),
);
}
// blockUserInput
@@ -685,8 +554,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
sessionId: sessionId,
value: '${blockInput.value ? 'un' : ''}block-input');
blockInput.value = !blockInput.value;
},
actionId: kShortcutActionToggleBlockInput));
}));
}
// switchSides
if (isDefaultConn &&
@@ -698,15 +566,13 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
v.add(TTextMenu(
child: Text(translate('Switch Sides')),
onPressed: () =>
showConfirmSwitchSidesDialog(sessionId, id, ffi.dialogManager),
actionId: kShortcutActionSwitchSides));
showConfirmSwitchSidesDialog(sessionId, id, ffi.dialogManager)));
}
// refresh
if (pi.version.isNotEmpty) {
v.add(TTextMenu(
child: Text(translate('Refresh')),
onPressed: () => sessionRefreshVideo(sessionId, pi),
actionId: kShortcutActionRefresh,
));
}
// record
@@ -729,8 +595,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
)
],
),
onPressed: () => ffi.recordingModel.toggle(),
actionId: kShortcutActionToggleRecording));
onPressed: () => ffi.recordingModel.toggle()));
}
// to-do:
@@ -747,14 +612,6 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
onPressed: ffi.ffiModel.timerScreenshot != 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) {
msgBox(
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),
));
}
// 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;
}
@@ -808,26 +653,23 @@ Future<List<TRadioMenu<String>>> toolbarViewStyle(
.then((_) => ffi.canvasModel.updateViewStyle());
}
return _registerRadioMenuShortcuts(ffi, [
return [
TRadioMenu<String>(
child: Text(translate('Scale original')),
value: kRemoteViewStyleOriginal,
groupValue: groupValue,
onChanged: onChanged,
actionId: kShortcutActionViewModeOriginal),
onChanged: onChanged),
TRadioMenu<String>(
child: Text(translate('Scale adaptive')),
value: kRemoteViewStyleAdaptive,
groupValue: groupValue,
onChanged: onChanged,
actionId: kShortcutActionViewModeAdaptive),
onChanged: onChanged),
TRadioMenu<String>(
child: Text(translate('Scale custom')),
value: kRemoteViewStyleCustom,
groupValue: groupValue,
onChanged: onChanged,
actionId: kShortcutActionViewModeCustom)
], ownedActionIds: _kToolbarViewStyleActionIds);
onChanged: onChanged)
];
}
Future<List<TRadioMenu<String>>> toolbarImageQuality(
@@ -839,25 +681,22 @@ Future<List<TRadioMenu<String>>> toolbarImageQuality(
await bind.sessionSetImageQuality(sessionId: ffi.sessionId, value: value);
}
return _registerRadioMenuShortcuts(ffi, [
return [
TRadioMenu<String>(
child: Text(translate('Good image quality')),
value: kRemoteImageQualityBest,
groupValue: groupValue,
onChanged: onChanged,
actionId: kShortcutActionImageQualityBest),
onChanged: onChanged),
TRadioMenu<String>(
child: Text(translate('Balanced')),
value: kRemoteImageQualityBalanced,
groupValue: groupValue,
onChanged: onChanged,
actionId: kShortcutActionImageQualityBalanced),
onChanged: onChanged),
TRadioMenu<String>(
child: Text(translate('Optimize reaction time')),
value: kRemoteImageQualityLow,
groupValue: groupValue,
onChanged: onChanged,
actionId: kShortcutActionImageQualityLow),
onChanged: onChanged),
TRadioMenu<String>(
child: Text(translate('Custom')),
value: kRemoteImageQualityCustom,
@@ -867,7 +706,7 @@ Future<List<TRadioMenu<String>>> toolbarImageQuality(
customImageQualityDialog(ffi.sessionId, id, ffi);
},
),
], ownedActionIds: _kToolbarImageQualityActionIds);
];
}
Future<List<TRadioMenu<String>>> toolbarCodec(
@@ -894,10 +733,7 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
}
final visible =
codecs.length == 4 && (codecs[0] || codecs[1] || codecs[2] || codecs[3]);
if (!visible) {
return _registerRadioMenuShortcuts<String>(ffi, [],
ownedActionIds: _kToolbarCodecActionIds);
}
if (!visible) return [];
onChanged(String? value) async {
if (value == null) return;
await bind.sessionPeerOption(
@@ -905,14 +741,12 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
bind.sessionChangePreferCodec(sessionId: sessionId);
}
TRadioMenu<String> radio(
String label, String value, bool enabled, String actionId) {
TRadioMenu<String> radio(String label, String value, bool enabled) {
return TRadioMenu<String>(
child: Text(label),
value: value,
groupValue: groupValue,
onChanged: enabled ? onChanged : null,
actionId: actionId);
onChanged: enabled ? onChanged : null);
}
var autoLabel = translate('Auto');
@@ -920,14 +754,14 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
ffi.qualityMonitorModel.data.codecFormat != null) {
autoLabel = '$autoLabel (${ffi.qualityMonitorModel.data.codecFormat})';
}
return _registerRadioMenuShortcuts(ffi, [
radio(autoLabel, 'auto', true, kShortcutActionCodecAuto),
if (codecs[0]) radio('VP8', 'vp8', codecs[0], kShortcutActionCodecVp8),
radio('VP9', 'vp9', true, kShortcutActionCodecVp9),
if (codecs[1]) radio('AV1', 'av1', codecs[1], kShortcutActionCodecAv1),
if (codecs[2]) radio('H264', 'h264', codecs[2], kShortcutActionCodecH264),
if (codecs[3]) radio('H265', 'h265', codecs[3], kShortcutActionCodecH265),
], ownedActionIds: _kToolbarCodecActionIds);
return [
radio(autoLabel, 'auto', true),
if (codecs[0]) radio('VP8', 'vp8', codecs[0]),
radio('VP9', 'vp9', true),
if (codecs[1]) radio('AV1', 'av1', codecs[1]),
if (codecs[2]) radio('H264', 'h264', codecs[2]),
if (codecs[3]) radio('H265', 'h265', codecs[3]),
];
}
Future<List<TToggleMenu>> toolbarCursor(
@@ -952,7 +786,6 @@ Future<List<TToggleMenu>> toolbarCursor(
v.add(TToggleMenu(
child: Text(translate('Show remote cursor')),
value: state.value,
actionId: kShortcutActionToggleShowRemoteCursor,
onChanged: enabled && !lockState.value
? (value) async {
if (value == null) return;
@@ -989,7 +822,6 @@ Future<List<TToggleMenu>> toolbarCursor(
v.add(TToggleMenu(
child: Text(translate('Follow remote cursor')),
value: value,
actionId: kShortcutActionToggleFollowRemoteCursor,
onChanged: (value) async {
if (value == null) return;
await bind.sessionToggleOption(sessionId: sessionId, value: option);
@@ -1018,7 +850,6 @@ Future<List<TToggleMenu>> toolbarCursor(
v.add(TToggleMenu(
child: Text(translate('Follow remote window focus')),
value: value,
actionId: kShortcutActionToggleFollowRemoteWindow,
onChanged: (value) async {
if (value == null) return;
await bind.sessionToggleOption(sessionId: sessionId, value: option);
@@ -1036,7 +867,6 @@ Future<List<TToggleMenu>> toolbarCursor(
v.add(TToggleMenu(
child: Text(translate('Zoom cursor')),
value: peerState.value,
actionId: kShortcutActionToggleZoomCursor,
onChanged: (value) async {
if (value == null) return;
await bind.sessionToggleOption(sessionId: sessionId, value: option);
@@ -1045,8 +875,7 @@ Future<List<TToggleMenu>> toolbarCursor(
},
));
}
return _registerToggleMenuShortcuts(ffi, v,
ownedActionIds: _kToolbarCursorActionIds);
return v;
}
Future<List<TToggleMenu>> toolbarDisplayToggle(
@@ -1062,7 +891,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
final option = 'show-quality-monitor';
v.add(TToggleMenu(
value: bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option),
actionId: kShortcutActionToggleQualityMonitor,
onChanged: (value) async {
if (value == null) return;
await bind.sessionToggleOption(sessionId: sessionId, value: option);
@@ -1076,7 +904,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleMute,
onChanged: (value) {
if (value == null) return;
bind.sessionToggleOption(sessionId: sessionId, value: option);
@@ -1101,7 +928,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
sessionId: sessionId, arg: kOptionEnableFileCopyPaste);
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleEnableFileCopyPaste,
onChanged: enabled
? (value) {
if (value == null) return;
@@ -1120,7 +946,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
if (ffiModel.viewOnly) value = true;
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleDisableClipboard,
onChanged: enabled
? (value) {
if (value == null) return;
@@ -1137,7 +962,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleLockAfterSessionEnd,
onChanged: enabled
? (value) {
if (value == null) return;
@@ -1190,7 +1014,6 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleTrueColor,
onChanged: (value) async {
if (value == null) return;
await bind.sessionToggleOption(sessionId: sessionId, value: option);
@@ -1215,8 +1038,7 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
},
child: Text(translate('View Mode'))));
}
return _registerToggleMenuShortcuts(ffi, v,
ownedActionIds: _kToolbarDisplayToggleActionIds);
return v;
}
var togglePrivacyModeTime = DateTime.now().subtract(const Duration(hours: 1));
@@ -1344,7 +1166,6 @@ List<TToggleMenu> toolbarKeyboardToggles(FFI ffi) {
final enabled = !ffi.ffiModel.viewOnly;
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleSwapCtrlCmd,
onChanged: enabled ? onChanged : null,
child: Text(translate('Swap control-command key'))));
}
@@ -1410,52 +1231,10 @@ List<TToggleMenu> toolbarKeyboardToggles(FFI ffi) {
final enabled = !ffi.ffiModel.viewOnly;
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleSwapLeftRightMouse,
onChanged: enabled ? onChanged : null,
child: Text(translate('swap-left-right-mouse'))));
}
return _registerToggleMenuShortcuts(ffi, 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);
return v;
}
bool showVirtualDisplayMenu(FFI ffi) {
-6
View File
@@ -4,8 +4,6 @@ import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/models/state_model.dart';
import 'package:get/get.dart';
export 'common/widgets/keyboard_shortcuts/shortcut_constants.dart';
const int kMaxVirtualDisplayCount = 4;
const int kAllVirtualDisplay = -1;
@@ -128,8 +126,6 @@ const String kOptionEnableBlockInput = "enable-block-input";
const String kOptionEnablePrivacyMode = "enable-privacy-mode";
const String kOptionEnablePermChangeInAcceptWindow =
"enable-perm-change-in-accept-window";
const String kOptionHideElevateButtonInAcceptWindow =
"hide-elevate-button-in-accept-window";
const String kOptionAllowRemoteConfigModification =
"allow-remote-config-modification";
const String kOptionVerificationMethod = "verification-method";
@@ -182,9 +178,7 @@ const String kOptionEnableIpv6Punch = "enable-ipv6-punch";
const String kOptionAllowSyncClipboardBetweenSessions =
"allow-sync-clipboard-between-sessions";
const String kOptionEnableWebrtc = "enable-webrtc";
const String kOptionRelayFallbackDelay = "relay-fallback-delay";
const String kOptionEnableTrustedDevices = "enable-trusted-devices";
const String kOptionTrustedDeviceExpiration = "trusted-device-expiration-days";
const String kOptionShowVirtualMouse = "show-virtual-mouse";
const String kOptionVirtualMouseScale = "virtual-mouse-scale";
const String kOptionShowVirtualJoystick = "show-virtual-joystick";
@@ -480,10 +480,6 @@ class _DesktopHomePageState extends State<DesktopHomePage>
return buildInstallCard("Permissions", "config_screen", "Configure",
() async {
bind.mainIsCanScreenRecording(prompt: true);
// macOS shows the request prompt only once per app, so later
// presses would do nothing without opening the settings pane.
launchUrl(Uri.parse(
'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'));
watchIsCanScreenRecording = true;
}, help: 'Help', link: translate("doc_mac_permission"));
} else if (!isOutgoingOnly && !bind.mainIsProcessTrusted(prompt: false)) {
@@ -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/consts.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/widgets/remote_toolbar.dart';
import 'package:flutter_hbb/mobile/widgets/dialog.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_hbb/models/printer_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:get/get.dart';
import 'package:provider/provider.dart';
@@ -422,50 +419,11 @@ class _GeneralState extends State<_General> {
if (!isWeb) audio(context),
if (!isWeb) record(context),
if (!isWeb) WaylandCard(),
other(),
if (!bind.isIncomingOnly()) keyboardShortcuts(),
other()
],
).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() {
final current = MyTheme.getThemeModePreference().toShortString();
onChanged(String value) async {
@@ -633,7 +591,13 @@ class _GeneralState extends State<_General> {
isServer: false,
),
],
if (!incomingOnly) ...webrtcOptions(context),
if (!incomingOnly)
_OptionCheckBox(
context,
'Enable WebRTC P2P connection',
kOptionEnableWebrtc,
isServer: false,
),
if (!isWeb && !incomingOnly)
Tooltip(
message: translate('sync-clipboard-between-sessions-tip'),
@@ -923,85 +887,6 @@ class _GeneralState extends State<_General> {
).marginOnly(left: _kContentHMargin);
});
}
// How long an already-connected relay is held back to give the direct WebRTC
// attempt a chance to win. It only means anything while WebRTC is on, so it
// follows the checkbox as an indented sub-option and is hidden outright when
// the box is clear — the shape `directIp` uses for its port.
List<Widget> webrtcOptions(BuildContext context) {
final stored = bind.mainGetLocalOption(key: kOptionRelayFallbackDelay);
final controller = TextEditingController(text: stored);
// What the field holds against what is saved. Apply is offered only while
// the two differ, so an untouched field shows no button at all, and neither
// does one typed back to its saved value or cleared when nothing was saved
// — the state an "edited" flag alone would still call dirty.
final typed = RxString(stored);
final saved = RxString(stored);
return [
_OptionCheckBox(
context,
'Enable WebRTC P2P connection',
kOptionEnableWebrtc,
isServer: false,
update: (_) => setState(() {}),
),
() {
final enabled = mainGetLocalBoolOptionSync(kOptionEnableWebrtc);
final isOptFixed = isOptionFixed(kOptionRelayFallbackDelay);
return Offstage(
offstage: !enabled,
child: Tooltip(
message: translate('relay-fallback-delay-tip'),
child: _SubLabeledWidget(
context,
'Relay fallback delay in seconds',
Row(children: [
SizedBox(
width: 95,
child: TextField(
controller: controller,
enabled: enabled && !isOptFixed,
onChanged: (v) => typed.value = v,
inputFormatters: [
// Seconds, at most one decimal. Clearing the field is
// allowed and restores the built-in default.
FilteringTextInputFormatter.allow(
RegExp(r'^([0-9]|[1-9][0-9])(\.[0-9]?)?$')),
],
decoration: const InputDecoration(
hintText: '2.5',
contentPadding:
EdgeInsets.symmetric(vertical: 12, horizontal: 12),
),
).workaroundFreezeLinuxMint().marginOnly(right: 15),
),
Obx(() => Offstage(
offstage: typed.value.trim() == saved.value.trim(),
child: ElevatedButton(
onPressed: enabled &&
!isOptFixed &&
!typed.value.trim().endsWith('.') &&
double.tryParse(typed.value.trim()) != 0
? () async {
final v = controller.text.trim();
await bind.mainSetLocalOption(
key: kOptionRelayFallbackDelay, value: v);
if (controller.text != v) controller.text = v;
typed.value = v;
saved.value = v;
}
: null,
child: Text(translate('Apply')),
),
))
]),
enabled: enabled && !isOptFixed,
),
),
);
}(),
];
}
}
enum _AccessMode {
@@ -1144,13 +1029,6 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
message: translate("enable-trusted-devices-tip"),
child: _OptionCheckBox(context, "Enable trusted devices",
kOptionEnableTrustedDevices,
optSetter: (key, value) async {
try {
await mainSetBoolOption(key, value);
} catch (error) {
showToast(error.toString());
}
},
enabled: !locked, update: (v) {
setState(() {});
}),
@@ -1168,21 +1046,7 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin {
).marginOnly(left: 30);
return Column(
children: [
tfa,
bot,
trust,
if (mainGetBoolOptionSync(kOptionEnableTrustedDevices))
trustedDeviceExpiration(
enabled: !locked,
onChanged: () {
if (mounted) setState(() {});
},
).marginOnly(
left: _kCheckBoxLeftMargin + 20 + _kContentHSubMargin,
top: _kContentHMargin,
),
],
children: [tfa, bot, trust],
);
}
@@ -2720,8 +2584,6 @@ Widget _OptionCheckBox(
bool isServer = true,
bool Function()? optGetter,
Future<void> Function(String, bool)? optSetter,
// Optional widget rendered between the label and the trailing space.
Widget? trailing,
}) {
getOpt() => optGetter != null
? optGetter()
@@ -2765,23 +2627,11 @@ Widget _OptionCheckBox(
offstage: !ref.value || checkedIcon == null,
child: checkedIcon?.marginOnly(right: 5),
),
// Without `trailing`, keep the original Expanded(Text) layout.
if (trailing == null)
Expanded(
child: Text(
translate(label),
style: TextStyle(color: disabledTextColor(context, enabled)),
))
else ...[
Flexible(
Expanded(
child: Text(
translate(label),
style: TextStyle(color: disabledTextColor(context, enabled)),
),
),
trailing,
const Spacer(),
],
translate(label),
style: TextStyle(color: disabledTextColor(context, enabled)),
))
],
),
).marginOnly(left: _kCheckBoxLeftMargin),
@@ -3188,37 +3038,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
//#region dialogs
@@ -497,12 +497,7 @@ class _FileManagerViewState extends State<FileManagerView> {
},
onExit: (evt) =>
widget._mouseFocusScope.value = MouseFocusScope.none,
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: _onFileListKeyEvent,
child: _buildFileList(context, _fileListScrollController),
),
child: _buildFileList(context, _fileListScrollController),
))
],
),
@@ -1140,7 +1135,6 @@ class _FileManagerViewState extends State<FileManagerView> {
: "${entry.lastModified().toString().replaceAll(".000", "")} ";
var secondaryPosition = RelativeRect.fromLTRB(0, 0, 0, 0);
onTap() {
_keyboardNode.requestFocus();
final items = selectedItems;
// handle double click
if (_checkDoubleClick(entry)) {
@@ -1369,102 +1363,6 @@ class _FileManagerViewState extends State<FileManagerView> {
debugPrint("focused on ${searchResult.first.name}");
}
KeyEventResult _onFileListKeyEvent(FocusNode node, KeyEvent event) {
// A focused child such as a sort header keeps its default keys, e.g.
// Enter to sort.
if (!_keyboardNode.hasPrimaryFocus) return KeyEventResult.ignored;
for (final binding in _fileListKeyBindings().entries) {
if (binding.key.accepts(event, HardwareKeyboard.instance)) {
binding.value();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
Map<ShortcutActivator, VoidCallback> _fileListKeyBindings() {
int all() => controller.directory.value.entries.length;
return {
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSelectionByKey(-1, false),
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSelectionByKey(1, false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): () =>
_moveSelectionByKey(-1, true),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): () =>
_moveSelectionByKey(1, true),
// Unhandled, they would move keyboard focus to the other pane.
const SingleActivator(LogicalKeyboardKey.arrowLeft): () {},
const SingleActivator(LogicalKeyboardKey.arrowRight): () {},
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
_moveSelectionByKey(_pageDelta(false), false),
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
_moveSelectionByKey(_pageDelta(true), false),
const SingleActivator(LogicalKeyboardKey.home): () =>
_moveSelectionByKey(-all(), false),
const SingleActivator(LogicalKeyboardKey.end): () =>
_moveSelectionByKey(all(), false),
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): () =>
_moveSelectionByKey(_pageDelta(false), true),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): () =>
_moveSelectionByKey(_pageDelta(true), true),
const SingleActivator(LogicalKeyboardKey.home, shift: true): () =>
_moveSelectionByKey(-all(), true),
const SingleActivator(LogicalKeyboardKey.end, shift: true): () =>
_moveSelectionByKey(all(), true),
const SingleActivator(LogicalKeyboardKey.enter): _openSelectedDirectory,
const SingleActivator(LogicalKeyboardKey.numpadEnter):
_openSelectedDirectory,
};
}
void _openSelectedDirectory() {
final items = selectedItems.items;
if (items.length != 1 || items.first.isFile) return;
controller.openDirectory(items.first.path);
selectedItems.clear();
}
List<Entry> _filteredEntries() {
final entries = controller.directory.value.entries;
return _searchText.isNotEmpty
? entries.where((element) {
return element.name.contains(_searchText.value);
}).toList(growable: false)
: entries;
}
int _pageDelta(bool down) {
final entries = _filteredEntries();
final items = selectedItems.items;
final index = items.isEmpty ? -1 : entries.indexOf(items.last);
final position = _fileListScrollController.position;
final first = (position.pixels / kDesktopFileTransferRowHeight).ceil();
final last = ((position.pixels + position.viewportDimension) /
kDesktopFileTransferRowHeight)
.floor() -
1;
return pageDelta(
index >= 0 ? index : (down ? -1 : entries.length), first, last, down);
}
void _moveSelectionByKey(int delta, bool extend) {
final filteredEntries = _filteredEntries();
final selection =
navigateSelection(filteredEntries, selectedItems.items, delta, extend);
if (selection.isEmpty) return;
selectedItems.items.assignAll(selection.where((e) => !e.isDrive));
final position = _fileListScrollController.position;
final top =
filteredEntries.indexOf(selection.last) * kDesktopFileTransferRowHeight;
final bottom = top + kDesktopFileTransferRowHeight;
if (top < position.pixels) {
_fileListScrollController.jumpTo(top);
} else if (bottom > position.pixels + position.viewportDimension) {
_fileListScrollController.jumpTo(bottom - position.viewportDimension);
}
}
void _onSelectedChanged(SelectedItems selectedItems, List<Entry> entries,
Entry entry, bool isLocal) {
final isCtrlDown = RawKeyboard.instance.keysPressed
@@ -1819,36 +1717,6 @@ class _FileManagerViewState extends State<FileManagerView> {
// }
}
/// Selection after a navigation key moves it by [delta] rows. A shift range is
/// returned ordered from its anchor to the moved end, so the first and last
/// items of [selected] stand for those two ends on the next press without
/// separate state.
@visibleForTesting
List<Entry> navigateSelection(
List<Entry> entries, List<Entry> selected, int delta, bool extend) {
if (entries.isEmpty) return [];
final current = selected.isEmpty ? -1 : entries.indexOf(selected.last);
// With nothing selected, moving down starts above the first row and moving
// up below the last one, as the Sciter grid did.
final lead = current >= 0 ? current : (delta > 0 ? -1 : entries.length);
final next = (lead + delta).clamp(0, entries.length - 1);
if (!extend || current < 0) return [entries[next]];
final first = entries.indexOf(selected.first);
final anchor = first < 0 ? current : first;
final step = next < anchor ? -1 : 1;
return [for (var i = anchor; i != next + step; i += step) entries[i]];
}
/// Rows a PageUp/PageDown press moves from [lead] while rows [first]..[last]
/// are fully visible: to that edge first, then a page further, as list views
/// do.
@visibleForTesting
int pageDelta(int lead, int first, int last, bool down) {
final page = max(1, last - first);
if (down) return lead < last ? last - lead : page;
return lead > first ? first - lead : -page;
}
Widget buildWindowsThisPC(BuildContext context, [TextStyle? textStyle]) {
final color = Theme.of(context).iconTheme.color?.withOpacity(0.7);
return Row(children: [
+2 -30
View File
@@ -62,15 +62,12 @@ class _InstallPageBody extends StatefulWidget {
class _InstallPageBodyState extends State<_InstallPageBody>
with WindowListener {
static const _printerStatusTimeout = Duration(seconds: 5);
late final TextEditingController controller;
final RxBool startmenu = true.obs;
final RxBool desktopicon = true.obs;
final RxBool printer = false.obs;
final RxBool showProgress = false.obs;
final RxBool btnEnabled = true.obs;
final RxBool cancelEnabled = true.obs;
// todo move to theme.
final buttonStyle = OutlinedButton.styleFrom(
@@ -86,33 +83,10 @@ class _InstallPageBodyState extends State<_InstallPageBody>
printer.value = installOptions['PRINTER'] == '1';
}
Future<void> _loadPrinterStatus() async {
btnEnabled.value = false;
showProgress.value = true;
try {
final status = await bind
.mainGetCommon(key: 'is-printer-installed')
.timeout(_printerStatusTimeout);
printer.value = status == 'true';
if (status != 'true' && status != 'false') {
debugPrint('Failed to check printer installation status: $status');
}
} catch (e) {
printer.value = false;
debugPrint('Failed to check printer installation status: $e');
} finally {
showProgress.value = false;
btnEnabled.value = true;
}
}
@override
void initState() {
windowManager.addListener(this);
super.initState();
if (printer.value) {
_loadPrinterStatus();
}
}
@override
@@ -243,9 +217,8 @@ class _InstallPageBodyState extends State<_InstallPageBody>
() => OutlinedButton.icon(
icon: Icon(Icons.close_rounded, size: 16),
label: Text(translate('Cancel')),
onPressed: cancelEnabled.value
? () => windowManager.close()
: null,
onPressed:
btnEnabled.value ? () => windowManager.close() : null,
style: buttonStyle,
).marginOnly(right: 10),
),
@@ -280,7 +253,6 @@ class _InstallPageBodyState extends State<_InstallPageBody>
void install() {
do_install() {
btnEnabled.value = false;
cancelEnabled.value = false;
showProgress.value = true;
String args = '';
if (startmenu.value) args += ' startmenu';
+153 -127
View File
@@ -17,7 +17,6 @@ import '../../common/widgets/toolbar.dart';
import '../../models/model.dart';
import '../../models/input_model.dart';
import '../../models/platform_model.dart';
import '../../models/shortcut_model.dart';
import '../../common/shared_state.dart';
import '../../utils/image.dart';
import '../widgets/remote_toolbar.dart';
@@ -163,18 +162,6 @@ class _RemotePageState extends State<RemotePage>
_ffi.ffiModel.pi.platform, _ffi.dialogManager);
_ffi.recordingModel
.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.start(
@@ -1018,8 +1005,8 @@ class _RemotePageState extends State<RemotePage>
bool get wantKeepAlive => true;
}
/// Tracks view size and DPR to update CanvasModel.updateViewStyle()
/// and InputModel.updateImageWidgetSize() only when either changes.
/// A widget that tracks the view size and updates CanvasModel.updateViewStyle()
/// and InputModel.updateImageWidgetSize() only when size actually changes.
/// This avoids scheduling post-frame callbacks on every LayoutBuilder rebuild.
class _ViewStyleUpdater extends StatefulWidget {
final CanvasModel canvasModel;
@@ -1039,12 +1026,10 @@ class _ViewStyleUpdater extends StatefulWidget {
class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
Size? _lastSize;
double? _lastDevicePixelRatio;
bool _callbackScheduled = false;
@override
Widget build(BuildContext context) {
final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
return LayoutBuilder(
builder: (context, constraints) {
final maxWidth = constraints.maxWidth;
@@ -1054,9 +1039,8 @@ class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
return widget.child;
}
final newSize = Size(maxWidth, maxHeight);
if (_lastSize != newSize || _lastDevicePixelRatio != devicePixelRatio) {
if (_lastSize != newSize) {
_lastSize = newSize;
_lastDevicePixelRatio = devicePixelRatio;
// Schedule the update for after the current frame to avoid setState during build.
// Use _callbackScheduled flag to prevent accumulating multiple callbacks
// when size changes rapidly before any callback executes.
@@ -1104,7 +1088,6 @@ class ImagePaint extends StatefulWidget {
class _ImagePaintState extends State<ImagePaint> {
bool _lastRemoteCursorMoved = false;
final _cursorDisplayScale = 1.0.obs;
String get id => widget.id;
RxBool get zoomCursor => widget.zoomCursor;
@@ -1118,19 +1101,47 @@ class _ImagePaintState extends State<ImagePaint> {
final m = Provider.of<ImageModel>(context);
var c = Provider.of<CanvasModel>(context);
final s = c.scale;
// Read the live DPR while the canvas's post-frame update is pending.
// CanvasModel caches the DPR and only refreshes it when the view style
// changes, so read it live to follow the window across monitors.
final dpr = MediaQuery.devicePixelRatioOf(context);
bool isViewScaled() =>
c.viewStyle.style == kRemoteViewStyleAdaptive ||
c.viewStyle.style == kRemoteViewStyleCustom;
bool isViewOriginal() => c.viewStyle.style == kRemoteViewStyleOriginal;
mouseRegion({child}) => Obx(() {
double getCursorScale() {
var c = Provider.of<CanvasModel>(context);
if (isDesktop) {
return _getDesktopCursorScale(c, dpr);
} else {
return zoomCursor.value || isViewOriginal() ? s : 1.0;
final cursor = Provider.of<CursorModel>(context);
// Predefined artwork must not inherit the cached remote bitmap's DPI.
final cache = keyboardEnabled.isTrue
? cursor.cache ?? preDefaultCursor.cache
: preForbiddenCursor.cache;
final peerDpr = cache?.pixelRatio ?? 0;
if (isViewScaled() && zoomCursor.isFalse && peerDpr > 0 &&
(!isWeb || widget.ffi.ffiModel.pi.platform == kPeerPlatformMacOS)) {
// Normalize to logical size; Windows takes physical pixels here.
// Web normalizes only macOS's optional Retina image, preserving
// the existing unzoomed sizing policy for other hosts.
return (isWindows ? dpr : 1.0) / peerDpr;
}
// Without density, preserve the legacy unzoomed size. Controller
// DPR alone cannot determine the remote bitmap's logical size.
final imageScale = isViewScaled() && zoomCursor.isTrue
? _cursorImageScale(widget.ffi, cursor, useLocalPointer: true)
: s;
var cursorScale = 1.0;
if (isWindows) {
// debug win10
if (zoomCursor.value && isViewScaled()) {
cursorScale = imageScale * dpr;
}
} else {
if (zoomCursor.value || isViewOriginal()) {
cursorScale = imageScale;
}
}
return cursorScale;
}
return MouseRegion(
@@ -1160,6 +1171,7 @@ class _ImagePaintState extends State<ImagePaint> {
child: child);
});
if (c.imageOverflow.isTrue && c.scrollStyle != ScrollStyle.scrollauto) {
_syncScrollAfterLayout(c);
final paintWidth = c.getDisplayWidth() * s;
final paintHeight = c.getDisplayHeight() * s;
final paintSize = Size(paintWidth, paintHeight);
@@ -1204,70 +1216,25 @@ class _ImagePaintState extends State<ImagePaint> {
}
}
/// Matches desktop cursors to the rendered image and native pixel units.
///
/// Windows cursor pixels are physical; NSCursor/GdkCursor use logical pixels.
/// Unzoomed Adaptive/Custom views preserve macOS cursors' point dimensions.
double _getDesktopCursorScale(CanvasModel c, double dpr) {
final peer = widget.ffi.ffiModel;
if (!zoomCursor.value &&
peer.pi.platform == kPeerPlatformMacOS &&
(c.viewStyle.style == kRemoteViewStyleAdaptive ||
c.viewStyle.style == kRemoteViewStyleCustom)) {
return isWindows ? dpr : 1.0;
}
if (peer.isPeerLinux && peer.pi.currentDisplay == kAllDisplayValue) {
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
// Remove the host output's density without applying canvas zoom.
final scale = 1.0 / _cursorDisplayScale.value;
return isWindows ? scale : scale / dpr;
}
final scale = c.scale / _cursorDisplayScale.value;
return isWindows ? scale * dpr : scale;
}
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
// Original and unzoomed views do not apply canvas zoom.
final scale = _getCursorScaleForDisplay(1.0);
return isWindows ? scale : scale / dpr;
}
final scale = _getCursorScaleForDisplay(c.scale);
return isWindows ? scale * dpr : scale;
}
double _getCursorScaleForDisplay(double scale) {
final peer = widget.ffi.ffiModel;
// All Displays can mix densities; no single display scale applies.
if (peer.pi.currentDisplay == kAllDisplayValue) return scale;
final displays = peer.pi.getCurDisplays();
if (displays.isEmpty) return scale;
if (peer.pi.platform == kPeerPlatformMacOS) {
// macOS sends NSImage.size in points (src/platform/macos.rs:640,682),
// while HiDPI screen frames use backing pixels (libs/scrap/src/quartz/display.rs:37).
return scale * displays.first.scale;
}
if (!peer.isPeerLinux) return scale;
// Match rendering when a Wayland host
// with multiple outputs reports a display scale > 1.
// A single-output host keeps scale at 1.0 to preserve physical uinput
// coordinates, even with OS scaling enabled. This counts host outputs,
// not the selected displays.length.
// See src/server/display_service.rs:650 (update_sync_displays) and
// src/server/drm_capturer.rs:1523 (DRM's matching convention).
return scale / displays.first.scale;
// Layout can change scroll metrics without notification. Compare against this
// build's fractions: a delayed refresh may already have changed the model.
void _syncScrollAfterLayout(CanvasModel canvas) {
// Both supported scrollbar view styles also paint from scroll fractions.
if (canvas.scrollStyle != ScrollStyle.scrolledge &&
canvas.viewStyle.style != kRemoteViewStyleCustom &&
canvas.viewStyle.style != kRemoteViewStyleOriginal) return;
final renderedScroll = (canvas.scrollX, canvas.scrollY);
SchedulerBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
canvas.updateScrollAfterLayout(renderedScroll);
});
}
Widget _buildScrollbarNonTextureRender(
ImageModel m, Size imageSize, double s) {
double sizeScale = s;
if (widget.ffi.ffiModel.isPeerLinux) {
final displays = widget.ffi.ffiModel.pi.getCurDisplays();
if (displays.isNotEmpty) {
sizeScale = s / displays[0].scale;
}
}
return CustomPaint(
size: imageSize,
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: sizeScale),
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: s),
);
}
@@ -1312,14 +1279,11 @@ class _ImagePaintState extends State<ImagePaint> {
top: (displays[i].y - rect.top) * s + offset.dy,
width: displays[i].width * sizeScale,
height: displays[i].height * sizeScale,
child: _trackCursorDisplay(
Obx(() => Texture(
textureId: textureId.value,
filterQuality:
isViewOriginal ? FilterQuality.none : FilterQuality.low,
)),
displays[i],
),
child: Obx(() => Texture(
textureId: textureId.value,
filterQuality:
isViewOriginal ? FilterQuality.none : FilterQuality.low,
)),
));
}
}
@@ -1330,20 +1294,6 @@ class _ImagePaintState extends State<ImagePaint> {
);
}
Widget _trackCursorDisplay(Widget child, Display display) {
final peer = widget.ffi.ffiModel;
if (!isDesktop ||
!peer.isPeerLinux ||
peer.pi.currentDisplay != kAllDisplayValue) {
return child;
}
return MouseRegion(
onEnter: (_) => _cursorDisplayScale.value = display.scale,
onHover: (_) => _cursorDisplayScale.value = display.scale,
child: child,
);
}
MouseCursor _buildCustomCursor(BuildContext context, double scale) {
final cursor = Provider.of<CursorModel>(context);
final cache = cursor.cache ?? preDefaultCursor.cache;
@@ -1471,43 +1421,119 @@ class CursorPaint extends StatelessWidget {
}
}
double cx = c.x;
double cy = c.y;
if (c.viewStyle.style == kRemoteViewStyleOriginal &&
c.scrollStyle == ScrollStyle.scrollbar) {
final imageOffset = _softwareImageOffset(c);
double cx = imageOffset?.dx ?? c.x;
double cy = imageOffset?.dy ?? c.y;
if (c.imageOverflow.isTrue && c.scrollStyle != ScrollStyle.scrollauto) {
final rect = c.parent.target!.ffiModel.rect;
if (rect == null) {
// unreachable!
debugPrint('unreachable! The displays rect is null.');
return Container();
}
if (cx < 0) {
final imageWidth = rect.width * c.scale;
cx = -imageWidth * c.scrollX;
}
if (cy < 0) {
final imageHeight = rect.height * c.scale;
cy = -imageHeight * c.scrollY;
}
// Scrollbar and edge scrolling share a layout that ignores canvas pan offsets.
final imageWidth = rect.width * c.scale;
final imageHeight = rect.height * c.scale;
// Match the video's integer centering on each fitting axis, even if a
// detached scroll controller left a stale fraction before layout sync.
cx = c.size.width < imageWidth
? -imageWidth * c.scrollX
: ((c.size.width - imageWidth) ~/ 2).toDouble();
cy = c.size.height < imageHeight
? -imageHeight * c.scrollY
: ((c.size.height - imageHeight) ~/ 2).toDouble();
}
double x = (m.x - hotx) * c.scale + cx;
double y = (m.y - hoty) * c.scale + cy;
double scale = 1.0;
final isViewOriginal = c.viewStyle.style == kRemoteViewStyleOriginal;
if (zoomCursor.value || isViewOriginal) {
x = m.x - hotx + cx / c.scale;
y = m.y - hoty + cy / c.scale;
scale = c.scale;
final image = m.image ?? preDefaultCursor.image;
// Match native registration's logical minimum for density-aware scaled views.
final logicalMinimum = (m.cache?.pixelRatio ?? 0) > 0 &&
c.viewStyle.style != kRemoteViewStyleOriginal;
final nativePixels = isWindows && !logicalMinimum
? MediaQuery.devicePixelRatioOf(context) : 1.0;
// Show remote cursor follows the image scale, independently of Zoom cursor.
double scale = _cursorImageScale(c.parent.target!, m);
if (image != null && (logicalMinimum || scale * nativePixels != 1.0)) {
final sx = kMinCursorSize / (image.width * nativePixels);
final sy = kMinCursorSize / (image.height * nativePixels);
// Match native resizing: a thin axis must not enlarge the whole cursor.
final minimumScale = sx < sy ? sx : sy;
if (scale < minimumScale) scale = minimumScale;
}
// Anchor the hotspot to the video position even when the minimum size
// makes the artwork scale differ from the video scale.
final x = (m.x * c.scale + cx) / scale - hotx;
final y = (m.y * c.scale + cy) / scale - hoty;
return CustomPaint(
painter: ImagePainter(
image: m.image ?? preDefaultCursor.image,
image: image,
x: x,
y: y,
scale: scale,
useIntegerPosition: false,
),
);
}
/// Match video-origin rounding: source pixels for software, logical pixels
/// for Linux textures. The caller handles scrolling and unrounded origins.
/// Keep cursor positions and hotspots fractional.
Offset? _softwareImageOffset(CanvasModel canvas) {
if (canvas.imageOverflow.isTrue &&
canvas.scrollStyle != ScrollStyle.scrollauto) {
return null;
}
final ffi = canvas.parent.target!;
final peer = ffi.ffiModel;
if (ffi.imageModel.useTextureRender || peer.pi.forceTextureRender) {
// Match Linux's texture origin without rounding the cursor or hotspot.
return isLinux
? Offset(canvas.x.toInt().toDouble(), canvas.y.toInt().toDouble())
: null;
}
var scale = canvas.scale;
final displays = peer.pi.getCurDisplays();
if (peer.isPeerLinux && displays.isNotEmpty) scale /= displays[0].scale;
// Match the origin used by _buildScrollAutoNonTextureRender's ImagePainter.
return Offset(
(canvas.x / scale).toInt() * scale, (canvas.y / scale).toInt() * scale);
}
}
/// Logical pixels per cursor bitmap pixel, matching the video renderer.
/// Linux display geometry, not cursor density, determines this ratio.
/// Native mixed-display cursors use mapped local input; overlays use the host
/// position. Callers apply minimum size, controller DPR and hotspot offsets.
double _cursorImageScale(FFI ffi, CursorModel cursor,
{bool useLocalPointer = false}) {
final canvas = ffi.canvasModel;
final peer = ffi.ffiModel;
if (!peer.isPeerLinux) return canvas.scale;
if (canvas.imageOverflow.isTrue &&
canvas.scrollStyle != ScrollStyle.scrollauto &&
!ffi.imageModel.useTextureRender &&
!peer.pi.forceTextureRender) {
return canvas.scale; // The nontexture scrollbar also paints physical pixels.
}
final displays = peer.pi.getCurDisplays();
if (displays.length == 1) return canvas.scale / displays.first.scale;
final rect = peer.rect;
if (rect != null) {
// Mapped local input is already in host desktop coordinates. CursorModel's
// position is relative to rect, so restore its origin for display lookup.
// Before the first local movement, both paths use the host position.
final position =
(useLocalPointer ? ffi.inputModel.remotePointerPosition.value : null) ??
Offset(cursor.x + rect.left, cursor.y + rect.top);
for (final display in displays) {
// Display origins are desktop coordinates; dimensions are physical pixels.
// Convert the dimensions so these bounds use the same units as position.
if (Rect.fromLTWH(display.x, display.y, display.width / display.scale,
display.height / display.scale).contains(position)) {
return canvas.scale / display.scale;
}
}
}
return canvas.scale;
}
+1 -4
View File
@@ -1073,10 +1073,7 @@ class _CmControlPanel extends StatelessWidget {
final model = Provider.of<ServerModel>(context);
final showElevation = canElevate &&
model.showElevation &&
client.type_() == ClientType.remote &&
bind.mainGetBuildinOption(
key: kOptionHideElevateButtonInAcceptWindow) !=
'Y';
client.type_() == ClientType.remote;
final showAccept = model.approveMode != 'password';
return Column(
mainAxisAlignment: MainAxisAlignment.end,
@@ -1,5 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ListSearchActionListener extends StatelessWidget {
final FocusNode node;
@@ -23,7 +22,7 @@ class ListSearchActionListener extends StatelessWidget {
autofocus: true,
onKeyEvent: (kv) {
final ch = kv.character;
if (ch == null || LogicalKeyboardKey.isControlCharacter(ch)) {
if (ch == null) {
return;
}
final action = buffer.input(ch);
@@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common/widgets/audio_input.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/models/chat_model.dart';
import 'package:flutter_hbb/models/state_model.dart';
@@ -1319,35 +1318,8 @@ class _ControlMenu extends StatelessWidget {
if (e.divider) {
return Divider();
} 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(
child: child,
child: e.child,
onPressed: e.onPressed,
ffi: ffi,
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
void onWindowMoved() {
_saveFrame();
@@ -472,8 +465,6 @@ class _DesktopTabState extends State<DesktopTab>
});
}
if (await _isLinuxWindowClosed()) return;
await _saveFrame(flush: true);
// hide window on close
@@ -481,7 +472,6 @@ class _DesktopTabState extends State<DesktopTab>
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
}
if (await _isLinuxWindowClosed()) return;
// macOS specific workaround, the window is not hiding when in fullscreen.
if (isMacOS && await windowManager.isFullScreen()) {
await windowManager.setFullScreen(false);
@@ -7,49 +7,36 @@ import 'package:flutter_hbb/models/platform_model.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
const _eventKeyUpdateMe = 'update-me';
final _isExtracting = false.obs;
Future<void> _handleUpdateMe(
String releasePageUrl, Map<String, dynamic> evt) async {
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
if (evt.containsKey('error')) {
_showUpdateError(releasePageUrl, evt['error'] as String);
}
}
Future<void> handleUpdate(String releasePageUrl) async {
final dialogClosed = _showVerifyingUpdate();
final String? downloadUrl;
try {
downloadUrl = await waitForUpdateVerification(
bind.mainGetCommon(key: 'verified-download-url-$releasePageUrl'),
dialogClosed,
);
} catch (error) {
_showUpdateError(releasePageUrl, error.toString());
return;
}
if (downloadUrl == null) {
return;
}
final verifiedDownloadUrl = downloadUrl;
if (downloadUrl.startsWith('error:')) {
_showUpdateError(releasePageUrl, downloadUrl.replaceFirst('error:', ''));
void handleUpdate(String releasePageUrl) {
_isExtracting.value = false;
String downloadUrl = releasePageUrl.replaceAll('tag', 'download');
String version = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
final String downloadFile =
bind.mainGetCommonSync(key: 'download-file-$version');
if (downloadFile.startsWith('error:')) {
final error = downloadFile.replaceFirst('error:', '');
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
return;
}
downloadUrl = '$downloadUrl/$downloadFile';
SimpleWrapper downloadId = SimpleWrapper('');
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
gFFI.dialogManager.dismissAll();
gFFI.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
title: Text(translate('Downloading {$appName}')),
content: UpdateProgress(
releasePageUrl, verifiedDownloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
title: Obx(() => Text(translate(_isExtracting.isTrue
? 'Preparing for installation ...'
: 'Downloading {$appName}'))),
content:
UpdateProgress(releasePageUrl, downloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
actions: [
dialogButton('Cancel', onPressed: () async {
if (_isExtracting.isFalse) dialogButton(translate('Cancel'), onPressed: () async {
onCanceled.value();
await bind.mainSetCommon(
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 {
final String releasePageUrl;
final String downloadUrl;
@@ -121,9 +74,9 @@ class UpdateProgressState extends State<UpdateProgress> {
Timer? _timer;
int? _totalSize;
int _downloadedSize = 0;
bool _downloadFinished = false;
int _getDataFailedCount = 0;
final String _eventKeyDownloadNewVersion = 'download-new-version';
final String _eventKeyExtractUpdateDmg = 'extract-update-dmg';
@override
void initState() {
@@ -135,6 +88,11 @@ class UpdateProgressState extends State<UpdateProgress> {
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
replace: true);
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
if (isMacOS) {
platformFFI.registerEventHandler(_eventKeyExtractUpdateDmg,
_eventKeyExtractUpdateDmg, handleExtractUpdateDmg,
replace: true);
}
}
@override
@@ -142,7 +100,10 @@ class UpdateProgressState extends State<UpdateProgress> {
cancelQueryTimer();
platformFFI.unregisterEventHandler(
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
if (isMacOS) {
platformFFI.unregisterEventHandler(
_eventKeyExtractUpdateDmg, _eventKeyExtractUpdateDmg);
}
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();
debugPrint('Download new version error: $error');
debugPrint(
'${isExtractDmg ? "Extract" : "Download"} new version error: $error');
final msgBoxType = 'custom-nocancel-nook-hasclose';
final msgBoxTitle = 'Error';
final msgBoxText = 'download-new-version-failed-tip';
final dialogManager = gFFI.dialogManager;
final releasePageUrl = widget.releasePageUrl;
close() {
dialogManager.dismissAll();
}
jumplink() {
launchUrl(Uri.parse(releasePageUrl));
launchUrl(Uri.parse(widget.releasePageUrl));
dialogManager.dismissAll();
}
retry() {
dialogManager.dismissAll();
handleUpdate(releasePageUrl);
handleUpdate(widget.releasePageUrl);
}
final List<Widget> buttons = [
dialogButton('Download', onPressed: jumplink),
dialogButton('Retry', onPressed: retry),
if (!isExtractDmg) dialogButton('Retry', onPressed: retry),
dialogButton('Close', onPressed: close),
];
dialogManager.dismissAll();
@@ -223,8 +186,6 @@ class UpdateProgressState extends State<UpdateProgress> {
}
} else if (key == 'downloaded_size') {
_downloadedSize = value as int;
} else if (key == 'finished') {
_downloadFinished = value as bool;
} else if (key == 'error') {
if (value != null) {
err = value.toString();
@@ -243,9 +204,7 @@ class UpdateProgressState extends State<UpdateProgress> {
if (err != '') {
_onError(err);
} else {
if (_downloadFinished &&
_totalSize != null &&
_downloadedSize >= _totalSize!) {
if (_totalSize != null && _downloadedSize >= _totalSize!) {
cancelQueryTimer();
bind.mainSetCommon(
key: 'remove-downloader', value: widget.downloadId.value);
@@ -253,7 +212,13 @@ class UpdateProgressState extends State<UpdateProgress> {
_onError('The download file size is 0.');
} else {
setState(() {});
updateMsgBox();
if (isMacOS) {
bind.mainSetCommon(
key: 'extract-update-dmg', value: widget.downloadUrl);
_isExtracting.value = true;
} else {
updateMsgBox();
}
}
} else {
setState(() {});
@@ -262,8 +227,6 @@ class UpdateProgressState extends State<UpdateProgress> {
}
void updateMsgBox() {
final releasePageUrl = widget.releasePageUrl;
final downloadUrl = widget.downloadUrl;
msgBox(
gFFI.sessionId,
'custom-nocancel',
@@ -271,30 +234,30 @@ class UpdateProgressState extends State<UpdateProgress> {
'{$appName}-to-update-tip',
'',
gFFI.dialogManager,
onSubmit: () async {
onSubmit: () {
debugPrint('Downloaded, update to new version now');
platformFFI.registerEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe,
(evt) => _handleUpdateMe(releasePageUrl, evt),
replace: true);
try {
await bind.mainSetCommon(key: 'update-me', value: downloadUrl);
} catch (error) {
platformFFI.unregisterEventHandler(
_eventKeyUpdateMe, _eventKeyUpdateMe);
_showUpdateError(releasePageUrl, error.toString());
}
bind.mainSetCommon(key: 'update-me', value: widget.downloadUrl);
},
submitTimeout: 5,
);
}
Future<void> handleExtractUpdateDmg(Map<String, dynamic> evt) async {
_isExtracting.value = false;
if (evt.containsKey('err') && (evt['err'] as String).isNotEmpty) {
_onError(evt['err'] as String, isExtractDmg: true);
} else {
updateMsgBox();
}
}
@override
Widget build(BuildContext context) {
getValue() => _totalSize == null
? 0.0
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
return LinearProgressIndicator(
value: getValue(),
value: _isExtracting.isTrue ? null : getValue(),
minHeight: 20,
borderRadius: BorderRadius.circular(5),
backgroundColor: Colors.grey[300],
-2
View File
@@ -577,8 +577,6 @@ _registerEventHandler() {
Widget keyListenerBuilder(BuildContext context, Widget? child) {
return RawKeyboardListener(
// Keep this keyboard-only wrapper from taking focus away from web inputs.
includeSemantics: !isWeb,
// `skipTraversal: isWeb` is to fix "Bad state: RenderBox was not laid out: minified:aeL#c19e4"
focusNode: FocusNode(skipTraversal: isWeb),
child: child ?? Container(),
+17 -74
View File
@@ -10,7 +10,6 @@ import 'package:toggle_switch/toggle_switch.dart';
import '../../common.dart';
import '../../common/widgets/dialog.dart';
import '../../consts.dart';
import '../../utils/android_documents.dart';
class FileManagerPage extends StatefulWidget {
FileManagerPage(
@@ -143,29 +142,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
}
}
Future<void> _changeLocalStorage({required bool workspace}) async {
try {
final path = workspace
? await AndroidDocuments.workspace()
: (await AndroidDocuments.selectFolder())?['path'] as String?;
if (path == null || !mounted) return;
final previousHome = model.localController.homePath;
model.localController.homePath = path;
try {
if (await model.localController.openDirectory(path, isBack: true)) {
model.localController.history.clear();
} else {
model.localController.homePath = previousHome;
}
} catch (_) {
model.localController.homePath = previousHome;
rethrow;
}
} catch (error) {
showToast(error.toString());
}
}
Future<void> _exportFile(Entry entry) async {
try {
final exported = await _runAndroidDocumentPicker(() => gFFI
@@ -230,11 +206,9 @@ class _FileManagerPageState extends State<FileManagerPage> {
}
Future<void> _exportLogs() async {
final String home;
try {
home = await AndroidDocuments.workspace();
} catch (error) {
showToast(error.toString());
final home = currentFileController.homePath;
if (home.isEmpty) {
showToast(translate('Failed'));
return;
}
final appDir = PathUtil.join(home, appName, false);
@@ -242,25 +216,22 @@ class _FileManagerPageState extends State<FileManagerPage> {
PathUtil.join(appDir, 'Logs', false),
PathUtil.join(appDir, 'ScreenRecord', false),
].where((p) => File(p).existsSync() || Directory(p).existsSync()).toList();
await _exportPaths(paths, includeDocumentLogs: true);
if (paths.isEmpty) {
showToast(translate('Failed'));
return;
}
await _exportPaths(paths);
}
Future<void> _exportPaths(Iterable<String> paths,
{bool includeDocumentLogs = false}) async {
Future<void> _exportPaths(Iterable<String> paths) async {
try {
final result = await _runAndroidDocumentPicker(() => gFFI
.invokeMethodWithResult<Map<dynamic, dynamic>>(
AndroidChannel.kExportFiles, {
'paths': paths.toList(),
if (includeDocumentLogs) 'documentLogs': true,
}));
final result = await _runAndroidDocumentPicker(() =>
gFFI.invokeMethodWithResult<Map<dynamic, dynamic>>(
AndroidChannel.kExportFiles, {'paths': paths.toList()}));
if (result == null) return;
final exported = result['exported'] as int? ?? 0;
final failed = result['failed'] as int? ?? 0;
if (includeDocumentLogs && exported > 0 && failed > 0) {
showToast('${translate('Successful')}: $exported, '
'${translate('Failed')}: $failed');
} else if (failed > 0 || (includeDocumentLogs && exported == 0)) {
if (failed > 0) {
showToast(translate('Failed'));
} else if (exported > 0) {
showToast(translate('Successful'));
@@ -346,31 +317,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
icon: Icon(Icons.more_vert),
itemBuilder: (context) {
return [
if (isAndroid && showLocal) ...[
PopupMenuItem(
value: 'workspace',
child: Row(
children: [
Icon(Icons.storage_outlined,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text(translate('RustDesk storage')),
],
),
),
PopupMenuItem(
value: 'choose_folder',
child: Row(
children: [
Icon(Icons.folder_open_outlined,
color: Theme.of(context).iconTheme.color),
SizedBox(width: 5),
Text('${translate('Other folders')}…'),
],
),
),
const PopupMenuDivider(),
],
PopupMenuItem(
child: Row(
children: [
@@ -382,7 +328,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
),
value: "refresh",
),
if (isAndroid && !AndroidDocuments.isPath(currentDir.path))
if (isAndroid)
PopupMenuItem(
enabled: showLocal && currentDir.path.isNotEmpty,
value: "import",
@@ -395,7 +341,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
],
),
),
if (isAndroid && !AndroidDocuments.isPath(currentDir.path))
if (isAndroid)
PopupMenuItem(
enabled: showLocal && currentDir.path.isNotEmpty,
value: "import_folder",
@@ -463,9 +409,7 @@ class _FileManagerPageState extends State<FileManagerPage> {
];
},
onSelected: (v) {
if (v == 'workspace' || v == 'choose_folder') {
_changeLocalStorage(workspace: v == 'workspace');
} else if (v == "refresh") {
if (v == "refresh") {
currentFileController.refresh();
} else if (v == "import") {
_importFiles();
@@ -571,7 +515,6 @@ class _FileManagerPageState extends State<FileManagerPage> {
},
actions: [
if (isAndroid &&
!AndroidDocuments.isPath(currentDir.path) &&
selectedItems?.isLocal == true &&
selectedItems?.items.isNotEmpty == true) ...[
if (selectedItems!.items.length == 1 &&
@@ -957,7 +900,7 @@ class _FileManagerViewState extends State<FileManagerView> {
Padding(
padding: EdgeInsets.fromLTRB(30, 5, 30, 0),
child: Text(
AndroidDocuments.displayPath(controller.directory.value.path),
controller.directory.value.path,
style: TextStyle(color: MyTheme.darkGray),
),
),
@@ -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),
),
),
],
),
);
}
}
+15 -78
View File
@@ -21,7 +21,6 @@ import '../../common/widgets/remote_input.dart';
import '../../models/input_model.dart';
import '../../models/model.dart';
import '../../models/platform_model.dart';
import '../../models/shortcut_model.dart';
import '../../utils/image.dart';
import '../widgets/dialog.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 {
RemotePage(
{Key? key,
@@ -134,7 +107,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
});
WakelockManager.enable(_uniqueKey);
_physicalFocusNode.requestFocus();
HardwareKeyboard.instance.addHandler(_handleLocalKeyEvent);
gFFI.inputModel.listenToMouse(true);
gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId);
keyboardSubscription =
@@ -150,19 +122,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
}
_disableAndroidSoftKeyboard(
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);
@@ -183,7 +142,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
@override
Future<void> dispose() async {
HardwareKeyboard.instance.removeHandler(_handleLocalKeyEvent);
WidgetsBinding.instance.removeObserver(this);
// Close the session up-front. `gFFI.close()` below only calls `sessionClose`
// after several awaits (canvas save, image update, the `enable_soft_keyboard`
@@ -217,7 +175,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// `on_voice_call_closed` should be called when the connection is ended.
// The inner logic of `on_voice_call_closed` will check if the voice call is active.
// Only one client is considered here for now.
gFFI.chatModel.onVoiceCallClosed("End connection");
gFFI.chatModel.onVoiceCallClosed("End connetion");
}
@override
@@ -295,10 +253,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
if (isIOS) {
_iosKeyboardWorkaroundTimer?.cancel();
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 100), () {
if (!mounted || gFFI.chatModel.inputNode.hasFocus) return;
if (!mounted) return;
_physicalFocusNode.unfocus();
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 50), () {
if (!mounted || gFFI.chatModel.inputNode.hasFocus) return;
if (!mounted) return;
_physicalFocusNode.requestFocus();
});
});
@@ -377,10 +335,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
} else if (newValue.length < oldValue.length) {
@@ -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) {
final ffiModel = Provider.of<FfiModel>(context);
return RawPointerMouseRegion(
@@ -704,6 +655,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
!gFFI.inputModel.relativeMouseMode.value;
Widget getBodyForMobile() {
final keyboardIsVisible = keyboardVisibilityController.isVisible;
return Container(
color: MyTheme.canvasColor,
child: Stack(children: () {
@@ -714,14 +666,9 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
right: 10,
child: QualityMonitor(gFFI.qualityMonitorModel),
),
Obx(() {
final chatKeyboardRequested =
gFFI.chatModel.softKeyboardRequested.value;
return KeyHelpTools(
keyboardIsVisible: keyboardVisibilityController.isVisible &&
(_showEdit || chatKeyboardRequested),
showGestureHelp: _showGestureHelp);
}),
KeyHelpTools(
keyboardIsVisible: keyboardIsVisible,
showGestureHelp: _showGestureHelp),
SizedBox(
width: 0,
height: 0,
@@ -858,18 +805,9 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
}();
}
void _registerMobileChatShortcut() {
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);
}
onPressedTextChat(String id) {
gFFI.chatModel.changeCurrentKey(MessageKey(id, ChatModel.clientModeID));
gFFI.chatModel.toggleChatOverlay(requestSoftKeyboard: requestSoftKeyboard);
gFFI.chatModel.toggleChatOverlay();
}
showChatOptions(String id) async {
@@ -1037,13 +975,12 @@ class _KeyHelpToolsState extends State<KeyHelpTools> {
@override
Widget build(BuildContext context) {
final keyboard = HardwareKeyboard.instance;
// Keep touch selections visible without physical modifiers opening the bar.
final hasTouchModifier = (inputModel.ctrl && !keyboard.isControlPressed) ||
(inputModel.alt && !keyboard.isAltPressed) ||
(inputModel.shift && !keyboard.isShiftPressed) ||
(inputModel.command && !keyboard.isMetaPressed);
if (!_pin && !hasTouchModifier && !widget.requestShow) {
final hasModifierOn = inputModel.ctrl ||
inputModel.alt ||
inputModel.shift ||
inputModel.command;
if (!_pin && !hasModifierOn && !widget.requestShow) {
gFFI.cursorModel
.keyHelpToolsVisibilityChanged(null, widget.keyboardIsVisible);
return Offstage();
-52
View File
@@ -13,7 +13,6 @@ import '../../common/widgets/dialog.dart';
import '../../consts.dart';
import '../../models/platform_model.dart';
import '../../models/server_model.dart';
import '../../utils/android_documents.dart';
import 'home_page.dart';
class ServerPage extends StatefulWidget implements PageShape {
@@ -574,44 +573,6 @@ class PermissionChecker extends StatefulWidget {
}
class _PermissionCheckerState extends State<PermissionChecker> {
static const _folderOptionIndent = 16.0;
Future<void> _selectFolder() async {
try {
final workspace = await gFFI.dialogManager.show<bool>(
(_, close, __) => CustomAlertDialog(
title: Text(translate('Change Path')),
content: Column(mainAxisSize: MainAxisSize.min, children: [
ListTile(
title: Text(translate('RustDesk storage')),
onTap: () => close(true),
),
ListTile(
title: Text('${translate('Other folders')}…'),
onTap: () => close(false),
),
]),
),
backDismiss: true,
clickMaskDismiss: true);
if (workspace == null) return;
if (workspace) {
showToast(await AndroidDocuments.workspace(share: true));
await bind.setLocalFlutterOption(
k: 'android-file-transfer-folder-setup', v: 'Y');
return;
}
final selected = await AndroidDocuments.selectFolder(share: true);
if (selected != null) {
await bind.setLocalFlutterOption(
k: 'android-file-transfer-folder-setup', v: 'Y');
showToast(AndroidDocuments.displayPath(selected['path'] as String));
}
} catch (error) {
showToast(error.toString());
}
}
@override
Widget build(BuildContext context) {
final serverModel = Provider.of<ServerModel>(context);
@@ -659,19 +620,6 @@ class _PermissionCheckerState extends State<PermissionChecker> {
serverModel.toggleFile,
enabled: !permissionChangeLocked,
),
if (isAndroid &&
!bind.isDisableSettings() &&
!bind.isOutgoingOnly() &&
bind.mainGetBuildinOption(key: kOptionHideSecuritySetting) != 'Y')
ListTile(
dense: true,
contentPadding:
const EdgeInsetsDirectional.only(start: _folderOptionIndent),
title: Text(translate('Change Path')),
trailing: const Icon(Icons.chevron_right),
enabled: !permissionChangeLocked,
onTap: _selectFolder,
),
hasAudioPermission
? PermissionRow(translate("Audio Capture"), serverModel.audioOk,
serverModel.toggleAudio,
+4 -40
View File
@@ -18,10 +18,8 @@ import '../../consts.dart';
import '../../models/model.dart';
import '../../models/platform_model.dart';
import '../widgets/deploy_dialog.dart';
import '../../models/shortcut_model.dart';
import '../widgets/dialog.dart';
import 'home_page.dart';
import 'mobile_keyboard_shortcuts_page.dart';
import 'scan_page.dart';
class SettingsPage extends StatefulWidget implements PageShape {
@@ -359,28 +357,12 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
onToggle: isOptionFixed(kOptionEnableTrustedDevices)
? null
: (v) async {
try {
await mainSetBoolOption(kOptionEnableTrustedDevices, v);
if (!mounted) return;
setState(() {
_enableTrustedDevices = v;
});
} catch (error) {
showToast(error.toString());
}
mainSetBoolOption(kOptionEnableTrustedDevices, v);
setState(() {
_enableTrustedDevices = v;
});
},
),
if (enable2fa && _enableTrustedDevices)
SettingsTile(
title: Text(translate('Trust duration (days)')),
trailing: trustedDeviceExpiration(
enabled: true,
showLabel: false,
onChanged: () {
if (mounted) setState(() {});
},
),
),
if (enable2fa && _enableTrustedDevices)
SettingsTile(
title: Text(translate('Manage trusted devices')),
@@ -915,24 +897,6 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
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())
SettingsTile.switchTile(
title: Text(translate('note-at-conn-end-tip')),
@@ -141,7 +141,7 @@ class _ViewCameraPageState extends State<ViewCameraPage>
// `on_voice_call_closed` should be called when the connection is ended.
// The inner logic of `on_voice_call_closed` will check if the voice call is active.
// Only one client is considered here for now.
gFFI.chatModel.onVoiceCallClosed("End connection");
gFFI.chatModel.onVoiceCallClosed("End connetion");
}
@override
@@ -11,3 +11,10 @@ const terminalKeyboardKeySpacing = 2.0;
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
const terminalKeyboardRow3TrailingPlaceholderCount = 2;
/// Returns the fixed width occupied by a row of equally sized key slots.
double terminalKeyboardRowWidth(int slotCount) {
if (slotCount <= 0) return 0;
return slotCount * terminalKeyboardKeyWidth +
(slotCount - 1) * terminalKeyboardKeySpacing;
}
@@ -1,100 +0,0 @@
import 'package:flutter/material.dart';
import '../../common.dart';
import '../../consts.dart';
import '../../models/model.dart';
import '../../models/platform_model.dart';
import '../../utils/android_documents.dart';
const _setupOption = 'android-file-transfer-folder-setup';
const _folderChoicePadding = EdgeInsets.fromLTRB(12, 12, 12, 0);
const _folderChoiceSpacing = 4.0;
enum _FolderChoice { workspace, other, skip }
Future<bool> showAndroidFileTransferSetup(FFI ffi) async {
if (bind.getLocalFlutterOption(k: _setupOption) == 'Y' ||
!_canConfigureSharedFolder(ffi)) {
return true;
}
try {
final choice = await ffi.dialogManager.show<_FolderChoice>(
(_, close, __) => _setupDialog(close),
backDismiss: true,
forceGlobal: true,
);
if (choice == null) return false;
switch (choice) {
case _FolderChoice.workspace:
await AndroidDocuments.workspace(share: true);
break;
case _FolderChoice.other:
if (await AndroidDocuments.selectFolder(share: true) == null) {
return false;
}
break;
case _FolderChoice.skip:
break;
}
await bind.setLocalFlutterOption(k: _setupOption, v: 'Y');
return true;
} catch (error) {
showToast(error.toString());
return false;
}
}
bool _canConfigureSharedFolder(FFI ffi) =>
!bind.isOutgoingOnly() &&
!bind.isDisableSettings() &&
bind.mainGetBuildinOption(key: kOptionHideSecuritySetting) != 'Y' &&
(!ffi.serverModel.clients.any((client) => !client.disconnected) ||
option2bool(
kOptionEnablePermChangeInAcceptWindow,
bind.mainGetBuildinOption(
key: kOptionEnablePermChangeInAcceptWindow)));
CustomAlertDialog _setupDialog(void Function([dynamic]) close) {
final choiceStyle = OutlinedButton.styleFrom(
alignment: AlignmentDirectional.centerStart,
minimumSize: const Size(0, kMinInteractiveDimension),
);
return CustomAlertDialog(
title: Text(translate('Transfer file')),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(translate('Choose which folder remote devices can access.')),
Padding(
padding: _folderChoicePadding,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
OutlinedButton(
style: choiceStyle,
onPressed: () => close(_FolderChoice.workspace),
child: Text(translate('RustDesk storage')),
),
const SizedBox(height: _folderChoiceSpacing),
OutlinedButton(
style: choiceStyle,
onPressed: () => close(_FolderChoice.other),
child: Text('${translate('Other folders')}…'),
),
],
),
),
],
),
actions: [
TextButton(
onPressed: () => close(_FolderChoice.skip),
child: Text(translate('Skip')),
),
],
onCancel: close,
);
}
+2 -16
View File
@@ -1,7 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
import 'package:flutter_hbb/common/widgets/toolbar.dart';
import 'package:get/get.dart';
@@ -70,8 +69,6 @@ void showServerSettingsWithValue(
ServerConfig serverConfig,
OverlayDialogManager dialogManager,
void Function(VoidCallback)? upSetState) async {
const labelWidth = 120.0;
const labelSpacing = 8.0;
var isInProgress = false;
final idCtrl = TextEditingController(text: serverConfig.idServer);
final relayCtrl = TextEditingController(text: serverConfig.relayServer);
@@ -115,10 +112,10 @@ void showServerSettingsWithValue(
return Row(
children: [
SizedBox(
width: labelWidth,
width: 120,
child: Text(label),
),
SizedBox(width: labelSpacing),
SizedBox(width: 8),
Expanded(
child: serverSettingsTextFormField(
label: label,
@@ -178,17 +175,6 @@ void showServerSettingsWithValue(
return null;
},
),
Padding(
padding: EdgeInsetsDirectional.only(
start: isDesktop || isWeb ? labelWidth + labelSpacing : 0,
),
child: ApiServerWarning(
controller: apiCtrl,
idController: idCtrl,
message: translate('api_server_connection_tip'),
emptyMessage: translate('api_server_empty_tip'),
),
),
SizedBox(height: 8),
buildField('Key', keyCtrl, ''),
if (isInProgress)
@@ -372,8 +372,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
Offset _position = Offset.zero;
bool _isInitialized = false;
bool _isDown = false;
Object? _activePress;
bool _remoteButtonDown = false;
Rect? _lastBlockedRect;
Orientation? _previousOrientation;
@@ -400,11 +398,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
@override
void dispose() {
_activePress = null;
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
if (_lastBlockedRect != null) {
_cursorModel.removeBlockedRect(_lastBlockedRect!);
}
@@ -576,8 +569,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
child: Listener(
onPointerMove: _onBodyPointerMoveUpdate,
onPointerDown: (event) async {
final press = Object();
_activePress = press;
_isDragging = false;
setState(() {
_isDown = true;
@@ -588,8 +579,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = true;
() async {
await _cursorModel.syncCursorPosition();
if (!mounted || !identical(_activePress, press)) return;
_remoteButtonDown = true;
await _inputModel
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
}();
@@ -597,8 +586,6 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
});
},
onPointerUp: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
@@ -617,8 +604,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
}));
} else {
// If it's not a quick tap, it could be a hold or drag.
if (_remoteButtonDown) {
_remoteButtonDown = false;
// If it was a hold, isSpecialHoldDragActive is true.
if (isSpecialHoldDragActive) {
_inputModel
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
@@ -630,16 +617,13 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = false;
},
onPointerCancel: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
});
_tapDownTimer?.cancel();
_tapDownTimer = null;
if (_remoteButtonDown) {
_remoteButtonDown = false;
if (isSpecialHoldDragActive) {
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
isSpecialHoldDragActive = false;
+5 -65
View File
@@ -64,11 +64,8 @@ class ChatModel with ChangeNotifier {
RxBool isWindowFocus = true.obs;
BlockableOverlayState _blockableOverlayState = BlockableOverlayState();
final Rx<VoiceCallStatus> _voiceCallStatus = Rx(VoiceCallStatus.notStarted);
final RxBool _softKeyboardRequested = false.obs;
bool _usingPhysicalChatInput = false;
Rx<VoiceCallStatus> get voiceCallStatus => _voiceCallStatus;
RxBool get softKeyboardRequested => _softKeyboardRequested;
TextEditingController textController = TextEditingController();
RxInt mobileUnreadSum = 0.obs;
@@ -83,8 +80,6 @@ class ChatModel with ChangeNotifier {
@override
void dispose() {
inputNode.removeListener(_updateChatInputControl);
_restoreChatInputControl();
textController.dispose();
super.dispose();
}
@@ -199,18 +194,13 @@ class ChatModel with ChangeNotifier {
}
}
showChatWindowOverlay(
{Offset? chatInitPos, bool requestSoftKeyboard = true}) {
showChatWindowOverlay({Offset? chatInitPos}) {
if (chatWindowOverlayEntry != null) return;
isWindowFocus.value = true;
_blockableOverlayState.setMiddleBlocked(true);
final overlayState = _blockableOverlayState.state;
if (overlayState == null) return;
if (isMobile) {
_softKeyboardRequested.value = requestSoftKeyboard;
gFFI.invokeMethod("enable_soft_keyboard", true);
}
if (isMobile &&
!gFFI.chatModel.currentKey.isOut && // not in remote page
gFFI.chatModel.latestReceivedKey != null) {
@@ -219,8 +209,7 @@ class ChatModel with ChangeNotifier {
}
final overlay = OverlayEntry(builder: (context) {
return Listener(
onPointerDown: (event) {
_requestChatSoftKeyboard(event);
onPointerDown: (_) {
if (!isWindowFocus.value) {
isWindowFocus.value = true;
_blockableOverlayState.setMiddleBlocked(true);
@@ -234,10 +223,6 @@ class ChatModel with ChangeNotifier {
});
overlayState.insert(overlay);
chatWindowOverlayEntry = overlay;
if (isMobile && !requestSoftKeyboard) {
inputNode.addListener(_updateChatInputControl);
_updateChatInputControl();
}
requestChatInputFocus();
}
@@ -246,9 +231,6 @@ class ChatModel with ChangeNotifier {
_blockableOverlayState.setMiddleBlocked(false);
chatWindowOverlayEntry!.remove();
chatWindowOverlayEntry = null;
_softKeyboardRequested.value = false;
inputNode.removeListener(_updateChatInputControl);
_restoreChatInputControl();
return;
}
}
@@ -257,14 +239,13 @@ class ChatModel with ChangeNotifier {
((!(isDesktop || isWebDesktop) && chatIconOverlayEntry == null) ||
chatWindowOverlayEntry == null);
toggleChatOverlay({Offset? chatInitPos, bool requestSoftKeyboard = true}) {
toggleChatOverlay({Offset? chatInitPos}) {
if (_isChatOverlayHide()) {
if (!isMobile) gFFI.invokeMethod("enable_soft_keyboard", true);
gFFI.invokeMethod("enable_soft_keyboard", true);
if (!(isDesktop || isWebDesktop)) {
showChatIconOverlay();
}
showChatWindowOverlay(
chatInitPos: chatInitPos, requestSoftKeyboard: requestSoftKeyboard);
showChatWindowOverlay(chatInitPos: chatInitPos);
} else {
hideChatIconOverlay();
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() {
_voiceCallStatus.value = VoiceCallStatus.waitingForResponse;
}
+8 -111
View File
@@ -4,7 +4,6 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/common/widgets/dialog.dart';
import 'package:flutter_hbb/utils/download_paths.dart';
import 'package:flutter_hbb/utils/event_loop.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as path;
@@ -12,7 +11,6 @@ import 'package:flutter_hbb/web/dummy.dart'
if (dart.library.html) 'package:flutter_hbb/web/web_unique.dart';
import '../consts.dart';
import '../utils/android_documents.dart';
import 'model.dart';
import 'platform_model.dart';
@@ -385,7 +383,6 @@ class FileController {
bool _isPathAllowed(String candidate) {
if (!isAndroid || !isLocal) return true;
if (AndroidDocuments.isPath(candidate)) return true;
if (homePath.isEmpty || candidate.isEmpty) return false;
final home = PathUtil.posixContext.normalize(homePath);
final target = PathUtil.posixContext.normalize(candidate);
@@ -411,15 +408,6 @@ class FileController {
return DirectoryData(directory.value, options.value);
}
Future<void> _restoreWorkspaceHome(String savedDir) async {
if (savedDir.isEmpty || AndroidDocuments.isPath(savedDir)) return;
final workspace = await AndroidDocuments.workspace();
if (PathUtil.posixContext.equals(workspace, savedDir) ||
PathUtil.posixContext.isWithin(workspace, savedDir)) {
homePath = workspace;
}
}
Future<void> onReady() async {
if (isLocal) {
options.value.home = await bind.mainGetHomeDir();
@@ -436,7 +424,6 @@ class FileController {
var savedDir = (await bind.sessionGetPeerOption(
sessionId: sessionId, name: isLocal ? "local_dir" : "remote_dir"));
if (isAndroid && isLocal) await _restoreWorkspaceHome(savedDir);
if (savedDir.isNotEmpty && !_isPathAllowed(savedDir)) {
savedDir = options.value.home;
await bind.sessionPeerOption(
@@ -449,13 +436,7 @@ class FileController {
options.value.home,
};
for (final dir in dirs) {
if (isAndroid && isLocal) await _restoreWorkspaceHome(dir);
if (await _openDirectoryPath(dir, isBack: true)) {
final documentRoot = RegExp(r'^/@rustdesk/tree/[^/]+/[^/]+')
.stringMatch(directory.value.path);
if (isLocal && documentRoot != null) {
homePath = documentRoot;
}
return true;
}
}
@@ -547,9 +528,6 @@ class FileController {
return true;
}
debugPrint("Failed to openDirectory $path: $e");
if (isAndroid && isLocal && AndroidDocuments.isPath(path)) {
showToast(e.toString());
}
return false;
}
}
@@ -586,9 +564,6 @@ class FileController {
}
Future<bool> _goToParentDirectory({bool isBack = false}) async {
if (AndroidDocuments.isRoot(directory.value.path)) {
return false;
}
final isWindows = options.value.isWindows;
final dirPath = directory.value.path;
var parent = PathUtil.dirname(dirPath, isWindows);
@@ -652,17 +627,6 @@ class FileController {
final transferJobIds = <int>[];
for (var from in items.items) {
final jobID = jobController.addTransferJob(from, isRemoteToLocal);
// Keep this check before PathUtil.join: Rust does not receive the selected
// root separately, and Web transfers bypass Rust validation.
if (isRemoteToLocal &&
!DownloadPaths.validName(from.name, windows: isWindows)) {
jobController.jobError({
'id': '$jobID',
'file_num': '0',
'err': 'Invalid file name: ${from.name}',
});
continue;
}
transferJobs.add((from, jobID));
transferJobIds.add(jobID);
}
@@ -687,15 +651,6 @@ class FileController {
return;
}
if (isRemoteToLocal) {
for (final (entry, jobID) in transferJobs) {
if (entry.isDirectory) {
await _downloadEmptyDirectories(entry, jobID, otherSideData);
}
}
return;
}
final List<Entry> entrys = items.items.toList();
var isRemote = isLocal == true ? true : false;
@@ -728,35 +683,6 @@ class FileController {
});
}
Future<void> _downloadEmptyDirectories(
Entry entry, int jobID, DirectoryData destination) async {
try {
final emptyDirs = await fileFetcher.readEmptyDirs(
entry.path, false, destination.options.showHidden);
final localRoot = PathUtil.join(destination.directory.path, entry.name,
destination.options.isWindows);
final paths = emptyDirs
.map((dir) => DownloadPaths.mapDirectory(
entry.path, dir.path, localRoot,
remoteWindows: options.value.isWindows,
localWindows: destination.options.isWindows))
.toList();
for (final path in paths) {
await DownloadPaths.ensureNoLinks(destination.directory.path, path);
}
for (final path in paths) {
await createDirWithRemote(path, false);
}
} on FormatException catch (err) {
await bind.sessionCancelJob(sessionId: sessionId, actId: jobID);
jobController.jobError({
'id': '$jobID',
'file_num': '0',
'err': err.message,
});
}
}
bool _removeCheckboxRemember = false;
Future<void> removeAction(SelectedItems items) async {
@@ -766,7 +692,7 @@ class FileController {
return;
}
final isWindows = options.value.isWindows;
await Future.forEach(items.items.toList(), (Entry item) async {
await Future.forEach(items.items, (Entry item) async {
final jobID = JobController.jobID.next();
var title = "";
var content = "";
@@ -1178,8 +1104,7 @@ class JobController {
}
Future<bool> jobDone(Map<String, dynamic> evt) async {
final waitingForResult = jobResultListener.isListening;
if (waitingForResult) {
if (jobResultListener.isListening) {
jobResultListener.complete(evt);
// return;
}
@@ -1195,11 +1120,6 @@ class JobController {
return true;
}
final job = jobTable[jobIndex];
if (job.type == JobType.transfer &&
job.isRemoteToLocal &&
job.state == JobState.error) {
return true;
}
job.recvJobRes = true;
if (job.type == JobType.deleteFile) {
job.state = JobState.done;
@@ -1230,8 +1150,7 @@ class JobController {
if (job.type == JobType.deleteDir) {
return job.state == JobState.done;
} else {
// An awaiting file-deletion batch refreshes when removeAction finishes.
return job.type != JobType.deleteFile || !waitingForResult;
return true;
}
}
@@ -1529,12 +1448,6 @@ class FileFetcher {
if (!_removeRemoteReadTask(entry.key, task)) continue;
task.completer.completeError(StateError(_kRemoteSessionChangedError));
}
for (final path in remoteEmptyDirsTasks.keys.toList()) {
if (!AndroidDocuments.isPath(path)) continue;
remoteEmptyDirsTasks
.remove(path)
?.completeError(StateError(_kRemoteSessionChangedError));
}
}
_RemoteReadTask _registerRemoteReadTask(String path, bool includeHidden) {
@@ -1575,18 +1488,15 @@ class FileFetcher {
final c = Completer<List<FileDirectory>>();
tasks[path] = c;
final timeout = AndroidDocuments.isPath(path)
? _kRemoteReadDirTimeout
: const Duration(seconds: 2);
Timer(timeout, () {
if (!identical(tasks[path], c)) return;
Timer(Duration(seconds: 2), () {
tasks.remove(path);
if (c.isCompleted) return;
c.completeError("Failed to read empty dirs, timeout");
});
return c.future;
}
Future<FileDirectory> registerReadRecursiveTask(int actID, String path) {
Future<FileDirectory> registerReadRecursiveTask(int actID) {
final tasks = readRecursiveTasks;
if (tasks.containsKey(actID)) {
throw "Failed to registerRemoveTask, already have same ReadRecursive job";
@@ -1594,10 +1504,7 @@ class FileFetcher {
final c = Completer<FileDirectory>();
tasks[actID] = c;
final timeout = AndroidDocuments.isPath(path)
? _kRemoteReadDirTimeout
: const Duration(seconds: 2);
Timer(timeout, () {
Timer(Duration(seconds: 2), () {
tasks.remove(actID);
if (c.isCompleted) return;
c.completeError("Failed to read dir, timeout");
@@ -1679,13 +1586,8 @@ class FileFetcher {
fdJsons.map((fdJson) => FileDirectory.fromJson(fdJson)).toList();
return fds;
} else {
final generation = _remoteSessionGeneration;
await bind.sessionReadRemoteEmptyDirsRecursiveSync(
sessionId: sessionId, path: path, includeHidden: showHidden);
if (AndroidDocuments.isPath(path) &&
generation != _remoteSessionGeneration) {
throw StateError(_kRemoteSessionChangedError);
}
return registerReadEmptyDirsTask(isLocal, path);
}
} catch (e) {
@@ -1699,11 +1601,6 @@ class FileFetcher {
if (isLocal) {
final res = await bind.sessionReadLocalDirSync(
sessionId: sessionId, path: path, showHidden: showHidden);
if (isAndroid && AndroidDocuments.isPath(path)) {
final data = jsonDecode(res);
if (data['error'] != null) throw StateError(data['error'] as String);
return FileDirectory.fromJson(data);
}
final fd = FileDirectory.fromJson(jsonDecode(res));
return fd;
} else {
@@ -1743,7 +1640,7 @@ class FileFetcher {
path: path,
isRemote: !isLocal,
showHidden: showHidden);
return registerReadRecursiveTask(actID, path);
return registerReadRecursiveTask(actID);
} catch (e) {
return Future.error(e);
}
+24 -337
View File
@@ -15,11 +15,8 @@ import 'package:get/get.dart';
import '../../models/model.dart';
import '../../models/platform_model.dart';
import '../../models/shortcut_model.dart';
import '../../models/state_model.dart';
import '../common/widgets/keyboard_shortcuts/shortcut_utils.dart';
import 'input_modifier_utils.dart';
import 'local_flutter_shortcuts.dart';
import 'relative_mouse_model.dart';
import '../common.dart';
import '../consts.dart';
@@ -419,14 +416,6 @@ class InputModel {
final ToReleaseRawKeys toReleaseRawKeys = ToReleaseRawKeys();
final ToReleaseKeys toReleaseKeys = ToReleaseKeys();
late final _localFlutterShortcuts = LocalFlutterShortcutDispatcher(
onTriggered: (action) {
final ffi = parent.target;
if (ffi != null && !ffi.closed) {
ffi.shortcutModel.onTriggered(action);
}
},
);
// trackpad
var _trackpadLastDelta = Offset.zero;
@@ -459,8 +448,12 @@ class InputModel {
// mouse
final isPhysicalMouse = false.obs;
int _lastButtons = 0;
int _pressedMouseButtons = 0;
Offset lastMousePos = Offset.zero;
// Latest local pointer position mapped to absolute remote desktop coordinates.
// Used to select the native cursor's display scale in Linux All Displays mode,
// without waiting for a host position update. Keep it separate from the
// host-reported position used to paint the remote cursor.
final remotePointerPosition = Rxn<Offset>();
int _lastWheelTsUs = 0;
// Wheel acceleration thresholds.
@@ -748,12 +741,7 @@ class InputModel {
}
KeyEventResult handleRawKeyEvent(RawKeyEvent e) {
if (_localFlutterShortcuts.tryDispatchRaw(e)) return KeyEventResult.handled;
if (isViewOnly) {
if (isWeb && !isInputSourceFlutter) return KeyEventResult.ignored;
_tryDispatchRawFlutterShortcut(e, releaseModifiers: false);
return KeyEventResult.handled;
}
if (isViewOnly) return KeyEventResult.handled;
if (isViewCamera) return KeyEventResult.handled;
if (!isInputSourceFlutter) {
if (isDesktop) {
@@ -762,7 +750,6 @@ class InputModel {
return KeyEventResult.ignored;
}
}
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey, raw: true);
if (_relativeMouse.handleRawKeyEvent(e)) {
return KeyEventResult.handled;
@@ -830,13 +817,8 @@ class InputModel {
// * Currently mobile does not enable map mode
if ((isDesktop || isWebDesktop) && keyboardMode == kKeyMapMode) {
_restoreRawFlutterShortcutModifiers(e);
mapKeyboardModeRaw(e, iosCapsLock);
} 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);
}
@@ -844,12 +826,7 @@ class InputModel {
}
KeyEventResult handleKeyEvent(KeyEvent e) {
if (_localFlutterShortcuts.tryDispatch(e)) return KeyEventResult.handled;
if (isViewOnly) {
if (isWeb && !isInputSourceFlutter) return KeyEventResult.ignored;
_tryDispatchFlutterShortcut(e, releaseModifiers: false);
return KeyEventResult.handled;
}
if (isViewOnly) return KeyEventResult.handled;
if (isViewCamera) return KeyEventResult.handled;
if (!isInputSourceFlutter) {
if (isDesktop) {
@@ -858,10 +835,6 @@ class InputModel {
return KeyEventResult.ignored;
}
}
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey);
if (isWeb && _tryDispatchFlutterShortcut(e)) {
return KeyEventResult.handled;
}
if (isWindows || isLinux) {
// Ignore meta keys. Because flutter window will loose focus if meta key is pressed.
if (e.physicalKey == PhysicalKeyboardKey.metaLeft ||
@@ -942,14 +915,6 @@ class InputModel {
final isDesktopAndMapMode =
isDesktop || (isWebDesktop && keyboardMode == kKeyMapMode);
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
newKeyboardMode(
e.character ?? '',
@@ -958,285 +923,12 @@ class InputModel {
e is KeyDownEvent || e is KeyRepeatEvent,
iosCapsLock);
} 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);
}
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
void newKeyboardMode(
String character, int usbHid, bool down, bool iosCapsLock) {
@@ -1389,10 +1081,6 @@ class InputModel {
}
}
_lastButtons = hasStaleButtonsOnMouseUp ? 0 : evt.buttons;
if (isDesktop && _relativeMouse.enabled.value && type == _kMouseEventUp) {
// A relative up can finish a press sent before the mode switch.
_pressedMouseButtons &= ~buttons;
}
out['buttons'] = buttons;
out['type'] = type;
@@ -1425,7 +1113,6 @@ class InputModel {
/// Reset key modifiers to false, including [shift], [ctrl], [alt] and [command].
void resetModifiers() {
shift = ctrl = alt = command = false;
if (parent.target?.closed == true) _localFlutterShortcuts.clear();
}
/// Modify the given modifier map [evt] based on current modifier key status.
@@ -2139,16 +1826,9 @@ class InputModel {
bool edgeScroll = false,
}) {
if (isViewCamera) return null;
final buttons = evt['buttons'];
final isMatchingMouseUp = (isDesktop || isWebDesktop) &&
evt['type'] == _kMouseEventUp &&
buttons is int &&
mouseButtonsToPeer(buttons).isNotEmpty &&
_pressedMouseButtons & buttons != 0;
double x = offset.dx;
double y = max(0.0, offset.dy);
// Cursor ownership may change between a forwarded down and its up.
if (_checkPeerControlProtected(x, y) && !isMatchingMouseUp) {
if (_checkPeerControlProtected(x, y)) {
return null;
}
@@ -2190,9 +1870,6 @@ class InputModel {
if (pos == null) {
return null;
}
if (isMatchingMouseUp) {
_pressedMouseButtons &= ~buttons;
}
if (type != '') {
evt['x'] = '0';
evt['y'] = '0';
@@ -2201,13 +1878,9 @@ class InputModel {
evt['y'] = '${pos.y.toInt()}';
}
final buttons = evt['buttons'];
if (buttons is int) {
evt['buttons'] = mouseButtonsToPeer(buttons);
if ((isDesktop || isWebDesktop) &&
type == kMouseEventTypeDown &&
evt['buttons'] != '') {
_pressedMouseButtons |= buttons;
}
} else {
// Log warning if buttons exists but is not an int (unexpected caller).
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
@@ -2286,7 +1959,7 @@ class InputModel {
canvasModel.updateLocalCursor(x, y);
}
return _handlePointerDevicePos(
final point = _handlePointerDevicePos(
kind,
x,
y,
@@ -2297,6 +1970,20 @@ class InputModel {
onExit: onExit,
buttons: buttons,
);
_rememberRemotePointer(point, isMove);
return point;
}
void _rememberRemotePointer(Point? point, bool isMove) {
final peer = parent.target!.ffiModel;
if (point == null ||
!isMove ||
!(isDesktop || isWebDesktop) ||
peer.pi.currentDisplay != kAllDisplayValue ||
!peer.isPeerLinux) {
return;
}
remotePointerPosition.value = Offset(point.x.toDouble(), point.y.toDouble());
}
bool _isInCurrentWindow(double x, double y) {
@@ -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');
}
}
}
+190 -400
View File
@@ -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/printer_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/state_model.dart';
import 'package:flutter_hbb/models/desktop_render_texture.dart';
@@ -59,8 +58,7 @@ const _restartReconnectSilentDelaySecs = 5;
class CachedPeerData {
Map<String, dynamic> updatePrivacyMode = {};
Map<String, dynamic> peerInfo = {};
// No shapes: the core keeps them for the session, and the window a tab moves to asks it
// for the one in use.
List<Map<String, dynamic>> cursorDataList = [];
Map<String, dynamic> lastCursorId = {};
Map<String, bool> permissions = {};
@@ -75,6 +73,7 @@ class CachedPeerData {
return jsonEncode({
'updatePrivacyMode': updatePrivacyMode,
'peerInfo': peerInfo,
'cursorDataList': cursorDataList,
'lastCursorId': lastCursorId,
'permissions': permissions,
'secure': secure,
@@ -89,6 +88,9 @@ class CachedPeerData {
final data = CachedPeerData();
data.updatePrivacyMode = map['updatePrivacyMode'];
data.peerInfo = map['peerInfo'];
for (final cursorData in map['cursorDataList']) {
data.cursorDataList.add(cursorData);
}
data.lastCursorId = map['lastCursorId'];
map['permissions'].forEach((key, value) {
data.permissions[key] = value;
@@ -164,7 +166,6 @@ class FfiModel with ChangeNotifier {
bool get isPeerMobile => isPeerAndroid;
bool get isPeerLinux => _pi.platform == kPeerPlatformLinux;
bool get isPeerWindows => _pi.platform == kPeerPlatformWindows;
bool get viewOnly => _viewOnly;
bool get showMyCursor => _showMyCursor;
@@ -321,6 +322,10 @@ class FfiModel with ChangeNotifier {
updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
setConnectionType(peerId, data.secure, data.direct, data.streamType);
await handlePeerInfo(data.peerInfo, peerId, true);
for (final element in data.cursorDataList) {
updateLastCursorId(element);
await handleCursorData(element);
}
if (data.lastCursorId.isNotEmpty) {
updateLastCursorId(data.lastCursorId);
handleCursorId(data.lastCursorId);
@@ -350,6 +355,9 @@ class FfiModel with ChangeNotifier {
} else if (name == 'switch_display') {
// switch display is kept for backward compatibility
handleSwitchDisplay(evt, sessionId, peerId);
} else if (name == 'cursor_data') {
updateLastCursorId(evt);
await handleCursorData(evt);
} else if (name == 'cursor_id') {
updateLastCursorId(evt);
handleCursorId(evt);
@@ -470,11 +478,6 @@ class FfiModel with ChangeNotifier {
} else if (name == 'exit_relative_mouse_mode') {
// Handle exit shortcut from rdev grab loop (Ctrl+Alt on Win/Linux, Cmd+G on macOS)
parent.target?.inputModel.exitRelativeMouseModeWithKeyRelease();
} else if (name == kShortcutEventName) {
final action = evt['action'];
if (action is String) {
parent.target?.shortcutModel.onTriggered(action);
}
} else {
debugPrint('Event is not handled in the fixed branch: $name');
}
@@ -1433,9 +1436,9 @@ class FfiModel with ChangeNotifier {
}
// After reconnecting, restore the last selected monitor once the canvas is ready.
// Switching earlier can offset the view if the monitor sizes differ.
// New monitor windows keep their selection in currentDisplay.
final last = lastUserDisplay ?? _pi.currentDisplay;
final last = lastUserDisplay;
pendingMonitorRestore = (!isCache &&
last != null &&
last != currentDisplay &&
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
sessionId: sessionId) !=
@@ -1658,14 +1661,9 @@ class FfiModel with ChangeNotifier {
parent.target?.cursorModel.updateCursorId(evt);
}
/// A shape arriving is the shape in use, as a cursor_id is.
handleCursorData(String id, int hotx, int hoty, int width, int height,
Uint8List colors) async {
// The replay selects this last, whatever the order the shapes are replayed in.
cachedPeerData.lastCursorId = {'id': id};
parent.target?.cursorModel.id = id;
await parent.target?.cursorModel
.updateCursorData(id, hotx, hoty, width, height, colors);
handleCursorData(Map<String, dynamic> evt) async {
cachedPeerData.cursorDataList.add(evt);
await parent.target?.cursorModel.updateCursorData(evt);
}
/// Handle the peer info synchronization event based on [evt].
@@ -2403,9 +2401,7 @@ class CanvasModel with ChangeNotifier {
// ViewStyle fields and is not captured by the equality check. Therefore, we must
// allow updates to proceed when style == kRemoteViewStyleCustom, even if the
// rest of the ViewStyle fields are unchanged.
if (_lastViewStyle == viewStyle &&
_devicePixelRatio == ui.window.devicePixelRatio &&
style != kRemoteViewStyleCustom) {
if (_lastViewStyle == viewStyle && style != kRemoteViewStyleCustom) {
return;
}
if (_lastViewStyle.style != viewStyle.style) {
@@ -2465,8 +2461,6 @@ class CanvasModel with ChangeNotifier {
_resetScroll();
Future.delayed(duration, () async {
// Layout updates scroll extents and detaches scrollbars no longer needed.
await SchedulerBinding.instance.endOfFrame;
updateScrollPercent();
});
}
@@ -2478,8 +2472,7 @@ class CanvasModel with ChangeNotifier {
style != null ? ScrollStyle.fromString(style) : ScrollStyle.scrollauto;
if (_scrollStyle != ScrollStyle.scrollauto) {
// Scrollbar and Scroll Edge share controllers and retain their positions.
updateScrollPercent();
_resetScroll();
}
notifyListeners();
@@ -2703,10 +2696,20 @@ class CanvasModel with ChangeNotifier {
setScrollPercent(scrollPixelPercent.x, scrollPixelPercent.y);
pushScrollPositionToUI(scrollPixel.x, scrollPixel.y);
// A no-op jump emits no notification to refresh the actual scroll fractions.
updateScrollPercent();
notifyListeners();
}
void updateScrollAfterLayout((double, double) renderedScroll) {
updateScrollPercent();
// A delayed refresh may already have changed the model without repainting.
if (renderedScroll != (_scrollX, _scrollY)) {
notifyListeners();
}
}
panX(double dx) {
_x += dx;
if (isMobile) {
@@ -2857,15 +2860,27 @@ class CanvasModel with ChangeNotifier {
}
}
// data for cursor
class CursorData {
// At most 1 MiB of RGBA, including Linux's square cursor padding: twice the largest
// accessibility cursor, beyond which a cursor is shown smaller rather than larger.
static const _maxRasterSize = 512;
// Bound integer cache keys and raster allocation: 4096 squared RGBA is 64 MiB.
const _maxCursorRasterSize = 4096;
bool _validCursorRasterSize(double width, double height,
{double rasterScale = 1}) =>
width.isFinite && height.isFinite && rasterScale.isFinite &&
width > 0 && height > 0 && rasterScale > 0 &&
width.ceilToDouble() * rasterScale <= _maxCursorRasterSize &&
height.ceilToDouble() * rasterScale <= _maxCursorRasterSize;
// Scale the host's bitmap and hotspot together. Incorrect source geometry
// must be fixed in host capture, independently of the client's sizing policy.
class CursorData {
final String peerId;
final String id;
img2.Image? _image;
final img2.Image image;
// Borrowed from CursorModel/PredefinedCursor, which own its lifetime.
// The plugin clones the handle before starting asynchronous encoding.
final ui.Image nativeImage;
// Zero preserves legacy sizing for capture backends without density metadata.
final double pixelRatio;
double scale;
Uint8List? data;
final double hotxOrigin;
@@ -2874,146 +2889,95 @@ class CursorData {
double hoty;
final int width;
final int height;
int _rasterWidth;
int _rasterHeight;
bool _scaleLimitReported = false;
int get rasterWidth => _rasterWidth;
int get rasterHeight => _rasterHeight;
img2.Image get image => _image!;
/// False for a shape not in use; only the shape in use keeps pixels, for a new raster.
bool get hasPixels => _image != null;
void releasePixels() {
_image = null;
data = null;
}
CursorData({
required this.peerId,
required this.id,
required img2.Image image,
required this.image,
required this.nativeImage,
this.pixelRatio = 0,
required this.scale,
required this.data,
required this.hotxOrigin,
required this.hotyOrigin,
required this.width,
required this.height,
}) : _image = image,
_rasterWidth = (width * scale).ceil(),
_rasterHeight = (height * scale).ceil(),
hotx = hotxOrigin * scale,
}) : hotx = hotxOrigin * scale,
hoty = hotyOrigin * scale;
int _doubleToInt(double v) => (v * 10e6).round().toInt();
double _limitScale(double requestedScale) {
final valid = requestedScale.isFinite && requestedScale > 0;
// Invalid requests retain the last valid raster and hotspot.
final limitedScale = valid
? min(requestedScale, _maxRasterSize / max(width, height))
: scale;
final limited = !valid || limitedScale != requestedScale;
if (limited && !_scaleLimitReported) {
debugPrint(
'Cursor $id: rejected scale $requestedScale for ${width}x$height; '
'using $limitedScale (maximum raster side $_maxRasterSize).');
// Keep the minimum-size policy here. Native callers let the plugin rasterize
// the original ui.Image; Web keeps the encoded-image resizing path.
double? _validatedScale(double scale,
{required bool useLegacyMinimum, required double rasterScale}) {
if (!scale.isFinite || scale <= 0) {
debugPrint('Rejected cursor $id: invalid scale $scale');
return null;
}
_scaleLimitReported = limited;
return limitedScale;
}
double _checkUpdateScale(double scale) {
scale = _limitScale(scale);
if (scale != 1.0) {
// A thin cursor must not grow just to make its short edge reach the minimum.
// Preserve unscaled legacy artwork, but never enlarge a thin cursor just
// to make its short edge reach the visibility minimum.
if (!useLegacyMinimum || scale != 1.0) {
scale = max(scale, kMinCursorSize / max(width, height));
}
final targetWidth = (width * scale).ceil();
final targetHeight = (height * scale).ceil();
if ((_rasterWidth != targetWidth || _rasterHeight != targetHeight) &&
!hasPixels) {
// Nothing to make this raster from; buildCursorOfCache asks for the pixels unless its
// native cursor was made before.
data = null;
return scale;
if (!_validCursorRasterSize(width * scale, height * scale,
rasterScale: rasterScale)) {
debugPrint('Rejected cursor $id: raster ${width * scale}x${height * scale} '
'at pixel ratio $rasterScale exceeds $_maxCursorRasterSize');
return null;
}
if (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
return scale;
}
double _checkUpdateScale(double scale, {required bool resizeImage}) {
double oldScale = this.scale;
// Web's long-edge minimum can round a thin axis below one raster pixel.
final webWidth = max(1, (width * scale).round());
final webHeight = max(1, (height * scale).round());
if (resizeImage && _doubleToInt(oldScale) != _doubleToInt(scale)) {
if (isWindows) {
data = img2
.copyResize(
image,
width: targetWidth,
height: targetHeight,
width: (width * scale).toInt(),
height: (height * scale).toInt(),
interpolation: img2.Interpolation.average,
)
.getBytes(order: img2.ChannelOrder.bgra);
} else if (isDesktop && scale < 1.0 && !image.hasPalette) {
data = Uint8List.fromList(
img2.encodePng(_resizeWithAlpha(targetWidth, targetHeight)));
} else {
data = Uint8List.fromList(
img2.encodePng(
img2.copyResize(
image,
width: targetWidth,
height: targetHeight,
width: isWeb ? webWidth : (width * scale).toInt(),
height: isWeb ? webHeight : (height * scale).toInt(),
interpolation: img2.Interpolation.average,
),
),
);
}
_rasterWidth = targetWidth;
_rasterHeight = targetHeight;
}
this.scale = scale;
hotx = hotxOrigin * _rasterWidth / width;
hoty = hotyOrigin * _rasterHeight / height;
hotx = hotxOrigin * scale;
hoty = hotyOrigin * scale;
if (isWeb) {
// CSS hotspots must follow the actual rounded PNG dimensions.
hotx = hotxOrigin * webWidth / width;
hoty = hotyOrigin * webHeight / height;
}
return scale;
}
img2.Image _resizeWithAlpha(int targetWidth, int targetHeight) {
final resized =
img2.Image.fromResized(image, width: targetWidth, height: targetHeight);
final dx = image.width / targetWidth;
final dy = image.height / targetHeight;
// Use the average filter's sample area, but weight RGB by alpha so
// transparent pixels do not darken visible edges in the straight-alpha PNG.
for (final pixel in resized) {
final x = (pixel.x * dx).toInt();
final y = (pixel.y * dy).toInt();
final sampleWidth = ((pixel.x + 1) * dx).toInt() - x;
final sampleHeight = ((pixel.y + 1) * dy).toInt() - y;
final samples = image.getRange(x, y, sampleWidth, sampleHeight);
num r = 0;
num g = 0;
num b = 0;
num a = 0;
while (samples.moveNext()) {
final sample = samples.current;
r += sample.r * sample.a;
g += sample.g * sample.a;
b += sample.b * sample.a;
a += sample.a;
}
if (a == 0) {
pixel.setRgba(0, 0, 0, 0);
continue;
}
pixel.setRgba(r / a, g / a, b / a, a / (sampleWidth * sampleHeight));
}
return resized;
}
String updateGetKey(double scale) {
scale = _checkUpdateScale(scale);
// The raster asked for, not the one made last: a shape without pixels keeps the native
// cursors of every raster it was shown at.
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${(width * scale).ceil()}_${(height * scale).ceil()}';
String? updateGetKey(double scale,
{bool resizeImage = true, bool useLegacyMinimum = true,
double rasterScale = 1}) {
final effectiveScale = _validatedScale(scale,
useLegacyMinimum: useLegacyMinimum, rasterScale: rasterScale);
if (effectiveScale == null) return null;
_checkUpdateScale(effectiveScale, resizeImage: resizeImage);
return '${peerId}_${id}_${_doubleToInt(width * effectiveScale)}_${_doubleToInt(height * effectiveScale)}';
}
}
@@ -3053,7 +3017,8 @@ class PredefinedCursor {
CursorData? get cache => _cache;
init() {
_image2 = img2.decodePng(base64Decode(png));
final pngBytes = base64Decode(png);
_image2 = img2.decodePng(pngBytes);
if (_image2 != null) {
// The png type of forbidden cursor image is `PngColorType.indexed`.
if (id == kPreForbiddenCursorId) {
@@ -3061,17 +3026,20 @@ class PredefinedCursor {
}
() async {
final defaultImg = _image2!;
// This function is called only one time, no need to care about the performance.
Uint8List data = defaultImg.getBytes(order: img2.ChannelOrder.rgba);
_image?.dispose();
_image = await img.decodeImageFromPixels(
data, defaultImg.width, defaultImg.height, ui.PixelFormat.rgba8888);
if (_image == null) {
print("decodeImageFromPixels failed, pre-defined cursor $id");
return;
// Native registration uses this ui.Image. The RGBA bytes from img2 are
// straight alpha, but PixelFormat.rgba8888 requires premultiplied alpha.
// Decode the PNG directly to preserve translucent cursor colors.
final codec = await ui.instantiateImageCodec(pngBytes);
final ui.Image nativeImage;
try {
nativeImage = (await codec.getNextFrame()).image;
} finally {
codec.dispose();
}
_image = nativeImage;
double scale = 1.0;
final Uint8List data;
if (isWindows) {
data = _image2!.getBytes(order: img2.ChannelOrder.bgra);
} else {
@@ -3082,6 +3050,7 @@ class PredefinedCursor {
peerId: '',
id: id,
image: _image2!.clone(),
nativeImage: nativeImage,
scale: scale,
data: data,
hotxOrigin:
@@ -3184,16 +3153,7 @@ class CursorModel with ChangeNotifier {
get lastIsBlocked => _lastIsBlocked;
/// The image of the shape in use, or the one shown before until it is back: a switch falls
/// back to the default cursor only for a shape the core cannot give. Asks the core for the
/// shape in use when it was let go.
ui.Image? get image {
if (_images[_id] == null && _cacheMap.containsKey(_id)) {
restorePixels(_id);
}
return _image;
}
ui.Image? get image => _image;
CursorData? get cache => _cache;
double get x => _x - _displayOriginX;
@@ -3206,10 +3166,7 @@ class CursorModel with ChangeNotifier {
double get hotx => _hotx;
double get hoty => _hoty;
set id(String id) {
if (_id != id) _unavailable = null;
_id = id;
}
set id(String id) => _id = id;
bool get isPeerControlProtected =>
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
@@ -3224,12 +3181,7 @@ class CursorModel with ChangeNotifier {
}
}
CursorModel(this.parent) {
// Made now, not when first drawn: nothing draws again when their decode lands, so the first
// build that needs one would show the shape before in its place.
preDefaultCursor.cache;
preForbiddenCursor.cache;
}
CursorModel(this.parent);
Set<String> get cachedKeys => _cacheKeys;
addKey(String key) => _cacheKeys.add(key);
@@ -3528,84 +3480,103 @@ class CursorModel with ChangeNotifier {
_images.clear();
}
/// Its image is kept with the ones used last, see [_imageLimit]; a shape that does not decode
/// is marked as one the core cannot give.
Future<void> updateCursorData(String id, int hotxInt, int hotyInt, int width,
int height, Uint8List rgba) async {
final generation = _generation;
if (_unavailable == id) _unavailable = null;
final hotx = hotxInt.toDouble();
final hoty = hotyInt.toDouble();
final image = await img.decodeImageFromPixels(
rgba, width, height, ui.PixelFormat.rgba8888);
updateCursorData(Map<String, dynamic> evt) async {
final id = evt['id'];
final hotx = double.parse(evt['hotx']);
final hoty = double.parse(evt['hoty']);
final width = int.parse(evt['width']);
final height = int.parse(evt['height']);
// Rust validates native packets; Web receives them directly from JavaScript.
if (isWeb && !_validCursorRasterSize(width.toDouble(), height.toDouble())) {
debugPrint('Rejected cursor $id: invalid source size ${width}x$height');
return;
}
final pixelRatio = double.tryParse(evt['scale'] ?? '0');
if (pixelRatio == null ||
(isWeb && (!pixelRatio.isFinite || pixelRatio < 0 ||
(pixelRatio > 0 &&
!_validCursorRasterSize(width / pixelRatio, height / pixelRatio))))) {
debugPrint('Rejected cursor $id: invalid pixel ratio ${evt['scale']}');
return;
}
List<dynamic> colors = json.decode(evt['colors']);
const bytesPerPixel = 4;
if (isWeb && colors.length != width * height * bytesPerPixel) {
debugPrint('Rejected cursor $id: invalid RGBA length ${colors.length}');
return;
}
final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
final ui.Image? image;
final platform = parent.target?.ffiModel.pi.platform;
if (!isWeb &&
(platform == kPeerPlatformMacOS || platform == kPeerPlatformWindows)) {
image = await _decodeStraightAlphaCursor(rgba, width, height);
} else {
image = await img.decodeImageFromPixels(
rgba, width, height, ui.PixelFormat.rgba8888);
}
if (image == null) {
// It did not decode; painting must not ask for it on every frame.
_markUnavailable(generation, id);
return;
}
if (!await _updateCache(
generation, rgba, image, id, hotx, hoty, width, height)) {
// Not kept, or the session was cleared while it decoded.
if (await _updateCache(rgba, image, id, hotx, hoty, width, height,
pixelRatio: pixelRatio)) {
_images[id]?.item1.dispose();
_images[id] = Tuple3(image, hotx, hoty);
} else {
image.dispose();
_markUnavailable(generation, id);
return;
}
final old = _images.remove(id);
_images[id] = Tuple3(image, hotx, hoty);
if (old != null) {
if (identical(old.item1, _image)) _image = image;
old.item1.dispose();
}
// Update last cursor data.
// Do not use the previous `image` and `id`, because `_id` may be changed.
_updateCurData();
final cache = _cacheMap[id];
if (id != _id && cache != null) _switchedAway(cache);
}
Future<ui.Image?> _decodeStraightAlphaCursor(
Uint8List rgba, int width, int height) async {
// macOS and Win32 capture send straight alpha; XFixes/DRM are premultiplied.
// Convert a copy for native ui.Image, preserving the wire and PNG cache colors.
final source = img2.Image.fromBytes(
width: width, height: height, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
for (final pixel in source) {
final opacity = pixel.a / pixel.maxChannelValue;
pixel.r = (pixel.r * opacity).round();
pixel.g = (pixel.g * opacity).round();
pixel.b = (pixel.b * opacity).round();
}
return img.decodeImageFromPixels(
source.getBytes(), width, height, ui.PixelFormat.rgba8888);
}
Future<bool> _updateCache(
int generation,
Uint8List rgba,
ui.Image image,
String id,
double hotx,
double hoty,
int w,
int h,
) async {
int h, {
required double pixelRatio,
}) async {
Uint8List? data;
img2.Image imgOrigin = img2.Image.fromBytes(
width: w,
height: h,
bytes: rgba.buffer,
bytesOffset: rgba.offsetInBytes,
order: img2.ChannelOrder.rgba);
width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
if (isWindows) {
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
} else {
ByteData? imgBytes =
await image.toByteData(format: ui.ImageByteFormat.png);
if (imgBytes == null) {
debugPrint('Unable to encode cursor $id as PNG');
return false;
}
data = imgBytes.buffer.asUint8List();
if (isDesktop &&
(parent.target?.ffiModel.isPeerLinux == true ||
parent.target?.ffiModel.isPeerWindows == true)) {
// PNG decoding supplies straight alpha for Linux/Windows cursor resizing.
final decoded = img2.decodePng(data);
if (decoded == null) {
debugPrint('Unable to decode cursor $id PNG for resizing');
return false;
}
imgOrigin = decoded;
}
}
final cache = CursorData(
peerId: peerId,
id: id,
image: imgOrigin,
nativeImage: image,
pixelRatio: pixelRatio,
scale: 1.0,
data: data,
hotxOrigin: hotx,
@@ -3613,200 +3584,34 @@ class CursorModel with ChangeNotifier {
width: w,
height: h,
);
if (generation != _generation) {
return false;
}
_cacheMap[id] = cache;
return true;
}
@visibleForTesting
Iterable<String> get shapeIds => _images.keys;
@visibleForTesting
CursorData? cachedShape(String id) => _cacheMap[id];
final _restoring = <String>{};
// Tabs in a window share its engine's native cursors, predefined ones included.
static int _nextKeyScope = 0;
final int _keyScope = _nextKeyScope++;
String nativeKey(CursorData cache, double scale) {
final key = '${_keyScope}_${cache.updateGetKey(scale)}';
// A native cursor at another raster does not hold the pixels this one is made from.
if (!_cacheKeys.contains(key)) _nativeIds.remove(cache.id);
return key;
}
// Native cursors stay for the session, one per raster of each shape, and only [clear]
// deletes them, as before; unlike the painted images they have no LRU, for now. A delete
// frees nothing on Windows: the engine's `deleteCustomCursor/windows` releases the HCURSOR
// with `DeleteObject`, which does not take a cursor. Measured on Windows with 500 cursors
// made by `CreateIconIndirect`, as the engine makes them: `DeleteObject` failed all 500 and
// left 500 USER objects alive, while `DestroyCursor` or `DestroyIcon` freed all 500. Each
// delete leaks its handle until the process exits, and making the cursor again for a raster
// or a shape shown once more leaks another, so an LRU would leak more than keeping them.
//
// Fixing the engine is not cheap. x64 runs our fork, rustdesk/engine, on Flutter 3.24; the
// fix is one more patch to rebuild, publish, and carry across every Flutter upgrade. arm64
// runs the stock engine of a newer Flutter, which has the same code: fixing it means
// porting the fork to that version and building and publishing an arm64 engine as well, or
// an upstream fix and waiting for it to reach stable. Once both engines destroy cursors, an
// LRU like the painted images' can come back. Content ids keep the count to the shapes the
// peer really shows, a few dozen to a couple of hundred.
/// The shape in use keeps its pixels, so a new raster is made from them at once; the others
/// keep none once their native cursor holds them.
void registered(CursorData cache, String key) {
_nativeIds.add(cache.id);
_awaitingNative.remove(cache.id);
if (cache.id != _id && identical(_cacheMap[cache.id], cache)) {
cache.releasePixels();
}
}
// The shapes a native cursor holds, and those keeping their pixels until one does, oldest
// first: one decoded after the peer moved on must still get a native cursor when shown
// again, rather than be decoded again every time it comes back.
final _nativeIds = <String>{};
final _awaitingNative = <String>{};
void _switchedAway(CursorData cache) {
_awaitingNative.remove(cache.id);
// Mobile only paints the cursor, from its image.
if (isMobile || _nativeIds.contains(cache.id)) {
cache.releasePixels();
return;
}
_awaitingNative.add(cache.id);
while (_awaitingNative.length > kRecentShapes) {
final oldest = _awaitingNative.first;
_awaitingNative.remove(oldest);
if (oldest != _id) _cacheMap[oldest]?.releasePixels();
}
}
/// The peer's shapes used last that keep a painted image, and the most that keep their pixels
/// waiting for a native cursor; the core rebuilds the others. An animated cursor is a shape per
/// frame, 18 for the Windows busy cursor and 23 for KDE's, and a cycle longer than this limit
/// would rebuild every frame.
static const kRecentShapes = 64;
/// The native cursor of the shape shown last, shown on while the shape in use is made.
String? shownKey;
void shown(CursorData cache, String key) {
// The forbidden cursor shows only while input is off; it is no stand-in for a shape.
if (cache.id != kPreForbiddenCursorId) shownKey = key;
}
/// Whether the desktop paints the peer's cursor over the remote image.
@protected
bool get showsRemoteCursor {
final tag = ShowRemoteCursorState.tag(parent.target?.id ?? '');
return Get.isRegistered<RxBool>(tag: tag) &&
Get.find<RxBool>(tag: tag).value;
}
// Painted images kept: mobile always paints the cursor, a desktop only when it shows the
// remote cursor, and otherwise the native cursors show the shapes.
int get _imageLimit => isMobile || showsRemoteCursor ? kRecentShapes : 1;
// `_images` is in order of use. The image painted is kept, whoever's it is.
void _evictImages() {
var excess = _images.length - _imageLimit;
_images.removeWhere((id, shape) {
if (excess <= 0 || id == _id || identical(shape.item1, _image)) {
return false;
}
excess--;
shape.item1.dispose();
return true;
});
}
/// The core keeps every shape the peer sent, compressed; see `Session::cursor_shapes`.
@protected
Future<CursorShape?> fetchCursorShape(String id) {
final ffi = parent.target;
if (ffi == null) return Future.value(null);
return bind.sessionGetCursorShape(sessionId: ffi.sessionId, id: id);
}
// The shape the core could not give, not asked for again while it is the one in use. One
// is enough: only the shape in use is asked for on every frame, and the peer's ids must not
// accumulate here.
String? _unavailable;
// Counts session clears, so that a decode finishing after one keeps nothing.
int _generation = 0;
/// Decodes the shape in use again from the core, for a raster its native cursor lacks, for
/// painting it, or for a window a tab moved to.
void restorePixels(String id) {
if (id != _id || _unavailable == id || !_restoring.add(id)) return;
final generation = _generation;
() async {
try {
// A throw becomes an error the await hands over later, not during the build that may
// have asked: a failure tells the listeners.
final shape = await Future.sync(() => fetchCursorShape(id));
if (generation != _generation) {
return;
} else if (shape == null) {
_markUnavailable(generation, id);
debugPrint('Cursor $id is not kept by the core');
} else {
// Decoded even if the peer moved on: an animation comes back to it.
await updateCursorData(id, shape.hotx, shape.hoty, shape.width,
shape.height, shape.colors);
}
} catch (e) {
_markUnavailable(generation, id);
debugPrint('Failed to fetch cursor $id: $e');
} finally {
_restoring.remove(id);
}
}();
}
void _markUnavailable(int generation, String id) {
if (generation != _generation || id != _id) return;
_unavailable = id;
_updateCurData();
}
bool _updateCurData() {
final previous = _cache;
final cache = _cacheMap[_id];
// A shape not decoded yet leaves the one shown before in place until it is; one the core
// cannot give leaves none, so the default cursor shows, as for a shape never sent.
if (cache != null || _unavailable == _id) _cache = cache;
if (previous != null && !identical(previous, _cache)) {
_switchedAway(previous);
}
final tmp = _images.remove(_id);
_cache = _cacheMap[_id];
final tmp = _images[_id];
if (tmp != null) {
_images[_id] = tmp;
_image = tmp.item1;
_hotx = tmp.item2;
_hoty = tmp.item3;
} else if (_unavailable == _id) {
_image = null;
try {
// may throw exception, because the listener maybe already dispose
notifyListeners();
} catch (e) {
debugPrint(
'WARNING: updateCursorId $_id, without notifyListeners(). $e');
}
return true;
} else {
return false;
}
_evictImages();
try {
// may throw exception, because the listener maybe already dispose
notifyListeners();
} catch (e) {
debugPrint('WARNING: updateCursorId $_id, without notifyListeners(). $e');
}
return tmp != null || cache != null;
}
updateCursorId(Map<String, dynamic> evt) {
if (!_updateCurData()) {
restorePixels(_id);
debugPrint(
'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
}
}
@@ -3859,10 +3664,6 @@ class CursorModel with ChangeNotifier {
_clearCache();
_cache = null;
_cacheMap.clear();
_nativeIds.clear();
_awaitingNative.clear();
_unavailable = null;
_generation++;
}
_clearCache() {
@@ -3871,8 +3672,6 @@ class CursorModel with ChangeNotifier {
debugPrint("deleting cursor with key $k");
deleteCustomCursor(k);
}
_cacheKeys.clear();
shownKey = null;
resetSystemCursor();
}
@@ -3908,11 +3707,9 @@ class QualityMonitorModel with ChangeNotifier {
bool get show => _show;
QualityMonitorData get data => _data;
// Only a WebRTC session on the web names its transport here: web has no
// session tab to show it on (the desktop tab's tooltip already does), and
// WebRTC is the one path that can be direct or TURN.
// Only a WebRTC session names its transport here: web has no session tab
// to show it on, and WebRTC is the one path that can be direct or TURN.
String? get webrtcTransport {
if (!isWeb) return null;
final ffiModel = parent.target?.ffiModel;
if (ffiModel == null) return null;
final streamType = ffiModel.cachedPeerData.streamType;
@@ -4054,7 +3851,6 @@ class FFI {
late final ElevationModel elevationModel; // session
late final CmFileModel cmFileModel; // cm
late final TextureModel textureModel; //session
late final ShortcutModel shortcutModel; // session
late final Peers recentPeersModel; // global
late final Peers favoritePeersModel; // global
late final Peers lanPeersModel; // global
@@ -4084,7 +3880,6 @@ class FFI {
elevationModel = ElevationModel(WeakReference(this));
cmFileModel = CmFileModel(WeakReference(this));
textureModel = TextureModel(WeakReference(this));
shortcutModel = ShortcutModel(WeakReference(this));
recentPeersModel = Peers(
name: PeersModelName.recent,
loadEvent: LoadEvent.recent,
@@ -4214,7 +4009,6 @@ class FFI {
}
if (isWeb) {
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
platformFFI.setRgbaCallback((int display, Uint8List data) {
onEvent2UIRgba();
imageModel.onRgba(display, data);
@@ -4297,9 +4091,6 @@ class FFI {
} else {
platformFFI.nextRgba(sessionId, display);
}
} else if (message is EventToUI_Cursor) {
await ffiModel.handleCursorData(message.id, message.hotx,
message.hoty, message.width, message.height, message.colors);
} else if (message is EventToUI_Texture) {
final display = message.field0;
final gpuTexture = message.field1;
@@ -4394,7 +4185,6 @@ class FFI {
ffiModel.pi.currentDisplay);
}
imageModel.callbacksOnFirstImage.clear();
shortcutModel.clear();
await imageModel.update(null);
cursorModel.clear();
ffiModel.clear();
-7
View File
@@ -59,9 +59,6 @@ class PlatformFFI {
final _toAndroidChannel = const MethodChannel('mChannel');
RustdeskImpl get ffiBind => _ffiBind;
@visibleForTesting
void setBindingForTesting(RustdeskImpl binding) => _ffiBind = binding;
F3? _session_get_rgba;
static get localeName => Platform.localeName;
@@ -288,10 +285,6 @@ class PlatformFFI {
void setRgbaCallback(void Function(int, Uint8List) fun) async {}
// web only
void setCursorDataCallback(
void Function(String, int, int, int, int, Uint8List) fun) async {}
// web only, decoded WebCodecs frames arriving as ready-made images
void setVideoFrameCallback(
Future<void> Function(int, ui.Image, bool Function()) fun) {}
-10
View File
@@ -15,8 +15,6 @@ import '../common/formatter/id_formatter.dart';
import '../desktop/pages/server_page.dart' as desktop;
import '../desktop/widgets/tabbar_widget.dart';
import '../mobile/pages/server_page.dart';
import '../mobile/widgets/android_file_transfer_setup.dart';
import '../utils/android_documents.dart';
import 'model.dart';
const kLoginDialogTag = "LOGIN";
@@ -401,14 +399,6 @@ class ServerModel with ChangeNotifier {
stopService();
}
} else {
if (isAndroid) {
try {
await AndroidDocuments.requireLogFolder();
await showAndroidFileTransferSetup(gFFI);
} catch (_) {
debugPrint('Folder setup failed; continuing service startup');
}
}
await checkRequestNotificationPermission();
if (bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) != 'Y') {
await checkFloatingWindowPermission();
-669
View File
@@ -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();
});
}
}
+4
View File
@@ -70,6 +70,10 @@ class TerminalModel with ChangeNotifier {
final _inputBuffer = <String>[];
/// Exposes buffered input only for lifecycle regression tests.
@visibleForTesting
int get debugBufferedInputCount => _inputBuffer.length;
// Buffer for output data received before terminal view has valid dimensions.
// This prevents NaN errors when writing to terminal before layout is complete.
final _pendingOutputChunks = <String>[];
@@ -9,7 +9,6 @@ import 'platform_model.dart';
import 'rustdesk_terminal.dart';
import 'terminal_copy_shortcut.dart';
import 'terminal_mouse_drag_reporter.dart';
import 'terminal_scroll_controller.dart';
part 'terminal_mouse_handler_input.dart';
part 'terminal_web_clipboard_gesture.dart';
@@ -56,7 +55,7 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
static const _scrollDown = 1;
final _terminalViewKey = GlobalKey<TerminalViewState>();
late final _scrollController = TerminalScrollController(() => widget.terminal);
final _scrollController = ScrollController();
final _mouseDrag = TerminalMouseDragReporter();
late final WheelButtonFixMouseHandler _mouseHandler;
TerminalMouseHandler? _previousMouseHandler;
@@ -1,36 +0,0 @@
import 'package:flutter/widgets.dart';
import 'package:xterm/xterm.dart';
class TerminalScrollController extends ScrollController {
TerminalScrollController(this.terminal);
final Terminal Function() terminal;
@override
ScrollPosition createScrollPosition(ScrollPhysics physics,
ScrollContext context, ScrollPosition? oldPosition) {
return super.createScrollPosition(
_TerminalScrollPhysics(terminal, parent: physics),
context,
oldPosition,
);
}
}
class _TerminalScrollPhysics extends ScrollPhysics {
const _TerminalScrollPhysics(this.terminal, {super.parent});
final Terminal Function() terminal;
@override
_TerminalScrollPhysics applyTo(ScrollPhysics? ancestor) =>
_TerminalScrollPhysics(terminal, parent: buildParent(ancestor));
@override
bool shouldAcceptUserOffset(ScrollMetrics position) {
// A retained main-screen offset can make this inner scrollable win the
// trackpad gesture, starving xterm's outer alternate-screen scroll handler.
if (terminal().isUsingAltBuffer) return false;
return super.shouldAcceptUserOffset(position);
}
}
-12
View File
@@ -153,7 +153,6 @@ class PlatformFFI {
gFFI.dialogManager.dismissAll();
closeConnection();
};
await _ffiBind.mainInit(appDir: '');
context.callMethod('init');
version = getByName('version');
window.onContextMenu.listen((event) {
@@ -190,17 +189,6 @@ class PlatformFFI {
};
}
// The web core calls this with a shape's pixels as bytes, as it calls onRgba for a frame.
void setCursorDataCallback(
void Function(String, int, int, int, int, Uint8List) fun) {
context["onCursorData"] = (String id, int hotx, int hoty, int width,
int height, Uint8List? rgba) {
if (rgba != null) {
fun(id, hotx, hoty, width, height, rgba);
}
};
}
late final WebVideoFrameQueue<JSObject, ui.Image> _videoFrameQueue;
// Zero-readback video path: the JS decoder hands decoded VideoFrames here
+46 -54
View File
@@ -1,13 +1,17 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter_custom_cursor/cursor_manager.dart'
as custom_cursor_manager;
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show WidgetsBinding;
import 'package:flutter_hbb/common.dart' show isLinux;
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:image/image.dart' as img;
deleteCustomCursor(String key) =>
custom_cursor_manager.CursorManager.instance.deleteCursor(key);
@@ -16,63 +20,51 @@ resetSystemCursor() {}
MouseCursor buildCursorOfCache(
CursorModel cursor, double scale, CursorData? cache) {
if (cache == null) {
return _shownCursor(cursor);
return MouseCursor.defer;
} else {
final key = cursor.nativeKey(cache, scale);
// Include the live DPR so moving between monitors rebuilds the native
// bitmap even when the remote view scale has not changed.
final dpr = WidgetsBinding
.instance.platformDispatcher.views.single.devicePixelRatio;
// Keep Original and older peers' pixel units and scale-1 behavior.
// Resizing uses a long-edge minimum regardless of source density.
final legacyMinimum = cache.pixelRatio == 0 ||
cursor.parent.target?.canvasModel.viewStyle.style == kRemoteViewStyleOriginal;
// The minimum is logical, while Windows callers pass a physical scale.
final effectiveScale = !legacyMinimum && isWindows
? math.max(scale, kMinCursorSize * dpr / math.max(cache.width, cache.height))
: scale;
final cacheKey = cache.updateGetKey(effectiveScale, resizeImage: false,
useLegacyMinimum: legacyMinimum,
rasterScale: isWindows ? 1 : (isLinux ? dpr.ceilToDouble() : dpr));
if (cacheKey == null) return MouseCursor.defer;
final key = '${cacheKey}_$dpr';
if (!cursor.cachedKeys.contains(key)) {
// data should be checked here, because it may be changed after `updateGetKey()`
final data = cache.data;
if (data == null) {
cursor.restorePixels(cache.id);
return _shownCursor(cursor);
}
// Square canvases avoid clipping or stray edge pixels on Linux.
final width = isLinux && cache.rasterWidth < cache.rasterHeight
? cache.rasterHeight
: cache.rasterWidth;
final height = isLinux ? width : cache.rasterHeight;
debugPrint(
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
// [Safety]
// It's ok to call async registerCursor in current synchronous context,
// because activating the cursor is also an async call and will always
// be executed after this.
custom_cursor_manager.CursorManager.instance
.registerCursor(custom_cursor_manager.CursorData()
..name = key
..buffer =
width == cache.rasterWidth && height == cache.rasterHeight
? data
: _padCursor(data, width)
..width = width
..height = height
..hotX = cache.hotx
..hotY = cache.hoty);
unawaited(custom_cursor_manager.CursorManager.instance
.registerCursorImage(
name: key,
image: cache.nativeImage,
hotSpot: Offset(cache.hotxOrigin, cache.hotyOrigin),
// Windows callers already express scale in physical pixels.
// The plugin takes logical scale and applies DPR during rasterization.
scale: isWindows ? cache.scale / dpr : cache.scale,
devicePixelRatio: dpr,
)
.then<void>((_) {}, onError: (Object error, StackTrace stack) {
cursor.cachedKeys.remove(key);
FlutterError.reportError(FlutterErrorDetails(
exception: error,
stack: stack,
library: 'native cursor',
context: ErrorDescription('registering cursor $key')));
}));
cursor.addKey(key);
cursor.registered(cache, key);
}
cursor.shown(cache, key);
return FlutterCustomMemoryImageCursor(key: key);
return FlutterCustomMemoryImageCursor(
key: key,
registrationToken: custom_cursor_manager.CursorManager.instance
.registrationTokenFor(key));
}
}
// The last shape's cursor stays while the one in use is made, rather than the system one.
MouseCursor _shownCursor(CursorModel cursor) {
final key = cursor.shownKey;
return key == null
? MouseCursor.defer
: FlutterCustomMemoryImageCursor(key: key);
}
Uint8List _padCursor(Uint8List data, int size) {
final bitmap = img.decodePng(data);
if (bitmap == null) {
throw const FormatException('Invalid native cursor PNG');
}
final padded = img.copyExpandCanvas(bitmap,
newWidth: size,
newHeight: size,
position: img.ExpandCanvasPosition.topLeft,
toImage: img.Image(width: size, height: size, numChannels: 4));
return Uint8List.fromList(img.encodePng(padded));
}
-98
View File
@@ -1,98 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../common.dart';
class AndroidDocuments {
static const root = '/@rustdesk/';
static bool isPath(String path) => path.startsWith(root);
static bool isRoot(String path) =>
RegExp(r'^/@rustdesk/tree/[^/]+/[^/]+$').hasMatch(path);
static String displayPath(String path) {
if (!isPath(path)) return path;
return path.replaceFirst(RegExp(r'^/@rustdesk/tree/[^/]+/'), '');
}
static Future<Map<String, dynamic>?> selectFolder({bool share = false}) async {
gFFI.ffiModel.beginAndroidDocumentPicker();
try {
final result = await gFFI.invokeMethodWithResult<String>(
'document_folder', {'share': share});
return result == null ? null : jsonDecode(result) as Map<String, dynamic>;
} finally {
gFFI.ffiModel.endAndroidDocumentPicker();
}
}
static Future<String> workspace({bool share = false}) async {
final path = await gFFI
.invokeMethodWithResult<String>('document_workspace', {'share': share});
if (path == null || path.isEmpty) {
throw StateError('App workspace is unavailable');
}
return path;
}
static Future<bool> requireLogFolder() async {
gFFI.ffiModel.beginAndroidDocumentPicker();
try {
final ready = await gFFI.invokeMethodWithResult<bool>(
'document_require_log_folder', {'checkOnly': true});
if (ready == null) {
throw StateError('Log directory setup did not complete');
}
if (ready) return true;
if (!await _confirmLogFolder()) return false;
final selected = await gFFI
.invokeMethodWithResult<bool>('document_require_log_folder');
if (selected == null) {
throw StateError('Log directory setup did not complete');
}
return selected;
} catch (error) {
debugPrint('Log directory setup failed');
await gFFI.dialogManager.show<void>(
(_, close, __) => CustomAlertDialog(
title: Text(translate('Error')),
content: Text(error is PlatformException
? translate(error.message ?? 'Failed')
: error.toString()),
actions: [
TextButton(onPressed: close, child: Text(translate('OK'))),
],
onSubmit: close,
onCancel: close,
),
backDismiss: true,
forceGlobal: true,
);
rethrow;
} finally {
gFFI.ffiModel.endAndroidDocumentPicker();
}
}
static Future<bool> _confirmLogFolder() async =>
await gFFI.dialogManager.show<bool>(
(_, close, __) => CustomAlertDialog(
title: Text(translate('Permissions')),
content: Text(
'${translate('android-logs-folder-tip')}\n'),
actions: [
TextButton(
onPressed: () => close(true),
child: Text(translate('Choose folder')),
),
],
onCancel: () => close(false),
),
backDismiss: true,
forceGlobal: true,
) ==
true;
}
-52
View File
@@ -1,52 +0,0 @@
import 'dart:io';
import 'package:path/path.dart' as path;
class DownloadPaths {
static Future<void> ensureNoLinks(String root, String destination) async {
if (!path.isWithin(root, destination)) {
throw FormatException('Invalid download directory: $destination');
}
var current = root;
for (final name in path.split(path.relative(destination, from: root))) {
current = path.join(current, name);
if (await FileSystemEntity.type(current, followLinks: false) ==
FileSystemEntityType.link) {
throw FormatException('Download directory contains a link: $current');
}
}
}
static bool validName(String name, {required bool windows}) {
if (name.isEmpty || name == '.' || name == '..' || name.contains('\x00')) {
return false;
}
if (name.contains('/')) return false;
return !windows ||
(!name.contains(RegExp(r'[<>:"\\|?*]')) &&
!name.endsWith('.') &&
!name.endsWith(' '));
}
static String mapDirectory(
String remoteRoot, String remotePath, String localRoot,
{required bool remoteWindows, required bool localWindows}) {
final remote = path.Context(
style: remoteWindows ? path.Style.windows : path.Style.posix);
final local = path.Context(
style: localWindows ? path.Style.windows : path.Style.posix);
if (remotePath.contains('\x00') ||
remote.split(remotePath).contains('..') ||
(!remote.equals(remoteRoot, remotePath) &&
!remote.isWithin(remoteRoot, remotePath))) {
throw FormatException('Invalid download directory: $remotePath');
}
final relative = remote.relative(remotePath, from: remoteRoot);
if (relative == '.') return localRoot;
final names = remote.split(relative);
if (names.any((name) => !validName(name, windows: localWindows))) {
throw FormatException('Invalid download directory: $remotePath');
}
return local.joinAll([localRoot, ...names]);
}
}
+6 -2
View File
@@ -96,12 +96,14 @@ class ImagePainter extends CustomPainter {
required this.x,
required this.y,
required this.scale,
this.useIntegerPosition = true,
});
ui.Image? image;
double x;
double y;
double scale;
final bool useIntegerPosition;
@override
void paint(Canvas canvas, Size size) {
@@ -122,8 +124,10 @@ class ImagePainter extends CustomPainter {
if (isWeb) {
paint.filterQuality = FilterQuality.high;
}
canvas.drawImage(
image!, Offset(x.toInt().toDouble(), y.toInt().toDouble()), paint);
final position = useIntegerPosition
? Offset(x.toInt().toDouble(), y.toInt().toDouble())
: Offset(x, y);
canvas.drawImage(image!, position, paint);
}
@override
+1 -109
View File
@@ -7,7 +7,6 @@ import 'package:uuid/uuid.dart';
import 'dart:html' as html;
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/models/shortcut_model.dart';
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');
@@ -27,14 +26,6 @@ sealed class EventToUI {
int field0,
bool field1,
) = EventToUI_Texture;
const factory EventToUI.cursor({
required String id,
required int hotx,
required int hoty,
required int width,
required int height,
required Uint8List colors,
}) = EventToUI_Cursor;
}
class EventToUI_Event implements EventToUI {
@@ -59,60 +50,7 @@ class EventToUI_Texture implements EventToUI {
bool get field1 => f1;
}
class EventToUI_Cursor implements EventToUI {
const EventToUI_Cursor({
required this.id,
required this.hotx,
required this.hoty,
required this.width,
required this.height,
required this.colors,
});
final String id;
final int hotx;
final int hoty;
final int width;
final int height;
final Uint8List colors;
}
class CursorShape {
final int hotx;
final int hoty;
final int width;
final int height;
final Uint8List colors;
const CursorShape({
required this.hotx,
required this.hoty,
required this.width,
required this.height,
required this.colors,
});
}
class RustdeskImpl {
// The core answers through the callback, before callMethod returns.
Future<CursorShape?> sessionGetCursorShape(
{required UuidValue sessionId, required String id, dynamic hint}) {
final completer = Completer<CursorShape?>();
js.context.callMethod('getCursorShape', [
id,
(int hotx, int hoty, int width, int height, Uint8List? colors) {
completer.complete(colors == null
? null
: CursorShape(
hotx: hotx,
hoty: hoty,
width: width,
height: height,
colors: colors));
}
]);
return completer.future;
}
Future<void> stopGlobalEventStream({required String appType, dynamic hint}) {
throw UnimplementedError("stopGlobalEventStream");
}
@@ -963,11 +901,7 @@ class RustdeskImpl {
}
String mainGetLocalOption({required String key, dynamic hint}) {
final v = js.context.callMethod('getByName', ['option:local', key]);
if (key == 'lang' && (v == 'pt' || v == 'br')) {
return 'pt-br';
}
return v;
return js.context.callMethod('getByName', ['option:local', key]);
}
// Do not return the real environment variables.
@@ -992,28 +926,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}) {
final inputSource =
js.context.callMethod('getByName', ['option:local', 'input-source']);
@@ -1260,17 +1172,6 @@ class RustdeskImpl {
}
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();
}
@@ -1834,10 +1735,6 @@ class RustdeskImpl {
throw UnimplementedError("mainRemoveTrustedDevices");
}
Future<void> mainRenewTrustedDevices({required String json, dynamic hint}) {
throw UnimplementedError("mainRenewTrustedDevices");
}
Future<void> mainClearTrustedDevices({dynamic hint}) {
throw UnimplementedError("mainClearTrustedDevices");
}
@@ -1932,11 +1829,6 @@ class RustdeskImpl {
}
String mainGetCommonSync({required String key, dynamic hint}) {
const prefix = 'resolve-api-server:';
if (key.startsWith(prefix)) {
return js.context
.callMethod('getByName', ['api_server', key.substring(prefix.length)]);
}
throw UnimplementedError("mainGetCommonSync");
}
+12 -18
View File
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:js' as js;
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
@@ -52,8 +53,9 @@ class CursorManager {
'cursor',
jsonEncode({
'url': cursorData.url,
'hotx': cursorData.hotX.toInt(),
'hoty': cursorData.hotY.toInt(),
// Rounding must keep the hotspot inside even a one-pixel raster.
'hotx': cursorData.hotX.round().clamp(0, cursorData.width - 1),
'hoty': cursorData.hotY.round().clamp(0, cursorData.height - 1),
})
]);
}
@@ -102,37 +104,29 @@ resetSystemCursor() => CursorManager.instance.resetSystemCursor();
MouseCursor buildCursorOfCache(
model.CursorModel cursor, double scale, model.CursorData? cache) {
if (cache == null) {
return _shownCursor(cursor);
return MouseCursor.defer;
} else {
final key = cursor.nativeKey(cache, scale);
// A short-edge minimum can enlarge thin artwork beyond CSS cursor limits.
// Keep unzoomed images unchanged and use the long edge when resizing.
final key = cache.updateGetKey(scale, useLegacyMinimum: scale == 1.0);
if (key == null) return MouseCursor.defer;
if (!cursor.cachedKeys.contains(key)) {
// data should be checked here, because it may be changed after `updateGetKey()`
final data = cache.data;
if (data == null) {
cursor.restorePixels(cache.id);
return _shownCursor(cursor);
return MouseCursor.defer;
}
debugPrint(
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
CursorManager.instance.registerCursor(CursorData(
key: key,
url: 'data:image/rgba;base64,${base64Encode(data)}',
width: (cache.width * cache.scale).toInt(),
height: (cache.height * cache.scale).toInt(),
width: max(1, (cache.width * cache.scale).round()),
height: max(1, (cache.height * cache.scale).round()),
hotX: cache.hotx,
hotY: cache.hoty));
cursor.addKey(key);
cursor.registered(cache, key);
}
cursor.shown(cache, key);
return FlutterCustomMemoryImageCursor(key: key);
}
}
// The last shape's cursor stays while the one in use is made, rather than the system one.
MouseCursor _shownCursor(model.CursorModel cursor) {
final key = cursor.shownKey;
return key == null
? MouseCursor.defer
: FlutterCustomMemoryImageCursor(key: key);
}
+5 -5
View File
@@ -339,8 +339,8 @@ packages:
dependency: "direct main"
description:
path: "."
ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
resolved-ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
resolved-ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
source: git
version: "0.1.0"
@@ -522,9 +522,9 @@ packages:
dependency: "direct main"
description:
path: "."
ref: db63b785c38153603e9fb84b50d3ec46f0d7e05e
resolved-ref: db63b785c38153603e9fb84b50d3ec46f0d7e05e
url: "https://github.com/rustdesk-org/flutter_custom_cursor"
ref: "ad940aaac3aada70958df2de761adda1a71aa2c4"
resolved-ref: "ad940aaac3aada70958df2de761adda1a71aa2c4"
url: "https://github.com/fufesou/flutter_custom_cursor"
source: git
version: "0.0.3"
flutter_gpu_texture_renderer:
+4 -4
View File
@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# 1.1.9-1 works for android, but for ios it becomes 1.1.91, need to set it to 1.1.9-a.1 for iOS, will get 1.1.9.1, but iOS store not allow 4 numbers
version: 1.5.1+68
version: 1.5.0+68
environment:
sdk: '^3.1.0'
@@ -58,12 +58,12 @@ dependencies:
desktop_multi_window:
git:
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
ref: cddc2e64f8fefce4f80db87b20bcda2dd019bed6
ref: 8b774a66671cbb9bcb2631af6ac28f9bdd469ce3
freezed_annotation: ^2.0.3
flutter_custom_cursor:
git:
url: https://github.com/rustdesk-org/flutter_custom_cursor
ref: db63b785c38153603e9fb84b50d3ec46f0d7e05e
url: https://github.com/fufesou/flutter_custom_cursor
ref: ad940aaac3aada70958df2de761adda1a71aa2c4
window_size:
git:
url: https://github.com/21pages/flutter-desktop-embedding.git
@@ -1,92 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/generated_bridge.dart';
import 'package:flutter_hbb/mobile/widgets/android_file_transfer_setup.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_hbb/models/server_model.dart';
import 'package:flutter_test/flutter_test.dart';
class _Binding extends Fake implements RustdeskImpl {
final options = <String, String>{};
@override
String translate(
{required String name, required String locale, dynamic hint}) =>
name;
@override
String getLocalFlutterOption({required String k, dynamic hint}) =>
options[k] ?? '';
@override
Future<void> setLocalFlutterOption(
{required String k, required String v, dynamic hint}) async {
options[k] = v;
}
@override
bool isDisableSettings({dynamic hint}) => false;
@override
bool isOutgoingOnly({dynamic hint}) => false;
@override
String mainGetBuildinOption({required String key, dynamic hint}) => '';
}
class _Server extends Fake implements ServerModel {
@override
List<Client> get clients => [];
}
class _Session extends Fake implements FFI {
@override
final dialogManager = OverlayDialogManager();
@override
final serverModel = _Server();
}
void main() {
late _Session session;
setUp(() {
platformFFI.setBindingForTesting(_Binding());
session = _Session();
});
Future<void> openApp(WidgetTester tester) => tester.pumpWidget(MaterialApp(
navigatorKey: globalKey,
home: const Scaffold(),
));
testWidgets('skipping folder setup suppresses later prompts', (tester) async {
await openApp(tester);
final first = showAndroidFileTransferSetup(session);
await tester.pumpAndSettle();
await tester.tap(find.text('Skip'));
await tester.pumpAndSettle();
expect(await first, isTrue);
expect(await showAndroidFileTransferSetup(_Session()), isTrue);
expect(find.byType(CustomAlertDialog), findsNothing);
});
testWidgets('canceling setup leaves it available at the next entry',
(tester) async {
await openApp(tester);
final first = showAndroidFileTransferSetup(session);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(await first, isFalse);
final retry = showAndroidFileTransferSetup(session);
await tester.pumpAndSettle();
expect(find.byType(CustomAlertDialog), findsOneWidget);
await tester.tap(find.text('Skip'));
await tester.pumpAndSettle();
expect(await retry, isTrue);
});
}
-80
View File
@@ -1,80 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
void main() {
test('warns only for remote HTTP endpoints', () {
final cases = <String?, bool>{
null: false,
'': false,
'https://api.example.com': false,
'http://api.example.com': true,
'http://192.168.1.13:13000': true,
'http://localhost:21114': false,
'http://127.0.0.1:21114': false,
'http://[::1]:21114': false,
};
for (final entry in cases.entries) {
expect(shouldWarnApiServer(entry.key), entry.value, reason: entry.key);
}
});
testWidgets('warning follows API and ID changes using the resolved endpoint',
(tester) async {
final api = TextEditingController();
final id = TextEditingController(text: 'id.example.com');
addTearDown(api.dispose);
addTearDown(id.dispose);
await tester.pumpWidget(MaterialApp(
home: ApiServerWarning(
controller: api,
idController: id,
message: 'HTTP warning',
emptyMessage: 'Default HTTP warning',
resolveApiServer: ({required api, required custom}) =>
api.isNotEmpty ? api : 'http://$custom',
),
));
expect(find.text('Default HTTP warning'), findsOneWidget);
id.text = 'localhost';
await tester.pump();
expect(find.text('Default HTTP warning'), findsNothing);
api.text = 'http://api.example.com';
await tester.pump();
expect(find.text('HTTP warning'), findsOneWidget);
api.text = 'https://api.example.com';
await tester.pump();
expect(find.text('HTTP warning'), findsNothing);
});
testWidgets('resolver failures are reported without breaking the server form',
(tester) async {
final api = TextEditingController();
final id = TextEditingController();
addTearDown(api.dispose);
addTearDown(id.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Column(children: [
TextField(controller: api),
Expanded(
child: ApiServerWarning(
controller: api,
idController: id,
message: 'HTTP warning',
emptyMessage: 'Default HTTP warning',
resolveApiServer: ({required api, required custom}) =>
throw const FormatException('API preview failed'),
)),
]),
),
));
expect(tester.takeException(), isA<FormatException>());
expect(find.byType(ErrorWidget), findsNothing);
expect(find.text('Default HTTP warning'), findsNothing);
expect(find.byType(TextField), findsOneWidget);
});
}
@@ -48,6 +48,74 @@ void main() {
expect(peers.single.online, isTrue);
});
test('peer copies preserve online state', () {
final peer = _peer(id: '987654321', online: true);
expect(Peer.copy(peer).online, isTrue);
});
test('online callbacks update autocomplete-only peers', () {
final peers = mergeAutocompletePeers(restRecentPeerIds: ['112233445']);
final changed = updateAutocompletePeerOnlineStates(
peers,
onlines: {'112233445'},
offlines: {},
);
expect(changed, isTrue);
expect(peers.single.online, isTrue);
});
test('online query ids are deduplicated and limited', () {
final peers = List.generate(
25,
(index) => _peer(id: index.toString()),
)..insert(1, _peer(id: '0'));
final ids = autocompleteOnlineQueryIds(peers, limit: 20);
expect(ids, hasLength(20));
expect(ids.first, '0');
expect(ids.where((id) => id == '0'), hasLength(1));
expect(ids.last, '19');
});
test('empty online query ids cancel pending debounce', () async {
final queriedIds = <List<String>>[];
final loader = AllPeersLoader(
queryOnlines: (ids) async {
queriedIds.add(ids);
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
loader.queryOnlines([]);
await Future.delayed(Duration(milliseconds: 2));
expect(queriedIds, isEmpty);
});
test('failed online query enqueue does not suppress retry', () async {
var queryCount = 0;
final loader = AllPeersLoader(
queryOnlines: (ids) {
queryCount += 1;
return Future<void>.error(Exception('queue full'));
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
expect(queryCount, 2);
});
test('online callback updates currently displayed options', () async {
final loader = AllPeersLoader(
queryOnlines: (ids) async {},
@@ -64,4 +132,17 @@ void main() {
expect(displayedOptions.single.online, isTrue);
await Future.delayed(Duration(milliseconds: 2));
});
test('cached online callback state is reapplied after peers merge', () {
final loader = AllPeersLoader();
loader.updateOnlineStateForTesting({
'onlines': '123456789',
'offlines': '',
});
final mergedPeers = [_peer(id: '123456789')];
loader.applyLastOnlineStateForTesting(mergedPeers);
expect(mergedPeers.single.online, isTrue);
});
}
+20
View File
@@ -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,
);
});
}
-66
View File
@@ -1,66 +0,0 @@
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
// A file of its own: nothing else in this isolate has made the default cursor before the model.
/// A core that keeps no shape.
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
@override
Future<CursorShape?> fetchCursorShape(String id) => Future.value(null);
@override
bool get showsRemoteCursor => false;
}
class _FFI extends Fake implements FFI {
_FFI() {
ffiModel = FfiModel(WeakReference(this));
cursorModel = _Cursor(this);
}
@override
final SessionID sessionId = const Uuid().v4obj();
@override
late final FfiModel ffiModel;
@override
late final CursorModel cursorModel;
}
String? _key(MouseCursor cursor) =>
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final channel = Platform.isWindows
? SystemChannels.mouseCursor
: const MethodChannel('flutter_custom_cursor');
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
(call) async => (call.arguments as Map<dynamic, dynamic>)['name']);
test('a shape the core cannot give shows the default cursor at once',
() async {
final ffi = _FFI();
final cursor = ffi.cursorModel;
final pixels = Uint8List.fromList(List.generate(8 * 8 * 4, (i) => i % 256));
await ffi.ffiModel.handleCursorData('1', 0, 0, 8, 8, pixels);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
final evt = {'id': '2'};
ffi.ffiModel.updateLastCursorId(evt);
ffi.ffiModel.handleCursorId(evt);
// Not a wait for the default cursor itself: asking for it would make it.
await Future<void>.delayed(const Duration(milliseconds: 500));
expect(cursor.cache, isNull);
final built = _key(buildCursorOfCache(
cursor, 1.0, cursor.cache ?? preDefaultCursor.cache));
expect(built, isNot(shown));
expect(built, contains('_${kPreDefaultCursorId}_'));
cursor.disposeImages();
});
}
@@ -0,0 +1,149 @@
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:flutter_custom_cursor/cursor_manager.dart' show CursorManager;
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/common.dart' as common;
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:image/image.dart' as img;
import 'package:provider/provider.dart';
import 'cursor_test_utils.dart';
void main() {
_rasterBoundsTests();
final registrations = <Map<dynamic, dynamic>>[];
captureNativeCursors(registrations);
for (final style in [kRemoteViewStyleAdaptive, kRemoteViewStyleCustom]) {
for (final (density, width, dpr) in [
(null, 4, 1.0),
('0', 4, 2.0),
(null, 32, 2.0),
('0', 32, 1.0),
]) {
testWidgets(
'legacy $style density=$density ${width}x32 DPR=$dpr',
(tester) => tester.runAsync(() => checkDensity(
tester, (style, density), registrations,
sourceSize: Size(width.toDouble(), 32), dpr: dpr)));
}
}
}
void _rasterBoundsTests() {
for (final (width, height, scale, legacy, rasterScale) in [
(32, 32, 1e300, false, 1.0),
(32, 32, 100.0, false, 2.0),
]) {
test('rejects raster ${width}x$height scale=$scale before key creation',
() async {
final image = await createTestImage(width: width, height: height);
addTearDown(image.dispose);
final data = CursorData(
peerId: 'bounds',
id: 'bounds',
image: img.Image(width: width, height: height, numChannels: 4),
nativeImage: image,
scale: 1,
data: null,
hotxOrigin: 0,
hotyOrigin: 0,
width: width,
height: height);
final initial = data.updateGetKey(1, resizeImage: false);
expect(
data.updateGetKey(scale,
resizeImage: false,
useLegacyMinimum: legacy,
rasterScale: rasterScale),
isNull);
expect(data.scale, 1);
expect(data.updateGetKey(1, resizeImage: false), initial);
});
}
}
Future<void> checkDensity(WidgetTester tester, (String, String?) input,
List<Map<dynamic, dynamic>> registrations,
{Size sourceSize = const Size(32, 32), double dpr = 1}) async {
final (style, density) = input;
final id = '$style-$density';
tester.view.devicePixelRatio = dpr;
addTearDown(tester.view.resetDevicePixelRatio);
final canvas = CursorTestCanvas(dpr, style: style, scale: 0.5);
final ffi = CursorTestFFI(canvas)..ffiModel.pi.platform = kPeerPlatformMacOS;
final cursor = CursorModel(WeakReference(ffi))..id = id;
addTearDown(() async {
expect(cursor.parent.target, same(ffi));
for (final key in cursor.cachedKeys) {
await deleteCustomCursor(key);
}
cursor.disposeImages();
cursor.dispose();
canvas.dispose();
});
await cursor.updateCursorData(_cursorEvent(id, density, size: sourceSize));
expect(cursor.cache!.pixelRatio, 0);
await _paintCursor(tester, ffi, cursor);
expect(tester.takeException(), isNull);
for (final key in cursor.cachedKeys) {
await CursorManager.instance.ensureCursorRegistered(key);
}
expect(registrations, hasLength(1));
await tester.pumpWidget(const SizedBox.shrink());
expect(cursor.cache!.scale, 1.0);
_expectLegacyRaster(registrations.single, sourceSize, dpr);
}
Future<void> _paintCursor(
WidgetTester tester, CursorTestFFI ffi, CursorModel cursor) async {
await tester.pumpWidget(MediaQuery(
data: MediaQueryData(devicePixelRatio: ffi.canvasModel.devicePixelRatio),
child: MultiProvider(
providers: [
ChangeNotifierProvider<ImageModel>(create: (_) => CursorTestImage()),
ChangeNotifierProvider<CanvasModel>.value(value: ffi.canvasModel),
ChangeNotifierProvider<CursorModel>.value(value: cursor),
],
child: ImagePaint(
ffi: ffi,
id: 'density-review',
zoomCursor: false.obs,
cursorOverImage: true.obs,
keyboardEnabled: true.obs,
remoteCursorMoved: false.obs)),
));
}
void _expectLegacyRaster(Map<dynamic, dynamic> args, Size size, double dpr) {
// Base unzoomed sizing is logical on macOS/GTK, physical on Windows.
final rasterScale = common.isWindows ? 1.0 : dpr;
final width = (size.width * rasterScale).toInt();
final height = (size.height * rasterScale).toInt();
final bufferWidth = common.isLinux ? size.longestSide * rasterScale : width;
expect((args['width'], args['height']), (bufferWidth, height));
expect((args['hotX'], args['hotY']),
((size.width ~/ 2) * rasterScale, (size.height ~/ 2) * rasterScale));
expect(args['imagePixelRatio'], dpr);
final decoded = decodeNativeCursorRaster(args);
expect((decoded.width, decoded.height), (bufferWidth, height));
expect(decoded.getPixel(width - 1, height - 1).a, 255);
if (bufferWidth > width) expect(decoded.getPixel(width, 0).a, 0);
}
Map<String, String> _cursorEvent(String id, String? density,
{Size size = const Size(32, 32)}) =>
{
'id': id,
'width': '${size.width.toInt()}',
'height': '${size.height.toInt()}',
'hotx': '${size.width ~/ 2}',
'hoty': '${size.height ~/ 2}',
if (density != null) 'scale': density,
'colors': jsonEncode(
List<int>.filled((size.width * size.height * 4).toInt(), 255)),
};
+236
View File
@@ -0,0 +1,236 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_custom_cursor/cursor_manager.dart' show CursorManager;
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:image/image.dart' as img;
import 'package:provider/provider.dart';
import 'cursor_test_utils.dart';
class _Cursor extends CursorModel {
_Cursor(this.cache, this._ffi) : super(WeakReference(_ffi));
final FFI _ffi;
@override
WeakReference<FFI> get parent => WeakReference(_ffi);
@override
CursorData cache;
@override
double get hotx => cache.hotxOrigin;
@override
double get hoty => cache.hotyOrigin;
}
class _LinuxDisplay extends Display {
@override
double get scale => 2;
}
Future<CursorData> _data(int density, String id,
{(int, int) source = (9, 18)}) async {
final bitmapDensity = density == 0 ? 1 : density;
final image = await createTestImage(
width: source.$1 * bitmapDensity, height: source.$2 * bitmapDensity);
return CursorData(
peerId: 'dpi-policy',
id: id,
image: img.Image(width: image.width, height: image.height, numChannels: 4),
nativeImage: image,
scale: 1,
data: Uint8List.fromList([1, 2]),
hotxOrigin: (source.$1 ~/ 2) * bitmapDensity.toDouble(),
hotyOrigin: (source.$2 ~/ 2) * bitmapDensity.toDouble(),
width: image.width,
height: image.height,
pixelRatio: density.toDouble(),
);
}
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final view = binding.platformDispatcher.views.single;
final windows = Platform.isWindows;
final registrations = <Map<dynamic, dynamic>>[];
captureNativeCursors(registrations);
tearDown(view.resetDevicePixelRatio);
for (final forbidden in [false, true]) {
test('predefined cursor forbidden=$forbidden preserves native RGBA', () {
view.devicePixelRatio = 1;
return _checkPredefinedCursor(
forbidden ? preForbiddenCursor : preDefaultCursor, registrations);
});
}
for (final testCase in [
(kRemoteViewStyleAdaptive, false, 0, 0.25, 1.0),
(kRemoteViewStyleCustom, false, 0, 0.25, 1.0),
(kRemoteViewStyleAdaptive, false, 1, 0.25, windows ? 2.0 : 1.0),
(kRemoteViewStyleAdaptive, false, 2, 0.25, windows ? 1.0 : 0.5),
(kRemoteViewStyleCustom, false, 2, 0.25, windows ? 1.0 : 0.5),
(kRemoteViewStyleAdaptive, true, 2, 0.25, windows ? 2 / 3 : 1 / 3),
(kRemoteViewStyleCustom, true, 2, 0.25, windows ? 2 / 3 : 1 / 3),
(kRemoteViewStyleOriginal, false, 1, 0.5, windows ? 1.0 : 2 / 3),
(kRemoteViewStyleOriginal, false, 2, 0.5, windows ? 1.0 : 0.5),
]) {
testWidgets(
'${testCase.$1} zoom=${testCase.$2} peerDPR=${testCase.$3}',
(tester) => tester
.runAsync(() => _checkPolicy(tester, testCase, registrations)));
}
test('live DPR changes invalidate a cached native cursor',
() => _checkDprChange(view, registrations));
for (final style in [kRemoteViewStyleAdaptive, kRemoteViewStyleCustom]) {
final dpr = style == kRemoteViewStyleAdaptive ? 1.0 : 2.0;
final source = style == kRemoteViewStyleAdaptive ? (64, 4) : (4, 64);
testWidgets('$style unknown-density thin cursor preserves zoom', (tester) =>
tester.runAsync(() => _checkPolicy(tester,
(style, true, 0, 0.5, windows ? 0.5 * dpr : 0.5), registrations,
dpr: dpr, source: source)));
testWidgets('$style forbidden cursor ignores remote DPR', (tester) =>
tester.runAsync(() => _checkPolicy(tester,
(style, false, 2, 0.25, 0.5), registrations, dpr: 1)));
testWidgets('Linux $style zoom follows video pixels', (tester) => tester.runAsync(
() => _checkPolicy(tester, (style, true, 2, 1.0, windows ? 1.0 : 0.5),
registrations, linux: true)));
}
}
Future<void> _checkPolicy(
WidgetTester tester,
(String, bool, int, double, double) testCase,
List<Map<dynamic, dynamic>> registrations,
{bool linux = false, double dpr = 2, (int, int) source = (9, 18)}) async {
final (style, zoom, density, viewScale, expectedScale) = testCase;
tester.view.devicePixelRatio = dpr;
final data = await _data(density, '$style-$zoom-$density', source: source);
final originalBytes = data.data;
// A stale cached DPR must not affect the cursor when the window moves.
final canvas = CursorTestCanvas(1, style: style, scale: viewScale);
final ffi = CursorTestFFI(canvas);
ffi.ffiModel.isPeerLinux = linux;
if (linux) ffi.ffiModel.pi.displays.add(_LinuxDisplay());
final cursor = _Cursor(data, ffi);
final keyboardEnabled = true.obs;
await tester.pumpWidget(MediaQuery(
data: MediaQueryData(devicePixelRatio: dpr),
child: MultiProvider(
providers: [
ChangeNotifierProvider<ImageModel>(create: (_) => CursorTestImage()),
ChangeNotifierProvider<CanvasModel>.value(value: canvas),
ChangeNotifierProvider<CursorModel>.value(value: cursor),
],
child: ImagePaint(
ffi: ffi,
id: 'dpi-policy',
zoomCursor: zoom.obs,
cursorOverImage: true.obs,
keyboardEnabled: keyboardEnabled,
remoteCursorMoved: false.obs,
)),
));
final revoke = !zoom && style != kRemoteViewStyleOriginal;
if (revoke) {
await Future.wait(cursor.cachedKeys
.map(CursorManager.instance.ensureCursorRegistered));
keyboardEnabled.value = false;
await tester.pump();
}
await tester.pumpWidget(const SizedBox.shrink());
for (final key in cursor.cachedKeys) {
await deleteCustomCursor(key);
}
data.nativeImage.dispose();
cursor.dispose();
canvas.dispose();
expect(data.scale, closeTo(expectedScale, 1e-9));
expect(data.hotx, closeTo(data.hotxOrigin * expectedScale, 1e-9));
expect(data.hoty, closeTo(data.hotyOrigin * expectedScale, 1e-9));
expect(data.data, same(originalBytes));
if (zoom && density == 0) {
final args = registrations.single;
final rasterScale = expectedScale * (Platform.isWindows ? 1 : dpr);
final width = source.$1 * rasterScale;
final height = source.$2 * rasterScale;
expect((args['width'], args['height']),
(Platform.isLinux && height > width ? height : width, height));
expect((args['hotX'], args['hotY']),
((source.$1 ~/ 2) * rasterScale, (source.$2 ~/ 2) * rasterScale));
}
if (revoke) {
final args = registrations.last;
expect(args['name'], contains('_${kPreForbiddenCursorId}_'));
final rasterSize = 32 * (Platform.isWindows ? 1 : dpr);
expect((args['width'], args['height']), (rasterSize, rasterSize));
expect((args['hotX'], args['hotY']), (0.0, 0.0));
}
if (style == kRemoteViewStyleAdaptive && !zoom && density > 0) {
final args = registrations.first;
expect((args['width'], args['height']), ((Platform.isLinux ? 18 : 9) * dpr, 18 * dpr));
expect((args['hotX'], args['hotY']), (4 * dpr, 9 * dpr));
expect(args['imagePixelRatio'], dpr);
}
}
Future<void> _checkDprChange(
TestFlutterView view, List<Map<dynamic, dynamic>> registrations) async {
// Keep the scale above the minimum so only DPR invalidates the cache.
final data = await _data(2, 'dpr-cache');
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 1);
final cursor = _Cursor(data, CursorTestFFI(canvas));
for (final dpr in [2.0, 1.0]) {
view.devicePixelRatio = dpr;
buildCursorOfCache(cursor, 1, data);
await deleteCustomCursor(cursor.cachedKeys.last);
}
expect(registrations, hasLength(2));
expect(registrations[0]['name'], isNot(registrations[1]['name']));
data.nativeImage.dispose();
cursor.dispose();
canvas.dispose();
}
Future<void> _checkPredefinedCursor(PredefinedCursor predefined,
List<Map<dynamic, dynamic>> registrations) async {
await Future.doWhile(() async {
await Future<void>.delayed(const Duration(milliseconds: 10));
return predefined.cache == null;
}).timeout(const Duration(seconds: 5));
final cache = predefined.cache!;
final original = img
.decodePng(base64Decode(predefined.png))!
.convert(format: img.Format.uint8, numChannels: 4);
final canvas = CursorTestCanvas(1, style: kRemoteViewStyleAdaptive, scale: 1);
final cursor = _Cursor(cache, CursorTestFFI(canvas));
buildCursorOfCache(cursor, 1, cache);
await deleteCustomCursor(cursor.cachedKeys.single);
cursor.dispose();
canvas.dispose();
final args = registrations.single;
final decoded = decodeNativeCursorRaster(args);
expect((decoded.width, decoded.height), (original.width, original.height));
expect(args['imagePixelRatio'], 1.0);
expect((args['hotX'], args['hotY']), (cache.hotxOrigin, cache.hotyOrigin));
expect(cache.image.getBytes(), original.getBytes());
// Actual bundled pixels cover transparent, opaque and translucent colors.
for (final (x, y) in [(0, 0), (1, 8), (13, 22), (16, 16)]) {
final expected = original.getPixel(x, y);
final actual = decoded.getPixel(x, y);
expect(actual.a, expected.a);
for (final (got, want) in [
(actual.r, expected.r),
(actual.g, expected.g),
(actual.b, expected.b)
]) {
expect(got, closeTo(want, 1), reason: '${predefined.id} at ($x, $y)');
}
}
}
+252
View File
@@ -0,0 +1,252 @@
import 'dart:convert';
import 'dart:ui' as ui;
import 'package:flutter/widgets.dart';
import 'package:flutter_custom_cursor/cursor_manager.dart' as cursor_manager;
import 'package:flutter_hbb/common/shared_state.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
import 'package:flutter_hbb/models/desktop_render_texture.dart';
import 'package:flutter_hbb/models/input_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import 'cursor_test_utils.dart';
const _viewport = Size(1920, 540);
const _id = 'local-display-review';
const _side = 64;
const _hotspot = Offset(8, 12);
class _Display extends Display {
_Display(this.density, double left, int w, int h) {
x = left;
width = w;
height = h;
}
final double density;
@override
double get scale => density;
}
class _Peer extends Fake implements FfiModel {
_Peer() {
pi.platform = kPeerPlatformLinux;
pi.currentDisplay = kAllDisplayValue;
pi.displays.assignAll([
_Display(2, 0, 3840, 2160),
_Display(1, 1920, 1920, 1080),
]);
}
@override
final pi = PeerInfo();
@override
bool get isPeerLinux => true;
@override
bool get keyboard => true;
@override
bool get viewOnly => false;
@override
Rect get rect => const Rect.fromLTWH(0, 0, 3840, 1080);
}
class _Texture extends Fake implements TextureModel {
final ids = <int, RxInt>{};
@override
RxInt getTextureId(int display) =>
ids.putIfAbsent(display, () => display.obs);
}
class _Canvas extends CanvasModel {
_Canvas(FFI ffi, String style)
: viewStyle = ViewStyle(
style: style,
width: 1920,
height: 540,
displayWidth: 3840,
displayHeight: 1080),
super(WeakReference(ffi)) {
id = _id;
}
@override
double get scale => 0.5;
@override
Size get size => _viewport;
@override
bool get cursorEmbedded => false;
@override
final ViewStyle viewStyle;
}
class _FFI extends Fake implements FFI {
_FFI(String style) {
canvasModel = _Canvas(this, style);
cursorModel = CursorModel(WeakReference(this));
inputModel = InputModel(WeakReference(this));
}
@override
final sessionId = Uuid().v4obj();
@override
String get id => _id;
@override
final ffiModel = _Peer();
@override
final imageModel = CursorTestImage(useTextureRender: true);
@override
final textureModel = _Texture();
@override
late final CanvasModel canvasModel;
@override
late final CursorModel cursorModel;
@override
late final InputModel inputModel;
Offset? mappedPosition;
}
Future<void> _shape(_FFI ffi, String id) async {
ffi.cursorModel.id = id;
await ffi.cursorModel.updateCursorData({
'id': id,
'width': '$_side',
'height': '$_side',
'scale': '2',
'hotx': '${_hotspot.dx}',
'hoty': '${_hotspot.dy}',
'colors': jsonEncode(List.generate(_side * _side * 4, (_) => 255)),
});
}
Widget _widget(_FFI ffi, double dpr) => Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(devicePixelRatio: dpr),
child: MultiProvider(
providers: [
ChangeNotifierProvider<ImageModel>.value(value: ffi.imageModel),
ChangeNotifierProvider<CanvasModel>.value(value: ffi.canvasModel),
ChangeNotifierProvider<CursorModel>.value(value: ffi.cursorModel),
],
child: ImagePaint(
ffi: ffi,
id: _id,
zoomCursor: true.obs,
cursorOverImage: true.obs,
keyboardEnabled: true.obs,
remoteCursorMoved: RemoteCursorMovedState.find(_id),
listenerBuilder: (child) => Listener(
child: child,
onPointerHover: (e) {
final point = ffi.inputModel.handlePointerDevicePos(
kPointerEventKindMouse,
e.position.dx,
e.position.dy,
true,
kMouseEventTypeDefault,
moveCanvas: false);
if (point != null) {
ffi.mappedPosition =
Offset(point.x.toDouble(), point.y.toDouble());
}
})))));
Future<void> _settle(WidgetTester tester, _FFI ffi) async {
await tester.pump();
for (final key in ffi.cursorModel.cachedKeys) {
await cursor_manager.CursorManager.instance.ensureCursorRegistered(key);
}
await tester.pump();
}
void main() {
final registrations = <Map<dynamic, dynamic>>[];
final activations = <String>[];
captureNativeCursors(registrations, activations: activations);
setUp(() => RemoteCursorMovedState.init(_id));
tearDown(() => RemoteCursorMovedState.delete(_id));
for (final (style, dpr) in [
(kRemoteViewStyleAdaptive, 1.0),
(kRemoteViewStyleCustom, 2.0),
]) {
for (final mode in ['movement', 'shape refresh', 'host position control']) {
testWidgets(
'mixed displays: $style DPR=$dpr $mode',
(tester) => tester.runAsync(
() => _checkMovement(tester, (style, dpr, mode), (registrations, activations))));
}
}
}
Future<void> _checkMovement(
WidgetTester tester,
(String, double, String) testCase,
(List<Map<dynamic, dynamic>>, List<String>) calls) async {
final (style, dpr, mode) = testCase;
final (registrations, activations) = calls;
tester.view.devicePixelRatio = dpr;
tester.view.physicalSize = _viewport * dpr;
addTearDown(tester.view.reset);
final ffi = _FFI(style);
addTearDown(() => _dispose(ffi));
await _shape(ffi, '$style-$dpr-$mode-1');
await ffi.cursorModel.updateCursorPosition({'x': '100', 'y': '100'}, _id);
ffi.canvasModel.updateLocalCursor(50, 50);
await tester.pumpWidget(_widget(ffi, dpr));
await _settle(tester, ffi);
expect(registrations.last['width'], 16 * dpr);
await _moveToB(tester, ffi, (mode, activations));
final args = registrations.last;
expect((args['width'], args['height']), (32 * dpr, 32 * dpr));
expect((args['hotX'], args['hotY']), (4 * dpr, 6 * dpr));
}
Future<void> _moveToB(WidgetTester tester, _FFI ffi, (String, List<String>) testCase) async {
final (mode, activations) = testCase;
final mouse = await tester.createGesture(kind: ui.PointerDeviceKind.mouse);
await mouse.addPointer(location: const Offset(50, 50));
await _settle(tester, ffi);
final before = activations.length;
for (final x in [60.0, 70.0, 80.0]) {
await mouse.moveTo(Offset(x, 50));
await _settle(tester, ffi);
expect(activations.length, before);
}
await mouse.moveTo(
Offset(1100 + CanvasModel.leftToEdge, 50 + CanvasModel.topToEdge));
await _settle(tester, ffi);
expect(activations.length, before + 1);
expect(ffi.mappedPosition, const Offset(2200, 100));
expect(ffi.cursorModel.offset, const Offset(100, 100));
if (mode == 'shape refresh') {
await _shape(ffi, '$mode-2');
} else if (mode == 'host position control') {
await ffi.cursorModel.updateCursorPosition({'x': '2200', 'y': '100'}, _id);
ffi.canvasModel.updateLocalCursor(1100, 50);
}
await _settle(tester, ffi);
final after = activations.length;
expect(after, before + (mode == 'shape refresh' ? 2 : 1));
for (final x in [1110.0, 1120.0, 1130.0]) {
await mouse.moveTo(Offset(x, 50));
await _settle(tester, ffi);
expect(activations.length, after);
}
final displayB = tester.widgetList<Positioned>(find.byType(Positioned)).last;
expect(displayB.width! / 1920, 0.5);
await mouse.removePointer();
}
Future<void> _dispose(_FFI ffi) async {
for (final key in ffi.cursorModel.cachedKeys) {
await deleteCustomCursor(key);
}
ffi.cursorModel.disposeImages();
ffi.cursorModel.dispose();
ffi.canvasModel.dispose();
ffi.imageModel.dispose();
// Relative mode is never started and this fixture has no Rust session.
ffi.inputModel.disposeSideButtonTracking();
}
+118
View File
@@ -0,0 +1,118 @@
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:image/image.dart' as img;
import 'cursor_test_utils.dart';
const _side = 32;
const _hotspot = Offset(7, 9);
const _colors = [
[64, 32, 16, 128],
[240, 100, 20, 255],
[0, 0, 0, 0],
[0, 0, 0, 128],
];
final _stripeWidth = _side ~/ _colors.length;
class _Canvas extends Fake implements CanvasModel {
@override
final viewStyle = ViewStyle(
style: kRemoteViewStyleAdaptive,
width: 200,
height: 160,
displayWidth: 200,
displayHeight: 160);
}
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final view = binding.platformDispatcher.views.single;
final registrations = <Map<dynamic, dynamic>>[];
captureNativeCursors(registrations);
tearDown(view.resetDevicePixelRatio);
for (final testCase in <(String, String?, List<int>)>[
(kPeerPlatformMacOS, null, [64, 32, 16, 128]),
(kPeerPlatformWindows, '0', [64, 32, 16, 128]),
(kPeerPlatformLinux, '0', [32, 16, 8, 128]),
]) {
for (final dpr in [1.0, 2.0]) {
test(
'native ${testCase.$1} scale=${testCase.$2} DPR=$dpr preserves alpha',
() {
view.devicePixelRatio = dpr;
return _checkCursor(testCase, dpr, registrations);
});
}
}
}
Future<void> _checkCursor((String, String?, List<int>) testCase, double dpr,
List<Map<dynamic, dynamic>> registrations) async {
final (platform, density, color) = testCase;
final ffi = CursorTestFFI(_Canvas())..ffiModel.pi.platform = platform;
final cursor = CursorModel(WeakReference(ffi))..id = '$testCase-$dpr';
addTearDown(() {
cursor.disposeImages();
cursor.dispose();
});
final palette = [color, ..._colors.skip(1)];
final rgba = [
for (var y = 0; y < _side; y++)
for (var x = 0; x < _side; x++) ...palette[x ~/ _stripeWidth]
];
await cursor.updateCursorData({
'id': '$testCase-$dpr',
'width': '$_side',
'height': '$_side',
'hotx': '${_hotspot.dx}',
'hoty': '${_hotspot.dy}',
if (density != null) 'scale': density,
'colors': jsonEncode(rgba),
});
final cache = cursor.cache!;
buildCursorOfCache(cursor, Platform.isWindows ? dpr : 1, cache);
await deleteCustomCursor(cursor.cachedKeys.single);
expect(cache.image.getBytes(), rgba); // Keep the original byte-cache source.
_checkRegistration(registrations.single, dpr);
// The same ui.Image also supplies the painted remote cursor.
final straight = await cache.nativeImage
.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
_checkColors(img.Image.fromBytes(
width: _side,
height: _side,
bytes: straight!.buffer,
bytesOffset: straight.offsetInBytes,
order: img.ChannelOrder.rgba));
// Real sessions own FFI strongly throughout asynchronous cursor decoding.
expect(cursor.parent.target, same(ffi));
}
void _checkRegistration(Map<dynamic, dynamic> args, double dpr) {
final decoded = decodeNativeCursorRaster(args);
expect((decoded.width, decoded.height), (_side * dpr, _side * dpr));
expect((args['hotX'], args['hotY']), (_hotspot.dx * dpr, _hotspot.dy * dpr));
_checkColors(decoded);
}
void _checkColors(img.Image bitmap) {
for (var stripe = 0; stripe < _colors.length; stripe++) {
final pixel = bitmap.getPixel(
((stripe + 0.5) * bitmap.width / _colors.length).floor(),
bitmap.height ~/ 2);
final expected = _colors[stripe];
expect(pixel.a, expected.last);
for (final (actual, wanted) in [
(pixel.r, expected[0]),
(pixel.g, expected[1]),
(pixel.b, expected[2])
]) {
expect(actual, closeTo(wanted, 1), reason: 'RGBA stripe $stripe');
}
}
}
+287
View File
@@ -0,0 +1,287 @@
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter/widgets.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/pages/remote_page.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/utils/image.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'cursor_test_utils.dart';
const _hotspot = Offset(4, 9);
const _remotePosition = Offset(100.25, 80.75);
const _canvasOffset = Offset(15.125, -10.25);
const _viewport = Size(200, 160);
class _CursorModel extends ChangeNotifier implements CursorModel {
_CursorModel(this.image, this.position, this.density, {this.hotspot = _hotspot});
final Offset position;
final double density;
final Offset hotspot;
@override
CursorData get cache => _Density(density);
@override
final ui.Image image;
@override
double get hotx => hotspot.dx;
@override
double get hoty => hotspot.dy;
@override
double get x => position.dx;
@override
double get y => position.dy;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _Density extends Fake implements CursorData {
_Density(this.pixelRatio);
@override
final double pixelRatio;
}
class _ImageModel extends ChangeNotifier implements ImageModel {
_ImageModel(this.useTextureRender);
@override
final bool useTextureRender;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _Display extends Display {
_Display(this.scale, double left) {
x = left;
width = 3840;
height = 2160;
}
@override
final double scale;
}
class _Peer extends Fake implements FfiModel {
@override
final pi = PeerInfo()
..displays.add(Display()
..width = _viewport.width.toInt()
..height = _viewport.height.toInt());
@override
bool isPeerLinux = false;
@override
Rect rect = Offset.zero & _viewport;
}
class _FFI extends Fake implements FFI {
_FFI(bool useTexture) : imageModel = _ImageModel(useTexture);
@override
final ImageModel imageModel;
@override
final _Peer ffiModel = _Peer();
@override
final textureModel = CursorTestTexture();
@override
late CanvasModel canvasModel;
}
class _CanvasModel extends ChangeNotifier implements CanvasModel {
_CanvasModel(String style, this.scale, bool useTexture)
: _ffi = _FFI(useTexture),
viewStyle = ViewStyle(
style: style,
width: _viewport.width,
height: _viewport.height,
displayWidth: _viewport.width.toInt(),
displayHeight: _viewport.height.toInt(),
) {
_ffi.canvasModel = this;
}
final _FFI _ffi;
@override
WeakReference<FFI> get parent => WeakReference(_ffi);
@override
final imageOverflow = false.obs;
@override
final ViewStyle viewStyle;
@override
double get x => _canvasOffset.dx;
@override
double get y => _canvasOffset.dy;
@override
final double scale;
@override
ScrollStyle get scrollStyle => ScrollStyle.scrollauto;
@override
Size get size => _viewport;
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _ScrollbarCanvasModel extends _CanvasModel {
_ScrollbarCanvasModel(String style, {Size? frame, double scale = 2})
: super(style, scale, true) {
imageOverflow.value = true;
if (frame != null) _ffi.ffiModel.rect = Offset.zero & frame;
}
@override
ScrollStyle get scrollStyle => ScrollStyle.scrollbar;
@override
double get scrollX => _ffi.ffiModel.rect.width * scale > size.width ? 0.1 : 0;
@override
double get scrollY => _ffi.ffiModel.rect.height * scale > size.height ? 0.2 : 0;
}
Future<ImagePainter> _paintCursor(WidgetTester tester, CanvasModel canvas,
{double dpr = 2, bool zoom = true, (int, int) source = (48, 64),
Offset position = _remotePosition, double density = 0,
Offset hotspot = _hotspot}) async {
final image = (await tester
.runAsync(() => createTestImage(width: source.$1, height: source.$2)))!;
addTearDown(image.dispose);
tester.view.devicePixelRatio = dpr;
tester.view.physicalSize = _viewport * dpr;
addTearDown(tester.view.reset);
await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData(devicePixelRatio: dpr),
child: MultiProvider(
providers: [
ChangeNotifierProvider<ImageModel>.value(value: canvas.parent.target!.imageModel),
ChangeNotifierProvider<CursorModel>(create: (_) => _CursorModel(image, position, density, hotspot: hotspot)),
ChangeNotifierProvider<CanvasModel>(create: (_) => canvas),
],
child: Stack(fit: StackFit.expand, children: [
// Measure the video's origin instead of copying its rounding policy.
if (canvas.parent.target!.imageModel.useTextureRender &&
canvas.scrollStyle == ScrollStyle.scrollauto)
ImagePaint(ffi: canvas.parent.target!, id: 'cursor-test',
zoomCursor: zoom.obs, cursorOverImage: false.obs,
keyboardEnabled: true.obs, remoteCursorMoved: false.obs),
CursorPaint(id: 'cursor-test', zoomCursor: zoom.obs),
]),
),
)));
final painter = tester.widget<CustomPaint>(find.byType(CustomPaint)).painter!
as ImagePainter;
expect(painter.image, same(image));
return painter;
}
void _linuxDisplayTests() {
for (final (texture, displayScale, allDisplays) in [
(false, 2.0, false), (true, 2.0, false), (true, 2.0, true),
(false, 1.0, false), (true, 1.0, false),
]) {
testWidgets('Linux scale=$displayScale texture=$texture all=$allDisplays',
(tester) async {
final canvas = _CanvasModel(kRemoteViewStyleCustom, 2, texture);
final peer = canvas._ffi.ffiModel;
peer.isPeerLinux = true;
// The first output's physical extent overlaps the second in logical
// coordinates. Selection must use logical extents and the union origin.
peer.pi.displays.assignAll([
if (displayScale > 1) _Display(4, -960), _Display(displayScale, 0),
]);
peer.pi.currentDisplay = allDisplays ? kAllDisplayValue
: peer.pi.displays.length - 1;
peer.rect = Rect.fromLTWH(allDisplays ? -960 : 0, 0, 3840, 2160);
final painter = await _paintCursor(tester, canvas,
dpr: 1, zoom: false, source: (64, 64), density: 2,
position: allDisplays ? _remotePosition + const Offset(960, 0)
: _remotePosition);
final pixelScale = 2 / displayScale;
expect(painter.scale, pixelScale);
final origin = texture ? tester.getTopLeft(find.byType(Texture).first)
: Offset((_canvasOffset.dx / pixelScale).toInt() * pixelScale,
(_canvasOffset.dy / pixelScale).toInt() * pixelScale);
final position = allDisplays
? _remotePosition + const Offset(960, 0) : _remotePosition;
expect((Offset(painter.x, painter.y) + _hotspot) * painter.scale,
position * 2 + origin);
});
}
}
void main() {
_linuxDisplayTests();
final minimumScale = Platform.isWindows ? 1 / 3 : 2 / 3;
for (final (style, zoom, dpr, source, canvasScale, scale, texture, density) in [
(kRemoteViewStyleAdaptive, false, 2.0, (48, 64), 0.375, 0.375, true, 0.0),
(kRemoteViewStyleOriginal, false, 2.0, (48, 64), 0.5, 0.5, true, 0.0),
(kRemoteViewStyleCustom, false, 2.0, (48, 64), 0.25, 0.25, false, 0.0),
(kRemoteViewStyleCustom, true, 2.0, (48, 64), 2.0, 2.0, false, 0.0),
(kRemoteViewStyleAdaptive, false, 2.25, (48, 48), 0.375, 0.375, false, 0.0),
(kRemoteViewStyleAdaptive, true, 2.0, (9, 18), 0.1, minimumScale, true, 0.0),
(kRemoteViewStyleAdaptive, true, 1.0, (64, 4), 0.5, 0.5, true, 0.0),
(kRemoteViewStyleCustom, true, 2.0, (4, 64), 0.5, 0.5, true, 0.0),
(kRemoteViewStyleAdaptive, true, 1.0, (48, 64), 0.05, 0.1875, true, 2.0),
(kRemoteViewStyleAdaptive, true, 2.0, (48, 64), 0.05, 0.1875, true, 2.0),
(kRemoteViewStyleCustom, true, 1.0, (48, 64), 0.05, 0.1875, true, 2.0),
(kRemoteViewStyleCustom, true, 2.0, (48, 64), 0.05, 0.1875, true, 2.0),
(kRemoteViewStyleCustom, true, 2.0, (8, 10), 1.0, 1.2, true, 2.0),
(kRemoteViewStyleOriginal, true, 1.0, (48, 64), 0.05, 0.1875, true, 2.0),
(kRemoteViewStyleOriginal, true, 2.0, (48, 64), 0.05,
Platform.isWindows ? 0.09375 : 0.1875, true, 2.0),
]) {
testWidgets(
'$style zoom=$zoom dpr=$dpr source=$source texture=$texture density=$density keeps remote geometry',
(tester) async {
final sourceHotspot = source.$1 <= _hotspot.dx || source.$2 <= _hotspot.dy
? Offset(source.$1 / 2, source.$2 / 2) : _hotspot;
final painter = await _paintCursor(
tester, _CanvasModel(style, canvasScale, texture),
dpr: dpr, zoom: zoom, source: source, density: density,
hotspot: sourceHotspot);
expect(painter.scale, scale);
var imageOrigin = texture
? tester.getTopLeft(find.byType(Texture).first) : _canvasOffset;
if (!texture) {
final background = CursorTestDraw();
ImagePainter(
image: painter.image,
x: _canvasOffset.dx / canvasScale,
y: _canvasOffset.dy / canvasScale,
scale: canvasScale,
).paint(background, _viewport);
imageOrigin = background.position!;
}
final target = _remotePosition * canvasScale + imageOrigin;
final hotspot = (Offset(painter.x, painter.y) + sourceHotspot) * scale;
expect(hotspot.dx, closeTo(target.dx, 1e-9));
expect(hotspot.dy, closeTo(target.dy, 1e-9));
final canvas = CursorTestDraw();
painter.paint(canvas, _viewport);
final position = canvas.position! + sourceHotspot * canvas.factor;
expect(position.dx, closeTo(target.dx, 1e-9));
expect(position.dy, closeTo(target.dy, 1e-9));
});
}
for (final style in [kRemoteViewStyleOriginal, kRemoteViewStyleCustom]) {
for (final (frame, scale, offset) in [
(_viewport, 2.0, const Offset(-40, -64)),
(const Size(199, 320), 1.0, const Offset(0, -64)),
(const Size(198, 320), 1.0, const Offset(1, -64)),
(const Size(400, 159), 1.0, const Offset(-40, 0)),
(const Size(400, 158), 1.0, const Offset(-40, 1)),
]) {
testWidgets('$style frame=$frame painted cursor follows scrollbar layout',
(tester) async {
final painter = await _paintCursor(
tester, _ScrollbarCanvasModel(style, frame: frame, scale: scale));
final target = _remotePosition * scale + offset;
expect((Offset(painter.x, painter.y) + _hotspot) * painter.scale, target);
});
}
}
}
-225
View File
@@ -1,225 +0,0 @@
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
/// Stands in for the core, which keeps every shape the peer sent.
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final core = <String, CursorShape>{};
final fetched = <String>[];
@override
Future<CursorShape?> fetchCursorShape(String id) {
fetched.add(id);
return Future.value(core[id]);
}
@override
bool get showsRemoteCursor => false;
}
String? _key(MouseCursor cursor) =>
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
class _FFI extends Fake implements FFI {
_FFI() {
ffiModel = FfiModel(WeakReference(this));
cursorModel = _Cursor(this);
}
@override
final SessionID sessionId = const Uuid().v4obj();
@override
late final FfiModel ffiModel;
@override
late final CursorModel cursorModel;
_Cursor get cursor => cursorModel as _Cursor;
}
Uint8List _pixels(int size, int seed) =>
Uint8List.fromList(List.generate(size * size * 4, (i) => (i + seed) % 256));
/// A shape as the core delivers it, and keeps it.
Future<void> _feed(_FFI ffi, String id, {int size = 8, int seed = 0}) {
final pixels = _pixels(size, seed);
ffi.cursor.core[id] =
CursorShape(hotx: 0, hoty: 0, width: size, height: size, colors: pixels);
return ffi.ffiModel.handleCursorData(id, 0, 0, size, size, pixels);
}
void _select(_FFI ffi, String id) {
final evt = {'id': id};
ffi.ffiModel.updateLastCursorId(evt);
ffi.ffiModel.handleCursorId(evt);
}
Future<void> _settle() async {
for (var i = 0; i < 2; i++) {
await Future<void>.delayed(const Duration(milliseconds: 5));
}
}
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final channel = Platform.isWindows
? SystemChannels.mouseCursor
: const MethodChannel('flutter_custom_cursor');
final registered = <String>[];
final deleted = <String>[];
late _FFI ffi;
setUp(() {
registered.clear();
deleted.clear();
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
(call) async {
final args = call.arguments as Map<dynamic, dynamic>;
if (call.method.startsWith('createCustomCursor')) {
registered.add(args['name'] as String);
return args['name'];
}
if (call.method.startsWith('deleteCustomCursor')) {
deleted.add(args['name'] as String);
}
return null;
});
ffi = _FFI();
});
tearDown(() {
ffi.cursorModel.disposeImages();
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);
});
test(
'only the shape in use keeps an image, and a shape its native cursor holds '
'keeps no pixels', () async {
final cursor = ffi.cursorModel;
for (var round = 0; round < 3; round++) {
for (final (id, seed) in [('1', 1), ('2', 2), ('3', 3)]) {
await _feed(ffi, id, seed: seed);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
}
expect(ffi.cursorModel.shapeIds, ['3']);
for (final id in ['1', '2']) {
expect(ffi.cursorModel.cachedShape(id)!.hasPixels, isFalse);
expect(ffi.cursorModel.cachedShape(id)!.data, isNull);
}
expect(ffi.cursor.fetched, isEmpty);
});
test('the shape in use keeps its pixels, and a new raster is made at once',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
expect(cursor.cache!.hasPixels, isTrue);
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
isNot(MouseCursor.defer));
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'nothing had to be decoded');
expect(registered.length, 2);
expect((cursor.cache!.rasterWidth, cursor.cache!.rasterHeight), (16, 16));
await _feed(ffi, '2');
expect(cursor.cachedShape('1')!.hasPixels, isFalse,
reason: 'switched away from, a shape keeps no pixels');
_select(ffi, '1');
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
isNot(MouseCursor.defer));
await _settle();
expect(registered.length, 2, reason: 'its native cursor is still there');
expect(ffi.cursor.fetched, isEmpty);
});
test('native cursors stay for the session, every raster of every shape',
() async {
// A delete frees nothing on Windows, so none is deleted before the session ends.
final cursor = ffi.cursorModel;
for (var i = 0; i < 100; i++) {
await _feed(ffi, '$i', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(deleted, isEmpty);
expect(cursor.cachedKeys.length, 100);
_select(ffi, '0');
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)),
cursor.nativeKey(cursor.cache!, 1.0));
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'its cursor is still there');
expect(registered.length, 100);
});
test('a new raster of a shape without pixels keeps the cursor shown before',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, '2', size: 32);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
_select(ffi, '1'); // its native cursor held its pixels, so they went
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
await _settle();
expect(ffi.cursor.fetched, ['1']);
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)),
cursor.nativeKey(cursor.cache!, 0.5));
});
test('a shape painted again is decoded again, the last one shown meanwhile',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
expect(ffi.cursorModel.image?.width, 8, reason: 'shape 2 until 1 is back');
await _settle();
expect(ffi.cursor.fetched, ['1']);
expect(ffi.cursorModel.image?.width, 16);
expect(ffi.cursorModel.shapeIds, ['1']);
});
test('a moved tab carries the id in use, and its window asks the core',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
await _feed(ffi, '1', size: 16);
final carried = ffi.ffiModel.cachedPeerData.toString();
expect(carried, isNot(contains('colors')));
expect(CachedPeerData.fromString(carried)!.lastCursorId['id'], '1',
reason: 'a shape arriving is the shape in use');
final moved = _FFI();
addTearDown(moved.cursorModel.disposeImages);
moved.cursor.core.addAll(ffi.cursor.core);
_select(moved, '1');
await _settle();
expect(moved.cursor.fetched, ['1']);
expect(moved.cursorModel.cache?.id, '1');
expect(moved.cursorModel.image?.width, 16);
});
test('a tab closing does not delete the cursors of another tab', () async {
final other = _FFI();
addTearDown(other.cursorModel.disposeImages);
while (preDefaultCursor.cache == null) {
await _settle();
}
buildCursorOfCache(ffi.cursorModel, 1.0, preDefaultCursor.cache);
buildCursorOfCache(other.cursorModel, 1.0, preDefaultCursor.cache);
await _settle();
expect(registered.toSet().length, 2, reason: 'each tab has its own');
ffi.cursorModel.clear();
await _settle();
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
});
}

Some files were not shown because too many files have changed in this diff Show More