Compare commits

..
Author SHA1 Message Date
rustdeskandClaude Opus 5.5 071d9b1eff fix(linux): stop using the window in onWindowClose once GTK destroyed it
On Linux, GTK destroys the window on a close request unless prevent-close
is on. When the main window is the last active one, onActiveWindowChanged()
turns prevent-close off and calls close(), yet onWindowClose() still went
on to hide() the destroyed window, and the close event that close() emits
re-entered onWindowClose() to save the frame through isMaximized(). The cm
and install windows never turn prevent-close on, so their window is always
gone by the time onWindowClose() runs.

With window_manager before cf4aef05 those calls segfaulted in
gtk_window_is_maximized; since then they fail with an unhandled
PlatformException(window_destroyed). Return early in both places instead.
Other platforms and sub windows keep the old path.

Fixes #16512

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R
2026-10-15 15:01:40 +08:00
RustDeskandClaude Opus 5.5 f1fa432bc8 Fix fdroid bridge version (#16560)
* fix(fdroid): generate the bridge with the Flutter version bridge.yml uses

#15139 moved the bridge Flutter version from bridge.yml's env into its
job matrix, so build_fdroid.sh read `.env.FLUTTER_VERSION` as "null".
The F-Droid recipe worked around that by pinning it to 3.24.5, which
equals ANDROID_FLUTTER_VERSION, and the script only generated the bridge
when the two versions differed, so the build failed on the missing
src/bridge_generated.rs.

Read the version from the default bridge-artifact matrix entry (3.22.3),
and always generate the bridge: the build needs it whether or not the
two Flutter versions match.

Fixes #16549

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* fix(fdroid): keep the recipe's version sed from overriding the bridge Flutter

The F-Droid recipe works around the old "null" read with
`sed 's/${FLUTTER_BRIDGE_VERSION}/<version>/'`, and its auto-update
copies that line into every new version. The 1.5.0 recipe pinned 3.24.5
and then 3.47.7, but flutter_rust_bridge codegen only works with the
Flutter version bridge.yml uses (3.22.3). Pass the unbraced variable to
prepare_flutter so that sed no longer matches the call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* fix(fdroid): raise the Gradle heap for the AGP 8 build

#15603 moved the Android build to Gradle 8.11.1 / AGP 8.10.1 with
compileSdk 36 and desugaring. The first F-Droid 1.5.0 build got past the
bridge and the Rust library, then failed in assembleRelease with "Gradle
build daemon has been stopped: since the JVM garbage collector is
thrashing", because gradle.properties still caps the heap at 1 GiB. CI
has long raised it to 2g; do the same here. A recipe that already
rewrites the -Xmx1024M setting keeps its own value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:42:39 +08:00
Maison da Silva 538126d42c Update Portuguese translations for keyboard shortcuts (#16555) 2026-10-15 12:06:47 +08:00
bovirus 9c6d3fcb4f Update Italian language (#16551)
* Update Italian language

* Update Italian language
2026-10-15 12:06:36 +08:00
Alex Rijckaert c230c57139 Update Dutch translation (#16540) 2026-10-15 12:05:52 +08:00
Leo Camus e614de83fc fix: read host= from an exe path with non-ASCII characters (#16556)
get_custom_server_from_string located "host=" in s.to_lowercase() and
sliced s with that byte index. Lowercasing can change a character's byte
length ("İ" is 2 bytes, "i̇" is 3), and on Windows the string is the full
exe path, so a profile such as C:\Users\İsmail shifted the slice past the
"h" and host came back empty. The client then fell back to the default
rendezvous server.

"host=" is ASCII, so search s.to_ascii_lowercase(), which keeps byte
offsets.
2026-10-15 10:30:06 +08:00
21pages e910029f51 feat: use the configured proxy for WebSocket connections (#16386)
* feat: add opt-in WebSocket proxy support

Add a WebSocket proxy option to the proxy dialog and custom client settings.
Keep WebSocket connections direct by default and use the configured proxy
without direct fallback when enabled.

Preserve relay targets regardless of the proxy address family and restart
connections when the option changes. Update hbb_common for proxy support.

Signed-off-by: 21pages <sunboeasy@gmail.com>

* update hbb_common

Signed-off-by: 21pages <sunboeasy@gmail.com>

* fix: remove WebSocket proxy opt-in

* chore: restore proxy settings UI and translations

* fix: update hbb_common for proxy read progress

* fix: update hbb_common proxy connections and IPv6 parsing

* fix: update hbb_common WebSocket local address

* update to rustdesk/hbb_common

Signed-off-by: 21pages <sunboeasy@gmail.com>

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-14 22:49:35 +08:00
rustdeskandClaude Opus 5.5 256dc9bc12 docs: scope the -p rule to macOS and Windows
Linux CI runs cargo test --workspace, so a Linux-gated test in another
crate already runs there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R
2026-10-14 16:39:57 +08:00
RustDeskandClaude Opus 5.5 b1761ee676 Ci run all dart tests (#16328)
* ci: run every Dart test, not three files

The step ran only the three cursor test files, so the other nine files
under flutter/test (terminal, file model, autocomplete, ...) never ran
on any pull request. With no path the runner takes the whole directory.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* ci: run the Rust tests CI could not reach

cargo test --workspace runs with the default features on x86_64 Linux
only, so the tests behind `windows`, `not(target_os = "linux")`,
`unix-file-copy-paste` and drmtap_dl's `tests` module never ran: the
platform, portable-service and audio tests, the clipboard crate's file
copy-paste and Windows file-name tests, and the drmtap loader's.

The macOS and Windows build jobs now run `cargo test --lib` after the
build with the build's own feature set, plus the clipboard crate. The
Linux job's list of named test runs gains drmtap_dl and the clipboard
feature. AGENTS.md says where tests go and what CI runs.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

* ci: drop the skips for tests that no longer exist

#16539 removed test_get_cursor_pos and test_get_key_state, the only
tests these skips matched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-14 16:31:58 +08:00
Mariano Abad d011aa3ea6 fix(wayland): a pending portal request no longer stalls the server (#16542)
* fix(wayland): a pending portal request no longer stalls the server

The screencast portal waits for the user while its picker is open, up to
three minutes. check_init waited under the CAP_DISPLAY_INFO write lock on
a tokio worker and get_capturables under RDP_SESSION_INFO. Every desktop
login read the display state on a worker behind them, and the session
close when the last connection went waited for the slot on a worker too.
With the server on 4 cpus a second login was enough: new connections
were accepted by the kernel and not served until the request ended
(#15973).

The locks keep their role: the write lock still serializes inits and
orders them with clear(), and the slot still orders the session close
calls after a pending request. What changes is where the waiting happens.
The part of check_init under the write lock moves, as is, to
init_displays(), run in spawn_blocking. is_inited and the first look in
check_init use try_read; when a writer holds the lock, is_inited answers
not inited yet and check_init redoes its look in spawn_blocking, then
goes on as before. get_displays_and_primary takes its read guard in
spawn_blocking, is_rdp_session_hold uses try_lock, close_session from the
ipc listener runs in spawn_blocking, and try_close_session from
AuthedConnID::drop on its own thread.

* fix(wayland): throttle the log when the session close thread cannot start

A peer can drop connections at any rate, so the error logged when
AuthedConnID::drop cannot spawn the thread for try_close_session goes
through throttled_log!, once a minute, like the auto-login logs of this
file (greptile on #16542).

* fix(wayland): count the remote connections again in the close thread

The session close moved to its own thread in this pr, so a remote that
comes in after the count and before the thread runs could have the
session it reuses closed under it. The thread counts the remote
connections again right before try_close_session, which brings the
window back to the one the close had on the dropping thread (coderabbit
on #16542).

* fix(wayland): one portal session close at a time, for remote and camera connections only

The close that AuthedConnID::drop runs off the dropping thread spawned one
OS thread per drop that left no remote connection, whatever the connection
type, and while a portal request waits for the user each of those threads
waited for the session slot. Now only a remote or view camera connection
leaving asks for the close (their video service is the one that opens the
portal session), no thread starts when the slot is free and empty (drm,
x11, nothing left to close), and one close runs at a time: a close asked
while one runs is left to it. The logic moves to wayland.rs; connection.rs
keeps a hook.
2026-10-14 16:26:46 +08:00
RustDeskandClaude Opus 5.5 9997b7a3b8 test: remove tests that do not pin user-visible behavior (#16539)
* test: remove tests that do not pin user-visible behavior

Apply the AGENTS.md test rules to the existing Rust and Flutter suites.
A test is kept when it is the only coverage of user- or API-visible
behavior, the regression test of a reported or fixed bug, a security
boundary (one test per rejection class), or a check against an external
reference. Tests that assert private state or the order of internal
steps, pin review-round corner cases, or repeat what a kept test already
covers are removed.

Rust: 679 -> 298 tests. Dart: 118 -> 45 tests.

Test-only helpers left without callers go with them
(applyLastOnlineStateForTesting, terminalKeyboardRowWidth,
debugBufferedInputCount, tokio's test-util dev feature), and cfg gates
and visibility that existed only for the deleted tests are narrowed.
Runtime behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

* test: keep tests that pin security and user-visible behavior

Restore six tests that review showed are the only coverage of their
behavior:

- update metadata rejects an artifact file name with path components;
- ICE candidates from another session are dropped;
- KCP delivers every multi-segment frame queued before a close;
- set_files rejects an empty name in a multi-file transfer;
- a lopsided elongated cursor keeps its centre hotspot (#16242);
- toggling Show hidden during a pending same-path read issues a new read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

* test: keep offline update and key-exchange downgrade rejections

Restore three tests that are the only coverage of their rejection class:

- offline update metadata rejects a signed artifact with an http or
  credential-bearing URL;
- offline verification rejects a renamed local file and a version that
  does not match the release;
- a key-exchange pick lowered in transit leaves both sides unable to
  decrypt, so a v0 fallback after a failed v1 decrypt cannot pass
  unnoticed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

* test: keep the decomposed-grapheme and reconnect-cancel tests

Each catches a plausible wrong change that passes every kept test:
mapping the first scalar under a locked Ctrl turns é into \x05,
and a reconnect that does not fail pending reads leaves them hanging
until the 30 s timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:45:22 +08:00
Leo Camus 76ab280ae9 fix(terminal): trim the replay buffer when output has no newline (#16545)
* fix(terminal): trim the replay buffer when output has no newline

OutputBuffer::append returned early when the last line was incomplete
and the new chunk had no newline, so the trim loop never ran. A program
that writes without newlines (a minified file through cat, a \r
progress bar) grew the replay buffer past MAX_OUTPUT_BUFFER_SIZE
without bound, one 4 KiB PTY read at a time, until a newline arrived.

Signed-off-by: leoca <leo.camus23@gmail.com>

* fix(terminal): keep recent output when trimming a line without newline

Trimming popped the whole incomplete line once it passed
MAX_OUTPUT_BUFFER_SIZE, so the reconnect replay could come back empty.
Newline-free output now goes into a new chunk once the incomplete one
holds DEFAULT_RECONNECT_BUFFER_BYTES, and trimming drops the oldest
chunks while the newest bytes stay. The test checks get_recent.

Signed-off-by: leoca <leo.camus23@gmail.com>

* fix(terminal): trim an oversized incomplete line to its newest half

Splitting the incomplete line into chunks made get_recent return whole
chunks only, so a reconnect could replay as little as the newest read.
Keep one line and, when it alone is over MAX_OUTPUT_BUFFER_SIZE, drop
its oldest bytes down to half the cap. The copy then happens once per
half buffer instead of on every append, and the replay keeps the
newest DEFAULT_RECONNECT_BUFFER_BYTES.

Signed-off-by: leoca <leo.camus23@gmail.com>

---------

Signed-off-by: leoca <leo.camus23@gmail.com>
2026-10-14 12:35:53 +08:00
HeZheng 29a160fc7e fix(mobile): prevent late mouse-down after floating button release (#16541)
Signed-off-by: zhenghe <zhenghe2009@gmail.com>
2026-10-14 11:26:13 +08:00
Mariano Abad 49a9574f97 fix(drm): pace the producer to the rate the encoder takes, with the panel refresh as floor (#16423)
* fix(drm): pace the producer to the rate the encoder takes, with the panel refresh as floor

The root producer slept a fixed 33 ms after every grab, so every DRM stream topped
out at 30 fps whatever the client asked (rustdesk#16175). Measured on a
1920x1080@60 i915 box with the client at Custom 60 and QoS settled at 60: 30
grabs, 30 converted, 29.8 sent. A shorter fixed interval reaches the rate but
oversamples: at 8 ms the same box grabbed and converted 117/s for 60 sent.

The consumer now tells the producer the rate it encodes at, in the ack byte it
already sends per converted frame: 0x01 as before, or 0x80|fps. Every producer
counts ack bytes and never read their value, so an older service sees exactly
the same credit and keeps its 33 ms; the JSON handshake and the ack count and
timing do not change. The rate is the encoder's spf (what frame() is called
with), lowered to what the encoder achieves when it is busy longer than spf per
frame: the time from one frame() call to the next, less what the call spent
waiting for a frame, so a late producer cannot talk its own demand down.

The producer replaces the post-work sleep with a deadline: the encoder's period
above 30 fps, the old 33 ms from 30 down to 15, and half the encoder's period
below 15, never faster than the panel (the exact CRTC refresh from libdrmtap
0.5.9's drmtap_crtc_refresh, re-read once a second; with an older library the
whole-hertz refresh the enumeration already read, so no extra connector probe).
The worker still wakes at least every 33 ms, because each tick also reads the
cursor and a slow frame rate must not slow the cursor down. Without a demand (an
older consumer, or before the first frame() call) the old 33 ms sleep stays.
MAX_STALLED and the WouldBlock retry keep their 5 s budget, pinned by a const
assertion.

Tests: the ack byte round trip and that it is one byte on the wire, the drain
(seeded byte streams: every byte one credit, the newest demand wins), the pacing
interval table (panel floor, below 30 and below 15, a 23.976 Hz panel), the panel
period rounded up, the deadline and its overrun, the wake that keeps the cursor
at 33 ms, the demand from spf and from a busy encoder, the busy time without the
wait (pure and through frame()), the demand log once per connection, the
whole-hertz fallback, and the reader's refresh answer. Each rule has a mutation
that turns its test red.

* ci: run the drm pacing tests in the drm step

drm_pacing_tests (src/ipc/drm.rs) and crtc_refresh_tests (libs/scrap
drm_reader.rs) match none of the existing filters.

* test(drm): keep three tests, on outputs and not on internal state

Per AGENTS.md (Tests), keep one to three tests, on outputs and not on internal
state: the demand ack as it goes on the wire, the producer interval for a
demand and a panel, and the exact refresh the reader returns.

* test(drm): the ack test goes through the producer drain

Per review: send_frame_ack(60) read back through drain_frame_acks gives one
credit and a demand of 60, so dropping the demand read in the producer turns
the test red. The interval test also pins drm_panel_period(148352, 2475) to
16_683_294 ns.

* fix(drm): time the encoder only after a frame() call that returned a frame

Since #16450 frame() drops a repeat as WouldBlock. The time after such a
call is video_service sleeping out its spf, and after a timeout it is
about zero once the wait is subtracted. Neither follows an encode, so
neither is a sample of the encoder pace now. Uses returned_at from #16450;
no new state.

* fix(drm): ask for the old 33 ms tick while the screen is still

Since #16450 a still screen is grabbed at the demand and dropped in
frame(), twice as often as master at 60. After 100 ms without a new
frame the demand is capped at 30, the old producer tick, and the next
new frame lifts it. 100 ms is three of those ticks, so a producer paced
at 30 in motion never reads as still. Uses returned_at; no new state.

* test(drm): a dropped repeat or timeout is no encoder time; a still screen asks for the old tick

Per review: the demand frame() reports stays with a 50 ms encoder through
a still screen of repeats and timeouts, and a still screen asks for 30
after STILL_AFTER until a new frame brings back 60.

* fix(drm): start the encoder average over when the rate goes up

Per review: the samples hold the sleep video_service paces itself with, so
after a rate increase (custom fps 1 -> 60, or QoS recovering) an average
taken at the old rate kept the demand low and the producer slow. A
shorter spf than the last now starts the average over and drops the
sample that spans the change. The demand is computed in one method that
takes its time as input, the still cap included.

* test(drm): drop the two pacing tests of the last round

Per review: they read shared.demand_fps and slept for real. The three
tests stay.

* build: pin libdrmtap 0.5.12 (rustdesk-org/libdrmtap 5936a7a88)

The panel floor of the pacing reads drmtap_crtc_refresh(), added in
libdrmtap 0.5.9. The mirror carries v0.5.12 since 2026-10-13, so the pin
moves there.

The rest of the range from 0.5.8 changes no struct in drmtap.h: 0.5.10
reads its environment through secure_getenv and loads no GL in a setuid,
setgid or file-capability process, which rustdesk does not run; 0.5.11
makes drmtap_deswizzle, also the CPU fallback of a tiled grab, refuse a
destination stride narrower than its rows instead of writing past it,
and exports drmtap_frame_owns_data, unused here; 0.5.12 changes only
docs and the version.
2026-10-14 10:44:43 +08:00
0740063863 Keyboard shortcuts (#14933)
* fix web break introduced in 38f130071 fix(linux): enable mouse side buttons in remote sessions (#14848)

* feat(shortcuts): user-configurable keyboard shortcuts for session actions

  Adds a keyboard shortcut feature (Rust matcher + Dart UI + cross-language
  parity tests) that lets users bind combinations like Ctrl+Alt+Shift+P to
  session actions. Bindings are stored in LocalConfig under
  `keyboard-shortcuts`; the matcher gates dispatch on `enabled` and
  `pass_through` flags so flipping the master switch off is a hard stop.

  Wire-up summary:
  - src/keyboard/shortcuts.rs: matcher, default bindings, parity test against
    flutter/test/fixtures/default_keyboard_shortcuts.json
  - src/keyboard.rs: shortcut intercept in process_event{,_with_session},
    feature-gated to `flutter`; runs before key swapping so users bind to
    physical keys
  - src/flutter_ffi.rs: main_reload_keyboard_shortcuts +
    main_get_default_keyboard_shortcuts; reload_from_config seeded in main_init
  - flutter/lib/common/widgets/keyboard_shortcuts/: shared config page body,
    recording dialog, shortcut display formatter, action group registry
  - flutter/lib/desktop/pages/desktop_keyboard_shortcuts_page.dart and
    flutter/lib/mobile/pages/mobile_keyboard_shortcuts_page.dart: platform
    shells around the shared body
  - flutter/lib/models/shortcut_model.dart: per-session ShortcutModel +
    registerSessionShortcutActions for actions with no toolbar TToggleMenu /
    TRadioMenu (fullscreen, switch display/tab, close tab, voice call, etc.)
  - flutter/lib/common/widgets/toolbar.dart: optional `actionId` field on
    TToggleMenu / TRadioMenu, plus per-helper auto-register pass that wires
    tagged entries' existing onChanged into the ShortcutModel
  - flutter/test/keyboard_shortcuts_test.dart + fixtures: cross-language
    parity (default bindings, supported key vocabulary)

  Design principles applied during review:

  1. Additions are fine; modifications to original logic must be deliberate.
     Tagging an existing TToggleMenu entry with `actionId:` is an addition.
     Rewriting its onChanged to satisfy a new contract is a modification —
     and was reverted for every case where the original click behavior was
     working. Four closures were touched and then reverted (mobile View
     Mode, Privacy mode multi-impl, Relative mouse mode, Reverse mouse
     wheel); their shortcuts are wired via standalone closures in
     shortcut_model.dart instead.

  2. Toolbar auto-register is reserved for entries whose onChanged is
     inherently self-flipping — typically `sessionToggleOption(name)` where
     the named option is flipped in place and the input bool is unused. The
     register pass passes `!menu.value` from registration time, which is
     harmless under self-flipping but wrong for closures that consume the
     input bool directly. Tagging a non-self-flipping entry forces a closure
     rewrite; choose non-toolbar registration in that case.

  3. When shortcuts are disabled, toolbar behavior must be bit-for-bit
     unchanged. The matcher's `enabled`-gate already guarantees no
     dispatch; the auto-register pass is left unconditional (its only effect
     is HashMap operations on a separate ShortcutModel) so mid-session
     enable works without a reconnect. The trade-off is intentional and
     documented at the top of toolbarControls.

  4. Comments stay terse. Rationale lives in one place — the doc comment of
     the helper or registration site, not duplicated at every call site.

  5. Where an existing helper needs a new optional behavior (e.g.
     `_OptionCheckBox` gaining a tooltip slot), the new branch must reduce
     to byte-identical output for existing callers (`trailing == null`
     case → original `Expanded(Text)` layout). Verified.

  6. Action IDs and labels stay consistent. Renamed `reset_cursor` →
     `reset_canvas` so the action ID matches its user-facing label
     ("Reset canvas") and capability flag.

  Out-of-scope but included:
  - AGENTS.md: documents flutter_rust_bridge no-codegen workflow and the
    Web target's hand-written TS client, since both are load-bearing for
    any new FFI work.
  - remote_toolbar.dart: i18n fix for the per-monitor tooltip ("All
    monitors" / "Monitor #N"), unrelated to shortcuts but kept here.

* langs

* fix(keyboard): shortcuts, harden config and callback lifecycle

Signed-off-by: fufesou <linlong1266@gmail.com>

* feat(keyboard): shortcuts, color of "Reset to defaults"

Signed-off-by: fufesou <linlong1266@gmail.com>

* feat(keyboard): shortcuts, release keys before shortcut callback

Signed-off-by: fufesou <linlong1266@gmail.com>

* feat(keyboard): shortcuts, debug web

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(keyboard): iPad, icon

Signed-off-by: fufesou <linlong1266@gmail.com>

* langs: add shortcut keys to az, gl, ur

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, keep local modifiers and release keys on the right session

When a chord fired, the shortcut path reused release_remote_keys(), which
replays synthetic releases through process_event(). That cleared the local
MODIFIERS_STATE while the user still held the modifiers, so the next key of
a held chord no longer matched and leaked to the remote, and it sent the
releases to the globally current session instead of the one that typed the
chord.

The shortcut path now releases the remote keys itself: it sends through the
caller's session, and restores the modifiers it released on the remote as
still held locally. The press that fired is remembered until its release,
so its auto repeats and its release are consumed instead of reaching the
remote.

Also state the contract for unavailable actions: a bound chord always
belongs to RustDesk and is a no-op when the session has no handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, record the physical key

The recording dialog and the Web Flutter matcher named keys by
LogicalKeyboardKey, while the native matcher sees the physical key through
its USB HID usage and the Web JS matcher through KeyboardEvent.code. On
AZERTY, QWERTZ, Dvorak and similar layouts a recorded binding then did not
fire, or fired from another key.

Name keys by their physical position everywhere: physicalKeyName maps the
USB HID usage to the stored name. A new fixture pins every name to its USB
HID usage, checked on the Dart side and against rdev::usb_hid_key_from_code
on the Rust side, and a test covers AZERTY and QWERTZ events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, keep an empty binding list on re-enable

setEnabled seeded the defaults whenever the binding list was empty, so a
user who cleared every binding got all defaults back after disable and
enable. Seed only when the config has never held a bindings list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, track every fired key until its release

FIRED_KEY held a single key, so overlapping shortcut keys broke it: with the
chord held, P then C overwrote P, P's release reached the remote, and a P
repeat could fire the screenshot again. A repeat after the modifiers were
released was also treated as a new press and leaked to the remote.

Keep a set of fired keys instead. Once a press fires, every event of that
key belongs to RustDesk until its release: repeats are consumed without
dispatching, whatever the modifiers do, and the release removes the key.
Entries whose release never arrives are dropped when a session view is
entered or a session is closed, not by guessing from the modifiers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, keep fired keys per session

FIRED_KEYS was process-global while dispatch is per session. Closing or
entering any session cleared the fired keys of all of them, so a key still
held in another session leaked its release to that remote, and a key fired
in one session made the same key in another session look like a repeat.

Key the fired set by session: try_dispatch resolves the session first and
only looks at that session's keys, and session_close clears only the
closing session. Entering a session view no longer clears anything: it is
a pointer enter, and a fired key may still be physically held across it.
A key whose release is missed otherwise heals itself: its next press is
consumed as a repeat and that release removes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(shortcuts): preserve input state and refresh action availability

* fix(keyboard): shortcuts, keep a fired key owned across session close

Close tab is itself a shortcut, so the session that consumed the key press
is gone before the key is released. Both matchers dropped the key with the
session: the Flutter dispatcher removed its own entries in clear(), and the
Rust set was keyed by session and cleared in session_close. The release,
and the repeats while the key stayed held, then reached the next session's
remote as ordinary input.

Ownership of a fired key is physical, so it is now one set shared by every
session on each side, and closing a session no longer touches it: clear()
only drops the pending action and modifier replay, and the Rust session
state only tracks released modifiers. A key whose release is missed heals
itself on its next press. Entering view-only with the Flutter input source
still clears the Rust set, since that source stops routing key events to it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, drop the Toggle Input Source action

The action switches the key capture backend between key down and key up.
Fired-key ownership lives in whichever matcher saw the press, the Flutter
dispatcher or the Rust set, and there is no handoff between them: after the
switch the repeats and the release of the held key reach the other backend,
which forwards them to the remote and, while the chord is held, matches the
action again and toggles the source back. Remove the shortcut instead of
building a handoff for one action. The toolbar radio menu is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* perf(keyboard): shortcuts, parse the config once per stored value

The Flutter matcher read the local config three times and parsed its JSON
three times on every key press in legacy mode, on Web and in view-only.
Keep one parsed snapshot keyed by the raw stored string, so a key press
costs one config read and no parsing while the config is unchanged. The
existing readers are thin views of the same snapshot.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix(keyboard): shortcuts, run focus-changing actions on key release

Close tab and tab switching move keyboard focus to another session before
the key that fired them is released. On Linux the Flutter input source
routes map-mode sessions through the Rust matcher and legacy-mode sessions
through the Dart matcher, and neither knows the other's fired keys, so
after such an action the repeats and the release of the held key reached
the next session's remote, and the key stayed recorded as fired in the
matcher that saw the press.

Routing Linux legacy mode through the Rust FFI path instead is not a drop-in
change: the raw key handler builds its event with no unicode, so Rust's
legacy mode would fall back to US key names and lose the layout-aware
characters the Dart path sends today, and it would take modifiers from the
X11 key state instead of Flutter's.

Run these three actions when the fired key is released. The matcher that
consumed the press then also sees the repeats and the release, the remote
modifiers are still released on the press, and a session that closes drops
the action it owed. Both matchers keep the same list of actions.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* test(keyboard): shortcuts, pin the key-up action list on both sides

kShortcutActionsRunOnKeyUp and runs_on_release are two hand-kept lists of
the actions that run on key release. Add a shared fixture and check each
side against it, the way the key vocabulary and the default bindings are
already checked, so adding a focus-changing action on one side breaks a
test until the other side follows. The Dart test also checks that every
listed id is a configurable action.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D

* fix: prevent lost input after remote session shortcuts

Avoid synthetic Alt presses that activate the Windows system menu
and swallow the next character.

Trigger restart, switch-sides, and chat actions on key release so
focus changes cannot leave subsequent shortcut presses ignored.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(mobile): correct Chat keyboard and input helper behavior

- Keep soft keyboard and helper hidden when Chat opens via shortcut
- Restore soft input on touch and remote focus after Chat closes
- Handle modifier releases while Chat owns focus
- Clear hidden virtual modifiers while preserving held keys and Pin behavior

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): prevent recording non-simultaneous key combinations

Build new captures from currently held keys instead of reusing released
letters. Preserve the last valid chord after release so it can be saved.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): isolate window actions and prevent duplicate Alt presses

- Dispatch shortcut actions only to the originating session window.
- Clear local modifier state on focus loss without resending modifiers
  already released to Windows peers, preventing lost following input.
- Strengthen the regression assertion against extra Alt keydown events

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(shortcuts): empty default shortcuts for Cmd+Option+Shift+Del on macOS and iOS

Because Del may be ambiguous for new macOS users.
Cmd+Option+Shift+Backspace is "Empty Trash without confirmation" shortcut on macOS.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: use session peer platform for Ctrl+Alt+Del events

Fix Android-to-Linux Ctrl+Alt+Del delivery by using the session's peer
platform instead of the desktop global session, which defaults to Windows

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: hide relative mouse mode shortcuts on Wayland

Separate relative mouse mode availability from screenshot support.
Filter unsupported actions and defaults while preserving saved bindings

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: align shortcut availability with platform support

- Hide unsupported mobile and web shortcut actions
- Enable mobile scaling and Android voice call shortcuts
- Use openMonitorInTheSameTab() for display switching
- Preserve cursor position when switching displays on desktop and web

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: prevent held-key shortcut recording bypass

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: preserve keyboard input after shortcut dialogs

Run native clipboard shortcuts on key release and wait for remote modifier releases before dispatching.

Release remote modifiers when mobile local UI takes focus, and document the tested iPad Bluetooth Mute shortcut limitation.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: preserve remote key state during local shortcuts

Keep unrelated held keys pressed for session actions that retain input. Preserve key release when focus or input handling changes, and avoid synthetic Alt taps during shortcut dispatch.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: suspend saved relative mouse shortcuts on Wayland

Filter the native active binding cache without changing stored configuration, so the binding becomes available again under X11.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: exclude unsupported Wayland shortcuts from Flutter matching

Keep saved bindings intact while filtering the active config used by the Flutter matcher. Cover stored bindings and enable/pass-through flags in the existing shortcut tests.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: retain forwarded key ownership across shortcut repeats

Ignore repeat presses for keys already forwarded to the peer, and release ordinary held keys before Show My Cursor enables view-only. Cover both paths with converter-level regressions.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: release Flutter-held keys before view-only shortcuts

Track ordinary keys forwarded by the Dart matcher paths and await their releases before View Only or Show My Cursor disables input. Keep Mute key ownership and existing empty-cleanup timing unchanged.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: filter active Flutter shortcuts by platform capabilities

Reuse the Settings action filter for saved bindings while preserving storage, default-seeding behavior and configurable Apple Ctrl+Alt+Del bindings.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: filter native shortcut caches for mobile controllers

Suspend saved desktop-only actions on Android and iOS and hide unavailable iOS actions without changing persisted bindings. Keep native cache filtering aligned with Flutter platform capabilities.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: share filtered shortcut bindings with the Web matcher

Pass the active platform config to JavaScript at startup and after settings changes, preserving unsupported saved bindings in local storage.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: release Flutter-held keys before focus-changing shortcuts

Drain ordinary keys owned by the original session before run-on-key-up
actions and native clipboard callbacks. Preserve Mute holds, pending-action
cancellation and Web clipboard key-down activation.

Document the required Web matcher counterpart in the bridge:
rustdesk/rustdesk-web-js@94abe431d6

Validation: 61 native Flutter tests, 32 Chrome/HTML tests, targeted analysis
and Windows debug build.

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact: remove the useless comments

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: prevent Windows menu activation from Alt-only shortcuts

Neutralize the forwarded Alt with a balanced temporary Ctrl press when a consumed local shortcut releases its only modifier in Windows Map mode. Keep physical modifier tracking and normal Alt pass-through unchanged.

Add a regression covering both Alt keys, trigger repeats and the eventual physical release. Verified with 36 native shortcut tests and real Windows menu/input checks.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: prevent Alt menu activation in all keyboard modes

Extend Windows Alt-only shortcut neutralization to Translate and Legacy. Keep the temporary Ctrl packets in Map mode so Legacy modifier synchronization cannot release Alt before Ctrl.

Extend the existing regression across keyboard modes and decode scan, virtual and control-key events. Verify 36 native tests and 34 Windows menu replay cases.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: initialize outgoing chat before shortcut dispatch

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: guard Windows Alt release in Flutter legacy shortcuts

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: coordinate Web shortcut dispatch and Alt modifier cleanup

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: distinguish AltGraph from ordinary Alt shortcuts

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: dispatch macOS Web shortcuts without waiting for keyup

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: support legacy peers in privacy mode shortcut

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: exclude AltGraph from Flutter shortcut matching

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: exclude GTK AltGr input from raw shortcut matching

Signed-off-by: fufesou <linlong1266@gmail.com>

* test: trim redundant keyboard shortcut coverage

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(keyboard): prevent Cmd shortcuts from opening remote Start

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): guard Windows menu keys after Ctrl/Cmd swapping

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): align recording and display routing

Reject non-Apple AltGraph captures to match runtime filtering. Honor individual-display windows for next, previous, and all-display shortcuts.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): reject GTK AltGr chords in recorder

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(android): restore keyboard focus for modifier-first input

Focus the existing FlutterView when a modifier is pressed without native view focus. This restores shortcut-first input after returning to RustDesk while preserving focused inputs and normal key dispatch.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): release held keys before keyboard mode changes

Drain Flutter-forwarded keys before keyboard-mode shortcut actions so releases use the original encoding. This prevents held keys from remaining down after a Web Input source 2 mode change.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(i18n): use sentence case for shortcut labels

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(mobile): preserve touch modifiers in the input helper

Keep touch-selected modifiers visible after hiding the keyboard. Clear physical modifier releases locally in view-only mode so they do not reopen the helper.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(web): preserve modifiers across Legacy-to-Map shortcuts

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(shortcuts): check support before registering all displays view

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: fufesou <linlong1266@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:31:44 +08:00
RustDeskandClaude Opus 5.5 13e1278b4c fix: auto-login types the OS password only at the logon or lock screen (#16520)
* fix: auto-login types the OS password only at the logon or lock screen

A remote-control login on Windows and macOS now reports is_logon_screen
in platform_additions, and the client skips auto-login when the peer
reports false. Peers that don't report it (older ones, Linux) keep
today's behaviour, so this narrows the leak into the focused window
without closing it: the value is a snapshot taken at login.

Windows 7 and Server 2008 R2 report the WTS lock flag reversed, so
there only LogonUI.exe tells the lock screen apart.

Refs #16510, #15261

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* windows: drop the LogonUI.exe check from is_logon_screen

LogonUI.exe can outlive the unlock and is matched by name only, so its
presence reported a lock screen on an unlocked desktop and let the
password through. Only the WTS lock flag decides now; on Windows 7 and
Server 2008 R2, which report it reversed, the result is inverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* windows: count only a confirmed logon or lock screen for auto-login

is_prelogin() reads a failed WTS user-name query as no user signed in,
and on Windows 7 the inverted is_locked() read a failed lock-flag query
as locked, so either failure let the password through. is_logon_screen
now uses its own queries that keep a failed read apart, and reads LOCK
and UNLOCK the other way round on Windows 7 and Server 2008 R2. The
existing functions stay as they are for their callers.

If the check task itself fails, the server reports false instead of
leaving the key out, which old clients' peers would mean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* auto-login: ask the peer with a protobuf field instead of a JSON key

The client sets the new LoginRequest.auto_login only when Auto Login
would type the OS password, and the server runs the logon-screen check
only then, so nothing new runs for any other login. The answer is the
new PeerInfo.skip_auto_login: its default, false, is what an old or
Linux server means, so those peers keep typing as before, and neither
field is encoded unless set. The is_logon_screen key in
platform_additions is gone.

Windows is_locked() now reads the lock flag through
is_session_locked_flag(), which handles the reversed LOCK/UNLOCK of
Windows 7 and Server 2008 R2. Its only caller is the
allow-logon-screen-password check, which on those systems accepted the
permanent password on an unlocked desktop. Windows 8 and later read the
same as before. The C is_session_locked() is removed and its
WTS_CURRENT_SESSION guard moves into get_session_flags().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* auto-login: let the peer type the password, after checking its screen

The login-time check left the whole time until the password arrived
open: the screen could be unlocked during the click, the 1.2 s wait and
two network trips, a second client's password landed on the desktop the
first one had just unlocked, and turning Auto Login on mid-login skipped
the check.

Now the client still clicks and waits, then sends the password in a new
Message.os_login (reusing OSLogin) to a Windows or macOS peer from 1.5.1.
The peer checks for its logon or lock screen right then and types the
password and Return only if it finds one; otherwise it drops them. Other
peers get the keys as before, and the OS Password menu item is
unchanged. The password goes out only after login, never in the login
request. LoginRequest.auto_login and PeerInfo.skip_auto_login are
removed, so nothing new runs unless os_login arrives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

* server: name os_login in scope-violation logs

A rejected os_login was logged as message.other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P1grQ39ByRWPUtTBdTzEBF

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 12:06:15 +08:00
rustdesk 0b5a3d74de 1.5.1 2026-10-12 17:08:40 +08:00
Mariano Abad 109c39bccb fix(drm): drop a frame equal to the previous one, as the other capturers do (#16450)
* fix(drm): drop a frame equal to the previous one, as the other capturers do

The producer grabs on a timer, so a still screen reached the encoder as the
same frame every tick and the client decoded about 30 frames per second of
nothing new (rustdesk#16449). The x11, pipewire and quartz capturers drop a
repeat with would_block_if_equal; the drm capturer now does the same.

A regression test checks that a repeat is not encoded again and that the next
new frame is. The frame helper of the tests now differs per call, and the 180
test forgets the frame its last case repeats on purpose.

* fix(drm): a frame whose encode failed is not dropped as a repeat

The capturer marked a frame as seen when it returned it, so when its encode
failed and the screen then stayed still, every later grab compared equal to
it and it was never sent: the client kept the previous image, and a hardware
encoder never reached its failure count to switch away.

handle_one_frame now also says whether the frame was encoded, and when it was
not the loop calls TraitCapturer::forget_last_frame(), a new method whose
default does nothing. The DRM capturer then returns the next repeat instead of
dropping it.

The DRM capturer also stops keeping a copy of the last frame: it compares the
new buffer with the one it returned last before replacing it, and a turned
frame is turned into a spare buffer first.

* fix(linux): x11 and pipewire do not drop a failed frame as a repeat either

Both capturers drop a frame equal to the one they returned last, so they had
the same hole as the drm one: a frame whose encode failed was not sent again
while the screen stayed still. They now forget it when the loop says so.

* fix(linux): every video run starts by forgetting the last frame

A pipewire recorder outlives a restarted run while another display keeps the
session open, and so did the frame it returned last. A run restarted by an
encoder switch or a new subscriber then dropped the first repeat and sent
nothing until the screen changed. The capturers of the other paths are built
fresh for each run, so for them the call does nothing.

* fix(drm): keep the repeat drop in the drm capturer, with one repeat a second

The shared part of the three commits before is reverted: TraitCapturer,
the video_service loop, x11 and pipewire are as on master again. So is the
restructure of frame() from the second commit: the drop is again the one
of the first commit, would_block_if_equal on the frame returned last, as
the other capturers do.

A repeat is dropped until a second has passed since frame() last returned
a frame, so a frame whose encode failed reaches the encoder again a second
later even if the screen stays still. The tests check the drop, the repeat
a second later, and that the second starts over after it.

* fix(drm): a frame is a repeat only when its format matches too

The same bytes as BGRA and as RGBA are two pictures when red and blue
differ, and the convert path can return either, so a change of format
clears the saved frame and the new one goes out. The 180 test no longer
checks a turned repeat: nothing reported asked for it.

* fix(drm): compare a frame with cur before replacing it, without a copy

saved_raw_data copied every changed frame (8 MB at 1080p). The previous
frame is still in cur when a new one arrives, so the bytes and the
format are compared with it before the swap; a rotated output turns the
frame into a spare buffer first. The 180 test checks the turned repeat
again, since that path compares on its own now.
2026-10-12 11:29:57 +08:00
Henrik Fransson ccfa714d2e Fix Swedish translation typo (#16529)
Signed-off-by: Henrik Fransson <hmf.hmf.hmf@gmail.com>
2026-10-12 10:57:11 +08:00
fufesou 0921a7432f feat(update): verify signed update metadata (#15914)
* feat(update): verify signed update metadata

* fix(update): harden metadata publishing and app names

- share strict app-name validation across Windows and macOS
- preserve published sidecars until replacements are ready
- select macOS test features by target architecture
- update the signing dependency and URL validation coverage

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): prevent replacing published release assets

- block reruns after signed update metadata is published
- clarify the security rationale for app-name validation

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): cache TLS responses and avoid double translations

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact: reduce the diffs

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(update): remove obsolete update paths

- remove unused FFI update branches
- delete legacy Windows and macOS update helpers
- simplify macOS daemon updates and redundant gating

Signed-off-by: fufesou <linlong1266@gmail.com>

* feat(update): secure same-identity macOS offline updates

- verify DMGs using signed metadata, size, and SHA-256
- enforce package and bundle identity plus macOS signature checks
- support custom release policies and propagate manual update failures

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): verify Windows installers with Authenticode

Reject unsigned or untrusted EXE/MSI updates
before elevation, clean up failed verified copies,
and fix the macOS manual updater logging import.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): clear stale URL on response body errors

Keep body-read failures in the common cleanup path and document the
cache-only Authenticode verification policy.

Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(update): remove OS signature sanity checks

Remove Windows Authenticode and macOS codesign/Gatekeeper verification.
Keep metadata, artifact integrity, bundle identity, and transaction checks.

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(update): move update scripts into res/update

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): secure Windows MSI handoff against junction races

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): secure Windows EXE handoff against junction races

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): preserve legacy custom client app names

- allow names starting with digits or underscores
- preserve leading hyphens on Windows for compatibility
- reject leading hyphens on macOS to avoid pgrep option parsing

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(update): remove some simple wrappers

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(update): simple refactor

* refact(update): comments on update.scpt

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(update): comments

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(update): create download destinations exclusively

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(macos): roll back updates when final readiness checks fail

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(msi): propagate MSI installation failures

Signed-off-by: fufesou <linlong1266@gmail.com>

* chore

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(macos): reject stale IPC sockets during updates

Require open IPC sockets in addition to launchd running state before committing the privileged update transaction. Inspect sockets with lsof to avoid triggering IPC authentication.

Add native socket regression coverage to macOS CI. Remove the unused Windows helper, combine offline metadata exports, and restore unrelated formatting changed by the PR.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(macos): allow offline updates without an installed bundle

Validate app-only updates against the running client's bundle identifier and check the destination identity when it exists. Replace source-text assertions with behavioral identity tests and run the macOS update tests in CI.

Signed-off-by: fufesou <linlong1266@gmail.com>

* ci, gate test with PUBLISH_UPDATE_METADATA == 'true'

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-12 10:56:50 +08:00
fufesou c8532719c0 Fix/macos mouse release (#16516)
* fix(macos): preserve mouse-up through cursor protection

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(macos): clear tracked presses released in relative mode

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(input): preserve desktop mouse releases through cursor protection

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(input): preserve button state when mouse-up is rejected

Clear tracked buttons only after coordinate validation succeeds.

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-10 19:05:45 +08:00
RustDeskandClaude Opus 5.5 4411d10f45 fix(linux): report the process user as the active user under Flatpak (#16519)
File transfer to a Flatpak peer always failed with "No active console
user logged on", because PeerInfo.username came from loginctl, which the
sandbox cannot reach: Flathub builds lack the org.freedesktop.Flatpak
talk-name, so `flatpak-spawn --host` fails. A Flatpak instance only runs
inside the logged-in user's own session, so that user is the active one.

Fixes #16506


Claude-Session: https://claude.ai/code/session_01WS1HTjp6UQuG43KEcQPq1R

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:44:10 +08:00
67090d3aa1 fix: a refused privacy-mode request no longer turns off another connection's (#16507)
* fix: a refused privacy-mode request no longer turns off another connection's

`Connection::turn_on_privacy`'s error arm tore down whatever privacy mode was
active, whoever owned it. With connection A in privacy mode, connection B's
request is correctly refused with OCCUPIED, and the error arm then called
`turn_off_privacy_to_msg(INVALID_PRIVACY_MODE_CONN_ID, ..)`. That id bypasses
the ownership check in `check_off_conn_id`, so A's privacy mode went away: the
screen was un-blanked and local input un-hooked. The call passes `state: None`,
so no `set_privacy_mode_state` goes out either and A was never told, leaving its
client showing privacy mode as on. `check_privacy_mode_changed` doesn't cover
it, as it only sends PrvOnByOther while a privacy mode is still active.

Pass `self.inner.id`, as the sibling error path above already does.
`check_off_conn_id` then cleans up after this connection when it owns privacy
mode, and refuses when another connection does.

The bypass itself stays: `ipc::Data::Close`, `reset_all` and `TurnOnGuard` need
an unconditional teardown. Its contract is now noted on `check_off_conn_id`,
since that is what the buggy call site got wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Steven Storie <sstangle73@gmail.com>

* fix: disconnect other remote sessions when privacy mode starts

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: exclude privacy disconnect hook from iOS builds

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: validate privacy mode before disconnecting other sessions

Signed-off-by: fufesou <linlong1266@gmail.com>

* chore

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: Steven Storie <sstangle73@gmail.com>
Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: fufesou <linlong1266@gmail.com>
2026-10-10 16:02:29 +08:00
fufesou 001b0e9617 Fix/preserve deleted printer (#16500)
* fix(windows): preserve manually deleted printers

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(windows): distinguish printer detection failures

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(windows): skip printer detection when disabled

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(flutter): load printer status asynchronously

Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(flutter): remove printer status mounted checks

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(msi): preserve deleted printers in direct upgrades

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(windows): preserve deleted printers in silent EXE installs

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(windows): skip printer installation when detection fails

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(installer): default printer off when detection fails

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(printer): limit checked enumeration to presence queries

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(installer): allow cancellation during printer detection

Inline MSI update command construction without changing its arguments.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(flutter): time out installer printer detection

Signed-off-by: fufesou <linlong1266@gmail.com>

* chore

Signed-off-by: fufesou <linlong1266@gmail.com>

* test(windows): cover multilingual install app names

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-10 00:21:17 +08:00
Hintay 0bc2473ffe fix(drm): size a plane-rotated scanout as the mode transposed (#16444) 2026-10-09 14:11:42 +08:00
fufesou 3f4bfe535e Fix/wayland input keyboard layout (#16462)
* fix(linux): respect Wayland keyboard layouts for uinput

Resolve printable keys from GNOME input sources or the Wayland keymap and KDE active layout group. Refresh layout metadata on input at most once per second, and preserve the keycode and owned modifiers until release.

Preserve the original Legacy character on client key release and handle Caps Lock shortcuts without introducing an unwanted Shift modifier.

Validated with GNOME/KDE full-service input and disconnect checks, plus Windows/Linux native keyboard capture and release checks.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): harden Wayland keyboard layout detection

Keep the last usable map on transient discovery failures and preserve the
legacy character path when no map is available, with explicit warnings.
Retain each injected key representation through release and handle IBus
default layout and variant metadata without compiling a layout named default.

Use native GNOME and Plasma sources, including KWin sessions without the
optional layout service. Read the Xwayland keymap and effective group from
the same keyboard on other desktops. Load XCB/XKB libraries dynamically and
accept the unix/:N local display spelling.

Validation: 24/24 temporary Linux production-module and IPC checks passed,
including an actual read-only Xwayland query. The two latest routing/display
regressions failed before their fixes. Rustfmt and git diff --check passed.
No Cargo/Flutter commands or full remote application tests were rerun.

Xwayland state freshness and synchronous desktop I/O remain known limits.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): bound input waits for layout refresh

Run throttled Wayland layout discovery in a single background worker and give the triggering input a 25 ms wait budget. Later input uses the existing map without waiting or queuing more queries. Preserve source error handling and skip known Legacy clipboard-only text.

Document Xwayland freshness and per-character modifier ownership limits. Desktop calls remain uncancelled; the budget bounds input waiting, subject to OS scheduling.

Validation: Linux module compilation with cached dependencies, 23 existing temporary module/IPC checks, and stalled-XCB timing probes passed. Rechecked cache/error/release cases after the final lock-scope change. No permanent regression tests or Cargo/Flutter commands.
Signed-off-by: fufesou <linlong1266@gmail.com>

* docs(linux): record layout query latency measurements

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): reply to failed uinput key state queries

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): prefer non-keypad character mappings

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): preserve text after unmappable uinput characters

Continue processing a text sequence when one character cannot be resolved
in the host layout. Return the first mapping error after the supported
characters are injected, so the existing throttled log still reports failure.

Keep modifier-query, injection and release errors fail-fast. This fixes
German a^bc losing bc without adding clipboard or fixed-US fallback.
The unsupported caret remains an explicit mapping error.

Validation: three temporary Linux checks (nine inputs) passed using the
production resolver and sequence methods, real framed IPC and native XKB
decoding. The suffix check failed before the fix. Formatting and diff checks
passed; no permanent tests, Cargo/Flutter commands or full app build added.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): preserve Latin shortcuts on non-Latin layouts

Detect Ctrl/Alt/Meta independently of CapsLock. If the active XKB map lacks
an ASCII shortcut letter, reuse the existing physical letter mapping while
preserving explicit Shift and the press-time key for release. Existing
layout mappings and unsupported ordinary text retain their behavior.

Honor disable-uinput-layout-fallback and log this compatibility path with
the existing throttle.

Validation: 12 temporary Linux production-module/IPC checks passed,
including 43 non-Latin shortcut/layout/lock/Shift cases. The new checks
failed before the fix. Formatting and git diff --check passed. No real
mobile/compositor session or Cargo/Flutter build was run.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): preserve missing punctuation shortcuts

Allow missing ASCII graphic shortcuts to reuse the existing physical key
table when Ctrl, Alt or Meta is active. This restores Ctrl+[ and Ctrl+]
with a valid Russian layout instead of discarding their character events.

Retain the table's Shift requirement for punctuation and use existing
modifier ownership and press-time release tracking. Uppercase letters do
not synthesize Shift. Active-layout mappings, ordinary text errors and
disable-uinput-layout-fallback retain their behavior.

Validation: 14 temporary Linux production-module/IPC checks passed after
recompiling the final source with rustc and cached dependencies. Includes
19 punctuation/lock/Shift combinations and 43 existing Latin-shortcut
cases. The two new checks failed before the fix. Formatting and
git diff --check passed. No Cargo/Flutter build or real mobile/native
Wayland session was run.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): respect held Shift when resolving shortcuts

Derive Shift-held candidates from the same XKB keymap and query the
caller's Shift state for character shortcuts. On US layouts, Ctrl+Shift+<
now uses the comma key instead of the extra ISO key that produces >.

Keep caller-held Shift out of synthesized modifier ownership. Preserve
ordinary input and letter-shortcut identity, and do not replace an
ordinary shortcut with a keypad alias to satisfy the held-Shift lookup.

Validation: 16 temporary Linux production-module/IPC checks passed with
native XKB event replay and cached dependencies via rustc. Includes
30 US text/shortcut cases and 40 UK/DE/FR character/lock cases. The new
Ctrl+Shift+< check failed before the fix. Changed sections pass formatting
and git diff --check. No Cargo/Flutter build or real mobile/native Wayland
session was run; device-state and packet-modifier handling use fixtures.

Signed-off-by: fufesou <linlong1266@gmail.com>

* docs(android): document paired-punctuation input limitation

Signed-off-by: fufesou <linlong1266@gmail.com>

* docs(linux): explain Xwayland layout synchronization limits

Document the focus-scoped modifier updates observed on GNOME and KWin. Core and physical X11 keyboards can retain an old layout group while native Wayland windows have focus; reconnecting or waiting cannot request the missing update.

Validation: 16 existing module/IPC probes and the live GNOME mapping probe passed. Live KDE queries reproduced native French versus stale Xwayland US. Formatting and diff checks passed. This is a comment-only change; strict Xwayland-only behavior is preserved.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): query native Sway and Hyprland keyboard layouts

Read the uinput keyboard's active layout through compositor IPC and
validate its group against the native Wayland keymap. Match the IPC
server to the Wayland session, and accept numbered Hyprland device
names while rejecting ambiguous keyboard selections.

Validation: 21 temporary production-module and framed-IPC checks passed.
Live Sway US/FR group and a/q mapping checks passed with Xwayland disabled;
the GNOME French layout probe also passed. Formatting checks passed.
A live Hyprland session and a full application build were not tested.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): defer unverified native compositor layout queries

Remove the Sway/Hyprland adapter that paired a uinput device's layout
group with a seat keymap based only on matching layout names. Different
device options can make a synthesized AltGr key toggle CapsLock instead.

Restore the existing best-effort Xwayland source for other desktops and
document the device-keymap information missing from the examined native
queries. GNOME/KDE discovery and injection/cache behavior are unchanged.

Validation: 16 temporary production-module/IPC checks passed after the
removal, plus read-only GNOME French and Xwayland mapping checks. Rust
formatting and diff checks passed. No full application build or mobile
end-to-end test was run for this follow-up.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): reject unreliable GNOME per-window layout sources

GNOME restores per-window layouts without persisting MRU. Reject MRU
selection when per-window input sources are enabled with multiple sources,
and invalidate the cached map and source identity for this typed error.
Transient discovery failures still retain the last valid mapping.

Reuse the existing logged/disableable compatibility policy. This contains
stale-map acceptance; it does not add effective per-window layout discovery.
Single-source and global-source GNOME configurations retain their path.

Validation: the old code failed the temporary stale-cache regression.
All 3 focused production-module checks pass after the fix, covering cache
invalidation/recovery, compatibility modes, single/default source mapping,
UK punctuation, and last-good retention after an IBus connection failure.
Compiled with rustc and cached Linux dependencies; formatting/diff checks
passed. No permanent tests, Cargo/Flutter build or mobile session added.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): reject inactive IBus layout sources

Read the current GlobalEngine description instead of looking up the
persisted MRU engine by name. GNOME can suppress IBus for password entry
without updating MRU, leaving the old engine's layout valid but inactive.

Report an engine-ID mismatch as UnreliableSource so the existing cache
invalidation path drops that mapping. Keep transient query-error handling
and layout/variant normalization. Do not infer a US compositor layout from
GNOME's xkb:us::eng echo engine.

Validation: the old code failed the inactive-engine cache and default-layout
checks. All 3 temporary production-module/D-Bus checks pass with this fix,
covering invalidation/recovery, compatibility policies, metadata sentinels,
query failures and ordinary French XKB selection. Compiled with rustc and
cached Linux dependencies; formatting/diff checks pass. No permanent tests,
Cargo/Flutter build or live password/mobile session added.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): prewarm uinput layout discovery at startup

Start the existing layout worker when the uinput keyboard client connects,
before the server accepts remote input. Reuse its throttle and single-worker
logic; keep the existing 25 ms input wait and background completion policy.
Prewarming reduces cold-start fallback without introducing input queues or
promising readiness while a desktop query remains outstanding.

Verified with three temporary Linux production-module checks using cached
dependencies: a 125 ms query resolves UK @ before first input, a 200 ms
outstanding query stays nonblocking and publishes its map, and a failed
startup query retries successfully. All three fail their startup assertions
before the change. No permanent tests or Cargo/Flutter builds were added.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): preserve first input wait during layout prewarming

Keep the startup query's completion receiver until the first relevant input
takes it. That input can wait for the already-running query within the
existing 25 ms deadline, without holding the receiver handoff lock. Later
input remains nonblocking and the existing single-worker guard is unchanged.
Prefer a due refresh to an old completed startup notification.

Verified with four temporary Linux production-module checks compiled with
rustc -C opt-level=3 and cached dependencies: joining a pending UK query,
one bounded wait followed by nonblocking input, due refresh after prewarm,
and recovery after query failure. Both lost-wait checks fail before the fix.
Formatting and git diff --check pass. No permanent tests or full build added.

An unoptimized delayed-query probe still exceeded 25 ms and used fallback;
this restores the wait opportunity, not an initial-readiness guarantee.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(uinput): remove unnecessary change

Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(linux): simplify uinput character releases

Release the mapping stored for the same character. Linux character input already pairs down/up events, so opposite-case matching is unnecessary.

Validation: git diff --check passed. Static comparisons confirmed that Map-mode dispatch, raw-key injection and keycode offsets match the PR base. No Cargo/Flutter commands or live-session tests were run.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): normalize Unicode CapsLock shortcuts

Normalize single-scalar Unicode lowercase for CapsLock shortcuts without adding Shift. For lowercase expansions, resolve the original symbol with the actual CapsLock state instead of truncating it. Document the existing first-seat discovery limitation.

Validation: two temporary Rust context checks against lookup fixtures failed before the fix and passed afterward. No Cargo/Flutter build or end-to-end input test was run.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): derive CapsLock shortcut keys from XKB

Keep the actual CapsLock state when resolving shortcut characters. Use the existing Caps-off and Caps+Shift mappings to omit generated Shift only when XKB confirms the same physical key and remaining modifiers, preserving the Turkish I/ı and İ/i key identities.

Validation: three temporary production-module checks passed on 192.168.5.32 with native libxkbcommon; two failed before this fix. Covered Turkish, German, Cyrillic and ASCII shortcuts, explicit Shift, ordinary text and UK punctuation. No full application build, IPC or end-to-end input test was run.
Signed-off-by: fufesou <linlong1266@gmail.com>

* refactor(linux): remove CapsLock shortcut special cases

Use the existing lock-state synchronization and ordinary XKB mappings for mobile soft-keyboard input. Remove CapsLock-specific shortcut remapping and compatibility-path lowercasing while retaining held-Shift punctuation handling.

Validation: rebuilt the Linux Rust library and reused the unchanged Flutter UI. Actual Android Gboard input matched UK punctuation on GNOME and KDE; French/German switching on KDE passed after the refresh interval. The user confirmed real iPad input on both hosts, including smart quotes. Formatting and whitespace checks passed. The optional Ctrl/Shift toolbar automation was inconclusive and is not counted as passing coverage.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): press Level3 before Shift for uinput characters

Preserve mapping candidate preference while storing generated modifiers in Level3-before-Shift order. This avoids activating Compose with lv3:ralt_switch_multikey; releases retain their existing reverse order.

Verified on Linux with temporary production-mapper/libxkbcommon tests: Lithuanian ! fails before this change and passes afterward; all 24 UK punctuation/lock-state cases pass with released modifiers and unchanged lock state. Formatting and diff checks pass. No full application build or mobile end-to-end test was run for this change.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): preserve legacy uinput IPC without a keymap

Send sequences and character clicks through their original IPC messages when the layout cache is unavailable, avoiding unnecessary synchronous key-state queries. Keep throttled fallback warnings and leave layout discovery, retry policy, and key-down/up pairing unchanged.

Verified with three temporary production-method checks on Linux using a recording transport and injected query errors. The unavailable-map routing check fails before the fix and passes afterward; raw-click routing and available-map query-error handling remain unchanged. Changed-code formatting and diff checks pass. No full application build or end-to-end input test was run.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(linux): skip layout queries for legacy uinput fallback

When no keymap is available, single-character input must use the legacy
KeyDown/KeyUp path without querying lock or modifier state first. Retain
the legacy key in the existing press record so discovery completing
before a repeat or release cannot change the selected representation.

Validated with four temporary production-method checks on Linux using a
controlled cache/resolver and recording transport: missing-map fallback
with query failures, press/release across cache transitions, unchanged
raw-key dispatch, and Ctrl+C without extra Shift or queries. The initial
fallback check failed before this change. Valid-map errors still surface.

Changed-code formatting and git diff --check pass. No full Cargo/Flutter
build or live service/mobile test was run for this change.

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-09 11:17:04 +08:00
Mariano Abad 9b9e5f113a fix(wayland): place a portal stream at the only output of its size (#16451)
* fix(wayland): place a portal stream at the only output of its size

xdg-desktop-portal-hyprland reports every stream at (0, 0). With no output at
the origin, sort_streams dropped the stream; with an output of another size
there, the stream took its origin and skipped try_fix_logical_size, so the
client sent physical pixels from the wrong origin and the pointer landed on
another output.

With more than one output, a stream whose position is not the origin of an
output of its size (a rotated output counts in either orientation) now takes
the origin of the only output of that size; with several outputs of that size,
or none, the position is kept. A position found by try_fill_positions names an
output of its size, or no output has its size, so later calls keep it while the
outputs and the measured size do not change.

Refs #15731

* fix(wayland): reconcile portal positions with measured sizes only

The first commit corrected any position that named no output of the stream
size, trusting the size. That size is the portal size when get_res() fails,
and it can be the mode of another output, so a correct portal position could
move onto the wrong output. A stream now records whether its position came from
the portal and whether its resolution was measured, and a portal position is
overridden only by a measured size.

Streams without a portal position go through try_fill_positions as before; one
it leaves unresolved, such as a rotated output whose transposed size no mode
matches, now takes the origin of the only output of its size.

Refs #15731

* fix(wayland): only a measured size moves a stream position

The reconciliation after try_fill_positions let a position through to
corrected_origin unless the portal had sent it. A position that
try_fill_positions restored from its cache is not from the portal, so when
get_res() failed and the size was the portal size, a cached (1920, 0) with a
1440x900 portal size moved to the 1440x900 output at (0, 0), and with both
outputs shared sort_streams dropped one of the streams. Only a measured size
moves a position now, whatever its source, so position_from_portal goes away.
2026-10-09 11:15:16 +08:00
21pages 1d4abd0258 fix: resolve HTTP API 407 errors through HTTPS proxies (#16496)
Upgrade reqwest to 0.12.28 to include the fix for missing
Proxy-Authorization headers when forwarding HTTP requests
through HTTPS proxies.

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-08 17:55:59 +08:00
NetViperandRustDesk 6da7977a94 fix(video): defer refresh teardown until hw encoder warms up (#16459)
* fix(video): defer refresh teardown until hw encoder warms up

On macOS, hevc_videotoolbox (the only encoder there reporting
!latency_free()) can return no packet for its first encode call. The
OPTION_REFRESH check in run() tore the encoder down with
bail!("SWITCH") inside that window, so each new encoder was destroyed
before producing a frame and rebuilt about once a second. With H265
selected on macOS 27 / Apple silicon, the picture froze or the session
dropped every 1-3 minutes.

On macOS, once the encoder has been fed a frame, defer the refresh
until it emits its first packet. Before that there is no warm-up to
lose, so a refresh can still restart a stalled capturer. Other
platforms and every latency-free encoder behave as before. An encoder
that never emits is still switched away from by the unchanged
max_fail_times path. The only new state is one flag.

Verified on macOS 27.0 / 27.0.1, M5 Pro, 2560x1440 H265. Soaked for two
weeks on a 1.4.9-based build carrying this deferral:
- before: ~40 "no valid frame" and ~27 refresh teardowns per 60s
- after:  37 sessions, every "no valid frame" at times:1, so
          max_fail_times was never approached; H265 never lost

Fixes #16457

Signed-off-by: David Riding <48262524+dmriding@users.noreply.github.com>

* Update video_service.rs

---------

Signed-off-by: David Riding <48262524+dmriding@users.noreply.github.com>
Co-authored-by: RustDesk <71636191+rustdesk@users.noreply.github.com>
2026-10-08 11:14:56 +08:00
fufesou 25d2c6db55 log key-up and text injection failures (#16455)
* fix(macos): log key-up and text injection failures

Report failed key releases through the rdev input path and
missing sources, mappings, or events in the Enigo keyboard path.
Throttle repeated failures without logging text contents or changing input behavior.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(macos): refine keyboard failure diagnostics

Remove key identities from virtual-input and Enigo failure logs while preserving operation and failure details. Also report key-down event creation failures in key_click with the existing throttle, without changing event posting or error propagation.

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(logs): update rdev, add diagnostic logs

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-08 00:23:14 +08:00
Stephan Paternotte f0bd880fe7 Update nl.rs (#16485)
lang: Dutch language file updated
- various consistency fixes
- ... -> …
- empty values translated
2026-10-07 21:33:18 +08:00
Ricardo Simões a916af8f00 Translate voice call audio capture prompt to pt-PT (#16482) 2026-10-07 18:56:05 +08:00
rustdeskandClaude Fable 5.1 9f9585ce15 Remove ConfigUpdate handling
Clients no longer apply a rendezvous-server list pushed by the
rendezvous server.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PkpVy2ufxgEjKd3SjXPnJ8
2026-10-06 17:17:06 +08:00
Andrzej Rudnik e8a865924b Updated Polish translation (#16456) 2026-10-06 10:58:02 +08:00
memory_clearandfufesou c9c0b5d0ef Fix translation for voice call audio capture prompt (#16433)
* Fix translation for voice call audio capture prompt

* fix: translation, audio capture prompt, wrong "Share screen"

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: fufesou <linlong1266@gmail.com>
2026-10-05 20:36:22 +08:00
5406950b02 fix(macos): open Screen Recording settings from Configure (#16452)
CGRequestScreenCaptureAccess shows its prompt only once per app. After
the user denies it, or after an update changes the code signature,
pressing Configure on the Screen Recording banner did nothing. Open the
Screen & System Audio Recording pane as well, so the button always
leads somewhere the user can grant access.

Co-authored-by: Eric Mason <17150+ericmason@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 20:15:32 +08:00
Mariano Abad 685fa2e4a1 fix(drm): the startup cache warm does not wake sleeping displays (#16437)
* fix(drm): the startup cache warm does not wake sleeping displays

Every `_drm` connection ran the display wake before the service answered with
its list, so the cache warm that each --server start runs (the service restarts
the --server every hour) woke displays that had idled off, with no client
connected (rustdesk#16356).

The --server now opens the handshake with DrmHello{wake}, and the service wakes
and settles only when asked. The warm asks without a wake; the availability
probes, the login refresh and the capture stream keep it, since a client is
waiting for them. Without a wake the service still clears the wake latch of a
connector it sees lit, as the warm did.

A warm that finds nothing lit leaves the cache without a verdict, where its own
wake used to make it Available. So a login that the DRM path can serve now
probes on a missing verdict before anything reads the cache (the greeter check,
the PipeWire prompt, the display list). That probe wakes the displays as the
warm did, but only when a client logs in.

* fix(drm): throttle the log of a peer that does not open with DrmHello

AGENTS.md: a log call that can fire at a rate a peer controls must not use
debug or higher unthrottled. Same 5 s interval as the rejected-IPC logs in
ipc/auth.rs.

* fix(drm): the startup warm keeps a list a login published while it queried

Per review: the warm samples the state generation before its query and
publishes only if no other probe published since, the check the two
background refreshes and the login refresh already use.

* fix(drm): log a failed login settlement task instead of dropping its error

Per review: the JoinError of the blocking task was discarded with `let _ =`.
2026-10-05 19:59:08 +08:00
Zixun LI e5bc204fe4 fix(wayland): avoid clock waits in PipeWire capture (#16430) 2026-10-03 06:51:33 +08:00
Cheolhee LeeandClaude Opus 5.5 fada664df7 fix(clipboard): unix, keep Windows directories searchable (#16406)
A directory pasted from Windows with FILE_ATTRIBUTE_READONLY or
FILE_ATTRIBUTE_HIDDEN (Git for Windows hides `.git`) was given mode 0444 or
0400 in the FUSE list, because the read-only and hidden branches came before
the directory branch. Without `x` the directory cannot be entered once a
mode-preserving copy lands it on disk. Windows does not restrict access to a
directory for either attribute, so give every directory 0755, as a plain one
already gets.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:50:12 +08:00
21pages 9d3ae7acd2 fix(windows): restore Flutter view visibility after FancyZones placement (#16397)
* fix(windows): restore Flutter view visibility after FancyZones placement

Signed-off-by: 21pages <sunboeasy@gmail.com>

* fix(windows): avoid stale resize targets during Flutter refresh

* fix(windows): update multi-window dependency for FancyZones

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-09-30 23:30:33 +08:00
Cheolhee Lee a7f2260203 fix(clipboard): unix, don't wrap FILETIMEs past 2554 (#16385) 2026-09-29 10:18:58 +08:00
berce 40a4aa34c8 Don't retry the _pa ipc at a Linux login screen (#16390)
At a greeter the cm is not started, so the `_pa` socket never exists and
the audio service fails to connect and logs an error once per second for
as long as a client is connected. Wait in `pa_impl::run` while
`is_prelogin()` is true; audio starts once a user logs in.

Fixes #16012
2026-09-29 10:17:06 +08:00
fufesou 0c18a8cbc9 fix(flutter): restore multi-window rendering after reconnect (#16383)
Use the window's current display when lastUserDisplay is unset so
additional monitor windows restore their capture subscriptions.

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-29 10:16:55 +08:00
rustdeskandClaude Opus 5.5 4812a9815b AGENTS.md: limit corner-case growth and test bloat
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 18:26:34 +08:00
b6b11fd9b1 fix(drm): apply the uinput range on one thread instead of holding a lock across the await (#16362)
* drm: apply the uinput range on one thread instead of holding a lock across the await

#16122 serialized the three paths that apply a uinput range in a DRM
session (the layout poll, `update_uinput_resolution` and `check_init`)
with a tokio Mutex held over the awaited `update_mouse_resolution`,
which AGENTS.md rules out ("Do not hold locks across `.await`"; greptile
on #16122). The serialization itself has to stay: the uinput service
keeps the range of whichever request reached it last and each apply
sends it over its own connection, so two overlapping applies can leave
the device on one range while the other one is recorded.

The check, the apply and what it records now run as one job on a
dedicated thread (`run_uinput_apply`), one job at a time in the order
asked, with the runtime of that thread for the IPC and its 3 s timeout.
The async paths await the answer and the display service loop blocks on
it; nothing holds a lock while it waits. The poll publishes its drift
flag inside its job, as it did under the lock. A thread that failed to
start or died is started again for a later job, so one failure does
not stop every later apply (the poll used to build a runtime per attempt
and retry). The drm-off build keeps the code it had.

Tests (in `input_map_tests`, which CI runs):
uinput_applies_run_one_at_a_time_in_the_order_asked,
a_uinput_apply_job_can_bound_its_ipc_with_a_timeout,
a_uinput_apply_thread_that_died_is_started_again. Mutations: every job
on its own thread, the apply runtime without timers, the answer never
sent, a dead thread not started again; each turns a test red. The call sites run IPC and are
covered by reading.

* drm: log a layout poll whose uinput apply job got no answer

The layout poll dropped the result of its job with let _ =, so a poll
whose job was dropped (the apply thread failed to start or went away)
left no trace, while update_uinput_resolution and check_init log it
(greptile and CodeRabbit on #16362). It logs now. The drift flag keeps
what the last poll that ran published; a later poll starts the thread
again and publishes it.

* drm: throttle the uinput apply thread failure logs

The layout poll hands the apply thread a job every 1.5s, so a thread that
cannot start logged two errors per poll for as long as a session lasted.
Keep one line per site every 10 minutes, with the count of the rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: rustdesk <71636191+rustdesk@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 17:27:08 +08:00
Cipher Professor d1722c5d6d fix(linux): use BUS_VIRTUAL for the virtual mouse device (#16382)
The uinput virtual mouse RustDesk creates on Linux reported bustype
BUS_USB. libinput's evdev_tag_external_mouse() tags any BUS_USB or
BUS_BLUETOOTH pointer device as an external mouse, so desktop
environments' "disable touchpad when an external mouse is present"
setting suspends the user's real touchpad whenever RustDesk creates
this device, even though nothing is physically plugged in.

Changed the constant to BUS_VIRTUAL (0x06, verified against the
current upstream kernel's include/uapi/linux/input.h), which
correctly identifies this as the software-only device it is.

Fixes #16318.

Signed-off-by: Mohsin Manzoor Bhat <mohsinmanzoor1913@gmail.com>
2026-09-28 17:03:42 +08:00
Mariano Abad 0d49ead0c3 fix(drm): turn a captured frame only when the plane did not rotate it (#16345)
* fix(drm): turn a captured frame only when the plane did not rotate it

A compositor rotates an output either in hardware, setting the primary
plane's `rotation` property, or in software, drawing the scanout already
turned. `wl_output` cannot tell the two apart, and `frame_transform`
guessed: 90/270 turned, 180 left alone, which is right for i915 + mutter
(rotate-180 in hardware, scanout upright) and wrong wherever the
compositor drew the scanout turned, where 180 comes out upside down.

Measured before changing it. virtio-gpu (no rotation property, mutter 46):
the scanout dump at 180 is the desktop upside down, at 90 and 270 the
logical desktop turned inside the native mode framebuffer. i915 + mutter
(GNOME 50) at 180: the plane reports rotate-180 and the dump is upright,
identical to the unrotated one. amdgpu + KWin 6 at 180: the plane stays at
rotate-0 and the dump is upside down.

The producer reads `drmtap_plane_rotation()` (libdrmtap 0.5.8, optional
symbol) right after each grab and stamps it on the frame, in the dma-buf
descriptor and in the CPU frame header, both `serde(default)` so an older
producer still parses. A plane that rotated scans out the logical desktop
whatever the output transform says: the compositor programs it from the
CRTC transform, which also folds in the connector's panel orientation that
`wl_output` never carries, so the consumer leaves such a frame alone. A
plane at rotate-0 scanned out what the compositor drew, and the frame is
turned by the whole output transform. `None` (a library before 0.5.8, or
nothing it could read) keeps the previous rule, so nothing changes until
the library says otherwise. The session is still sized from the output
transform: a plane that rotated 90 in hardware hands over the portrait
scanout those dims already name.

* build: pin libdrmtap 0.5.8 (rustdesk-org/libdrmtap 95d4d7454)

The rotation fix reads drmtap_plane_rotation(), added in libdrmtap 0.5.8. The mirror carries that commit since 2026-09-25, so the pin moves there.

* drm: pin the decoding of a frame from a producer older than the plane rotation

The root service and the --server are upgraded separately, so a frame
header or a dma-buf descriptor without `plane_rotation` must still
decode, as None, which keeps the previous rule. The tests built both
messages with the field set to None; this one decodes payloads that omit
it, and one that carries it (greptile on #16345). Serde already reads a
missing Option as None, so what the test pins is the wire name and the
None on absence, for both messages.

Mutation: renaming the field on the wire, in either message, turns it red.

* drm: take the plane rotation right after the grab, not after the copies

`drmtap_plane_rotation()` reads the rotation property of the plane the
last grab came from at the moment it is called. The cpu path asked only
after `DrmReader::grab()` had copied the frame into its buffer and the
producer had copied it again into the message, so on a large frame the
compositor had time to change the plane and the frame went out with the
rotation of the next one; `frame_transform` turns that frame by it with
nothing to absorb the skew (zhou, review of 26-sep).

`DrmReader` now reads the rotation right after a successful
`drmtap_grab_mapped` or `drmtap_grab_desc`, before any copy or release,
and `plane_rotation()` returns that snapshot, so both paths stamp a frame
with the rotation its own grab saw.

Test: a_frame_keeps_the_rotation_its_plane_had_when_it_was_grabbed, in
`plane_rotation_tests` (which CI already runs), drives the reader through
a fake library whose frame release turns the plane: the rotation read at
the grab survives on the cpu grab and on the dma-buf export. Mutations:
no snapshot on the cpu grab, none on the export, and the cpu snapshot
taken after the release, each turn it red.
2026-09-28 15:54:55 +08:00
flusheDData be9b96cf65 Translate voice call instruction to Spanish (#16358) 2026-09-28 13:53:54 +08:00
Cheolhee LeeandClaude Opus 5.5 89fcf56c4e fix(clipboard): unix, don't let the next file's preload fail a request (#16364)
After serving a request for file N, `serve_file_contents` preloads the
next non-directory file with `load_handle()?`. When that file can no
longer be opened (deleted or renamed after the copy, or unreadable), its
error replaced N's reply, so every size and range request for N failed
although N itself is intact.

Keep the preload best-effort. Its failure is logged at trace, because it
can fire on every request for N, and N+1's own request still reports the
error.

Signed-off-by: chlee <sourcehatchery@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 11:46:34 +08:00
Cheolhee LeeandClaude Opus 5.5 8a76628007 fix(clipboard): unix, use the real Windows FILETIME epoch offset (#16366)
`LDAP_EPOCH_DELTA`, the offset from the FILETIME epoch (1601-01-01) to
the Unix epoch in 100 ns units, was 116444772610000000. The real offset
is 116444736000000000 (11644473600 s), so the old value is 3661 s
(1h01m01s) too large.

Unix peers encode and decode with the same constant, so the error cancels
between them, but Windows sends and reads real FILETIMEs: files copied
from Windows got a modified time 1h01m01s too early on Linux and macOS,
and files copied from Linux or macOS were sent one 1h01m01s too late.

Signed-off-by: chlee <sourcehatchery@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 11:37:03 +08:00
Winston b5d8b979d8 i18n(tw): use the Screen Share page label in the voice call hint (#16355)
The hint referenced the "Screen share" page as 「螢幕分享」, but the
actual Traditional Chinese label of that page is 「僅分享螢幕畫面」
(the value of the "Screen Share" key). Match it, as zh-CN does with
"仅共享屏幕".

Signed-off-by: Mosquito1123 <zhangwentong1123@icloud.com>
2026-09-26 15:08:51 +08:00
fufesou 44683d108b fix(macos): clear Finder progress after clipboard transfers (#16346)
* fix(macos): clear Finder progress after clipboard transfers

Signed-off-by: fufesou <linlong1266@gmail.com>

* test(macos): cover single-response clipboard completion

Verify progress completion, handle cleanup, and finalized file contents.
Move function-only Finder imports into progress helpers.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(macos): unpublish clipboard progress before renaming

Complete and unpublish NSProgress before the final file rename to avoid
stale Finder and Dock progress indicators.

Signed-off-by: fufesou <linlong1266@gmail.com>

* chore: add ref

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-26 15:03:55 +08:00
Mariano Abad 50258e21e9 fix(drm): measure the cursor hotspot on drivers without HOTSPOT_X/Y, confirm before publishing (#16122)
* drm: carry the cursor plane position on the frame header

CursorSnapshot gains the plane position x/y. It rides DmabufDesc.cursor_pos
and Data::DrmFrame.cursor_pos as a serde-default Option, so a producer that
predates the field reads as None on the consumer, and a consumer that predates
it ignores the key. The producer reads the cursor once per delivered frame,
after the grab, so a WouldBlock retry does no cursor work; the position is a
few ms newer than the frame, which the consumer tolerates because it only
counts consecutive identical positions. The consumer destructures the field
and does not use it yet.

* input: remember the last absolute peer move and forget it on any other move

The DRM cursor calibration subtracts a cursor plane origin from the point this
process injected, so the point has to be the post-remap uinput one and nothing
else: LATEST_PEER_INPUT_CURSOR stores an X-server coordinate on the relative
arm. The new sample carries an Instant, a sequence number (two measurements
against one sample are not independent) and the layout generation it was
mapped against. A relative delta and a move this process makes itself forget
it. display_service exposes the existing drift flag to readers.

* drm: resolve the cursor calibration context once, with the capturer

CalContext { rect, physical_size, built_gen } is computed in
IpcDrmCapturer::new from the same wayland snapshot the transform comes from,
and only when the snapshot is complete, the output is an identity match, the
unfolded transform is 0 (180 included) and the geometry is valid. It is
stored in Shared before the transform's Release store, so a receive thread
that has seen the transform sees the context. Nothing reads it yet.

* drm: measure the cursor hotspot and confirm it before publishing

On a driver without HOTSPOT_X/Y the wire carries infer_hotspot's guess, which
the bitmap cannot get right for a shape whose click point the theme put where
the alpha does not mark it. This process injects the tip and the plane origin
rides every frame: once both are still, tip - origin is the hotspot.

Only a guessed shape is measured. The first measurement is a candidate and
changes nothing visible. A second measurement confirms it only from another
stable plane position and another peer sample, and then the retained
candidate is the one value that reaches the cache, the served hotspot, the id
remix and the delivery. Near what is served, nothing changes, even when the
value is also near the wire, so a correction a few px from the wire does not
flap; near the wire otherwise, the wire is served and the cached correction is
dropped. A stable position is measured at most once, a layout generation
change stops measurement once the display service's poll has seen it, and the
cache is read only behind the context gate, so a correction measured upright
never reaches a rotated output.

Each of these gates has a test that goes red with the check removed or
altered (file restored byte for byte afterwards):
  publish the first measurement          -> retained candidate, same sample, still plane, local nudge
  same sample confirms                   -> same sample never confirms, local nudge
  confirm with the new value             -> retained candidate, near wire, in band
  drop the near-wire arm                 -> near wire serves the wire
  drop the in-band arm                   -> in band changes nothing visible
  drop the re-store after clear-on-cap   -> in band stays cached
  measure a kernel-measured hotspot      -> never calibrated at the origin
  read the cache without a context       -> not served without a context
  drop the once-per-position flag        -> still plane measured once
  drop the transform gate                -> context only for an upright output
  swap phys and extent                   -> the arithmetic, the scaled context
  drop the clear-on-cap                  -> cache bounded
  drop the partial-snapshot gate         -> context only for an identity match
  drop the generation check              -> closed intervals
  compare the wire before the served     -> in band with both keeps the served correction

* drm: a cached hotspot correction is served only under the generation it was confirmed in

The calibration cache mapped a wire cursor id to its confirmed hotspot
and nothing else. A pair of stops taken inside the layout poll window,
after a monitor moved and before the poll saw it, could confirm a value
measured against the old layout; the generation gate then stopped that
stream, but the capturer rebuilt after the promotion seeded its served
hotspot from the cache and replayed the value under the new layout, until
another pair of its own replaced it (zhou, review of 25-sep).

Each entry now carries the layout generation it was confirmed under, and
a stream reads the cache under its own `built_gen` only: a value from
another generation is not served, the wire hotspot is, until a pair on
this generation confirms one. Checked at the read rather than by clearing
on promotion, and an entry is replaced or dropped only by its own
generation or a newer one, the bound included (at the cap the cache
clears what the writer's generation or an older one confirmed, and
caches nothing if only newer entries are left), so a receive thread
still running on the old layout can neither serve its value to the
rebuilt stream nor undo the value that stream confirmed.

Tests: a_correction_confirmed_under_an_older_generation_is_not_served (two
stops under one generation, the stream rebuilt under the next, its own
pair, then the old stream writing late),
the_bound_never_drops_an_entry_from_a_newer_generation. Mutations:
reading without the generation filter, replacing or dropping a newer
entry from an older generation, and at the cap either clearing
everything or caching when only newer entries are left, each turn one
of them red.

* drm: calibrate only against samples injected under the layout's adopted uinput range

`usable_sample` took the remap flag being clear as "the input mapping is
ready". It is not: the display service bumps the layout generation and
promotes the baseline before the uinput range update completes, and a
failed or pending update leaves the device mapping absolute coordinates
with the range of the previous layout. Every sample then carries the new
generation while its point lands scaled by the old range; two stops share
that error and agreement confirms it (zhou, review of 25-sep: a desktop
narrowed from 4000 to 3800 px puts a hotx of 4 at 54, inside the bitmap).

The display service now keeps the layout generation whose uinput range
the device runs, and a count, raised when an apply starts and again when
the device acknowledges it. Both move when `update_mouse_resolution`
returns Ok, on the DRM session-init path (also run by the hotplug
worker) and in the layout poll; the session-init path labels the range
with the generation read before it computed the rect, and the raw DRM
union it falls back to when the compositor cannot be asked with no
generation, so no stream measures on it until the poll applies or finds
a compositor range. A range that already fits the layout moves the
generation only, so the samples injected under it stay valid. From the
moment an apply starts, on any path, no generation is ready, the count
is raised and the recorded rect is forgotten, so an apply that fails or
times out (the device may still take the range late) leaves nothing
ready, and only an acknowledged apply records a generation again. The
poll and `update_uinput_resolution` run on different threads; they
check, apply and record under one lock. `check_init`, which a display
falling back to PipeWire runs inside a DRM session, records its apply
the same way (cfg(feature = "drm") lines only; the drm-off build is
unchanged). It has no fits check and applies on every run, as before, so
each run moves the count. A path that read its generation before the
poll bumped it records under the older one; no stream measures then
until a later layout check records the current one. A sample is stamped
under the ENIGO guard of its move, which an adoption also needs for its
refresh, so a move stamped with the count of an adoption was injected
after that adoption's refresh. The count is raised before the generation
is published and read after it. A stream measures only while that
generation is its own; each peer sample carries the count at injection
and is a reference only under the current one; a candidate measured
under one count starts over instead of confirming under the next. The
remap flag is untouched.

Tests: a_stale_input_mapping_publishes_nothing_until_fresh_samples_follow_the_adoption
(generations equal, no drift, the device on the previous range: two
stops publish and cache nothing; after the adoption a sample from before
it does not count, and fresh ones confirm),
a_sample_is_a_reference_only_under_the_adopted_input_mapping,
a_candidate_does_not_confirm_across_an_input_mapping_change,
an_acknowledged_range_is_an_adoption_and_a_fitting_one_is_not,
the_raw_drm_union_labels_a_range_with_no_generation,
an_apply_leaves_no_range_ready_until_it_is_acknowledged; the drm CI step runs
input_map_tests. Mutations: dropping the adopted-generation gate,
dropping the count gate, confirming across counts, an adoption that does
not count, a fitting range that counts, the union labelled with the
generation, and an apply that keeps the recorded rect or leaves a
generation ready, each turn one of them red. The call sites (the lock,
the calls before and after each apply on the three paths, the range-fits
branches) run IPC and are covered by reading.

* drm: forget the peer sample under the mouse lock on a move of this process

The temporary-move thread (the display probe `fill_displays` runs in the
PipeWire init, `check_init`) forgot the last absolute peer sample before
it took ENIGO. A peer move holding ENIGO at that moment moved the pointer
and recorded its sample after the forget, and the temporary move then
landed on top: the pointer somewhere else, the sample still the peer
point, with the current generation, count and a fresh sequence, so two
such overlaps could confirm a wrong hotspot (zhou, review of e6103daea).

The forget now runs under the lock the peer move records its sample
under, right before the move (`forget_sample_and_move`), so a peer move
lands entirely before the forget or entirely after the move. The drm-off
build keeps the line it had. The relative path of the peer already
forgets under the ENIGO guard of its move.

Test: a_move_of_this_process_forgets_the_sample_of_a_peer_move_it_waited_for
(the peer holds a stand-in lock when the move asks for it; nothing is
forgotten before the move has the lock; the peer records its sample and
releases it, and after the move the sample is gone). Mutations: the
forget taken before the lock (red in five runs of five) and no forget at
all, each turn it red. The call site in the thread, which passes ENIGO,
is covered by reading.
2026-09-26 14:59:19 +08:00
Winston 47a2a3c83d i18n(tw): fill missing Traditional Chinese translations (#16353)
Fill the three empty entries in src/lang/tw.rs, mirroring the existing
zh-CN (cn.rs) translations and reusing the terminology already used
elsewhere in the file:

- terminal-clipboard-write-tip
- Allow terminal apps to copy to clipboard
- To start a voice call, enable "Audio capture" on the "Screen share" page.

Signed-off-by: Mosquito1123 <zhangwentong1123@icloud.com>
2026-09-26 12:32:43 +08:00
Tayfur YıldızandTayfurYldz 17feabbcab fix(windows): allow existing session to foreground (#16349)
Signed-off-by: TayfurYldz <238304586+TayfurYldz@users.noreply.github.com>
Co-authored-by: TayfurYldz <238304586+TayfurYldz@users.noreply.github.com>
2026-09-26 11:46:58 +08:00
RustDeskandClaude Opus 5.5 08affc69c4 Fix clipboard range overflow (#16329)
* fix(clipboard): unix file server, bound range reads

The Range request fields nPositionLow and cbRequested are UINT32s carried
in i32 fields, but were sign-extended to u64. A negative cbRequested
became a near-u64::MAX length, `offset + length` wrapped past the clamp,
and the server tried to allocate a u64::MAX buffer, aborting the process.
Sign-extending nPositionLow also rejected offsets whose low word is
>= 2 GiB, breaking reads past 2 GiB in large files.

- decode nPositionLow and cbRequested as u32
- clamp with `length > file.size - offset` (offset <= size is checked above)
- allocate the read buffer fallibly and return an error instead of aborting

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(enigo): win, scale absolute mouse moves without overflow

mouse_move_to multiplied the peer-supplied coordinate by 65535 in i32,
which overflows for large values, and divided by the virtual screen size,
which panics if the metrics come back as 0. Scale in i64, clamp to i32,
and skip the move when the virtual screen size is unavailable. Results
for inputs that did not overflow are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(agents): avoid unthrottled high-frequency debug logs

Debug output is written to the log file, so per-packet / per-event log sites
must use trace or hbb_common's throttled_log!.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): unix file server, reject range reads over the frame limit

A response larger than MAX_FRAME_LENGTH (1 GiB) cannot be encoded for
sending, yet the server allocated and read it first, then failed the send.
Reject such requests before allocating, so a peer can no longer make the
server allocate more than 1 GiB per request. Requests that work today are
unaffected.

Drop the extra allocation-failure log; the caller already logs the error.

Tests cover the wire decoding through read_file_contents (negative
cbRequested, nPositionLow past 2 GiB) and the frame-limit rejection. Tests
that use the global CLIP_FILES now take a shared lock.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): keep file transfers on the file list they started from

A file-contents request names a file only by its index, and the side that
owns the files resolved it against whatever it held at that moment. On
Windows 10+ Explorer's clipboard also offers FileContents, which the owner
re-read from the live clipboard for every chunk, so copying another file
mid-transfer spliced the new file into the one being pasted (#16332). A
second paste, or another connection's paste, replaced the list the same
way, and on macOS/Linux sync_files replaced CLIP_FILES on every host copy.

Each request now names its list in the existing clip_data_id field: an
FNV-1a hash of the file-descriptor PDU, which both sides already hold.
Owners keep the last 4 lists they sent and serve a request from the list
it names; an unknown id fails instead of reading another file. Peers that
send no id read the list last sent to their connection, and a Windows
owner stops reading the live clipboard once it has changed since the list
was built.

Tests cover a host copy and a second paste during a transfer, a list id
sent to another connection, and the hash's reference vectors.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): unix file server, cap a single range read at 16 MiB

A peer could still make the server allocate and read up to the 1 GiB frame
limit per request. Cap the data a single range read returns at 16 MiB. The
read is clamped to the rest of the file first, and a larger one is refused
rather than shortened: a short response reads as end of file to IStream
callers on Windows and would silently truncate the copy.

macOS requests 4 MiB per range (BLOCK_SIZE) and FUSE reads are smaller. A
Windows client forwards the application's IStream::Read size, so only an
application reading more than 16 MiB in one call is affected.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(enigo): win, warn (throttled) when a mouse move is skipped

A missing virtual screen size is a fault that should show up in a user's
log, but mouse_move_to runs per input event. Log it at warn at most once a
minute via throttled_log! instead of at trace.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): review fixes for the file lists kept per transfer

unix owner:
- A retired list closes its files and 8 MiB read buffers; they reopen,
  from offset 0, on the next read.
- The new list is built aside and swapped in only on success, so a failed
  rebuild leaves the current list in place.
- A rebuild with an unchanged id keeps its peers on the new list instead of
  retiring a duplicate, so re-copying a directory no longer pushes out a
  list that a transfer is still reading.

Windows:
- One served-list slot per list, recording every connection it was sent
  to, so pastes of the same list do not use up slots.
- A request for an earlier list is served before OleGetClipboard, so a busy
  clipboard cannot fail it.
- An IStream read over 16 MiB is split into requests the unix file server
  accepts. Reads up to 16 MiB take the unchanged path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): give each copied file list its own id

The list id hashed only the descriptors, so two copies with identical
names, sizes and times (the same file in two folders) shared an id and a
transfer could read the other copy's files. Each owner now writes a random
nonce into the first descriptor's clsid, inside the reserved bytes every
peer skips; no owner sets FD_CLSID. The paste side hashes what it received,
so it needs no change, and older peers ignore the bytes. Re-sending the same
paths with the same descriptors keeps the nonce, and the id.

Windows owner:
- Serve a request from its list before the ownership check when the list is
  no longer current or the host clipboard now holds files from a peer, so
  another controller copying onto the host no longer fails in-flight
  transfers. Only lists sent to that connection are served.
- Evict the list sent least recently instead of in insertion order.

unix owner: take everything from the crate in one use block.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard,enigo): bound served-list reads, clamp absolute moves

wf_cliprdr: the served-list branch runs before the ownership check, yet it
allocated the peer's cbRequested (up to 4 GiB) before looking the list up.
Accept only FILECONTENTS_SIZE or a range of at most 16 MiB there, which is
all that clients sending an id ever request, and fail anything else before
allocating.

enigo: clamp the scaled absolute coordinate to 0..=65535, the range
MOUSEEVENTF_ABSOLUTE takes, instead of to the i32 range. Coordinates on the
virtual desktop give the same result as before; off-desktop ones now land on
its edge.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): keep a file list while it is being read, throttle read errors

A unix paste side fetches every new file list as soon as the host copies,
so each copy retires the previous list, and four copies during one long
transfer evicted the list it was still reading. A kept list that serves a
read now becomes the most recent (unix: back of the retired queue, Windows:
last_served), so the next eviction takes a list nobody is reading.

A failed file-contents read logged an error per request, and peers can now
trigger new ones (an unknown list id, an over-limit range). Log it through
throttled_log! instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): unix, keep retired lists in the order they were sent

A peer that sends no list id is served the list last sent to its
connection, found by searching the retired queue from the back. That only
holds while the queue stays in retirement order, which is the order lists
were sent. The previous commit moved a list to the back on every read, so
another connection reading an older list could make a peer's next chunk
come from that list: a transfer of B continued with A's bytes.

Keep the queue in retirement order and track recency in a separate
last_used stamp, set on retirement and on each read. A full queue evicts the
list with the lowest stamp, so a list still being read is kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): unix, keep files being read open when their list is retired

Retiring a list closed every file handle, so the next read of a file part-way
through reopened it by path. If that path had been replaced meanwhile (an
editor saving over it), the rest of the transfer came from the replacement:
AAAABBBB arrived as AAAADDDD. Close only files that are not being read, such
as the preloaded next file; a file part-way through keeps its handle and
offset, and so its identity.

Tests read two files of one list alternately, retire the list, replace both
paths by rename, and check each file continues with its original bytes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): cap Windows ranges, expire idle kept lists, check file identity

Windows owner: refuse every FILECONTENTS_RANGE over 16 MiB before
allocating. Only the served-list branch was capped; requests without an id
still allocated whatever the peer asked for, up to 4 GiB.

Both owners: a kept (retired / non-current) file list that nobody has read
for 5 minutes is dropped, with its open files; its transfer is over or its
peer gone. The current list never expires, as before. On Windows, reads of
the current list through the existing path now also refresh its kept copy,
so a long transfer does not lose its list once a newer one is sent.

Windows owner: old-list reads compare the file's size and last-write time
with the descriptor that was sent, on the handle they read from, and fail
on a mismatch instead of reading whatever file now has that path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(clipboard): unix, check list expiry without backdating an Instant

an_idle_retired_list_expires backdated a timestamp with
Instant::now().checked_sub(TTL + 1s), which is None while the monotonic
clock is under about five minutes, as on a freshly booted CI machine; the
list then never expired and the test failed. expire_retired now takes the
current time, and the test passes a later one instead. Callers pass
Instant::now(), so behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): drop read-time refresh, idle expiry and rebuild reuse; tighten checks

Remove the read-time recency and the 5-minute idle expiry on both owners,
and the unix reuse of an unchanged rebuild (has_same_files). They covered
corner cases, added state, and each brought regressions of its own. Kept
lists are again evicted oldest first (unix) or least recently sent
(Windows), 4 at most; a transfer that outlives 4 newer lists fails cleanly.

Windows: serve kept lists after the existing ownership check again, so a
request carrying a list id no longer bypasses it while the host clipboard
holds files from another session. Refuse request types other than size or
range before allocating.

unix: a retired list's file must still match the size and modified time it
was listed with, checked on the handle the read uses; a file replaced at
its path before its read now fails instead of being served.

Tests: drop the four tests of the removed behavior, add
a_retired_list_refuses_a_file_replaced_before_its_read.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(agents): handle corner cases raised in review with small fixes or docs

A refactor added to cover a corner case rarely converges: new counters,
timestamps and expiry rules interact with state existing code relies on,
and the next review round finds the problems they introduced. Fix a corner
case when the fix is a few lines with no new state; otherwise document it
as a known limit, and ask before anything larger.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 11:25:12 +08:00
RustDeskandClaude Opus 5.5 e9ddbd8f46 cursor: bound the decoded cursor caches on the Flutter client (#16304)
* cursor: name a shape by what it looks like, not by its handle

A cursor id was the platform's handle for the shape: HCURSOR on
Windows, the XFixes serial on X11. Apps mint a new handle for a shape
they have shown before (Chrome, Electron, Qt custom cursors), and an
X11 animated cursor gets one per frame, so one arrow arrived under
thousands of ids over a session. The controlled side cached and sent
it again under each, and the controller decoded, rendered and kept it
again under each, and grew by gigabytes over weeks of connection.

The controlled side now names a shape by an xxh3 hash of its size,
hotspot and pixels, taken once when a handle is first seen, before
the pixels are compressed. The per-connection send already sends a
shape once and afterwards only its id, so a shape now crosses once
however many handles it has. The id is opaque in the protocol, so
controllers of any version accept it. The DRM backend already named
shapes by content with FNV-1a; it uses the same hash now.

A peer before 1.5.0 still names shapes by handle, and the fix has to
work against every deployed peer. For those peers the controller
hashes each CursorData's compressed colors with its geometry: one
peer compresses the same pixels to the same bytes, so a shape seen
before is recognised without being decompressed. The UI gets that
shape once, under one id, and every later handle for it is passed on
as a cursor_id of that id. The map from the peer's ids is kept for the
connection, unbounded, since the peer sends a shape once and may
select any id it named again; an entry is two integers. From 1.5.0
the controller passes the peer's ids through unchanged, on the old
path.

The web core in flutter/web does the same in its own tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: hold a content id to what the web client can read

The web client decodes a u64 into a JS number and throws on a value
past 2^53, which drops the whole message. A full 64-bit xxh3 id is
almost always past it, so a web client connected to a peer on this
build would never have been given a cursor shape. DRM's ids were
already full width, so web clients lost the cursor on DRM peers too;
the controlled side now renames those as well.

The id keeps the hash's low 53 bits. Two of ten thousand distinct
shapes then collide with a chance of about one in two hundred million.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: hand the UI a shape's pixels as they are, not as text

A shape's pixels went to the Flutter UI as a JSON array of integers
inside the cursor_data event: the core serialised a 1 MiB shape into
up to 4 MiB of text on the receive loop, and the UI parsed that into a
million-element list and copied it into bytes, on the UI thread. The
event, text and all, was then kept for the session so that a tab
moved to another window could replay it, and a reconnect, on which the
peer sends every shape again, appended another copy of each.

The core now sends a shape as an EventToUI::Cursor variant carrying
Vec<u8>, which flutter_rust_bridge hands to Dart as a Uint8List, on
the same per-session stream as the events so that it keeps its order
with the cursor_id events around it. The web core calls onCursorData
with the Uint8Array, as it calls onRgba for a frame. The id stays
text, since the peer's ids can exceed Dart's int.

The replay keeps each shape's pixels once, by id, and encodes them as
base64 only when a tab moves. A shape arriving is also recorded as the
last one selected, since the replay goes in first-seen order; before,
a tab moved right after a new shape came back on the previous one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let a controller ask the peer for a shape again

A peer sends each shape once per connection and afterwards only its
id, so a controller must keep every shape it was sent for as long as
it is connected. The controlled side now answers
Misc::request_cursor_data with the CursorData of that id, from the
shapes it has sent, and only to a connection the cursor service
would send it to. A controller from 1.5.0 on can then bound what it
keeps and ask again for a shape it let go. None asks yet: the peer has
to have the answer before a controller can rely on it, and peers are
updated last.

The shapes are kept by content id, and every handle for a shape
shares its one message, where each handle used to keep its own copy.
They are dropped with the service's own cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep a shape as its ui.Image and nothing else

Each shape the UI had been sent stayed in four copies for the session:
the pixels for a tab move, an image package copy to resize from (on a
macOS or Linux controller of a Windows or Linux peer, a second one
decoded back from a PNG), the bytes handed to the native cursor, and
the ui.Image painted when the peer moves the pointer.

A shape now keeps only its ui.Image. The resize source and the native
bytes exist while a native cursor is being registered and are dropped
once it is; a shape shown again at a raster it was registered at needs
neither. For a raster it lacks, the pixels are read back from the
ui.Image, which returns them exactly as they came. A tab move reads
every shape back the same way, and the moved window decodes them as
it would have on arrival.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: pin that a released shape keeps neither its pixels nor its bytes

The shape in use once registered, the shapes not in use, and the
pixels read back for a moved tab are all dropped; the tests now say so,
so that a later change keeping one of them fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep one native cursor per shape, and each tab its own

A shape got a native cursor for every raster it was shown at, and all
of them stayed until the session ended, so every zoom or DPR change
added a native cursor for each shape in use. A shape now keeps the one
at its current raster; the one it replaces is deleted the next time a
cursor already registered is built, by when its successor has been
activated. A raster returned to before that takes its cursor back
instead of registering another under the same name.

The native cursors of a window's engine are shared by its tabs, and
the predefined cursors had one name in all of them, so a tab closing
deleted the default and forbidden cursors the other tabs still showed.
Names are now scoped to the tab's cursor model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep the shapes compressed in the core, and only the one in use in the UI

The UI kept every shape as a ui.Image, one raw copy each, for as long
as the session lasted, because the peer sends a shape once and a
shape might have to be drawn again. The core receives the shapes
compressed, at a few hundredths of that, and now keeps them so:
Session::cursor_shapes holds each shape that decoded, as the peer sent
it, under the id the UI knows it by. The colors are copied, since the
message's may be a slice of a larger received buffer.

The UI keeps a ui.Image for the shape in use alone. A shape shown
again at a raster its native cursor has needs no pixels at all; for a
raster it lacks, for painting it, or for the window a tab moved to,
the UI asks the core through session_get_cursor_shape, which
decompresses and checks the shape again with decode_cursor_data, the
same size and decompression limits as on arrival. A shape the core
cannot give is not asked for again until the peer sends it. A tab
move now carries only the id in use, and nothing is read back from
the GPU.

The web core keeps the shapes the same way and gives them back through
getCursorShape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a decode that finishes after the session clears keeps nothing

A shape asked of the core while a tab closed was decoded after the
cursor model had been cleared and stored in it, where nothing disposed
of its ui.Image again; a shape whose cache failed to build left its
ui.Image undisposed as well. A clear now starts a new generation, and a
fetch or decode from an earlier one disposes what it made. A shape the
core gave but that did not decode is not asked for again on every
frame it is painted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep a native cursor for the shape in use alone

Every shape the peer showed kept a native cursor for the session, each
a raster the size of the shape as displayed. A shape switched away
from now gives its native cursor up the way a replaced raster does:
deleted the next time a cursor already registered is built, taken back
if the shape returns first. A shape shown again after that is rebuilt
from the compressed copy the core keeps. The predefined cursors are
not the peer's shapes and stay registered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep the native cursors of the 16 shapes used last

Keeping a native cursor for the shape in use alone rebuilt one on
nearly every switch, since the pointer moves among a few shapes: the
arrow, text, hand, four resize arrows, wait. The native cursors of the
peer's shapes are now kept in order of use, 16 of them, and the one
used longest ago gives its cursor up the way a replaced raster does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: forget the native cursors a session clear deletes

The clear deleted every registered native cursor but kept their names,
so a cursor model used again, as the mobile client's is, took each
name for registered and showed a cursor that no longer existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: hold a native cursor to 512 pixels a side

A native cursor could be registered up to 1024 pixels a side, four
MiB of pixels each, which with sixteen kept made 64 MiB at worst. The
largest cursor a system shows is 256 pixels (Windows' largest pointer
size), so a raster twice that is shown no larger: the cursor is drawn
smaller rather than rejected, and sixteen kept come to 16 MiB at most.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a shape switched away from while it decodes is not marked lost

A shape asked of the core was taken for undecodable when it was no
longer kept once its decode finished, but a shape the peer switched
away from in the meantime is let go on purpose, and marking it made
every later request for it be skipped: its native cursor stayed
deferred and its painted cursor missing for the rest of the session.
The decode now reports whether it decoded, and only a failure marks
the shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* flutter: leave two untouched signatures as they were

dart format had rewrapped registerEventHandler and sessionSetCommon
next to the cursor additions.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: read a shape's pixels from where its view starts

The pixels used to be copied out of the JSON event into a fresh list,
so the list's buffer began at its first pixel. Now they come straight
from the core, native or web, as whatever Uint8List it hands over, and
img2's fromBytes takes the buffer, not the list, so a view into a
larger buffer would have been read from the buffer's start. Neither
core gives a view today; this stops depending on that.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a DRM cache reset keeps the shape it was making room for

The shape being sent was filed in CURSOR_SHAPES before the DRM ceiling
cleared it with everything else, so a controller asking for the shape
on screen got nothing until the next new shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: delete a replaced native cursor at the next build that shows one

A replaced native cursor was deleted only by a build of a cursor
already registered, so a run of new shapes, each shown once, left
every replaced cursor registered: 16 on the books, all of them in the
system. Now every build that shows a cursor deletes the ones replaced
before it, right before it registers or takes one back; what replaced
them was activated in an earlier frame, so they are off screen. A
build that has to ask for pixels shows nothing new and deletes
nothing, so a raster returned to right after being replaced still
takes its cursor back; one returned to later registers again.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a shape that does not decode leaves no handle and no copy

CursorDedupe named a handle as it hashed the shape, before the shape
was checked, so a peer sending shapes that fail the checks under new
handles grew the map with nothing the UI could ever select, and such
a shape took over the handle of one that had decoded. The handle is
now named once its shape decoded, or was shown before.

The flutter build also copied a shape's compressed colors out of the
message before the checks, so a message with a small size and huge
colors was copied whole before being rejected. The copy is made once
the shape decoded; until then the message's own bytes are held.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: remember the shape the core lacks only while it is in use

Every id the core could not give was kept in a set for the session,
so a peer sending cursor_id after cursor_id of shapes it never sent
grew it by a string each, at a few bytes of traffic per entry. The
mark exists so that painting does not ask for the shape in use on
every frame, and the shape in use is one, so one mark is kept: the
peer selecting another shape forgets it, and selecting a lost shape
again asks once more.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: forget the shape the core lacks once the peer selects another

The mark was replaced only by another shape the core lacked, so a
lost shape selected again after a known one was still not asked for.
Selecting any other shape now clears it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: leave the DRM cursor's own id as it was

The wire id is cursor_content_id whatever the platform, set in
run_cursor over the shape's pixels, so the id the DRM reader derives
for itself only tells one hardware cursor from the next and keys the
service's cache. Which hash it uses does not reach a controller; the
change to xxh3 and the dependency it brought to scrap go.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: say the 1.5.0 gate means the release

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: say why the peer answers request_cursor_data with what it holds

No controller sends it yet, and a review asked for it to go because a
cache reset on the peer could leave a request unanswered. A shape the
peer's cache dropped is rebuilt, and indexed again, the next time it
is shown, before any connection names it by id, so the shape a
controller has just been told to show is always there to give; that
is the contract a future bounded controller relies on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: drop the tests nothing can fail

a_handle_is_named_once_its_shape_is_shown dates from when `name`
wrote the handle map. `name` is pure now, so its last assertion
cannot fail, and the others repeat two neighbours.
every_handle_the_peer_named_stays_for_the_connection fails only for
a bound added on purpose, which the struct's doc rules out. The Dart
arrival test is covered by the first test of its file.

The kept-shape test now asserts what `cursor_shape` is for, a copy
rather than a view of the received buffer, in place of the unknown
fields it drops. The content-id test moves out from between two
`use` lines.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let the kept-shape tests run without the flutter feature

CI's cargo test builds the default features, and the two functions
under test are pure, so they compile for every test build and the
module loses its feature gate.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep native cursors for every frame of an animated cursor

An animated cursor is a shape per frame, 18 for the Windows busy cursor
and 23 for KDE's wait cursor. With 16 native cursors a cycle longer than
that missed on every frame: fetched from the core, decoded, registered
again and the replaced cursor deleted, about thirty times a second for
as long as the peer was busy. 64 holds two such animations and the
everyday set besides.

The tests settle in 10 ms instead of 100 ms, so the ones that fill the
limit stay quick.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: release only the shapes that can hold pixels

Selecting a cursor swept every shape of the session to release pixels,
though only two can hold any: the shape selected before, and a shape
that finished decoding after the peer moved on. Release those, so a
cursor_id costs the same however many shapes the peer has shown.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: show the native cursor limit holds two animations and the everyday set

64 is a working set, not the longest animation: KDE's wait and progress
cursors are 23 frames each, and a session that meets both plus a dozen
static shapes must keep them all, or every turn rebuilds.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let the shape in use keep its pixels for a new raster

Dropping them once the native cursor was registered meant every scale
change, zooming with the cursor zoomed or crossing to a display of
another scale, showed the system arrow while the core gave the shape
back and it decoded again. The shape in use now keeps them and makes the
new raster at once; a shape switched away from still keeps none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: never fall back to the default cursor on a switch

A switch to a shape without its image, or without a native cursor at
its raster, showed the default arrow until the core gave the shape back
and it decoded: the painted cursor on every switch back, the native one
after an eviction or while a new shape decoded.

- The shape shown before stays, image, hotspot and native cursor, until
  the one in use is ready.
- Where the cursor is painted, on mobile or with the remote cursor
  shown, the images of the 64 shapes used last are kept, like the native
  cursors, so an animation does not decode a frame per turn. Elsewhere
  only the shape in use keeps one.
- A shape that finishes decoding after the peer moved on is kept with
  them instead of dropped, so a fast animation fills them at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: name the dedupe's content-id set for what it holds

`shown` read as the shape on screen. It is the shapes decoded and given
to the UI, keyed by content id, so a shape arriving under a new handle
is looked up once instead of scanning the handle map: `decoded`,
`has_decoded`, and `record` for the call that fills both maps. The web
mirror is renamed the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep native cursors for the session, as before

Evicting native cursors and deleting a shape's replaced raster made
Windows leak more than master. The engine's deleteCustomCursor/windows
frees the HCURSOR with DeleteObject, which does not take a cursor, so a
delete frees nothing and each cursor made again for a raster, or for a
shape shown once more, leaks another handle. Keeping every raster of
every shape until the session is cleared creates each one once, as
master does.

Fixing the engine instead is not cheap: x64 runs our fork on Flutter
3.24, where the fix is one more patch to rebuild and carry across every
upgrade; arm64 runs the stock engine of a newer Flutter with the same
code, where it means porting the fork and publishing an arm64 engine
too, or waiting for an upstream fix to reach stable. Content ids keep
the count to the shapes the peer really shows.

The painted images, the compressed shapes in the core, and a switch
showing the cursor shown before are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: record the Windows measurement behind keeping native cursors

A measurement on Windows confirmed what the engine source implied: of
500 cursors made by CreateIconIndirect, DeleteObject freed none and
left 500 USER objects alive, while DestroyCursor and DestroyIcon freed
all 500. The comment now says so, that native cursors have no LRU for
that reason only, and that one can come back once both engines destroy
cursors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: look a native cursor up by the raster asked for

The key ended in the raster made last. A shape switched away from keeps
no pixels, so its raster stays where it was, and going back to a raster
it was shown at before looked up the wrong key: A at 1.0, A at 0.5, then
B, then A at 1.0 again missed the 32x32 cursor that was still there,
fetched A from the core, and showed B meanwhile. With native cursors
kept for every raster, the key now ends in the raster asked for; with
pixels, that is the raster made, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let a shape keep its pixels until a native cursor holds them

A shape switched away from, or decoded after the peer moved on, let its
pixels go whether or not it had a native cursor, and a native cursor is
made only for the shape in use. A shape whose restore kept finishing
after the next switch, as an animation's frames can, was fetched and
decoded again every time it came back and never got a native cursor.

A shape without one now keeps its pixels until one is made, at most
kRecentShapes of them, the one waiting longest let go first. Mobile
only paints the cursor, so it lets them go as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* proto: keep cursor ids as strings in JS

A Windows peer before 1.5.0 names a cursor by its handle, sign-extended
above 2^53 when its top bit is set. The web client decodes u64 fields
into JS numbers, and ts-proto throws on a value a number cannot hold,
so each such cursor_data or cursor_id was dropped whole and the web
cursor stayed on the shape before. [jstype = JS_STRING] makes ts-proto
generate these two fields as strings; the wire format, the Rust code
generated and every other client are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: wait for a native cursor at the raster asked for, not any raster

A shape let its pixels go once it had a native cursor at some raster.
After a zoom, or on a display of another scale, an animation's frames
had native cursors at the old raster only; each was fetched again at
the new one, and a restore that finished after the next switch let its
pixels go at once, so the frames never got a native cursor at the new
raster and the cursor stayed on the one shown before. A lookup that
finds no native cursor at the raster asked for now counts the shape as
waiting for one, so a late restore keeps its pixels until it has one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: count a shape held again when its asked raster has a native cursor

A lookup that missed took the shape out of _nativeIds, but one that hit
did not put it back. A shape asked at a new raster, then at one it has a
native cursor for, still counted as waiting: a restore finishing after
the switch away kept its pixels in _awaitingNative instead of letting
them go. The set now says whether the raster asked last has a native
cursor, either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* Revert "cursor: count a shape held again when its asked raster has a native cursor"

This reverts commit 7cefbfc7a.

_nativeIds is meant as "no raster of this shape is still missing its
native cursor", not "the raster asked last has one". A shape asked at a
new raster whose restore is on its way, then shown at a raster it has a
cursor for, still waits for the new one; counting it held let the late
restore's pixels go, so going back to the new raster fetched it again,
and with an animation's frames and a scale that keeps changing, the
loop 1e4388771 fixed could come back. Keeping the pixels costs at most
a waiting slot, within the 64. A test now locks this: a raster still
missing keeps a late restore whatever was shown meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: reuse a shape sent before without compressing it again

A handle not seen before sent the service through the whole path:
capture the pixels, name them by content, compress them, and only then
find the shape already in CURSOR_SHAPES and drop what it compressed. An
app that mints a new handle for the same cursor, as Chrome and Electron
do, paid a compress per handle, a few ms for an enlarged cursor. The
content id is now looked up first, and only a new shape is compressed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: bound the handles the service files, and the shapes with them

A platform may mint a new handle each time it shows a shape, as Chrome
and Electron do, so cached_cursor_data grew by an entry per handle for
the life of the service, even when every one named the same shape; and
the compressed shapes in CURSOR_SHAPES were bounded by nothing but the
handles. Past 4096 handles, or 32 MiB of compressed shapes however few
the handles, both start over together, keeping the shape being sent: a
handle shown again is captured and named again. On every platform; the
DRM build's own 64-entry ceiling is unchanged and comes first there.

CURSOR_SHAPES keeps the bytes it holds beside the shapes, cleared with
them, so every path that clears it resets the count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let the macOS seed report a change, and the content name the cursor

macOS named a cursor by a fingerprint of its size, hotspot and two
pixels near the hotspot. It collides between standard cursors: the open
and the closed hand give one value, and the arrows with a badge (copy,
not allowed, contextual menu, disappearing item) another, so a switch
between them was never sent, or a cached shape of the other was.
CGSCurrentCursorSeed already says when the cursor changed; get_cursor
now reports the seed, and the shape is named by its content, as on
every platform. The fingerprint is gone.

get_cursor_data checks the seed before and after the capture. The seed
was taken before capturing, so a capture that found the cursor changed
again lost the change; it now leaves it for the next poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: file no macOS seeds, and send nothing for the shape already shown

A macOS seed marks a change and never comes back, so filing it as a
handle only filled the map; the byte ceiling still bounds the shapes
there. A new handle or seed for the shape already shown, which a seed
change without a new shape or an app minting handles gives, sent every
connection a cursor_id for what it already showed; a shape is one
message however many handles name it, so the same message is not sent
again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: capture the macOS cursor shown without checking the seed around it

Every macOS seed change is now captured, pixel by pixel, and a seed
that moved during that capture failed it; the service then logged an
error and slept a second, so the controller's cursor lagged while it
changed. The check guarded nothing: the shape is named by its content,
not the seed, and a change after get_cursor read the seed moves it on,
so the next poll captures it anyway. Resetting the seed on a failed
check was not needed for the same reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: fall back to the default cursor for a shape the core cannot give

The shape shown before stays while the one in use decodes, so a switch
does not flash the default cursor. It also stayed once the shape in use
was known to be lost (rejected by the core, or not decoding): the
controller kept drawing, say, an I-beam for a pointer it never got,
until the peer changed shape. Both the native and the painted cursor
now leave the default one, as master did for the native cursor. A shape
that does not decode is marked in updateCursorData, whether it was sent
or fetched again, so both paths agree.

The client also selects a shape it rejects as it arrives. It showed the
shape before until the peer selected the rejected one again, and the
default cursor from then on; it now looks the same both times. Sciter
ignores an id it has no shape for, as it did.

The default and forbidden cursors are made with the model. They were
made the first time a build asked for one, and their decode lands
later with nothing to draw again, so that first build showed the shape
before in their place.

A fetch failing after the session was cleared marks nothing in the new
one, and a fetch that throws at once tells the listeners after the
build that asked for it, not during it.

The forbidden cursor, shown while input is off, became the cursor shown
last, so a raster made after input came back showed it until the
shape's pixels were fetched, or for good if they never came. Only a
shape stands in for a shape now; CursorModel.shown keeps the rule for
both builders.

_checkView asks for a single registration again: every native cursor
is made once per session, and one made twice leaks an HCURSOR on
Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: name a handle by the shape rejected under it, not the one before

A shape the client rejects is selected as it arrives, so that it shows
the default cursor then as it does later. Under a handle reused for it,
the dedupe still named the shape the handle had brought before, and
selecting that switched the pointer to an old shape: A under handle 7,
then B under 8, then a rejected C under 7 showed A in place of B, and
again whenever the peer selected 7.

The handle now names the rejected content, which is never marked
decoded, since only a shape not decoded before reaches the decode: the
UI has no shape under it and shows the default cursor, then and when
the handle is selected again. The shape the handle named before stays
kept for the other handles naming it, and a handle that brings it again
names it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: file no handle for a shape that is rejected under it

A shape rejected under a handle named the handle by the rejected
content, so that a known handle does not show the shape it brought
before. A handle never seen was filed the same way, so a peer sending
shapes that do not decode under new handles grew the map with each,
where a rejected shape used to leave nothing. Only a known handle is
renamed now; one never seen is not filed and is passed on as unknown,
which the UI shows as the default cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: say what Future.sync defers, and give the default cursor time on a slow runner

The comment on the fetch in restorePixels read as if the fetch were put
off; it runs at once, and Future.sync only turns its throw into an error
the await hands over later, which is what keeps the notify out of the
build.

cursor_default_test gave the default cursor 100 ms to decode, which a
slow runner may miss. It cannot wait for the cursor itself, since asking
for it would make it; it now waits 500 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 12:09:46 +08:00
fufesou bb924d2939 fix: avoid unnecessary clipboard reads and stale initial sync (#16293)
* refact: simple refactor

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(clipboard): don't keep the clipboard cache

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: prevent initial clipboard sync from overwriting newer updates

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: invalidate initial clipboard snapshots on remote and file updates

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: handle clipboard changes during initial sync

Track clipboard changes even when they produce no sync message.
Refresh invalidated snapshots to preserve sync after Wayland startup.
Prevent repeated PeerInfo responses from restarting initial sync.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: skip file clipboard reads when file sync is not required

Check is_file_required() before reading clipboard file URLs to avoid
unnecessary clipboard access when no session needs file synchronization.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: refresh clipboard requirements before listener startup

Update Flutter's text and file clipboard requirements before starting the
shared clipboard loop so startup notifications use the current settings.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: exclude disconnected sessions from clipboard requirements

Only count connected Flutter sessions when checking clipboard requirements.
Recompute them on disconnect so a remaining session with sync disabled
does not keep unnecessary clipboard reads enabled.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: filter disconnected sessions from clipboard requirements

Exclude disconnected Flutter sessions from text and file clipboard
requirement calculations, even when their tabs remain open.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: block file clipboard traffic before login

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: skip Wayland host startup clipboard broadcasts

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: respect initial clipboard sync setting on Wayland

Stop broadcasting startup selections through the normal clipboard sync
path. Keep generation invalidation for snapshots captured before the
listener becomes active.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: wait for clipboard listener readiness before initial sync

Wait for Linux clipboard backends to finish subscribing before the
initial read. Update clipboard-master to use its readiness callback.

Report completion for empty or failed reads so initial sync does not
remain pending. Document snapshot invalidation across listener restarts.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: wait for Linux clipboard readiness asynchronously

Use watch notifications to keep the connection loop responsive during
clipboard startup. Cancel readiness waits when the session channel closes.

Advance generation on readiness and capture it with each initial read
so listener restarts invalidate older snapshots.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: preserve Wayland startup file clipboard sync

Distinguish startup selections from normal clipboard changes.
Process startup files through the existing client clipboard worker,
while keeping text initial sync and host startup suppression unchanged.

Signed-off-by: fufesou <linlong1266@gmail.com>

* fix: bound clipboard readiness waits on Linux

Add a five-second timeout to the initial-sync readiness wait and
log failures.

Update clipboard-master to support timeout and cancellation while
waiting for the initial Wayland selection.

Signed-off-by: fufesou <linlong1266@gmail.com>

* refact(clipboard): update clipboard-master

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-25 11:34:01 +08:00
Maison da Silva 134af545ae Rename Portuguese module from ptbr to pt_BR (#16342) 2026-09-25 11:23:22 +08:00
Maison da Silva 417e3bdd2c Rename ptbr.rs to pt_BR.rs (#16343) 2026-09-25 11:23:11 +08:00
RustDeskandClaude Opus 5.5 483cc10266 fix(appimage): build AppRun with bounded argument splitting (#16330)
* fix(appimage): build AppRun with bounded argument splitting

AppRun v2.0.0, which appimage-builder downloads, copies each argument
into a 1 KiB stack buffer in apprun_shell_split_arguments, so any
argument of 1024 bytes or more aborts the AppImage with "buffer overflow
detected" before RustDesk starts (e.g. --connect with a 10000-char id).

Build AppRun from the v2.0.0 commit with a patch that sizes the buffer
from the input and stops the quote/escape scanning at the terminating
NUL, in ubuntu:16.04 like upstream's release, and put it where
appimage-builder looks before downloading.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(appimage): verify the patched AppRun is the one shipped

Reset the split buffer by its first byte rather than zeroing all of it
per argument, check the AppRun source tarball's sha256, pin the build
image by digest, and fail the job if appimage-builder deployed anything
other than the binary built here.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 00:49:00 +08:00
fufesou efec124c52 Fix, online state, validate the data length (#16339)
* fix(client): reject truncated online status responses

Validate the bitmap length before indexing server-provided states. Return an error for short responses so they cannot panic or update cached online status.

Signed-off-by: fufesou <linlong1266@gmail.com>

* docs(client): illustrate online status bitmap sizing

Signed-off-by: fufesou <linlong1266@gmail.com>

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-25 00:35:47 +08:00
HeZheng 341193290e fix(mobile): honor reverse mouse wheel setting (#16337)
* fix(mobile): honor reverse mouse wheel setting

Signed-off-by: zhenghe <zhenghe2009@gmail.com>

* refactor(mobile): place wheel helper under platform

Signed-off-by: zhenghe <zhenghe2009@gmail.com>

---------

Signed-off-by: zhenghe <zhenghe2009@gmail.com>
2026-09-24 23:29:36 +08:00
RustDeskandClaude Opus 5.5 f299fb9906 fix(clipboard): unix, check file transfer permission on incoming file… (#16333)
* fix(clipboard): unix, check file transfer permission on incoming file clipboard

The Cliprdr arm served incoming file clipboard messages on Linux/macOS
without checking the file transfer permission, which the controlled
side can turn off mid-session. can_sub_file_clipboard_service() only
gates the outgoing service, so a peer could keep pushing files in and
keep requesting the host's copied file list and contents.

Check file_transfer_enabled() on every message. It is the same
permission the client and the Windows cm use for file copy-paste.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(clipboard): honor one-way file transfer on incoming file requests

One-way file transfer was only enforced on the outgoing side: the host
never announces its clipboard files. A controller could still send
FormatDataRequest / FileContentsRequest directly, and the host answered
them, from the live clipboard on Windows and from serv_files on
Linux/macOS.

Drop those two requests when one-way file transfer is on, before any
platform handling. The messages that carry the peer's own files to
this side are untouched.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* style: drop redundant doc comment

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 21:10:54 +08:00
58ff78a823 Hdr tonemap (#16033)
* scrap: tone-map HDR desktops to SDR in the Windows capturer

With HDR enabled, Windows composes the desktop as linear scRGB in
R16G16B16A16_FLOAT and places SDR white at the user's "SDR content
brightness" (DISPLAYCONFIG_SDR_WHITE_LEVEL / 1000, e.g. 2.5 for 200
nits) rather than at 1.0. The legacy IDXGIOutput1::DuplicateOutput we
used always converts that surface to BGRA8, and it does so by clipping,
so everything above ~40% linear brightness lands on white. That is the
washed-out / overexposed / high-contrast picture reported for HDR hosts
in #5368, #9951, #12707 and discussion #7652.

Ask for the desktop with IDXGIOutput5::DuplicateOutput1 and the format
list [R16G16B16A16_FLOAT, B8G8R8A8_UNORM]. An SDR desktop still yields
BGRA8 and takes the unchanged path. A float frame is converted on the
GPU by a small pixel shader: divide by the SDR white level, clamp, apply
the sRGB transfer. SDR content round-trips exactly, HDR highlights clip
at white, the same result the local user sees. The white level is read
per output through DisplayConfigGetDeviceInfo and refreshed once a
second, so dragging the Windows slider tracks remotely. The converted
BGRA8 texture feeds both the staging-copy (CPU) path and the vram
(hwcodec texture) path; rotation is unchanged. Toggling HDR mid-session
invalidates the duplication as before, and the recreated capturer
re-detects the format.

The shaders are compiled at runtime from a dynamically loaded
d3dcompiler_47.dll so no new import is added to the binary. If the DLL,
the compile or any D3D object creation fails, a process-wide flag makes
later capturers fall back to the legacy DuplicateOutput, i.e. today's
behaviour.

This deliberately stops at SDR on the controlled side, with no option
and no protocol change, which is how OBS, Sunshine (client without HDR)
and macOS screen capture handle it. Real HDR pass-through would need
10-bit capture, Main10/AV1-10 encoders in the hwcodec fork, colour
metadata on the wire and, decisively, an HDR output path on the
controller: Flutter's desktop external textures are BGRA8888/RGBA8888
only on every platform, so nothing would be visible. When that changes
it should follow the Sunshine/Moonlight pattern: an hdr capability bit
advertised by the controller behind an explicit user toggle, negotiated
like i444.

Type-checked against x86_64-pc-windows-msvc (with and without the vram
feature); not yet run on an HDR machine, which needs Windows 10 1703+
with HDR on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F
(cherry picked from commit ca3c2f8ac7d1549a40855411b0539a69c82d7223)

* scrap: stay on DXGI when the HDR conversion fails, load the compiler once

Review follow-up:

- A tone-map failure surfaced as a capture error, and the capture loop
  answers any DXGI error by switching the capturer to GDI for the rest
  of its life. The capturer now drops the tone-map, re-creates the
  duplication with the legacy DuplicateOutput (DXGI's clipped BGRA8,
  the pre-HDR behaviour) and returns WouldBlock, so the session stays
  on DXGI and simply fetches the next frame.

- Only failures that cannot succeed anywhere in the process (no
  d3dcompiler_47.dll, shaders that do not compile) set the global
  UNAVAILABLE flag; D3D object creation failures stay with the capturer
  that hit them, so another adapter or a recreated capturer tries again.

- D3DCompile is resolved once through a OnceLock instead of a
  LoadLibrary per capturer that was never freed.

- The module doc now states what this pass is: normalization of an HDR
  desktop to SDR, with everything above SDR white clipping, not a tone
  map, and why a roll-off is deliberately not applied. The earlier
  claim that clipping matches what the local user sees was wrong for
  HDR content on an HDR display.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: only apply the SDR white level to outputs DXGI reports as HDR

Review follow-up:

- An FP16 desktop is not necessarily HDR. Since Windows 11 22H2 an
  Advanced Color (WCG) SDR display is composed in FP16 scRGB too, and
  there 1.0 is the display's reference white, not 80 nits, so the
  SDRWhiteLevel scaling does not apply (Microsoft: "Reference white
  applies only to HDR displays"). Query IDXGIOutput6::GetDesc1 and treat
  the output as HDR only for DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020,
  the documented Win32 check; a non-HDR FP16 frame now gets just the
  scRGB -> sRGB transfer. Without IDXGIOutput6 (before Windows 10 1803)
  FP16 can only mean HDR.

- The SDR white level is now Option: a failed query or a reported 0 is
  "unknown" on both the initial and the refresh path, an HDR output with
  an unknown level logs a warning and keeps the 80-nit assumption until
  the periodic re-query succeeds. DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL
  needs Windows 10 1709, not 1703 as an earlier message said.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: re-read the Advanced Color state while capturing, gate FP16 on IDXGIOutput6

Review follow-up:

- The HDR/WCG decision was taken once when the conversion was created.
  HDR can be switched on or off, and a WCG desktop can turn into an HDR
  one, without the duplication being invalidated, so the choice between
  "divide by the SDR white level" and "no scaling" could go stale. The
  once-a-second refresh now re-reads it: it keeps an IDXGIFactory1,
  and when IsCurrent reports FALSE it creates a fresh factory and
  re-finds the output by GDI name, since a stale factory's outputs keep
  stale descriptions (this is the procedure the GetDesc1 docs require).
  On a change it switches modes, re-reads the white level and updates
  the shader constant; an unreadable level keeps the last known one.

- Float frames are only requested when IDXGIOutput6 exists, as
  Microsoft's duplication sample does. That interface is also what tells
  HDR from WCG, so there is no longer a state where FP16 is requested
  without being able to interpret it. IDXGIOutput6 dates from Windows 10
  1703, not 1803 as the previous commit said; 1803 added IDXGIFactory6.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: replace the DXGI factory and output together when re-reading HDR state

Review follow-up: when the fresh factory did not find the output by name,
the refresh kept the new, current factory next to the old output, and
because IsCurrent then reported TRUE it never enumerated again, so the
stale output could stay forever. enumerate_output6 now returns both or
neither, and the refresh only replaces the pair together; a null factory
forces another enumeration on the next refresh while the old output is
still read in the meantime. The constructor gets the same guarantee for
free, since a failed lookup leaves the factory null there too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: keep enumerate_output6's both-or-neither promise when IDXGIOutput6 is missing

Review nit: a matched output whose IDXGIOutput6 query fails returned the
fresh factory next to a null output, which let the constructor pair a
current factory with the capturer's fallback output. Return neither in
that case so the next refresh enumerates again.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RLb1dNdhFqUQExJPANjo1F

* scrap: log DuplicateOutput1 failures before fallback

Signed-off-by: 21pages <sunboeasy@gmail.com>

* scrap: avoid null duplication after HDR fallback failure

Signed-off-by: 21pages <sunboeasy@gmail.com>

* scrap: load the D3D compiler securely from System32

Signed-off-by: 21pages <sunboeasy@gmail.com>

* scrap: release the frame through the state machine when abandoning the tone-map

master's FrameState machine is left at Acquired by the raw ReleaseFrame(),
so the next release_frame() hits DXGI_ERROR_INVALID_CALL on the fresh
duplication and the capture loop falls back to GDI -- the outcome the
fallback exists to avoid.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: 21pages <sunboeasy@gmail.com>
2026-09-23 18:40:49 +08:00
Ricardo Simõesgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
a8ae0d6d66 Review and complete pt_PT.rs translation (European Portuguese) (#16311)
* Update pt_PT.rs

* Update pt_PT.rs

* Update src/lang/pt_PT.rs fiz misspelling of "Apenas"

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Fix config_screen: replace trailing slash with period

Per CodeRabbit's suggestion — the slash was rendered directly in the
permission prompt text, not as a line continuation, so it read as a
stray character instead of proper punctuation.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Fix terminal-clipboard-write-tip: translate full 3-sentence source text

Per Greptile's review — the previous translation for this key only
covered a short summary (matching an equally incomplete ptbr.rs entry),
not the full English source defined in en.rs, which explains the
permission's scope (persists across all connections until disabled in
Settings) and that manual copy/paste is unaffected. Translated from the
actual en.rs source text as required by AGENTS.md's localization
guidelines.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-09-23 17:31:06 +08:00
asereze 2e333f64a4 Update sc.rs (#16314)
* Update sc.rs

* Update sc.rs
2026-09-23 17:30:47 +08:00
RustDeskandClaude Opus 5.5 e424b57fca Kx v1 (#16326)
* key exchange version 1 on the rendezvous and peer handshakes

Bump hbb_common for key exchange version 1, one stream key per direction,
and negotiate it on both handshakes.

Rendezvous: `secure_tcp` reads the version the server advertises in
`KeyExchange.version`, answers with the highest both speak, splits the key
when that is at least 1, and arms the check of the server's echo on its first
encrypted message.

Peer: the controlled side advertises `KX_VERSION_LATEST` inside the signed
`IdPk`, the controller answers in `PublicKey.kx_version` and both split the
key when the pick is at least 1. A pick above what was offered is refused as
a bug or tampering. `decode_id_pk_dtls` returns the advertised version along
with the fingerprint.

An absent field on either side is version 0, so any old peer or server keeps
today's stream byte for byte.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* bump hbb_common: keep the advertisement check armed until an echo arrives

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* bump hbb_common: drop box_pk_of until something calls it

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* key exchange: say 0 on WebRTC, where no stream key applies

A WebRTC stream is encrypted by DTLS and `set_key_split` collapses to
`set_key` on it, which sets nothing but `peer_verified`. Both sides still
put 1 on the wire, the controlled peer in its signed identity and the
controller in its pick, and agreed on a version neither applied. That held
only because both fell into the same branch: the day one side splits keys
on WebRTC and the other does not, they would agree on 1, derive different
keys, and have no version mismatch to point at.

The controlled peer now advertises 0 on WebRTC and refuses a pick above
what it advertised rather than above the newest it speaks anywhere; the
controller picks 0 there. What is on the wire is what runs.

Also bumps hbb_common for the echo contract: the server tags every
message after the exchange, not the first alone, so dropping one frame at
a known position does not rid an attacker of the downgrade check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* key exchange: verify the server's signed version before trusting it

bump hbb_common d9f519e: KeyExchange.signed_version

A server that signs its version sets bit 255 of the ephemeral key inside
the signed keys[0]. A client that sees that bit, or the field itself,
verifies sign("rdkx-ver" || key || version LE) under the server's signing
key before picking a version and refuses the exchange otherwise, so a
version lowered in the clear is caught at the handshake rather than one
frame pair later by the echo. A legacy server sends canonical keys and no
field and takes the unchanged path; the echo still checks its version.

Tests: version 1 keys match the server both ways; an advertisement
lowered in transit is refused at the first echo; legacy, signed-1 and
signed-3 servers each exchange application data; nine tamperings of the
signed version are refused before the client replies.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: comments say what the fields and functions are

bump hbb_common e3452ac: the same on the shared side.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: drop the advertisement echo

bump hbb_common 5194159: RendezvousMessage.kx_advertised and the check on
decrypted frames are gone. signed_version settles the version inside the
exchange, so the client arms nothing after it; the stub in the tests
stops tagging its frames and the test of a lowered advertisement goes,
the signed-version cases covering that refusal before any reply.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: verify KxParams, the server's signed structure

bump hbb_common e74a188: KeyExchange.signed_params and KxParams.

The client parses the signed bytes as KxParams and compares its fields
to the key it verified and the version it was shown, rather than
matching a fixed byte string, so a field added to KxParams later parses
past an older client. The tamper cases now include a payload signed as
the old byte string.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: require the KxParams signing prefix before parsing

bump hbb_common 26582e1: KX_PARAMS_DOMAIN.

Without it a signed IdPk, which the server signs with the same key,
parsed as a KxParams whose pk was the id and whose version was 0, so an
id registered with the bytes of a marked ephemeral key could stand in
for the params at version 0. Two tamper cases pin this: params signed
without the prefix, and a signed IdPk in their place.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: one call sets the negotiated key

bump hbb_common cbc8772: Stream::set_negotiated_key.

The rendezvous client, the controller and the controlled side each
branched on the picked version to choose between split and single keys.
They now hand the transcript to Stream, which makes that choice once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* Update hbb_common: refuse unknown key exchange versions, pin wire vectors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* client: prove the peer handshake picks its version and encrypts under it

The rendezvous exchange had tests against a stub server; the peer
handshake had none, so a controller that fell back to version 0 would
still connect, still report secured, and pass every test. These run
Client::secure_connection against a stub controlled peer and check
the pick it sees and the application data both ways: new peers pick 1,
a peer without versions gets 0, and a pick lowered in transit leaves
the two sides unable to read each other.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* Update hbb_common: pin the subkeys for an advertisement above the pick

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* Update hbb_common to main, with #614 merged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

* key exchange: name the picked version, say why the marker bit is safe

Review follow-ups with no change in behaviour: the rendezvous pick is
called picked, as in the peer handshake and KxTranscript; the marker
comment says X25519 ignores the bit and the bytes stay as signed; the
controlled side's refusal names the version it offered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019aokqJuhjvB3kijXtAg5Ns

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 17:30:22 +08:00
21pages b30f781fd6 fix: restrict VRAM stall detection to AMD SDK (#16319) 2026-09-23 14:20:42 +08:00
RustDesk 68a35e65f2 fix(unix): ignore SIGPIPE in native Flutter entry (#16322)
* fix(linux): ignore SIGPIPE in Flutter runner

Initialize SIGPIPE before entering the Rust core so writes to closed IPC peers return EPIPE instead of terminating the server. Add a native-entry regression test for the failure reported in #16297.

* test(linux): remove SIGPIPE runner test

* fix(flutter): initialize SIGPIPE in the Rust native entry

Share SIGPIPE initialization between the Linux and macOS native runners before core startup. Remove the Linux C++ initialization.

* fix: share SIGPIPE initialization with Sciter startup

Initialize SIGPIPE before global_init in core_main, shared by Flutter and Sciter on Linux and macOS.

* fix(flutter): keep SIGPIPE setup in the native FFI entry

Sciter already receives SIGPIPE initialization from the Rust runtime. Scope the missing startup initialization to native Flutter runners on Linux and macOS.
2026-09-23 14:05:15 +08:00
Mariano Abad 7c21b4569c test(drm): bound the excused shapes at their worst angle, not only on average (#16320)
Both of the review follow-ups on rustdesk#16242.

One comment still said alias was 0.11 px worse than master. That was the
number before the directional rule; it is 0.51.

And the exemption for help and alias was bounded only on the average over the
angles master handles. The worst single angle is the larger number and the one
that would be felt - help is 8.00 px under master at 270 and 21.54 here - so
leaving it unbounded let the exemption widen quietly. Both directions are
bounded now, at the measured values: alias 0.51 mean and 8.94 at 90, help 4.73
mean and 13.54 at 270.

Tests only.
2026-09-23 10:39:10 +08:00
Ricardo Simões c6a358afbe Update lang.rs - Splits ambiguous pt into pt-pt and pt-br (#16155)
* Update lang.rs - Splits ambiguous pt into pt-pt and pt-br

Splits the ambiguous "Português" entry into two explicit options: Português (Portugal) [pt-pt] and Português (Brasil) [pt-br]. The pt_PT.rs translation file already existed in the repo (fully translated, key-complete) but was never wired into lang.rs. Kept the old "pt" and "br" locale codes mapped to ptbr::T for backward compatibility with existing user configs.

* Preserve pt-PT/pt-BR region in automatic locale resolution

Preserve pt-PT/pt-BR region in automatic locale resolution

* Fix pt-pt detection: check region suffix instead of redundant "pt" substring

Fix pt-pt detection: check region suffix instead of redundant "pt" substring

* Normalize legacy pt/br saved lang option to pt-br

Normalize legacy pt/br saved lang option to pt-br

* Normalize legacy pt/br lang option on Web client

* Add regression tests for pt-pt/pt-br locale resolution

* Follow CLDR inheritance for Portuguese regional locales (pt-AO, pt-MZ, etc.)
2026-09-22 16:31:23 +08:00
Dmytro 458ffe44c6 Update Ukrainian README (#16309)
* Start Ukrainian README terminology update

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Synchronize Ukrainian README with current documentation

Update content, terminology, build instructions, badges, and project structure to match the current English README.

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Polish Ukrainian README dependency wording

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

* Clarify Docker build argument placement

Address review feedback by explaining where optional build arguments should be appended to the docker run command.

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>

---------

Signed-off-by: Dmytro <dmitriy.gaponuk@gmail.com>
2026-09-22 16:12:11 +08:00
21pages 2e7255f083 fix: suppress heartbeat HTTP retry and TCP proxy logs (#16273)
* fix: suppress heartbeat HTTP retry and TCP proxy logs

Signed-off-by: 21pages <sunboeasy@gmail.com>

* refactor: move API log interval to common module

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-09-22 16:04:22 +08:00
fufesouandMariano Abad 12f61b1fda Fix/drm rotated cursor (#16242)
* fix(drm): turn the cursor by the output's real angle, and guess its hotspot upright

Two things were wrong with a rotated output's cursor, and the maintainer's
physical test found both.

The bare-metal hotspot is a guess - the top-left of the sprite's opaque box,
since HOTSPOT_X/Y only exist on para-virtualised drivers - and it was guessed on
the sprite as scanned out, then mapped as if it were a point on it. A turned
arrow's tip is never in that corner: at 90 the guess is off by the arrow's width
along x, small enough to pass as fine, and at 270 by its height along y, which
is what was noticed. Measured on an i915 box with a 64x64 Adwaita arrow, hotspot
against tip: +11,0 at 90 and 0,+18 at 270 before, 0,0 at every angle after. A
guessed hotspot is now guessed on the upright sprite, in the consumer, and the
wire says whether the driver measured it so a real one still maps as a point.

And 180 was clamped to 0 for the whole session because a hardware-rotated
primary plane scans out upright. That holds for the frame and not for the
cursor: the compositor pre-rotates the sprite in software either way, so it
arrived upside down. The frame keeps the clamp; the cursor gets the real angle.

(cherry picked from commit 6a73100b4783fbf9c8f43e0dc7651b7568db9ea9)

* test(drm): drive the cursor path, and drop the field nothing reads

The two tests called the helpers, so nothing pinned the production
decision: restore master's `t == 90 || t == 270` in deliver_drm_cursor
and both still pass while the 180 sprite goes back to upside down. The
new test drives deliver_drm_cursor and reads back what it published,
and it fails under exactly that mutation.

The other way to reintroduce the bug was to point the receive thread at
`Shared::transform` again. That field had no readers left once both
gates moved to `cursor_transform` - it was stored and never loaded - so
it is gone, and the doc above TRANSFORM_PENDING now names the field
that actually holds a racing cursor back.

Also four comments that said more than the code does: the sprite is
treated as pre-rotated at every angle because wl_output cannot say
otherwise, not because the compositor provably always does it; the old
flow was off at every angle, not just at one of 90/270; the 180
symptom had its own cause, the clamp, rather than all of it coming out
of the hotspot guess; and the test arrow's opaque box is its left three
columns, not the whole bitmap.

* docs(drm): say what the 180 measurement actually showed

The loop asserts the old mapping was wrong at 180 too, and that is true
of the mapping, but master never ran it there: the clamp sent 180 down
the untouched branch, so guess and sprite turned together and the
hotspot landed on the tip. The bench measured exactly that - (0,0) at
180, with only the sprite upside down. The comment said the old flow was
wrong at every angle without that distinction, which is the kind of gap
between a claim and a measurement worth closing before someone else
finds it.

* fix(drm): centre the guessed hotspot of an I-beam lying either way

The bounding-box guess only centred TALL shapes, so a HORIZONTAL I-beam was
handed the top-left corner of its box. Adwaita's `vertical-text` is exactly that
shape: at 24 px its opaque box is 20x9 and the theme's own hotspot is (12, 11),
its centre. The corner guess lands 11.2 px away; the centre lands 1.4 px away.

It matters more since this branch turns the sprite upright before guessing. Such
a cursor used to reach a quarter-turned output as a TALL bitmap, where the
tall-only rule centred it by accident; guessing on the upright bitmap - correct in
itself, and what fixes arrows at every angle - is what exposed the asymmetry.

Found by fufesou at pixel level on rustdesk#16242, and reproduced here against the
installed theme before changing anything: same declared hotspot, same bounding
box, same two errors. Then checked across ALL 35 shapes of that theme at 24 px:
making the aspect test symmetric moves exactly one of them, `vertical-text`, from
11.2 px to 1.4 px, and leaves the other 34 byte-identical.

The old flow is not the fix. It was right for this one shape and wrong for arrows
at every angle, which is what `a_guessed_hotspot_is_guessed_on_the_upright_sprite`
pins; the fix belongs in the guess, not in the order of operations.

The regression test that missed this used only `arrow()`, as fufesou pointed out.
Three things the first version of the replacement got wrong, all of them in what
it CLAIMED rather than in the fix:

- Its expected point was the centre of the BITMAP, which equals the centre of the
  opaque box only because the fixtures filled their bitmaps symmetrically. Both
  I-beam fixtures are now off-centre in their buffers, the way a sprite sits in a
  64x64 hardware cursor, and the test asserts up front that the two centres differ
  so the fixture cannot quietly stop discriminating.
- It called the arrow's box "elongated by less than the factor of two", when 3x6
  IS the factor of two and the arrow keeps its tip only because the comparison is
  strict. That makes the arrow the control for one side of the threshold, and it
  is now described as such.
- It said the case was driven "through the whole delivery path" while chaining the
  helpers itself. It now calls `deliver_drm_cursor` and reads the published
  hotspot back out of DRM_CURSOR, at 0, 90, 180 and 270, feeding it what the
  producer really sends for a guessed hotspot: the producer's own guess, made on
  the sprite as scanned out.

And the threshold was pinned from one side only. A third fixture carries the real
2.22:1 aspect of the shape that was wrong, so a stricter rule cannot pass on 6:1
bars while silently un-centring the actual cursor.

Mutations, each restored byte-for-byte afterwards: back to tall-only, the bitmap
centre instead of the box centre, the threshold loosened to one and tightened to
three. All four fail the test.

* build(drm): point the pin at the synced mirror and drop the helper fallback

The mirror is synced, so the pin moves from 5da68a3a (libdrmtap 0.5.4) to
49b204f (0.5.6), which is what rustdesk-org/libdrmtap now carries.

-Dhelper=disabled, as the maintainer asked on #16242. rustdesk never uses the
privileged helper: every drmtap_open lives in src/ipc/drm.rs, i.e. the root
service, which already holds CAP_SYS_ADMIN, and the unprivileged side opens a
render node instead. What the library carries without the option is a fallback
that walks six hardcoded paths, two of them under /usr/local, and execs the
first one that passes access(X_OK) -- no check of its owner, no check of its
mode -- from inside the ROOT process. The option compiles that path out.

Asserted on the artifact as well as passed as a flag, for the same reason the
EGL check is: a flag cannot notice a stale build-pkg or an object substituted
by hand, and meson accepts an unknown -D silently on versions predating the
option. Measured on the produced .so: socketpair 4 -> 0, the helper search
paths 3 -> 0, and nm -D shows no fork, execl or socketpair import. The check
fails as it should when pointed at a .so built with the helper.

* fix(drm): use the library's hotspot provenance, and keep legacy IPC meaning

Answers the two blockers in the maintainer's review of 9acb37a9d, plus the
three he marked should-fix.

hot_measured no longer guesses. The pinned libdrmtap 0.5.6 exports
drmtap_cursor_hotspot_valid, and the old test -- hot_x != 0 || hot_y != 0 --
cannot separate the two things a (0, 0) hotspot means: no HOTSPOT_X/Y on the
plane, or a driver whose answer really is the corner. The symbol is resolved
OPTIONALLY, the way drmtap_render_node and drmtap_list_devices already are,
with the same version-aware warning when a library that reports 0.5.6 or newer
does not carry it. An older deployed .so keeps the previous behaviour instead
of the ABI floor moving under it and refusing to load.

The IPC default is corrected. Data is JSON over a unix socket between two
processes upgraded separately, so an old root service can be streaming to a
freshly started --server and its DrmCursor has no hot_measured at all. Read as
bool::default() the new consumer discards a hotspot the producer measured and
re-infers one from the upright bitmap, moving the cursor on a rotated display
for the length of the upgrade. The default is now true, which is not a claim
that the value was measured: it means "no provenance available, so behave as
the old protocol did". A new producer that wants re-inference sends false
explicitly, which serializes, so new-to-new is unchanged.

hot_measured is folded into the cursor id. It is not metadata about the cursor,
it selects what the consumer does with it, so a sample whose pixels and (0, 0)
hotspot are unchanged but whose provenance flipped is a different cursor and
must not be deduped away by the producer.

build.py reconfigures an existing meson build dir with -Dhelper=disabled
instead of only configuring a fresh one; a directory from before the option
kept its old configuration and the artifact assertion then failed the build.

And the drm CI job now runs the drm-gated tests. It built the feature without
ever executing them, so every cursor rotation and hotspot test had no
continuous coverage. A cargo test filter that matches nothing exits 0, so the
step also asserts it actually ran some.

Verified by mutation, each caught by its own test and no other: ignoring the
library's answer fails the two provenance tests; the serde default back to
false fails the legacy-deserialization test; dropping hot_measured from the id
fails the identity test.

* feat(drm): say once where the cursor hotspot came from

The provenance decision was unverifiable anywhere but a unit test: nothing on
a running box distinguishes the three states, so a deploy proved nothing. One
info line does, and with it all three are measured -- Some(false) on i915,
None with a 0.5.4 library swapped in behind the soname, and Some(true) via a
C probe on virtio-gpu, where no rustdesk build runs.

Once per state, not once per sample. A cursor is read on every capture
iteration and its provenance changes approximately never; a per-frame log line
here is the same defect libdrmtap already shipped once. Measured on Sigma-26:
one line across a whole session. The should-we-log decision is its own
function so it cannot quietly become per-sample again.

* test(drm): drive a legacy cursor message from the wire, not from a literal

The upgrade window is the one thing in this round that could not be staged
with two live processes: a --server from one build does not run inside the
other's tree, so the old service respawns it and it dies with exit 127. Tried
on two boxes, with two files swapped and with the whole tree.

This is the honest form of that test and it runs in CI rather than once on a
desk. It takes the exact bytes an old producer puts on the socket -- no
hot_measured key at all, adjacently tagged as Data really is -- deserializes
them the way the receive loop does, drives the real delivery path, and reads
back what was published. The transform is non-zero on purpose: at 0 the path
never consults hot_measured, so a test there could not tell the branches
apart, and the fixture is asserted to make mapping and re-inferring disagree
before anything is concluded from them.

Verified by mutation: restoring #[serde(default)] -- the reported bug -- fails
it, and so does a delivery path that ignores hot_measured.

* fix(drm): run the tests that matter in ci, and keep provenance state per stream

Answers the review of 7dc6817 plus the CI failure fufesou reported on 401c2f7.

The drm test step was broken three ways and none of them showed up as a red
test: it reused the production $FEATURES, so the test binary failed to LINK
(undefined reference to fcntl64 from hwcodec) and the tests never ran; it
summed the counts with bc, which the ubuntu18.04 container does not install;
and `cargo test --lib` at the repo root builds the ROOT package only, so the
provenance tests in libs/scrap were never selected -- the "at least one test
ran" guard passed on the root filters and hid it. Now: --features drm rather
than the production set, awk instead of bc, and an explicit `-p scrap` run
with the same assertion. Locally 36, 9 and 5 tests, and a bogus filter still
fails the step.

Provenance logging state was process-global on both sides. DRM runs one
reader per captured display, and two outputs with different but STABLE
provenance -- one publishing HOTSPOT_X/Y and one not, which is an ordinary
multi-GPU host -- would overwrite each other and make every message look like
a change, i.e. exactly the per-frame logging the one-shot was written to
avoid. The producer's state moves into DrmReader, the consumer's is keyed by
display. The hidden-cursor sentinel is no longer recorded: it carries
hot_measured=false because it has no hotspot, so counting it turned every
hide and show into a provenance transition.

The 180 test is renamed to say what it pins -- i915 advertising rotate-180
with mutter -- and its comment says plainly that it is not a general contract,
that Plasma is still wrong there, and that changing it means re-measuring.

Verified by mutation: restoring the global slot fails the new per-display
test, and so does recording the hidden sentinel.

* fix(drm): centre the guessed hotspot on the axes a cursor mirrors about

The guess put the click point at the top-left corner of the opaque box unless
the box was more than twice as long as it is wide. That corner is where an
arrow's tip is, because cursors are drawn pointing up and to the left, but a
shape that mirrors onto itself has no tip to point with: a crosshair, a
two-headed resize arrow, a cell marker. Those got a corner where the theme puts
the middle, and the error is about half the glyph.

So: centre the axis the shape is symmetric about, and keep the corner
everywhere else. Measured against the hotspots the theme declares, which is the
value a compositor programs into HOTSPOT_X/Y where the property exists:

  adwaita-icon-theme 50, 35 shapes at six nominal sizes, 210 cases
    mean error 0.43 -> 0.27 of the cursor size, 17 shapes improve, none worse
  adwaita-icon-theme 46, 34 shapes at five sizes, 170 more cases
    better at every size, none worse

The threshold is not fitted: from 90 to 98 percent agreement nothing regresses,
and below 90 three shapes do.

The corpus is carried as fixtures so the expected value comes from the theme
author rather than from our own heuristic, and two tests read it: the published
hotspot must not move when the output turns, with the old flow's 15 px average
movement as the control, and the guess must stay inside the measured bounds
with the old rule frozen as the baseline.

The elongation test stays ahead of the mirror test so an elongated shape that
is not symmetric still keeps its centre.

* fix(drm): put a directional cursor's hotspot on the edge it resizes

The mirror rule centred the axes a shape is symmetric about and left the
other axis on the top-left corner. That is right for an arrow, whose tip is
that corner, and wrong for the resize cursors: those are a pointer plus the
marker of the edge being resized, the theme puts the click point on the
marker, and the marker is at whichever end the cursor names. Always taking
the corner therefore had to be wrong for one of every mirrored pair, since
e-resize and w-resize are the same picture reflected.

So an axis is read as directional when the perpendicular axis mirrors, which
is the n/e/s/w family, or when the shape mirrors about a diagonal, which is
the corner family. A directional axis takes the heavier end.

A diagonal reflection only lines up inside a square, and these boxes are not
square, so where the box sits in that square decides the answer: ne-resize
scores 0.62 anchored one way and 0.98 the other, and nw-resize is the reverse.
Both anchorings are tried and the better answer wins.

Measured against MASTER now, not against this PR's previous revision, which
is what the maintainer asked for. Over the angles master handles (0, 90, 270),
adwaita-icon-theme 50 at 24 px:

  mean error per shape   12.08 px -> 4.20
  (shape, angle) cases   83 better, 18 the same, 4 worse of 105
  shapes worse than master   help (+4.73) and alias (+0.51)

Both of those are semantic: the theme puts help's click point on the dot of
its question mark. The same holds at 48 px and on adwaita-icon-theme 46,
where ne-resize is also 1.34 px worse because its glyph is drawn differently
there.

The test baseline was wrong and is fixed here: it froze this PR's earlier
symmetric aspect test rather than master's tall-only one, so it could only
show that the new rule does not regress the old rule. It now freezes master's
guess AND master's delivery, and names the two shapes it excuses with the
measured size of each.

The mirror threshold moves from 95 to 88, the middle of the 86 to 91 interval
that regresses nothing on either theme version.

---------

Co-authored-by: Mariano Abad <weimaraner@gmail.com>
2026-09-22 15:18:10 +08:00
rustdesk 6a0eb9a1fd fix(terminal): preserve trackpad scrolling in alternate screen
Prevent the inner terminal scrollable from accepting user scrolling in the alternate buffer, so xterm's existing outer handler receives trackpad gestures after main-screen history.

Keep wheel encoding and drag reporting unchanged. Cover trackpad forwarding, subsequent drag coordinates, arrow fallback, and return to local scrollback.
2026-09-22 11:45:05 +08:00
rustdeskandClaude Fable 5.1 763d4eeb05 bump hbb_common: tungstenite 0.29 forks, read buffer grown as bytes arrive
hbb_common 7dc56d6..d9895ff, one commit: tokio-tungstenite and tungstenite
up from 0.26 to rustdesk-org's rustdesk-patches-0.29 branches. The
tungstenite fork grows the read buffer a read_buffer_size chunk at a time
as bytes arrive, where upstream reserved the whole length a frame header
declared. It is pinned here at the workspace root, the one place cargo
reads [patch], so hbb_common's copy and tokio-tungstenite's resolve to
the same one. The lockfile moves only those two crates and drops utf-8,
which 0.29 no longer pulls.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab
2026-09-21 17:58:35 +08:00
fufesou a5d4ef97e8 fix(ws): reject text frames after encryption is enabled (#16295)
Signed-off-by: fufesou <linlong1266@gmail.com>
2026-09-20 18:21:15 +08:00
RustDeskandClaude Fable 5.1 dd9b21cf86 server: hold an unauthenticated connection to a small message (#16254)
* server: hold an unauthenticated connection to a small message

Until a peer authorizes it sends only a public key, a login request, a test delay
and a close reason, none of them large. Nothing said so: a frame header could
declare up to whatever the transport allowed, 1 GiB on TCP and WebRTC, and a
connection holds its place for up to LOGIN_GRACE before it has to authorize. With
MAX_UNAUTHORIZED_CONNS places to fill, that is 64 GiB of header-declared payload
one peer could make us hold - or, on WebSocket, 1 GiB bought outright with a few
hundred bytes of frame headers, because tungstenite reserves a frame's declared
payload as soon as it passes max_frame_size.

The cap goes on in create_tcp_connection, before the identity handshake, so that
read is bounded too, and comes off once the login is settled. It comes off before
connect_port_forward_if_needed rather than beside the rest of authorization: a
multiplexed tunnel narrows the same knob again for its own framing and has to have
the last word.

128 KiB is several times the largest login request anyone sends - a long hostname,
an os_login, an avatar URL, a file-transfer path - and is also the read buffer
tungstenite allocates per WebSocket connection whatever we do, so on that transport
the bound costs nothing beyond a floor already paid. A server hands that avatar
out as a URL; only a custom client that inlines an image into the avatar option
instead can reach the bound at all. Together with
MAX_UNAUTHORIZED_CONNS it holds every unauthorized connection to 8 MiB. Redis
answered this same shape in CVE-2021-32675 with 16 KiB, tighter because a
per-message bound is the only one it has; here the connection count is the other.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* server: test that the unauthenticated cap is on before the handshake reads

hbb_common covers each transport's cap; nothing covered where the connection
layer puts it. A header one byte over MAX_UNAUTHORIZED_MESSAGE, written to a
connection stalled in the identity handshake, has to end the handshake on the
header alone and release the connection's place: the test fails with the cap
moved past the handshake or dropped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* client: hold the clipboard until this round's login is accepted

The clipboard listener is one per process, started by the first session to
log in, and its broadcast went to every session - one whose login was still
waiting on a password, 2FA or the peer's consent included. What the user
copied meanwhile went to a machine that had not admitted them; the peer
drops it unread before authorization, but it is in that peer's hands.

The check goes on the round, not the session: a session-level one reads a
state and later a sender that a reconnect can have swapped in between, so a
broadcast that passed for the round before could still queue on the next.
Remote is the round - its queue, and is_connected set once its own PeerInfo
is in - so a Clipboard or MultiClipboards that reaches handle_msg_from_ui
before then is dropped there, on the line before it would go out. What the
login itself sends through the same queue, Auth2FA among it, goes as before.

The unauthenticated cap on the other side is how this came up: a clipboard
over 128 KiB ended such a login with "Reset by the peer". The small case had
always gone through quietly.

A test drives a round's Remote over a loopback pair before any login: a
clipboard does not reach the far end, a 2FA code does, and once the round is
connected the clipboard does too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 14:26:42 +08:00
269 changed files with 23799 additions and 8820 deletions
+1 -1
View File
@@ -234,7 +234,7 @@ jobs:
CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}"
;;
*)
CARGO_TEST_OPTIONS="--workspace --no-fail-fast -- --skip test_get_cursor_pos --skip test_get_key_state"
CARGO_TEST_OPTIONS="--workspace --no-fail-fast"
;;
esac;
+347 -9
View File
@@ -9,6 +9,9 @@ on:
upload-tag:
type: string
default: "nightly"
publish-update-metadata:
type: boolean
default: false
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
# variables from this workflow!
@@ -45,16 +48,54 @@ env:
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VCPKG_CMAKE_VERSION: "4.3.0"
ARMV7_VCPKG_COMMIT_ID: "6f29f12e82a8293156836ad81cc9bf5af41fe836" # 2025.01.13, got "/opt/artifacts/vcpkg/vcpkg: No such file or directory" with latest version
VERSION: "1.5.0"
VERSION: "1.5.1"
NDK_VERSION: "r28c"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
PUBLISH_UPDATE_METADATA: "${{ inputs.publish-update-metadata }}"
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
jobs:
validate-update-metadata-keys:
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- name: Checkout source code
if: ${{ inputs.publish-update-metadata }}
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
if: ${{ inputs.publish-update-metadata }}
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
if: ${{ inputs.publish-update-metadata }}
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Test update metadata signer
if: ${{ inputs.publish-update-metadata }}
run: |
python -m unittest \
res/update/test_generate_update_metadata.py \
res/update/test_update_metadata_cli.py \
res/update/test_macos_update_scripts.py
- name: Validate update metadata keys
if: ${{ inputs.publish-update-metadata }}
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: python res/update/generate_update_metadata.py check-key
generate-sbom:
needs: [validate-update-metadata-keys]
runs-on: ubuntu-latest
permissions:
@@ -83,9 +124,11 @@ jobs:
rustdesk.sbom.json
generate-bridge:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/bridge.yml
build-RustDeskTempTopMostWindow:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
strategy:
fail-fast: false
@@ -323,6 +366,17 @@ jobs:
Write-Host "Ingore the printer driver error."
}
- name: Run the Rust tests
# x86_64 only: the tests are the same code on arm64, and that runner is the slow one.
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'x86_64' }}
shell: bash
run: |
# The build's own features, so the tests see the code that ships.
FEATURES=$(python3 ./build.py --portable --flutter --skip-portable-pack --hwcodec ${{ matrix.job.build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Its Windows tests run nowhere else.
cargo test --locked --release -p clipboard
- name: find Runner.res
# Windows: find Runner.res (compiled from ./flutter/windows/runner/Runner.rc), copy to ./Runner.res
# Runner.rc does not contain actual version, but Runner.res does
@@ -360,6 +414,18 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./rustdesk/
- name: Verify Windows Flutter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\rustdesk\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
if: env.UPLOAD_ARTIFACT == 'true'
@@ -450,9 +516,25 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput
- name: Upload signed Windows Flutter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.exe
if-no-files-found: error
- name: Upload signed Windows Flutter MSI
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-msi
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.msi
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -463,6 +545,7 @@ jobs:
# The fallback for the flutter version, we use Sciter for 32bit Windows.
build-for-windows-sciter:
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.os }}
# Temporarily disable this action due to additional test is needed.
# if: false
@@ -595,6 +678,18 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./Release/
- name: Verify Windows Sciter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\Release\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
run: |
@@ -612,9 +707,17 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput/
- name: Upload signed Windows Sciter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-sciter-x86-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}-sciter.exe
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -755,6 +858,7 @@ jobs:
target: x86_64-apple-darwin,
os: macos-15-intel, #macos-latest or macos-14 use M1 now, https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#:~:text=14%20GB-,macos%2Dlatest%20or%20macos%2D14,-The%20macos%2Dlatestlabel
extra-build-args: "",
extra-cargo-features: "",
arch: x86_64,
vcpkg-triplet: x64-osx,
}
@@ -763,6 +867,7 @@ jobs:
os: macos-14,
# extra-build-args: "--disable-flutter-texture-render", # disable this for mac, because we see a lot of users reporting flickering both on arm and x64, and we can not confirm if texture rendering has better performance if htere is no vram, https://github.com/rustdesk/rustdesk/issues/6296
extra-build-args: "--screencapturekit",
extra-cargo-features: ",screencapturekit",
arch: aarch64,
vcpkg-triplet: arm64-osx,
}
@@ -871,10 +976,10 @@ jobs:
name: bridge-artifact
path: ./
- name: Test cursor sizing
- name: Run the Dart tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
working-directory: flutter
run: flutter test --timeout 60s test/cursor_size_test.dart
run: flutter test --timeout 60s
- name: Setup vcpkg with Github Actions binary cache
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
@@ -916,9 +1021,28 @@ jobs:
sed -i -e "s/platform :osx, '.*'/platform :osx, '${MIN_MACOS_VERSION}'/" flutter/macos/Podfile
sed -i -e "s/osx_minimum_system_version = \"[0-9]*.[0-9]*\"/osx_minimum_system_version = \"${MIN_MACOS_VERSION}\"/" Cargo.toml
sed -i -e "s/MACOSX_DEPLOYMENT_TARGET = [0-9]*.[0-9]*;/MACOSX_DEPLOYMENT_TARGET = ${MIN_MACOS_VERSION};/" flutter/macos/Runner.xcodeproj/project.pbxproj
echo "MACOSX_DEPLOYMENT_TARGET=${MIN_MACOS_VERSION}" >> "$GITHUB_ENV"
fi
./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }}
- name: Test verified updates
if: env.PUBLISH_UPDATE_METADATA == 'true'
run: |
python3 -m unittest res/update/test_macos_update_scripts.py
cargo test --locked --release --lib platform::macos::update_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib verified_dmg_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib update_metadata::tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
- name: Run the Rust tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
run: |
# The build's own features, so the tests see the code that ships. MACOSX_DEPLOYMENT_TARGET
# comes from the build step's export.
FEATURES=$(./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Opt-in, and its macOS tests run nowhere else.
cargo test --locked --release -p clipboard --features unix-file-copy-paste
- name: create unsigned dmg
if: env.UPLOAD_ARTIFACT == 'true'
run: |
@@ -951,6 +1075,13 @@ jobs:
./flutter/build/macos/Build/Products/Release/RustDesk.app \
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
./flutter/macos/Runner/Release.entitlements
if [ "$PUBLISH_UPDATE_METADATA" = "true" ]; then
reported_version="$(./flutter/build/macos/Build/Products/Release/RustDesk.app/Contents/MacOS/RustDesk --version)"
if [ "$reported_version" != "$VERSION" ]; then
echo "::error::RustDesk reports version '$reported_version', expected '$VERSION'"
exit 1
fi
fi
create-dmg --icon "RustDesk.app" 200 190 --hide-extension "RustDesk.app" --window-size 800 400 --app-drop-link 600 185 rustdesk-${{ env.VERSION }}.dmg ./flutter/build/macos/Build/Products/Release/RustDesk.app
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict rustdesk-${{ env.VERSION }}.dmg -vvv
# notarize the rustdesk-${{ env.VERSION }}.dmg
@@ -958,13 +1089,26 @@ jobs:
- name: Rename rustdesk
if: env.UPLOAD_ARTIFACT == 'true'
shell: bash
env:
VERSION: ${{ env.VERSION }}
ARCH: ${{ matrix.job.arch }}
run: |
for name in rustdesk*??.dmg; do
mv "$name" "${name%%.dmg}-${{ matrix.job.arch }}.dmg"
done
if [ -f "rustdesk-${VERSION}.dmg" ]; then
mv "rustdesk-${VERSION}.dmg" "rustdesk-${VERSION}-${ARCH}.dmg"
fi
test -f "rustdesk-${VERSION}-${ARCH}.dmg"
- name: Upload signed macOS DMG
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.MACOS_P12_BASE64 != null
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: macos-${{ matrix.job.arch }}-dmg
path: ./rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.dmg
if-no-files-found: error
- name: Publish DMG package
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
@@ -972,6 +1116,141 @@ jobs:
files: |
rustdesk*-${{ matrix.job.arch }}.dmg
publish-signed-update-metadata:
needs: [build-for-windows-flutter, build-for-windows-sciter, build-for-macOS]
runs-on: ubuntu-22.04
if: ${{ inputs.upload-artifact && inputs.publish-update-metadata && github.repository == 'rustdesk/rustdesk' }}
concurrency:
group: signed-update-${{ inputs.upload-tag }}
cancel-in-progress: false
permissions:
# Required to inspect and publish signed release assets for the target tag.
contents: write
steps:
- name: Refuse to replace published update metadata
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TAG_NAME: ${{ env.TAG_NAME }}
run: |
set -euo pipefail
releases="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases?per_page=100")"
release_id="$(
jq -r --arg tag "$TAG_NAME" '
[.[][] | select(.tag_name == $tag)] |
if length == 0 then ""
elif length == 1 then .[0].id
else error("multiple releases found for tag")
end
' <<<"$releases"
)"
if [ -z "$release_id" ]; then
exit 0
fi
assets="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases/${release_id}/assets?per_page=100")"
if jq -e 'any(.[][]; .name == "rustdesk-update.json")' <<<"$assets" >/dev/null; then
echo "::error::Signed update metadata is already published for ${TAG_NAME}; use a new release tag for corrected artifacts."
exit 1
fi
- name: Checkout source code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Download Windows artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: windows-*
path: ./artifacts/
merge-multiple: true
- name: Download macOS artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: macos-*
path: ./artifacts/
merge-multiple: true
- name: Sign update metadata
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
run: |
python res/update/generate_update_metadata.py sign \
--artifact windows x86_64 exe "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact windows x86_64 msi "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact windows aarch64 exe "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact windows aarch64 msi "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact windows x86 exe "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact macos aarch64 dmg "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact macos x86_64 dmg "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download \
--published-at "$(git log -1 --format=%cI)" \
--metadata-out ./rustdesk-update.json \
--signature-out ./rustdesk-update.json.sig
- name: Verify update metadata
env:
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: |
python res/update/generate_update_metadata.py verify \
--metadata ./rustdesk-update.json \
--signature ./rustdesk-update.json.sig \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download
- name: Upload signed update artifacts
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: |
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.exe
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.msi
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.msi
./artifacts/rustdesk-${{ env.VERSION }}-x86-sciter.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.dmg
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.dmg
# The release action replaces same-name assets, so keep published sidecars
# until replacements are ready.
- name: Upload signed update metadata signature
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json.sig
# Clients discover the release through metadata, so publish it only after every referenced asset.
- name: Publish signed update metadata
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json
publish_unsigned:
needs:
- build-for-macOS
@@ -2046,6 +2325,61 @@ 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
@@ -2126,6 +2460,7 @@ jobs:
build-rustdesk-linux-sciter:
if: ${{ inputs.upload-artifact }}
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.on }}
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
strategy:
@@ -2406,7 +2741,9 @@ jobs:
sudo pip3 install git+https://github.com/rustdesk-org/appimage-builder.git
# run appimage-builder
pushd appimage
./build-apprun.sh ${{ matrix.job.arch }}
sudo appimage-builder --skip-tests --recipe ./AppImageBuilder-${{ matrix.job.arch }}.yml
cmp AppDir/AppRun appimage-build/AppRun/v2.0.0/AppRun-Release-${{ matrix.job.arch }}
- name: Publish appimage package
if: env.UPLOAD_ARTIFACT == 'true'
@@ -2504,6 +2841,7 @@ jobs:
build-rustdesk-web:
if: False
needs: [validate-update-metadata-keys]
name: build-rustdesk-web
runs-on: ubuntu-22.04
permissions:
+2 -1
View File
@@ -15,4 +15,5 @@ jobs:
secrets: inherit
with:
upload-artifact: true
upload-tag: ${{ github.ref_name }}
upload-tag: ${{ github.ref_name }}
publish-update-metadata: ${{ github.repository == 'rustdesk/rustdesk' }}
+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.0"
VERSION: "1.5.1"
NDK_VERSION: "r26d"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
+2
View File
@@ -58,3 +58,5 @@ 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,6 +48,20 @@ workspace member. `base::config::keys` re-exports the handful of keys
* Do not add dependencies unless needed.
* Keep code simple and idiomatic.
### Logging
* `debug` and above are written to the log file. A log call that can fire
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
peer controls) must not use `debug` or higher unthrottled.
* For such a site, pick one:
* `log::trace!` when the event is expected and the line only helps while
actively debugging;
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
that should still show up in a user's log. It keeps one line per interval
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
directly only when the decision drives more than one log call.
## Tokio Rules
* Assume a Tokio runtime already exists.
@@ -59,6 +73,30 @@ 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.
@@ -127,12 +165,40 @@ 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
+27 -33
View File
@@ -1305,7 +1305,7 @@ dependencies = [
[[package]]
name = "clipboard-master"
version = "4.0.0-beta.6"
source = "git+https://github.com/rustdesk-org/clipboard-master#7762d74e38db37cfeb6ded88c964b9cdbddfb6db"
source = "git+https://github.com/rustdesk-org/clipboard-master#522fafb65edfe7939cf63fa797f916569ecab595"
dependencies = [
"objc",
"objc-foundation",
@@ -4163,16 +4163,6 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "iri-string"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
dependencies = [
"memchr",
"serde 1.0.228",
]
[[package]]
name = "is-terminal"
version = "0.4.16"
@@ -6772,7 +6762,7 @@ dependencies = [
[[package]]
name = "rdev"
version = "0.5.0-2"
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
dependencies = [
"cocoa 0.24.1",
"core-foundation 0.9.4",
@@ -6901,11 +6891,10 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.12.24"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"async-compression",
"base64 0.22.1",
"bytes",
"futures-channel",
@@ -6934,7 +6923,6 @@ dependencies = [
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
@@ -7087,7 +7075,7 @@ dependencies = [
[[package]]
name = "rustdesk"
version = "1.5.0"
version = "1.5.1"
dependencies = [
"android-wakelock",
"android_logger",
@@ -7187,6 +7175,7 @@ dependencies = [
"uuid",
"virtual_display",
"wallpaper",
"wayland-client",
"winapi 0.3.9",
"windows 0.61.1",
"windows-service",
@@ -7196,12 +7185,14 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xkbcommon-dl",
"xxhash-rust",
"zstd",
]
[[package]]
name = "rustdesk-portable-packer"
version = "1.5.0"
version = "1.5.1"
dependencies = [
"brotli",
"dirs 5.0.1",
@@ -8609,8 +8600,8 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
version = "0.26.2"
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=9c320de8e7c546cb654b017b7f4cbb4a5cc09cd9#9c320de8e7c546cb654b017b7f4cbb4a5cc09cd9"
version = "0.29.0"
source = "git+https://github.com/rustdesk-org/tokio-tungstenite?rev=c241b11b03de4881faf1ecd2fe6e867c92f3013b#c241b11b03de4881faf1ecd2fe6e867c92f3013b"
dependencies = [
"futures-util",
"log",
@@ -8743,20 +8734,25 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.6"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"async-compression",
"bitflags 2.9.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"iri-string",
"http-body-util",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
@@ -8893,9 +8889,8 @@ dependencies = [
[[package]]
name = "tungstenite"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
version = "0.29.0"
source = "git+https://github.com/rustdesk-org/tungstenite-rs?rev=efce47e5364f00a63302cf07ab1fb13ded478914#efce47e5364f00a63302cf07ab1fb13ded478914"
dependencies = [
"bytes",
"data-encoding",
@@ -8909,7 +8904,6 @@ dependencies = [
"rustls-pki-types",
"sha1",
"thiserror 2.0.17",
"utf-8",
"webpki-roots 0.26.11",
]
@@ -9139,12 +9133,6 @@ dependencies = [
"log",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf16string"
version = "0.2.0"
@@ -10814,6 +10802,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]]
name = "xxhash-rust"
version = "0.8.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
[[package]]
name = "yasna"
version = "0.5.2"
+10 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk"
version = "1.5.0"
version = "1.5.1"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2021"
build= "build.rs"
@@ -63,6 +63,7 @@ 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 }
@@ -201,6 +202,8 @@ gtk = "0.18"
termios = "0.3"
terminfo = "0.8"
winit = "0.30"
wayland-client = "0.31"
xkbcommon-dl = { version = "0.4", features = ["x11"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
@@ -218,6 +221,11 @@ 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;
@@ -265,7 +273,7 @@ os-version = "0.2"
[dev-dependencies]
hound = "3.5"
docopt = "1.1"
tokio = { version = "1.44", features = ["test-util"] }
tokio = "1.44"
[package.metadata.bundle]
name = "RustDesk"
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.0
version: 1.5.1
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.0
version: 1.5.1
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+55
View File
@@ -0,0 +1,55 @@
--- a/src/common/shell_utils.c
+++ b/src/common/shell_utils.c
@@ -201,7 +201,8 @@
const char *begin = str;
const char *end = str;
- char buffer[1024] = {0x0};
+ size_t buffer_size = strlen(str) + 1;
+ char *buffer = calloc(buffer_size, sizeof(char));
while (*begin != '\0') {
begin = apprun_string_consume_spaces(begin);
@@ -209,7 +210,7 @@
if (*begin == '\\') {
strncat(buffer, begin + 1, 1);
- end = begin + 2;
+ end = begin[1] != '\0' ? begin + 2 : begin + 1;
consumed = true;
}
@@ -218,7 +219,8 @@
strncat(buffer, begin + 1, end - begin - 1);
consumed = true;
- end++;
+ if (*end != '\0')
+ end++;
}
if (!consumed && *begin == '\"') {
@@ -226,7 +228,8 @@
strncat(buffer, begin + 1, end - begin - 1);
consumed = true;
- end++;
+ if (*end != '\0')
+ end++;
}
if (!consumed && *begin != '\'' && *begin != '\"' && *begin != '\\') {
@@ -240,11 +243,12 @@
split_count++;
}
- memset(buffer, 0, 1024);
+ buffer[0] = '\0';
}
begin = end;
}
+ free(buffer);
return splits;
}
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# AppRun v2.0.0, which appimage-builder downloads, splits every argument into a 1 KiB stack
# buffer, so any argument of 1024 bytes or more aborts the AppImage before RustDesk starts.
# Build it with apprun-split-arguments.patch into the path appimage-builder checks before
# downloading. ubuntu:16.04 is what upstream released from, so the host glibc floor is unchanged.
set -euo pipefail
arch=$1
version=v2.0.0
commit=407700ccef58e1a64cc49856074aee4b1c75d599
sha256=05729f2ae0a744369d2d19d0f37acfbdcb1ee064172955b7576883ccef5113b3
image=ubuntu:16.04@sha256:1f1a2d56de1d604801a9671f301190704c25d604a416f59e03c04f5c6ffee0d6
here=$(cd "$(dirname "$0")" && pwd)
case $arch in
x86_64) packages="cmake make g++" ;;
aarch64) packages="cmake make g++ g++-aarch64-linux-gnu" ;;
*) echo "Unsupported arch: $arch" >&2; exit 1 ;;
esac
tmp=$(mktemp -d)
src=$tmp/src
curl -fsSL -o "$tmp/apprun.tar.gz" "https://github.com/AppImageCrafters/AppRun/archive/$commit.tar.gz"
echo "$sha256 $tmp/apprun.tar.gz" | sha256sum -c -
mkdir "$src"
tar -xzf "$tmp/apprun.tar.gz" -C "$src" --strip-components=1
patch -d "$src" -p1 < "$here/apprun-split-arguments.patch"
docker run --rm -v "$src:/src" -w /src -e DEBIAN_FRONTEND=noninteractive "$image" bash -c "
set -e
apt-get update
apt-get install -y --no-install-recommends $packages
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=../cmake/$arch-toolchain.cmake
cmake --build . --target AppRun"
mkdir -p "$here/appimage-build/AppRun/$version"
cp "$src/build/src/apprun/AppRun" "$here/appimage-build/AppRun/$version/AppRun-Release-$arch"
+45 -5
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.4.
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.12.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
LIBDRMTAP_SHA_PINNED = '5936a7a88b94aa43516a3dd0eb509d2383f31e2d'
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
LIBDRMTAP_SHA = os.environ.get('DRMTAP_SHA', LIBDRMTAP_SHA_PINNED)
# Every way of getting a different .so than the pin needs the same explicit opt-in. Otherwise the
@@ -489,8 +489,10 @@ def build_libdrmtap_so():
# override of the three -- no fetch, no sha verification, an object built by something this
# script cannot see -- so it is the likeliest to hand over a CPU-only build, and skipping the
# assertion on exactly this path would leave the check guarding only the case that was
# already trustworthy.
# already trustworthy. The helper check rides along for the same reason, and it matters
# more here than anywhere: this is the branch the packaging workflow takes.
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
return so
# Fetch the pinned source if it is not already present. third_party/libdrmtap is not a submodule
# anymore; it is git-ignored. The commit is fetched BY SHA rather than by cloning a branch:
@@ -521,8 +523,22 @@ def build_libdrmtap_so():
f'libdrmtap at {src} is {got_sha}, expected {LIBDRMTAP_SHA} '
f'(stale checkout from a different pin; removed, re-run to re-fetch)')
build_dir = os.path.join(src, 'build-pkg')
# Configure a fresh dir, or RE-configure one an earlier build left behind. Without the second
# branch a build-pkg created before this option was added keeps its old configuration, meson
# skips setup, and the compile produces a helper-enabled .so. The assertion below then fails
# the build rather than shipping it, so this is a developer-build correctness fix and not a
# security one -- but it turns a confusing failure into no failure at all.
if not os.path.exists(os.path.join(build_dir, 'build.ninja')):
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release')
# -Dhelper=disabled: rustdesk never uses the privileged helper. The capture context is
# opened only in the root service (every drmtap_open lives in src/ipc/drm.rs), which
# already has CAP_SYS_ADMIN, and the unprivileged side opens a render node instead. Without
# this the library still carries the fallback: a fork/exec that walks six hardcoded paths,
# two of them under /usr/local, and execs the first that passes access(X_OK) with no check
# of its owner or mode -- inside the ROOT process. The option compiles that path out
# entirely. Requested by the maintainer on rustdesk#16242.
system2(f'meson setup "{build_dir}" "{src}" --buildtype=release -Dhelper=disabled')
else:
system2(f'meson configure "{build_dir}" -Dhelper=disabled')
# Build only the shared library, not the bundled helper binary or the static archive. Since
# libdrmtap 0.4.11 the project is `both_libraries` (a version-scripted .so + a static .a), so the
# bare `drmtap` target is ambiguous ("drmtap:shared_library" vs "drmtap:static_library"); ask for
@@ -533,9 +549,31 @@ def build_libdrmtap_so():
# require exactly one so a stale object from an earlier build is never silently picked.
so = _single_real_so(sos, f'the libdrmtap meson build dir {build_dir}')
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
return so
def _assert_so_has_no_helper(so_path):
# Asserted on the ARTIFACT for the same reason the EGL check is: a build flag cannot notice a
# stale object left by an earlier build, or one substituted by hand, and `-Dhelper=disabled` is
# silently accepted by meson versions that predate the option. What the option removes is the
# whole fork/exec path, so the produced .so imports no socketpair and carries none of the
# helper search paths; both go to zero, measured on libdrmtap 0.5.6 (4 -> 0 and 3 -> 0).
#
# This matters because the object is loaded by the ROOT service. With the path compiled in, a
# caller that ever lost CAP_SYS_ADMIN would exec whatever sits at the first of six hardcoded
# locations that passes access(X_OK), without checking its owner or its mode.
with open(so_path, 'rb') as f:
blob = f.read()
found = [m.decode() for m in (b'socketpair', b'/usr/libexec/drmtap-helper') if m in blob]
if found:
raise Exception(
f'{so_path} still carries the privileged-helper fallback ({", ".join(found)}). '
f'It must be built with -Dhelper=disabled: rustdesk captures as root and never uses '
f'the helper, so this is a fork/exec path in the privileged process that nothing '
f'reaches. Delete third_party/libdrmtap/build-pkg and rebuild.')
def _assert_so_has_egl(so_path):
# libdrmtap treats egl/glesv2 as OPTIONAL dependencies: without their headers and pkg-config
# files, meson silently builds a CPU-only stub. That stub still exports every symbol the loader
@@ -863,8 +901,10 @@ def build_deb_from_folder(version, binary_folder, want_drm=False):
# takes the .so straight out of a bundle somebody else produced, so it has the same
# exposure as DRMTAP_PREBUILT_DIR (see the comment on that branch). A CPU-only stub
# would ship, the loader would accept it, and capture would degrade to PipeWire
# without a word.
# without a word. A bundle produced before the helper was disabled is caught here too,
# which is the point: it must not be repackaged into a deb.
_assert_so_has_egl(so)
_assert_so_has_no_helper(so)
stage_libdrmtap_into_deb(so)
system2(f'rm -f "{so}"')
system2('rm -f tmpdeb/usr/share/rustdesk/libdrmtap.so tmpdeb/usr/share/rustdesk/libdrmtap.so.0')
+43 -35
View File
@@ -1,39 +1,45 @@
<p align="center">
<img src="../res/logo-header.svg" alt="RustDesk - Ваша віддалена стільниця"><br>
<a href="#публічні-сервери">Сервери</a> •
<a href="#кроки-для-збірки">Збирання</a> •
<img src="../res/logo-header.svg" alt="RustDesk - Ваш віддалений робочий стіл"><br>
<a href="#кроки-для-збірки">Збірка</a> •
<a href="#як-зібрати-за-допомогою-docker">Docker</a> •
<a href="#структура-файлів">Структура</a> •
<a href="#знімки-екрана">Знімки екрана</a><br>
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>]<br>
<b>Нам потрібна ваша допомога для перекладу цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації</a> RustDesk вашою рідною мовою</B>
[<a href="../README.md">English</a>] | [<a href="README-CS.md">česky</a>] | [<a href="README-ZH.md">中文</a>] | [<a href="README-HU.md">Magyar</a>] | [<a href="README-ES.md">Español</a>] | [<a href="README-FA.md">فارسی</a>] | [<a href="README-FR.md">Français</a>] | [<a href="README-DE.md">Deutsch</a>] | [<a href="README-PL.md">Polski</a>] | [<a href="README-ID.md">Indonesian</a>] | [<a href="README-FI.md">Suomi</a>] | [<a href="README-ML.md">മലയാളം</a>] | [<a href="README-JP.md">日本語</a>] | [<a href="README-NL.md">Nederlands</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Русский</a>] | [<a href="README-PTBR.md">Português (Brasil)</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">한국어</a>] | [<a href="README-AR.md">العربي</a>] | [<a href="README-VN.md">Tiếng Việt</a>] | [<a href="README-DA.md">Dansk</a>] | [<a href="README-GR.md">Ελληνικά</a>] | [<a href="README-TR.md">Türkçe</a>] | [<a href="README-NO.md">Norsk</a>] | [<a href="README-RO.md">Română</a>]<br>
<b>Нам потрібна ваша допомога з перекладом цього README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">інтерфейсу RustDesk</a> та <a href="https://github.com/rustdesk/doc.rustdesk.com">документації RustDesk</a> вашою рідною мовою</b>
</p>
Спілкування з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
> [!CAUTION]
> **Застереження щодо неналежного використання:** <br>
> Розробники RustDesk не схвалюють і не підтримують неетичне або незаконне використання цього програмного забезпечення. Неналежне використання, зокрема несанкціонований доступ, керування або втручання в приватність, суворо суперечить нашим правилам. Автори не несуть відповідальності за неналежне використання застосунку.
[![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)
Спілкуйтеся з нами: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
Ще один застосунок для віддаленого керування стільницею, написаний на Rust. Працює з коробки, не потребує налаштування. Ви повністю контролюєте свої дані, не турбуючись про безпеку. Ви можете використовувати наш сервер ретрансляції, [налаштувати свій власний](https://rustdesk.com/server), або [написати свій власний сервер ретрансляції](https://github.com/rustdesk/rustdesk-server-demo).
[![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).
![image](https://user-images.githubusercontent.com/71636191/171661982-430285f0-2e12-4b1d-9957-4a58e375304d.png)
RustDesk вітає внесок кожного. Ознайомтеся з [CONTRIBUTING.md](CONTRIBUTING.md), щоб отримати допомогу на початковому етапі.
RustDesk вітає внески від усіх охочих. Дивіться [CONTRIBUTING.md](CONTRIBUTING.md), щоб дізнатися, з чого почати.
[**ЧаПи**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**FAQ**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**ЗАВАНТАЖЕННЯ ЗАСТОСУНКУ**](https://github.com/rustdesk/rustdesk/releases)
[**ЗАВАНТАЖИТИ ГОТОВУ ЗБІРКУ**](https://github.com/rustdesk/rustdesk/releases)
[**НІЧНІ ЗБІРКИ**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
[<img src="https://f-droid.org/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Get it on Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Залежності
Стільничні версії використовують Flutter чи Sciter (застаріле) для графічного інтерфейсу. Ця інструкція лише для Sciter, оскільки він є більш простим та дружнім для початківців. Перегляньте [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) для збірки версії на Flutter.
Версії для настільних ОС використовують Flutter або Sciter (застарілий) для графічного інтерфейсу. Ця інструкція стосується лише Sciter, оскільки з ним простіше почати. Для збірки версії на Flutter дивіться наш [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml).
Будь ласка, завантажте динамічну бібліотеку Sciter самостійно.
Динамічну бібліотеку Sciter потрібно завантажити окремо.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
@@ -41,14 +47,14 @@ RustDesk вітає внесок кожного. Ознайомтеся з [CONT
## Кроки для збірки
- Підготуйте середовище розробки Rust і середовище збирання C++.
- Підготуйте середовище розробки Rust і середовище для збирання C++.
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg), і правильно встановіть змінну `VCPKG_ROOT`.
- Встановіть [vcpkg](https://github.com/microsoft/vcpkg) і правильно задайте змінну середовища `VCPKG_ROOT`.
- Windows: vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static
- Linux/macOS: vcpkg install libvpx libyuv opus aom
- Запустіть `cargo run`
- Запустіть `cargo run`.
## [Збирання](https://rustdesk.com/docs/en/dev/build/)
@@ -110,7 +116,7 @@ cd
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone https://github.com/rustdesk/rustdesk
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
@@ -120,54 +126,56 @@ VCPKG_ROOT=$HOME/vcpkg cargo run
## Як зібрати за допомогою Docker
Почніть з клонування сховища та створення docker-контейнера:
Спочатку клонуйте репозиторій і зберіть Docker-контейнер:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .
```
Надалі щоразу, коли вам буде потрібно зібрати застосунок, запускайте таку команду:
Після цього щоразу, коли потрібно зібрати застосунок, запускайте таку команду:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Зверніть увагу, що перша збірка може зайняти більше часу, перш ніж залежності будуть кешовані, але наступні збірки будуть виконуватися швидше. Крім того, якщо вам потрібно вказати інші аргументи для команди збірки, ви можете зробити це в кінці команди у змінній `<OPTIONAL-ARGS>`. Наприклад, якщо ви хочете створити оптимізовану версію, ви маєте запустити наведену вище команду і в кінці рядка додати `--release`. Отриманий виконуваний файл буде доступний у цільовій папці вашої системи і може бути запущений за допомогою:
Перша збірка може тривати довше, доки залежності не буде кешовано. Наступні збірки виконуватимуться швидше. Якщо потрібно передати додаткові аргументи команді збірки, додайте їх після `rustdesk-builder` у кінці команди `docker run`. Наприклад, для оптимізованої release-збірки додайте `--release`. Отриманий виконуваний файл буде доступний у каталозі `target` вашої системи та його можна запустити так:
```sh
target/debug/rustdesk
```
Або, якщо ви використовуєте виконуваний файл релізу:
Або, якщо використовується release-збірка:
```sh
target/release/rustdesk
```
Будь ласка, переконайтеся, що ви запускаєте ці команди з кореня сховища RustDesk, інакше додаток не зможе знайти необхідні ресурси. Також зверніть увагу, що інші cargo підкоманди, такі як `install` або `run`, наразі не підтримуються цим методом, оскільки вони будуть встановлювати або запускати програму всередині контейнера, а не на хості.
Запускайте ці команди з кореневого каталогу репозиторію RustDesk, інакше застосунок може не знайти потрібні ресурси. Також зверніть увагу, що інші підкоманди cargo, наприклад `install` або `run`, наразі не підтримуються цим способом, оскільки вони встановлюватимуть або запускатимуть програму всередині контейнера, а не на хост-системі.
## Структура файлів
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфіг, обгортка tcp/udp, protobuf, функції fs для передавання файлів і деякі інші службові функції
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: відеокодек, конфігурація, обгортка tcp/udp та інші допоміжні функції, спільні із сервером
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, функції файлової системи для передавання файлів, код клавіатури та платформоспецифічний код, що використовуються лише цим застосунком
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: захоплення екрана
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: специфічне для платформи керування клавіатурою/мишею
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux, macOS.
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: графічний інтерфейс користувача
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: сервіси аудіо/буфера обміну/вводу/відео та мережевих підключень
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: однорангове зʼєднання
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: комунікація з [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування віддаленого прямого (обхід TCP NAT) або ретрансльованого зʼєднання
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: специфічний для платформи код
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для мобільних пристроїв
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: платформоспецифічне керування клавіатурою та мишею
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: реалізація копіювання та вставлення файлів для Windows, Linux і macOS
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: застарілий інтерфейс Sciter (deprecated)
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: служби аудіо, буфера обміну, введення та відео, а також мережеві з'єднання
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: встановлення однорангового з'єднання
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: зв'язок із [rustdesk-server](https://github.com/rustdesk/rustdesk-server), очікування прямого віддаленого з'єднання (TCP hole punching) або з'єднання через ретранслятор
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: платформоспецифічний код
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: код Flutter для настільних і мобільних платформ
## Знімки екрана
![Менеджер зʼєднань](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)
@@ -199,7 +199,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
context,
Manifest.permission.RECORD_AUDIO
) != PackageManager.PERMISSION_GRANTED) {
"To start a voice call, enable \"Audio capture\" on the \"Screen share\" page."
"To start a voice call, enable \"Audio capture\" on the \"Share screen\" page."
} else {
"Failed to start voice call."
}
@@ -19,6 +19,7 @@ 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
@@ -35,6 +36,7 @@ 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
@@ -107,6 +109,15 @@ 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
+66 -57
View File
@@ -154,7 +154,7 @@ prebuild)
.github/workflows/bridge.yml)"
FLUTTER_BRIDGE_VERSION="$(yq -r \
.env.FLUTTER_VERSION \
'.jobs.generate_bridge.strategy.matrix.job[] | select(.["artifact-name"] == "bridge-artifact") | .["flutter-version"]' \
.github/workflows/bridge.yml)"
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
@@ -306,67 +306,69 @@ prebuild)
git apply res/fdroid/patches/*.patch
# If Flutter version used to generate bridge files differs from Flutter
# version used to compile Rustdesk library, generate bridge using the
# `FLUTTER_BRIDGE_VERSION` an restore the pubspec later
# Generate bridge files using `FLUTTER_BRIDGE_VERSION`, which may differ
# from the Flutter version used to compile RustDesk library, and restore
# the pubspec later
if [ "${FLUTTER_VERSION}" != "${FLUTTER_BRIDGE_VERSION}" ]; then
# Find first libclang.so and set BRIDGE_LLVM_PATH
# Find first libclang.so and set BRIDGE_LLVM_PATH
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
prepare_flutter "${FLUTTER_BRIDGE_VERSION}" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
# Unbraced on purpose: F-Droid recipes rewrite the braced form with sed to
# pin a version, but the bridge generator only works with the Flutter
# version bridge.yml uses
prepare_flutter "$FLUTTER_BRIDGE_VERSION" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
# Install Flutter version for RustDesk library build
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
@@ -379,6 +381,13 @@ prebuild)
flutter/android/build.gradle \
flutter/android/app/build.gradle
# Gradle 8 / AGP 8 thrash in the default 1 GiB heap; raise it as CI does
sed \
-i \
-e 's/org.gradle.jvmargs=-Xmx1024M/org.gradle.jvmargs=-Xmx2g/g' \
flutter/android/gradle.properties
# `firebase_analytics` is not in these files now, but we still keep the following lines.
sed \
@@ -271,11 +271,6 @@ class AllPeersLoader {
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
_updateOnlineState(evt);
}
@visibleForTesting
bool applyLastOnlineStateForTesting(List<Peer> peers) {
return _applyLastOnlineState(peers);
}
}
class AutocompletePeerTile extends StatefulWidget {
@@ -0,0 +1,111 @@
// 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();
}
}
@@ -0,0 +1,481 @@
// 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,
),
),
);
}
}
@@ -0,0 +1,418 @@
// 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),
],
);
}
}
@@ -0,0 +1,287 @@
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;
}
@@ -0,0 +1,122 @@
/// 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],
},
];
@@ -0,0 +1,208 @@
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;
}
+256 -35
View File
@@ -11,6 +11,7 @@ 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';
@@ -92,16 +93,77 @@ 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.divider = false,
this.actionId});
Widget getChild() {
if (trailingIcon != null) {
@@ -123,20 +185,73 @@ 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});
required this.onChanged,
this.actionId});
}
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});
{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;
}
handleOsPasswordEditIcon(
@@ -337,6 +452,17 @@ 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 &&
@@ -404,7 +530,8 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
return;
}
await sendClipboardKeystrokes();
}));
},
actionId: kShortcutActionSendClipboardKeystrokes));
}
if (isDefaultConn &&
isWaylandPeer &&
@@ -439,7 +566,8 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
if (isDefaultConn && isMobile) {
v.add(TTextMenu(
child: Text(translate('Reset canvas')),
onPressed: () => ffi.cursorModel.reset()));
onPressed: () => ffi.cursorModel.reset(),
actionId: kShortcutActionResetCanvas));
}
// https://github.com/rustdesk/rustdesk/pull/9731
@@ -515,7 +643,8 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
v.add(
TTextMenu(
child: Text('${translate("Insert Ctrl + Alt + Del")}'),
onPressed: () => bind.sessionCtrlAltDel(sessionId: sessionId)),
onPressed: () => bind.sessionCtrlAltDel(sessionId: sessionId),
actionId: kShortcutActionSendCtrlAltDel),
);
}
// restart
@@ -528,7 +657,8 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
TTextMenu(
child: Text(translate('Restart remote device')),
onPressed: () =>
showRestartRemoteDevice(pi, id, sessionId, ffi.dialogManager)),
showRestartRemoteDevice(pi, id, sessionId, ffi.dialogManager),
actionId: kShortcutActionRestartRemote),
);
}
// insertLock
@@ -536,7 +666,8 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
v.add(
TTextMenu(
child: Text(translate('Insert Lock')),
onPressed: () => bind.sessionLockScreen(sessionId: sessionId)),
onPressed: () => bind.sessionLockScreen(sessionId: sessionId),
actionId: kShortcutActionInsertLock),
);
}
// blockUserInput
@@ -554,7 +685,8 @@ 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 &&
@@ -566,13 +698,15 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
v.add(TTextMenu(
child: Text(translate('Switch Sides')),
onPressed: () =>
showConfirmSwitchSidesDialog(sessionId, id, ffi.dialogManager)));
showConfirmSwitchSidesDialog(sessionId, id, ffi.dialogManager),
actionId: kShortcutActionSwitchSides));
}
// refresh
if (pi.version.isNotEmpty) {
v.add(TTextMenu(
child: Text(translate('Refresh')),
onPressed: () => sessionRefreshVideo(sessionId, pi),
actionId: kShortcutActionRefresh,
));
}
// record
@@ -595,7 +729,8 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
)
],
),
onPressed: () => ffi.recordingModel.toggle()));
onPressed: () => ffi.recordingModel.toggle(),
actionId: kShortcutActionToggleRecording));
}
// to-do:
@@ -612,6 +747,14 @@ 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,
@@ -629,6 +772,7 @@ List<TTextMenu> toolbarControls(BuildContext context, String id, FFI ffi) {
});
}
},
actionId: kShortcutActionScreenshot,
));
}
}
@@ -639,6 +783,17 @@ 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;
}
@@ -653,23 +808,26 @@ Future<List<TRadioMenu<String>>> toolbarViewStyle(
.then((_) => ffi.canvasModel.updateViewStyle());
}
return [
return _registerRadioMenuShortcuts(ffi, [
TRadioMenu<String>(
child: Text(translate('Scale original')),
value: kRemoteViewStyleOriginal,
groupValue: groupValue,
onChanged: onChanged),
onChanged: onChanged,
actionId: kShortcutActionViewModeOriginal),
TRadioMenu<String>(
child: Text(translate('Scale adaptive')),
value: kRemoteViewStyleAdaptive,
groupValue: groupValue,
onChanged: onChanged),
onChanged: onChanged,
actionId: kShortcutActionViewModeAdaptive),
TRadioMenu<String>(
child: Text(translate('Scale custom')),
value: kRemoteViewStyleCustom,
groupValue: groupValue,
onChanged: onChanged)
];
onChanged: onChanged,
actionId: kShortcutActionViewModeCustom)
], ownedActionIds: _kToolbarViewStyleActionIds);
}
Future<List<TRadioMenu<String>>> toolbarImageQuality(
@@ -681,22 +839,25 @@ Future<List<TRadioMenu<String>>> toolbarImageQuality(
await bind.sessionSetImageQuality(sessionId: ffi.sessionId, value: value);
}
return [
return _registerRadioMenuShortcuts(ffi, [
TRadioMenu<String>(
child: Text(translate('Good image quality')),
value: kRemoteImageQualityBest,
groupValue: groupValue,
onChanged: onChanged),
onChanged: onChanged,
actionId: kShortcutActionImageQualityBest),
TRadioMenu<String>(
child: Text(translate('Balanced')),
value: kRemoteImageQualityBalanced,
groupValue: groupValue,
onChanged: onChanged),
onChanged: onChanged,
actionId: kShortcutActionImageQualityBalanced),
TRadioMenu<String>(
child: Text(translate('Optimize reaction time')),
value: kRemoteImageQualityLow,
groupValue: groupValue,
onChanged: onChanged),
onChanged: onChanged,
actionId: kShortcutActionImageQualityLow),
TRadioMenu<String>(
child: Text(translate('Custom')),
value: kRemoteImageQualityCustom,
@@ -706,7 +867,7 @@ Future<List<TRadioMenu<String>>> toolbarImageQuality(
customImageQualityDialog(ffi.sessionId, id, ffi);
},
),
];
], ownedActionIds: _kToolbarImageQualityActionIds);
}
Future<List<TRadioMenu<String>>> toolbarCodec(
@@ -733,7 +894,10 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
}
final visible =
codecs.length == 4 && (codecs[0] || codecs[1] || codecs[2] || codecs[3]);
if (!visible) return [];
if (!visible) {
return _registerRadioMenuShortcuts<String>(ffi, [],
ownedActionIds: _kToolbarCodecActionIds);
}
onChanged(String? value) async {
if (value == null) return;
await bind.sessionPeerOption(
@@ -741,12 +905,14 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
bind.sessionChangePreferCodec(sessionId: sessionId);
}
TRadioMenu<String> radio(String label, String value, bool enabled) {
TRadioMenu<String> radio(
String label, String value, bool enabled, String actionId) {
return TRadioMenu<String>(
child: Text(label),
value: value,
groupValue: groupValue,
onChanged: enabled ? onChanged : null);
onChanged: enabled ? onChanged : null,
actionId: actionId);
}
var autoLabel = translate('Auto');
@@ -754,14 +920,14 @@ Future<List<TRadioMenu<String>>> toolbarCodec(
ffi.qualityMonitorModel.data.codecFormat != null) {
autoLabel = '$autoLabel (${ffi.qualityMonitorModel.data.codecFormat})';
}
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]),
];
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);
}
Future<List<TToggleMenu>> toolbarCursor(
@@ -786,6 +952,7 @@ 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;
@@ -822,6 +989,7 @@ 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);
@@ -850,6 +1018,7 @@ 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);
@@ -867,6 +1036,7 @@ 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);
@@ -875,7 +1045,8 @@ Future<List<TToggleMenu>> toolbarCursor(
},
));
}
return v;
return _registerToggleMenuShortcuts(ffi, v,
ownedActionIds: _kToolbarCursorActionIds);
}
Future<List<TToggleMenu>> toolbarDisplayToggle(
@@ -891,6 +1062,7 @@ 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);
@@ -904,6 +1076,7 @@ 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);
@@ -928,6 +1101,7 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
sessionId: sessionId, arg: kOptionEnableFileCopyPaste);
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleEnableFileCopyPaste,
onChanged: enabled
? (value) {
if (value == null) return;
@@ -946,6 +1120,7 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
if (ffiModel.viewOnly) value = true;
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleDisableClipboard,
onChanged: enabled
? (value) {
if (value == null) return;
@@ -962,6 +1137,7 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
bind.sessionGetToggleOptionSync(sessionId: sessionId, arg: option);
v.add(TToggleMenu(
value: value,
actionId: kShortcutActionToggleLockAfterSessionEnd,
onChanged: enabled
? (value) {
if (value == null) return;
@@ -1014,6 +1190,7 @@ 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);
@@ -1038,7 +1215,8 @@ Future<List<TToggleMenu>> toolbarDisplayToggle(
},
child: Text(translate('View Mode'))));
}
return v;
return _registerToggleMenuShortcuts(ffi, v,
ownedActionIds: _kToolbarDisplayToggleActionIds);
}
var togglePrivacyModeTime = DateTime.now().subtract(const Duration(hours: 1));
@@ -1166,6 +1344,7 @@ 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'))));
}
@@ -1231,10 +1410,52 @@ 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 v;
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);
}
bool showVirtualDisplayMenu(FFI ffi) {
+2
View File
@@ -4,6 +4,8 @@ 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;
@@ -480,6 +480,10 @@ 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)) {
@@ -0,0 +1,66 @@
// 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,12 +10,15 @@ 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';
@@ -419,11 +422,50 @@ class _GeneralState extends State<_General> {
if (!isWeb) audio(context),
if (!isWeb) record(context),
if (!isWeb) WaylandCard(),
other()
other(),
if (!bind.isIncomingOnly()) keyboardShortcuts(),
],
).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 {
@@ -2657,6 +2699,8 @@ 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()
@@ -2700,11 +2744,23 @@ Widget _OptionCheckBox(
offstage: !ref.value || checkedIcon == null,
child: checkedIcon?.marginOnly(right: 5),
),
Expanded(
// Without `trailing`, keep the original Expanded(Text) layout.
if (trailing == null)
Expanded(
child: Text(
translate(label),
style: TextStyle(color: disabledTextColor(context, enabled)),
))
else ...[
Flexible(
child: Text(
translate(label),
style: TextStyle(color: disabledTextColor(context, enabled)),
))
translate(label),
style: TextStyle(color: disabledTextColor(context, enabled)),
),
),
trailing,
const Spacer(),
],
],
),
).marginOnly(left: _kCheckBoxLeftMargin),
@@ -3111,6 +3167,37 @@ 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
+30 -2
View File
@@ -62,12 +62,15 @@ class _InstallPageBody extends StatefulWidget {
class _InstallPageBodyState extends State<_InstallPageBody>
with WindowListener {
static const _printerStatusTimeout = Duration(seconds: 5);
late final TextEditingController controller;
final RxBool startmenu = true.obs;
final RxBool desktopicon = true.obs;
final RxBool printer = false.obs;
final RxBool showProgress = false.obs;
final RxBool btnEnabled = true.obs;
final RxBool cancelEnabled = true.obs;
// todo move to theme.
final buttonStyle = OutlinedButton.styleFrom(
@@ -83,10 +86,33 @@ class _InstallPageBodyState extends State<_InstallPageBody>
printer.value = installOptions['PRINTER'] == '1';
}
Future<void> _loadPrinterStatus() async {
btnEnabled.value = false;
showProgress.value = true;
try {
final status = await bind
.mainGetCommon(key: 'is-printer-installed')
.timeout(_printerStatusTimeout);
printer.value = status == 'true';
if (status != 'true' && status != 'false') {
debugPrint('Failed to check printer installation status: $status');
}
} catch (e) {
printer.value = false;
debugPrint('Failed to check printer installation status: $e');
} finally {
showProgress.value = false;
btnEnabled.value = true;
}
}
@override
void initState() {
windowManager.addListener(this);
super.initState();
if (printer.value) {
_loadPrinterStatus();
}
}
@override
@@ -217,8 +243,9 @@ class _InstallPageBodyState extends State<_InstallPageBody>
() => OutlinedButton.icon(
icon: Icon(Icons.close_rounded, size: 16),
label: Text(translate('Cancel')),
onPressed:
btnEnabled.value ? () => windowManager.close() : null,
onPressed: cancelEnabled.value
? () => windowManager.close()
: null,
style: buttonStyle,
).marginOnly(right: 10),
),
@@ -253,6 +280,7 @@ class _InstallPageBodyState extends State<_InstallPageBody>
void install() {
do_install() {
btnEnabled.value = false;
cancelEnabled.value = false;
showProgress.value = true;
String args = '';
if (startmenu.value) args += ' startmenu';
@@ -17,6 +17,7 @@ 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';
@@ -162,6 +163,18 @@ 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(
@@ -5,6 +5,7 @@ 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';
@@ -1318,8 +1319,35 @@ 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: e.child,
child: child,
onPressed: e.onPressed,
ffi: ffi,
trailingIcon: e.trailingIcon);
@@ -418,6 +418,13 @@ class _DesktopTabState extends State<DesktopTab>
}
}
// On Linux, GTK destroys the window on a close request unless prevent-close
// is on. It is off for the cm and install windows, and onActiveWindowChanged()
// turns it off to quit, so the window can no longer be saved or hidden.
// https://github.com/rustdesk/rustdesk/issues/16512
Future<bool> _isLinuxWindowClosed() async =>
isLinux && isMainWindow && !await windowManager.isPreventClose();
@override
void onWindowMoved() {
_saveFrame();
@@ -465,6 +472,8 @@ class _DesktopTabState extends State<DesktopTab>
});
}
if (await _isLinuxWindowClosed()) return;
await _saveFrame(flush: true);
// hide window on close
@@ -472,6 +481,7 @@ class _DesktopTabState extends State<DesktopTab>
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
}
if (await _isLinuxWindowClosed()) return;
// macOS specific workaround, the window is not hiding when in fullscreen.
if (isMacOS && await windowManager.isFullScreen()) {
await windowManager.setFullScreen(false);
@@ -7,36 +7,49 @@ import 'package:flutter_hbb/models/platform_model.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
final _isExtracting = false.obs;
const _eventKeyUpdateMe = 'update-me';
void handleUpdate(String releasePageUrl) {
_isExtracting.value = false;
String downloadUrl = releasePageUrl.replaceAll('tag', 'download');
String version = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
final String downloadFile =
bind.mainGetCommonSync(key: 'download-file-$version');
if (downloadFile.startsWith('error:')) {
final error = downloadFile.replaceFirst('error:', '');
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
Future<void> _handleUpdateMe(
String releasePageUrl, Map<String, dynamic> evt) async {
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
if (evt.containsKey('error')) {
_showUpdateError(releasePageUrl, evt['error'] as String);
}
}
Future<void> handleUpdate(String releasePageUrl) async {
final dialogClosed = _showVerifyingUpdate();
final String? downloadUrl;
try {
downloadUrl = await waitForUpdateVerification(
bind.mainGetCommon(key: 'verified-download-url-$releasePageUrl'),
dialogClosed,
);
} catch (error) {
_showUpdateError(releasePageUrl, error.toString());
return;
}
if (downloadUrl == null) {
return;
}
final verifiedDownloadUrl = downloadUrl;
if (downloadUrl.startsWith('error:')) {
_showUpdateError(releasePageUrl, downloadUrl.replaceFirst('error:', ''));
return;
}
downloadUrl = '$downloadUrl/$downloadFile';
SimpleWrapper downloadId = SimpleWrapper('');
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
gFFI.dialogManager.dismissAll();
gFFI.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
title: Obx(() => Text(translate(_isExtracting.isTrue
? 'Preparing for installation ...'
: 'Downloading {$appName}'))),
content:
UpdateProgress(releasePageUrl, downloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
title: Text(translate('Downloading {$appName}')),
content: UpdateProgress(
releasePageUrl, verifiedDownloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
actions: [
if (_isExtracting.isFalse) dialogButton(translate('Cancel'), onPressed: () async {
dialogButton('Cancel', onPressed: () async {
onCanceled.value();
await bind.mainSetCommon(
key: 'cancel-downloader', value: downloadId.value);
@@ -56,6 +69,40 @@ void handleUpdate(String releasePageUrl) {
});
}
Future<T?> waitForUpdateVerification<T extends Object>(
Future<T> verification,
Future<void> dialogClosed,
) async {
final dialogClosedMarker = Object();
final result = await Future.any<Object>([
verification.then<Object>((value) => value),
dialogClosed.then<Object>((_) => dialogClosedMarker),
]);
return identical(result, dialogClosedMarker) ? null : result as T;
}
Future<void> _showVerifyingUpdate() async {
gFFI.dialogManager.dismissAll();
await gFFI.dialogManager.show<void>(
(setState, close, context) => CustomAlertDialog(
title: Text(translate('Preparing for installation ...')),
content: const LinearProgressIndicator(),
actions: [
dialogButton('Close', onPressed: close, isOutline: true),
],
onCancel: close,
),
tag: 'verifying-update',
);
}
void _showUpdateError(String releasePageUrl, String error) {
debugPrint('Update error: $error');
gFFI.dialogManager.dismissAll();
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
}
class UpdateProgress extends StatefulWidget {
final String releasePageUrl;
final String downloadUrl;
@@ -74,9 +121,9 @@ class UpdateProgressState extends State<UpdateProgress> {
Timer? _timer;
int? _totalSize;
int _downloadedSize = 0;
bool _downloadFinished = false;
int _getDataFailedCount = 0;
final String _eventKeyDownloadNewVersion = 'download-new-version';
final String _eventKeyExtractUpdateDmg = 'extract-update-dmg';
@override
void initState() {
@@ -88,11 +135,6 @@ class UpdateProgressState extends State<UpdateProgress> {
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
replace: true);
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
if (isMacOS) {
platformFFI.registerEventHandler(_eventKeyExtractUpdateDmg,
_eventKeyExtractUpdateDmg, handleExtractUpdateDmg,
replace: true);
}
}
@override
@@ -100,10 +142,7 @@ class UpdateProgressState extends State<UpdateProgress> {
cancelQueryTimer();
platformFFI.unregisterEventHandler(
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
if (isMacOS) {
platformFFI.unregisterEventHandler(
_eventKeyExtractUpdateDmg, _eventKeyExtractUpdateDmg);
}
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
super.dispose();
}
@@ -128,35 +167,33 @@ class UpdateProgressState extends State<UpdateProgress> {
}
}
// `isExtractDmg` is true when handling extract-update-dmg event.
// It's a rare case that the dmg file is corrupted and cannot be extracted.
void _onError(String error, {bool isExtractDmg = false}) {
void _onError(String error) {
cancelQueryTimer();
debugPrint(
'${isExtractDmg ? "Extract" : "Download"} new version error: $error');
debugPrint('Download new version error: $error');
final msgBoxType = 'custom-nocancel-nook-hasclose';
final msgBoxTitle = 'Error';
final msgBoxText = 'download-new-version-failed-tip';
final dialogManager = gFFI.dialogManager;
final releasePageUrl = widget.releasePageUrl;
close() {
dialogManager.dismissAll();
}
jumplink() {
launchUrl(Uri.parse(widget.releasePageUrl));
launchUrl(Uri.parse(releasePageUrl));
dialogManager.dismissAll();
}
retry() {
dialogManager.dismissAll();
handleUpdate(widget.releasePageUrl);
handleUpdate(releasePageUrl);
}
final List<Widget> buttons = [
dialogButton('Download', onPressed: jumplink),
if (!isExtractDmg) dialogButton('Retry', onPressed: retry),
dialogButton('Retry', onPressed: retry),
dialogButton('Close', onPressed: close),
];
dialogManager.dismissAll();
@@ -186,6 +223,8 @@ class UpdateProgressState extends State<UpdateProgress> {
}
} else if (key == 'downloaded_size') {
_downloadedSize = value as int;
} else if (key == 'finished') {
_downloadFinished = value as bool;
} else if (key == 'error') {
if (value != null) {
err = value.toString();
@@ -204,7 +243,9 @@ class UpdateProgressState extends State<UpdateProgress> {
if (err != '') {
_onError(err);
} else {
if (_totalSize != null && _downloadedSize >= _totalSize!) {
if (_downloadFinished &&
_totalSize != null &&
_downloadedSize >= _totalSize!) {
cancelQueryTimer();
bind.mainSetCommon(
key: 'remove-downloader', value: widget.downloadId.value);
@@ -212,13 +253,7 @@ class UpdateProgressState extends State<UpdateProgress> {
_onError('The download file size is 0.');
} else {
setState(() {});
if (isMacOS) {
bind.mainSetCommon(
key: 'extract-update-dmg', value: widget.downloadUrl);
_isExtracting.value = true;
} else {
updateMsgBox();
}
updateMsgBox();
}
} else {
setState(() {});
@@ -227,6 +262,8 @@ class UpdateProgressState extends State<UpdateProgress> {
}
void updateMsgBox() {
final releasePageUrl = widget.releasePageUrl;
final downloadUrl = widget.downloadUrl;
msgBox(
gFFI.sessionId,
'custom-nocancel',
@@ -234,30 +271,30 @@ class UpdateProgressState extends State<UpdateProgress> {
'{$appName}-to-update-tip',
'',
gFFI.dialogManager,
onSubmit: () {
onSubmit: () async {
debugPrint('Downloaded, update to new version now');
bind.mainSetCommon(key: 'update-me', value: widget.downloadUrl);
platformFFI.registerEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe,
(evt) => _handleUpdateMe(releasePageUrl, evt),
replace: true);
try {
await bind.mainSetCommon(key: 'update-me', value: downloadUrl);
} catch (error) {
platformFFI.unregisterEventHandler(
_eventKeyUpdateMe, _eventKeyUpdateMe);
_showUpdateError(releasePageUrl, error.toString());
}
},
submitTimeout: 5,
);
}
Future<void> handleExtractUpdateDmg(Map<String, dynamic> evt) async {
_isExtracting.value = false;
if (evt.containsKey('err') && (evt['err'] as String).isNotEmpty) {
_onError(evt['err'] as String, isExtractDmg: true);
} else {
updateMsgBox();
}
}
@override
Widget build(BuildContext context) {
getValue() => _totalSize == null
? 0.0
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
return LinearProgressIndicator(
value: _isExtracting.isTrue ? null : getValue(),
value: getValue(),
minHeight: 20,
borderRadius: BorderRadius.circular(5),
backgroundColor: Colors.grey[300],
@@ -0,0 +1,95 @@
// 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),
),
),
],
),
);
}
}
+77 -14
View File
@@ -21,6 +21,7 @@ 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';
@@ -40,6 +41,32 @@ 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,
@@ -107,6 +134,7 @@ 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 =
@@ -122,6 +150,19 @@ 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);
@@ -142,6 +183,7 @@ 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`
@@ -253,10 +295,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
if (isIOS) {
_iosKeyboardWorkaroundTimer?.cancel();
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 100), () {
if (!mounted) return;
if (!mounted || gFFI.chatModel.inputNode.hasFocus) return;
_physicalFocusNode.unfocus();
_iosKeyboardWorkaroundTimer = Timer(Duration(milliseconds: 50), () {
if (!mounted) return;
if (!mounted || gFFI.chatModel.inputNode.hasFocus) return;
_physicalFocusNode.requestFocus();
});
});
@@ -335,6 +377,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
} else if (newValue.length < oldValue.length) {
@@ -534,6 +580,9 @@ 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(
@@ -655,7 +704,6 @@ 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: () {
@@ -666,9 +714,14 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
right: 10,
child: QualityMonitor(gFFI.qualityMonitorModel),
),
KeyHelpTools(
keyboardIsVisible: keyboardIsVisible,
showGestureHelp: _showGestureHelp),
Obx(() {
final chatKeyboardRequested =
gFFI.chatModel.softKeyboardRequested.value;
return KeyHelpTools(
keyboardIsVisible: keyboardVisibilityController.isVisible &&
(_showEdit || chatKeyboardRequested),
showGestureHelp: _showGestureHelp);
}),
SizedBox(
width: 0,
height: 0,
@@ -805,9 +858,18 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
}();
}
onPressedTextChat(String id) {
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);
}
gFFI.chatModel.changeCurrentKey(MessageKey(id, ChatModel.clientModeID));
gFFI.chatModel.toggleChatOverlay();
gFFI.chatModel.toggleChatOverlay(requestSoftKeyboard: requestSoftKeyboard);
}
showChatOptions(String id) async {
@@ -975,12 +1037,13 @@ class _KeyHelpToolsState extends State<KeyHelpTools> {
@override
Widget build(BuildContext context) {
final hasModifierOn = inputModel.ctrl ||
inputModel.alt ||
inputModel.shift ||
inputModel.command;
if (!_pin && !hasModifierOn && !widget.requestShow) {
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) {
gFFI.cursorModel
.keyHelpToolsVisibilityChanged(null, widget.keyboardIsVisible);
return Offstage();
@@ -18,8 +18,10 @@ 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 {
@@ -897,6 +899,24 @@ 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')),
@@ -11,10 +11,3 @@ const terminalKeyboardKeySpacing = 2.0;
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
const terminalKeyboardRow3TrailingPlaceholderCount = 2;
/// Returns the fixed width occupied by a row of equally sized key slots.
double terminalKeyboardRowWidth(int slotCount) {
if (slotCount <= 0) return 0;
return slotCount * terminalKeyboardKeyWidth +
(slotCount - 1) * terminalKeyboardKeySpacing;
}
@@ -372,6 +372,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
Offset _position = Offset.zero;
bool _isInitialized = false;
bool _isDown = false;
Object? _activePress;
bool _remoteButtonDown = false;
Rect? _lastBlockedRect;
Orientation? _previousOrientation;
@@ -398,6 +400,11 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
@override
void dispose() {
_activePress = null;
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
if (_lastBlockedRect != null) {
_cursorModel.removeBlockedRect(_lastBlockedRect!);
}
@@ -569,6 +576,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
child: Listener(
onPointerMove: _onBodyPointerMoveUpdate,
onPointerDown: (event) async {
final press = Object();
_activePress = press;
_isDragging = false;
setState(() {
_isDown = true;
@@ -579,6 +588,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = true;
() async {
await _cursorModel.syncCursorPosition();
if (!mounted || !identical(_activePress, press)) return;
_remoteButtonDown = true;
await _inputModel
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
}();
@@ -586,6 +597,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
});
},
onPointerUp: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
@@ -604,8 +617,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
}));
} else {
// If it's not a quick tap, it could be a hold or drag.
// If it was a hold, isSpecialHoldDragActive is true.
if (isSpecialHoldDragActive) {
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
@@ -617,13 +630,16 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = false;
},
onPointerCancel: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
});
_tapDownTimer?.cancel();
_tapDownTimer = null;
if (isSpecialHoldDragActive) {
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
isSpecialHoldDragActive = false;
+65 -5
View File
@@ -64,8 +64,11 @@ 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;
@@ -80,6 +83,8 @@ class ChatModel with ChangeNotifier {
@override
void dispose() {
inputNode.removeListener(_updateChatInputControl);
_restoreChatInputControl();
textController.dispose();
super.dispose();
}
@@ -194,13 +199,18 @@ class ChatModel with ChangeNotifier {
}
}
showChatWindowOverlay({Offset? chatInitPos}) {
showChatWindowOverlay(
{Offset? chatInitPos, bool requestSoftKeyboard = true}) {
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) {
@@ -209,7 +219,8 @@ class ChatModel with ChangeNotifier {
}
final overlay = OverlayEntry(builder: (context) {
return Listener(
onPointerDown: (_) {
onPointerDown: (event) {
_requestChatSoftKeyboard(event);
if (!isWindowFocus.value) {
isWindowFocus.value = true;
_blockableOverlayState.setMiddleBlocked(true);
@@ -223,6 +234,10 @@ class ChatModel with ChangeNotifier {
});
overlayState.insert(overlay);
chatWindowOverlayEntry = overlay;
if (isMobile && !requestSoftKeyboard) {
inputNode.addListener(_updateChatInputControl);
_updateChatInputControl();
}
requestChatInputFocus();
}
@@ -231,6 +246,9 @@ class ChatModel with ChangeNotifier {
_blockableOverlayState.setMiddleBlocked(false);
chatWindowOverlayEntry!.remove();
chatWindowOverlayEntry = null;
_softKeyboardRequested.value = false;
inputNode.removeListener(_updateChatInputControl);
_restoreChatInputControl();
return;
}
}
@@ -239,13 +257,14 @@ class ChatModel with ChangeNotifier {
((!(isDesktop || isWebDesktop) && chatIconOverlayEntry == null) ||
chatWindowOverlayEntry == null);
toggleChatOverlay({Offset? chatInitPos}) {
toggleChatOverlay({Offset? chatInitPos, bool requestSoftKeyboard = true}) {
if (_isChatOverlayHide()) {
gFFI.invokeMethod("enable_soft_keyboard", true);
if (!isMobile) gFFI.invokeMethod("enable_soft_keyboard", true);
if (!(isDesktop || isWebDesktop)) {
showChatIconOverlay();
}
showChatWindowOverlay(chatInitPos: chatInitPos);
showChatWindowOverlay(
chatInitPos: chatInitPos, requestSoftKeyboard: requestSoftKeyboard);
} else {
hideChatIconOverlay();
hideChatWindowOverlay();
@@ -522,6 +541,47 @@ 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;
}
+336 -4
View File
@@ -15,8 +15,11 @@ 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';
@@ -416,6 +419,14 @@ 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;
@@ -448,6 +459,7 @@ class InputModel {
// mouse
final isPhysicalMouse = false.obs;
int _lastButtons = 0;
int _pressedMouseButtons = 0;
Offset lastMousePos = Offset.zero;
int _lastWheelTsUs = 0;
@@ -736,7 +748,12 @@ class InputModel {
}
KeyEventResult handleRawKeyEvent(RawKeyEvent e) {
if (isViewOnly) return KeyEventResult.handled;
if (_localFlutterShortcuts.tryDispatchRaw(e)) return KeyEventResult.handled;
if (isViewOnly) {
if (isWeb && !isInputSourceFlutter) return KeyEventResult.ignored;
_tryDispatchRawFlutterShortcut(e, releaseModifiers: false);
return KeyEventResult.handled;
}
if (isViewCamera) return KeyEventResult.handled;
if (!isInputSourceFlutter) {
if (isDesktop) {
@@ -745,6 +762,7 @@ class InputModel {
return KeyEventResult.ignored;
}
}
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey, raw: true);
if (_relativeMouse.handleRawKeyEvent(e)) {
return KeyEventResult.handled;
@@ -812,8 +830,13 @@ 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);
}
@@ -821,7 +844,12 @@ class InputModel {
}
KeyEventResult handleKeyEvent(KeyEvent e) {
if (isViewOnly) return KeyEventResult.handled;
if (_localFlutterShortcuts.tryDispatch(e)) return KeyEventResult.handled;
if (isViewOnly) {
if (isWeb && !isInputSourceFlutter) return KeyEventResult.ignored;
_tryDispatchFlutterShortcut(e, releaseModifiers: false);
return KeyEventResult.handled;
}
if (isViewCamera) return KeyEventResult.handled;
if (!isInputSourceFlutter) {
if (isDesktop) {
@@ -830,6 +858,10 @@ 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 ||
@@ -910,6 +942,14 @@ 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 ?? '',
@@ -918,12 +958,285 @@ 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) {
@@ -1076,6 +1389,10 @@ class InputModel {
}
}
_lastButtons = hasStaleButtonsOnMouseUp ? 0 : evt.buttons;
if (isDesktop && _relativeMouse.enabled.value && type == _kMouseEventUp) {
// A relative up can finish a press sent before the mode switch.
_pressedMouseButtons &= ~buttons;
}
out['buttons'] = buttons;
out['type'] = type;
@@ -1108,6 +1425,7 @@ 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.
@@ -1821,9 +2139,16 @@ class InputModel {
bool edgeScroll = false,
}) {
if (isViewCamera) return null;
final buttons = evt['buttons'];
final isMatchingMouseUp = (isDesktop || isWebDesktop) &&
evt['type'] == _kMouseEventUp &&
buttons is int &&
mouseButtonsToPeer(buttons).isNotEmpty &&
_pressedMouseButtons & buttons != 0;
double x = offset.dx;
double y = max(0.0, offset.dy);
if (_checkPeerControlProtected(x, y)) {
// Cursor ownership may change between a forwarded down and its up.
if (_checkPeerControlProtected(x, y) && !isMatchingMouseUp) {
return null;
}
@@ -1865,6 +2190,9 @@ class InputModel {
if (pos == null) {
return null;
}
if (isMatchingMouseUp) {
_pressedMouseButtons &= ~buttons;
}
if (type != '') {
evt['x'] = '0';
evt['y'] = '0';
@@ -1873,9 +2201,13 @@ class InputModel {
evt['y'] = '${pos.y.toInt()}';
}
final buttons = evt['buttons'];
if (buttons is int) {
evt['buttons'] = mouseButtonsToPeer(buttons);
if ((isDesktop || isWebDesktop) &&
type == kMouseEventTypeDown &&
evt['buttons'] != '') {
_pressedMouseButtons |= buttons;
}
} else {
// Log warning if buttons exists but is not an int (unexpected caller).
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
@@ -0,0 +1,211 @@
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');
}
}
}
+288 -52
View File
@@ -21,6 +21,7 @@ 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';
@@ -58,7 +59,8 @@ const _restartReconnectSilentDelaySecs = 5;
class CachedPeerData {
Map<String, dynamic> updatePrivacyMode = {};
Map<String, dynamic> peerInfo = {};
List<Map<String, dynamic>> cursorDataList = [];
// No shapes: the core keeps them for the session, and the window a tab moves to asks it
// for the one in use.
Map<String, dynamic> lastCursorId = {};
Map<String, bool> permissions = {};
@@ -73,7 +75,6 @@ class CachedPeerData {
return jsonEncode({
'updatePrivacyMode': updatePrivacyMode,
'peerInfo': peerInfo,
'cursorDataList': cursorDataList,
'lastCursorId': lastCursorId,
'permissions': permissions,
'secure': secure,
@@ -88,9 +89,6 @@ class CachedPeerData {
final data = CachedPeerData();
data.updatePrivacyMode = map['updatePrivacyMode'];
data.peerInfo = map['peerInfo'];
for (final cursorData in map['cursorDataList']) {
data.cursorDataList.add(cursorData);
}
data.lastCursorId = map['lastCursorId'];
map['permissions'].forEach((key, value) {
data.permissions[key] = value;
@@ -323,10 +321,6 @@ class FfiModel with ChangeNotifier {
updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
setConnectionType(peerId, data.secure, data.direct, data.streamType);
await handlePeerInfo(data.peerInfo, peerId, true);
for (final element in data.cursorDataList) {
updateLastCursorId(element);
await handleCursorData(element);
}
if (data.lastCursorId.isNotEmpty) {
updateLastCursorId(data.lastCursorId);
handleCursorId(data.lastCursorId);
@@ -356,9 +350,6 @@ class FfiModel with ChangeNotifier {
} else if (name == 'switch_display') {
// switch display is kept for backward compatibility
handleSwitchDisplay(evt, sessionId, peerId);
} else if (name == 'cursor_data') {
updateLastCursorId(evt);
await handleCursorData(evt);
} else if (name == 'cursor_id') {
updateLastCursorId(evt);
handleCursorId(evt);
@@ -479,6 +470,11 @@ 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');
}
@@ -1437,9 +1433,9 @@ class FfiModel with ChangeNotifier {
}
// After reconnecting, restore the last selected monitor once the canvas is ready.
// Switching earlier can offset the view if the monitor sizes differ.
final last = lastUserDisplay;
// New monitor windows keep their selection in currentDisplay.
final last = lastUserDisplay ?? _pi.currentDisplay;
pendingMonitorRestore = (!isCache &&
last != null &&
last != currentDisplay &&
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
sessionId: sessionId) !=
@@ -1662,9 +1658,14 @@ class FfiModel with ChangeNotifier {
parent.target?.cursorModel.updateCursorId(evt);
}
handleCursorData(Map<String, dynamic> evt) async {
cachedPeerData.cursorDataList.add(evt);
await parent.target?.cursorModel.updateCursorData(evt);
/// A shape arriving is the shape in use, as a cursor_id is.
handleCursorData(String id, int hotx, int hoty, int width, int height,
Uint8List colors) async {
// The replay selects this last, whatever the order the shapes are replayed in.
cachedPeerData.lastCursorId = {'id': id};
parent.target?.cursorModel.id = id;
await parent.target?.cursorModel
.updateCursorData(id, hotx, hoty, width, height, colors);
}
/// Handle the peer info synchronization event based on [evt].
@@ -2858,12 +2859,13 @@ class CanvasModel with ChangeNotifier {
// data for cursor
class CursorData {
// At most 4 MiB of RGBA, including Linux's square cursor padding.
static const _maxRasterSize = 1024;
// At most 1 MiB of RGBA, including Linux's square cursor padding: twice the largest
// accessibility cursor, beyond which a cursor is shown smaller rather than larger.
static const _maxRasterSize = 512;
final String peerId;
final String id;
final img2.Image image;
img2.Image? _image;
double scale;
Uint8List? data;
final double hotxOrigin;
@@ -2879,17 +2881,28 @@ class CursorData {
int get rasterWidth => _rasterWidth;
int get rasterHeight => _rasterHeight;
img2.Image get image => _image!;
/// False for a shape not in use; only the shape in use keeps pixels, for a new raster.
bool get hasPixels => _image != null;
void releasePixels() {
_image = null;
data = null;
}
CursorData({
required this.peerId,
required this.id,
required this.image,
required img2.Image image,
required this.scale,
required this.data,
required this.hotxOrigin,
required this.hotyOrigin,
required this.width,
required this.height,
}) : _rasterWidth = (width * scale).ceil(),
}) : _image = image,
_rasterWidth = (width * scale).ceil(),
_rasterHeight = (height * scale).ceil(),
hotx = hotxOrigin * scale,
hoty = hotyOrigin * scale;
@@ -2921,6 +2934,13 @@ class CursorData {
final targetWidth = (width * scale).ceil();
final targetHeight = (height * scale).ceil();
if ((_rasterWidth != targetWidth || _rasterHeight != targetHeight) &&
!hasPixels) {
// Nothing to make this raster from; buildCursorOfCache asks for the pixels unless its
// native cursor was made before.
data = null;
return scale;
}
if (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
if (isWindows) {
data = img2
@@ -2991,7 +3011,9 @@ class CursorData {
String updateGetKey(double scale) {
scale = _checkUpdateScale(scale);
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${rasterWidth}_$rasterHeight';
// 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()}';
}
}
@@ -3162,7 +3184,16 @@ class CursorModel with ChangeNotifier {
get lastIsBlocked => _lastIsBlocked;
ui.Image? get image => _image;
/// The image of the shape in use, or the one shown before until it is back: a switch falls
/// back to the default cursor only for a shape the core cannot give. Asks the core for the
/// shape in use when it was let go.
ui.Image? get image {
if (_images[_id] == null && _cacheMap.containsKey(_id)) {
restorePixels(_id);
}
return _image;
}
CursorData? get cache => _cache;
double get x => _x - _displayOriginX;
@@ -3175,7 +3206,10 @@ class CursorModel with ChangeNotifier {
double get hotx => _hotx;
double get hoty => _hoty;
set id(String id) => _id = id;
set id(String id) {
if (_id != id) _unavailable = null;
_id = id;
}
bool get isPeerControlProtected =>
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
@@ -3190,7 +3224,12 @@ class CursorModel with ChangeNotifier {
}
}
CursorModel(this.parent);
CursorModel(this.parent) {
// Made now, not when first drawn: nothing draws again when their decode lands, so the first
// build that needs one would show the shape before in its place.
preDefaultCursor.cache;
preForbiddenCursor.cache;
}
Set<String> get cachedKeys => _cacheKeys;
addKey(String key) => _cacheKeys.add(key);
@@ -3489,30 +3528,44 @@ class CursorModel with ChangeNotifier {
_images.clear();
}
updateCursorData(Map<String, dynamic> evt) async {
final id = evt['id'];
final hotx = double.parse(evt['hotx']);
final hoty = double.parse(evt['hoty']);
final width = int.parse(evt['width']);
final height = int.parse(evt['height']);
List<dynamic> colors = json.decode(evt['colors']);
final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
/// Its image is kept with the ones used last, see [_imageLimit]; a shape that does not decode
/// is marked as one the core cannot give.
Future<void> updateCursorData(String id, int hotxInt, int hotyInt, int width,
int height, Uint8List rgba) async {
final generation = _generation;
if (_unavailable == id) _unavailable = null;
final hotx = hotxInt.toDouble();
final hoty = hotyInt.toDouble();
final image = await img.decodeImageFromPixels(
rgba, width, height, ui.PixelFormat.rgba8888);
if (image == null) {
// It did not decode; painting must not ask for it on every frame.
_markUnavailable(generation, id);
return;
}
if (await _updateCache(rgba, image, id, hotx, hoty, width, height)) {
_images[id]?.item1.dispose();
_images[id] = Tuple3(image, hotx, hoty);
if (!await _updateCache(
generation, rgba, image, id, hotx, hoty, width, height)) {
// Not kept, or the session was cleared while it decoded.
image.dispose();
_markUnavailable(generation, id);
return;
}
final old = _images.remove(id);
_images[id] = Tuple3(image, hotx, hoty);
if (old != null) {
if (identical(old.item1, _image)) _image = image;
old.item1.dispose();
}
// Update last cursor data.
// Do not use the previous `image` and `id`, because `_id` may be changed.
_updateCurData();
final cache = _cacheMap[id];
if (id != _id && cache != null) _switchedAway(cache);
}
Future<bool> _updateCache(
int generation,
Uint8List rgba,
ui.Image image,
String id,
@@ -3523,7 +3576,11 @@ class CursorModel with ChangeNotifier {
) async {
Uint8List? data;
img2.Image imgOrigin = img2.Image.fromBytes(
width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
width: w,
height: h,
bytes: rgba.buffer,
bytesOffset: rgba.offsetInBytes,
order: img2.ChannelOrder.rgba);
if (isWindows) {
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
} else {
@@ -3556,34 +3613,200 @@ class CursorModel with ChangeNotifier {
width: w,
height: h,
);
if (generation != _generation) {
return false;
}
_cacheMap[id] = cache;
return true;
}
@visibleForTesting
Iterable<String> get shapeIds => _images.keys;
@visibleForTesting
CursorData? cachedShape(String id) => _cacheMap[id];
final _restoring = <String>{};
// Tabs in a window share its engine's native cursors, predefined ones included.
static int _nextKeyScope = 0;
final int _keyScope = _nextKeyScope++;
String nativeKey(CursorData cache, double scale) {
final key = '${_keyScope}_${cache.updateGetKey(scale)}';
// A native cursor at another raster does not hold the pixels this one is made from.
if (!_cacheKeys.contains(key)) _nativeIds.remove(cache.id);
return key;
}
// Native cursors stay for the session, one per raster of each shape, and only [clear]
// deletes them, as before; unlike the painted images they have no LRU, for now. A delete
// frees nothing on Windows: the engine's `deleteCustomCursor/windows` releases the HCURSOR
// with `DeleteObject`, which does not take a cursor. Measured on Windows with 500 cursors
// made by `CreateIconIndirect`, as the engine makes them: `DeleteObject` failed all 500 and
// left 500 USER objects alive, while `DestroyCursor` or `DestroyIcon` freed all 500. Each
// delete leaks its handle until the process exits, and making the cursor again for a raster
// or a shape shown once more leaks another, so an LRU would leak more than keeping them.
//
// Fixing the engine is not cheap. x64 runs our fork, rustdesk/engine, on Flutter 3.24; the
// fix is one more patch to rebuild, publish, and carry across every Flutter upgrade. arm64
// runs the stock engine of a newer Flutter, which has the same code: fixing it means
// porting the fork to that version and building and publishing an arm64 engine as well, or
// an upstream fix and waiting for it to reach stable. Once both engines destroy cursors, an
// LRU like the painted images' can come back. Content ids keep the count to the shapes the
// peer really shows, a few dozen to a couple of hundred.
/// The shape in use keeps its pixels, so a new raster is made from them at once; the others
/// keep none once their native cursor holds them.
void registered(CursorData cache, String key) {
_nativeIds.add(cache.id);
_awaitingNative.remove(cache.id);
if (cache.id != _id && identical(_cacheMap[cache.id], cache)) {
cache.releasePixels();
}
}
// The shapes a native cursor holds, and those keeping their pixels until one does, oldest
// first: one decoded after the peer moved on must still get a native cursor when shown
// again, rather than be decoded again every time it comes back.
final _nativeIds = <String>{};
final _awaitingNative = <String>{};
void _switchedAway(CursorData cache) {
_awaitingNative.remove(cache.id);
// Mobile only paints the cursor, from its image.
if (isMobile || _nativeIds.contains(cache.id)) {
cache.releasePixels();
return;
}
_awaitingNative.add(cache.id);
while (_awaitingNative.length > kRecentShapes) {
final oldest = _awaitingNative.first;
_awaitingNative.remove(oldest);
if (oldest != _id) _cacheMap[oldest]?.releasePixels();
}
}
/// The peer's shapes used last that keep a painted image, and the most that keep their pixels
/// waiting for a native cursor; the core rebuilds the others. An animated cursor is a shape per
/// frame, 18 for the Windows busy cursor and 23 for KDE's, and a cycle longer than this limit
/// would rebuild every frame.
static const kRecentShapes = 64;
/// The native cursor of the shape shown last, shown on while the shape in use is made.
String? shownKey;
void shown(CursorData cache, String key) {
// The forbidden cursor shows only while input is off; it is no stand-in for a shape.
if (cache.id != kPreForbiddenCursorId) shownKey = key;
}
/// Whether the desktop paints the peer's cursor over the remote image.
@protected
bool get showsRemoteCursor {
final tag = ShowRemoteCursorState.tag(parent.target?.id ?? '');
return Get.isRegistered<RxBool>(tag: tag) &&
Get.find<RxBool>(tag: tag).value;
}
// Painted images kept: mobile always paints the cursor, a desktop only when it shows the
// remote cursor, and otherwise the native cursors show the shapes.
int get _imageLimit => isMobile || showsRemoteCursor ? kRecentShapes : 1;
// `_images` is in order of use. The image painted is kept, whoever's it is.
void _evictImages() {
var excess = _images.length - _imageLimit;
_images.removeWhere((id, shape) {
if (excess <= 0 || id == _id || identical(shape.item1, _image)) {
return false;
}
excess--;
shape.item1.dispose();
return true;
});
}
/// The core keeps every shape the peer sent, compressed; see `Session::cursor_shapes`.
@protected
Future<CursorShape?> fetchCursorShape(String id) {
final ffi = parent.target;
if (ffi == null) return Future.value(null);
return bind.sessionGetCursorShape(sessionId: ffi.sessionId, id: id);
}
// The shape the core could not give, not asked for again while it is the one in use. One
// is enough: only the shape in use is asked for on every frame, and the peer's ids must not
// accumulate here.
String? _unavailable;
// Counts session clears, so that a decode finishing after one keeps nothing.
int _generation = 0;
/// Decodes the shape in use again from the core, for a raster its native cursor lacks, for
/// painting it, or for a window a tab moved to.
void restorePixels(String id) {
if (id != _id || _unavailable == id || !_restoring.add(id)) return;
final generation = _generation;
() async {
try {
// A throw becomes an error the await hands over later, not during the build that may
// have asked: a failure tells the listeners.
final shape = await Future.sync(() => fetchCursorShape(id));
if (generation != _generation) {
return;
} else if (shape == null) {
_markUnavailable(generation, id);
debugPrint('Cursor $id is not kept by the core');
} else {
// Decoded even if the peer moved on: an animation comes back to it.
await updateCursorData(id, shape.hotx, shape.hoty, shape.width,
shape.height, shape.colors);
}
} catch (e) {
_markUnavailable(generation, id);
debugPrint('Failed to fetch cursor $id: $e');
} finally {
_restoring.remove(id);
}
}();
}
void _markUnavailable(int generation, String id) {
if (generation != _generation || id != _id) return;
_unavailable = id;
_updateCurData();
}
bool _updateCurData() {
_cache = _cacheMap[_id];
final tmp = _images[_id];
final previous = _cache;
final cache = _cacheMap[_id];
// A shape not decoded yet leaves the one shown before in place until it is; one the core
// cannot give leaves none, so the default cursor shows, as for a shape never sent.
if (cache != null || _unavailable == _id) _cache = cache;
if (previous != null && !identical(previous, _cache)) {
_switchedAway(previous);
}
final tmp = _images.remove(_id);
if (tmp != null) {
_images[_id] = tmp;
_image = tmp.item1;
_hotx = tmp.item2;
_hoty = tmp.item3;
try {
// may throw exception, because the listener maybe already dispose
notifyListeners();
} catch (e) {
debugPrint(
'WARNING: updateCursorId $_id, without notifyListeners(). $e');
}
return true;
} else {
return false;
} else if (_unavailable == _id) {
_image = null;
}
_evictImages();
try {
// may throw exception, because the listener maybe already dispose
notifyListeners();
} catch (e) {
debugPrint('WARNING: updateCursorId $_id, without notifyListeners(). $e');
}
return tmp != null || cache != null;
}
updateCursorId(Map<String, dynamic> evt) {
if (!_updateCurData()) {
debugPrint(
'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
restorePixels(_id);
}
}
@@ -3636,6 +3859,10 @@ class CursorModel with ChangeNotifier {
_clearCache();
_cache = null;
_cacheMap.clear();
_nativeIds.clear();
_awaitingNative.clear();
_unavailable = null;
_generation++;
}
_clearCache() {
@@ -3644,6 +3871,8 @@ class CursorModel with ChangeNotifier {
debugPrint("deleting cursor with key $k");
deleteCustomCursor(k);
}
_cacheKeys.clear();
shownKey = null;
resetSystemCursor();
}
@@ -3825,6 +4054,7 @@ 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
@@ -3854,6 +4084,7 @@ 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,
@@ -3983,6 +4214,7 @@ class FFI {
}
if (isWeb) {
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
platformFFI.setRgbaCallback((int display, Uint8List data) {
onEvent2UIRgba();
imageModel.onRgba(display, data);
@@ -4065,6 +4297,9 @@ class FFI {
} else {
platformFFI.nextRgba(sessionId, display);
}
} else if (message is EventToUI_Cursor) {
await ffiModel.handleCursorData(message.id, message.hotx,
message.hoty, message.width, message.height, message.colors);
} else if (message is EventToUI_Texture) {
final display = message.field0;
final gpuTexture = message.field1;
@@ -4159,6 +4394,7 @@ class FFI {
ffiModel.pi.currentDisplay);
}
imageModel.callbacksOnFirstImage.clear();
shortcutModel.clear();
await imageModel.update(null);
cursorModel.clear();
ffiModel.clear();
+7
View File
@@ -59,6 +59,9 @@ 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;
@@ -285,6 +288,10 @@ class PlatformFFI {
void setRgbaCallback(void Function(int, Uint8List) fun) async {}
// web only
void setCursorDataCallback(
void Function(String, int, int, int, int, Uint8List) fun) async {}
// web only, decoded WebCodecs frames arriving as ready-made images
void setVideoFrameCallback(
Future<void> Function(int, ui.Image, bool Function()) fun) {}
+669
View File
@@ -0,0 +1,669 @@
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,10 +70,6 @@ class TerminalModel with ChangeNotifier {
final _inputBuffer = <String>[];
/// Exposes buffered input only for lifecycle regression tests.
@visibleForTesting
int get debugBufferedInputCount => _inputBuffer.length;
// Buffer for output data received before terminal view has valid dimensions.
// This prevents NaN errors when writing to terminal before layout is complete.
final _pendingOutputChunks = <String>[];
@@ -9,6 +9,7 @@ import 'platform_model.dart';
import 'rustdesk_terminal.dart';
import 'terminal_copy_shortcut.dart';
import 'terminal_mouse_drag_reporter.dart';
import 'terminal_scroll_controller.dart';
part 'terminal_mouse_handler_input.dart';
part 'terminal_web_clipboard_gesture.dart';
@@ -55,7 +56,7 @@ class _TerminalMouseInteractionState extends State<TerminalMouseInteraction> {
static const _scrollDown = 1;
final _terminalViewKey = GlobalKey<TerminalViewState>();
final _scrollController = ScrollController();
late final _scrollController = TerminalScrollController(() => widget.terminal);
final _mouseDrag = TerminalMouseDragReporter();
late final WheelButtonFixMouseHandler _mouseHandler;
TerminalMouseHandler? _previousMouseHandler;
@@ -0,0 +1,36 @@
import 'package:flutter/widgets.dart';
import 'package:xterm/xterm.dart';
class TerminalScrollController extends ScrollController {
TerminalScrollController(this.terminal);
final Terminal Function() terminal;
@override
ScrollPosition createScrollPosition(ScrollPhysics physics,
ScrollContext context, ScrollPosition? oldPosition) {
return super.createScrollPosition(
_TerminalScrollPhysics(terminal, parent: physics),
context,
oldPosition,
);
}
}
class _TerminalScrollPhysics extends ScrollPhysics {
const _TerminalScrollPhysics(this.terminal, {super.parent});
final Terminal Function() terminal;
@override
_TerminalScrollPhysics applyTo(ScrollPhysics? ancestor) =>
_TerminalScrollPhysics(terminal, parent: buildParent(ancestor));
@override
bool shouldAcceptUserOffset(ScrollMetrics position) {
// A retained main-screen offset can make this inner scrollable win the
// trackpad gesture, starving xterm's outer alternate-screen scroll handler.
if (terminal().isUsingAltBuffer) return false;
return super.shouldAcceptUserOffset(position);
}
}
+12
View File
@@ -153,6 +153,7 @@ class PlatformFFI {
gFFI.dialogManager.dismissAll();
closeConnection();
};
await _ffiBind.mainInit(appDir: '');
context.callMethod('init');
version = getByName('version');
window.onContextMenu.listen((event) {
@@ -189,6 +190,17 @@ class PlatformFFI {
};
}
// The web core calls this with a shape's pixels as bytes, as it calls onRgba for a frame.
void setCursorDataCallback(
void Function(String, int, int, int, int, Uint8List) fun) {
context["onCursorData"] = (String id, int hotx, int hoty, int width,
int height, Uint8List? rgba) {
if (rgba != null) {
fun(id, hotx, hoty, width, height, rgba);
}
};
}
late final WebVideoFrameQueue<JSObject, ui.Image> _videoFrameQueue;
// Zero-readback video path: the JS decoder hands decoded VideoFrames here
+14 -3
View File
@@ -16,14 +16,15 @@ resetSystemCursor() {}
MouseCursor buildCursorOfCache(
CursorModel cursor, double scale, CursorData? cache) {
if (cache == null) {
return MouseCursor.defer;
return _shownCursor(cursor);
} else {
final key = cache.updateGetKey(scale);
final key = cursor.nativeKey(cache, scale);
if (!cursor.cachedKeys.contains(key)) {
// data should be checked here, because it may be changed after `updateGetKey()`
final data = cache.data;
if (data == null) {
return MouseCursor.defer;
cursor.restorePixels(cache.id);
return _shownCursor(cursor);
}
// Square canvases avoid clipping or stray edge pixels on Linux.
final width = isLinux && cache.rasterWidth < cache.rasterHeight
@@ -48,11 +49,21 @@ MouseCursor buildCursorOfCache(
..hotX = cache.hotx
..hotY = cache.hoty);
cursor.addKey(key);
cursor.registered(cache, key);
}
cursor.shown(cache, key);
return FlutterCustomMemoryImageCursor(key: key);
}
}
// The last shape's cursor stays while the one in use is made, rather than the system one.
MouseCursor _shownCursor(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) {
+100 -1
View File
@@ -7,6 +7,7 @@ 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');
@@ -26,6 +27,14 @@ sealed class EventToUI {
int field0,
bool field1,
) = EventToUI_Texture;
const factory EventToUI.cursor({
required String id,
required int hotx,
required int hoty,
required int width,
required int height,
required Uint8List colors,
}) = EventToUI_Cursor;
}
class EventToUI_Event implements EventToUI {
@@ -50,7 +59,60 @@ class EventToUI_Texture implements EventToUI {
bool get field1 => f1;
}
class EventToUI_Cursor implements EventToUI {
const EventToUI_Cursor({
required this.id,
required this.hotx,
required this.hoty,
required this.width,
required this.height,
required this.colors,
});
final String id;
final int hotx;
final int hoty;
final int width;
final int height;
final Uint8List colors;
}
class CursorShape {
final int hotx;
final int hoty;
final int width;
final int height;
final Uint8List colors;
const CursorShape({
required this.hotx,
required this.hoty,
required this.width,
required this.height,
required this.colors,
});
}
class RustdeskImpl {
// The core answers through the callback, before callMethod returns.
Future<CursorShape?> sessionGetCursorShape(
{required UuidValue sessionId, required String id, dynamic hint}) {
final completer = Completer<CursorShape?>();
js.context.callMethod('getCursorShape', [
id,
(int hotx, int hoty, int width, int height, Uint8List? colors) {
completer.complete(colors == null
? null
: CursorShape(
hotx: hotx,
hoty: hoty,
width: width,
height: height,
colors: colors));
}
]);
return completer.future;
}
Future<void> stopGlobalEventStream({required String appType, dynamic hint}) {
throw UnimplementedError("stopGlobalEventStream");
}
@@ -901,7 +963,11 @@ class RustdeskImpl {
}
String mainGetLocalOption({required String key, dynamic hint}) {
return js.context.callMethod('getByName', ['option:local', key]);
final v = js.context.callMethod('getByName', ['option:local', key]);
if (key == 'lang' && (v == 'pt' || v == 'br')) {
return 'pt-br';
}
return v;
}
// Do not return the real environment variables.
@@ -926,6 +992,28 @@ 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']);
@@ -1172,6 +1260,17 @@ 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();
}
+14 -3
View File
@@ -102,14 +102,15 @@ resetSystemCursor() => CursorManager.instance.resetSystemCursor();
MouseCursor buildCursorOfCache(
model.CursorModel cursor, double scale, model.CursorData? cache) {
if (cache == null) {
return MouseCursor.defer;
return _shownCursor(cursor);
} else {
final key = cache.updateGetKey(scale);
final key = cursor.nativeKey(cache, scale);
if (!cursor.cachedKeys.contains(key)) {
// data should be checked here, because it may be changed after `updateGetKey()`
final data = cache.data;
if (data == null) {
return MouseCursor.defer;
cursor.restorePixels(cache.id);
return _shownCursor(cursor);
}
debugPrint(
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
@@ -121,7 +122,17 @@ MouseCursor buildCursorOfCache(
hotX: cache.hotx,
hotY: cache.hoty));
cursor.addKey(key);
cursor.registered(cache, key);
}
cursor.shown(cache, key);
return FlutterCustomMemoryImageCursor(key: key);
}
}
// The last shape's cursor stays while the one in use is made, rather than the system one.
MouseCursor _shownCursor(model.CursorModel cursor) {
final key = cursor.shownKey;
return key == null
? MouseCursor.defer
: FlutterCustomMemoryImageCursor(key: key);
}
+2 -2
View File
@@ -339,8 +339,8 @@ packages:
dependency: "direct main"
description:
path: "."
ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
resolved-ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
resolved-ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
source: git
version: "0.1.0"
+2 -2
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.0+68
version: 1.5.1+68
environment:
sdk: '^3.1.0'
@@ -58,7 +58,7 @@ dependencies:
desktop_multi_window:
git:
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
ref: 8b774a66671cbb9bcb2631af6ac28f9bdd469ce3
ref: cddc2e64f8fefce4f80db87b20bcda2dd019bed6
freezed_annotation: ^2.0.3
flutter_custom_cursor:
git:
@@ -48,74 +48,6 @@ void main() {
expect(peers.single.online, isTrue);
});
test('peer copies preserve online state', () {
final peer = _peer(id: '987654321', online: true);
expect(Peer.copy(peer).online, isTrue);
});
test('online callbacks update autocomplete-only peers', () {
final peers = mergeAutocompletePeers(restRecentPeerIds: ['112233445']);
final changed = updateAutocompletePeerOnlineStates(
peers,
onlines: {'112233445'},
offlines: {},
);
expect(changed, isTrue);
expect(peers.single.online, isTrue);
});
test('online query ids are deduplicated and limited', () {
final peers = List.generate(
25,
(index) => _peer(id: index.toString()),
)..insert(1, _peer(id: '0'));
final ids = autocompleteOnlineQueryIds(peers, limit: 20);
expect(ids, hasLength(20));
expect(ids.first, '0');
expect(ids.where((id) => id == '0'), hasLength(1));
expect(ids.last, '19');
});
test('empty online query ids cancel pending debounce', () async {
final queriedIds = <List<String>>[];
final loader = AllPeersLoader(
queryOnlines: (ids) async {
queriedIds.add(ids);
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
loader.queryOnlines([]);
await Future.delayed(Duration(milliseconds: 2));
expect(queriedIds, isEmpty);
});
test('failed online query enqueue does not suppress retry', () async {
var queryCount = 0;
final loader = AllPeersLoader(
queryOnlines: (ids) {
queryCount += 1;
return Future<void>.error(Exception('queue full'));
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
expect(queryCount, 2);
});
test('online callback updates currently displayed options', () async {
final loader = AllPeersLoader(
queryOnlines: (ids) async {},
@@ -132,17 +64,4 @@ void main() {
expect(displayedOptions.single.online, isTrue);
await Future.delayed(Duration(milliseconds: 2));
});
test('cached online callback state is reapplied after peers merge', () {
final loader = AllPeersLoader();
loader.updateOnlineStateForTesting({
'onlines': '123456789',
'offlines': '',
});
final mergedPeers = [_peer(id: '123456789')];
loader.applyLastOnlineStateForTesting(mergedPeers);
expect(mergedPeers.single.online, isTrue);
});
}
-20
View File
@@ -1,20 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'cm_demo.dart' as cm_demo;
void main() {
test('connection manager demo clients match the current Client API', () {
expect(cm_demo.testClients, hasLength(4));
expect(cm_demo.testClients.map((client) => client.name), [
'UserAAAAAA',
'UserBBBBB',
'UserC',
'UserDDDDDDDDDDDd',
]);
expect(
cm_demo.testClients.every(
(client) => client.keyboard && !client.clipboard && !client.audio),
isTrue,
);
});
}
+66
View File
@@ -0,0 +1,66 @@
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
// A file of its own: nothing else in this isolate has made the default cursor before the model.
/// A core that keeps no shape.
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
@override
Future<CursorShape?> fetchCursorShape(String id) => Future.value(null);
@override
bool get showsRemoteCursor => false;
}
class _FFI extends Fake implements FFI {
_FFI() {
ffiModel = FfiModel(WeakReference(this));
cursorModel = _Cursor(this);
}
@override
final SessionID sessionId = const Uuid().v4obj();
@override
late final FfiModel ffiModel;
@override
late final CursorModel cursorModel;
}
String? _key(MouseCursor cursor) =>
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final channel = Platform.isWindows
? SystemChannels.mouseCursor
: const MethodChannel('flutter_custom_cursor');
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
(call) async => (call.arguments as Map<dynamic, dynamic>)['name']);
test('a shape the core cannot give shows the default cursor at once',
() async {
final ffi = _FFI();
final cursor = ffi.cursorModel;
final pixels = Uint8List.fromList(List.generate(8 * 8 * 4, (i) => i % 256));
await ffi.ffiModel.handleCursorData('1', 0, 0, 8, 8, pixels);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
final evt = {'id': '2'};
ffi.ffiModel.updateLastCursorId(evt);
ffi.ffiModel.handleCursorId(evt);
// Not a wait for the default cursor itself: asking for it would make it.
await Future<void>.delayed(const Duration(milliseconds: 500));
expect(cursor.cache, isNull);
final built = _key(buildCursorOfCache(
cursor, 1.0, cursor.cache ?? preDefaultCursor.cache));
expect(built, isNot(shown));
expect(built, contains('_${kPreDefaultCursorId}_'));
cursor.disposeImages();
});
}
+225
View File
@@ -0,0 +1,225 @@
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)));
});
}
+20 -51
View File
@@ -1,4 +1,3 @@
import 'dart:convert';
import 'dart:io';
import 'dart:ui' as ui;
@@ -79,6 +78,8 @@ class _FFI extends Fake implements FFI {
final ffiModel = _Peer();
@override
final inputModel = _Input();
@override
var id = '';
}
class _Cursor extends CursorModel {
@@ -107,17 +108,11 @@ void main() {
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
for (final scenario in [
((4, 64), 0.5, (2, 32)),
((64, 4), 0.5, (32, 2)),
((1, 64), 0.25, (1, 16)),
((8, 8), 0.5, (12, 12)),
((4, 64), 1.0, (4, 64)),
((1, 512), 10.0, (2, 1024)),
]) {
test('native cursor size $scenario',
() => _checkSize(scenario, registrations));
}
test('native raster boundaries rebuild buffers and distinguish cache keys',
() => _checkRasterTransitions(registrations));
test('cursor resize limits preserve the last valid raster', () async {
for (final size in [(30, 20), (20, 30)]) {
await _checkResizeLimits(size, registrations);
@@ -131,15 +126,15 @@ void main() {
test('Windows peer cursor alpha survives resizing $pattern',
() => _checkWindowsPeerAlpha(pattern, registrations));
}
for (final style in [
kRemoteViewStyleOriginal,
kRemoteViewStyleAdaptive,
kRemoteViewStyleCustom
for (final (style, zoom) in [
(kRemoteViewStyleOriginal, false),
(kRemoteViewStyleAdaptive, false),
(kRemoteViewStyleAdaptive, true),
(kRemoteViewStyleCustom, false),
(kRemoteViewStyleCustom, true),
]) {
for (final zoom in [false, true]) {
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
}
@@ -181,15 +176,14 @@ Future<void> _checkWindowsPeerAlpha(
addTearDown(() => _dispose(cursor));
addTearDown(cursor.disposeImages);
addTearDown(ffi.canvasModel.dispose);
await cursor.updateCursorData({
'id': 'alpha',
'hotx': '0',
'hoty': '0',
'width': '$sourceSize',
'height': '$sourceSize',
'colors': jsonEncode(List.generate(sourceSize * sourceSize * channels,
(i) => pattern.$1[i % pattern.$1.length])),
});
await cursor.updateCursorData(
'alpha',
0,
0,
sourceSize,
sourceSize,
Uint8List.fromList(List.generate(sourceSize * sourceSize * channels,
(i) => pattern.$1[i % pattern.$1.length])));
buildCursorOfCache(cursor, 1.0 / dpr, cursor.cache);
await Future<void>.delayed(Duration.zero);
final args = registrations.single;
@@ -241,34 +235,9 @@ void _expectSize(Map<dynamic, dynamic> args, (int, int) expected) {
}
}
Future<void> _checkRasterTransitions(
List<Map<dynamic, dynamic>> registrations) async {
const delta = 3e-8;
const scaleAboveOne = (2.25 / 1.75) / 2.25 * 1.75;
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
final cursor = _Cursor(_data((64, 64)), ffi);
addTearDown(() => _dispose(cursor));
addTearDown(ffi.canvasModel.dispose);
for (final (scale, expected) in [
(scaleAboveOne, (65, 65)),
(0.5 - delta, (32, 32)),
(0.5 + delta, (33, 33)),
(1.0, (64, 64)),
(scaleAboveOne, (65, 65)),
(1.0, (64, 64)),
]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await Future<void>.delayed(Duration.zero);
final key = cursor.cache.updateGetKey(scale);
_expectSize(
registrations.singleWhere((args) => args['name'] == key), expected);
}
expect(registrations.length, 4);
}
Future<void> _checkResizeLimits(
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
const maxSide = 1024;
const maxSide = 512;
const sourceLongEdge = 30;
const validScale = maxSide / sourceLongEdge;
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
@@ -361,7 +330,7 @@ Future<void> _checkView(WidgetTester tester, (String, bool) mode,
mode.$1 != kRemoteViewStyleOriginal
? (sourceSize * (Platform.isWindows ? dpr : 1.0)).ceil()
: (size * scale * (Platform.isWindows ? dpr : 1.0)).ceil();
final key = cursor.cache.updateGetKey(cursor.cache.scale);
final key = cursor.nativeKey(cursor.cache, cursor.cache.scale);
_expectSize(registrations.singleWhere((v) => v['name'] == key), (w, w));
}
await tester.pumpWidget(const SizedBox.shrink());
-72
View File
@@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_hbb/models/file_model.dart';
@@ -62,19 +61,6 @@ void main() {
expect(directory.path, '/fast');
});
test('a send failure fails and removes its registered task', () async {
final failure = StateError('send failed');
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, __, ___) => Future<void>.error(failure),
);
await expectLater(
fileFetcher.fetchDirectory('/failed', false, false),
throwsA(same(failure)),
);
expect(fileFetcher.hasPendingRemoteRead('/failed'), isFalse);
});
test('a resolved Home path completes the sole empty-path request', () async {
final sent = <_SentRead>[];
final fileFetcher = FileFetcher(
@@ -107,35 +93,6 @@ void main() {
expect(controller.directory.value.path, '/home/user');
});
test('an exact path response is not taken by a pending Home request',
() async {
final sent = <_SentRead>[];
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, path, includeHidden) async {
sent.add(_SentRead(path, includeHidden));
},
);
final home = fileFetcher.fetchDirectory('', false, false);
final regular = fileFetcher.fetchDirectory('/regular', false, false);
await Future<void>.delayed(Duration.zero);
var homeCompleted = false;
home.then<void>((_) => homeCompleted = true);
fileFetcher.tryCompleteTask(_directoryJson('/unmatched'), 'false');
await Future<void>.delayed(Duration.zero);
expect(homeCompleted, isFalse);
fileFetcher.tryCompleteTask(_directoryJson('/regular'), 'false');
expect((await regular).path, '/regular');
await Future<void>.delayed(Duration.zero);
expect(homeCompleted, isFalse);
fileFetcher.tryCompleteTask(_directoryJson('/home/user'), 'false');
expect((await home).path, '/home/user');
expect(sent.map((request) => request.path), ['', '/regular']);
});
test('a read error completes the sole pending request', () async {
final fileFetcher = FileFetcher(
() => _sessionId,
@@ -230,35 +187,6 @@ void main() {
expect((await replacement).path, '/same');
});
test('a late dispatch failure cannot remove a replacement task', () async {
final dispatches = <Completer<void>>[];
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, __, ___) {
final dispatch = Completer<void>();
dispatches.add(dispatch);
return dispatch.future;
},
);
final first = fileFetcher.fetchDirectory('/same', false, false);
await Future<void>.delayed(Duration.zero);
final firstError = expectLater(first, throwsA(isA<StateError>()));
fileFetcher.beginRemoteSession();
await firstError;
final replacement = fileFetcher.fetchDirectory('/same', false, false);
await Future<void>.delayed(Duration.zero);
expect(dispatches, hasLength(2));
dispatches.first.completeError(StateError('late dispatch failure'));
await Future<void>.delayed(Duration.zero);
expect(fileFetcher.hasPendingRemoteRead('/same'), isTrue);
fileFetcher.tryCompleteTask(_directoryJson('/same'), 'false');
expect((await replacement).path, '/same');
dispatches.last.complete();
await Future<void>.delayed(Duration.zero);
});
test('navigation ignores stale directory responses', () async {
final fileFetcher = FileFetcher(
() => _sessionId,
+11
View File
@@ -0,0 +1,11 @@
[
{"action": "send_ctrl_alt_del", "mods": ["primary", "alt", "shift"], "key": "delete"},
{"action": "toggle_fullscreen", "mods": ["primary", "alt", "shift"], "key": "enter"},
{"action": "switch_display_next", "mods": ["primary", "alt", "shift"], "key": "arrow_right"},
{"action": "switch_display_prev", "mods": ["primary", "alt", "shift"], "key": "arrow_left"},
{"action": "screenshot", "mods": ["primary", "alt", "shift"], "key": "p"},
{"action": "toggle_show_remote_cursor", "mods": ["primary", "alt", "shift"], "key": "m"},
{"action": "toggle_mute", "mods": ["primary", "alt", "shift"], "key": "s"},
{"action": "toggle_block_input", "mods": ["primary", "alt", "shift"], "key": "i"},
{"action": "toggle_chat", "mods": ["primary", "alt", "shift"], "key": "c"}
]
+8
View File
@@ -0,0 +1,8 @@
[
"close_tab",
"switch_tab_next",
"switch_tab_prev",
"restart_remote",
"switch_sides",
"toggle_chat"
]
+65
View File
@@ -0,0 +1,65 @@
[
["a", 4],
["b", 5],
["c", 6],
["d", 7],
["e", 8],
["f", 9],
["g", 10],
["h", 11],
["i", 12],
["j", 13],
["k", 14],
["l", 15],
["m", 16],
["n", 17],
["o", 18],
["p", 19],
["q", 20],
["r", 21],
["s", 22],
["t", 23],
["u", 24],
["v", 25],
["w", 26],
["x", 27],
["y", 28],
["z", 29],
["digit1", 30],
["digit2", 31],
["digit3", 32],
["digit4", 33],
["digit5", 34],
["digit6", 35],
["digit7", 36],
["digit8", 37],
["digit9", 38],
["digit0", 39],
["f1", 58],
["f2", 59],
["f3", 60],
["f4", 61],
["f5", 62],
["f6", 63],
["f7", 64],
["f8", 65],
["f9", 66],
["f10", 67],
["f11", 68],
["f12", 69],
["delete", 76],
["backspace", 42],
["tab", 43],
["space", 44],
["enter", 40],
["enter", 88],
["arrow_left", 80],
["arrow_right", 79],
["arrow_up", 82],
["arrow_down", 81],
["home", 74],
["end", 77],
["page_up", 75],
["page_down", 78],
["insert", 73]
]
+11
View File
@@ -0,0 +1,11 @@
[
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"digit0", "digit1", "digit2", "digit3", "digit4",
"digit5", "digit6", "digit7", "digit8", "digit9",
"f1", "f2", "f3", "f4", "f5", "f6",
"f7", "f8", "f9", "f10", "f11", "f12",
"delete", "backspace", "tab", "space", "enter",
"arrow_left", "arrow_right", "arrow_up", "arrow_down",
"home", "end", "page_up", "page_down", "insert"
]
@@ -0,0 +1,99 @@
@TestOn('browser')
import 'dart:async';
import 'dart:js' as js;
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common/widgets/remote_input.dart';
import 'package:flutter_hbb/mobile/widgets/floating_mouse_widgets.dart';
import 'package:flutter_hbb/models/input_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_test/flutter_test.dart';
class _Input extends Fake implements InputModel {
final events = <(String, MouseButtons)>[];
@override
Future<void> tapDown(MouseButtons button) async =>
events.add(('down', button));
@override
Future<void> tapUp(MouseButtons button) async => events.add(('up', button));
}
class _FFI extends Fake implements FFI {}
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final syncs = <Completer<void>>[];
@override
Future<void> syncCursorPosition() {
final sync = Completer<void>();
syncs.add(sync);
return sync.future;
}
}
void main() {
setUp(() {
isSpecialHoldDragActive = false;
js.context['isMobile'] = js.allowInterop(() => true);
js.context['getByName'] =
js.allowInterop((String name, [String? key]) => '');
js.context['setByName'] = js.allowInterop((String name, dynamic value) {});
});
tearDown(() {
isSpecialHoldDragActive = false;
for (final name in ['isMobile', 'getByName', 'setByName']) {
js.context.deleteProperty(name);
}
});
for (final end in ['release', 'cancel', 'dispose']) {
testWidgets('pending hold cannot press after $end', (tester) async {
final cancel = end == 'cancel';
final ffi = _FFI();
final input = _Input();
final cursor = _Cursor(ffi);
final button = cancel ? MouseButtons.right : MouseButtons.left;
await tester.pumpWidget(MaterialApp(
home: Stack(children: [
FloatingLeftRightButton(
isLeft: !cancel, inputModel: input, cursorModel: cursor),
]),
));
await tester.pump();
final target = find.byType(FloatingLeftRightButton);
final first = await tester.startGesture(tester.getCenter(target));
await tester.pump(const Duration(milliseconds: 201));
expect(cursor.syncs, hasLength(1));
if (end == 'dispose') {
await tester.pumpWidget(const SizedBox());
cursor.syncs.single.complete();
await tester.pump(const Duration(milliseconds: 1));
expect(input.events, isEmpty);
return;
}
if (cancel) {
await first.cancel();
} else {
await first.up();
}
// A new press must not make the old synchronization valid again.
final second = await tester.startGesture(tester.getCenter(target));
await tester.pump(const Duration(milliseconds: 201));
cursor.syncs.first.complete();
await tester.pump();
expect(input.events, isEmpty);
cursor.syncs.last.complete();
await tester.pump();
expect(input.events, [('down', button)]);
await second.up();
expect(input.events, [('down', button), ('up', button)]);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(milliseconds: 1));
expect(input.events, [('down', button), ('up', button)]);
});
}
}
+1 -319
View File
@@ -4,19 +4,6 @@ import 'package:flutter_hbb/models/input_modifier_utils.dart';
void main() {
group('shouldReleaseStaleMobileShift', () {
test('does not release when cached shift is already false', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: false,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('releases one-shot mobile shift after a text key', () {
expect(
shouldReleaseStaleMobileShift(
@@ -30,20 +17,6 @@ void main() {
);
});
test('does not release manually toggled shift without tracked key down',
() {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: false,
),
isFalse,
);
});
test('does not release when shift is still physically pressed', () {
expect(
shouldReleaseStaleMobileShift(
@@ -56,84 +29,9 @@ void main() {
isFalse,
);
});
test('does not release on non-mobile platforms', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: false,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('releases on enter key', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.enter,
hasTrackedShiftKeyDown: true,
),
isTrue,
);
});
test('releases on arrow key', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.arrowLeft,
hasTrackedShiftKeyDown: true,
),
isTrue,
);
});
test('does not release on modifier events', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.shiftLeft,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('does not release on shiftRight modifier events', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.shiftRight,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
});
group('shouldApplyTerminalInputModifiers', () {
test('accepts ordinary single-character keyboard input', () {
expect(shouldApplyTerminalInputModifiers('a'), isTrue);
expect(shouldApplyTerminalInputModifiers(' '), isTrue);
expect(shouldApplyTerminalInputModifiers('/'), isTrue);
});
test('accepts supplementary-plane single-character keyboard input', () {
expect(shouldApplyTerminalInputModifiers('😀'), isTrue);
});
test('rejects terminal control bytes and multi-character sequences', () {
for (final input in ['\x00', '\x03', '\t', '\n', '\r', '\x1B', '\x7F']) {
expect(
@@ -147,43 +45,6 @@ void main() {
});
group('applyTerminalInputModifiers', () {
test('keeps decomposed graphemes intact under Ctrl', () {
const decomposedEAcute = 'e\u0301';
expect(
applyTerminalInputModifiers(
decomposedEAcute,
ctrlLocked: true,
altLocked: false,
),
decomposedEAcute,
);
});
test('keeps non-ASCII graphemes intact under Ctrl', () {
for (final input in ['é', '😀']) {
expect(
applyTerminalInputModifiers(
input,
ctrlLocked: true,
altLocked: false,
),
input,
);
}
});
test('maps Ctrl underscore to unit separator', () {
expect(
applyTerminalInputModifiers(
'_',
ctrlLocked: true,
altLocked: false,
),
'\x1F',
);
});
test('maps the complete Ctrl symbol range', () {
const mappings = {
'[': '\x1B',
@@ -219,22 +80,6 @@ void main() {
});
});
group('terminalPastePayload', () {
test('wraps paste text when bracketed paste mode is active', () {
expect(
terminalPastePayload('d', bracketedPasteMode: true),
'\x1B[200~d\x1B[201~',
);
});
test('keeps a lone newline unchanged when bracketed paste is disabled', () {
expect(
terminalPastePayload('\n', bracketedPasteMode: false),
'\n',
);
});
});
group('prepareTerminalInputPayload', () {
test('normalizes a mobile keyboard Enter to carriage return', () {
expect(
@@ -278,26 +123,9 @@ void main() {
);
});
test('keeps large keyboard payloads unchanged when modifiers are inactive',
() {
final payload = 'd' * (1024 * 1024);
expect(
prepareTerminalInputPayload(
payload,
source: TerminalInputSource.keyboard,
isMobileOrWebMobile: false,
bracketedPasteMode: false,
ctrlLocked: false,
altLocked: false,
),
payload,
);
});
test('keeps decomposed graphemes intact with locked keyboard modifiers',
() {
const decomposedEAcute = 'e\u0301';
const decomposedEAcute = 'é';
expect(
prepareTerminalInputPayload(
@@ -312,20 +140,6 @@ void main() {
);
});
test('preserves a lone pasted newline when modifiers are locked', () {
expect(
prepareTerminalInputPayload(
'\n',
source: TerminalInputSource.paste,
isMobileOrWebMobile: true,
bracketedPasteMode: false,
ctrlLocked: true,
altLocked: true,
),
'\n',
);
});
test('wraps paste without applying locked modifiers', () {
expect(
prepareTerminalInputPayload(
@@ -373,25 +187,6 @@ void main() {
);
});
test(
'keeps default xterm paste behavior when virtual modifiers are inactive',
() {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: false,
),
isFalse,
);
});
test('handles Ctrl+V and Meta+V when a virtual modifier lock is active',
() {
expect(
@@ -423,95 +218,6 @@ void main() {
isTrue,
);
});
test('handles paste shortcut repeats while a virtual lock is active', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: false,
isKeyRepeat: true,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isTrue,
);
});
test('ignores key-up and unmodified V events', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: false,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: false,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
});
test('ignores paste shortcuts with extra modifiers', () {
for (final state in [
(control: true, meta: false, alt: true, shift: false),
(control: true, meta: false, alt: false, shift: true),
(control: false, meta: true, alt: false, shift: true),
(control: true, meta: true, alt: false, shift: false),
]) {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: state.control,
metaPressed: state.meta,
altPressed: state.alt,
shiftPressed: state.shift,
modifierLockActive: true,
),
isFalse,
);
}
});
test('ignores non-V key events', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyC,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
});
});
group('shouldClearTerminalModifiersWhenRow3Collapses', () {
@@ -526,29 +232,5 @@ void main() {
isTrue,
);
});
test('does not clear modifiers when row expands', () {
expect(
shouldClearTerminalModifiersWhenRow3Collapses(
wasExpanded: false,
willExpand: true,
ctrlLocked: true,
altLocked: true,
),
isFalse,
);
});
test('clears Alt state when expanded row is collapsed', () {
expect(
shouldClearTerminalModifiersWhenRow3Collapses(
wasExpanded: true,
willExpand: false,
ctrlLocked: false,
altLocked: true,
),
isTrue,
);
});
});
}
+507
View File
@@ -0,0 +1,507 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_actions.dart';
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart';
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_utils.dart';
import 'package:flutter_hbb/models/shortcut_model.dart';
ShortcutPlatformCapabilities capabilities({
bool includeFullscreenShortcut = true,
bool includeScreenshotShortcut = true,
bool includeRelativeMouseModeShortcut = true,
bool includeTabShortcuts = true,
bool includeToolbarShortcut = true,
bool includeCloseTabShortcut = true,
bool includeSwitchSidesShortcut = true,
bool includeRecordingShortcut = true,
bool includeResetCanvasShortcut = true,
bool includePinToolbarShortcut = true,
bool includeViewModeShortcut = true,
bool includeVoiceCallShortcut = true,
Set<String> excludedActions = const {},
}) {
return ShortcutPlatformCapabilities(
includeFullscreenShortcut: includeFullscreenShortcut,
includeScreenshotShortcut: includeScreenshotShortcut,
includeRelativeMouseModeShortcut: includeRelativeMouseModeShortcut,
includeTabShortcuts: includeTabShortcuts,
includeToolbarShortcut: includeToolbarShortcut,
includeCloseTabShortcut: includeCloseTabShortcut,
includeSwitchSidesShortcut: includeSwitchSidesShortcut,
includeRecordingShortcut: includeRecordingShortcut,
includeResetCanvasShortcut: includeResetCanvasShortcut,
includePinToolbarShortcut: includePinToolbarShortcut,
includeViewModeShortcut: includeViewModeShortcut,
includeVoiceCallShortcut: includeVoiceCallShortcut,
excludedActions: excludedActions,
);
}
void main() {
test('kDefaultShortcutBindings matches fixture', () {
// The fixture is the cross-language source of truth for default
// bindings. Rust has its own parity test against the same file
// (`default_bindings_match_fixture_json` in src/keyboard/shortcuts.rs),
// so a drift on either side breaks CI.
final fixturePath = 'test/fixtures/default_keyboard_shortcuts.json';
final fixture =
jsonDecode(File(fixturePath).readAsStringSync()) as List<dynamic>;
expect(kDefaultShortcutBindings, equals(fixture),
reason: 'kDefaultShortcutBindings drifted from $fixturePath — update '
'shortcut_constants.dart, the fixture, and Rust default_bindings() '
'together');
});
test('save order preserves macOS control modifier', () {
expect(canonicalShortcutModsForSave({'ctrl'}), ['ctrl']);
expect(canonicalShortcutModsForSave({'shift', 'ctrl', 'primary', 'alt'}),
['primary', 'ctrl', 'alt', 'shift']);
});
test('shortcutBindingMapsFrom ignores malformed bindings', () {
expect(shortcutBindingMapsFrom('not a list'), isEmpty);
final bindings = shortcutBindingMapsFrom([
{
'action': kShortcutActionScreenshot,
'mods': ['primary'],
'key': 'p',
},
'bad',
1,
{
'action': kShortcutActionToggleMute,
'mods': ['alt'],
'key': 's',
},
]);
expect(bindings, hasLength(2));
expect(bindings.map((binding) => binding['action']), [
kShortcutActionScreenshot,
kShortcutActionToggleMute,
]);
});
test('shortcutBindingMapsFrom ignores malformed binding fields', () {
final valid = {
'action': kShortcutActionScreenshot,
'mods': ['primary', 'ctrl', 'alt', 'shift'],
'key': 'p',
};
final malformed = [
for (final field in ['action', 'mods', 'key'])
{...valid}..remove(field),
for (final fields in [
{'action': 1},
{'action': null},
{'key': 1},
{'key': null},
{'mods': null},
{'mods': 'primary'},
{'mods': ['primary', 1]},
{'mods': ['primary', null]},
{'mods': ['primary', 'unknown']},
])
{...valid, ...fields},
];
for (final binding in malformed) {
expect(shortcutBindingMapsFrom([binding, valid]), [valid],
reason: 'malformed binding should be ignored: $binding');
}
});
test('shortcutBindingMapsFrom preserves unbound and unknown bindings', () {
expect(
shortcutBindingMapsFrom([
{'action': kShortcutActionScreenshot, 'mods': [], 'key': ''},
{'action': 'future_action', 'mods': ['ctrl'], 'key': 'future_key'},
]),
[
{'action': kShortcutActionScreenshot, 'mods': [], 'key': ''},
{'action': 'future_action', 'mods': ['ctrl'], 'key': 'future_key'},
],
);
});
test('platform filtering ignores malformed binding fields', () {
final filtered = filterDefaultBindingsForPlatform([
{'action': 1, 'mods': ['primary'], 'key': 'p'},
{'action': kShortcutActionScreenshot, 'mods': ['primary'], 'key': 1},
{'action': kShortcutActionToggleMute, 'mods': ['alt'], 'key': 's'},
{
'action': kShortcutActionToggleFullscreen,
'mods': ['primary'],
'key': 'enter',
},
], capabilities(includeFullscreenShortcut: false));
expect(filtered, [
{'action': kShortcutActionToggleMute, 'mods': ['alt'], 'key': 's'},
]);
});
test('shortcutModSetFrom ignores malformed modifiers', () {
expect(shortcutModSetFrom('not a list'), isEmpty);
expect(shortcutModSetFrom(['primary', 1, 'alt', null, 'primary']), {
'primary',
'alt',
});
});
test('non-desktop defaults exclude desktop-only and tab shortcuts', () {
final defaults = [
{
'action': kShortcutActionSendCtrlAltDel,
'mods': ['primary', 'alt', 'shift'],
'key': 'delete',
},
{
'action': kShortcutActionToggleFullscreen,
'mods': ['primary', 'alt', 'shift'],
'key': 'enter',
},
{
'action': kShortcutActionSwitchDisplayNext,
'mods': ['primary', 'alt', 'shift'],
'key': 'arrow_right',
},
{
'action': kShortcutActionScreenshot,
'mods': ['primary', 'alt', 'shift'],
'key': 'p',
},
{
'action': kShortcutActionSwitchTabNext,
'mods': ['primary', 'alt', 'shift'],
'key': 'right_bracket',
},
{
'action': kShortcutActionToggleRelativeMouseMode,
'mods': ['primary', 'alt', 'shift'],
'key': 'g',
},
];
final filtered = filterDefaultBindingsForPlatform(
defaults,
capabilities(
includeFullscreenShortcut: false,
includeScreenshotShortcut: false,
includeRelativeMouseModeShortcut: false,
includeTabShortcuts: false,
includeToolbarShortcut: false,
includeCloseTabShortcut: false,
includeSwitchSidesShortcut: false,
includeRecordingShortcut: false,
includeResetCanvasShortcut: false,
includePinToolbarShortcut: false,
includeViewModeShortcut: false,
includeVoiceCallShortcut: false,
),
);
expect(filtered.map((binding) => binding['action']), [
kShortcutActionSendCtrlAltDel,
kShortcutActionSwitchDisplayNext,
]);
});
Set<String> idSet(Iterable<KeyboardShortcutActionGroup> groups) =>
{for (final e in allActionEntries(groups)) e.id};
test('filterKeyboardShortcutActionGroupsForPlatform strips desktop-only', () {
final groups = filterKeyboardShortcutActionGroupsForPlatform(
capabilities(
includeFullscreenShortcut: false,
includeScreenshotShortcut: false,
includeRelativeMouseModeShortcut: false,
includeTabShortcuts: false,
includeToolbarShortcut: false,
includeCloseTabShortcut: false,
includeSwitchSidesShortcut: false,
// Recording / Reset Canvas are intentionally still included here —
// they have non-desktop platforms (mobile Android / mobile both).
includeRecordingShortcut: true,
includeResetCanvasShortcut: true,
includePinToolbarShortcut: false,
includeViewModeShortcut: false,
includeVoiceCallShortcut: false,
),
);
final ids = idSet(groups);
// Desktop-only actions are stripped.
expect(ids, isNot(contains(kShortcutActionToggleFullscreen)));
expect(ids, isNot(contains(kShortcutActionToggleRelativeMouseMode)));
expect(ids, isNot(contains(kShortcutActionScreenshot)));
expect(ids, isNot(contains(kShortcutActionToggleToolbar)));
expect(ids, isNot(contains(kShortcutActionCloseTab)));
expect(ids, isNot(contains(kShortcutActionSwitchSides)));
expect(ids, isNot(contains(kShortcutActionPinToolbar)));
expect(ids, isNot(contains(kShortcutActionViewModeOriginal)));
expect(ids, isNot(contains(kShortcutActionViewModeAdaptive)));
expect(ids, isNot(contains(kShortcutActionSwitchTabNext)));
expect(ids, isNot(contains(kShortcutActionSwitchTabPrev)));
// Cross-platform actions survive.
expect(ids, contains(kShortcutActionSendCtrlAltDel));
expect(ids, contains(kShortcutActionInsertLock));
expect(ids, contains(kShortcutActionRestartRemote));
expect(ids, contains(kShortcutActionSwitchDisplayNext));
expect(ids, contains(kShortcutActionToggleRecording));
expect(ids, contains(kShortcutActionResetCanvas));
expect(ids, contains(kShortcutActionToggleMute));
});
test(
'filterKeyboardShortcutActionGroupsForPlatform hides Toggle Recording on Web/iOS',
() {
final groups = filterKeyboardShortcutActionGroupsForPlatform(
capabilities(includeRecordingShortcut: false),
);
final ids = idSet(groups);
expect(ids, isNot(contains(kShortcutActionToggleRecording)));
// Other Session Control entries unaffected.
expect(ids, contains(kShortcutActionSendCtrlAltDel));
expect(ids, contains(kShortcutActionInsertLock));
});
test(
'filterKeyboardShortcutActionGroupsForPlatform keeps full set on desktop',
() {
final groups =
filterKeyboardShortcutActionGroupsForPlatform(capabilities());
expect(idSet(groups), equals(idSet(kKeyboardShortcutActionGroups)));
});
test('Wayland hides relative mouse mode but keeps screenshot', () {
final ids = idSet(filterKeyboardShortcutActionGroupsForPlatform(
capabilities(includeRelativeMouseModeShortcut: false),
));
expect(ids, isNot(contains(kShortcutActionToggleRelativeMouseMode)));
expect(ids, contains(kShortcutActionScreenshot));
});
test('filterKeyboardShortcutActionGroupsForPlatform drops empty groups', () {
// With every capability flag off, groups whose items are all behind
// those flags get dropped. Display / Keyboard parent groups still carry
// cross-platform direct items so they survive even when the gated
// subgroups thin out.
final groups = filterKeyboardShortcutActionGroupsForPlatform(
capabilities(
includeFullscreenShortcut: false,
includeScreenshotShortcut: false,
includeRelativeMouseModeShortcut: false,
includeTabShortcuts: false,
includeToolbarShortcut: false,
includeCloseTabShortcut: false,
includeSwitchSidesShortcut: false,
includeRecordingShortcut: false,
includeResetCanvasShortcut: false,
includePinToolbarShortcut: false,
includeViewModeShortcut: false,
includeVoiceCallShortcut: false,
),
);
final titles = groups.map((g) => g.titleKey).toList();
// "Other" has nothing but platform-gated entries → dropped entirely.
expect(titles, isNot(contains('Other')));
// Parent groups with cross-platform direct items survive.
expect(titles, contains('Display'));
expect(titles, contains('Keyboard'));
// The "View Mode" subgroup under Display is gated by includeViewModeShortcut,
// so it must be absent from Display's surviving children.
final displayChildren =
groups.firstWhere((g) => g.titleKey == 'Display').children;
final subgroupTitles = displayChildren
.whereType<KeyboardShortcutActionSubgroup>()
.map((s) => s.titleKey)
.toList();
expect(subgroupTitles, isNot(contains('View Mode')));
// No surviving group is empty either way.
expect(groups.every((g) => g.children.isNotEmpty), isTrue);
// No surviving subgroup is empty.
for (final group in groups) {
for (final child in group.children) {
if (child is KeyboardShortcutActionSubgroup) {
expect(child.entries, isNotEmpty,
reason: 'subgroup "${child.titleKey}" should not be empty');
}
}
}
});
test('physicalKeyName covers the supported-keys fixture', () {
// `shortcut_key_usb_hid.json` pins every key name to the USB HID usage
// it is recorded and matched from. Rust has a mirror test against the
// same file (`usb_hid_keys_match_fixture` in src/keyboard/shortcuts.rs),
// and the set of names must equal `supported_shortcut_keys.json`.
final supported = (jsonDecode(
File('test/fixtures/supported_shortcut_keys.json')
.readAsStringSync()) as List<dynamic>)
.cast<String>()
.toSet();
final pairs = (jsonDecode(File('test/fixtures/shortcut_key_usb_hid.json')
.readAsStringSync()) as List<dynamic>)
.cast<List<dynamic>>();
for (final pair in pairs) {
final name = pair[0] as String;
final usage = pair[1] as int;
expect(physicalKeyName(PhysicalKeyboardKey(0x00070000 | usage)),
equals(name),
reason: 'USB HID 0x${usage.toRadixString(16)} should be "$name"');
}
expect(pairs.map((p) => p[0] as String).toSet(), equals(supported));
// Modifier-only / unsupported keys must return null.
expect(physicalKeyName(PhysicalKeyboardKey.shiftLeft), isNull);
expect(physicalKeyName(PhysicalKeyboardKey.escape), isNull);
expect(physicalKeyName(PhysicalKeyboardKey.f13), isNull);
expect(physicalKeyName(PhysicalKeyboardKey.numpad1), isNull);
});
test('enable seeds defaults only for a config without bindings', () {
expect(shouldSeedDefaultShortcutBindings(<String, dynamic>{}), isTrue);
expect(
shouldSeedDefaultShortcutBindings(
<String, dynamic>{'enabled': false, 'pass_through': true}),
isTrue);
// The user cleared every binding: re-enabling must not bring defaults back.
expect(
shouldSeedDefaultShortcutBindings(
<String, dynamic>{'enabled': false, 'bindings': <dynamic>[]}),
isFalse);
});
test('ShortcutConfig.parse reads the flags and bindings once', () {
final config = ShortcutConfig.parse(jsonEncode({
'enabled': true,
'pass_through': false,
'bindings': [
{'action': 'screenshot', 'mods': ['primary'], 'key': 'p'},
'not a binding',
],
}));
expect(config.enabled, isTrue);
expect(config.passThrough, isFalse);
expect(config.bindings, [
{'action': 'screenshot', 'mods': ['primary'], 'key': 'p'},
]);
for (final raw in ['', 'not json', '[]', '{"bindings": "x"}']) {
final broken = ShortcutConfig.parse(raw);
expect(broken.enabled, isFalse, reason: raw);
expect(broken.passThrough, isFalse, reason: raw);
expect(broken.bindings, isEmpty, reason: raw);
}
});
test('Wayland active config preserves stored bindings and flags', () {
const relative = {
'action': kShortcutActionToggleRelativeMouseMode,
'mods': ['primary'],
'key': 'r',
};
const mute = {
'action': kShortcutActionToggleMute,
'mods': ['primary'],
'key': 'm',
};
for (final flags in [(true, false), (false, false), (true, true)]) {
final stored = ShortcutConfig.parse(jsonEncode({
'enabled': flags.$1,
'pass_through': flags.$2,
'bindings': [relative, mute],
}));
final active = stored.forPlatform(
capabilities(includeRelativeMouseModeShortcut: false));
expect(active.bindings, [mute]);
expect(active.enabled, flags.$1);
expect(active.passThrough, flags.$2);
expect(stored.bindings, [relative, mute]);
expect(stored.forPlatform(capabilities()).bindings, [relative, mute]);
}
});
test('active saved bindings follow Settings capabilities without reseeding', () {
final actions = [
kShortcutActionSwitchDisplayAll,
kShortcutActionKeyboardModeMap,
kShortcutActionToggleShowMyCursor,
kShortcutActionToggleZoomCursor,
kShortcutActionToggleRecording,
kShortcutActionToggleVoiceCall,
kShortcutActionResetCanvas,
kShortcutActionToggleMute,
kShortcutActionSendCtrlAltDel,
];
final saved = ShortcutConfig.parse(jsonEncode({
'enabled': true,
'bindings': [
for (final action in actions)
{'action': action, 'mods': ['primary'], 'key': 'm'},
],
}));
final cap = capabilities(
includeRecordingShortcut: false,
includeVoiceCallShortcut: false,
includeResetCanvasShortcut: false,
excludedActions: {
kShortcutActionSwitchDisplayAll,
kShortcutActionKeyboardModeMap,
kShortcutActionToggleShowMyCursor,
kShortcutActionToggleZoomCursor,
},
);
expect(saved.forPlatform(cap).bindings.map((b) => b['action']),
[kShortcutActionToggleMute, kShortcutActionSendCtrlAltDel]);
expect(saved.bindings.map((b) => b['action']), actions);
expect(saved.forPlatform(capabilities()).bindings, saved.bindings);
});
test('non-US layouts record and match the physical key', () {
// AZERTY: the key labelled "A" sits where US QWERTY has Q. The native
// matcher only sees the physical position (USB HID usage), so the
// binding must name that position too.
const azertyA = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyQ,
logicalKey: LogicalKeyboardKey.keyA,
character: 'a',
timeStamp: Duration.zero,
);
expect(shortcutKeyNameForEvent(azertyA), 'q');
// QWERTZ: the key labelled "Z" sits where US QWERTY has Y.
const qwertzZ = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyY,
logicalKey: LogicalKeyboardKey.keyZ,
character: 'z',
timeStamp: Duration.zero,
);
expect(shortcutKeyNameForEvent(qwertzZ), 'y');
});
test('kShortcutActionsRunOnKeyUp matches the fixture and names real actions',
() {
// Rust has a mirror test against the same file
// (`key_up_actions_match_fixture` in src/keyboard/shortcuts.rs).
final fixture = (jsonDecode(
File('test/fixtures/key_up_shortcut_actions.json')
.readAsStringSync()) as List<dynamic>)
.cast<String>()
.toSet();
expect(kShortcutActionsRunOnKeyUp, equals(fixture),
reason: 'kShortcutActionsRunOnKeyUp drifted from the fixture — update '
'shortcut_constants.dart, the fixture, and Rust runs_on_release '
'together');
final actions = idSet(kKeyboardShortcutActionGroups);
for (final id in kShortcutActionsRunOnKeyUp) {
expect(actions, contains(id), reason: '"$id" is not a configurable action');
}
});
}
@@ -0,0 +1,566 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart';
import 'package:flutter_hbb/models/local_flutter_shortcuts.dart';
LocalFlutterShortcutDispatcher dispatcherFor(
void Function(String) onTriggered) {
final dispatcher = LocalFlutterShortcutDispatcher(onTriggered: onTriggered);
addTearDown(dispatcher.clear);
addTearDown(LocalFlutterShortcutDispatcher.resetFiredKeys);
return dispatcher;
}
class _ShortcutHarness {
final String? Function(KeyEvent) match;
final Future<void> Function() releaseModifiers;
final LocalFlutterShortcutDispatcher dispatcher;
_ShortcutHarness({
required this.match,
required this.releaseModifiers,
required void Function(String) onTriggered,
}) : dispatcher = dispatcherFor(onTriggered);
bool tryDispatch(KeyEvent event) => dispatcher.tryDispatch(
event,
match: () => match(event),
releaseModifiers: releaseModifiers,
);
void clear() => dispatcher.clear();
}
KeyEvent down(PhysicalKeyboardKey key,
{LogicalKeyboardKey logicalKey = LogicalKeyboardKey.keyP}) =>
KeyDownEvent(
physicalKey: key,
logicalKey: logicalKey,
timeStamp: Duration.zero,
);
KeyEvent repeat(PhysicalKeyboardKey key) => KeyRepeatEvent(
physicalKey: key,
logicalKey: LogicalKeyboardKey.keyP,
timeStamp: Duration.zero,
);
KeyEvent up(PhysicalKeyboardKey key,
{LogicalKeyboardKey logicalKey = LogicalKeyboardKey.keyP}) =>
KeyUpEvent(
physicalKey: key,
logicalKey: logicalKey,
timeStamp: Duration.zero,
);
RawKeyEvent rawP({required bool down, bool repeat = false, bool ctrl = false}) {
final data = RawKeyEventDataLinux(
keyHelper: GtkKeyHelper(),
scanCode: 33,
keyCode: 112,
unicodeScalarValues: 112,
modifiers: ctrl ? GtkKeyHelper.modifierControl : 0,
isDown: down,
);
return down
? RawKeyDownEvent(data: data, repeat: repeat)
: RawKeyUpEvent(data: data);
}
void main() {
for (final action in [
kShortcutActionToggleViewOnly,
kShortcutActionToggleShowMyCursor,
kShortcutActionToggleMute,
...kShortcutActionsRunOnKeyUp,
kShortcutActionSendClipboardKeystrokes,
]) {
test('forwarded W retains correct ownership across $action', () async {
final events = <String>['W down'];
final released = Completer<void>();
final dispatcher = dispatcherFor(events.add);
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyW,
down: true, release: () {
events.add('W up');
return released.future;
});
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP),
match: () => action), isTrue);
await pumpEventQueue();
if (kShortcutActionsRunOnKeyUp.contains(action) ||
(!kIsWeb && action == kShortcutActionSendClipboardKeystrokes)) {
expect(events, ['W down']);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
await pumpEventQueue();
}
if (action == kShortcutActionToggleMute ||
(kIsWeb && action == kShortcutActionSendClipboardKeystrokes)) {
expect(events, ['W down', action]);
} else {
expect(events, ['W down', 'W up']);
}
released.complete();
await pumpEventQueue();
expect(events.last, action);
});
}
for (final action in [
kShortcutActionToggleViewOnly,
kShortcutActionToggleChat,
if (!kIsWeb) kShortcutActionSendClipboardKeystrokes,
]) {
test('$action cleanup skips released keys and cancels after session close',
() async {
final events = <String>[];
final released = Completer<void>();
final dispatcher = dispatcherFor(events.add);
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyW,
down: true, release: () {
events.add('W up');
return released.future;
});
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyC,
down: true, release: () async => events.add('C up'));
dispatcher.recordForwardedKey(PhysicalKeyboardKey.keyC,
down: false, release: () async => events.add('C up'));
dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP), match: () => action);
dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP));
await pumpEventQueue();
expect(events, ['W up']);
dispatcher.clear();
released.complete();
await pumpEventQueue();
expect(events, ['W up']);
});
}
test('owns each overlapping shortcut key until its own release', () async {
var modifiersPressed = true;
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (event) => modifiersPressed
? event.physicalKey == PhysicalKeyboardKey.keyP
? 'screenshot'
: 'chat'
: null,
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyC)), isTrue);
modifiersPressed = false;
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyC)), isTrue);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
await Future<void>.value();
expect(actions, ['screenshot', 'chat']);
});
test('binding changes do not forward a previously consumed key', () async {
var enabled = true;
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => enabled ? 'screenshot' : null,
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
enabled = false;
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
await Future<void>.value();
expect(actions, ['screenshot']);
});
test('unmatched key stays forwarded when modifiers change during repeat',
() async {
var modifiersPressed = false;
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => modifiersPressed ? 'screenshot' : null,
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
modifiersPressed = true;
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
await Future<void>.value();
expect(actions, isEmpty);
});
test('auto-repeat cannot trigger an action again', () async {
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => 'screenshot',
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
await Future<void>.value();
expect(actions, ['screenshot', 'screenshot']);
});
test('releases remote modifiers before running the action', () async {
final released = Completer<void>();
final actions = <String>[];
var releases = 0;
final dispatcher = _ShortcutHarness(
match: (_) => 'screenshot',
releaseModifiers: () {
releases++;
return released.future;
},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
expect(releases, 1);
expect(actions, isEmpty);
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
expect(releases, 1);
released.complete();
await Future<void>.value();
expect(actions, ['screenshot']);
});
test('native clipboard prompt can be repeated immediately after cancelling',
() async {
var dialogOpen = false;
var prompts = 0;
final dispatcher = _ShortcutHarness(
match: (_) => kShortcutActionSendClipboardKeystrokes,
releaseModifiers: () async {},
onTriggered: (_) {
dialogOpen = true;
prompts++;
},
);
bool route(KeyEvent event) => !dialogOpen && dispatcher.tryDispatch(event);
for (var attempt = 1; attempt <= 2; attempt++) {
expect(route(down(PhysicalKeyboardKey.keyV)), isTrue);
await Future<void>.value();
expect(dialogOpen, isFalse,
reason: 'the local dialog must not consume the trigger release');
expect(route(repeat(PhysicalKeyboardKey.keyV)), isTrue);
expect(route(up(PhysicalKeyboardKey.keyV)), isTrue);
await Future<void>.value();
expect(dialogOpen, isTrue);
expect(prompts, attempt);
dialogOpen = false;
}
}, skip: kIsWeb);
test('native clipboard waits for outstanding remote modifier releases',
() async {
final released = Completer<void>();
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => kShortcutActionSendClipboardKeystrokes,
releaseModifiers: () => released.future,
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue);
await Future<void>.value();
expect(actions, isEmpty,
reason: 'clipboard input must follow the remote modifier releases');
released.complete();
await Future<void>.value();
expect(actions, [kShortcutActionSendClipboardKeystrokes]);
}, skip: kIsWeb);
test('Web clipboard still runs on key down for browser activation', () async {
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => kShortcutActionSendClipboardKeystrokes,
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue);
await Future<void>.value();
expect(actions, [kShortcutActionSendClipboardKeystrokes]);
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue);
expect(actions, [kShortcutActionSendClipboardKeystrokes]);
}, skip: !kIsWeb);
test('closing a clipboard owner preserves another session release', () async {
final closingRelease = Completer<void>();
final nextRelease = Completer<void>();
final actions = <String>[];
final closing = _ShortcutHarness(
match: (_) => kShortcutActionSendClipboardKeystrokes,
releaseModifiers: () => closingRelease.future,
onTriggered: (_) => actions.add('closing'),
);
final next = _ShortcutHarness(
match: (_) => kShortcutActionSendClipboardKeystrokes,
releaseModifiers: () => nextRelease.future,
onTriggered: (_) => actions.add('next'),
);
expect(closing.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue);
expect(next.tryDispatch(down(PhysicalKeyboardKey.keyC)), isTrue);
closing.clear();
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
closingRelease.complete();
await Future<void>.value();
expect(actions, isEmpty,
reason: 'the live session still awaits its own modifier release');
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue);
nextRelease.complete();
await Future<void>.value();
expect(actions, ['next']);
}, skip: kIsWeb);
test('closing the session drops its pending action but keeps the fired key',
() async {
// Close tab is itself a shortcut: the session that matched the key is
// gone before the key is released, and the next session gets the rest.
final released = Completer<void>();
final actions = <String>[];
var enabled = true;
final closing = _ShortcutHarness(
match: (_) => enabled ? 'close_tab' : null,
releaseModifiers: () => released.future,
onTriggered: actions.add,
);
final next = _ShortcutHarness(
match: (_) => enabled ? 'close_tab' : null,
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(closing.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
closing.clear();
released.complete();
await Future<void>.value();
expect(actions, isEmpty, reason: 'a closed session runs nothing');
expect(next.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
enabled = false;
expect(next.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
expect(next.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
await Future<void>.value();
expect(actions, isEmpty);
});
test('focus-changing actions run when the key is released', () async {
// Close tab moves focus before the key is released; the release may then
// land in a session whose keys go through the other matcher.
var releases = 0;
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => kShortcutActionCloseTab,
releaseModifiers: () async => releases++,
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyW)), isTrue);
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyW)), isTrue);
await Future<void>.value();
expect(releases, 1, reason: 'remote modifiers are released on the press');
expect(actions, isEmpty, reason: 'the action waits for the release');
final other = dispatcherFor(actions.add);
expect(other.tryDispatch(up(PhysicalKeyboardKey.keyW)), isTrue);
await Future<void>.value();
expect(actions, [kShortcutActionCloseTab]);
expect(other.tryDispatch(up(PhysicalKeyboardKey.keyW)), isFalse);
});
test('closing the session drops its action pending on key release',
() async {
final actions = <String>[];
final dispatcher = _ShortcutHarness(
match: (_) => kShortcutActionSwitchTabNext,
releaseModifiers: () async {},
onTriggered: actions.add,
);
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyW)), isTrue);
dispatcher.clear();
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyW)), isTrue,
reason: 'the key stays owned');
await Future<void>.value();
expect(actions, isEmpty);
});
test('raw legacy shortcuts own repeats and release after modifiers change',
() async {
addTearDown(RawKeyboard.instance.clearKeysPressed);
final actions = <String>[];
final dispatcher = dispatcherFor(actions.add);
bool dispatch(RawKeyEvent event) {
RawKeyboard.instance.handleRawKeyEvent(event);
return dispatcher.tryDispatchRaw(
event,
match: () => event.isControlPressed ? 'screenshot' : null,
releaseModifiers: () async {},
);
}
expect(dispatch(rawP(down: true, ctrl: true)), isTrue);
expect(dispatch(rawP(down: true, repeat: true)), isTrue);
expect(dispatch(rawP(down: false)), isTrue);
expect(dispatch(rawP(down: true)), isFalse);
expect(dispatch(rawP(down: true, repeat: true, ctrl: true)), isFalse);
expect(dispatch(rawP(down: false, ctrl: true)), isFalse);
await Future<void>.value();
expect(actions, ['screenshot']);
});
test('shortcut key ownership follows focus to another session', () {
final actions = <String>[];
final first = dispatcherFor(actions.add);
final second = dispatcherFor(actions.add);
expect(
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
match: () => 'next_tab'),
isTrue,
);
expect(second.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
expect(second.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
expect(
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
match: () => 'next_tab'),
isTrue,
);
expect(actions, ['next_tab', 'next_tab']);
});
test('closing another session keeps every fired key owned', () {
final first = dispatcherFor((_) {});
final second = dispatcherFor((_) {});
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
match: () => 'screenshot');
second.tryDispatch(down(PhysicalKeyboardKey.keyC), match: () => 'chat');
second.clear();
expect(second.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
expect(first.tryDispatch(repeat(PhysicalKeyboardKey.keyC)), isTrue);
expect(second.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
expect(first.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
expect(first.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
expect(first.tryDispatch(down(PhysicalKeyboardKey.keyC)), isFalse);
});
test('restores released modifiers before the next ordinary map key', () {
final dispatcher = dispatcherFor((_) {});
dispatcher.recordReleasedModifiers([
PhysicalKeyboardKey.controlLeft,
PhysicalKeyboardKey.altRight,
]);
final pressed = {PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.keyC};
expect(
dispatcher.takeModifiersToRestore(
down(PhysicalKeyboardKey.keyC), pressed),
[PhysicalKeyboardKey.controlLeft],
);
expect(
dispatcher.takeModifiersToRestore(
repeat(PhysicalKeyboardKey.keyC), pressed),
isEmpty,
);
});
test('modifier events do not replay previously released modifiers', () {
final dispatcher = dispatcherFor((_) {});
dispatcher.recordReleasedModifiers([PhysicalKeyboardKey.controlLeft]);
expect(
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.shiftLeft),
{PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.shiftLeft}),
isEmpty,
);
expect(
dispatcher.takeModifiersToRestore(
up(PhysicalKeyboardKey.controlLeft), {PhysicalKeyboardKey.shiftLeft}),
isEmpty,
);
expect(
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.keyC),
{PhysicalKeyboardKey.shiftLeft, PhysicalKeyboardKey.keyC}),
isEmpty,
);
});
test('session closure drops pending modifier replay', () {
final dispatcher = dispatcherFor((_) {});
dispatcher.recordReleasedModifiers([PhysicalKeyboardKey.controlLeft]);
dispatcher.clear();
expect(
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.keyC),
{PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.keyC}),
isEmpty,
);
});
for (final releaseControl in [false, true]) {
test(
'view-only resume restores only still-held modifiers '
'(releaseControl=$releaseControl)', () {
final keyboard = HardwareKeyboard();
var viewOnly = true;
final dispatcher = dispatcherFor((_) => viewOnly = false);
final controlDown = down(PhysicalKeyboardKey.controlLeft,
logicalKey: LogicalKeyboardKey.controlLeft);
keyboard.handleKeyEvent(controlDown);
expect(dispatcher.tryDispatch(controlDown, viewOnly: true), isFalse);
final shortcutDown = down(PhysicalKeyboardKey.keyP);
keyboard.handleKeyEvent(shortcutDown);
expect(
dispatcher.tryDispatch(shortcutDown,
viewOnly: true, match: () => 'toggle_view_only'),
isTrue,
);
expect(viewOnly, isFalse);
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
final shortcutUp = up(PhysicalKeyboardKey.keyP);
keyboard.handleKeyEvent(shortcutUp);
expect(dispatcher.tryDispatch(shortcutUp), isTrue);
if (releaseControl) {
final controlUp = up(PhysicalKeyboardKey.controlLeft,
logicalKey: LogicalKeyboardKey.controlLeft);
keyboard.handleKeyEvent(controlUp);
}
final copyDown =
down(PhysicalKeyboardKey.keyC, logicalKey: LogicalKeyboardKey.keyC);
keyboard.handleKeyEvent(copyDown);
expect(dispatcher.tryDispatch(copyDown), isFalse);
expect(
dispatcher.resumeModifiersAfterViewOnly(
copyDown.physicalKey, keyboard.physicalKeysPressed),
isTrue,
);
expect(
dispatcher.takeModifiersToRestore(
copyDown, keyboard.physicalKeysPressed),
releaseControl ? isEmpty : [PhysicalKeyboardKey.controlLeft],
);
expect(keyboard.isControlPressed, !releaseControl);
});
}
}
+277
View File
@@ -0,0 +1,277 @@
import 'dart:async';
import 'dart:convert';
import 'package:dash_chat_2/dash_chat_2.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_hbb/common.dart' show SessionID;
import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart';
import 'package:flutter_hbb/generated_bridge.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/models/chat_model.dart';
import 'package:flutter_hbb/models/input_model.dart';
import 'package:flutter_hbb/models/local_flutter_shortcuts.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_hbb/models/shortcut_model.dart';
import 'package:uuid/uuid.dart';
class _ChatBinding extends Fake implements RustdeskImpl {
final sent = <(SessionID, String)>[];
final cmSent = <(int, String)>[];
@override
String translate(
{required String name, required String locale, dynamic hint}) =>
name;
@override
Future<void> sessionSendChat(
{required SessionID sessionId,
required String text,
dynamic hint}) async {
sent.add((sessionId, text));
}
@override
Future<void> cmSendChat(
{required int connId, required String msg, dynamic hint}) async {
cmSent.add((connId, msg));
}
}
class _Chat extends ChatModel {
_Chat(FFI session) : super(WeakReference(session));
final opened = <MessageKey>[];
@override
void toggleChatOverlay(
{Offset? chatInitPos, bool requestSoftKeyboard = true}) {
opened.add(currentKey);
}
}
class _LegacyBinding extends _ChatBinding {
final keys = <(String, bool, bool)>[];
@override
bool sessionGetToggleOptionSync(
{required SessionID sessionId, required String arg, dynamic hint}) =>
false;
@override
String mainGetInputSource({dynamic hint}) => 'Input source 2';
@override
bool mainCurrentIsWayland({dynamic hint}) => false;
@override
String mainGetLocalOption({required String key, dynamic hint}) =>
'{"enabled":true,"bindings":[{"action":"toggle_mute",'
'"key":"s","mods":["alt"]}]}';
@override
Future<void> sessionInputKey(
{required SessionID sessionId,
required String name,
required bool down,
required bool press,
required bool alt,
required bool ctrl,
required bool shift,
required bool command,
dynamic hint}) async {
expect([press, ctrl, shift, command], [false, false, false, false]);
keys.add((name, down, alt));
}
@override
Future<void> sessionSendMouse(
{required SessionID sessionId, required String msg, dynamic hint}) async {
expect(jsonDecode(msg)['relative_mouse_mode'], '0');
}
}
Future<void> _rawKey(InputModel input,
{required int scan,
required int key,
bool down = true,
bool alt = true}) async {
final data = RawKeyEventDataLinux(
keyHelper: GtkKeyHelper(),
scanCode: scan,
keyCode: key,
unicodeScalarValues: key < 256 ? key : 0,
modifiers: alt ? GtkKeyHelper.modifierMod1 : 0,
isDown: down);
final event = down ? RawKeyDownEvent(data: data) : RawKeyUpEvent(data: data);
RawKeyboard.instance.handleRawKeyEvent(event);
input.handleRawKeyEvent(event);
}
class _Session extends Fake implements FFI {
@override
bool closed = false;
@override
final String id = 'test-peer';
@override
final SessionID sessionId = const Uuid().v4obj();
@override
late final FfiModel ffiModel = FfiModel(WeakReference(this));
@override
late final _Chat chatModel = _Chat(this);
@override
late ShortcutModel shortcutModel;
@override
ConnType get connType => ConnType.defaultConn;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _Session session;
late ShortcutModel model;
setUp(() {
session = _Session();
model = ShortcutModel(WeakReference(session));
session.shortcutModel = model;
});
tearDown(() => model.clear());
for (final peer in [
kPeerPlatformWindows,
kPeerPlatformLinux,
kPeerPlatformMacOS
]) {
for (final alt in [(64, 0xffe9, 'VK_MENU'), (108, 0xffea, 'RAlt')]) {
test('Legacy $peer ${alt.$3} shortcut releases modifiers before dispatch',
() async {
final binding = _LegacyBinding();
platformFFI.setBindingForTesting(binding);
session.ffiModel.pi.platform = peer;
final input = InputModel(WeakReference(session))
..keyboardMode = kKeyLegacyMode;
addTearDown(() {
session.closed = true;
input.resetModifiers();
input.disposeRelativeMouseMode();
RawKeyboard.instance.clearKeysPressed();
LocalFlutterShortcutDispatcher.resetFiredKeys();
session.ffiModel.dispose();
});
final firedAt = <int>[];
model.register(
kShortcutActionToggleMute, () => firedAt.add(binding.keys.length));
await _rawKey(input, scan: alt.$1, key: alt.$2);
await _rawKey(input, scan: 39, key: 0x73);
await pumpEventQueue();
expect(binding.keys, [
(alt.$3, true, true),
if (peer == kPeerPlatformWindows) ('VK_CONTROL', true, true),
// GTK reports Alt without a side on the letter event.
('VK_MENU', false, false),
('RAlt', false, false),
if (peer == kPeerPlatformWindows) ('VK_CONTROL', false, false),
]);
expect(firedAt, [binding.keys.length]);
await _rawKey(input, scan: 39, key: 0x73, down: false);
await _rawKey(input, scan: 38, key: 0x61);
expect(binding.keys.last, ('VK_A', true, true));
await _rawKey(input, scan: 38, key: 0x61, down: false);
await _rawKey(input,
scan: alt.$1, key: alt.$2, down: false, alt: false);
await _rawKey(input, scan: 38, key: 0x61, alt: false);
expect(binding.keys.last, ('VK_A', true, false));
await _rawKey(input, scan: 38, key: 0x61, down: false, alt: false);
expect(binding.keys.where((key) => key.$1 == 'VK_S'), isEmpty);
});
}
}
test('fresh Chat shortcut sends through its outgoing session', () async {
final binding = _ChatBinding();
platformFFI.setBindingForTesting(binding);
final chat = session.chatModel;
addTearDown(() {
chat.dispose();
chat.inputNode.dispose();
session.ffiModel.dispose();
});
expect(chat.currentKey.isOut, isFalse);
expect(chat.messages, isEmpty);
registerSessionShortcutActions(session);
model.onTriggered(kShortcutActionToggleChat);
await pumpEventQueue();
chat.send(ChatMessage(
text: 'first message', user: chat.me, createdAt: DateTime.now()));
await pumpEventQueue();
expect(binding.sent, [(session.sessionId, 'first message')]);
expect(binding.cmSent, isEmpty);
expect(chat.opened, [MessageKey(session.id, ChatModel.clientModeID)]);
expect(
chat.messages.keys, [MessageKey(session.id, ChatModel.clientModeID)]);
});
test('a removed menu action cannot run its cached callback', () async {
var calls = 0;
model.register('mute', () => calls++);
model.registerRefresher(['mute'], () => model.unregister('mute'));
model.onTriggered('mute');
await pumpEventQueue();
expect(calls, 0);
});
test('an action becomes available without reopening its menu', () async {
var calls = 0;
model.registerRefresher(['screenshot'], () {
model.register('screenshot', () => calls++);
});
model.onTriggered('screenshot');
await pumpEventQueue();
expect(calls, 1);
});
test('refresh finishes before invoking the current callback', () async {
final ready = Completer<void>();
final calls = <String>[];
model.register('cursor', () => calls.add('stale'));
model.registerRefresher(['cursor'], () async {
await ready.future;
model.register('cursor', () => calls.add('current'));
});
model.onTriggered('cursor');
expect(calls, isEmpty);
ready.complete();
await pumpEventQueue();
expect(calls, ['current']);
});
test('closing during a refresh prevents late registration and dispatch',
() async {
final ready = Completer<void>();
var calls = 0;
model.registerRefresher(['mute'], () async {
await ready.future;
model.register('mute', () => calls++);
});
model.onTriggered('mute');
session.closed = true;
model.clear();
ready.complete();
await pumpEventQueue();
model.onTriggered('mute');
await pumpEventQueue();
expect(calls, 0);
});
}
@@ -0,0 +1,96 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/models/terminal_mouse_handler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:xterm/xterm.dart';
const _captureMouse = '\x1b[?1007l\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?1003h';
void main() {
late Terminal terminal;
late TerminalController controller;
late List<String> output;
setUp(() {
output = [];
terminal = Terminal()..onOutput = output.add;
controller = TerminalController();
});
Future<TerminalViewState> mount(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(left: 30, top: 50),
child: SizedBox(
width: 400,
height: 120,
child: TerminalMouseInteraction(terminal, controller: controller),
),
),
),
));
terminal.write(List.generate(80, (i) => 'line $i\r\n').join());
await tester.pump();
final view = tester.state<TerminalViewState>(find.byType(TerminalView));
expect(view.widget.scrollController!.offset, greaterThan(0));
return view;
}
Future<void> scrollTrackpad(
WidgetTester tester, Offset point, double distance) async {
final pointer = TestPointer(2, PointerDeviceKind.trackpad);
await tester.sendEventToBinding(pointer.panZoomStart(point));
await tester.sendEventToBinding(
pointer.panZoomUpdate(point, pan: Offset(0, distance)));
await tester.sendEventToBinding(
pointer.panZoomUpdate(point, pan: Offset(0, distance * 2)));
await tester.sendEventToBinding(pointer.panZoomEnd());
await tester.pump();
}
testWidgets('alternate screen reports trackpad after main-screen history',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
final render = view.renderTerminal;
final point = render.localToGlobal(
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
await scrollTrackpad(tester, point, render.lineHeight * 3);
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[<64;3;2M'));
expect(view.widget.scrollController!.offset, 0);
expect(controller.selection, isNull);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets('leaving alternate screen restores local trackpad scrollback',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
terminal.write('\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1006l\x1b[?1049l');
await tester.pump();
final before = view.widget.scrollController!.offset;
await scrollTrackpad(
tester, view.renderTerminal.localToGlobal(const Offset(40, 40)), 48);
expect(output, isEmpty);
expect(view.widget.scrollController!.offset, lessThan(before));
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets('alternate screen without mouse capture still simulates arrows',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h');
await tester.pump();
await scrollTrackpad(
tester, view.renderTerminal.localToGlobal(const Offset(40, 40)), -48);
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[B'));
expect(view.widget.scrollController!.offset, 0);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
}
@@ -17,24 +17,5 @@ void main() {
['Ctrl', 'Alt', '-', 'PgUp', 'PgDn'],
);
});
test('keeps two trailing Row3 placeholders for row alignment', () {
expect(terminalKeyboardRow3TrailingPlaceholderCount, 2);
});
test('keeps every expanded row aligned at 348dp', () {
final rowWidths = [
terminalKeyboardRowWidth(terminalKeyboardRow1Keys.length),
terminalKeyboardRowWidth(terminalKeyboardRow2Keys.length + 1),
terminalKeyboardRowWidth(
terminalKeyboardRow3Keys.length +
terminalKeyboardRow3TrailingPlaceholderCount,
),
];
expect(terminalKeyboardKeyWidth, 48);
expect(terminalKeyboardKeySpacing, 2);
expect(rowWidths, everyElement(348));
});
});
}
@@ -1,5 +1,3 @@
import 'dart:async';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/terminal_model.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -14,42 +12,6 @@ class _FakeFFI implements FFI {
}
void main() {
test('ignores paste that completes after the terminal model is disposed',
() async {
final model = TerminalModel(_FakeFFI());
final delayedClipboardText = Completer<String>();
// This mirrors Ctrl/Cmd+V: clipboard access starts first, then the page and
// model are disposed before the asynchronous read supplies its text.
final paste = delayedClipboardText.future.then(model.pasteText);
model.dispose();
delayedClipboardText.complete('late clipboard text');
await paste;
expect(model.debugBufferedInputCount, 0);
});
test('ignores terminal text input after the terminal model is disposed', () {
final model = TerminalModel(_FakeFFI());
var checkedCtrlLock = false;
var clearedCtrlLock = false;
model.isCtrlLocked = () {
checkedCtrlLock = true;
return true;
};
model.clearCtrlLock = () {
clearedCtrlLock = true;
};
model.dispose();
model.terminal.textInput('d');
expect(checkedCtrlLock, isFalse);
expect(clearedCtrlLock, isFalse);
expect(model.debugBufferedInputCount, 0);
});
test('builds its terminal with the wheel button fix', () {
final model = TerminalModel(_FakeFFI());
addTearDown(model.dispose);
+1 -95
View File
@@ -71,10 +71,9 @@ void main() {
String? report(
TerminalMouseButton button, [
TerminalMouseButtonState state = TerminalMouseButtonState.down,
CellOffset position = const CellOffset(10, 5),
]) {
output.clear();
terminal.mouseInput(button, state, position);
terminal.mouseInput(button, state, const CellOffset(10, 5));
return output.isEmpty ? null : output.single;
}
@@ -102,40 +101,6 @@ void main() {
);
});
test('reports utf-encoding wheel buttons beyond the normal-mode range', () {
terminal.write('\x1b[?1000h\x1b[?1005h');
expect(
report(
TerminalMouseButton.wheelDown,
TerminalMouseButtonState.down,
const CellOffset(400, 300),
),
'\x1b[M${String.fromCharCode(32 + 65)}'
'${String.fromCharCode(32 + 401)}${String.fromCharCode(32 + 301)}',
);
});
test('reports urxvt-encoding wheel buttons shifted by 32', () {
terminal.write('\x1b[?1000h\x1b[?1015h');
expect(report(TerminalMouseButton.wheelUp), '\x1b[96;11;6M');
expect(report(TerminalMouseButton.wheelDown), '\x1b[97;11;6M');
});
test('sends a null byte for coordinates past the encoding limit', () {
terminal.write('\x1b[?1000h');
expect(
report(
TerminalMouseButton.wheelUp,
TerminalMouseButtonState.down,
const CellOffset(300, 300),
),
'\x1b[M${String.fromCharCode(32 + 64)}\x00\x00',
);
});
test('leaves non-wheel buttons to the upstream handler', () {
terminal.write('\x1b[?1000h\x1b[?1006h');
@@ -147,27 +112,6 @@ void main() {
);
});
test('stays silent when the peer has not enabled mouse reporting', () {
expect(report(TerminalMouseButton.wheelDown), isNull);
expect(report(TerminalMouseButton.left), isNull);
});
test('stays silent for the wheel in click-only mode', () {
terminal.write('\x1b[?9h\x1b[?1006h');
expect(report(TerminalMouseButton.wheelDown), isNull);
expect(report(TerminalMouseButton.left), '\x1b[<0;11;6M');
});
test('does not report wheel button releases', () {
terminal.write('\x1b[?1000h\x1b[?1006h');
expect(
report(TerminalMouseButton.wheelDown, TerminalMouseButtonState.up),
isNull,
);
});
testWidgets('dragging below scrolls and extends selection', (tester) async {
final controller = TerminalController();
_writeLines(terminal, 80);
@@ -258,42 +202,4 @@ void main() {
expect(output.last, '\x1b[<0;${endCell.x + 1};${endCell.y + 1}m');
expect(controller.suspendedPointerInputs, isFalse);
});
testWidgets('tmux drag stays suppressed after mouse mode is disabled',
(tester) async {
final controller = TerminalController();
terminal.write('\x1b[?1049h\x1b[?1002h\x1b[?1006hword');
await tester.pumpWidget(_terminalHarness(terminal, controller));
final renderTerminal = tester
.state<TerminalViewState>(find.byType(TerminalView))
.renderTerminal;
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
final start = renderTerminal.localToGlobal(const Offset(40, 40));
final end = renderTerminal.localToGlobal(const Offset(240, 80));
await mouse.down(start);
output.clear();
terminal.write('\x1b[?1002l');
await mouse.moveTo(end);
expect(output, isEmpty);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isTrue);
terminal.write('\x1b[?1002h');
await mouse.moveTo(start);
expect(output, isEmpty);
expect(controller.selection, isNull);
await mouse.up();
expect(output, isEmpty);
expect(controller.suspendedPointerInputs, isFalse);
await mouse.down(start);
output.clear();
terminal.write('\x1b[?1002l');
await mouse.up();
await tester.pump(kDoubleTapTimeout);
expect(output, isEmpty);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isFalse);
});
}
+8 -5
View File
@@ -59,19 +59,22 @@ constexpr UINT kForceRedrawMaxTries = 25;
// per call (each nudge re-enters the 100ms resize wait).
constexpr UINT kForceRedrawCheapTries = 2;
// Re-enters the embedder's OnWindowSizeChanged by nudging the Flutter child
// window by 1px and back: this resets the resize target and resends the window
// metrics. Same as BaseFlutterWindow::ForceChildRefresh() on the
// rustdesk_desktop_multi_window side.
// A nonzero intermediate width can time out before Flutter resizes its surface.
// Restoring the old width then leaves that intermediate resize pending. Zero
// width resends metrics without creating a new resize target, as in the plugin.
void ForceChildRefresh(HWND child) {
if (!child) {
return;
}
// FancyZones can queue a hide before the Flutter view is reparented.
if ((GetWindowLongPtr(child, GWL_STYLE) & WS_VISIBLE) == 0) {
ShowWindow(child, SW_SHOWNA);
}
RECT rect;
GetWindowRect(child, &rect);
LONG width = rect.right - rect.left;
LONG height = rect.bottom - rect.top;
SetWindowPos(child, nullptr, 0, 0, width + 1, height,
SetWindowPos(child, nullptr, 0, 0, 0, height,
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
SetWindowPos(child, nullptr, 0, 0, width, height,
SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
+8
View File
@@ -104,6 +104,14 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
}
if (!allow_multiple_instances) {
if (!command_line_arguments.empty()) {
// The process launched by the browser owns the foreground permission.
// Transfer it to the existing RustDesk process before dispatching the
// URI so that it can bring an existing session to the foreground.
DWORD pid = 0;
::GetWindowThreadProcessId(hwnd, &pid);
if (pid != 0) {
::AllowSetForegroundWindow(pid);
}
// Dispatch command line arguments
DispatchToUniLinksDesktop(hwnd);
} else {
+15 -2
View File
@@ -310,7 +310,9 @@ message KeyEvent {
}
message CursorData {
uint64 id = 1;
// A string in JS: a Windows peer before 1.5.0 sends its cursor handle, sign-extended above
// 2^53 when its top bit is set, which a JS number cannot hold.
uint64 id = 1 [jstype = JS_STRING];
sint32 hotx = 2;
sint32 hoty = 3;
int32 width = 4;
@@ -705,6 +707,9 @@ message TestDelay {
message PublicKey {
bytes asymmetric_value = 1;
bytes symmetric_value = 2;
// The key exchange version the controller picked, the highest both sides speak; absent,
// i.e. 0, is the original scheme.
uint32 kx_version = 3;
}
message SignedId { bytes id = 1; }
@@ -856,6 +861,12 @@ message Misc {
DisplayResolution change_display_resolution = 36;
MessageQuery message_query = 37;
int32 follow_current_display = 38;
// Since 1.5.0: send the CursorData of this id again. No controller sends this yet; it is
// here so a controller can one day bound its own shape store and ask for the shape the
// peer just selected. The peer answers with what it holds then: a shape its cache dropped
// is rebuilt, and held again, the next time it is shown, before any connection names it
// by id again, so the shape just selected is always there to give.
uint64 request_cursor_data = 39;
}
}
@@ -999,7 +1010,7 @@ message Message {
AudioFrame audio_frame = 11;
CursorData cursor_data = 12;
CursorPosition cursor_position = 13;
uint64 cursor_id = 14;
uint64 cursor_id = 14 [jstype = JS_STRING]; // as CursorData.id
KeyEvent key_event = 15;
Clipboard clipboard = 16;
FileAction file_action = 17;
@@ -1019,5 +1030,7 @@ message Message {
TerminalAction terminal_action = 31;
TerminalResponse terminal_response = 32;
PortForwardChannel port_forward_channel = 33;
// Auto Login: the peer types the password only if it is at its logon or lock screen.
OSLogin os_login = 34;
}
}
-62
View File
@@ -1677,15 +1677,6 @@ mod tests {
assert_err_contains(err, "empty file name");
}
#[test]
fn set_files_rejects_null_byte_name() {
let mut job = new_validation_job(103);
let err = job
.set_files(vec![new_file_entry("bad\0name.txt")])
.expect_err("null byte in file name must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn set_files_rejects_mixed_entries_when_one_is_traversal() {
let mut job = new_validation_job(104);
@@ -1708,39 +1699,6 @@ mod tests {
assert_err_contains(err, "absolute path");
}
#[cfg(not(windows))]
#[test]
fn set_files_allows_backslash_prefixed_name_on_unix() {
let mut job = new_validation_job(105);
assert!(job
.set_files(vec![new_file_entry("\\\\server\\share\\payload.txt")])
.is_ok());
}
#[test]
fn remove_file_rejects_empty_path() {
let err = remove_file("").expect_err("empty file path must be rejected");
assert_err_contains(err, "cannot be empty");
}
#[test]
fn remove_file_rejects_null_byte_path() {
let err = remove_file("bad\0path").expect_err("null byte path must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn create_dir_rejects_empty_path() {
let err = create_dir("").expect_err("empty directory path must be rejected");
assert_err_contains(err, "cannot be empty");
}
#[test]
fn create_dir_rejects_null_byte_path() {
let err = create_dir("bad\0path").expect_err("null byte path must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn rename_file_rejects_invalid_new_name() {
let tmp_root = TestTempDir::new("rustdesk_rename_invalid");
@@ -1790,24 +1748,4 @@ mod tests {
assert!(!src.exists());
assert!(dst.exists());
}
#[cfg(windows)]
#[test]
fn set_files_rejects_windows_drive_absolute_path() {
let mut job = new_validation_job(106);
let err = job
.set_files(vec![new_file_entry("C:\\Windows\\Temp\\payload.txt")])
.expect_err("drive-letter absolute path must be rejected");
assert_err_contains(err, "absolute path");
}
#[cfg(windows)]
#[test]
fn set_files_rejects_windows_verbatim_drive_absolute_path() {
let mut job = new_validation_job(1061);
let err = job
.set_files(vec![new_file_entry(r"\\?\C:\Windows\Temp\x.txt")])
.expect_err("verbatim drive absolute path must be rejected");
assert_err_contains(err, "absolute path");
}
}
-56
View File
@@ -515,48 +515,6 @@ pub fn get_home_dir_trusted() -> Option<PathBuf> {
mod tests {
use super::*;
#[test]
fn test_transform_degrees_maps_all_eight_variants() {
use sctk::reexports::client::protocol::wl_output::Transform;
// Flipped variants report their rotation: the frame still needs that turn to read
// upright, and the mirror half has no producer among desktop compositors to test.
for (t, deg) in [
(Transform::Normal, 0),
(Transform::_90, 90),
(Transform::_180, 180),
(Transform::_270, 270),
(Transform::Flipped, 0),
(Transform::Flipped90, 90),
(Transform::Flipped180, 180),
(Transform::Flipped270, 270),
] {
assert_eq!(transform_degrees(t), deg, "{t:?}");
}
}
#[test]
fn test_display_info_without_transform_defaults_to_zero() {
// A snapshot serialized by an older probe child carries no transform field; it must
// deserialize with 0 rather than fail, or a greeter-side child update becomes a
// lockstep upgrade.
let old = r#"{"name":"HDMI-1","x":0,"y":0,"width":1920,"height":1080,"logical_size":null,"refresh_rate":60}"#;
let info: WaylandDisplayInfo = serde_json::from_str(old).unwrap();
assert_eq!(info.transform, 0);
let roundtrip: WaylandDisplayInfo =
serde_json::from_str(&serde_json::to_string(&info).unwrap()).unwrap();
assert_eq!(roundtrip.transform, 0);
}
#[test]
fn test_run_cmds_trim_newline() {
assert_eq!(run_cmds_trim_newline("echo -n 123").unwrap(), "123");
assert_eq!(run_cmds_trim_newline("echo 123").unwrap(), "123");
assert_eq!(
run_cmds_trim_newline("whoami").unwrap() + "\n",
run_cmds("whoami").unwrap()
);
}
/// Test get_home_dir_trusted: returns valid path and ignores HOME env var
#[test]
fn test_get_home_dir_trusted() {
@@ -584,20 +542,6 @@ mod tests {
}
}
/// Test shell_quote with normal strings
#[test]
fn test_shell_quote_normal() {
assert_eq!(shell_quote("hello"), "'hello'");
assert_eq!(shell_quote("/home/user"), "'/home/user'");
}
/// Test shell_quote with spaces
#[test]
fn test_shell_quote_spaces() {
assert_eq!(shell_quote("/home/my user/file"), "'/home/my user/file'");
assert_eq!(shell_quote("path with spaces"), "'path with spaces'");
}
/// Test shell_quote with single quotes (the tricky case)
#[test]
fn test_shell_quote_single_quotes() {
-8
View File
@@ -288,11 +288,3 @@ fn send_data_to_all(data: ClipboardFile) {
allow_err!(msg_channel.sender.send(data.clone()));
}
}
#[cfg(test)]
mod tests {
// #[test]
// fn test_cliprdr_run() {
// super::cliprdr_run();
// }
}
+89 -22
View File
@@ -48,6 +48,19 @@ pub struct FileDescription {
pub creation_time: SystemTime,
pub size: u64,
pub perm: u16,
/// `file_list_id()` of the list this file came from, sent back in file contents requests
#[serde(default)]
pub clip_data_id: i32,
}
/// Identifies a file list by its descriptor PDU, which both peers hold, so file contents
/// requests can name the list they read from. FNV-1a, same as `wf_cliprdr_file_list_id()`.
pub fn file_list_id(file_descriptor_pdu: &[u8]) -> i32 {
file_descriptor_pdu
.iter()
.fold(0x811c_9dc5_u32, |id, byte| {
(id ^ *byte as u32).wrapping_mul(0x0100_0193)
}) as i32
}
pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
@@ -69,6 +82,7 @@ impl FileDescription {
fn parse_file_descriptor(
bytes: &mut Bytes,
conn_id: i32,
clip_data_id: i32,
) -> Result<FileDescription, CliprdrError> {
let flags = bytes.get_u32_le();
// skip reserved 32 bytes
@@ -126,12 +140,13 @@ impl FileDescription {
// cannot set as is...
} else if normal {
PERM_RWX
} else if directory {
// Windows ignores read-only and hidden on a directory; without `x` it cannot be entered.
PERM_RWX
} else if readonly {
PERM_READ
} else if hidden {
PERM_SELF_RO
} else if directory {
PERM_RWX
} else {
PERM_RW
};
@@ -154,8 +169,11 @@ impl FileDescription {
let valid_write_time = flags & FLAGS_FD_LAST_WRITE != 0;
let last_modified = if valid_write_time && last_write_time >= LDAP_EPOCH_DELTA {
let last_write_time = (last_write_time - LDAP_EPOCH_DELTA) * 100;
let last_write_time = Duration::from_nanos(last_write_time);
let last_write_time = last_write_time - LDAP_EPOCH_DELTA;
let last_write_time = Duration::new(
last_write_time / 10_000_000,
(last_write_time % 10_000_000) as u32 * 100,
);
SystemTime::UNIX_EPOCH + last_write_time
} else {
SystemTime::UNIX_EPOCH
@@ -175,6 +193,7 @@ impl FileDescription {
creation_time: last_modified,
size,
perm,
clip_data_id,
};
Ok(desc)
@@ -186,6 +205,7 @@ impl FileDescription {
file_descriptor_pdu: Vec<u8>,
conn_id: i32,
) -> Result<Vec<Self>, CliprdrError> {
let clip_data_id = file_list_id(&file_descriptor_pdu);
let mut data = Bytes::from(file_descriptor_pdu);
if data.remaining() < 4 {
return Err(CliprdrError::InvalidRequest {
@@ -206,7 +226,7 @@ impl FileDescription {
let mut files = Vec::with_capacity(count);
for _ in 0..count {
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
files.push(desc);
}
@@ -222,9 +242,8 @@ mod tests {
const PDU_HEADER_SIZE: usize = size_of::<u32>();
const DESCRIPTOR_SIZE: usize = 592;
const ATTRIBUTES_OFFSET: usize = PDU_HEADER_SIZE + 36;
const LAST_WRITE_TIME_OFFSET: usize = PDU_HEADER_SIZE + 56;
const NAME_OFFSET: usize = PDU_HEADER_SIZE + 72;
const FILE_NAME_CODE_UNITS: usize = 260;
const INVALID_UTF16_UNIT: u16 = 0xdc00;
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
fn descriptor_pdu(name: &str) -> Vec<u8> {
@@ -271,23 +290,71 @@ mod tests {
}
#[test]
fn ignores_data_after_null_terminator() {
let name = "file.txt";
let mut pdu = descriptor_pdu(name);
let padding_offset = NAME_OFFSET + (name.encode_utf16().count() + 1) * size_of::<u16>();
pdu[padding_offset..padding_offset + size_of::<u16>()]
.copy_from_slice(&INVALID_UTF16_UNIT.to_le_bytes());
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
assert_eq!(files[0].name, PathBuf::from("file.txt"));
fn file_list_id_is_fnv1a() {
// Reference vectors; the Windows side computes the same id in C.
assert_eq!(file_list_id(b"") as u32, 0x811c_9dc5);
assert_eq!(file_list_id(b"a") as u32, 0xe40c_292c);
assert_eq!(file_list_id(b"foobar") as u32, 0xbf9c_f968);
}
#[test]
fn rejects_non_terminated_file_name() {
let name = "a".repeat(FILE_NAME_CODE_UNITS);
assert!(matches!(
parse_name(&name),
Err(CliprdrError::InvalidRequest { .. })
));
fn parsed_files_carry_their_list_id() {
let pdu = descriptor_pdu("file.txt");
let id = file_list_id(&pdu);
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
assert_eq!(files[0].clip_data_id, id);
}
fn parse_perm(attributes: u32) -> u16 {
let mut pdu = descriptor_pdu("folder");
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
.copy_from_slice(&attributes.to_le_bytes());
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].perm
}
#[test]
fn windows_directories_stay_searchable() {
const FILE_ATTRIBUTE_READONLY: u32 = 0x01;
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x02;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
for attributes in [
FILE_ATTRIBUTE_DIRECTORY,
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_READONLY,
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN,
] {
assert_eq!(
parse_perm(attributes),
PERM_RWX,
"attributes {attributes:#x}"
);
}
}
fn parse_last_write_time(filetime: u64) -> SystemTime {
let mut pdu = descriptor_pdu("file.txt");
pdu[PDU_HEADER_SIZE..PDU_HEADER_SIZE + size_of::<u32>()]
.copy_from_slice(&(FLAGS_FD_ATTRIBUTES | FLAGS_FD_LAST_WRITE).to_le_bytes());
pdu[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + size_of::<u64>()]
.copy_from_slice(&filetime.to_le_bytes());
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].last_modified
}
#[test]
fn decodes_last_write_time_from_windows_filetime() {
// 2023-11-14 22:13:20 UTC
assert_eq!(
parse_last_write_time(133_444_736_000_000_000),
SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000)
);
// 3000-01-01 00:00:00 UTC
assert_eq!(
parse_last_write_time(441_481_536_000_000_000),
SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000)
);
// 1969-12-31 23:59:59 UTC falls back to the Unix epoch.
assert_eq!(
parse_last_write_time(116_444_736_000_000_000 - 10_000_000),
SystemTime::UNIX_EPOCH
);
}
}
+8 -31
View File
@@ -549,8 +549,8 @@ impl FuseServer {
n_position_low,
n_position_high,
cb_requested,
have_clip_data_id: false,
clip_data_id: 0,
have_clip_data_id: true,
clip_data_id: node.clip_data_id,
};
send_data(node.conn_id, request.clone()).map_err(|e| {
@@ -611,6 +611,9 @@ struct FuseNode {
/// connection id
pub conn_id: i32,
/// id of the peer's file list this node came from
pub clip_data_id: i32,
/// file index in peer's file list
/// NOTE:
/// it is NOT the same as inode, this is the index in the file list
@@ -634,6 +637,7 @@ impl FuseNode {
pub fn from_description(inode: Inode, desc: FileDescription) -> Self {
Self {
conn_id: desc.conn_id,
clip_data_id: desc.clip_data_id,
index: inode as usize - 2,
name: desc
.name
@@ -650,6 +654,7 @@ impl FuseNode {
pub fn new_root() -> Self {
Self {
conn_id: 0,
clip_data_id: 0,
index: 0,
name: String::from("/"),
parent: None,
@@ -898,6 +903,7 @@ mod fuse_test {
size: 0,
perm: 0,
clip_data_id: 0,
}
}
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
@@ -960,35 +966,6 @@ mod fuse_test {
}
}
fn build_single_file(prefix: &str) {
let raw_name = "simple_test_file.txt";
let f_name = if prefix == "" {
raw_name.to_string()
} else {
prefix.to_string() + "/" + raw_name
};
let desc = desc_gen(&f_name, FileType::File);
let tree = FuseNode::build_tree(vec![desc]).unwrap();
assert_eq!(tree.len(), 2);
assert_eq!(tree[0].name, "/");
assert_eq!(tree[0].children, vec![2]);
assert_eq!(tree[1].name, raw_name);
assert_eq!(tree[1].index, 0);
assert_eq!(tree[1].attributes.kind, FileType::File);
}
#[test]
fn test_parse_single() {
build_single_file("");
build_single_file("/");
build_single_file("test");
build_single_file("/test");
build_single_file("🗂");
build_single_file("/🗂");
}
#[test]
fn test_parse_tree() {
build_tree("");
+29 -26
View File
@@ -160,12 +160,12 @@ impl LocalFile {
| archive_flag
| normal_flag;
let win32_time = self
let win32_time = (self
.last_write_time
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64
/ 100
.as_nanos()
/ 100) as u64
+ LDAP_EPOCH_DELTA;
let size_high = (self.size >> 32) as u32;
@@ -322,7 +322,8 @@ pub(super) fn construct_file_list(paths: &[PathBuf]) -> Result<Vec<LocalFile>, C
mod file_list_test {
use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
sync::atomic::AtomicU64,
time::{Duration, SystemTime},
};
use hbb_common::bytes::{BufMut, BytesMut};
@@ -465,29 +466,31 @@ mod file_list_test {
Ok(())
}
const LAST_WRITE_TIME_OFFSET: usize = 56;
fn file_with_last_write_time(last_write_time: SystemTime) -> LocalFile {
let mut file = generate_tree("").remove(1);
file.last_write_time = last_write_time;
file
}
fn encoded_last_write_time(last_write_time: SystemTime) -> Result<u64, CliprdrError> {
let descriptor = file_with_last_write_time(last_write_time).as_bin()?;
let field = &descriptor[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + 8];
Ok(u64::from_le_bytes(field.try_into().unwrap()))
}
#[test]
fn read_exact_at_reopens_after_read_failure() -> Result<(), Box<dyn std::error::Error>> {
let file_path = std::env::temp_dir().join(format!(
"rustdesk-clipboard-local-file-{}",
std::process::id()
));
std::fs::write(&file_path, b"")?;
let mut file = LocalFile::try_open(&std::env::temp_dir(), &file_path)?;
file.size = 1;
let mut buf = [0u8; 1];
assert!(file.read_exact_at(&mut buf, 0).is_err());
assert!(file.handle.is_none());
assert_eq!(file.offset.load(Ordering::Relaxed), 0);
std::fs::write(&file_path, [42u8])?;
file.read_exact_at(&mut buf, 0)?;
assert_eq!(buf, [42u8]);
assert!(file.handle.is_none());
std::fs::remove_file(file_path)?;
fn encodes_last_write_time_as_windows_filetime() -> Result<(), CliprdrError> {
// 2023-11-14 22:13:20 UTC
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
assert_eq!(encoded_last_write_time(time)?, 133_444_736_000_000_000);
// 3000-01-01 00:00:00 UTC
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000);
assert_eq!(encoded_last_write_time(time)?, 441_481_536_000_000_000);
// Times before 1970 are sent as 1970-01-01 00:00:00 UTC.
let time = SystemTime::UNIX_EPOCH - Duration::from_secs(1);
assert_eq!(encoded_last_write_time(time)?, 116_444_736_000_000_000);
Ok(())
}
}
@@ -4,6 +4,8 @@ use crate::{
};
use base::fs::join_validated_path;
use hbb_common::{allow_err, log, tokio::time::Instant};
use objc2::rc::Id;
use objc2_foundation::NSProgress;
use std::{
cmp::min,
fs::{File, FileTimes, OpenOptions},
@@ -15,7 +17,7 @@ use std::{
Arc, Mutex,
},
thread,
time::{Duration, SystemTime},
time::Duration,
};
const RECV_RETRY_TIMES: usize = 3;
@@ -23,15 +25,16 @@ const RECV_RETRY_TIMES: usize = 3;
const DOWNLOAD_EXTENSION: &str = "rddownload";
const RECEIVE_WAIT_TIMEOUT: Duration = Duration::from_millis(5_000);
// https://stackoverflow.com/a/15112784/1926020
// "1984-01-24 08:00:00 +0000"
const TIMESTAMP_FOR_FILE_PROGRESS_COMPLETED: u64 = 443779200;
const ATTR_PROGRESS_FRACTION_COMPLETED: &str = "com.apple.progress.fractionCompleted";
fn create_new_file(path: impl AsRef<Path>) -> std::io::Result<File> {
OpenOptions::new().write(true).create_new(true).open(path)
}
fn finder_progress_byte_count(bytes: u64) -> Result<i64, CliprdrError> {
i64::try_from(bytes).map_err(|_| CliprdrError::InvalidRequest {
description: format!("File progress byte count exceeds i64::MAX: {bytes}"),
})
}
pub struct FileContentsResponse {
pub conn_id: i32,
pub msg_flags: i32,
@@ -53,6 +56,7 @@ struct PasteTaskProgress {
download_file_path: String,
download_file_current_size: u64,
file_handle: Option<BufWriter<File>>,
finder_progress: Option<Id<NSProgress>>,
error: Option<CliprdrError>,
is_canceled: bool,
}
@@ -116,6 +120,7 @@ impl PasteTask {
download_file_path: "".to_owned(),
download_file_current_size: 0,
file_handle: None,
finder_progress: None,
error: None,
is_canceled: false,
},
@@ -318,7 +323,7 @@ impl PasteTaskHandle {
} else {
self.progress.offset += size;
self.progress.download_file_current_size += size;
self.update_progress_completed(None);
self.update_progress_completed(None)?;
}
if self.progress.file_handle.is_none() {
self.progress.list_index = self.files.len() as i32;
@@ -329,44 +334,52 @@ impl PasteTaskHandle {
Ok(())
}
fn start_progress_completed(&self) {
if let Some(file) = self.progress.file_handle.as_ref() {
let creation_time =
SystemTime::UNIX_EPOCH + Duration::from_secs(TIMESTAMP_FOR_FILE_PROGRESS_COMPLETED);
file.get_ref()
.set_times(FileTimes::new().set_created(creation_time))
.ok();
xattr::set(
&self.progress.download_file_path,
ATTR_PROGRESS_FRACTION_COMPLETED,
"0.0".as_bytes(),
)
.ok();
}
fn start_progress_completed(&mut self) -> Result<(), CliprdrError> {
use objc2::rc::autoreleasepool;
use objc2_foundation::{
NSProgressFileOperationKindDownloading, NSProgressKindFile, NSString, NSURL,
};
let total_bytes = finder_progress_byte_count(self.progress.download_file_size)?;
// Finder can retain the legacy timestamp/xattr indicator after a single-chunk transfer.
autoreleasepool(|_| unsafe {
let progress = NSProgress::discreteProgressWithTotalUnitCount(total_bytes);
let url =
NSURL::fileURLWithPath(&NSString::from_str(&self.progress.download_file_path));
progress.setKind(Some(NSProgressKindFile));
progress.setFileOperationKind(Some(NSProgressFileOperationKindDownloading));
progress.setFileURL(Some(&url));
progress.setCancellable(false);
progress.setPausable(false);
progress.publish();
self.progress.finder_progress = Some(progress);
});
Ok(())
}
fn update_progress_completed(&mut self, fraction_completed: Option<f64>) {
let fraction_completed = fraction_completed.unwrap_or_else(|| {
let current_size = self.progress.download_file_current_size as f64;
let total_size = self.progress.download_file_size as f64;
if total_size > 0.0 {
current_size / total_size
} else {
1.0
}
});
xattr::set(
&self.progress.download_file_path,
ATTR_PROGRESS_FRACTION_COMPLETED,
&fraction_completed.to_string().as_bytes(),
)
.ok();
fn update_progress_completed(
&mut self,
completed_bytes: Option<u64>,
) -> Result<(), CliprdrError> {
use objc2::rc::autoreleasepool;
let completed_bytes = finder_progress_byte_count(
completed_bytes.unwrap_or(self.progress.download_file_current_size),
)?;
if let Some(progress) = self.progress.finder_progress.as_ref() {
autoreleasepool(|_| unsafe {
progress.setCompletedUnitCount(completed_bytes);
});
}
Ok(())
}
#[inline]
fn remove_progress_completed(path: &str) {
if !path.is_empty() {
xattr::remove(path, ATTR_PROGRESS_FRACTION_COMPLETED).ok();
fn remove_progress_completed(&mut self) {
use objc2::rc::autoreleasepool;
if let Some(progress) = self.progress.finder_progress.take() {
autoreleasepool(|_| unsafe { progress.unpublish() });
}
}
@@ -416,7 +429,7 @@ impl PasteTaskHandle {
self.progress.download_file_path = download_file_path;
self.progress.download_file_current_size = 0;
self.progress.file_handle = Some(writer);
self.start_progress_completed();
self.start_progress_completed()?;
}
Err(e) => {
self.progress.error = Some(CliprdrError::FileError {
@@ -522,14 +535,12 @@ impl PasteTaskHandle {
}
fn on_cancelled(&mut self) {
self.remove_progress_completed();
self.progress.file_handle = None;
std::fs::remove_file(&self.progress.download_file_path).ok();
}
fn on_done(&mut self) -> Result<(), CliprdrError> {
self.update_progress_completed(Some(1.0));
Self::remove_progress_completed(&self.progress.download_file_path);
let Some(file) = self.progress.file_handle.as_mut() else {
return Ok(());
};
@@ -542,6 +553,11 @@ impl PasteTaskHandle {
log::error!("Failed to flush file: {:?}", e);
}
self.progress.file_handle = None;
// Updating or unpublishing after rename can leave stale Finder/Dock progress.
// https://crbug.com/40217637
// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/download/download_status_updater_mac.mm
self.update_progress_completed(Some(self.progress.download_file_size))?;
self.remove_progress_completed();
let Some(file_desc) = self.files.get(self.progress.download_file_index as usize) else {
// unreachable
@@ -617,6 +633,7 @@ impl PasteTaskHandle {
};
let cb_requested = min(BLOCK_SIZE as u64, file.size - self.progress.offset);
let conn_id = file.conn_id;
let clip_data_id = file.clip_data_id;
let (n_position_high, n_position_low) = (
(self.progress.offset >> 32) as i32,
@@ -629,8 +646,8 @@ impl PasteTaskHandle {
n_position_low,
n_position_high,
cb_requested: cb_requested as _,
have_clip_data_id: false,
clip_data_id: 0,
have_clip_data_id: true,
clip_data_id,
};
allow_err!(send_data(conn_id, request));
self.progress.last_sent_time = Instant::now();
@@ -669,10 +686,16 @@ impl PasteTaskHandle {
}
}
impl Drop for PasteTaskHandle {
fn drop(&mut self) {
self.remove_progress_completed();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::symlink;
use std::{os::unix::fs::symlink, time::SystemTime};
struct TestDirectory(PathBuf);
@@ -703,6 +726,7 @@ mod tests {
creation_time: SystemTime::UNIX_EPOCH,
size,
perm: 0,
clip_data_id: 0,
}
}
@@ -719,6 +743,7 @@ mod tests {
download_file_path: String::new(),
download_file_current_size: 0,
file_handle: None,
finder_progress: None,
error: None,
is_canceled: false,
},
@@ -727,6 +752,63 @@ mod tests {
}
}
#[test]
fn finder_progress_completes_single_response_transfer() {
let (_temp, target, _) = test_directories();
let data = b"single response";
let file = file_description("small.txt", FileType::File, data.len() as u64);
let mut task = paste_task_handle(target.clone(), vec![file]);
task.update_next(0).unwrap();
let download_path = PathBuf::from(&task.progress.download_file_path);
let progress = task.progress.finder_progress.as_ref().unwrap().clone();
assert_eq!(unsafe { progress.completedUnitCount() }, 0);
task.handle_file_contents_response(FileContentsResponse {
conn_id: 0,
msg_flags: 1,
stream_id: 0,
requested_data: data.to_vec(),
})
.unwrap();
unsafe {
assert_eq!(progress.totalUnitCount(), data.len() as i64);
assert_eq!(progress.completedUnitCount(), progress.totalUnitCount());
assert!(progress.isFinished());
}
assert!(task.progress.finder_progress.is_none());
assert!(task.progress.file_handle.is_none());
assert!(task.is_finished());
assert!(task.progress.error.is_none());
assert!(!download_path.exists());
assert_eq!(std::fs::read(target.join("small.txt")).unwrap(), data);
}
#[test]
fn finder_progress_reports_bytes_below_one_percent() {
let (_temp, target, _) = test_directories();
let size = u32::MAX as u64 + 1;
let file = file_description("large.bin", FileType::File, size);
let mut task = paste_task_handle(target, vec![file]);
task.update_next(0).unwrap();
task.handle_file_contents_response(FileContentsResponse {
conn_id: 0,
msg_flags: 1,
stream_id: 0,
requested_data: vec![1],
})
.unwrap();
let progress = task.progress.finder_progress.as_ref().unwrap();
unsafe {
assert_eq!(progress.totalUnitCount(), size as i64);
assert_eq!(progress.completedUnitCount(), 1);
}
task.on_cancelled();
assert!(task.progress.finder_progress.is_none());
assert!(!Path::new(&task.progress.download_file_path).exists());
}
#[test]
fn validates_all_paths_before_creating_files() {
let (_temp, target, outside) = test_directories();
@@ -772,18 +854,4 @@ mod tests {
assert!(!download_path.exists());
assert!(!outside.join("file.txt").exists());
}
#[test]
fn rejects_symlink_component_when_creating_directory() {
let (_temp, target, outside) = test_directories();
symlink(&outside, target.join("link")).unwrap();
let directory = file_description("link/escaped", FileType::Directory, 0);
let mut task = paste_task_handle(target, vec![directory]);
assert!(matches!(
task.update_next(0),
Err(CliprdrError::InvalidRequest { .. })
));
assert!(!outside.join("escaped").exists());
}
}
@@ -430,31 +430,3 @@ pub fn create_pasteboard_context() -> ResultType<Box<PasteboardContext>> {
context.init();
Ok(context)
}
#[cfg(test)]
mod tests {
#[test]
fn test_temp_files_count() {
let mut c = super::PasteboardContext::temp_files_count();
let mut created_files = vec![];
for _ in 0..10 {
let path = format!(
"/tmp/{}{}",
super::TEMP_FILE_PREFIX,
uuid::Uuid::new_v4().to_string()
);
if std::fs::File::create(&path).is_ok() {
created_files.push(path);
c += 1;
}
}
assert_eq!(c, super::PasteboardContext::temp_files_count());
// Clean up the created files.
for file in created_files {
std::fs::remove_file(&file).ok();
}
}
}
+2 -1
View File
@@ -40,7 +40,8 @@ pub(super) const FILE_NAME_FIELD_SIZE: usize = FILE_NAME_CODE_UNITS * std::mem::
// begin of epoch used by microsoft
// 1601-01-01 00:00:00 + LDAP_EPOCH_DELTA*(100 ns) = 1970-01-01 00:00:00
const LDAP_EPOCH_DELTA: u64 = 116444772610000000;
// 134_774 days (369 years, 89 leap days) * 86_400 s * 10_000_000 per s
const LDAP_EPOCH_DELTA: u64 = 116_444_736_000_000_000;
lazy_static! {
static ref REMOTE_FORMAT_MAP: DashMap<i32, String> = DashMap::from_iter(
+390 -49
View File
@@ -1,11 +1,27 @@
use super::local_file::LocalFile;
use crate::{platform::unix::local_file::construct_file_list, ClipboardFile, CliprdrError};
use crate::{
platform::unix::{
filetype::file_list_id,
local_file::{construct_file_list, LocalFile},
},
ClipboardFile, CliprdrError,
};
use hbb_common::{
bytes::{BufMut, BytesMut},
log,
};
use parking_lot::Mutex;
use std::{path::PathBuf, sync::Arc, time::SystemTime, usize};
use std::{
collections::VecDeque,
path::PathBuf,
sync::{atomic::Ordering, Arc},
time::SystemTime,
usize,
};
// Our clients request at most this much per range: macOS 4 MiB, FUSE less, and Windows
// splits larger reads (WF_CLIPRDR_MAX_RANGE_READ). A larger read is refused, not shortened:
// a short response reads as end of file to IStream callers on Windows.
const MAX_RANGE_READ: u64 = 16 * 1024 * 1024;
lazy_static::lazy_static! {
// local files are cached, this value should not be changed when copying files
@@ -13,8 +29,18 @@ lazy_static::lazy_static! {
// We need to keep the file list in the same order as the remote side.
// We may add a `FileId` field to `CliprdrFileContentsRequest` in the future.
static ref CLIP_FILES: Arc<Mutex<ClipFiles>> = Default::default();
// Lists replaced by a newer copy after a peer was sent them, oldest first. The peer's
// streams keep reading the list they came from. Lock after `CLIP_FILES`.
static ref RETIRED_CLIP_FILES: Mutex<VecDeque<ClipFiles>> = Default::default();
}
const MAX_RETIRED_CLIP_FILES: usize = 4;
// The first descriptor's `clsid`, inside the 32 reserved bytes every peer skips. A random
// nonce there makes each copy's list id distinct, even when two copies have identical
// names, sizes and times (the same file in two folders).
const LIST_NONCE: std::ops::Range<usize> = 8..24;
#[derive(Debug)]
enum FileContentsRequest {
Size {
@@ -62,6 +88,10 @@ struct ClipFiles {
file_list: Vec<LocalFile>,
first_file_index: usize,
files_pdu: Vec<u8>,
// `file_list_id(files_pdu)`, which peers send back as `clip_data_id`.
id: i32,
// Connections that were sent `files_pdu`.
served_to: Vec<i32>,
}
impl ClipFiles {
@@ -71,6 +101,8 @@ impl ClipFiles {
self.file_list.clear();
self.first_file_index = usize::MAX;
self.files_pdu.clear();
self.id = 0;
self.served_to.clear();
}
fn sync_files(
@@ -100,9 +132,54 @@ impl ClipFiles {
data.put(file.as_bin()?.as_slice());
}
self.files_pdu = data.to_vec();
if let Some(nonce) = self.files_pdu.get_mut(LIST_NONCE) {
nonce.copy_from_slice(&rand::random::<[u8; 16]>());
}
self.id = file_list_id(&self.files_pdu);
Ok(())
}
// Close files that are not being read, such as the preloaded next file; `read_exact_at`
// reopens them on the next read. A file part-way through keeps its handle and offset, so
// its remaining bytes come from the same file even if its path is replaced meanwhile.
fn release_handles(&mut self) {
for file in self.file_list.iter_mut() {
if file.offset.load(Ordering::Relaxed) == 0 {
file.handle = None;
}
}
}
// A retired list's file is reopened by path once its handle was closed, and the path may now
// name a replacement. Check size and modified time on the handle the read will use, and refuse
// a file that no longer matches the list.
fn check_retired_file(&mut self, request: &FileContentsRequest) -> Result<(), CliprdrError> {
let FileContentsRequest::Range { file_idx, .. } = request else {
return Ok(());
};
let Some(file) = self.file_list.get_mut(*file_idx) else {
return Ok(());
};
if file.is_dir {
return Ok(());
}
file.load_handle()?;
let unchanged = file
.handle
.as_ref()
.and_then(|handle| handle.get_ref().metadata().ok())
.map_or(false, |md| {
md.len() == file.size && md.modified().ok() == Some(file.last_write_time)
});
if unchanged {
Ok(())
} else {
Err(CliprdrError::InvalidRequest {
description: format!("file {} changed since its list was sent", file.name),
})
}
}
fn get_files_for_audit(&self, request: &FileContentsRequest) -> Option<ClipboardFile> {
if let FileContentsRequest::Range {
file_idx, offset, ..
@@ -213,12 +290,21 @@ impl ClipFiles {
),
});
}
let read_size = if offset + length > file.size {
let read_size = if length > file.size - offset {
file.size - offset
} else {
length
};
if read_size > MAX_RANGE_READ {
return Err(CliprdrError::InvalidRequest {
description: format!(
"file contents request of {} bytes exceeds the {} byte limit, conn: {}",
read_size, MAX_RANGE_READ, conn_id
),
});
}
let mut buf = vec![0u8; read_size as usize];
file.read_exact_at(&mut buf, offset)?;
@@ -238,7 +324,10 @@ impl ClipFiles {
// hot reload next file
for next_file in self.file_list.iter_mut().skip(file_idx + 1) {
if !next_file.is_dir {
next_file.load_handle()?;
// Best-effort: if it still cannot be opened, its own request reports that.
if let Err(e) = next_file.load_handle() {
log::trace!("failed to preload the next file: {:?}", e);
}
break;
}
}
@@ -249,6 +338,44 @@ impl ClipFiles {
#[inline]
pub fn clear_files() {
CLIP_FILES.lock().clear();
RETIRED_CLIP_FILES.lock().clear();
}
// The list a request reads from: the one its `clip_data_id` names, else the one last sent to
// the connection. A named list that is gone yields `None`. A peer that sends no id and was
// never sent a list reads the current one, as before.
fn select_clip_files<'a>(
current: &'a mut ClipFiles,
retired: &'a mut VecDeque<ClipFiles>,
conn_id: i32,
clip_data_id: Option<i32>,
) -> Option<&'a mut ClipFiles> {
match clip_data_id {
Some(id) if current.id == id => Some(current),
Some(id) => retired
.iter_mut()
.rev()
.find(|files| files.id == id && files.served_to.contains(&conn_id)),
None if current.served_to.contains(&conn_id) => Some(current),
None => retired
.iter_mut()
.rev()
.find(|files| files.served_to.contains(&conn_id))
.or(Some(current)),
}
}
// Keep a list a peer was sent, so its streams do not read the new copy at the same indexes.
fn retire_if_served(mut replaced: ClipFiles) {
if replaced.served_to.is_empty() {
return;
}
replaced.release_handles();
let mut retired = RETIRED_CLIP_FILES.lock();
if retired.len() == MAX_RETIRED_CLIP_FILES {
retired.pop_front();
}
retired.push_back(replaced);
}
pub fn read_file_contents(
@@ -259,6 +386,7 @@ pub fn read_file_contents(
n_position_low: i32,
n_position_high: i32,
cb_requested: i32,
clip_data_id: Option<i32>,
) -> Vec<Result<ClipboardFile, CliprdrError>> {
let fcr = if dw_flags == 0x1 {
FileContentsRequest::Size {
@@ -266,8 +394,11 @@ pub fn read_file_contents(
file_idx: list_index as usize,
}
} else if dw_flags == 0x2 {
let offset = (n_position_high as u64) << 32 | n_position_low as u64;
let length = cb_requested as u64;
// nPositionLow and cbRequested are UINT32s carried in i32 fields. Sign-extending
// them rejects offsets whose low word is >= 2 GiB and turns a negative length
// into a near-u64::MAX read.
let offset = (n_position_high as u64) << 32 | n_position_low as u32 as u64;
let length = cb_requested as u32 as u64;
FileContentsRequest::Range {
stream_id,
@@ -281,7 +412,23 @@ pub fn read_file_contents(
})];
};
let mut clip_files = CLIP_FILES.lock();
let mut current = CLIP_FILES.lock();
let mut retired = RETIRED_CLIP_FILES.lock();
let current_ptr: *const ClipFiles = &*current;
let Some(clip_files) = select_clip_files(&mut current, &mut retired, conn_id, clip_data_id)
else {
return vec![Err(CliprdrError::InvalidRequest {
description: format!(
"file list {:?} is not available to conn: {}",
clip_data_id, conn_id
),
})];
};
if !std::ptr::eq(&*clip_files, current_ptr) {
if let Err(e) = clip_files.check_retired_file(&fcr) {
return vec![Err(e)];
}
}
let mut res = vec![];
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
res.push(Ok(files_res));
@@ -301,12 +448,21 @@ pub fn sync_files(files: &[String]) -> Result<(), CliprdrError> {
{
return Ok(());
}
files_lock.sync_files(files, current)?;
files_lock.build_file_list_pdu()
// Build aside, so a failure leaves the current list in place.
let mut next = ClipFiles::default();
next.sync_files(files, current)?;
next.build_file_list_pdu()?;
let replaced = std::mem::replace(&mut *files_lock, next);
retire_if_served(replaced);
Ok(())
}
pub fn get_file_list_pdu() -> Vec<u8> {
CLIP_FILES.lock().files_pdu.clone()
pub fn get_file_list_pdu(conn_id: i32) -> Vec<u8> {
let mut clip_files = CLIP_FILES.lock();
if !clip_files.files_pdu.is_empty() && !clip_files.served_to.contains(&conn_id) {
clip_files.served_to.push(conn_id);
}
clip_files.files_pdu.clone()
}
#[cfg(test)]
@@ -343,46 +499,28 @@ mod sig_test {
p.to_string_lossy().to_string()
}
#[test]
fn fingerprint_missing_path_is_default() {
let tmp = TmpDir::new("missing");
let missing = path_str(&tmp.join("does_not_exist.bin"));
let sigs = fingerprint(&[missing]);
assert_eq!(sigs.len(), 1);
// A path that can't be stat'd -> default sig, which forces a rebuild.
assert_eq!(sigs[0], FileSig::default());
assert_eq!(sigs[0].mtime, None);
// Tests that drive the global CLIP_FILES must not interleave.
static CLIP_FILES_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn lock_clip_files() -> std::sync::MutexGuard<'static, ()> {
CLIP_FILES_TEST_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[test]
fn fingerprint_detects_inplace_edit() {
let tmp = TmpDir::new("edit");
let file = tmp.join("a.bin");
fs::write(&file, b"small").unwrap();
let p = path_str(&file);
let before = fingerprint(&[p.clone()]);
// Same content, same path: fingerprint must be stable.
let again = fingerprint(&[p.clone()]);
assert_eq!(before, again);
assert_eq!(before[0].size, 5);
assert!(!before[0].is_dir);
// Edit in place so the file grows.
fs::write(&file, b"much larger contents than before").unwrap();
let after = fingerprint(&[p]);
assert_ne!(before, after);
assert!(after[0].size > before[0].size);
// Sparse, so a multi-GiB file costs no disk space.
fn write_at(path: &PathBuf, offset: u64, data: &[u8]) {
use std::io::{Seek, SeekFrom, Write};
let mut f = fs::File::create(path).unwrap();
f.seek(SeekFrom::Start(offset)).unwrap();
f.write_all(data).unwrap();
}
#[test]
fn fingerprint_flags_directory() {
let tmp = TmpDir::new("dir");
let sub = tmp.join("subdir");
fs::create_dir_all(&sub).unwrap();
let sigs = fingerprint(&[path_str(&sub)]);
assert_eq!(sigs.len(), 1);
assert!(sigs[0].is_dir);
fn range_data(res: Vec<Result<ClipboardFile, CliprdrError>>) -> Vec<u8> {
match res.into_iter().last() {
Some(Ok(ClipboardFile::FileContentsResponse { requested_data, .. })) => requested_data,
other => panic!("unexpected response: {:?}", other),
}
}
#[test]
@@ -393,7 +531,8 @@ mod sig_test {
let files = vec![path_str(&file)];
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
// reset first (this is the only test that touches the global).
// reset first.
let _guard = lock_clip_files();
clear_files();
sync_files(&files).unwrap();
@@ -415,4 +554,206 @@ mod sig_test {
clear_files(); // leave the global clean for other tests
}
#[test]
fn range_request_decodes_wire_fields_as_u32() {
let tmp = TmpDir::new("decode");
let small = tmp.join("small.bin");
fs::write(&small, b"0123456789").unwrap();
let large = tmp.join("large.bin");
write_at(&large, 0x8000_0000, b"tail");
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&small), path_str(&large)]).unwrap();
let small_idx = CLIP_FILES.lock().first_file_index as i32;
let large_idx = small_idx + 1;
// A negative cbRequested is a UINT32 length, clamped to the rest of the file.
let res = read_file_contents(0, 0, small_idx, 0x2, 1, 0, -1, None);
assert_eq!(range_data(res), b"123456789");
// An nPositionLow with bit 31 set is an offset past 2 GiB, not a huge one.
let res = read_file_contents(0, 0, large_idx, 0x2, 0x8000_0000u32 as i32, 0, 4, None);
assert_eq!(range_data(res), b"tail");
clear_files();
}
#[test]
fn range_request_over_limit_is_rejected() {
let tmp = TmpDir::new("limit");
let file = tmp.join("big.bin");
let size = MAX_RANGE_READ + 1;
write_at(&file, size - 1, b"x");
let files = vec![path_str(&file)];
let mut clip = ClipFiles::default();
clip.sync_files(&files, fingerprint(&files)).unwrap();
let file_idx = clip.first_file_index;
let res = clip.serve_file_contents(
0,
FileContentsRequest::Range {
stream_id: 0,
file_idx,
offset: 0,
length: u32::MAX as u64,
},
);
assert!(matches!(res, Err(CliprdrError::InvalidRequest { .. })));
}
#[test]
fn host_copy_during_transfer_keeps_serving_the_sent_list() {
let tmp = TmpDir::new("recopy_in_flight");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
get_file_list_pdu(1);
let idx = CLIP_FILES.lock().first_file_index as i32;
let read = |offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, None));
assert_eq!(read(0), b"AAAA");
// Copying another file on this side must not redirect the peer's stream.
sync_files(&[path_str(&second)]).unwrap();
assert_eq!(read(4), b"AAAA");
clear_files();
}
#[test]
fn stream_keeps_its_list_after_a_second_paste() {
let tmp = TmpDir::new("repaste_in_flight");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let first_id = file_list_id(&get_file_list_pdu(1));
let idx = CLIP_FILES.lock().first_file_index as i32;
// The peer copies the second file on this side and pastes it while the first
// transfer is still reading.
sync_files(&[path_str(&second)]).unwrap();
let second_id = file_list_id(&get_file_list_pdu(1));
assert_ne!(first_id, second_id);
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
assert_eq!(read(first_id), b"AAAA");
assert_eq!(read(second_id), b"BBBB");
clear_files();
}
#[test]
fn named_list_must_have_been_sent_to_the_conn() {
let tmp = TmpDir::new("foreign_list");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let first_id = file_list_id(&get_file_list_pdu(1));
let idx = CLIP_FILES.lock().first_file_index as i32;
sync_files(&[path_str(&second)]).unwrap();
let refused = |conn_id, id| {
matches!(
read_file_contents(conn_id, 7, idx, 0x2, 0, 0, 4, Some(id)).last(),
Some(Err(CliprdrError::InvalidRequest { .. }))
)
};
// Retired list, asked for by a connection it was never sent to.
assert!(refused(2, first_id));
// A list id this side never sent.
assert!(refused(1, first_id ^ 1));
clear_files();
}
fn list_files(selection: &[&PathBuf]) -> ClipFiles {
let files: Vec<String> = selection.iter().map(|p| path_str(p)).collect();
let mut clip = ClipFiles::default();
clip.sync_files(&files, fingerprint(&files)).unwrap();
clip
}
fn read_head(clip: &mut ClipFiles, file_idx: usize) -> Result<Vec<u8>, CliprdrError> {
let request = FileContentsRequest::Range {
stream_id: 0,
file_idx,
offset: 0,
length: 4,
};
match clip.serve_file_contents(0, request)? {
ClipboardFile::FileContentsResponse { requested_data, .. } => Ok(requested_data),
other => panic!("unexpected response: {:?}", other),
}
}
// Preloading the file after the requested one is best-effort: a file that can no longer
// be opened fails its own requests, not those of the file before it.
fn assert_only_its_own_requests_fail(clip: &mut ClipFiles, broken: &PathBuf) {
let first_idx = clip.first_file_index;
let broken_idx = clip
.file_list
.iter()
.position(|f| &f.path == broken)
.unwrap();
let size = FileContentsRequest::Size {
stream_id: 0,
file_idx: first_idx,
};
clip.serve_file_contents(0, size).unwrap();
assert_eq!(read_head(clip, first_idx).unwrap(), b"AAAA");
assert!(matches!(
read_head(clip, broken_idx),
Err(CliprdrError::FileError { .. })
));
}
#[test]
fn a_deleted_next_file_fails_only_its_own_requests() {
let tmp = TmpDir::new("next_deleted");
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
fs::write(&first, b"AAAAAAAA").unwrap();
fs::write(&second, b"BBBBBBBB").unwrap();
let mut clip = list_files(&[&first, &second]);
fs::remove_file(&second).unwrap();
assert_only_its_own_requests_fail(&mut clip, &second);
}
#[test]
fn the_next_file_is_preloaded_past_a_directory() {
let tmp = TmpDir::new("next_preloaded");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let dir = tmp.join("dir");
fs::create_dir(&dir).unwrap();
let inner = dir.join("inner.bin");
fs::write(&inner, b"BBBBBBBB").unwrap();
// Listed as first.bin, dir, dir/inner.bin.
let mut clip = list_files(&[&first, &dir]);
let first_idx = clip.first_file_index;
let inner_idx = clip.file_list.len() - 1;
assert_eq!(clip.file_list[inner_idx].path, inner);
assert_eq!(read_head(&mut clip, first_idx).unwrap(), b"AAAA");
assert!(clip.file_list[inner_idx].handle.is_some());
// The last file has no next file to preload.
assert_eq!(read_head(&mut clip, inner_idx).unwrap(), b"BBBB");
}
}
+361 -13
View File
@@ -54,6 +54,12 @@
/* File clipboard redirection always advertises the descriptor and contents formats. */
#define WF_CLIPRDR_FILE_FORMAT_COUNT 2u
#define WF_CLIPRDR_COM_LPT_PREFIX_LENGTH 3u
/* File lists kept after they were sent, so a transfer still in flight keeps reading its own
* files after a later copy or paste replaces them. */
#define WF_CLIPRDR_SERVED_FILE_LISTS 4u
/* Largest range served in one request, here and by the unix file server (MAX_RANGE_READ in
* serv_files.rs). Larger IStream reads are split into requests of this size. */
#define WF_CLIPRDR_MAX_RANGE_READ (16u * 1024u * 1024u)
static const WCHAR WF_CLIPRDR_SUPERSCRIPT_DIGITS[] = L"\x00B9\x00B2\x00B3";
static const WCHAR WF_CLIPRDR_INVALID_FILE_NAME_CHARS[] = L"<>:\"|?*";
@@ -213,6 +219,21 @@ static BOOL wf_cliprdr_bounded_strlen(const char *value, size_t max_len, size_t
return FALSE;
}
/* Identifies a file list by its FILEGROUPDESCRIPTORW bytes, which both peers hold, and is
* carried as FileContentsRequest.clipDataId. FNV-1a, same as `file_list_id()` on unix. */
static UINT32 wf_cliprdr_file_list_id(const BYTE *data, SIZE_T size)
{
UINT32 id = 2166136261u;
SIZE_T i;
for (i = 0; i < size; i++)
{
id ^= data[i];
id *= 16777619u;
}
return id;
}
/**
* Clipboard Formats
*/
@@ -358,6 +379,7 @@ struct _CliprdrStream
void *m_pData;
UINT32 m_connID;
UINT32 m_streamId; // unique CLIPRDR streamId; avoids leaking a heap pointer
UINT32 m_clipDataId; // id of the file list this stream was created from
};
typedef struct _CliprdrStream CliprdrStream;
@@ -377,6 +399,21 @@ struct _CliprdrDataObject
};
typedef struct _CliprdrDataObject CliprdrDataObject;
struct wf_served_file_list
{
UINT32 id;
UINT32 *connIDs; // connections the list was sent to
size_t nConnIDs;
UINT64 last_served; // served_file_list_seq when last sent; the lowest is evicted first
size_t nFiles;
size_t first_file_index;
WCHAR **file_names;
UINT64 *file_sizes;
BYTE *descriptors; // the FILEGROUPDESCRIPTORW sent, nonce included
SIZE_T descriptorsSize;
};
typedef struct wf_served_file_list wfServedFileList;
struct wf_clipboard
{
// wfContext* wfc;
@@ -424,6 +461,10 @@ struct wf_clipboard
WCHAR **file_names;
size_t first_file_index;
FILEDESCRIPTORW **fileDescriptor;
DWORD file_list_seq; // clipboard sequence number the file list was read at
UINT32 file_list_id; // wf_cliprdr_file_list_id() of the file list, 0 while none is valid
wfServedFileList served_file_lists[WF_CLIPRDR_SERVED_FILE_LISTS];
UINT64 served_file_list_seq;
BOOL legacyApi;
HMODULE hUser32;
@@ -451,8 +492,8 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
static UINT cliprdr_send_lock(wfClipboard *clipboard);
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
ULONG index, UINT32 flag, DWORD positionhigh,
DWORD positionlow, ULONG request);
UINT32 clipDataId, ULONG index, UINT32 flag,
DWORD positionhigh, DWORD positionlow, ULONG request);
static BOOL is_file_descriptor_from_remote();
static BOOL is_set_by_instance(wfClipboard *clipboard);
@@ -464,6 +505,7 @@ static HRESULT CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC *pFormatEtc,
static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC *instance);
static void CliprdrStream_Delete(CliprdrStream *instance);
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead);
static BOOL try_open_clipboard(HWND hwnd)
{
@@ -550,7 +592,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
return S_FALSE;
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId, instance->m_lIndex,
if (cb > WF_CLIPRDR_MAX_RANGE_READ)
return wf_cliprdr_stream_read_split(This, (BYTE *)pv, cb, pcbRead);
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
instance->m_clipDataId, instance->m_lIndex,
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
instance->m_lOffset.LowPart, cb);
@@ -591,6 +637,26 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
return S_OK;
}
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead)
{
HRESULT hr = S_OK;
ULONG total = 0;
ULONG chunk;
ULONG n;
while (total < cb && hr == S_OK)
{
chunk = cb - total < WF_CLIPRDR_MAX_RANGE_READ ? cb - total : WF_CLIPRDR_MAX_RANGE_READ;
n = 0;
hr = CliprdrStream_Read(This, pv + total, chunk, &n);
total += n;
}
*pcbRead = total;
if (FAILED(hr))
return hr;
return total < cb ? S_FALSE : S_OK;
}
static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream *This, const void *pv, ULONG cb,
ULONG *pcbWritten)
{
@@ -736,7 +802,8 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Clone(IStream *This, IStream **pp
return E_NOTIMPL;
}
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc)
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc,
UINT32 clipDataId)
{
IStream *iStream = NULL;
BOOL success = FALSE;
@@ -779,6 +846,7 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
instance->m_lOffset.QuadPart = 0;
instance->m_connID = connID;
instance->m_streamId = (UINT32)InterlockedIncrement(&clipboard->req_f_stream_id_seq);
instance->m_clipDataId = clipDataId;
if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES)
{
@@ -790,8 +858,8 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
{
/* get content size of this stream */
if (cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
instance->m_lIndex, FILECONTENTS_SIZE, 0, 0,
8) == CHANNEL_RC_OK)
instance->m_clipDataId, instance->m_lIndex,
FILECONTENTS_SIZE, 0, 0, 8) == CHANNEL_RC_OK)
{
success = TRUE;
}
@@ -1007,6 +1075,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
IStream **streams = NULL;
UINT stream_count = 0;
SIZE_T hmem_size;
UINT32 clipDataId;
// DWORD remote_format_id = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat);
// FIXME: origin code may be failed here???
if (cliprdr_send_data_request(instance->m_connID, clipboard, instance->m_pFormatEtc[idx].cfFormat) != 0)
@@ -1053,10 +1122,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
return wf_cliprdr_fail_locked_file_descriptor_data(
clipboard, pMedium, instance, NULL, 0, E_OUTOFMEMORY);
clipDataId = wf_cliprdr_file_list_id((const BYTE *)dsc, hmem_size);
for (i = 0; i < stream_count; i++)
{
streams[i] =
(IStream *)CliprdrStream_New(instance->m_connID, i, clipboard, &dsc->fgd[i]);
streams[i] = (IStream *)CliprdrStream_New(instance->m_connID, i, clipboard,
&dsc->fgd[i], clipDataId);
if (!streams[i])
{
return wf_cliprdr_fail_locked_file_descriptor_data(
@@ -1996,9 +2066,9 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
}
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId, ULONG index,
UINT32 flag, DWORD positionhigh, DWORD positionlow,
ULONG nreq)
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
UINT32 clipDataId, ULONG index, UINT32 flag,
DWORD positionhigh, DWORD positionlow, ULONG nreq)
{
UINT rc;
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
@@ -2023,7 +2093,8 @@ static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 con
fileContentsRequest.nPositionLow = positionlow;
fileContentsRequest.nPositionHigh = positionhigh;
fileContentsRequest.cbRequested = nreq;
fileContentsRequest.clipDataId = 0;
fileContentsRequest.haveClipDataId = TRUE;
fileContentsRequest.clipDataId = clipDataId;
fileContentsRequest.msgFlags = 0;
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
if (rc != ERROR_SUCCESS)
@@ -2424,6 +2495,242 @@ error:
return res;
}
static void wf_cliprdr_free_served_file_list(wfServedFileList *list)
{
size_t i;
if (list->file_names)
{
for (i = 0; i < list->nFiles; i++)
free(list->file_names[i]);
free(list->file_names);
}
free(list->file_sizes);
free(list->connIDs);
free(list->descriptors);
ZeroMemory(list, sizeof(*list));
}
static BOOL wf_cliprdr_served_to(const wfServedFileList *list, UINT32 connID)
{
size_t i;
for (i = 0; i < list->nConnIDs; i++)
{
if (list->connIDs[i] == connID)
return TRUE;
}
return FALSE;
}
static void wf_cliprdr_forget_served_file_lists(wfClipboard *clipboard)
{
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
wf_cliprdr_free_served_file_list(&clipboard->served_file_lists[i]);
}
/* Whether a kept list has the current file_names and the same descriptors as dsc, apart
* from the nonce in fgd[0].clsid. */
static BOOL wf_cliprdr_is_same_file_list(wfClipboard *clipboard, const wfServedFileList *list,
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
{
SIZE_T nonce_start = offsetof(FILEGROUPDESCRIPTORW, fgd) + offsetof(FILEDESCRIPTORW, clsid);
SIZE_T nonce_end = nonce_start + sizeof(CLSID);
size_t i;
if (!list->file_names || list->nFiles != clipboard->nFiles ||
list->descriptorsSize != size || size < nonce_end)
return FALSE;
for (i = 0; i < list->nFiles; i++)
{
if (!clipboard->file_names[i] || wcscmp(list->file_names[i], clipboard->file_names[i]) != 0)
return FALSE;
}
return memcmp(list->descriptors, dsc, nonce_start) == 0 &&
memcmp(list->descriptors + nonce_end, (const BYTE *)dsc + nonce_end,
size - nonce_end) == 0;
}
/* Puts a nonce in fgd[0].clsid, which peers ignore without FD_CLSID. The list id hashes it,
* so each copy gets its own id even when two copies have identical names, sizes and times
* (the same file in two folders). Re-sending unchanged files keeps their nonce, and id. */
static void wf_cliprdr_stamp_file_list(wfClipboard *clipboard, FILEGROUPDESCRIPTORW *dsc,
SIZE_T size)
{
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (wf_cliprdr_is_same_file_list(clipboard, &clipboard->served_file_lists[i], dsc, size))
{
dsc->fgd[0].clsid =
((const FILEGROUPDESCRIPTORW *)clipboard->served_file_lists[i].descriptors)
->fgd[0]
.clsid;
return;
}
}
if (FAILED(CoCreateGuid(&dsc->fgd[0].clsid)))
ZeroMemory(&dsc->fgd[0].clsid, sizeof(CLSID));
}
static BOOL wf_cliprdr_copy_file_list(wfClipboard *clipboard, wfServedFileList *list,
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
{
size_t i;
list->file_names = (WCHAR **)calloc(clipboard->nFiles, sizeof(WCHAR *));
list->file_sizes = (UINT64 *)calloc(clipboard->nFiles, sizeof(UINT64));
list->descriptors = (BYTE *)malloc(size);
if (!list->file_names || !list->file_sizes || !list->descriptors)
return FALSE;
CopyMemory(list->descriptors, dsc, size);
list->descriptorsSize = size;
list->nFiles = clipboard->nFiles;
for (i = 0; i < clipboard->nFiles; i++)
{
if (!clipboard->file_names[i] ||
!(list->file_names[i] = _wcsdup(clipboard->file_names[i])))
return FALSE;
if (clipboard->fileDescriptor[i])
list->file_sizes[i] = ((UINT64)clipboard->fileDescriptor[i]->nFileSizeHigh << 32) |
clipboard->fileDescriptor[i]->nFileSizeLow;
}
list->id = clipboard->file_list_id;
list->first_file_index = clipboard->first_file_index;
return TRUE;
}
/* One slot per list, shared by every connection it was sent to. A full table evicts the list
* sent least recently, so a list a transfer has just started on is kept. */
static void wf_cliprdr_remember_served_file_list(wfClipboard *clipboard, UINT32 connID,
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
{
wfServedFileList *list = NULL;
UINT32 *connIDs;
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (clipboard->served_file_lists[i].file_names &&
clipboard->served_file_lists[i].id == clipboard->file_list_id)
{
list = &clipboard->served_file_lists[i];
break;
}
}
if (!list)
{
// An empty slot has last_served 0, so it is taken first.
list = &clipboard->served_file_lists[0];
for (i = 1; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (clipboard->served_file_lists[i].last_served < list->last_served)
list = &clipboard->served_file_lists[i];
}
wf_cliprdr_free_served_file_list(list);
if (!wf_cliprdr_copy_file_list(clipboard, list, dsc, size))
{
wf_cliprdr_free_served_file_list(list);
return;
}
}
list->last_served = ++clipboard->served_file_list_seq;
if (wf_cliprdr_served_to(list, connID))
return;
connIDs = (UINT32 *)realloc(list->connIDs, (list->nConnIDs + 1) * sizeof(UINT32));
if (!connIDs)
return;
connIDs[list->nConnIDs++] = connID;
list->connIDs = connIDs;
}
/* Reads like wf_cliprdr_get_file_contents, but only from the file the list was sent with: a
* different size or last-write time means the path now names another file, and the read fails
* rather than continuing a transfer with its bytes. */
static BOOL wf_cliprdr_get_served_file_contents(const WCHAR *file_name, const FILEDESCRIPTORW *dsc,
BYTE *buffer, DWORD positionLow, DWORD positionHigh,
DWORD nRequested, DWORD *puSize)
{
BOOL res = FALSE;
HANDLE hFile;
LARGE_INTEGER size;
LARGE_INTEGER position;
FILETIME lastWrite;
DWORD nGet;
hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return FALSE;
if (GetFileSizeEx(hFile, &size) &&
(UINT64)size.QuadPart == (((UINT64)dsc->nFileSizeHigh << 32) | dsc->nFileSizeLow) &&
(!(dsc->dwFlags & FD_WRITESTIME) ||
(GetFileTime(hFile, NULL, NULL, &lastWrite) &&
CompareFileTime(&lastWrite, &dsc->ftLastWriteTime) == 0)))
{
position.LowPart = positionLow;
position.HighPart = (LONG)positionHigh;
if (SetFilePointerEx(hFile, position, NULL, FILE_BEGIN) &&
ReadFile(hFile, buffer, nRequested, &nGet, NULL))
{
*puSize = nGet;
res = TRUE;
}
}
CloseHandle(hFile);
return res;
}
/* Serves a request by path from the file list it names, if that list was sent to the same
* connection. An unknown list fails the request rather than falling back to other files. */
static BOOL wf_cliprdr_read_served_file_list(wfClipboard *clipboard,
const CLIPRDR_FILE_CONTENTS_REQUEST *request,
BYTE *data, UINT32 cbRequested, DWORD *puSize)
{
wfServedFileList *list = NULL;
size_t i;
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
{
if (clipboard->served_file_lists[i].file_names &&
clipboard->served_file_lists[i].id == request->clipDataId &&
wf_cliprdr_served_to(&clipboard->served_file_lists[i], request->connID))
{
list = &clipboard->served_file_lists[i];
break;
}
}
if (!list || request->listIndex >= list->nFiles)
return FALSE;
if (request->dwFlags == FILECONTENTS_SIZE)
{
CopyMemory(data, &list->file_sizes[request->listIndex], sizeof(UINT64));
*puSize = sizeof(UINT64);
return TRUE;
}
if (request->dwFlags != FILECONTENTS_RANGE)
return FALSE;
if (clipboard->context->HandleClipboardFiles &&
request->listIndex == (UINT32)list->first_file_index &&
request->nPositionLow == 0 && request->nPositionHigh == 0)
{
clipboard->context->HandleClipboardFiles(request->connID, list->nFiles, list->file_names);
}
return wf_cliprdr_get_served_file_contents(
list->file_names[request->listIndex],
&((const FILEGROUPDESCRIPTORW *)list->descriptors)->fgd[request->listIndex], data,
request->nPositionLow, request->nPositionHigh, cbRequested, puSize);
}
/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */
static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t pathLen)
{
@@ -3028,6 +3335,8 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
STGMEDIUM stg_medium;
DROPFILES *dropFiles;
FILEGROUPDESCRIPTORW *groupDsc;
clipboard->file_list_seq = GetClipboardSequenceNumber();
clipboard->file_list_id = 0;
result = OleGetClipboard(&dataObj);
if (FAILED(result))
@@ -3164,6 +3473,10 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
buff = groupDsc;
rc = ERROR_SUCCESS;
wf_cliprdr_stamp_file_list(clipboard, groupDsc, size);
clipboard->file_list_id = wf_cliprdr_file_list_id((const BYTE *)groupDsc, size);
wf_cliprdr_remember_served_file_list(clipboard, formatDataRequest->connID, groupDsc,
size);
}
else
{
@@ -3376,6 +3689,18 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
return ERROR_INTERNAL_ERROR;
}
// Refuse an unknown request type, or a range over the cap, before allocating for it. Clients
// of this version split larger reads; an older Windows client reading more in one
// IStream::Read fails, as with unix owners.
if ((fileContentsRequest->dwFlags != FILECONTENTS_SIZE &&
fileContentsRequest->dwFlags != FILECONTENTS_RANGE) ||
(fileContentsRequest->dwFlags == FILECONTENTS_RANGE &&
fileContentsRequest->cbRequested > WF_CLIPRDR_MAX_RANGE_READ))
{
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
goto exit;
}
// If the clipboard is set by the instance, or the file descriptor is from remote,
// we should not process the request.
// Because this may be the following cases:
@@ -3401,6 +3726,22 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
goto exit;
}
// A stream whose list is no longer the current one reads by path from the list it came from.
// Only lists sent to this connection are served.
if (fileContentsRequest->haveClipDataId &&
fileContentsRequest->clipDataId != clipboard->file_list_id)
{
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
cbRequested = fileContentsRequest->dwFlags == FILECONTENTS_SIZE
? sizeof(UINT64)
: fileContentsRequest->cbRequested;
pData = (BYTE *)calloc(1, cbRequested);
if (pData && wf_cliprdr_read_served_file_list(clipboard, fileContentsRequest, pData,
cbRequested, &uSize))
rc = CHANNEL_RC_OK;
goto exit;
}
cbRequested = fileContentsRequest->cbRequested;
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
cbRequested = sizeof(UINT64);
@@ -3430,7 +3771,13 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
vFormatEtc.lindex = fileContentsRequest->listIndex;
vFormatEtc.ptd = NULL;
if ((uStreamIdStc != fileContentsRequest->streamId) ||
if (GetClipboardSequenceNumber() != clipboard->file_list_seq)
{
// The clipboard changed after the peer got its file list. The live FileContents
// belongs to the new copy, so reading it would splice another file into this one.
bIsStreamFile = FALSE;
}
else if ((uStreamIdStc != fileContentsRequest->streamId) ||
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
{
LPENUMFORMATETC pEnumFormatEtc;
@@ -3842,6 +4189,7 @@ BOOL wf_cliprdr_uninit(wfClipboard *clipboard, CliprdrClientContext *cliprdr)
CloseHandle(clipboard->req_fevent);
clear_file_array(clipboard);
wf_cliprdr_forget_served_file_lists(clipboard);
clear_format_map(clipboard);
free(clipboard->format_mappings);
return TRUE;
-36
View File
@@ -146,39 +146,3 @@ fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
Ok(tokens)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn success() {
assert_eq!(
tokenize("{{Hello World!}} {+CTRL}hi{-CTRL}"),
Ok(vec![
Token::Sequence("{Hello World!} ".into()),
Token::KeyDown(Key::Control),
Token::Sequence("hi".into()),
Token::KeyUp(Key::Control)
])
);
}
#[test]
fn unexpected_open() {
assert_eq!(tokenize("{hello{}world}"), Err(ParseError::UnexpectedOpen));
}
#[test]
fn unmatched_open() {
assert_eq!(
tokenize("{this is going to fail"),
Err(ParseError::UnmatchedOpen)
);
}
#[test]
fn unmatched_close() {
assert_eq!(
tokenize("{+CTRL}{{this}} is going to fail}"),
Err(ParseError::UnmatchedClose)
);
}
}
-25
View File
@@ -525,28 +525,3 @@ impl fmt::Debug for Enigo {
write!(f, "Enigo")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_key_state() {
let mut enigo = Enigo::new();
let keys = [Key::CapsLock, Key::NumLock];
for k in keys.iter() {
enigo.key_click(k.clone());
let a = enigo.get_key_state(k.clone());
enigo.key_click(k.clone());
let b = enigo.get_key_state(k.clone());
assert!(a != b);
}
let keys = [Key::Control, Key::Alt, Key::Shift];
for k in keys.iter() {
enigo.key_down(k.clone()).ok();
let a = enigo.get_key_state(k.clone());
enigo.key_up(k.clone());
let b = enigo.get_key_state(k.clone());
assert!(a != b);
}
}
}
-7
View File
@@ -391,13 +391,6 @@ fn convert_to_tfc_key(key: Key) -> Option<TFC_Key> {
Some(key)
}
#[test]
fn test_key_seq() {
// Get 6^ in French.
let mut en = Enigo::new();
en.key_sequence("^^");
}
/// Both directions: the failure is silent, so a one-directional test passes against the bug.
#[test]
fn test_custom_mouse_dispatch_follows_is_x11() {
+55
View File
@@ -36,6 +36,7 @@ const kUCKeyActionDisplay: u16 = 3;
#[allow(non_upper_case_globals)]
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
const BUF_LEN: usize = 4;
const KEYBOARD_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
const MOUSE_EVENT_BUTTON_NUMBER_BACK: i64 = 3;
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
@@ -428,7 +429,19 @@ impl KeyboardControllable for Enigo {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
event.set_string(cluster);
self.post(event, None);
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: event source is not initialized"
);
}
}
}
@@ -436,17 +449,40 @@ impl KeyboardControllable for Enigo {
fn key_click(&mut self, key: Key) {
let keycode = self.key_to_keycode(key);
if keycode == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: keycode mapping is unavailable"
);
return;
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-down in key-click: could not create keyboard event"
);
}
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up in key-click: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: event source is not initialized"
);
}
}
@@ -465,10 +501,29 @@ impl KeyboardControllable for Enigo {
fn key_up(&mut self, key: Key) {
let code = self.key_to_keycode(key);
if code == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Cannot map macOS Enigo key-up to a keycode"
);
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
self.post(event, Some(code));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: event source is not initialized"
);
}
}
+30 -4
View File
@@ -39,6 +39,17 @@ fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) -> DWORD {
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
}
// `v` comes from the remote peer unchecked, so scale in i64 to avoid overflow, and clamp to
// the 0..=65535 range MOUSEEVENTF_ABSOLUTE takes.
// `extent` is 0 when the virtual screen metrics are unavailable.
fn to_absolute(v: i32, origin: i32, extent: i32) -> Option<i32> {
if extent <= 0 {
return None;
}
let abs = (v as i64 - origin as i64) * 65535 / extent as i64;
Some(abs.clamp(0, 65535) as i32)
}
fn keybd_event(mut flags: u32, vk: u16, scan: u16) -> DWORD {
let mut scan = scan;
unsafe {
@@ -126,13 +137,28 @@ impl MouseControllable for Enigo {
}
fn mouse_move_to(&mut self, x: i32, y: i32) {
let (left, top, width, height) = unsafe {
(
GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN),
)
};
let (Some(dx), Some(dy)) = (to_absolute(x, left, width), to_absolute(y, top, height))
else {
hbb_common::throttled_log!(
std::time::Duration::from_secs(60),
warn,
"mouse_move_to skipped: virtual screen size unavailable"
);
return;
};
mouse_event(
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
0,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535
/ unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535
/ unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
dx,
dy,
);
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk-portable-packer"
version = "1.5.0"
version = "1.5.1"
edition = "2021"
description = "RustDesk Remote Desktop"
@@ -20,6 +20,7 @@ windows = { version = "0.61", features = [
"Wdk_System",
"Wdk_System_SystemServices",
"Win32",
"Win32_Storage_FileSystem",
"Win32_System",
"Win32_System_SystemInformation",
] }
@@ -36,4 +37,3 @@ FileDescription = "RustDesk Remote Desktop"
winres = "0.1"
winapi = { version = "0.3", features = [ "winnt", "pdh", "synchapi" ] }
-50
View File
@@ -279,26 +279,6 @@ mod tests {
.find(|file| normalize_path(&file.path) == normalize_path(path))
}
#[test]
fn parses_the_generate_py_layout() {
let (files, exe) = parse(blob(
&[("./rustdesk.exe", b"app"), ("./custom.txt", b"cfg")],
"./rustdesk.exe",
))
.unwrap();
assert_eq!(exe, "./rustdesk.exe");
assert_eq!(files.len(), 2);
assert_eq!(entry(&files, "./custom.txt").unwrap().raw, b"cfg");
}
#[test]
fn rejects_malformed_blobs() {
assert!(parse(b"".as_slice()).is_none());
assert!(parse(b"notrustd".as_slice()).is_none());
// Truncated mid-record rather than panicking on a slice out of range.
assert!(parse(b"rustdesk\x00\x00\x00\x40partial".as_slice()).is_none());
}
#[test]
fn distinguishes_an_absent_package_from_a_malformed_one() {
assert!(parse_package_blob(None).unwrap().0.is_empty());
@@ -372,34 +352,4 @@ mod tests {
);
assert_eq!(entry(&files, "./librustdesk.dll").unwrap().raw, b"core");
}
#[test]
fn package_paths_are_recorded_for_the_dropped_file_sweep() {
let package = parse(blob(
&[("./custom.txt", b"cfg"), ("./data/logo.png", b"img")],
"./acme.exe",
))
.unwrap();
let mut paths: Vec<String> = package.0.iter().map(|f| f.path.clone()).collect();
paths.sort();
assert_eq!(paths, vec!["./custom.txt", "./data/logo.png"]);
// Merging must not disturb them: the generic payload contributes none.
let embedded = parse(blob(&[("./librustdesk.dll", b"core")], "./rustdesk.exe")).unwrap();
let (files, _) = merge(embedded, package);
assert!(entry(&files, "./data/logo.png").is_some());
}
#[test]
fn matches_paths_across_separator_styles() {
// generate.py emits backslashes when it runs on Windows.
let embedded = parse(blob(&[(".\\rustdesk.exe", b"app")], ".\\rustdesk.exe")).unwrap();
let package = parse(blob(&[("./custom.txt", b"cfg")], "./acme.exe")).unwrap();
let (files, exe) = merge(embedded, package);
assert_eq!(exe, "./acme.exe");
assert!(entry(&files, "./acme.exe").is_some());
assert!(entry(&files, ".\\rustdesk.exe").is_none());
}
}
+36
View File
@@ -19,6 +19,8 @@ const APP_METADATA_CONFIG: &str = "meta.toml";
const META_LINE_PREFIX_TIMESTAMP: &str = "timestamp = ";
const META_LINE_PREFIX_FILE: &str = "file = ";
const APP_PREFIX: &str = "rustdesk";
#[cfg(windows)]
const VERIFIED_UPDATE_FILE_PREFIX: &str = "rustdesk-verified-";
const APPNAME_RUNTIME_ENV_KEY: &str = "RUSTDESK_APPNAME";
#[cfg(windows)]
const SET_FOREGROUND_WINDOW_ENV_KEY: &str = "SET_FOREGROUND_WINDOW";
@@ -287,6 +289,13 @@ fn main() -> Result<(), String> {
#[cfg(not(windows))]
let quick_support = false;
#[cfg(windows)]
if args.first().is_some_and(|arg| arg == "--update") {
if let Err(err) = win::schedule_verified_update_cleanup() {
eprintln!("Failed to schedule verified update file cleanup: {}", err);
}
}
let mut ui = false;
let reader = BinaryReader::new()?;
if let Some(exe) = setup(
@@ -314,6 +323,33 @@ mod win {
pub const RUNTIME_BROKER_EXE: &'static str = "C:\\Windows\\System32\\RuntimeBroker.exe";
pub const WIN_TOPMOST_INJECTED_PROCESS_EXE: &'static str = "RuntimeBroker_rustdesk.exe";
pub(super) fn schedule_verified_update_cleanup() -> std::io::Result<()> {
use windows::{
core::{HSTRING, PCWSTR},
Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT},
};
let current_exe = std::env::current_exe()?;
let is_verified_update = current_exe
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name.starts_with(super::VERIFIED_UPDATE_FILE_PREFIX) && name.ends_with(".exe")
});
if !is_verified_update {
return Ok(());
}
unsafe {
MoveFileExW(
&HSTRING::from(current_exe.as_path()),
PCWSTR::null(),
MOVEFILE_DELAY_UNTIL_REBOOT,
)
}
.map_err(std::io::Error::other)
}
pub(super) fn copy_runtime_broker(dir: &Path) {
let src = RUNTIME_BROKER_EXE;
let tgt = WIN_TOPMOST_INJECTED_PROCESS_EXE;
+44 -15
View File
@@ -5,7 +5,7 @@ use winapi::{
shared::{
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
ntdef::HANDLE,
winerror::ERROR_INVALID_PRINTER_NAME,
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
},
um::winspool::{
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
@@ -42,20 +42,49 @@ fn enum_local_printer(
#[inline]
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
let r = common_enum(
"EnumPrintersW",
enum_local_printer,
1,
|info: &PRINTER_INFO_1W| {
if is_name_equal(name, info.pName) {
Some(true)
} else {
None
}
},
|| None,
)?;
Ok(r.unwrap_or(false))
const PRINTER_INFO_LEVEL: DWORD = 1;
let mut needed = 0;
let mut returned = 0;
if enum_local_printer(
PRINTER_INFO_LEVEL,
null_mut(),
0,
&mut needed,
&mut returned,
) == FALSE
{
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
bail!("Failed to query EnumPrintersW buffer size: {error}");
}
}
if needed == 0 {
return Ok(false);
}
let mut buffer = vec![0u8; needed as usize];
if enum_local_printer(
PRINTER_INFO_LEVEL,
buffer.as_mut_ptr(),
needed,
&mut needed,
&mut returned,
) == FALSE
{
bail!(
"Failed to call EnumPrintersW, error: {}",
io::Error::last_os_error()
);
}
let printers = buffer.as_ptr() as *const PRINTER_INFO_1W;
for index in 0..returned {
let printer = unsafe { &*printers.add(index as usize) };
if is_name_equal(name, printer.pName) {
return Ok(true);
}
}
Ok(false)
}
// Only return the first matched printer
+2 -2
View File
@@ -14,7 +14,7 @@ wayland = ["gstreamer", "gstreamer-app", "gstreamer-video", "dbus", "tracing", "
# `drm` is a pure runtime-dlopen backend: rustdesk loads `libdrmtap.so.0` at runtime (`drmtap_dl.rs`)
# and NEVER link-time links it, so the graceful PipeWire fallback when the .so or EGL is absent is
# preserved and the drm build pulls in no libdrm/seccomp/cap/EGL link-time deps. The .so is pinned by
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.4). We deliberately do
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.12). We deliberately do
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
# and a CAP_SYS_ADMIN helper and emits `-ldrm -lseccomp -lcap`, which would defeat the dlopen model.
# Depends on `wayland`: the three drm modules live inside the `#[cfg(feature = "wayland")]` arm of
@@ -38,7 +38,7 @@ serde = {version="1.0", features=["derive"]}
[dependencies.winapi]
version = "0.3"
default-features = true
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
features = ["dxgi", "dxgi1_2", "dxgi1_5", "dxgi1_6", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
[target.'cfg(target_os = "macos")'.dependencies]
block = "0.1"
-17
View File
@@ -199,23 +199,6 @@ mod webrtc {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::raw::c_uint;
#[test]
fn tile_log2_uses_c_uint_and_rounds_up() {
let one_thread: c_uint = tile_log2(1);
let three_threads: c_uint = tile_log2(3);
let max_threads: c_uint = tile_log2(64);
assert_eq!(one_thread, 0);
assert_eq!(three_threads, 2);
assert_eq!(max_threads, 6);
}
}
}
impl EncoderApi for AomEncoder {
+553 -32
View File
@@ -8,6 +8,7 @@ use hbb_common::log;
use std::ffi::CString;
use std::io;
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::raw::c_int;
// Trust-boundary limits and formats `drm_render` (the unprivileged converter) imports: two copies that drift apart would weaken one side.
// 16384 covers 8K+ with headroom; anything larger is rejected as a bogus/hostile geometry.
@@ -29,7 +30,275 @@ pub struct CursorSnapshot {
pub height: u32,
pub hotx: i32,
pub hoty: i32,
/// Whether the hotspot came from the plane's HOTSPOT_X/Y properties. Those exist on
/// para-virtualised drivers only; on bare metal it is `infer_hotspot`'s guess, made on the
/// bitmap as scanned out - which on a rotated output is the compositor's pre-rotated sprite,
/// so the consumer must re-guess on the upright one.
pub hot_measured: bool,
pub colors: Vec<u8>,
/// Cursor plane position (CRTC_X/CRTC_Y), in this reader's scanout pixels.
pub x: i32,
pub y: i32,
}
/// Fold everything that makes a cursor a DIFFERENT cursor into its id.
///
/// The producer dedupes by comparing this against the last one it sent, so anything left out is
/// something a change in which the consumer will never be told about. Geometry and the hotspot are
/// the obvious ones: identical pixels at a new size or hotspot are a new shape.
///
/// `hot_measured` belongs here too, and that is less obvious. It is not metadata about the cursor,
/// it selects what the consumer DOES with it: false means rotate the bitmap and re-infer a
/// hotspot, true means map the supplied point. So a sample whose pixels and `(0, 0)` hotspot are
/// unchanged but whose provenance flipped is a different cursor as far as the client is concerned,
/// and without this it would be deduped away and never sent.
fn cursor_id(hash: u64, width: u32, height: u32, hotx: i32, hoty: i32, hot_measured: bool) -> u64 {
let mut id = hash;
for v in [
width as u64,
height as u64,
hotx as u32 as u64,
hoty as u32 as u64,
hot_measured as u64,
] {
id ^= v;
id = id.wrapping_mul(1099511628211);
}
id
}
/// Encodes a provenance answer for the one-shot log below. -1 is "nothing reported yet".
fn provenance_code(answered: Option<bool>) -> i8 {
match answered {
None => 0,
Some(false) => 1,
Some(true) => 2,
}
}
/// Whether this sample's provenance is worth a log line, given what was last reported.
///
/// Its own function because the obvious version of this is a line per cursor read, and a cursor is
/// read far more often than it changes. A per-sample log here was a real defect in libdrmtap for
/// the same reason. So: the first sample of a run, and thereafter only a genuine change of state.
fn provenance_is_news(last: i8, now: i8) -> bool {
last != now
}
impl DrmReader {
/// Say once, and again only if it changes, where the hotspot is coming from. Without this the
/// three states are indistinguishable on a running box, which makes the decision unverifiable
/// anywhere but a unit test.
fn note_hotspot_provenance(&mut self, answered: Option<bool>, hot_measured: bool) {
let now = provenance_code(answered);
let last = std::mem::replace(&mut self.last_provenance, now);
if !provenance_is_news(last, now) {
return;
}
match answered {
Some(true) => log::info!(
"drm: cursor hotspot provenance: the driver published HOTSPOT_X/Y, using its value"
),
Some(false) => log::info!(
"drm: cursor hotspot provenance: the plane exposes no HOTSPOT_X/Y, inferring the \
hotspot from the bitmap"
),
None => log::info!(
"drm: cursor hotspot provenance: unavailable (libdrmtap older than 0.5.6, or a \
pre-0.5.6 privileged helper); falling back to the coordinate heuristic, which says \
hot_measured={hot_measured}"
),
}
}
}
/// Whether `hot_x`/`hot_y` are the driver's answer rather than a guess.
///
/// `answered` is what `drmtap_cursor_hotspot_valid` said: `Some(v)` when it answered, `None` when
/// the symbol is absent (a library older than 0.5.6) or it reported that nothing recorded an
/// answer for this sample.
///
/// When it answered, that is the answer, full stop - including `Some(true)` on a `(0, 0)` hotspot,
/// which is the whole reason the entry point exists: a para-virtualized driver really can put the
/// hotspot at the top-left corner, and the coordinates alone cannot tell that apart from a plane
/// that exposes no HOTSPOT_X/Y at all. When it could not answer, fall back to the old test. That
/// test is wrong in both directions, but it is what this code did before, and it keeps a deployed
/// older `.so` behaving exactly as it used to instead of changing under it.
fn hot_measured_from(answered: Option<bool>, hot_x: i32, hot_y: i32) -> bool {
match answered {
Some(measured) => measured,
None => hot_x != 0 || hot_y != 0,
}
}
/// A mirror has to agree on this many of every 100 pixels of the union to count as symmetry.
/// Swept against master over two theme versions: below 86 the rule starts moving shapes whose
/// corner guess was already right (`grabbing`), and from 92 up the directional cursors of the
/// older theme stop being recognised and regress. 86 to 91 is the interval that holds on both,
/// so this sits in the middle of it.
const MIRROR_AGREEMENT_PERCENT: u64 = 88;
/// Guess the click point of a cursor bitmap, for the drivers that publish no hotspot.
///
/// Three facts drive it, in order of how much of the shape they read.
///
/// A shape that is mirror symmetric about one of the box's mid-lines has no distinguished end on
/// that axis: a crosshair, an I-beam, a two-headed resize arrow. On such an axis the click point
/// is the middle.
///
/// A shape that mirrors onto itself only under a half turn or about a DIAGONAL is a two-headed or
/// corner resize cursor. Those are a pointer plus the marker of the edge being resized, and the
/// theme puts the click point on that marker, which is the heavier end. The heavier end is also
/// the only thing that separates `e-resize` from `w-resize`: they are the same picture reflected.
///
/// Everything else keeps the top-left corner of the opaque box, because cursors are DRAWN
/// pointing up and to the left, so that corner is where an arrow's tip is. That is a fact about
/// the sprite in its own upright frame, and the reason this guess is only meaningful when taken
/// there rather than on a sprite the compositor pre-rotated.
///
/// Measured against the hotspots the theme declares, which is the value a compositor programs
/// into HOTSPOT_X/Y where the property exists, and against what master delivers over the angles
/// master handles (0, 90, 270). adwaita-icon-theme 50 at 24 px: mean error per shape 12.08 px
/// down to 4.20, better on 83 of the 105 (shape, angle) cases and worse on 4. The same holds at
/// 48 px and on adwaita-icon-theme 46.
///
/// Two shapes stay further out than master and no bitmap rule reaches them: `help`, whose click
/// point the theme puts on the dot of its question mark, and `alias` by half a pixel. That is why
/// a hotspot the driver publishes is always preferred to this, and why rustdesk#16122 recovers it
/// exactly from the injected pointer instead of guessing.
pub fn infer_hotspot(rgba: &[u8], w: usize, h: usize) -> (i32, i32) {
let (mut minx, mut miny, mut maxx, mut maxy) = (w as i32, h as i32, -1i32, -1i32);
for (i, px) in rgba.chunks_exact(4).take(w * h).enumerate() {
if px[3] >= 128 {
let (x, y) = ((i % w) as i32, (i / w) as i32);
minx = minx.min(x);
maxx = maxx.max(x);
miny = miny.min(y);
maxy = maxy.max(y);
}
}
if maxx < minx || maxy < miny {
return (0, 0);
}
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
let (cx, cy) = ((minx + maxx) / 2, (miny + maxy) / 2);
// An elongated box keeps its centre whichever way it lies (rustdesk#16242): a bar has no
// corner to speak of. Kept ahead of the mirror test so it still covers an elongated shape
// that is NOT symmetric, which the theme happens not to contain but a custom cursor can.
if bh > bw * 2 || bw > bh * 2 {
return (cx, cy);
}
let opaque = |x: i32, y: i32| {
rgba.get((y as usize * w + x as usize) * 4 + 3)
.is_some_and(|&a| a >= 128)
};
let agrees = |i: u64, u: u64| u == 0 || i * 100 >= u * MIRROR_AGREEMENT_PERCENT;
// One pass over the opaque box, comparing it with its own three mirrors, and the mass of each
// half while we are here.
let (mut ix, mut ux) = (0u64, 0u64);
let (mut iy, mut uy) = (0u64, 0u64);
let (mut ih, mut uh) = (0u64, 0u64);
let (mut left, mut right, mut top, mut bottom) = (0u64, 0u64, 0u64, 0u64);
let (half_w, half_h) = (bw / 2, bh / 2);
for y in miny..=maxy {
for x in minx..=maxx {
let (fx, fy) = (maxx - (x - minx), maxy - (y - miny));
let here = opaque(x, y);
for (other, (i, u)) in [
(opaque(fx, y), (&mut ix, &mut ux)),
(opaque(x, fy), (&mut iy, &mut uy)),
(opaque(fx, fy), (&mut ih, &mut uh)),
] {
*i += u64::from(here && other);
*u += u64::from(here || other);
}
if here {
if x - minx < half_w {
left += 1;
} else if maxx - x < half_w {
right += 1;
}
if y - miny < half_h {
top += 1;
} else if maxy - y < half_h {
bottom += 1;
}
}
}
}
// Symmetric under a half turn and the centre is the only point the shape cannot tell from
// itself, whichever the per-axis answers are: a two-headed diagonal arrow mirrors to the
// other diagonal on each axis alone, so neither axis reads as symmetric.
if agrees(ih, uh) {
return (cx, cy);
}
let diagonal = mirrors_about_a_diagonal(&opaque, minx, miny, bw, bh, &agrees);
// An axis is DIRECTIONAL when the shape is a pointer plus an edge marker rather than a plain
// arrow: the perpendicular axis mirrors (the n/e/s/w resize cursors), or the shape mirrors
// about a diagonal (the corner ones). The marker is the end the click point belongs to, and
// it is the heavier end, which is the only thing that tells `e-resize` from `w-resize` - they
// are the same picture reflected. Everything else keeps the up-left corner.
let side = |heavier_is_max: bool, lo: i32, hi: i32| if heavier_is_max { hi } else { lo };
(
if agrees(ix, ux) {
cx
} else if agrees(iy, uy) || diagonal {
side(right > left, minx, maxx)
} else {
minx
},
if agrees(iy, uy) {
cy
} else if agrees(ix, ux) || diagonal {
side(bottom > top, miny, maxy)
} else {
miny
},
)
}
/// Whether the opaque box mirrors onto itself about either of its diagonals.
///
/// A diagonal reflection of a `bw x bh` box is a `bh x bw` box, so the two can only be compared
/// inside a square, and where the box is not square the answer depends on where in that square it
/// is placed: the corner resize cursors are drawn against one corner, and padding away from that
/// corner moves the shape off the diagonal it is symmetric about. `ne-resize` scores 0.62 anchored
/// top-left and 0.98 anchored bottom-right; `nw-resize` is the other way round. So both anchorings
/// are tried and the best answer wins, which is what "the shape is symmetric" means once the
/// reflection is allowed to be shifted back into place.
fn mirrors_about_a_diagonal(
opaque: &impl Fn(i32, i32) -> bool,
minx: i32,
miny: i32,
bw: i32,
bh: i32,
agrees: &impl Fn(u64, u64) -> bool,
) -> bool {
let k = bw.max(bh);
for (dx, dy) in [(0, 0), (k - bw, k - bh)] {
// The box placed at (dx, dy) inside a k x k square, empty everywhere else.
let cell = |r: i32, c: i32| {
let (x, y) = (c - dx, r - dy);
(0..bw).contains(&x) && (0..bh).contains(&y) && opaque(minx + x, miny + y)
};
let (mut id, mut ud, mut ia, mut ua) = (0u64, 0u64, 0u64, 0u64);
for r in 0..k {
for c in 0..k {
let here = cell(r, c);
for (other, (i, u)) in [
(cell(c, r), (&mut id, &mut ud)),
(cell(k - 1 - c, k - 1 - r), (&mut ia, &mut ua)),
] {
*i += u64::from(here && other);
*u += u64::from(here || other);
}
}
}
if agrees(id, ud) || agrees(ia, ua) {
return true;
}
}
false
}
/// One enumerated DRM display, physical geometry only (the server overlays the Wayland logical origin/scale where it can match one).
@@ -40,6 +309,8 @@ pub struct DisplaySnapshot {
pub y: i32,
pub width: u32,
pub height: u32,
/// The kernel's whole-hertz vrefresh: 59.94 reads 60. `DrmReader::crtc_refresh` is exact.
pub refresh_hz: u32,
pub active: bool,
}
@@ -101,6 +372,16 @@ pub struct DrmReader {
lib: &'static DrmtapLib,
ctx: *mut drmtap_ctx,
buf: Vec<u8>,
/// Last provenance reported by THIS reader, for the one-shot log. Per reader and not global:
/// several readers run at once, one per captured display, and their provenance can legitimately
/// differ and be stable -- a virtio-gpu output publishes HOTSPOT_X/Y while an i915 one on the
/// same host does not. A single global would read those two steady streams as an endless
/// alternation and log on every sample, which is the per-frame logging this was written to
/// avoid. -1 is "nothing reported yet".
last_provenance: i8,
/// The plane rotation read right after the last successful grab, before any copy: libdrmtap
/// reads the property when asked, so a read after the copies could describe the next frame.
last_plane_rotation: Option<u32>,
}
impl DrmReader {
@@ -134,9 +415,11 @@ impl DrmReader {
return None;
}
Some(DrmReader {
last_provenance: -1,
lib,
ctx,
buf: Vec::new(),
last_plane_rotation: None,
})
}
@@ -160,6 +443,7 @@ impl DrmReader {
format!("drmtap_grab_mapped failed: errno {errno}"),
));
}
self.last_plane_rotation = self.read_plane_rotation();
if frame.data.is_null() || frame.width == 0 || frame.height == 0 {
(self.lib.frame_release)(self.ctx, &mut frame);
return Err(io::ErrorKind::WouldBlock.into());
@@ -254,6 +538,40 @@ impl DrmReader {
.map(|s| s.to_owned())
}
/// The DRM `rotation` bitmask of the plane the last successful grab read from, as it was right
/// after that grab. A plane without the property answers rotate-0: it cannot have turned
/// anything, so the compositor drew the scanout already turned and the whole output transform
/// is still to be undone. `None` only when the library cannot say: it predates the call
/// (0.5.8), no plane is bound, or the property set could not be read.
pub fn plane_rotation(&self) -> Option<u32> {
self.last_plane_rotation
}
/// The refresh of the captured CRTC in hertz as the reduced fraction `(num, den)` of its
/// current mode, read now. `None` when the library predates the call (0.5.9) or the CRTC has
/// no mode.
pub fn crtc_refresh(&mut self) -> Option<(u64, u64)> {
let f = self.lib.crtc_refresh?;
let (mut num, mut den) = (0u64, 0u64);
// SAFETY: self.ctx is a live context and both outputs outlive the call.
let rc = unsafe { f(self.ctx, &mut num, &mut den) };
(rc == 0 && num != 0 && den != 0).then_some((num, den))
}
fn read_plane_rotation(&mut self) -> Option<u32> {
let f = self.lib.plane_rotation?;
let mut rotation: u32 = 0;
// SAFETY: self.ctx is a live context and `rotation` outlives the call.
let rc = unsafe { f(self.ctx, &mut rotation) };
plane_rotation_answer(rc, rotation)
}
/// The primary plane's rotation read NOW, for a caller that has not grabbed (enumeration):
/// `plane_rotation()` only reflects the last grab.
pub fn query_plane_rotation(&mut self) -> Option<u32> {
self.read_plane_rotation()
}
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
@@ -285,6 +603,7 @@ impl DrmReader {
format!("drmtap_grab_desc failed: errno {errno}"),
));
}
self.last_plane_rotation = self.read_plane_rotation();
// `desc.dma_buf_fd` is the canonical fd (what split_capture.c sends); `frame` owns it too and `frame_release` closes the library's copy.
let raw_fd = if desc.dma_buf_fd >= 0 {
desc.dma_buf_fd
@@ -363,7 +682,10 @@ impl DrmReader {
height: 1,
hotx: 0,
hoty: 0,
hot_measured: false,
colors: vec![0, 0, 0, 0],
x: 0,
y: 0,
})
} else if !c.pixels.is_null()
&& c.width > 0
@@ -376,54 +698,48 @@ impl DrmReader {
let src = std::slice::from_raw_parts(c.pixels, n);
let mut hash: u64 = 1469598103934665603;
let mut colors = Vec::with_capacity(n * 4);
let (mut minx, mut miny, mut maxx, mut maxy) = (cw, ch, -1i32, -1i32);
for (i, &p) in src.iter().enumerate() {
let a = ((p >> 24) & 0xff) as u8;
let r = ((p >> 16) & 0xff) as u8;
let g = ((p >> 8) & 0xff) as u8;
let b = (p & 0xff) as u8;
colors.push(r);
colors.push(g);
colors.push(b);
colors.push(a);
for &p in src.iter() {
colors.push(((p >> 16) & 0xff) as u8);
colors.push(((p >> 8) & 0xff) as u8);
colors.push((p & 0xff) as u8);
colors.push(((p >> 24) & 0xff) as u8);
hash ^= p as u64;
hash = hash.wrapping_mul(1099511628211);
if a >= 128 {
let x = (i as i32) % cw;
let y = (i as i32) / cw;
if x < minx { minx = x; }
if x > maxx { maxx = x; }
if y < miny { miny = y; }
if y > maxy { maxy = y; }
}
}
let (hotx, hoty) = if c.hot_x != 0 || c.hot_y != 0 {
// Ask the library where the hotspot came from instead of guessing from the
// coordinates. `hot_x/hot_y == (0, 0)` means two opposite things - the plane
// exposes no HOTSPOT_X/Y (every bare-metal driver), or it exposes them and the
// driver's answer IS the top-left corner - and the old test below cannot separate
// them: it overrides a real (0, 0) measurement with a guess from the bitmap, and
// on a driver without the properties it would trust a hotspot nobody published.
// Asked BEFORE cursor_release, which is what owns this sample.
let answered = self.lib.cursor_hotspot_valid.and_then(|f| {
let mut valid: c_int = 0;
// 0 = answered; -ENOTSUP = nothing recorded an answer for this sample, which
// is what a cursor read through a pre-0.5.6 privileged helper produces.
(f(&c, &mut valid) == 0).then(|| valid != 0)
});
let hot_measured = hot_measured_from(answered, c.hot_x, c.hot_y);
self.note_hotspot_provenance(answered, hot_measured);
let (hotx, hoty) = if hot_measured {
(c.hot_x, c.hot_y)
} else if maxx >= minx && maxy >= miny {
let (bw, bh) = (maxx - minx + 1, maxy - miny + 1);
if bh > bw * 2 {
((minx + maxx) / 2, (miny + maxy) / 2)
} else {
(minx, miny)
}
} else {
(0, 0)
infer_hotspot(&colors, cw as usize, ch as usize)
};
// Fold geometry + hotspot into the id: identical pixels with a changed size or
// hotspot must count as a new shape, otherwise drm_capture_worker suppresses the
// update (it dedupes by id) and the client keeps rendering the stale cursor.
let mut id = hash;
for v in [cw as u32 as u64, ch as u32 as u64, hotx as u32 as u64, hoty as u32 as u64] {
id ^= v;
id = id.wrapping_mul(1099511628211);
}
let id = cursor_id(hash, cw as u32, ch as u32, hotx, hoty, hot_measured);
Some(CursorSnapshot {
id,
width: cw as u32,
height: ch as u32,
hotx,
hoty,
hot_measured,
colors,
x: c.x,
y: c.y,
})
} else {
None
@@ -458,6 +774,7 @@ impl DrmReader {
y: raw[i].y as i32,
width: raw[i].width,
height: raw[i].height,
refresh_hz: raw[i].refresh_hz,
active: raw[i].active != 0,
}
})
@@ -475,3 +792,207 @@ impl Drop for DrmReader {
}
}
}
#[cfg(test)]
mod hotspot_provenance_tests {
use super::hot_measured_from;
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
/// para-virtualized driver that really publishes the hotspot at the image's top-left corner.
/// `(0, 0)` measured is still measured, and re-inferring one from the bitmap would move a
/// cursor the driver had already placed.
#[test]
fn a_measured_zero_hotspot_is_measured() {
assert!(hot_measured_from(Some(true), 0, 0));
}
}
#[cfg(test)]
mod hotspot_guess_tests {
use super::infer_hotspot;
/// A sprite from an ASCII picture: `#` is opaque, anything else transparent. Written this way
/// because every case here is about a SHAPE, and a shape is unreadable as a byte array.
fn sprite(rows: &[&str]) -> (Vec<u8>, usize, usize) {
let (h, w) = (rows.len(), rows[0].len());
let mut px = vec![0u8; w * h * 4];
for (y, row) in rows.iter().enumerate() {
assert_eq!(row.len(), w, "ragged picture");
for (x, c) in row.bytes().enumerate() {
if c == b'#' {
px[(y * w + x) * 4 + 3] = 255;
}
}
}
(px, w, h)
}
/// An arrow keeps the top-left corner of its box. Cursors are drawn pointing up and left, so
/// that corner IS the tip - and it is a fact about the sprite upright, which is why the
/// consumer re-takes this guess after turning a rotated sprite back.
#[test]
fn an_arrow_points_at_the_corner_of_its_box() {
let (px, w, h) = sprite(&[
".........",
".#.......",
".##......",
".###.....",
".####....",
".#####...",
".###.....",
".#..##...",
"......##.",
]);
assert_eq!(infer_hotspot(&px, w, h), (1, 1));
}
/// A shape that mirrors onto itself about the box's mid-lines has no tip to point with, so
/// the corner names nothing and the middle is the only answer the shape supports. This is the
/// crosshair/cell/resize family, 17 of the installed theme's 35 shapes.
#[test]
fn a_symmetric_shape_is_held_by_its_middle() {
let (px, w, h) = sprite(&[
"....#....",
"....#....",
"....#....",
"....#....",
"#########",
"....#....",
"....#....",
"....#....",
"....#....",
]);
assert_eq!(infer_hotspot(&px, w, h), (4, 4));
}
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
/// theme puts the click point on the BAR. The bar is the heavy end, and it is the only thing
/// that separates `e-resize` from `w-resize`: they are the same picture reflected, so a rule
/// that always took the up-left corner had to be wrong for one of the two.
#[test]
fn a_directional_resize_cursor_is_held_by_its_bar() {
let (px, w, h) = sprite(&[
"......####",
"..##..####",
".###..####",
"####..####",
".###..####",
"..##..####",
"......####",
]);
assert_eq!(infer_hotspot(&px, w, h), (9, 3));
// The mirror image has to answer the other side, or the rule is not reading the shape.
let (px, w, h) = sprite(&[
"####......",
"####..##..",
"####..###.",
"####..####",
"####..###.",
"####..##..",
"####......",
]);
assert_eq!(infer_hotspot(&px, w, h), (0, 3));
}
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
/// keeps its centre. Nothing in the installed theme is shaped like this - its two I-beams are
/// both symmetric - but a custom cursor can be, and this is the rustdesk#16242 round-one fix.
#[test]
fn an_elongated_shape_keeps_its_centre_even_when_it_is_lopsided() {
let (px, w, h) = sprite(&["##########.", "#####......", "##########."]);
assert_eq!(infer_hotspot(&px, w, h), (4, 1));
}
}
/// DRM_MODE_ROTATE_0: the `rotation` bitmask of a plane that turned nothing.
const DRM_MODE_ROTATE_0: u32 = 1 << 0;
/// What a `drmtap_plane_rotation` return means to the consumer. Success is the mask. `-ENOTSUP`
/// (the plane has no `rotation` property) is rotate-0, not "unknown": such a plane cannot have
/// turned the scanout, so the frame arrives turned by the whole output transform, which is the
/// virtio-gpu and vmwgfx case this exists for. Anything else (`-ENOENT` with no plane bound, a
/// failed property read) is `None`, and the consumer keeps its pre-0.5.8 rule.
fn plane_rotation_answer(rc: c_int, rotation: u32) -> Option<u32> {
if rc == 0 {
Some(rotation)
} else if rc == -hbb_common::libc::ENOTSUP {
Some(DRM_MODE_ROTATE_0)
} else {
None
}
}
#[cfg(test)]
mod plane_rotation_tests {
use super::*;
#[test]
fn a_plane_without_the_property_turned_nothing() {
assert_eq!(plane_rotation_answer(0, 0x4), Some(0x4));
assert_eq!(plane_rotation_answer(0, 0x1), Some(0x1));
assert_eq!(plane_rotation_answer(-hbb_common::libc::ENOTSUP, 0), Some(0x1));
assert_eq!(plane_rotation_answer(-hbb_common::libc::ENOENT, 0), None);
assert_eq!(plane_rotation_answer(-hbb_common::libc::EINVAL, 0), None);
assert_eq!(plane_rotation_answer(-hbb_common::libc::EIO, 7), None);
}
}
#[cfg(test)]
mod crtc_refresh_tests {
use super::*;
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
static RC: AtomicI32 = AtomicI32::new(0);
static NUM: AtomicU64 = AtomicU64::new(0);
static DEN: AtomicU64 = AtomicU64::new(0);
unsafe extern "C" fn crtc_refresh(_: *mut drmtap_ctx, num: *mut u64, den: *mut u64) -> c_int {
*num = NUM.load(Ordering::SeqCst);
*den = DEN.load(Ordering::SeqCst);
RC.load(Ordering::SeqCst)
}
unsafe extern "C" fn grab_mapped(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) -> c_int {
-1
}
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {}
unsafe extern "C" fn grab_desc(
_: *mut drmtap_ctx,
_: *mut drmtap_dmabuf_desc,
_: *mut drmtap_frame_info,
) -> c_int {
-1
}
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, _: *mut u32) -> c_int {
-1
}
fn reader(with_call: bool) -> DrmReader {
let mut lib = DrmtapLib::fake(grab_mapped, frame_release, grab_desc, plane_rotation);
if with_call {
lib.crtc_refresh = Some(crtc_refresh);
}
DrmReader {
lib: Box::leak(Box::new(lib)),
ctx: std::ptr::null_mut(),
buf: Vec::new(),
last_provenance: -1,
last_plane_rotation: None,
}
}
/// rustdesk#16175: the exact refresh paces the producer; an older library has no answer.
#[test]
fn the_crtc_refresh_is_a_fraction_or_nothing() {
assert_eq!(reader(false).crtc_refresh(), None, "a library before 0.5.9");
let mut r = reader(true);
RC.store(0, Ordering::SeqCst);
NUM.store(148352, Ordering::SeqCst);
DEN.store(2475, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), Some((148352, 2475)));
RC.store(-hbb_common::libc::ENODATA, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), None, "a CRTC with no mode");
RC.store(0, Ordering::SeqCst);
DEN.store(0, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), None, "a zero denominator is no answer");
}
}

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