Compare commits

..
37 Commits
Author SHA1 Message Date
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
65 changed files with 8468 additions and 592 deletions
+49 -1
View File
@@ -874,7 +874,7 @@ jobs:
- name: Test cursor sizing
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
working-directory: flutter
run: flutter test --timeout 60s test/cursor_size_test.dart
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
- name: Setup vcpkg with Github Actions binary cache
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
@@ -2046,6 +2046,52 @@ jobs:
*) echo "::error::build.py returned no '$want' feature: $FEATURES"; exit 1 ;;
esac
done
# Run the drm-gated unit tests HERE, because nowhere else does. The ordinary linux CI
# runs the suite, but `drm` is opt-in, so every test behind that feature -- the cursor
# rotation and hotspot ones especially -- has no continuous coverage at all otherwise.
# Debug rather than --release: these are pure logic tests and the release build is
# already the slow part of this job.
# A MINIMAL feature set, not the production $FEATURES: these are pure logic tests of
# the drm paths, and pulling hwcodec in makes the test binary fail to link at all
# (undefined reference to fcntl64 in this container), so the tests never run.
#
# Two packages, because `cargo test --lib` at the root builds the ROOT package only:
# the provenance tests live in libs/scrap and would never be selected from here. The
# ordinary linux CI runs --workspace but without the drm feature, so these are not
# covered there either.
#
# awk sums the counts rather than bc, which this container does not install.
#
# A cargo test FILTER that matches nothing exits 0, so a rename would turn this into a
# green no-op. Assert each command actually ran something.
run_drm_tests() {
local desc="$1"; shift
local out
out=$("$@" 2>&1) || { echo "$out"; echo "::error::drm tests failed: $desc"; exit 1; }
local ran
ran=$(echo "$out" | awk '/^running [0-9]+ tests?$/ { n += $2 } END { print n+0 }')
echo "$desc ran $ran tests"
if [ "$ran" -lt 1 ]; then
echo "::error::$desc selected no tests; it was renamed or removed"
exit 1
fi
}
run_drm_tests "rustdesk drm_capturer_tests" \
cargo test --locked --lib --features drm drm_capturer_tests
run_drm_tests "rustdesk ipc::test" \
cargo test --locked --lib --features drm ipc::test
run_drm_tests "rustdesk cursor_pos_tests" \
cargo test --locked --lib --features drm cursor_pos_tests
run_drm_tests "rustdesk peer_abs_sample_tests" \
cargo test --locked --lib --features drm peer_abs_sample_tests
run_drm_tests "rustdesk input_map_tests" \
cargo test --locked --lib --features drm input_map_tests
run_drm_tests "scrap hotspot_provenance_tests" \
cargo test --locked -p scrap --features drm hotspot_provenance_tests
run_drm_tests "scrap hotspot_guess_tests" \
cargo test --locked -p scrap --features drm hotspot_guess_tests
run_drm_tests "scrap plane_rotation_tests" \
cargo test --locked -p scrap --features drm plane_rotation_tests
cargo build --locked --lib --features "$FEATURES" --release
rm -rf target/release/deps target/release/build
rm -rf ~/.cargo
@@ -2406,7 +2452,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'
+38
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.
@@ -127,12 +141,36 @@ 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.
## 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
+8 -1
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",
@@ -7196,6 +7196,7 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xxhash-rust",
"zstd",
]
@@ -10806,6 +10807,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"
+1
View File
@@ -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 }
+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.8.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '5da68a3a368db569716d0d0f11cefacbb11b2290'
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
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)
+279 -52
View File
@@ -58,7 +58,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 +74,6 @@ class CachedPeerData {
return jsonEncode({
'updatePrivacyMode': updatePrivacyMode,
'peerInfo': peerInfo,
'cursorDataList': cursorDataList,
'lastCursorId': lastCursorId,
'permissions': permissions,
'secure': secure,
@@ -88,9 +88,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 +320,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 +349,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);
@@ -1437,9 +1427,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 +1652,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 +2853,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 +2875,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 +2928,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 +3005,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 +3178,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 +3200,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 +3218,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 +3522,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 +3570,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 +3607,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 +3853,10 @@ class CursorModel with ChangeNotifier {
_clearCache();
_cache = null;
_cacheMap.clear();
_nativeIds.clear();
_awaitingNative.clear();
_unavailable = null;
_generation++;
}
_clearCache() {
@@ -3644,6 +3865,8 @@ class CursorModel with ChangeNotifier {
debugPrint("deleting cursor with key $k");
deleteCustomCursor(k);
}
_cacheKeys.clear();
shownKey = null;
resetSystemCursor();
}
@@ -3983,6 +4206,7 @@ class FFI {
}
if (isWeb) {
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
platformFFI.setRgbaCallback((int display, Uint8List data) {
onEvent2UIRgba();
imageModel.onRgba(display, data);
@@ -4065,6 +4289,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;
+4
View File
@@ -285,6 +285,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) {}
+11
View File
@@ -189,6 +189,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) {
+66 -1
View File
@@ -26,6 +26,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 +58,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 +962,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.
+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"
+1 -1
View File
@@ -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:
+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();
});
}
+683
View File
@@ -0,0 +1,683 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/native/custom_cursor.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
/// Stands in for the core, which keeps every shape the peer sent.
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final core = <String, CursorShape>{};
final fetched = <String>[];
// While set, a fetch answers only when [answerFetches] is called.
bool holdFetches = false;
// While set, a fetch throws before it returns a future.
bool throwAtOnce = false;
final _held = <Completer<CursorShape?>, String>{};
@override
Future<CursorShape?> fetchCursorShape(String id) {
fetched.add(id);
if (throwAtOnce) throw StateError('no core');
if (!holdFetches) return Future.value(core[id]);
final answer = Completer<CursorShape?>();
_held[answer] = id;
return answer.future;
}
void answerFetches() {
final held = Map.of(_held);
_held.clear();
held.forEach((answer, id) => answer.complete(core[id]));
}
void failFetches() {
final held = Map.of(_held);
_held.clear();
held.forEach((answer, _) => answer.completeError(StateError('failed')));
}
bool showRemoteCursor = false;
@override
bool get showsRemoteCursor => showRemoteCursor;
}
String? _key(MouseCursor cursor) =>
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
class _FFI extends Fake implements FFI {
_FFI() {
ffiModel = FfiModel(WeakReference(this));
cursorModel = _Cursor(this);
}
@override
final SessionID sessionId = const Uuid().v4obj();
@override
late final FfiModel ffiModel;
@override
late final CursorModel cursorModel;
_Cursor get cursor => cursorModel as _Cursor;
}
Uint8List _pixels(int size, int seed) =>
Uint8List.fromList(List.generate(size * size * 4, (i) => (i + seed) % 256));
/// A shape as the core delivers it, and keeps it.
Future<void> _feed(_FFI ffi, String id, {int size = 8, int seed = 0}) {
final pixels = _pixels(size, seed);
ffi.cursor.core[id] =
CursorShape(hotx: 0, hoty: 0, width: size, height: size, colors: pixels);
return ffi.ffiModel.handleCursorData(id, 0, 0, size, size, pixels);
}
void _select(_FFI ffi, String id) {
final evt = {'id': id};
ffi.ffiModel.updateLastCursorId(evt);
ffi.ffiModel.handleCursorId(evt);
}
Future<void> _settle() async {
for (var i = 0; i < 2; i++) {
await Future<void>.delayed(const Duration(milliseconds: 5));
}
}
void main() {
final binding = TestWidgetsFlutterBinding.ensureInitialized();
final channel = Platform.isWindows
? SystemChannels.mouseCursor
: const MethodChannel('flutter_custom_cursor');
final registered = <String>[];
final deleted = <String>[];
late _FFI ffi;
setUp(() {
registered.clear();
deleted.clear();
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
(call) async {
final args = call.arguments as Map<dynamic, dynamic>;
if (call.method.startsWith('createCustomCursor')) {
registered.add(args['name'] as String);
return args['name'];
}
if (call.method.startsWith('deleteCustomCursor')) {
deleted.add(args['name'] as String);
}
return null;
});
ffi = _FFI();
});
tearDown(() {
ffi.cursorModel.disposeImages();
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);
});
test(
'only the shape in use keeps an image, and a shape its native cursor holds '
'keeps no pixels', () async {
final cursor = ffi.cursorModel;
for (var round = 0; round < 3; round++) {
for (final (id, seed) in [('1', 1), ('2', 2), ('3', 3)]) {
await _feed(ffi, id, seed: seed);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
}
expect(ffi.cursorModel.shapeIds, ['3']);
for (final id in ['1', '2']) {
expect(ffi.cursorModel.cachedShape(id)!.hasPixels, isFalse);
expect(ffi.cursorModel.cachedShape(id)!.data, isNull);
}
expect(ffi.cursor.fetched, isEmpty);
});
test('the shape in use keeps its pixels, and a new raster is made at once',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
expect(cursor.cache!.hasPixels, isTrue);
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
isNot(MouseCursor.defer));
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'nothing had to be decoded');
expect(registered.length, 2);
expect((cursor.cache!.rasterWidth, cursor.cache!.rasterHeight), (16, 16));
await _feed(ffi, '2');
expect(cursor.cachedShape('1')!.hasPixels, isFalse,
reason: 'switched away from, a shape keeps no pixels');
_select(ffi, '1');
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
isNot(MouseCursor.defer));
await _settle();
expect(registered.length, 2, reason: 'its native cursor is still there');
expect(ffi.cursor.fetched, isEmpty);
});
test('native cursors stay for the session, every raster of every shape',
() async {
// A delete frees nothing on Windows, so none is deleted before the session ends.
final cursor = ffi.cursorModel;
for (var i = 0; i < 100; i++) {
await _feed(ffi, '$i', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(deleted, isEmpty);
expect(cursor.cachedKeys.length, 100);
_select(ffi, '0');
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)),
cursor.nativeKey(cursor.cache!, 1.0));
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'its cursor is still there');
expect(registered.length, 100);
});
test(
'a raster made before is found again after the shape was switched away from',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'A', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
final first = registered.single;
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
await _feed(ffi, 'B');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
final count = registered.length;
_select(ffi, 'A'); // its pixels went; its cursors at both rasters stay
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), first);
await _settle();
expect(ffi.cursor.fetched, isEmpty);
expect(registered.length, count);
});
test('a new raster of a shape without pixels keeps the cursor shown before',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, '2', size: 32);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
_select(ffi, '1'); // its native cursor held its pixels, so they went
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
await _settle();
expect(ffi.cursor.fetched, ['1']);
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)),
cursor.nativeKey(cursor.cache!, 0.5));
});
test('shapes that keep decoding late still get their native cursors',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'arrow');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
// A and B arrive, each decoding only after the peer moved on.
for (final (id, seed) in [('A', 1), ('B', 2)]) {
final pixels = _pixels(8, seed);
ffi.cursor.core[id] =
CursorShape(hotx: 0, hoty: 0, width: 8, height: 8, colors: pixels);
final decoding = ffi.ffiModel.handleCursorData(id, 0, 0, 8, 8, pixels);
_select(ffi, 'arrow');
await decoding;
}
// Each fetch answers only after the next switch.
ffi.cursor.holdFetches = true;
for (var i = 0; i < 6; i++) {
_select(ffi, i.isEven ? 'A' : 'B');
ffi.cursor.answerFetches();
await _settle();
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(registered.where((key) => key.contains('_A_')), isNotEmpty);
expect(registered.where((key) => key.contains('_B_')), isNotEmpty);
});
test('a zoom still gets native cursors for shapes that keep decoding late',
() async {
final cursor = ffi.cursorModel;
// An animation whose frames have native cursors at 1.0 only.
for (final (id, seed) in [('A', 1), ('B', 2)]) {
await _feed(ffi, id, size: 32, seed: seed);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
// At 0.5 each frame is fetched again, and each fetch answers after the next switch.
ffi.cursor.holdFetches = true;
for (var i = 0; i < 6; i++) {
_select(ffi, i.isEven ? 'A' : 'B');
ffi.cursor.answerFetches();
await _settle();
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
}
expect(
registered
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
isNotEmpty);
expect(
registered
.where((key) => key.contains('_B_') && key.endsWith('_16_16')),
isNotEmpty);
});
test(
'a raster still missing keeps a late restore, whatever was shown meanwhile',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'A', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, 'B');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
_select(ffi, 'A');
ffi.cursor.holdFetches = true;
buildCursorOfCache(cursor, 0.5, cursor.cache); // no cursor at 0.5: fetched
buildCursorOfCache(cursor, 1.0, cursor.cache); // 1.0 has one meanwhile
_select(ffi, 'B');
ffi.cursor.answerFetches();
await _settle();
ffi.cursor.fetched.clear();
_select(ffi, 'A');
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
expect(ffi.cursor.fetched, isEmpty,
reason: 'its pixels waited for the cursor at 0.5');
expect(
registered
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
isNotEmpty);
});
test('shapes waiting for a native cursor keep their pixels, within the limit',
() async {
const max = CursorModel.kRecentShapes;
for (var i = 0; i <= max + 1; i++) {
await _feed(ffi, '$i');
}
expect(ffi.cursorModel.cachedShape('0')!.hasPixels, isFalse,
reason: 'the one waiting longest is let go');
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue);
expect(ffi.cursorModel.cachedShape('$max')!.hasPixels, isTrue);
});
test('two animated cursors and the everyday set keep their native cursors',
() async {
// Each frame is a shape of its own: 18 for the Windows busy cursor, 23 for
// KDE Breeze's wait and progress cursors on X11.
const frames = 23;
const statics = 12;
final cursor = ffi.cursorModel;
final shapes = [
for (var i = 0; i < statics; i++) 's$i',
for (var i = 0; i < frames; i++) 'wait$i',
for (var i = 0; i < frames; i++) 'progress$i',
];
for (var i = 0; i < shapes.length; i++) {
await _feed(ffi, shapes[i], seed: i);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
ffi.cursor.fetched.clear();
for (final id in shapes) {
_select(ffi, id);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(ffi.cursor.fetched, isEmpty,
reason: 'every shape kept its native cursor');
expect(registered.length, shapes.length);
expect(deleted, isEmpty);
});
test('a shape painted again is decoded again, the last one shown meanwhile',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
expect(ffi.cursorModel.image?.width, 8, reason: 'shape 2 until 1 is back');
await _settle();
expect(ffi.cursor.fetched, ['1']);
expect(ffi.cursorModel.image?.width, 16);
expect(ffi.cursorModel.shapeIds, ['1']);
});
test('a shape the core gives but that does not decode is asked for once',
() async {
await _feed(ffi, '1');
await _feed(ffi, '2');
ffi.cursor.core['1'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
_select(ffi, '1');
for (var i = 0; i < 5; i++) {
ffi.cursorModel.image;
await _settle();
}
expect(ffi.cursor.fetched, ['1']);
});
test('a shape switched away from while it decoded is asked for again',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
ffi.cursorModel.image; // asks the core
// The core has answered and the shape is decoding when the peer moves on.
await Future<void>.delayed(Duration.zero);
_select(ffi, '2');
await _settle();
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue,
reason:
'decoded after the peer moved on, it waits for its native cursor');
_select(ffi, '1');
ffi.cursorModel.image;
await _settle();
expect(ffi.cursor.fetched, ['1', '1']);
expect(ffi.cursorModel.image?.width, 16);
});
test('a shape decoded after the session was cleared is not kept', () async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
ffi.cursorModel.image; // asks the core
ffi.cursorModel.clear();
await _settle();
expect(ffi.cursorModel.shapeIds, isEmpty);
expect(ffi.cursorModel.cache, isNull);
});
test('a shape the core does not have is asked for once', () async {
await _feed(ffi, '1');
await _feed(ffi, '2');
ffi.cursor.core.remove('1');
_select(ffi, '1');
for (var i = 0; i < 5; i++) {
ffi.cursorModel.image;
await _settle();
}
expect(ffi.cursor.fetched, ['1']);
});
test('a shape the core lacks is remembered only while it is in use',
() async {
await _feed(ffi, '1');
for (var i = 0; i < 1000; i++) {
_select(ffi, 'missing$i');
ffi.cursorModel.image;
}
await _settle();
expect(ffi.cursor.fetched.length, 1000, reason: 'each is asked for once');
_select(ffi, 'missing0');
await _settle();
expect(ffi.cursor.fetched.length, 1001,
reason: 'nothing is kept for a shape no longer in use');
});
test('a shape the core lacks is asked for again after another was in use',
() async {
await _feed(ffi, '1');
_select(ffi, 'missing0');
await _settle();
_select(ffi, '1');
_select(ffi, 'missing0');
await _settle();
expect(ffi.cursor.fetched, ['missing0', 'missing0']);
});
test('a moved tab carries the id in use, and its window asks the core',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
await _feed(ffi, '1', size: 16);
final carried = ffi.ffiModel.cachedPeerData.toString();
expect(carried, isNot(contains('colors')));
expect(CachedPeerData.fromString(carried)!.lastCursorId['id'], '1',
reason: 'a shape arriving is the shape in use');
final moved = _FFI();
addTearDown(moved.cursorModel.disposeImages);
moved.cursor.core.addAll(ffi.cursor.core);
_select(moved, '1');
await _settle();
expect(moved.cursor.fetched, ['1']);
expect(moved.cursorModel.cache?.id, '1');
expect(moved.cursorModel.image?.width, 16);
});
test('a shape keeps a native cursor for each raster it was shown at',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
for (final scale in [1.0, 0.5, 1.0, 0.5]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await _settle();
}
expect(registered.length, 2, reason: 'a raster returned to is reused');
expect(deleted, isEmpty);
expect(cursor.cachedKeys, registered.toSet());
});
test('a cleared session forgets the native cursors it deleted', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
cursor.clear();
await _settle();
expect(deleted, registered);
expect(cursor.cachedKeys, isEmpty);
});
test('a tab closing does not delete the cursors of another tab', () async {
final other = _FFI();
addTearDown(other.cursorModel.disposeImages);
while (preDefaultCursor.cache == null) {
await _settle();
}
buildCursorOfCache(ffi.cursorModel, 1.0, preDefaultCursor.cache);
buildCursorOfCache(other.cursorModel, 1.0, preDefaultCursor.cache);
await _settle();
expect(registered.toSet().length, 2, reason: 'each tab has its own');
ffi.cursorModel.clear();
await _settle();
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
});
test('a shape given as a view into a larger buffer is read from the view',
() async {
final pixels = _pixels(8, 3);
final padded = Uint8List(16 + pixels.length)
..setRange(16, 16 + pixels.length, pixels);
await ffi.ffiModel
.handleCursorData('1', 0, 0, 8, 8, Uint8List.sublistView(padded, 16));
final p = ffi.cursorModel.cache!.image.getPixel(0, 0);
expect([p.r, p.g, p.b, p.a], [3, 4, 5, 6]);
});
test('a shape still decoding leaves the one shown before in place', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
_select(ffi, '2'); // its shape has not decoded yet
expect(cursor.cache?.id, '1');
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), shown);
expect(cursor.image, isNotNull);
await _feed(ffi, '2');
expect(cursor.cache?.id, '2');
});
for (final how in ['does not have', 'cannot decode']) {
test('a shape the core $how leaves the default cursor, not the one before',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
if (how == 'cannot decode') {
ffi.cursor.core['2'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
}
_select(ffi, '2');
expect(cursor.cache?.id, '1', reason: 'kept while the shape may come');
var notified = 0;
cursor.addListener(() => notified++);
await _settle();
expect(cursor.cache, isNull,
reason: 'the desktop shows preDefaultCursor');
expect(cursor.image, isNull, reason: 'and so does a painted cursor');
expect(notified, greaterThan(0));
});
}
test('a shape sent that does not decode leaves the default cursor', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
ffi.cursor.core['2'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
await ffi.ffiModel.handleCursorData('2', 0, 0, 8, 8, Uint8List(3));
expect(cursor.cache, isNull);
expect(cursor.image, isNull);
_select(ffi, '2');
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'it is not asked for either');
});
test('a fetch failing after the session was cleared marks nothing in it',
() async {
final cursor = ffi.cursorModel;
ffi.cursor.holdFetches = true;
_select(ffi, '1'); // not decoded here yet, so it is asked for
cursor.clear();
ffi.cursor.failFetches();
await _settle();
ffi.cursor.holdFetches = false;
_select(ffi, '1'); // the same id, now in the new session
await _settle();
expect(ffi.cursor.fetched, ['1', '1']);
});
test('a fetch that throws at once tells the listeners after the build',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
ffi.cursor.throwAtOnce = true;
cursor.id = '2';
var notified = 0;
cursor.addListener(() => notified++);
cursor.restorePixels('2');
expect(notified, 0, reason: 'a build may be what asked');
await _settle();
expect(notified, greaterThan(0));
expect(cursor.cache, isNull);
});
test('a raster still being made falls back to a shape, not the forbidden one',
() async {
final cursor = ffi.cursorModel;
for (var i = 0; preForbiddenCursor.cache == null && i < 100; i++) {
await _settle();
}
expect(preForbiddenCursor.cache, isNotNull);
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, '2', size: 32);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
buildCursorOfCache(cursor, 1.0, preForbiddenCursor.cache); // input disabled
_select(ffi, '1'); // its native cursor held its pixels, so they went
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
});
group('a painted cursor', () {
void painted(String how) {
if (how == 'mobile') {
final was = isMobile;
isMobile = true;
addTearDown(() => isMobile = was);
} else {
ffi.cursor.showRemoteCursor = true;
}
}
for (final how in ['mobile', 'remote cursor shown']) {
test('keeps the images of two animations and the everyday set ($how)',
() async {
painted(how);
final cursor = ffi.cursorModel;
final shapes = [
for (var i = 0; i < 12; i++) 's$i',
for (var i = 0; i < 23; i++) 'wait$i',
for (var i = 0; i < 23; i++) 'progress$i',
];
for (var i = 0; i < shapes.length; i++) {
await _feed(ffi, shapes[i], seed: i);
}
for (final id in shapes) {
_select(ffi, id);
expect(cursor.shapeIds.last, id, reason: 'its image is at hand');
}
await _settle();
expect(ffi.cursor.fetched, isEmpty);
});
}
test('keeps the images used last, and decodes the others again', () async {
painted('mobile');
const max = CursorModel.kRecentShapes;
final cursor = ffi.cursorModel;
for (var i = 0; i <= max; i++) {
await _feed(ffi, '$i');
}
expect(cursor.shapeIds.length, max);
_select(ffi, '$max');
_select(ffi, '1');
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'shape 1 was used lately');
_select(ffi, '0');
expect(cursor.image, isNotNull, reason: 'shape 1 until 0 is back');
await _settle();
expect(ffi.cursor.fetched, ['0']);
expect(cursor.shapeIds.length, max);
});
test('keeps a shape that finished decoding after the peer moved on',
() async {
painted('mobile');
const max = CursorModel.kRecentShapes;
final cursor = ffi.cursorModel;
for (var i = 0; i <= max; i++) {
await _feed(ffi, '$i');
}
_select(ffi, '0');
cursor.image; // let go, so it is asked for
await Future<void>.delayed(Duration.zero);
_select(ffi, '1');
await _settle();
_select(ffi, '0');
cursor.image;
await _settle();
expect(ffi.cursor.fetched, ['0'], reason: 'the late one was kept');
expect(cursor.shapeIds.last, '0');
});
});
}
+14 -14
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 {
@@ -111,7 +112,7 @@ void main() {
((1, 64), 0.25, (1, 16)),
((8, 8), 0.5, (12, 12)),
((4, 64), 1.0, (4, 64)),
((1, 512), 10.0, (2, 1024)),
((1, 512), 10.0, (1, 512)),
]) {
test('native cursor size $scenario',
() => _checkSize(scenario, registrations));
@@ -181,15 +182,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;
@@ -259,7 +259,7 @@ Future<void> _checkRasterTransitions(
]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await Future<void>.delayed(Duration.zero);
final key = cursor.cache.updateGetKey(scale);
final key = cursor.nativeKey(cursor.cache, scale);
_expectSize(
registrations.singleWhere((args) => args['name'] == key), expected);
}
@@ -268,7 +268,7 @@ Future<void> _checkRasterTransitions(
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 +361,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());
+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 {
+10 -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;
@@ -859,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;
}
}
@@ -1002,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;
+95 -5
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,6 +242,7 @@ 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;
@@ -282,6 +303,22 @@ mod tests {
assert_eq!(files[0].name, PathBuf::from("file.txt"));
}
#[test]
fn file_list_id_is_fnv1a() {
// Reference vectors; the Windows side computes the same id in C.
assert_eq!(file_list_id(b"") as u32, 0x811c_9dc5);
assert_eq!(file_list_id(b"a") as u32, 0xe40c_292c);
assert_eq!(file_list_id(b"foobar") as u32, 0xbf9c_f968);
}
#[test]
fn parsed_files_carry_their_list_id() {
let pdu = descriptor_pdu("file.txt");
let id = file_list_id(&pdu);
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
assert_eq!(files[0].clip_data_id, id);
}
#[test]
fn rejects_non_terminated_file_name() {
let name = "a".repeat(FILE_NAME_CODE_UNITS);
@@ -290,4 +327,57 @@ mod tests {
Err(CliprdrError::InvalidRequest { .. })
));
}
fn parse_perm(attributes: u32) -> u16 {
let mut pdu = descriptor_pdu("folder");
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
.copy_from_slice(&attributes.to_le_bytes());
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].perm
}
#[test]
fn windows_directories_stay_searchable() {
const FILE_ATTRIBUTE_READONLY: u32 = 0x01;
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x02;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
for attributes in [
FILE_ATTRIBUTE_DIRECTORY,
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_READONLY,
FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN,
] {
assert_eq!(
parse_perm(attributes),
PERM_RWX,
"attributes {attributes:#x}"
);
}
}
fn parse_last_write_time(filetime: u64) -> SystemTime {
let mut pdu = descriptor_pdu("file.txt");
pdu[PDU_HEADER_SIZE..PDU_HEADER_SIZE + size_of::<u32>()]
.copy_from_slice(&(FLAGS_FD_ATTRIBUTES | FLAGS_FD_LAST_WRITE).to_le_bytes());
pdu[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + size_of::<u64>()]
.copy_from_slice(&filetime.to_le_bytes());
FileDescription::parse_file_descriptors(pdu, 0).unwrap()[0].last_modified
}
#[test]
fn decodes_last_write_time_from_windows_filetime() {
// 2023-11-14 22:13:20 UTC
assert_eq!(
parse_last_write_time(133_444_736_000_000_000),
SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000)
);
// 3000-01-01 00:00:00 UTC
assert_eq!(
parse_last_write_time(441_481_536_000_000_000),
SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000)
);
// 1969-12-31 23:59:59 UTC falls back to the Unix epoch.
assert_eq!(
parse_last_write_time(116_444_736_000_000_000 - 10_000_000),
SystemTime::UNIX_EPOCH
);
}
}
+8 -2
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> {
+46 -3
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;
@@ -323,6 +323,7 @@ mod file_list_test {
use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
time::{Duration, SystemTime},
};
use hbb_common::bytes::{BufMut, BytesMut};
@@ -490,4 +491,46 @@ mod file_list_test {
std::fs::remove_file(file_path)?;
Ok(())
}
const LAST_WRITE_TIME_OFFSET: usize = 56;
fn file_with_last_write_time(last_write_time: SystemTime) -> LocalFile {
let mut file = generate_tree("").remove(1);
file.last_write_time = last_write_time;
file
}
fn encoded_last_write_time(last_write_time: SystemTime) -> Result<u64, CliprdrError> {
let descriptor = file_with_last_write_time(last_write_time).as_bin()?;
let field = &descriptor[LAST_WRITE_TIME_OFFSET..LAST_WRITE_TIME_OFFSET + 8];
Ok(u64::from_le_bytes(field.try_into().unwrap()))
}
#[test]
fn encodes_last_write_time_as_windows_filetime() -> Result<(), CliprdrError> {
// 2023-11-14 22:13:20 UTC
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
assert_eq!(encoded_last_write_time(time)?, 133_444_736_000_000_000);
// 3000-01-01 00:00:00 UTC
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(32_503_680_000);
assert_eq!(encoded_last_write_time(time)?, 441_481_536_000_000_000);
// Times before 1970 are sent as 1970-01-01 00:00:00 UTC.
let time = SystemTime::UNIX_EPOCH - Duration::from_secs(1);
assert_eq!(encoded_last_write_time(time)?, 116_444_736_000_000_000);
Ok(())
}
#[test]
fn last_write_time_round_trips() -> Result<(), CliprdrError> {
let file = file_with_last_write_time(
SystemTime::UNIX_EPOCH + Duration::new(1_700_000_000, 123_456_700),
);
let mut pdu = BytesMut::with_capacity(4 + FILE_DESCRIPTOR_SIZE);
pdu.put_u32_le(1);
pdu.put(file.as_bin()?.as_slice());
let parsed = FileDescription::parse_file_descriptors(pdu.to_vec(), 0)?;
assert_eq!(parsed[0].last_modified, file.last_write_time);
Ok(())
}
}
@@ -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,75 @@ 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 finder_progress_rejects_unrepresentable_byte_count() {
let (_temp, target, _) = test_directories();
let file = file_description("large.bin", FileType::File, i64::MAX as u64 + 1);
let mut task = paste_task_handle(target.clone(), vec![file]);
let error = task.update_next(0).expect_err("byte count must not wrap");
assert!(matches!(&error, CliprdrError::InvalidRequest { .. }));
task.on_error(error);
assert!(task.progress.finder_progress.is_none());
assert!(std::fs::read_dir(target).unwrap().next().is_none());
}
#[test]
fn validates_all_paths_before_creating_files() {
let (_temp, target, outside) = test_directories();
+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(
+610 -13
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,6 +499,30 @@ mod sig_test {
p.to_string_lossy().to_string()
}
// 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())
}
// 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();
}
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]
fn fingerprint_missing_path_is_default() {
let tmp = TmpDir::new("missing");
@@ -393,7 +573,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 +596,420 @@ mod sig_test {
clear_files(); // leave the global clean for other tests
}
#[test]
fn range_request_huge_length_is_clamped() {
let tmp = TmpDir::new("range");
let file = tmp.join("data.bin");
fs::write(&file, b"0123456789").unwrap();
let files = vec![path_str(&file)];
let mut clip = ClipFiles::default();
clip.sync_files(&files, fingerprint(&files)).unwrap();
let file_idx = clip.first_file_index;
// offset + length used to wrap to 0, skip the clamp and ask for a u64::MAX buffer.
let resp = clip
.serve_file_contents(
0,
FileContentsRequest::Range {
stream_id: 0,
file_idx,
offset: 1,
length: u64::MAX,
},
)
.unwrap();
match resp {
ClipboardFile::FileContentsResponse { requested_data, .. } => {
assert_eq!(requested_data, b"123456789");
}
_ => panic!("unexpected response"),
}
}
#[test]
fn range_request_decodes_wire_fields_as_u32() {
let tmp = TmpDir::new("decode");
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();
}
#[test]
fn failed_recopy_keeps_the_current_list() {
let tmp = TmpDir::new("failed_recopy");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let missing = tmp.join("missing.bin");
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let pdu = get_file_list_pdu(1);
assert!(sync_files(&[path_str(&missing)]).is_err());
assert_eq!(get_file_list_pdu(1), pdu);
clear_files();
}
fn file_index(path: &PathBuf) -> i32 {
let files = CLIP_FILES.lock();
files
.file_list
.iter()
.position(|f| &f.path == path)
.unwrap() as i32
}
// Replaces `path` the way editors save: write aside, then rename over it.
fn replace_atomically(path: &PathBuf, data: &[u8]) {
let aside = path.with_extension("new");
fs::write(&aside, data).unwrap();
fs::rename(&aside, path).unwrap();
}
#[test]
fn retired_list_closes_only_files_not_being_read() {
let tmp = TmpDir::new("retired_handles");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAABBBB").unwrap();
let next = tmp.join("next.bin");
fs::write(&next, b"CCCCDDDD").unwrap();
let other = tmp.join("other.bin");
fs::write(&other, b"EEEEEEEE").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first), path_str(&next)]).unwrap();
let id = file_list_id(&get_file_list_pdu(1));
let (first_idx, next_idx) = (file_index(&first), file_index(&next));
let read =
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
// Leaves `first` open at offset 4, and preloads `next`.
assert_eq!(read(first_idx, 0), b"AAAA");
sync_files(&[path_str(&other)]).unwrap();
{
let retired = RETIRED_CLIP_FILES.lock();
let open = |idx: i32| retired[0].file_list[idx as usize].handle.is_some();
assert!(open(first_idx));
assert!(!open(next_idx));
}
assert_eq!(read(first_idx, 4), b"BBBB");
assert_eq!(read(next_idx, 0), b"CCCC");
clear_files();
}
#[test]
fn files_being_read_keep_their_content_when_their_paths_are_replaced() {
let tmp = TmpDir::new("replaced_paths");
let first = tmp.join("first.bin");
fs::write(&first, b"1111aaaa").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"2222bbbb").unwrap();
let other = tmp.join("other.bin");
fs::write(&other, b"EEEEEEEE").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
let id = file_list_id(&get_file_list_pdu(1));
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
let read =
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
// Two files part-way through at once.
assert_eq!(read(first_idx, 0), b"1111");
assert_eq!(read(second_idx, 0), b"2222");
sync_files(&[path_str(&other)]).unwrap();
replace_atomically(&first, b"3333cccc");
replace_atomically(&second, b"4444dddd");
assert_eq!(read(first_idx, 4), b"aaaa");
assert_eq!(read(second_idx, 4), b"bbbb");
clear_files();
}
#[test]
fn same_file_metadata_in_another_folder_is_another_list() {
let tmp = TmpDir::new("same_metadata");
let (dir_a, dir_b) = (tmp.join("a"), tmp.join("b"));
fs::create_dir_all(&dir_a).unwrap();
fs::create_dir_all(&dir_b).unwrap();
let (first, second) = (dir_a.join("report.bin"), dir_b.join("report.bin"));
fs::write(&first, b"AAAAAAAA").unwrap();
fs::write(&second, b"BBBBBBBB").unwrap();
// Same name, size and mtime: the descriptors differ only by the nonce.
let mtime = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
for path in [&first, &second] {
fs::File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(mtime)
.unwrap();
}
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first)]).unwrap();
let first_id = file_list_id(&get_file_list_pdu(1));
let idx = CLIP_FILES.lock().first_file_index as i32;
sync_files(&[path_str(&second)]).unwrap();
let second_id = file_list_id(&get_file_list_pdu(1));
assert_ne!(first_id, second_id);
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
assert_eq!(read(first_id), b"AAAA");
assert_eq!(read(second_id), b"BBBB");
clear_files();
}
#[test]
fn a_retired_list_refuses_a_file_replaced_before_its_read() {
let tmp = TmpDir::new("replaced_unread");
let first = tmp.join("first.bin");
fs::write(&first, b"AAAAAAAA").unwrap();
let second = tmp.join("second.bin");
fs::write(&second, b"BBBBBBBB").unwrap();
let other = tmp.join("other.bin");
fs::write(&other, b"EEEEEEEE").unwrap();
let _guard = lock_clip_files();
clear_files();
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
let id = file_list_id(&get_file_list_pdu(1));
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
let read = |idx, offset| read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id));
assert_eq!(range_data(read(first_idx, 0)), b"AAAA");
// Retiring closes `second`, which has not been read yet; it is then replaced.
sync_files(&[path_str(&other)]).unwrap();
replace_atomically(&second, b"CCCCCCCCCC");
assert!(matches!(
read(second_idx, 0).last(),
Some(Err(CliprdrError::InvalidRequest { .. }))
));
// The file part-way through is unaffected.
assert_eq!(range_data(read(first_idx, 4)), b"AAAA");
clear_files();
}
fn list_files(selection: &[&PathBuf]) -> ClipFiles {
let files: Vec<String> = selection.iter().map(|p| path_str(p)).collect();
let mut clip = ClipFiles::default();
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 an_unreadable_next_file_fails_only_its_own_requests() {
use std::os::unix::fs::PermissionsExt;
let tmp = TmpDir::new("next_unreadable");
let (first, second) = (tmp.join("first.bin"), tmp.join("second.bin"));
fs::write(&first, b"AAAAAAAA").unwrap();
fs::write(&second, b"BBBBBBBB").unwrap();
let mut clip = list_files(&[&first, &second]);
fs::set_permissions(&second, fs::Permissions::from_mode(0o000)).unwrap();
// Root opens it regardless of its mode.
if fs::File::open(&second).is_ok() {
return;
}
assert_only_its_own_requests_fail(&mut clip, &second);
}
#[test]
fn the_next_file_is_preloaded_past_a_directory() {
let tmp = TmpDir::new("next_preloaded");
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;
+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
@@ -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.8). 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"
+659 -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).
@@ -101,6 +370,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 +413,11 @@ impl DrmReader {
return None;
}
Some(DrmReader {
last_provenance: -1,
lib,
ctx,
buf: Vec::new(),
last_plane_rotation: None,
})
}
@@ -160,6 +441,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 +536,23 @@ 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
}
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)
}
/// 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 +584,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 +663,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 +679,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
@@ -475,3 +772,333 @@ impl Drop for DrmReader {
}
}
}
#[cfg(test)]
mod hotspot_provenance_tests {
use super::{cursor_id, hot_measured_from, provenance_code, provenance_is_news};
/// The log this makes observable is one line per CHANGE, not one per cursor read. A cursor is
/// read far more often than its provenance changes, and a per-sample line here would be the
/// same defect libdrmtap already had once.
#[test]
fn provenance_is_logged_once_and_then_only_on_a_change() {
let (none, guessed, measured) = (
provenance_code(None),
provenance_code(Some(false)),
provenance_code(Some(true)),
);
assert_ne!(none, guessed);
assert_ne!(guessed, measured);
assert_ne!(none, measured);
// First sample of a run: -1 is the unset sentinel, so anything is news.
assert!(provenance_is_news(-1, measured));
// The same state again is not.
assert!(!provenance_is_news(measured, measured));
assert!(!provenance_is_news(guessed, guessed));
// A real transition is.
assert!(provenance_is_news(guessed, measured));
assert!(provenance_is_news(measured, none));
}
/// The dedup key has to move when the provenance does, or the consumer is never told that the
/// same picture now means something different. This is the transition that produces it: the
/// properties become readable, the driver's answer is the corner, and the bitmap is unchanged.
#[test]
fn provenance_changes_the_cursor_identity() {
let guessed = cursor_id(0xabc, 24, 24, 0, 0, false);
let measured = cursor_id(0xabc, 24, 24, 0, 0, true);
assert_ne!(
guessed, measured,
"same pixels, same (0, 0), different meaning: the producer must not dedupe this away"
);
// And the pre-existing parts still count, so this did not trade one blind spot for another.
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 32, 24, 0, 0, true));
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 24, 24, 1, 0, true));
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xdef, 24, 24, 0, 0, true));
}
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
/// 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));
}
/// And the mirror: when the library says it was NOT measured, that is the answer even if the
/// coordinates happen to be non-zero. The old test would have trusted them.
#[test]
fn the_librarys_no_beats_the_coordinates() {
assert!(!hot_measured_from(Some(false), 12, 11));
assert!(!hot_measured_from(Some(false), 0, 0));
}
/// No answer available: either the symbol is absent (a library older than 0.5.6) or nothing
/// recorded one for this sample (a cursor read through an older privileged helper). Neither
/// is "it was a guess", so the pre-existing behaviour is kept rather than resolved either way
/// -- an older deployed .so must keep behaving as it used to.
#[test]
fn without_an_answer_the_old_heuristic_stands() {
assert!(!hot_measured_from(None, 0, 0));
assert!(hot_measured_from(None, 12, 11));
assert!(hot_measured_from(None, 0, 5));
}
}
#[cfg(test)]
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));
}
/// Each axis is decided by its OWN mirror. This shape is symmetric left-to-right and not
/// top-to-bottom, which is the single-direction resize family: the click point is centred
/// across the axis that mirrors and stays at the edge on the axis that does not.
#[test]
fn one_symmetric_axis_centres_that_axis_only() {
let (px, w, h) = sprite(&[
"....#....",
"...###...",
"..#####..",
".#######.",
"....#....",
"....#....",
"....#....",
"....#....",
"....#....",
]);
assert_eq!(infer_hotspot(&px, w, h), (4, 0));
}
/// A two-headed DIAGONAL arrow mirrors onto the other diagonal about either axis alone, so
/// neither axis reads as symmetric - and it is still a shape with no tip. The half turn is
/// what catches it.
#[test]
fn a_diagonal_two_headed_arrow_is_held_by_its_middle_too() {
let (px, w, h) = sprite(&[
"###......",
"##.......",
"#.#......",
"...#.....",
"....#....",
".....#...",
"......#.#",
".......##",
"......###",
]);
let (hx, hy) = infer_hotspot(&px, w, h);
assert_eq!((hx, hy), (4, 4), "a half turn maps this shape onto itself");
}
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
/// 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));
}
/// A corner resize cursor is a bracket hugging one corner, and it mirrors onto itself about a
/// DIAGONAL rather than about either axis, so neither per-axis test sees it. The click point
/// is the inner corner of the bracket, which is the heavy end on both axes.
///
/// A real one's box is usually not square, and a diagonal reflection only lines up inside a
/// square, so which corner of that square the box is placed against decides the answer:
/// `ne-resize` scores 0.62 anchored one way and 0.98 the other, and `nw-resize` is the
/// reverse. Both anchorings are therefore tried. That case cannot be built as a small
/// picture - a non-square box can never be exactly diagonal-symmetric - so it is covered by
/// the theme corpus instead, where dropping the second anchoring sends `ne-resize` back past
/// master.
#[test]
fn a_corner_bracket_is_held_by_its_inner_corner() {
let (px, w, h) = sprite(&[
".....##", ".....##", ".....##", ".....##", ".....##", "#######", "#######",
]);
assert_eq!(infer_hotspot(&px, w, h), (6, 6));
}
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
/// 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));
}
/// Nothing opaque is not a shape, and must not read as a box at the origin with a hotspot in
/// the middle of it.
#[test]
fn a_blank_sprite_has_no_hotspot_to_guess() {
let (px, w, h) = sprite(&["...", "...", "..."]);
assert_eq!(infer_hotspot(&px, w, h), (0, 0));
}
}
/// 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::*;
use std::os::fd::AsRawFd;
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
#[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);
}
// What the plane answers whenever it is asked. The fake release turns it, the way a compositor
// may once the frame is out, so a read taken after the release or outside the grab sees 0x1.
static PLANE: AtomicU32 = AtomicU32::new(0x1);
static FD: AtomicI32 = AtomicI32::new(-1);
static PIXELS: [u8; 16] = [0; 16];
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, rotation: *mut u32) -> c_int {
*rotation = PLANE.load(Ordering::SeqCst);
0
}
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {
PLANE.store(0x1, Ordering::SeqCst);
}
unsafe extern "C" fn grab_mapped(_: *mut drmtap_ctx, f: *mut drmtap_frame_info) -> c_int {
(*f).data = PIXELS.as_ptr() as *mut _;
(*f).width = 2;
(*f).height = 2;
(*f).stride = 8;
(*f).format = DRM_FORMAT_XRGB8888;
0
}
unsafe extern "C" fn grab_desc(
_: *mut drmtap_ctx,
d: *mut drmtap_dmabuf_desc,
_: *mut drmtap_frame_info,
) -> c_int {
(*d).dma_buf_fd = FD.load(Ordering::SeqCst);
(*d).width = 2;
(*d).height = 2;
(*d).num_planes = 1;
(*d).pitches[0] = 8;
0
}
#[test]
fn a_frame_keeps_the_rotation_its_plane_had_when_it_was_grabbed() {
let lib: &'static DrmtapLib = Box::leak(Box::new(DrmtapLib::fake(
grab_mapped,
frame_release,
grab_desc,
plane_rotation,
)));
let mut r = DrmReader {
lib,
ctx: std::ptr::null_mut(),
buf: Vec::new(),
last_provenance: -1,
last_plane_rotation: None,
};
PLANE.store(0x4, Ordering::SeqCst);
r.grab().expect("the fake grab succeeds");
assert_eq!(r.plane_rotation(), Some(0x4), "cpu grab");
let (fd, _peer) = std::os::unix::net::UnixStream::pair().unwrap();
FD.store(fd.as_raw_fd(), Ordering::SeqCst);
PLANE.store(0x8, Ordering::SeqCst);
r.grab_desc().expect("the fake export succeeds");
assert_eq!(r.plane_rotation(), Some(0x8), "dma-buf export");
}
}
+97
View File
@@ -127,6 +127,12 @@ type FnGrabMapped = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_frame_info
type FnFrameRelease = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_frame_info);
type FnGetCursor = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_cursor_info) -> c_int;
type FnCursorRelease = unsafe extern "C" fn(*mut drmtap_ctx, *mut drmtap_cursor_info);
/// `drmtap_cursor_hotspot_valid`, added in libdrmtap 0.5.6. Answers, for the sample in hand,
/// whether `hot_x`/`hot_y` were read from the driver's HOTSPOT_X/Y plane properties: 0 with
/// `*valid` set, `-EINVAL` on a null argument, and `-ENOTSUP` when nothing recorded an answer,
/// which is what a cursor read through an older privileged helper produces.
type FnCursorHotspotValid =
unsafe extern "C" fn(*const drmtap_cursor_info, *mut c_int) -> c_int;
// Split-capture entry points (libdrmtap >= 0.4.10), required: `grab_desc` runs on the privileged
// export side, `open_render`/`convert_dmabuf` on the unprivileged converter side.
type FnGrabDesc =
@@ -134,6 +140,12 @@ type FnGrabDesc =
type FnOpenRender = unsafe extern "C" fn(*const c_char) -> *mut drmtap_ctx;
// libdrmtap >= 0.4.15; returns a ctx-owned string, or NULL if it has none.
type FnRenderNode = unsafe extern "C" fn(*mut drmtap_ctx) -> *const c_char;
/// `drmtap_plane_rotation`, added in libdrmtap 0.5.8: the DRM `rotation` bitmask the primary
/// plane scans out with, read now (0x1 = 0, 0x2 = 90, 0x4 = 180, 0x8 = 270, plus 0x10/0x20 for
/// a reflection). 0 with `*rotation` set; `-ENOTSUP` when the plane has no such property, which
/// means the compositor can only have rotated in software; `-ENOENT` with no plane bound;
/// `-EINVAL` on a null argument.
type FnPlaneRotation = unsafe extern "C" fn(*mut drmtap_ctx, *mut u32) -> c_int;
type FnConvertDmabuf =
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
@@ -148,13 +160,72 @@ pub struct DrmtapLib {
pub frame_release: FnFrameRelease,
pub get_cursor: FnGetCursor,
pub cursor_release: FnCursorRelease,
/// Optional: it only exists from libdrmtap 0.5.6. Absent means the library cannot say where a
/// hotspot came from, NOT that it was a guess; `drm_reader` keeps the old heuristic for that
/// case and nothing else changes.
pub cursor_hotspot_valid: Option<FnCursorHotspotValid>,
pub grab_desc: FnGrabDesc,
pub open_render: FnOpenRender,
pub convert_dmabuf: FnConvertDmabuf,
pub render_node: Option<FnRenderNode>,
/// Optional: it only exists from libdrmtap 0.5.8. Absent means the library cannot say whether
/// the plane rotated the scanout, and the consumer keeps the pre-0.5.8 rule for that case.
pub plane_rotation: Option<FnPlaneRotation>,
pub version: (c_int, c_int, c_int),
}
/// A library whose capture entry points are the given fakes and whose others do nothing, for the
/// tests of the reader.
#[cfg(test)]
impl DrmtapLib {
pub(crate) fn fake(
grab_mapped: FnGrabMapped,
frame_release: FnFrameRelease,
grab_desc: FnGrabDesc,
plane_rotation: FnPlaneRotation,
) -> Self {
unsafe extern "C" fn open(_: *const drmtap_config) -> *mut drmtap_ctx {
std::ptr::null_mut()
}
unsafe extern "C" fn close(_: *mut drmtap_ctx) {}
unsafe extern "C" fn list_displays(_: *mut drmtap_ctx, _: *mut drmtap_display, _: c_int) -> c_int {
0
}
unsafe extern "C" fn get_cursor(_: *mut drmtap_ctx, _: *mut drmtap_cursor_info) -> c_int {
-1
}
unsafe extern "C" fn cursor_release(_: *mut drmtap_ctx, _: *mut drmtap_cursor_info) {}
unsafe extern "C" fn open_render(_: *const c_char) -> *mut drmtap_ctx {
std::ptr::null_mut()
}
unsafe extern "C" fn convert_dmabuf(
_: *mut drmtap_ctx,
_: *const drmtap_dmabuf_desc,
_: *mut drmtap_frame_info,
) -> c_int {
-1
}
DrmtapLib {
_lib: hbb_common::libloading::os::unix::Library::this().into(),
open,
close,
list_displays,
list_devices: None,
grab_mapped,
frame_release,
get_cursor,
cursor_release,
cursor_hotspot_valid: None,
grab_desc,
open_render,
convert_dmabuf,
render_node: None,
plane_rotation: Some(plane_rotation),
version: (0, 5, 8),
}
}
}
// SAFETY: the resolved fn pointers are plain C entry points with no interior mutability;
// libdrmtap contexts are used single-threaded by the caller. The Library handle is never moved out.
unsafe impl Send for DrmtapLib {}
@@ -278,6 +349,10 @@ impl DrmtapLib {
};
let render_node: Option<FnRenderNode> =
lib.get(b"drmtap_render_node").ok().map(|s| *s);
let cursor_hotspot_valid: Option<FnCursorHotspotValid> =
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
let plane_rotation: Option<FnPlaneRotation> =
lib.get(b"drmtap_plane_rotation").ok().map(|s| *s);
// Log the load only now that every required symbol resolved: this fn still returns None on a missing one.
let loaded_from = real
.as_ref()
@@ -309,6 +384,26 @@ impl DrmtapLib {
points at and remove any leftover libdrmtap.so.0* beside it. {effect}"
);
}
// Same shape as the check above, and for the same reason: a library that REPORTS a
// version which exports the symbol and then does not have it is a stale or
// hand-substituted object, and saying so beats silently taking the legacy path.
if (minor, patch) >= (5, 6) && cursor_hotspot_valid.is_none() {
log::warn!(
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
drmtap_cursor_hotspot_valid: it is a stale or pre-release build. Check what \
the soname symlink points at. Cursor hotspot provenance falls back to \
guessing from the coordinates, which cannot tell an absent HOTSPOT_X/Y from \
a driver that really puts the hotspot at (0, 0)."
);
}
if (minor, patch) >= (5, 8) && plane_rotation.is_none() {
log::warn!(
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
drmtap_plane_rotation: it is a stale or pre-release build. Check what the \
soname symlink points at. A 180-degree output rotated by the compositor in \
software will be captured upside down."
);
}
Some(DrmtapLib {
_lib: lib,
open,
@@ -319,10 +414,12 @@ impl DrmtapLib {
frame_release,
get_cursor,
cursor_release,
cursor_hotspot_valid,
grab_desc,
open_render,
convert_dmabuf,
render_node,
plane_rotation,
version: (major, minor, patch),
})
}
+5 -2
View File
@@ -118,12 +118,15 @@ impl EncoderApi for VRamEncoder {
});
}
if frames.len() > 0 {
// This kind of problem is occurred after a period of time when using AMD encoding,
// This kind of problem is occurred after a period of time when using the AMD SDK,
// the encoding length is fixed at about 40, and the picture is still
const MIN_BAD_LEN: usize = 100;
const MAX_BAD_COUNTER: usize = 30;
let this_frame_len = frames[0].data.len();
if this_frame_len < MIN_BAD_LEN && this_frame_len == self.last_frame_len {
if self.ctx.f.driver == Driver::AMF
&& this_frame_len < MIN_BAD_LEN
&& this_frame_len == self.last_frame_len
{
self.same_bad_len_counter += 1;
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
log::info!(
+629
View File
@@ -0,0 +1,629 @@
//! HDR desktop -> SDR normalization for Desktop Duplication frames.
//!
//! With HDR enabled Windows composes the desktop as linear scRGB in
//! R16G16B16A16_FLOAT, and SDR "white" sits at the user's SDR content
//! brightness (DISPLAYCONFIG_SDR_WHITE_LEVEL) rather than at 1.0. The legacy
//! DuplicateOutput converts that to BGRA8 by clipping, which is the washed-out
//! picture reported for HDR hosts. This pass divides by the SDR white level,
//! clamps, and applies the sRGB transfer, so SDR content comes out exactly as
//! it would from an SDR desktop.
//!
//! It is a normalization, not a tone map: anything brighter than SDR white
//! (HDR video, HDR games) clips to white on the SDR viewer, where the local
//! HDR display would show it brighter than white. A roll-off would have to
//! move SDR white below 1.0 to make headroom, trading the accuracy of the SDR
//! content this pass exists for, so it is deliberately not done.
//!
//! Windows 11 22H2 also composes Advanced Color SDR (WCG) desktops in FP16,
//! but there 1.0 is the display's reference white rather than 80 nits and no
//! SDR white level applies. IDXGIOutput6 tells the two apart, and for a
//! non-HDR output the pass only applies the scRGB -> sRGB transfer.
//!
//! The conversion is automatic and stays on the controlled side on purpose:
//! the controller renders through Flutter external textures, which are 8-bit
//! on every desktop platform, so there is nothing to gain from sending HDR.
//! Real HDR pass-through, if the renderer ever supports it, should follow the
//! Sunshine/Moonlight pattern instead: an `hdr` capability bit advertised by
//! the controller behind an explicit user toggle, negotiated like i444.
use super::ComPtr;
use hbb_common::log;
use std::{
io, mem, ptr,
sync::{atomic::AtomicBool, OnceLock},
time::{Duration, Instant},
};
use winapi::{
ctypes::c_void,
shared::{
basetsd::SIZE_T,
dxgi::{CreateDXGIFactory1, IDXGIFactory1, IID_IDXGIFactory1, DXGI_OUTPUT_DESC},
dxgi1_2::IDXGIOutput1,
dxgi1_6::{IDXGIOutput6, IID_IDXGIOutput6, DXGI_OUTPUT_DESC1},
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
dxgitype::{DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_SAMPLE_DESC},
minwindef::{FALSE, LPCVOID, UINT, ULONG},
ntdef::{LONG, LPCSTR, WCHAR},
winerror::S_OK,
},
um::{
d3d11::*,
d3dcommon::{ID3DBlob, ID3DInclude, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D_SHADER_MACRO},
libloaderapi::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32},
unknwnbase::IUnknown,
wingdi::{
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
DISPLAYCONFIG_TOPOLOGY_ID,
},
winnt::HRESULT,
},
};
/// Set once the tone-map can never work in this process (no d3dcompiler, the
/// shaders do not compile). Capturers then stop asking DXGI for float frames.
/// Device-specific failures are not recorded here; the capturer that hit one
/// re-duplicates without the tone-map on its own.
pub static UNAVAILABLE: AtomicBool = AtomicBool::new(false);
/// Failures no capturer on this machine can recover from, as opposed to
/// device-specific ones that a recreated capturer may not hit again.
pub fn is_permanent(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::Unsupported
}
const VS_SRC: &str = "\
float4 main(uint id : SV_VertexID) : SV_Position {
float2 uv = float2((id << 1) & 2, id & 2);
return float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);
}";
const PS_SRC: &str = "\
Texture2D<float4> src : register(t0);
cbuffer Params : register(b0) { float inv_sdr_white; float3 pad; };
float4 main(float4 pos : SV_Position) : SV_Target {
float3 lin = saturate(src.Load(int3(pos.xy, 0)).rgb * inv_sdr_white);
float3 lo = lin * 12.92;
float3 hi = 1.055 * pow(lin, 1.0 / 2.4) - 0.055;
return float4(lerp(hi, lo, step(lin, 0.0031308)), 1.0);
}";
const OUTPUT_STATE_REFRESH: Duration = Duration::from_secs(1);
pub struct HdrToSdr {
device: ComPtr<ID3D11Device>,
context: ComPtr<ID3D11DeviceContext>,
vs: ComPtr<ID3D11VertexShader>,
ps: ComPtr<ID3D11PixelShader>,
params: ComPtr<ID3D11Buffer>,
target: ComPtr<ID3D11Texture2D>,
rtv: ComPtr<ID3D11RenderTargetView>,
srv: ComPtr<ID3D11ShaderResourceView>,
// Texture `srv` was created for. The view keeps it alive, so the address
// cannot be recycled behind our back.
srv_source: *mut ID3D11Texture2D,
width: u32,
height: u32,
device_name: [WCHAR; 32],
// Advanced Color state is read from `output6`, which is re-enumerated from a
// fresh factory whenever `factory` stops being current.
factory: ComPtr<IDXGIFactory1>,
output6: ComPtr<IDXGIOutput6>,
is_hdr: bool,
// DISPLAYCONFIG units (1000 == 80 nits == scRGB 1.0). `None` when it could
// not be read, in which case 80 nits is assumed until it can.
sdr_white_level: Option<u32>,
queried_at: Instant,
}
impl HdrToSdr {
pub fn new(
device: *mut ID3D11Device,
context: *mut ID3D11DeviceContext,
output: *mut IDXGIOutput1,
device_name: &[WCHAR; 32],
) -> io::Result<Self> {
unsafe {
if device.is_null() || context.is_null() {
return Err(other("no d3d11 device"));
}
(*device).AddRef();
let device = ComPtr(device);
(*context).AddRef();
let context = ComPtr(context);
let compile = load_d3d_compile()?;
let vs_code = compile_shader(compile, VS_SRC, b"vs_4_0\0")?;
let ps_code = compile_shader(compile, PS_SRC, b"ps_4_0\0")?;
let mut vs = ptr::null_mut();
check(
(*device.0).CreateVertexShader(
(*vs_code.0).GetBufferPointer(),
(*vs_code.0).GetBufferSize(),
ptr::null_mut(),
&mut vs,
),
"CreateVertexShader",
)?;
let vs = ComPtr(vs);
let mut ps = ptr::null_mut();
check(
(*device.0).CreatePixelShader(
(*ps_code.0).GetBufferPointer(),
(*ps_code.0).GetBufferSize(),
ptr::null_mut(),
&mut ps,
),
"CreatePixelShader",
)?;
let ps = ComPtr(ps);
// Not found leaves the factory null, so the first refresh enumerates
// again instead of trusting the capturer's possibly stale output.
let (factory, mut output6) = enumerate_output6(device_name);
if output6.is_null() {
output6 = query_output6(output as *mut IUnknown);
}
// Float frames are only requested where IDXGIOutput6 exists, so an
// unreadable description still comes from an HDR-capable stack.
let is_hdr = output_is_hdr(output6.0).unwrap_or(true);
let sdr_white_level = if is_hdr {
query_sdr_white_level(device_name)
} else {
None
};
if is_hdr && sdr_white_level.is_none() {
log::warn!(
"HDR output but the SDR white level cannot be read (needs Windows 10 1709+), \
assuming 80 nits until it can"
);
}
let init = params_data(sdr_white_level);
let desc = D3D11_BUFFER_DESC {
ByteWidth: mem::size_of_val(&init) as _,
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_CONSTANT_BUFFER,
CPUAccessFlags: 0,
MiscFlags: 0,
StructureByteStride: 0,
};
let data = D3D11_SUBRESOURCE_DATA {
pSysMem: init.as_ptr() as _,
SysMemPitch: 0,
SysMemSlicePitch: 0,
};
let mut params = ptr::null_mut();
check(
(*device.0).CreateBuffer(&desc, &data, &mut params),
"CreateBuffer",
)?;
let params = ComPtr(params);
log::info!(
"scRGB desktop conversion ready, hdr {is_hdr}, sdr white level {sdr_white_level:?}"
);
Ok(Self {
device,
context,
vs,
ps,
params,
target: ComPtr(ptr::null_mut()),
rtv: ComPtr(ptr::null_mut()),
srv: ComPtr(ptr::null_mut()),
srv_source: ptr::null_mut(),
width: 0,
height: 0,
device_name: *device_name,
factory,
output6,
is_hdr,
sdr_white_level,
queried_at: Instant::now(),
})
}
}
/// Renders `source` (R16G16B16A16_FLOAT) into an owned B8G8R8A8_UNORM
/// texture of the same size and returns it. The texture stays valid until
/// the next call.
pub fn convert(
&mut self,
source: *mut ID3D11Texture2D,
desc: &D3D11_TEXTURE2D_DESC,
) -> io::Result<*mut ID3D11Texture2D> {
unsafe {
self.refresh_output_state();
self.ensure_target(desc.Width, desc.Height)?;
self.ensure_source_view(source)?;
let ctx = self.context.0;
let rtv = self.rtv.0;
let srv = self.srv.0;
let params = self.params.0;
let viewport = D3D11_VIEWPORT {
TopLeftX: 0.0,
TopLeftY: 0.0,
Width: self.width as f32,
Height: self.height as f32,
MinDepth: 0.0,
MaxDepth: 1.0,
};
(*ctx).OMSetRenderTargets(1, &rtv, ptr::null_mut());
(*ctx).OMSetBlendState(ptr::null_mut(), &[0.0; 4], 0xffff_ffff);
(*ctx).OMSetDepthStencilState(ptr::null_mut(), 0);
(*ctx).RSSetState(ptr::null_mut());
(*ctx).RSSetViewports(1, &viewport);
(*ctx).IASetInputLayout(ptr::null_mut());
(*ctx).IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
(*ctx).VSSetShader(self.vs.0, ptr::null(), 0);
(*ctx).PSSetShader(self.ps.0, ptr::null(), 0);
(*ctx).PSSetConstantBuffers(0, 1, &params);
(*ctx).PSSetShaderResources(0, 1, &srv);
(*ctx).Draw(3, 0);
// Unbind so the next frame's copy and the encoder never see the
// target as a live render target or the desktop image as a bound
// shader input.
let no_srv: *mut ID3D11ShaderResourceView = ptr::null_mut();
(*ctx).PSSetShaderResources(0, 1, &no_srv);
(*ctx).OMSetRenderTargets(0, ptr::null(), ptr::null_mut());
Ok(self.target.0)
}
}
unsafe fn ensure_target(&mut self, width: u32, height: u32) -> io::Result<()> {
if !self.target.is_null() && self.width == width && self.height == height {
return Ok(());
}
let desc = D3D11_TEXTURE2D_DESC {
Width: width,
Height: height,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
CPUAccessFlags: 0,
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
};
let mut target = ptr::null_mut();
check(
(*self.device.0).CreateTexture2D(&desc, ptr::null(), &mut target),
"CreateTexture2D",
)?;
let target = ComPtr(target);
let mut rtv = ptr::null_mut();
check(
(*self.device.0).CreateRenderTargetView(target.0 as *mut _, ptr::null(), &mut rtv),
"CreateRenderTargetView",
)?;
self.rtv = ComPtr(rtv);
self.target = target;
self.width = width;
self.height = height;
Ok(())
}
unsafe fn ensure_source_view(&mut self, source: *mut ID3D11Texture2D) -> io::Result<()> {
if !self.srv.is_null() && self.srv_source == source {
return Ok(());
}
let mut srv = ptr::null_mut();
check(
(*self.device.0).CreateShaderResourceView(source as *mut _, ptr::null(), &mut srv),
"CreateShaderResourceView",
)?;
self.srv = ComPtr(srv);
self.srv_source = source;
Ok(())
}
// Advanced Color state is dynamic: HDR can be switched on or off, or a WCG
// desktop can turn into an HDR one, without the duplication being lost. An
// output's description is a snapshot, so once the factory is no longer
// current a new factory and output are needed to see the new state, as the
// GetDesc1 docs require.
unsafe fn refresh_output_state(&mut self) {
if self.queried_at.elapsed() < OUTPUT_STATE_REFRESH {
return;
}
self.queried_at = Instant::now();
if self.factory.is_null() || (*self.factory.0).IsCurrent() == FALSE {
let (factory, output6) = enumerate_output6(&self.device_name);
if !output6.is_null() {
self.factory = factory;
self.output6 = output6;
} else {
// Keep reading the old output, but enumerate again next time.
self.factory = ComPtr(ptr::null_mut());
}
}
let is_hdr = output_is_hdr(self.output6.0).unwrap_or(self.is_hdr);
let level = if is_hdr {
query_sdr_white_level(&self.device_name)
} else {
None
};
// A transiently unreadable level keeps the last known one.
if is_hdr == self.is_hdr && (level.is_none() || level == self.sdr_white_level) {
return;
}
log::info!(
"output changed: hdr {} -> {is_hdr}, sdr white level {:?} -> {level:?}",
self.is_hdr,
self.sdr_white_level
);
if is_hdr && level.is_none() {
log::warn!(
"HDR output but the SDR white level cannot be read, assuming 80 nits until it can"
);
}
self.is_hdr = is_hdr;
self.sdr_white_level = level;
let data = params_data(level);
(*self.context.0).UpdateSubresource(
self.params.0 as *mut _,
0,
ptr::null(),
data.as_ptr() as _,
0,
0,
);
}
}
// `None` is either a non-HDR (WCG) output, where 1.0 already is the display's
// reference white, or an HDR output whose level is unknown; both use 1.0.
fn params_data(sdr_white_level: Option<u32>) -> [f32; 4] {
[
1000.0 / sdr_white_level.unwrap_or(1000) as f32,
0.0,
0.0,
0.0,
]
}
// FP16 desktop composition means either HDR (scene-referred, 1.0 == 80 nits)
// or, since Windows 11 22H2, Advanced Color SDR (display-referred), and only
// IDXGIOutput6 (Windows 10 1703) tells them apart. `None` when it cannot be
// read right now.
unsafe fn output_is_hdr(output6: *mut IDXGIOutput6) -> Option<bool> {
if output6.is_null() {
return None;
}
let mut desc: DXGI_OUTPUT_DESC1 = mem::zeroed();
if (*output6).GetDesc1(&mut desc) != S_OK {
return None;
}
Some(desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020)
}
unsafe fn query_output6(object: *mut IUnknown) -> ComPtr<IDXGIOutput6> {
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
if !object.is_null() {
(*object).QueryInterface(
&IID_IDXGIOutput6,
&mut output6 as *mut *mut _ as *mut *mut _,
);
}
ComPtr(output6)
}
// A fresh factory sees the current display configuration; the output is found
// by its GDI name because the outputs of a stale factory keep stale descriptions.
// Returns both or neither: a non-null factory guarantees the output came from
// its topology, so a caller that sees a null factory knows to enumerate again.
unsafe fn enumerate_output6(
device_name: &[WCHAR; 32],
) -> (ComPtr<IDXGIFactory1>, ComPtr<IDXGIOutput6>) {
let mut factory: *mut c_void = ptr::null_mut();
if CreateDXGIFactory1(&IID_IDXGIFactory1, &mut factory) != S_OK {
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
}
let factory = ComPtr(factory as *mut IDXGIFactory1);
let mut adapter_index = 0;
loop {
let mut adapter = ptr::null_mut();
if (*factory.0).EnumAdapters1(adapter_index, &mut adapter) != S_OK {
break;
}
let adapter = ComPtr(adapter);
adapter_index += 1;
let mut output_index = 0;
loop {
let mut output = ptr::null_mut();
if (*adapter.0).EnumOutputs(output_index, &mut output) != S_OK {
break;
}
let output = ComPtr(output);
output_index += 1;
let mut desc: DXGI_OUTPUT_DESC = mem::zeroed();
if (*output.0).GetDesc(&mut desc) == S_OK && wide_eq(&desc.DeviceName, device_name) {
let output6 = query_output6(output.0 as *mut IUnknown);
if output6.is_null() {
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
}
return (factory, output6);
}
}
}
(ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()))
}
fn other(msg: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::Other, msg.into())
}
fn check(hr: HRESULT, what: &str) -> io::Result<()> {
if hr == S_OK {
Ok(())
} else {
Err(other(format!("{what} failed: {hr:#x}")))
}
}
// D3DCompile(pSrcData, SrcDataSize, pSourceName, pDefines, pInclude,
// pEntrypoint, pTarget, Flags1, Flags2, ppCode, ppErrorMsgs)
type D3DCompileFn = unsafe extern "system" fn(
LPCVOID,
SIZE_T,
LPCSTR,
*const D3D_SHADER_MACRO,
*mut ID3DInclude,
LPCSTR,
LPCSTR,
UINT,
UINT,
*mut *mut ID3DBlob,
*mut *mut ID3DBlob,
) -> HRESULT;
static D3D_COMPILE: OnceLock<Result<D3DCompileFn, String>> = OnceLock::new();
// Loaded once per process and kept: the compiler DLL is only needed on HDR
// desktops, and an import-time link would make every install depend on it.
fn load_d3d_compile() -> io::Result<D3DCompileFn> {
D3D_COMPILE
.get_or_init(|| unsafe { find_d3d_compile() })
.clone()
.map_err(|e| io::Error::new(io::ErrorKind::Unsupported, e))
}
unsafe fn find_d3d_compile() -> Result<D3DCompileFn, String> {
let name: Vec<u16> = "d3dcompiler_47.dll\0".encode_utf16().collect();
let module = LoadLibraryExW(name.as_ptr(), ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
if module.is_null() {
return Err("d3dcompiler_47.dll not available".into());
}
let f = GetProcAddress(module, b"D3DCompile\0".as_ptr() as _);
if f.is_null() {
return Err("D3DCompile not exported".into());
}
Ok(mem::transmute::<_, D3DCompileFn>(f))
}
unsafe fn compile_shader(
compile: D3DCompileFn,
src: &str,
target: &[u8],
) -> io::Result<ComPtr<ID3DBlob>> {
let mut code = ptr::null_mut();
let mut errors = ptr::null_mut();
let hr = compile(
src.as_ptr() as _,
src.len(),
ptr::null(),
ptr::null(),
ptr::null_mut(),
b"main\0".as_ptr() as _,
target.as_ptr() as _,
0,
0,
&mut code,
&mut errors,
);
let errors = ComPtr(errors);
if hr != S_OK || code.is_null() {
let msg = if errors.is_null() {
String::new()
} else {
let bytes = std::slice::from_raw_parts(
(*errors.0).GetBufferPointer() as *const u8,
(*errors.0).GetBufferSize(),
);
String::from_utf8_lossy(bytes).into_owned()
};
if !code.is_null() {
(*(code as *mut IUnknown)).Release();
}
return Err(io::Error::new(
io::ErrorKind::Unsupported,
format!("D3DCompile failed: {hr:#x} {msg}"),
));
}
Ok(ComPtr(code))
}
const DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL: u32 = 11;
const QDC_ONLY_ACTIVE_PATHS: u32 = 2;
#[repr(C)]
#[allow(non_snake_case)]
struct DISPLAYCONFIG_SDR_WHITE_LEVEL {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER,
SDRWhiteLevel: ULONG,
}
#[link(name = "user32")]
extern "system" {
fn GetDisplayConfigBufferSizes(
flags: u32,
numPathArrayElements: *mut u32,
numModeInfoArrayElements: *mut u32,
) -> LONG;
fn QueryDisplayConfig(
flags: u32,
numPathArrayElements: *mut u32,
pathArray: *mut DISPLAYCONFIG_PATH_INFO,
numModeInfoArrayElements: *mut u32,
modeInfoArray: *mut DISPLAYCONFIG_MODE_INFO,
currentTopologyId: *mut DISPLAYCONFIG_TOPOLOGY_ID,
) -> LONG;
fn DisplayConfigGetDeviceInfo(requestPacket: *mut DISPLAYCONFIG_DEVICE_INFO_HEADER) -> LONG;
}
/// SDR white level of the output whose GDI name is `device_name`
/// (e.g. `\\.\DISPLAY1`), in DISPLAYCONFIG units (1000 == 80 nits). `None`
/// when the query fails (before Windows 10 1709) or reports 0.
fn query_sdr_white_level(device_name: &[WCHAR; 32]) -> Option<u32> {
unsafe {
let mut n_paths = 0u32;
let mut n_modes = 0u32;
if GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut n_paths, &mut n_modes) != 0 {
return None;
}
let mut paths: Vec<DISPLAYCONFIG_PATH_INFO> = vec![mem::zeroed(); n_paths as usize];
let mut modes: Vec<DISPLAYCONFIG_MODE_INFO> = vec![mem::zeroed(); n_modes as usize];
if QueryDisplayConfig(
QDC_ONLY_ACTIVE_PATHS,
&mut n_paths,
paths.as_mut_ptr(),
&mut n_modes,
modes.as_mut_ptr(),
ptr::null_mut(),
) != 0
{
return None;
}
for path in &paths[..n_paths as usize] {
let mut source: DISPLAYCONFIG_SOURCE_DEVICE_NAME = mem::zeroed();
source.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
source.header.size = mem::size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as _;
source.header.adapterId = path.sourceInfo.adapterId;
source.header.id = path.sourceInfo.id;
if DisplayConfigGetDeviceInfo(&mut source.header) != 0
|| !wide_eq(&source.viewGdiDeviceName, device_name)
{
continue;
}
let mut white: DISPLAYCONFIG_SDR_WHITE_LEVEL = mem::zeroed();
white.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
white.header.size = mem::size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as _;
white.header.adapterId = path.targetInfo.adapterId;
white.header.id = path.targetInfo.id;
if DisplayConfigGetDeviceInfo(&mut white.header) == 0 && white.SDRWhiteLevel != 0 {
return Some(white.SDRWhiteLevel);
}
}
None
}
}
fn wide_eq(a: &[WCHAR], b: &[WCHAR]) -> bool {
let end = |s: &[WCHAR]| s.iter().position(|&c| c == 0).unwrap_or(s.len());
a[..end(a)] == b[..end(b)]
}
+120 -4
View File
@@ -1,18 +1,20 @@
use std::{io, mem, ptr, slice};
pub mod gdi;
pub use gdi::CapturerGDI;
pub mod hdr;
pub mod mag;
use winapi::{
shared::{
dxgi::*,
dxgi1_2::*,
dxgi1_6::*,
dxgiformat::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT},
dxgitype::*,
minwindef::{DWORD, FALSE, TRUE, UINT},
ntdef::LONG,
windef::{HMONITOR, RECT},
winerror::*,
// dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
},
um::{
d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown, wingdi::*,
@@ -66,6 +68,7 @@ pub struct Capturer {
adapter_desc1: DXGI_ADAPTER_DESC1,
rotate: Rotate,
frame_state: FrameState,
hdr: Option<hdr::HdrToSdr>,
}
impl Capturer {
@@ -113,7 +116,7 @@ impl Capturer {
}
} else {
res = wrap_hresult(unsafe {
let hres = (*display.inner.0).DuplicateOutput(device.0 as *mut _, &mut duplication);
let hres = Self::duplicate_output(&display, device.0, &mut duplication);
if hres != S_OK {
gdi_capturer = display.create_gdi();
println!("Fallback to GDI");
@@ -169,7 +172,8 @@ impl Capturer {
device,
context,
duplication: ComPtr(duplication),
fastlane: desc.DesktopImageInSystemMemory == TRUE,
fastlane: desc.DesktopImageInSystemMemory == TRUE
&& desc.ModeDesc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT,
surface: ComPtr(ptr::null_mut()),
texture: ComPtr(ptr::null_mut()),
width: display.width() as usize,
@@ -183,9 +187,104 @@ impl Capturer {
adapter_desc1,
rotate,
frame_state: FrameState::Idle,
hdr: None,
})
}
// Asks for the float desktop that HDR mode composes so it can be tone-mapped;
// the legacy call would hand back DXGI's clipped BGRA8 conversion instead.
// Only where IDXGIOutput6 (Windows 10 1703) exists, since that is what later
// tells an HDR desktop from a WCG one; Microsoft's duplication sample gates
// the float request the same way.
unsafe fn duplicate_output(
display: &Display,
device: *mut ID3D11Device,
duplication: &mut *mut IDXGIOutputDuplication,
) -> HRESULT {
if !hdr::UNAVAILABLE.load(std::sync::atomic::Ordering::Relaxed) {
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
(*display.inner.0).QueryInterface(
&IID_IDXGIOutput6,
&mut output6 as *mut *mut _ as *mut *mut _,
);
if !output6.is_null() {
let output6 = ComPtr(output6);
let formats = [DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8A8_UNORM];
let hres = (*output6.0).DuplicateOutput1(
device as *mut _,
0,
formats.len() as UINT,
formats.as_ptr(),
duplication,
);
if hres == S_OK {
return hres;
}
hbb_common::log::warn!(
"HDR DuplicateOutput1 failed: hr={:#x}, fallback=DuplicateOutput",
hres as u32
);
}
}
(*display.inner.0).DuplicateOutput(device as *mut _, duplication)
}
unsafe fn tonemap(
&mut self,
source: *mut ID3D11Texture2D,
desc: &D3D11_TEXTURE2D_DESC,
) -> io::Result<*mut ID3D11Texture2D> {
if self.hdr.is_none() {
match hdr::HdrToSdr::new(
self.device.0,
self.context.0,
self.display.inner.0,
&self.display.desc.DeviceName,
) {
Ok(hdr) => self.hdr = Some(hdr),
Err(err) => return self.abandon_tonemap(err),
}
}
let converted = match self.hdr.as_mut() {
Some(hdr) => hdr.convert(source, desc),
None => Err(io::Error::new(io::ErrorKind::Other, "no tone-map")),
};
match converted {
Ok(texture) => Ok(texture),
Err(err) => self.abandon_tonemap(err),
}
}
// Drops the tone-map and re-duplicates the output the legacy way, so DXGI
// hands over clipped BGRA8 (the pre-HDR behaviour). If re-duplication fails,
// switch to GDI before returning. The caller sees WouldBlock and asks again.
unsafe fn abandon_tonemap<T>(&mut self, err: io::Error) -> io::Result<T> {
if hdr::is_permanent(&err) {
hdr::UNAVAILABLE.store(true, std::sync::atomic::Ordering::Relaxed);
}
hbb_common::log::error!("HDR tone-map failed, re-duplicating without it: {err}");
self.hdr = None;
if let Err(release_err) = self.release_frame() {
hbb_common::log::warn!("DXGI frame cleanup failed while disabling HDR: {release_err}");
}
self.duplication = ComPtr(ptr::null_mut());
let mut duplication = ptr::null_mut();
let result = wrap_hresult(
(*self.display.inner.0).DuplicateOutput(self.device.0 as *mut _, &mut duplication),
);
if let Err(err) = result {
if self.set_gdi() {
return Err(io::ErrorKind::WouldBlock.into());
}
return Err(err);
}
self.duplication = ComPtr(duplication);
let mut desc: DXGI_OUTDUPL_DESC = mem::zeroed();
(*duplication).GetDesc(&mut desc);
self.fastlane = desc.DesktopImageInSystemMemory == TRUE;
Err(io::ErrorKind::WouldBlock.into())
}
fn create_rotations(
device: *mut ID3D11Device,
context: *mut ID3D11DeviceContext,
@@ -339,6 +438,9 @@ impl Capturer {
}
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
if self.duplication.0.is_null() {
return Err(io::ErrorKind::AddrNotAvailable.into());
}
let mut frame = ptr::null_mut();
#[allow(invalid_value)]
let mut info = mem::MaybeUninit::uninit().assume_init();
@@ -377,6 +479,12 @@ impl Capturer {
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
(*texture.0).GetDesc(&mut texture_desc);
let mut source = texture.0;
if texture_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
source = self.tonemap(texture.0, &texture_desc)?;
(*source).GetDesc(&mut texture_desc);
}
texture_desc.Usage = D3D11_USAGE_STAGING;
texture_desc.BindFlags = 0;
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
@@ -397,7 +505,7 @@ impl Capturer {
&mut surface as *mut *mut _ as *mut *mut _,
);
(*self.context.0).CopyResource(readable.0 as *mut _, texture.0 as *mut _);
(*self.context.0).CopyResource(readable.0 as *mut _, source as *mut _);
Ok(surface)
}
@@ -505,6 +613,14 @@ impl Capturer {
let texture = ComPtr(texture);
self.texture = texture;
let mut frame_desc: D3D11_TEXTURE2D_DESC = mem::zeroed();
(*self.texture.0).GetDesc(&mut frame_desc);
if frame_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
let converted = self.tonemap(self.texture.0, &frame_desc)?;
(*converted).AddRef();
self.texture = ComPtr(converted);
}
let mut final_texture = self.texture.0 as *mut c_void;
let mut rotation = match self.display.rotation() {
DXGI_MODE_ROTATION_ROTATE90 => 90,
+31 -17
View File
@@ -1,9 +1,7 @@
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use crate::clipboard::clipboard_listener;
use crate::clipboard::clipboard_listener::{self, ClipboardEvent};
use async_trait::async_trait;
use bytes::Bytes;
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use clipboard_master::CallbackResult;
#[cfg(not(target_os = "linux"))]
use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
@@ -1942,14 +1940,19 @@ impl Client {
break;
}
match rx_cb_result.recv_timeout(Duration::from_millis(CLIPBOARD_INTERVAL)) {
Ok(CallbackResult::Next) => {
handler.check_clipboard();
Ok(ClipboardEvent::Changed) => {
handler.check_clipboard(true);
}
Ok(CallbackResult::Stop) => {
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
Ok(ClipboardEvent::InitialSelection) => {
// Preserve file startup sync without bypassing text initial-sync settings.
handler.check_clipboard(false);
}
Ok(ClipboardEvent::Stop) => {
log::debug!("Clipboard listener stopped");
break;
}
Ok(CallbackResult::StopWithError(err)) => {
Ok(ClipboardEvent::StopWithError(err)) => {
log::error!("Clipboard listener stopped with error: {}", err);
break;
}
@@ -2051,16 +2054,16 @@ impl ClientClipboardHandler {
}
}
fn check_clipboard(&mut self) {
fn check_clipboard(&mut self, check_text: bool) {
if CLIPBOARD_STATE.lock().unwrap().running {
#[cfg(feature = "unix-file-copy-paste")]
if let Some(urls) = check_clipboard_files(&mut self.ctx, ClipboardSide::Client, false) {
if !urls.is_empty() {
#[cfg(target_os = "macos")]
if crate::clipboard::is_file_url_set_by_rustdesk(&urls) {
return;
}
if self.is_file_required() {
if self.is_file_required() {
if let Some(urls) = check_clipboard_files(&mut self.ctx, ClipboardSide::Client, false) {
if !urls.is_empty() {
#[cfg(target_os = "macos")]
if crate::clipboard::is_file_url_set_by_rustdesk(&urls) {
return;
}
match clipboard::platform::unix::serv_files::sync_files(&urls) {
Ok(()) => {
let msg = crate::clipboard_file::clip_2_msg(
@@ -2077,8 +2080,8 @@ impl ClientClipboardHandler {
}
}
if let Some(msg) = check_clipboard(&mut self.ctx, ClipboardSide::Client, false) {
if self.is_text_required() {
if check_text && self.is_text_required() {
if let Some(msg) = check_clipboard(&mut self.ctx, ClipboardSide::Client, false) {
self.send_msg(msg, false);
}
}
@@ -4973,6 +4976,8 @@ pub enum Data {
RejectInsecureConnection,
Login((String, String, String, bool)),
Message(Message),
#[cfg(not(any(target_os = "android", target_os = "ios")))]
InitialClipboard(usize, Option<Message>),
SendFiles((i32, JobType, String, String, i32, bool, bool)),
RemoveDirAll((i32, String, bool, bool)),
ConfirmDeleteFiles((i32, i32)),
@@ -5369,6 +5374,15 @@ pub mod peer_online {
match msg_in.union {
Some(rendezvous_message::Union::OnlineResponse(online_response)) => {
let states = online_response.states;
// One bit per ID, rounded up to whole bytes:
// 0 IDs -> 0 bytes; 1..=8 -> 1; 9..=16 -> 2; 17..=24 -> 3.
let required_len = ids.len().div_ceil(u8::BITS as usize);
if states.len() < required_len {
bail!(
"Invalid online response: expected at least {required_len} state bytes, got {}",
states.len()
);
}
let mut onlines = Vec::new();
let mut offlines = Vec::new();
for i in 0..ids.len() {
+440 -31
View File
@@ -1,5 +1,5 @@
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use crate::clipboard::{update_clipboard, ClipboardSide};
use crate::clipboard::{clipboard_listener, update_clipboard, ClipboardSide};
#[cfg(not(any(target_os = "ios")))]
use crate::{audio_service, clipboard::CLIPBOARD_INTERVAL, ConnInner, CLIENT_SERVER};
use crate::{
@@ -61,7 +61,7 @@ use hbb_common::{
use hbb_common::{tokio::sync::Mutex as TokioMutex, ResultType};
use scrap::CodecFormat;
use std::{
collections::HashMap,
collections::{HashMap, HashSet},
ffi::c_void,
num::NonZeroI64,
path::PathBuf,
@@ -84,7 +84,12 @@ pub struct Remote<T: InvokeUiSession> {
remove_jobs: HashMap<i32, RemoveJob>,
timer: crate::RustDeskInterval,
last_update_jobs_status: (Instant, HashMap<i32, u64>),
// Set after PeerInfo for this round, not when the transport connects.
is_connected: bool,
// Whether the scheduled initial snapshot may still be sent.
// The connection loop clears this when handling its result or a live clipboard update.
#[cfg(not(any(target_os = "android", target_os = "ios")))]
initial_clipboard_pending: bool,
first_frame: bool,
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
client_conn_id: i32, // used for file clipboard
@@ -96,6 +101,7 @@ pub struct Remote<T: InvokeUiSession> {
chroma: Arc<RwLock<Option<Chroma>>>,
last_record_state: bool,
sent_close_reason: bool,
cursor_dedupe: CursorDedupe,
}
#[derive(Default)]
@@ -132,6 +138,8 @@ impl<T: InvokeUiSession> Remote<T> {
timer: crate::rustdesk_interval(time::interval(SEC30)),
last_update_jobs_status: (Instant::now(), Default::default()),
is_connected: false,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
initial_clipboard_pending: false,
first_frame: false,
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
client_conn_id: 0,
@@ -145,6 +153,7 @@ impl<T: InvokeUiSession> Remote<T> {
chroma: Default::default(),
last_record_state: false,
sent_close_reason: false,
cursor_dedupe: Default::default(),
}
}
@@ -432,6 +441,11 @@ impl<T: InvokeUiSession> Remote<T> {
#[cfg(not(target_os = "ios"))]
if self.handler.is_default() && _set_disconnected_ok {
// Other sessions may keep the listener running after this one disconnects.
#[cfg(feature = "flutter")]
crate::flutter::update_text_clipboard_required();
#[cfg(all(feature = "flutter", feature = "unix-file-copy-paste"))]
crate::flutter::update_file_clipboard_required();
Client::try_stop_clipboard();
}
@@ -445,7 +459,7 @@ impl<T: InvokeUiSession> Remote<T> {
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
async fn handle_local_clipboard_msg(
&self,
&mut self,
peer: &mut Stream,
msg: Option<clipboard::ClipboardFile>,
) {
@@ -458,6 +472,10 @@ impl<T: InvokeUiSession> Remote<T> {
} => {
self.handler.msgbox(&r#type, &title, &text, "");
}
// File-data responses bypass is_stopping_allowed, but still require login.
_ if !self.is_connected => {
log::debug!("Discarding local file clipboard message before login");
}
_ => {
let is_stopping_allowed = clip.is_stopping_allowed();
let server_file_transfer_enabled =
@@ -466,9 +484,7 @@ impl<T: InvokeUiSession> Remote<T> {
self.handler.lc.read().unwrap().enable_file_copy_paste.v;
let view_only = self.handler.lc.read().unwrap().view_only.v;
let stop = is_stopping_allowed
&& (view_only
|| !self.is_connected
|| !(server_file_transfer_enabled && file_transfer_enabled));
&& (view_only || !(server_file_transfer_enabled && file_transfer_enabled));
log::debug!(
"Process clipboard message from system, view_only: {}, stop: {}, is_stopping_allowed: {}, server_file_transfer_enabled: {}, file_transfer_enabled: {}",
view_only, stop, is_stopping_allowed, server_file_transfer_enabled, file_transfer_enabled
@@ -485,6 +501,10 @@ impl<T: InvokeUiSession> Remote<T> {
// to-do: Show msgbox with "Don't show again" option
};
log::debug!("Send system clipboard message to remote");
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if matches!(&clip, clipboard::ClipboardFile::FormatList { .. }) {
self.initial_clipboard_pending = false;
}
let msg = crate::clipboard_file::clip_2_msg(clip);
allow_err!(peer.send(&msg).await);
}
@@ -625,6 +645,82 @@ impl<T: InvokeUiSession> Remote<T> {
self.sent_close_reason = true;
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
fn start_initial_clipboard_sync(&mut self) {
let peer_info = {
let lc = self.handler.lc.read().unwrap();
lc.peer_info
.as_ref()
.map(|pi| (pi.version.clone(), pi.platform.clone()))
};
let Some((peer_version, peer_platform)) = peer_info else {
log::error!("Cannot start initial clipboard sync without peer information");
return;
};
self.initial_clipboard_pending = true;
let sender = self.sender.clone();
let permission_config = self.handler.get_permission_config();
// Clipboard access and encoding must not block the connection loop.
let read_clipboard = move || {
// Capture after readiness, before reading; later changes invalidate this snapshot.
let generation = clipboard_listener::current_generation();
let msg_out = if permission_config.is_text_clipboard_required() {
crate::clipboard::get_current_clipboard_msg(
&peer_version,
&peer_platform,
crate::clipboard::ClipboardSide::Client,
)
} else {
None
};
let msg_out = msg_out.filter(|_| permission_config.is_text_clipboard_required());
// Empty or failed reads must also finish the pending initial-sync attempt.
if let Err(err) = sender.send(Data::InitialClipboard(generation, msg_out)) {
log::debug!("Failed to send initial clipboard result: {}", err);
}
};
#[cfg(target_os = "linux")]
self.spawn_initial_clipboard_read_after_ready(read_clipboard);
#[cfg(not(target_os = "linux"))]
tokio::task::spawn_blocking(read_clipboard);
}
// Linux listener creation returns before X11/Wayland has subscribed to changes.
// Capture after readiness so changes during the read can invalidate the snapshot.
// A separate task keeps a stalled backend from blocking the connection loop.
#[cfg(target_os = "linux")]
fn spawn_initial_clipboard_read_after_ready(&self, read_clipboard: impl FnOnce() + Send + 'static) {
// Initial-sync wait budget, not a protocol-defined startup deadline.
const CLIPBOARD_READY_TIMEOUT: Duration = Duration::from_secs(5);
let sender = self.sender.clone();
tokio::spawn(async move {
let ready = tokio::select! {
result = time::timeout(CLIPBOARD_READY_TIMEOUT, clipboard_listener::wait_for_ready()) => {
match result {
Ok(ready) => ready,
Err(err) => Err(err.into()),
}
}
_ = sender.closed() => return,
};
if let Err(err) = ready {
log::error!(
"Failed to wait for clipboard listener readiness (limit {:?}): {}",
CLIPBOARD_READY_TIMEOUT,
err,
);
let generation = clipboard_listener::current_generation();
if let Err(err) = sender.send(Data::InitialClipboard(generation, None)) {
log::debug!("Failed to send initial clipboard result: {}", err);
}
return;
}
tokio::task::spawn_blocking(read_clipboard);
});
}
async fn handle_msg_from_ui(&mut self, data: Data, peer: &mut Stream) -> bool {
match data {
Data::Close => {
@@ -640,6 +736,27 @@ impl<T: InvokeUiSession> Remote<T> {
Data::ToggleClipboardFile => {
self.check_clipboard_file_context();
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Data::InitialClipboard(generation, msg) => {
// A live update supersedes any initial snapshot still being prepared.
if !self.initial_clipboard_pending {
return true;
}
self.initial_clipboard_pending = false;
if !self.handler.is_text_clipboard_required() {
return true;
}
if generation != clipboard_listener::current_generation() {
// A clipboard change or listener restart can invalidate the snapshot
// without sending a live update that supersedes it.
drop(msg);
self.start_initial_clipboard_sync();
return true;
}
if let Some(msg) = msg {
allow_err!(peer.send(&msg).await);
}
}
Data::Message(msg) => {
// The Flutter clipboard broadcast is process-wide, so a clipboard can reach this
// round's queue before the round has logged in; it is dropped here, on the round
@@ -655,6 +772,20 @@ impl<T: InvokeUiSession> Remote<T> {
return true;
}
match &msg.union {
Some(message::Union::Cliprdr(_)) if !self.is_connected => {
log::debug!("Discarding outgoing file clipboard message before login");
return true;
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Some(message::Union::Clipboard(_)) | Some(message::Union::MultiClipboards(_)) => {
self.initial_clipboard_pending = false;
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Some(message::Union::Cliprdr(clip))
if matches!(clip.union.as_ref(), Some(cliprdr::Union::FormatList(_))) =>
{
self.initial_clipboard_pending = false;
}
Some(message::Union::Misc(misc)) => match misc.union {
Some(misc::Union::RefreshVideo(_)) => {
self.video_threads.iter().for_each(|(_, v)| {
@@ -1467,6 +1598,14 @@ impl<T: InvokeUiSession> Remote<T> {
#[cfg(all(target_os = "windows", not(feature = "flutter")))]
self.check_clipboard_file_context();
if self.handler.is_default() {
// Startup notifications must see the current sessions' clipboard requirements.
#[cfg(feature = "flutter")]
#[cfg(not(target_os = "ios"))]
crate::flutter::update_text_clipboard_required();
#[cfg(all(feature = "flutter", feature = "unix-file-copy-paste"))]
crate::flutter::update_file_clipboard_required();
#[cfg(feature = "flutter")]
#[cfg(not(target_os = "ios"))]
let rx = Client::try_start_clipboard(None);
@@ -1488,31 +1627,18 @@ impl<T: InvokeUiSession> Remote<T> {
timeout(CLIPBOARD_INTERVAL, rx.recv()).await.ok();
}
// `is_connected`` becomes true after the first PeerInfo.
// Reconnects create a new Remote. Refreshes after a generation change
// use a separate entry point and are not blocked by this guard.
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if self.handler.lc.read().unwrap().sync_init_clipboard.v {
if let Some(msg_out) = crate::clipboard::get_current_clipboard_msg(
&peer_version,
&peer_platform,
crate::clipboard::ClipboardSide::Client,
) {
let sender = self.sender.clone();
let permission_config = self.handler.get_permission_config();
tokio::spawn(async move {
if permission_config.is_text_clipboard_required() {
sender.send(Data::Message(msg_out)).ok();
}
});
}
if !self.is_connected
&& self.handler.is_text_clipboard_required()
&& self.handler.lc.read().unwrap().sync_init_clipboard.v
{
self.start_initial_clipboard_sync();
}
// to-do: Android, is `sync_init_clipboard` really needed?
// https://github.com/rustdesk/rustdesk/discussions/9010
#[cfg(feature = "flutter")]
#[cfg(not(target_os = "ios"))]
crate::flutter::update_text_clipboard_required();
#[cfg(all(feature = "flutter", feature = "unix-file-copy-paste"))]
crate::flutter::update_file_clipboard_required();
}
if self.handler.is_file_transfer() {
@@ -1523,11 +1649,29 @@ impl<T: InvokeUiSession> Remote<T> {
}
_ => {}
},
Some(message::Union::CursorData(cd)) if self.dedupes_cursors() => {
self.set_cursor_data_by_content(cd);
}
Some(message::Union::CursorId(id)) if self.dedupes_cursors() => {
self.handler
.set_cursor_id(self.cursor_dedupe.id(id).to_string());
}
Some(message::Union::CursorData(cd)) => {
let id = cd.id;
#[cfg(feature = "flutter")]
let compressed = cd.colors.clone();
match decode_cursor_data(cd) {
Ok(cd) => self.handler.set_cursor_data(cd),
Err(err) => log::warn!("Rejected cursor {id}: {err}"),
Ok(cd) => {
#[cfg(feature = "flutter")]
self.keep_cursor_shape(cursor_shape(id, &cd, &compressed));
self.handler.set_cursor_data(cd)
}
Err(err) => {
log::warn!("Rejected cursor {id}: {err}");
// The peer shows it now: selected, the UI treats it as a shape it
// lacks, as it will when the peer selects it again.
self.handler.set_cursor_id(id.to_string());
}
}
}
Some(message::Union::CursorId(id)) => {
@@ -1555,7 +1699,10 @@ impl<T: InvokeUiSession> Remote<T> {
crate::flutter::send_clipboard_msg_to_other_sessions(msg, session_id);
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
update_clipboard(vec![cb], ClipboardSide::Client);
{
self.initial_clipboard_pending = false;
update_clipboard(vec![cb], ClipboardSide::Client);
}
#[cfg(target_os = "ios")]
{
let content = if cb.compress {
@@ -1590,7 +1737,10 @@ impl<T: InvokeUiSession> Remote<T> {
crate::flutter::send_clipboard_msg_to_other_sessions(msg, session_id);
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
update_clipboard(_mcb.clipboards, ClipboardSide::Client);
{
self.initial_clipboard_pending = false;
update_clipboard(_mcb.clipboards, ClipboardSide::Client);
}
#[cfg(target_os = "ios")]
{
if let Some(cb) = _mcb
@@ -2417,6 +2567,10 @@ impl<T: InvokeUiSession> Remote<T> {
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
async fn handle_cliprdr_msg(&mut self, clip: base::message_proto::Cliprdr, _peer: &mut Stream) {
if !self.is_connected {
log::debug!("Discarding incoming file clipboard message before login");
return;
}
log::debug!("handling cliprdr msg from server peer");
#[cfg(feature = "flutter")]
if let Some(base::message_proto::cliprdr::Union::FormatList(_)) = &clip.union {
@@ -2448,6 +2602,9 @@ impl<T: InvokeUiSession> Remote<T> {
};
#[cfg(target_os = "windows")]
{
if matches!(&clip, clipboard::ClipboardFile::FormatList { .. }) {
self.initial_clipboard_pending = false;
}
let _ = ContextSend::proc(|context| -> ResultType<()> {
context
.server_clip_file(self.client_conn_id, clip)
@@ -2456,6 +2613,10 @@ impl<T: InvokeUiSession> Remote<T> {
}
#[cfg(feature = "unix-file-copy-paste")]
if crate::is_support_file_copy_paste_num(self.handler.lc.read().unwrap().version) {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if matches!(&clip, clipboard::ClipboardFile::FormatList { .. }) {
self.initial_clipboard_pending = false;
}
let mut out_msgs = vec![];
#[cfg(target_os = "macos")]
@@ -2560,6 +2721,69 @@ impl<T: InvokeUiSession> Remote<T> {
msg.set_misc(misc);
self.sender.send(Data::Message(msg)).ok();
}
/// A shape that decoded, for the UI to ask for again; see `Session::cursor_shapes`.
#[cfg(feature = "flutter")]
fn keep_cursor_shape(&self, shape: CursorData) {
self.handler
.cursor_shapes
.write()
.unwrap()
.insert(shape.id, shape);
}
fn dedupes_cursors(&self) -> bool {
!crate::is_peer_naming_cursors_by_content(self.handler.lc.read().unwrap().version)
}
/// A shape the UI already has, under whatever handle, is only selected.
fn set_cursor_data_by_content(&mut self, cd: CursorData) {
let peer_id = cd.id;
let id = CursorDedupe::name(&cd);
if self.cursor_dedupe.has_decoded(id) {
self.cursor_dedupe.record(peer_id, id);
self.handler.set_cursor_id(id.to_string());
return;
}
#[cfg(feature = "flutter")]
let compressed = cd.colors.clone();
match decode_cursor_data(cd) {
Ok(mut cd) => {
cd.id = id;
self.cursor_dedupe.record(peer_id, id);
#[cfg(feature = "flutter")]
self.keep_cursor_shape(cursor_shape(id, &cd, &compressed));
self.handler.set_cursor_data(cd);
}
Err(err) => {
log::warn!("Rejected cursor {peer_id}: {err}");
self.handler
.set_cursor_id(self.cursor_dedupe.rejected(peer_id, id).to_string());
}
}
}
}
/// A shape that decoded, still compressed, under the id the UI knows it by. Copied once it
/// decoded: the message's colors may be a slice of a larger received buffer, which a clone
/// would keep alive.
#[cfg(any(feature = "flutter", test))]
fn cursor_shape(id: u64, cd: &CursorData, compressed: &[u8]) -> CursorData {
CursorData {
id,
hotx: cd.hotx,
hoty: cd.hoty,
width: cd.width,
height: cd.height,
colors: compressed.to_vec().into(),
..Default::default()
}
}
/// The RGBA of a shape kept by `Session::cursor_shapes`, for the UI to draw it again.
#[cfg(any(feature = "flutter", test))]
pub(crate) fn kept_cursor_rgba(shape: CursorData) -> hbb_common::ResultType<CursorData> {
decode_cursor_data(shape)
}
// Both UI handlers receive validated, uncompressed RGBA from the receive loop.
@@ -2603,6 +2827,49 @@ fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
Ok(cd)
}
/// Gives the UI one id per shape for a peer that names shapes by handle, so the UI decodes and
/// keeps a shape once however many handles it arrives under. Nothing is dropped for the
/// connection: the peer sends a shape once and may select any handle it named again.
#[derive(Default)]
struct CursorDedupe {
ids: HashMap<u64, u64>,
// The shapes given to the UI, by content id: whether one that arrives needs decoding.
decoded: HashSet<u64>,
}
impl CursorDedupe {
/// Hashes the compressed colors: one peer compresses the same pixels to the same bytes, and
/// a shape seen before is then never decompressed again.
fn name(cd: &CursorData) -> u64 {
crate::cursor_content_id(cd.width, cd.height, cd.hotx, cd.hoty, &cd.colors)
}
fn id(&self, peer_id: u64) -> u64 {
self.ids.get(&peer_id).copied().unwrap_or(peer_id)
}
fn has_decoded(&self, id: u64) -> bool {
self.decoded.contains(&id)
}
/// Names the handle once its shape decoded, now or before.
fn record(&mut self, peer_id: u64, id: u64) {
self.ids.insert(peer_id, id);
self.decoded.insert(id);
}
/// Names a known handle by the content of a shape that did not decode, which is never
/// marked decoded: the UI has no shape under it, now or when the handle is selected again,
/// and the shape the handle named before is not shown in its place. A handle never seen is
/// not filed, so what a peer sends that does not decode takes no room.
fn rejected(&mut self, peer_id: u64, id: u64) -> u64 {
if let Some(named) = self.ids.get_mut(&peer_id) {
*named = id;
}
id
}
}
struct RemoveJob {
files: Vec<FileEntry>,
path: String,
@@ -2725,3 +2992,145 @@ mod tests {
);
}
}
#[cfg(test)]
mod cursor_dedupe_tests {
use super::*;
fn shape(id: u64, hotx: i32, colors: &[u8]) -> CursorData {
CursorData {
id,
hotx,
width: 2,
height: 2,
colors: colors.to_vec().into(),
..Default::default()
}
}
#[test]
fn a_shape_sent_under_a_new_handle_keeps_its_id() {
let mut dedupe = CursorDedupe::default();
let first = CursorDedupe::name(&shape(1, 0, b"arrow"));
assert!(!dedupe.has_decoded(first));
dedupe.record(1, first);
let again = CursorDedupe::name(&shape(2, 0, b"arrow"));
assert_eq!(again, first);
assert!(dedupe.has_decoded(again));
dedupe.record(2, again);
assert_eq!(dedupe.id(2), first);
assert_eq!(dedupe.id(1), first);
}
#[test]
fn the_hotspot_is_part_of_the_shape() {
let a = CursorDedupe::name(&shape(1, 0, b"arrow"));
let b = CursorDedupe::name(&shape(2, 1, b"arrow"));
assert_ne!(a, b);
}
#[test]
fn a_reused_handle_names_its_latest_shape() {
let mut dedupe = CursorDedupe::default();
dedupe.record(1, CursorDedupe::name(&shape(1, 0, b"arrow")));
let beam = CursorDedupe::name(&shape(1, 0, b"beam"));
dedupe.record(1, beam);
assert_eq!(dedupe.id(1), beam);
}
#[test]
fn a_rejected_shape_names_its_handle_and_is_never_decoded() {
let mut dedupe = CursorDedupe::default();
let arrow = CursorDedupe::name(&shape(7, 0, b"arrow"));
dedupe.record(7, arrow);
let beam = CursorDedupe::name(&shape(8, 0, b"beam"));
dedupe.record(8, beam);
let broken = CursorDedupe::name(&shape(7, 0, b"broken"));
assert_eq!(
dedupe.rejected(7, broken),
broken,
"not the shape it named before"
);
assert_eq!(
dedupe.id(7),
broken,
"nor when the handle is selected again"
);
assert_eq!(dedupe.id(8), beam, "another handle keeps its shape");
assert!(!dedupe.has_decoded(broken));
assert!(
dedupe.has_decoded(arrow),
"kept for a handle that brings it again"
);
dedupe.record(7, arrow);
assert_eq!(dedupe.id(7), arrow);
}
#[test]
fn a_shape_rejected_under_handles_never_seen_files_nothing() {
let mut dedupe = CursorDedupe::default();
let broken = CursorDedupe::name(&shape(0, 0, b"broken"));
for handle in 0..1000 {
assert_eq!(dedupe.rejected(handle, broken), broken);
}
assert!(dedupe.ids.is_empty());
assert!(!dedupe.has_decoded(broken));
}
#[test]
fn an_id_the_peer_never_sent_is_passed_on() {
assert_eq!(CursorDedupe::default().id(7), 7);
}
#[test]
fn peers_from_1_5_0_name_cursors_by_content() {
use hbb_common::get_version_number as v;
assert!(!crate::is_peer_naming_cursors_by_content(v("1.4.9")));
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.0")));
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.1")));
}
}
#[cfg(test)]
mod kept_cursor_tests {
use super::*;
fn compressed(width: i32, height: i32) -> CursorData {
let rgba = vec![7u8; (width * height * 4) as usize];
CursorData {
id: 1,
width,
height,
colors: hbb_common::compress::compress(&rgba).into(),
..Default::default()
}
}
#[test]
fn a_kept_shape_is_a_copy_under_the_ui_id() {
let mut cd = compressed(4, 4);
cd.hotx = 1;
let kept = cursor_shape(42, &cd, &cd.colors);
assert_eq!(kept.id, 42);
assert_eq!((kept.hotx, kept.width, kept.height), (1, 4, 4));
assert_eq!(kept.colors, cd.colors);
assert_ne!(
kept.colors.as_ptr(),
cd.colors.as_ptr(),
"not a view of the received buffer"
);
}
#[test]
fn a_kept_shape_is_checked_again_when_it_is_read() {
assert_eq!(kept_cursor_rgba(compressed(4, 4)).unwrap().colors.len(), 64);
assert!(
kept_cursor_rgba(compressed(513, 1)).is_err(),
"over the size cap"
);
let mut bomb = compressed(4, 4);
bomb.colors = hbb_common::compress::compress(&vec![0u8; 1 << 20]).into();
assert!(kept_cursor_rgba(bomb).is_err(), "more pixels than its size");
}
}
+107 -16
View File
@@ -34,8 +34,6 @@ const CLIPBOARD_FORMAT_EXCEL_XML_SPREADSHEET: &'static str = "XML Spreadsheet";
#[cfg(not(target_os = "android"))]
lazy_static::lazy_static! {
static ref ARBOARD_MTX: Arc<Mutex<()>> = Arc::new(Mutex::new(()));
// cache the clipboard msg
static ref LAST_MULTI_CLIPBOARDS: Arc<Mutex<MultiClipboards>> = Arc::new(Mutex::new(MultiClipboards::new()));
// For updating in server and getting content in cm.
// Clipboard on Linux is "server--clients" mode.
// The clipboard content is owned by the server and passed to the clients when requested.
@@ -79,8 +77,7 @@ pub fn check_clipboard(
side: ClipboardSide,
force: bool,
) -> Option<Message> {
let (msg, clipboards) = read_clipboard_message(ctx, side, force)?;
*LAST_MULTI_CLIPBOARDS.lock().unwrap() = clipboards;
let (msg, _) = read_clipboard_message(ctx, side, force)?;
Some(msg)
}
@@ -564,18 +561,25 @@ pub fn get_current_clipboard_msg(
peer_platform: &str,
side: ClipboardSide,
) -> Option<Message> {
let mut multi_clipboards = LAST_MULTI_CLIPBOARDS.lock().unwrap();
if multi_clipboards.clipboards.is_empty() {
let mut ctx = ClipboardContext::new().ok()?;
*multi_clipboards = proto::create_multi_clipboards(ctx.get(side, true).ok()?);
// Clipboard changes can be skipped while synchronization is disabled.
#[cfg(target_os = "linux")]
if !clipboard_listener::is_ready() {
log::error!("Cannot read initial clipboard before the listener is ready");
return None;
}
let ctx = match ClipboardContext::new() {
Ok(ctx) => ctx,
Err(err) => {
log::error!("Failed to create clipboard context for initial sync: {}", err);
return None;
}
};
let (msg, multi_clipboards) = read_clipboard_message(&mut Some(ctx), side, true)?;
if multi_clipboards.clipboards.is_empty() {
return None;
}
if is_support_multi_clipboard(peer_version, peer_platform) {
let mut msg = Message::new();
msg.set_multi_clipboards(multi_clipboards.clone());
Some(msg)
} else {
// Find the first text clipboard and send it.
@@ -888,10 +892,13 @@ pub fn get_clipboards_msg(client: bool) -> Option<Message> {
#[cfg(not(target_os = "android"))]
pub mod clipboard_listener {
use clipboard_master::{CallbackResult, ClipboardHandler, Master, Shutdown};
#[cfg(target_os = "linux")]
use hbb_common::tokio::sync::watch;
use hbb_common::{bail, log, ResultType};
use std::{
collections::HashMap,
io,
sync::atomic::{AtomicUsize, Ordering},
sync::mpsc::{channel, Sender},
sync::{Arc, Mutex},
thread::JoinHandle,
@@ -901,15 +908,83 @@ pub mod clipboard_listener {
pub static ref CLIPBOARD_LISTENER: Arc<Mutex<ClipboardListener>> = Default::default();
}
static CLIPBOARD_GENERATION: AtomicUsize = AtomicUsize::new(0);
pub enum ClipboardEvent {
Changed,
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
InitialSelection,
Stop,
StopWithError(io::Error),
}
pub fn current_generation() -> usize {
CLIPBOARD_GENERATION.load(Ordering::SeqCst)
}
#[cfg(target_os = "linux")]
pub fn is_ready() -> bool {
let listener = CLIPBOARD_LISTENER.lock().unwrap();
let ready = listener
.ready
.as_ref()
.map(|ready| *ready.borrow())
.unwrap_or(false);
ready
&& listener
.handle
.as_ref()
.map(|(_, h)| !h.is_finished())
.unwrap_or(false)
}
#[cfg(target_os = "linux")]
pub async fn wait_for_ready() -> ResultType<()> {
let Some(mut ready) = CLIPBOARD_LISTENER.lock().unwrap().ready.clone() else {
bail!("Clipboard listener has not started");
};
let is_ready = *ready.borrow_and_update();
if !is_ready {
ready.changed().await?;
}
Ok(())
}
struct Handler {
subscribers: Arc<Mutex<HashMap<String, Sender<CallbackResult>>>>,
subscribers: Arc<Mutex<HashMap<String, Sender<ClipboardEvent>>>>,
#[cfg(target_os = "linux")]
ready: Option<watch::Sender<bool>>,
}
impl ClipboardHandler for Handler {
#[cfg(target_os = "linux")]
fn on_clipboard_ready(&mut self) {
// A restart must invalidate older snapshots, including on X11 or an empty selection.
CLIPBOARD_GENERATION.fetch_add(1, Ordering::SeqCst);
if let Some(tx) = self.ready.take() {
if let Err(err) = tx.send(true) {
log::debug!("Failed to report clipboard listener readiness: {}", err);
}
}
}
fn on_clipboard_change(&mut self) -> CallbackResult {
// Empty or unsupported contents still invalidate an initial snapshot.
CLIPBOARD_GENERATION.fetch_add(1, Ordering::SeqCst);
let sub_lock = self.subscribers.lock().unwrap();
for tx in sub_lock.values() {
tx.send(CallbackResult::Next).ok();
tx.send(ClipboardEvent::Changed).ok();
}
CallbackResult::Next
}
fn on_clipboard_initial_selection(&mut self) -> CallbackResult {
// Only client file sync consumes this event; text initial sync is per session.
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
for tx in self.subscribers.lock().unwrap().values() {
if let Err(err) = tx.send(ClipboardEvent::InitialSelection) {
log::debug!("Failed to notify initial clipboard selection: {}", err);
}
}
CallbackResult::Next
}
@@ -918,23 +993,30 @@ pub mod clipboard_listener {
let msg = format!("Clipboard listener error: {}", error);
let sub_lock = self.subscribers.lock().unwrap();
for tx in sub_lock.values() {
tx.send(CallbackResult::StopWithError(io::Error::new(
tx.send(ClipboardEvent::StopWithError(io::Error::new(
io::ErrorKind::Other,
msg.clone(),
)))
.ok();
}
#[cfg(target_os = "linux")]
if self.ready.is_some() {
// Subscribers must receive the error before a failed startup stops.
return CallbackResult::StopWithError(error);
}
CallbackResult::Next
}
}
#[derive(Default)]
pub struct ClipboardListener {
subscribers: Arc<Mutex<HashMap<String, Sender<CallbackResult>>>>,
subscribers: Arc<Mutex<HashMap<String, Sender<ClipboardEvent>>>>,
handle: Option<(Shutdown, JoinHandle<()>)>,
#[cfg(target_os = "linux")]
ready: Option<watch::Receiver<bool>>,
}
pub fn subscribe(name: String, tx: Sender<CallbackResult>) -> ResultType<()> {
pub fn subscribe(name: String, tx: Sender<ClipboardEvent>) -> ResultType<()> {
log::info!("Subscribe clipboard listener: {}", &name);
let mut listener_lock = CLIPBOARD_LISTENER.lock().unwrap();
listener_lock
@@ -946,8 +1028,12 @@ pub mod clipboard_listener {
cleanup_stale_listener(&mut listener_lock);
if listener_lock.handle.is_none() {
log::info!("Start clipboard listener thread");
#[cfg(target_os = "linux")]
let (tx_ready, rx_ready) = watch::channel(false);
let handler = Handler {
subscribers: listener_lock.subscribers.clone(),
#[cfg(target_os = "linux")]
ready: Some(tx_ready),
};
let (tx_start_res, rx_start_res) = channel();
let h = start_clipboard_master_thread(handler, tx_start_res);
@@ -962,6 +1048,11 @@ pub mod clipboard_listener {
}
};
listener_lock.handle = Some((shutdown, h));
#[cfg(target_os = "linux")]
{
// Initial-sync tasks await backend readiness without blocking the connection loop.
listener_lock.ready = Some(rx_ready);
}
log::info!("Clipboard listener thread started");
}
@@ -993,7 +1084,7 @@ pub mod clipboard_listener {
let is_empty = {
let mut sub_lock = listener_lock.subscribers.lock().unwrap();
if let Some(tx) = sub_lock.remove(name) {
tx.send(CallbackResult::Stop).ok();
tx.send(ClipboardEvent::Stop).ok();
}
sub_lock.is_empty()
};
+66 -3
View File
@@ -224,6 +224,13 @@ pub fn msg_2_clip(msg: Cliprdr) -> Option<ClipboardFile> {
}
}
pub fn is_file_data_request(msg: &Cliprdr) -> bool {
matches!(
msg.union,
Some(cliprdr::Union::FormatDataRequest(_)) | Some(cliprdr::Union::FileContentsRequest(_))
)
}
#[cfg(feature = "unix-file-copy-paste")]
pub mod unix_file_clip {
use super::*;
@@ -314,7 +321,7 @@ pub mod unix_file_clip {
requested_format_id: _requested_format_id,
} => {
log::debug!("requested format id: {}", _requested_format_id);
let format_data = serv_files::get_file_list_pdu();
let format_data = serv_files::get_file_list_pdu(conn_id);
if !format_data.is_empty() {
return vec![clip_2_msg(ClipboardFile::FormatDataResponse {
msg_flags: 1,
@@ -365,7 +372,8 @@ pub mod unix_file_clip {
n_position_low,
n_position_high,
cb_requested,
..
have_clip_data_id,
clip_data_id,
} => {
log::debug!("file contents request: stream_id: {}, list_index: {}, dw_flags: {}, n_position_low: {}, n_position_high: {}, cb_requested: {}", stream_id, list_index, dw_flags, n_position_low, n_position_high, cb_requested);
return serv_files::read_file_contents(
@@ -376,12 +384,18 @@ pub mod unix_file_clip {
n_position_low,
n_position_high,
cb_requested,
have_clip_data_id.then_some(clip_data_id),
)
.into_iter()
.map(|res| match res {
Ok(data) => clip_2_msg(data),
Err(e) => {
log::error!("failed to read file contents: {:?}", e);
hbb_common::throttled_log!(
std::time::Duration::from_secs(5),
error,
"failed to read file contents: {:?}",
e
);
resp_file_contents_fail(stream_id)
}
})
@@ -433,3 +447,52 @@ pub mod unix_file_clip {
vec![]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn is_request(clip: ClipboardFile) -> bool {
match clip_2_msg(clip).union {
Some(message::Union::Cliprdr(msg)) => is_file_data_request(&msg),
_ => false,
}
}
#[test]
fn test_is_file_data_request() {
assert!(is_request(ClipboardFile::FormatDataRequest {
requested_format_id: 0,
}));
assert!(is_request(ClipboardFile::FileContentsRequest {
stream_id: 0,
list_index: 0,
dw_flags: 0,
n_position_low: 0,
n_position_high: 0,
cb_requested: 0,
have_clip_data_id: false,
clip_data_id: 0,
}));
// Messages that carry the peer's own clipboard files must stay allowed.
assert!(!is_request(ClipboardFile::MonitorReady));
assert!(!is_request(ClipboardFile::FormatList {
format_list: vec![],
}));
assert!(!is_request(ClipboardFile::FormatListResponse {
msg_flags: 0
}));
assert!(!is_request(ClipboardFile::FormatDataResponse {
msg_flags: 0,
format_data: vec![],
}));
assert!(!is_request(ClipboardFile::FileContentsResponse {
msg_flags: 0,
stream_id: 0,
requested_data: vec![],
}));
assert!(!is_request(ClipboardFile::TryEmpty));
assert!(!is_request(ClipboardFile::Files { files: vec![] }));
}
}
+101 -7
View File
@@ -59,6 +59,7 @@ pub const PLATFORM_MACOS: &str = "Mac OS";
pub const PLATFORM_ANDROID: &str = "Android";
pub const TIMER_OUT: Duration = Duration::from_secs(1);
pub(crate) const API_LOG_INTERVAL: Duration = Duration::from_secs(600);
pub const DEFAULT_KEEP_ALIVE: i32 = 60_000;
const MIN_VER_MULTI_UI_SESSION: &str = "1.2.4";
@@ -148,6 +149,24 @@ pub fn is_support_multi_ui_session_num(ver: i64) -> bool {
ver >= hbb_common::get_version_number(MIN_VER_MULTI_UI_SESSION)
}
/// Peers from the 1.5.0 release name a cursor by `cursor_content_id`; older ones by the
/// platform handle, which apps mint anew for the same shape.
#[inline]
pub fn is_peer_naming_cursors_by_content(ver: i64) -> bool {
ver >= hbb_common::get_version_number("1.5.0")
}
/// One id per cursor look, however many handles a platform gives it. Held to 53 bits: the web
/// client decodes a u64 into a JS number and drops the whole message when it does not fit.
pub fn cursor_content_id(width: i32, height: i32, hotx: i32, hoty: i32, colors: &[u8]) -> u64 {
let mut hasher = xxhash_rust::xxh3::Xxh3::new();
for v in [width, height, hotx, hoty] {
hasher.update(&v.to_le_bytes());
}
hasher.update(colors);
hasher.digest() & ((1 << 53) - 1)
}
#[inline]
#[cfg(feature = "unix-file-copy-paste")]
pub fn is_support_file_copy_paste(ver: &str) -> bool {
@@ -1196,6 +1215,9 @@ pub fn get_local_option(key: &str) -> String {
}
}
}
if key == "lang" && (v == "pt" || v == "br") {
return "pt-br".to_owned();
}
v
}
@@ -1244,6 +1266,23 @@ fn is_tcp_proxy_api_target(url: &str) -> bool {
should_use_tcp_proxy_for_api_url(url, &ui_get_api_server())
}
#[inline]
fn should_throttle_log(url: &str) -> bool {
url::Url::parse(url)
.map(|parsed| parsed.path().ends_with("/api/heartbeat"))
.unwrap_or(false)
}
macro_rules! api_log {
($level:ident, $url:expr, $interval:expr, $($arg:tt)+) => {{
if should_throttle_log($url) {
hbb_common::throttled_log!($interval, $level, $($arg)+);
} else {
log::$level!($($arg)+);
}
}};
}
fn tcp_proxy_log_target(url: &str) -> String {
url::Url::parse(url)
.ok()
@@ -1293,7 +1332,10 @@ async fn tcp_proxy_request(
parsed.path().to_string()
};
log::debug!(
api_log!(
debug,
url,
API_LOG_INTERVAL,
"Sending {} {} via TCP proxy to {}",
method,
parsed.path(),
@@ -1453,7 +1495,10 @@ where
};
if should_fallback && can_fallback_to_raw_tcp(url) {
log::warn!(
api_log!(
warn,
url,
API_LOG_INTERVAL,
"HTTP {} to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
method,
tcp_proxy_log_target(url),
@@ -1465,7 +1510,13 @@ where
match tcp_fn.await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
api_log!(
warn,
url,
API_LOG_INTERVAL,
"TCP proxy fallback also failed: {:?}",
tcp_err
);
}
}
}
@@ -1523,7 +1574,10 @@ pub async fn post_request_with_status(
Ok((status, _)) => *status >= 500,
};
if should_fallback && can_fallback_to_raw_tcp(&url) {
log::warn!(
api_log!(
warn,
&url,
API_LOG_INTERVAL,
"HTTP POST to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
tcp_proxy_log_target(&url),
http_result
@@ -1534,7 +1588,13 @@ pub async fn post_request_with_status(
match post_request_via_tcp_proxy_status(&url, &body, header).await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
api_log!(
warn,
&url,
API_LOG_INTERVAL,
"TCP proxy fallback also failed: {:?}",
tcp_err
);
}
}
}
@@ -1591,7 +1651,10 @@ async fn post_request_(
Err(e) => {
if (tls_type.is_none() || danger_accept_invalid_cert.is_none()) && e.is_request() {
if danger_accept_invalid_cert.is_none() {
log::warn!(
api_log!(
warn,
url,
API_LOG_INTERVAL,
"HTTP request failed: {:?}, try again, danger accept invalid cert",
e
);
@@ -1606,7 +1669,13 @@ async fn post_request_(
)
.await
} else {
log::warn!("HTTP request failed: {:?}, try again with native-tls", e);
api_log!(
warn,
url,
API_LOG_INTERVAL,
"HTTP request failed: {:?}, try again with native-tls",
e
);
post_request_(
url,
tls_url,
@@ -2885,6 +2954,16 @@ mod tests {
};
use std::collections::HashSet;
#[test]
fn a_cursor_content_id_fits_a_web_client_number() {
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
for colors in [&b"arrow"[..], b"beam", b"hand", b""] {
for hotx in 0..64 {
assert!(cursor_content_id(32, 32, hotx, 0, colors) <= MAX_SAFE_INTEGER);
}
}
}
#[inline]
fn get_timestamp_secs() -> u128 {
(std::time::SystemTime::UNIX_EPOCH
@@ -3135,6 +3214,21 @@ mod tests {
));
}
#[test]
fn test_should_throttle_log() {
assert!(should_throttle_log("https://example.com/api/heartbeat"));
assert!(should_throttle_log(
"https://example.com/api/heartbeat?token=secret"
));
assert!(should_throttle_log("https://example.com/prefix/api/heartbeat"));
assert!(!should_throttle_log("https://example.com/api/heartbeat2"));
assert!(!should_throttle_log("https://example.com/api/sysinfo"));
assert!(!should_throttle_log(
"https://example.com/api/sysinfo?next=/api/heartbeat"
));
assert!(!should_throttle_log("not a url"));
}
#[test]
fn test_get_tcp_proxy_addr_normalizes_bare_ipv6_host() {
struct RestoreCustomRendezvousServer(String);
+26 -16
View File
@@ -105,6 +105,16 @@ fn load_plugin_in_app_path(dll_name: &str) -> Result<Library, LibError> {
#[cfg(not(windows))]
#[no_mangle]
pub extern "C" fn rustdesk_core_main() -> bool {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
use hbb_common::libc;
// Native runners bypass Rust's startup, which normally ignores SIGPIPE.
if unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) } == libc::SIG_ERR {
eprintln!("Failed to ignore SIGPIPE: {}", std::io::Error::last_os_error());
std::process::exit(1);
}
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
if crate::core_main::core_main().is_some() {
return true;
@@ -641,23 +651,21 @@ impl FlutterHandler {
}
impl InvokeUiSession for FlutterHandler {
// On the event stream, so that it keeps its order with the cursor_id events around it.
fn set_cursor_data(&self, cd: CursorData) {
let colors = &cd.colors;
self.push_event(
"cursor_data",
&[
("id", &cd.id.to_string()),
("hotx", &cd.hotx.to_string()),
("hoty", &cd.hoty.to_string()),
("width", &cd.width.to_string()),
("height", &cd.height.to_string()),
(
"colors",
&serde_json::ser::to_string(&colors).unwrap_or("".to_owned()),
),
],
&[],
);
let colors = cd.colors.to_vec();
for session in self.session_handlers.read().unwrap().values() {
if let Some(stream) = &session.event_stream {
stream.add(EventToUI::Cursor {
id: cd.id.to_string(),
hotx: cd.hotx,
hoty: cd.hoty,
width: cd.width,
height: cd.height,
colors: colors.clone(),
});
}
}
}
fn set_cursor_id(&self, id: String) {
@@ -1407,6 +1415,7 @@ fn try_send_close_event(event_stream: &Option<StreamSink<EventToUI>>) {
pub fn update_text_clipboard_required() {
let is_required = sessions::get_sessions()
.iter()
.filter(|s| s.connection_round_state.lock().unwrap().is_connected())
.any(|s| s.is_default() && s.is_text_clipboard_required());
#[cfg(target_os = "android")]
let _ = scrap::android::ffi::call_clipboard_manager_enable_client_clipboard(is_required);
@@ -1417,6 +1426,7 @@ pub fn update_text_clipboard_required() {
pub fn update_file_clipboard_required() {
let is_required = sessions::get_sessions()
.iter()
.filter(|s| s.connection_round_state.lock().unwrap().is_connected())
.any(|s| s.is_default() && s.is_file_clipboard_required());
Client::set_is_file_clipboard_required(is_required);
}
+38
View File
@@ -97,6 +97,16 @@ pub enum EventToUI {
Event(String),
Rgba(usize),
Texture(usize, bool), // (display, gpu_texture)
// A shape's RGBA as bytes: as text it was four times the size and parsed on the UI thread.
// The id stays text, since the peer's ids can exceed Dart's int.
Cursor {
id: String,
hotx: i32,
hoty: i32,
width: i32,
height: i32,
colors: Vec<u8>,
},
}
pub fn host_stop_system_key_propagate(_stopped: bool) {
@@ -201,6 +211,34 @@ pub fn session_start_with_displays(
Ok(())
}
// A cursor shape the core keeps, as RGBA, for a window that has to draw it again.
pub struct CursorShape {
pub hotx: i32,
pub hoty: i32,
pub width: i32,
pub height: i32,
pub colors: Vec<u8>,
}
pub fn session_get_cursor_shape(session_id: SessionID, id: String) -> Option<CursorShape> {
let id = id.parse::<u64>().ok()?;
let session = sessions::get_session_by_session_id(&session_id)?;
let shape = session.cursor_shapes.read().unwrap().get(&id).cloned()?;
match crate::client::io_loop::kept_cursor_rgba(shape) {
Ok(cd) => Some(CursorShape {
hotx: cd.hotx,
hoty: cd.hoty,
width: cd.width,
height: cd.height,
colors: cd.colors.to_vec(),
}),
Err(err) => {
log::warn!("Kept cursor {id} failed to decode: {err}");
None
}
}
}
pub fn session_get_remember(session_id: SessionID) -> Option<bool> {
if let Some(session) = sessions::get_session_by_session_id(&session_id) {
Some(session.get_remember())
+6 -2
View File
@@ -5,7 +5,7 @@ use std::{
};
#[cfg(not(any(target_os = "ios")))]
use crate::{ui_interface::get_builtin_option, Connection};
use crate::{common::API_LOG_INTERVAL, ui_interface::get_builtin_option, Connection};
use hbb_common::{
config::{self, Config, LocalConfig},
log,
@@ -242,7 +242,11 @@ async fn start_hbbs_sync_async() {
}
let modified_at = LocalConfig::get_option("strategy_timestamp").parse::<i64>().unwrap_or(0);
v["modified_at"] = json!(modified_at);
if let Ok(s) = crate::post_request(url.clone(), v.to_string(), "").await {
let response = crate::post_request(url.clone(), v.to_string(), "").await;
if let Err(err) = &response {
hbb_common::throttled_log!(API_LOG_INTERVAL, warn, "Heartbeat failed: {err:?}");
}
if let Ok(s) = response {
if let Ok(mut rsp) = serde_json::from_str::<HashMap::<&str, Value>>(&s) {
if rsp.remove("sysinfo").is_some() {
info_uploaded.uploaded = false;
+135 -1
View File
@@ -540,7 +540,17 @@ pub enum Data {
/// Service -> client: a frame header; the packed BGRA pixels follow via `send_raw()`.
/// CPU-fallback path (no render node, or no transferable dma-buf): pixels cross the wire.
#[cfg(all(target_os = "linux", feature = "drm"))]
DrmFrame { width: u32, height: u32 },
DrmFrame {
width: u32,
height: u32,
/// See `DmabufDesc::plane_rotation`; absent from a producer older than this field.
#[serde(default)]
plane_rotation: Option<u32>,
/// See `DmabufDesc::cursor_pos`: the cursor plane position read right after this frame,
/// or `None` when the cursor is hidden, the read failed or the producer predates the field.
#[serde(default)]
cursor_pos: Option<(i32, i32)>,
},
/// Service -> client: a zero-copy dma-buf frame descriptor. The scanout fd is NOT a field; when
/// `desc.has_fd` it rides an SCM_RIGHTS ancillary message on the same `DrmConn::send_msg`, and
/// there is NO trailing `send_raw()` body. The unprivileged `--server` imports the fd and does
@@ -555,9 +565,29 @@ pub enum Data {
height: u32,
hotx: i32,
hoty: i32,
/// Whether the hotspot came from the driver, or was inferred from the bitmap.
///
/// Absent means the producer predates the field, and the default must then be TRUE, not
/// `bool::default()`. These messages are JSON over a unix socket between two processes
/// that are upgraded separately: an old root service can be streaming to a freshly
/// started `--server`, and its `{"hotx": 12, "hoty": 11}` carries no provenance. Read as
/// `false`, the new consumer would throw that hotspot away and re-infer one from the
/// upright bitmap, moving the cursor on a rotated display for the length of the upgrade.
/// Defaulting to true means "no provenance available, so behave as the old protocol did"
/// -- use the point the producer sent. It is not a claim that the value was measured; a
/// new producer that wants re-inference says `hot_measured: false` explicitly, which
/// serializes, so new-to-new is unaffected.
#[serde(default = "legacy_hot_measured")]
hot_measured: bool,
},
}
/// The default for a `hot_measured` that is not on the wire at all; see the field's docs.
#[cfg(all(target_os = "linux", feature = "drm"))]
fn legacy_hot_measured() -> bool {
true
}
#[tokio::main(flavor = "current_thread")]
pub async fn start(postfix: &str) -> ResultType<()> {
let mut incoming = new_listener(postfix).await?;
@@ -2310,4 +2340,108 @@ mod test {
fn test_select_server_uid_fails_when_multiple_servers_are_ambiguous() {
assert!(select_server_uid_for_user_main_ipc(&[501, 502], None, false).is_err());
}
/// The upgrade window: an old root service is still streaming when a new `--server` starts,
/// and its DrmCursor carries no `hot_measured` at all. Read as `false` the consumer would
/// discard a hotspot the producer did measure and re-infer one from the bitmap, which moves
/// the cursor on a rotated display until the old process is replaced. `bool::default()` is
/// the wrong default here; the right one preserves what the old protocol meant.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[test]
fn a_drm_cursor_without_provenance_keeps_the_hotspot_the_producer_sent() {
// `Data` is adjacently tagged (`tag = "t", content = "c"`), so this is the real shape on
// the socket, not a simplified one.
let legacy =
r#"{"t":"DrmCursor","c":{"id":7,"width":24,"height":24,"hotx":12,"hoty":11}}"#;
let msg: Data = serde_json::from_str(legacy).expect("legacy DrmCursor must deserialize");
match msg {
Data::DrmCursor {
hotx,
hoty,
hot_measured,
..
} => {
assert_eq!((hotx, hoty), (12, 11));
assert!(
hot_measured,
"a message with no provenance field must be treated as the old protocol did, \
i.e. use the hotspot as sent, not re-infer it"
);
}
other => panic!("expected DrmCursor, got {other:?}"),
}
// And a NEW producer that really wants re-inference says so, which serializes: the
// default must not swallow an explicit false.
let modern = r#"{"t":"DrmCursor","c":{"id":7,"width":24,"height":24,"hotx":0,"hoty":0,"hot_measured":false}}"#;
match serde_json::from_str::<Data>(modern).expect("modern DrmCursor must deserialize") {
Data::DrmCursor { hot_measured, .. } => assert!(!hot_measured),
other => panic!("expected DrmCursor, got {other:?}"),
}
}
/// A frame from a producer that predates the plane rotation reads as `None`, in the cpu frame
/// header and in the dma-buf descriptor: the root service and the `--server` are upgraded
/// separately, and `None` keeps the previous rule.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[test]
fn a_frame_without_a_plane_rotation_reads_as_none() {
let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#;
match serde_json::from_str::<Data>(legacy).expect("legacy DrmFrame must deserialize") {
Data::DrmFrame { plane_rotation, .. } => assert_eq!(plane_rotation, None),
other => panic!("expected DrmFrame, got {other:?}"),
}
let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"plane_rotation":4}}"#;
match serde_json::from_str::<Data>(modern).expect("modern DrmFrame must deserialize") {
Data::DrmFrame { plane_rotation, .. } => assert_eq!(plane_rotation, Some(4)),
other => panic!("expected DrmFrame, got {other:?}"),
}
let desc = DmabufDesc {
buffer_id: 0,
width: 4,
height: 4,
format: 0,
modifier: 0,
fb_id: 0,
num_planes: 1,
offsets: [0; 4],
pitches: [16, 0, 0, 0],
hdr_eotf: 0,
hdr_max_nits: 0,
has_fd: false,
plane_rotation: Some(4),
cursor_pos: None,
};
let mut value = serde_json::to_value(&desc).unwrap();
assert!(value.as_object_mut().unwrap().remove("plane_rotation").is_some());
let legacy: DmabufDesc =
serde_json::from_value(value).expect("legacy DmabufDesc must deserialize");
assert_eq!(legacy.plane_rotation, None);
}
/// A frame header from a producer that predates the cursor plane position reads as `None`;
/// a producer that sends one is read back exactly. A pin, not a gate: the consumer only ever
/// measures against `Some`.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[test]
fn a_drm_frame_without_a_cursor_position_reads_as_none() {
let legacy = r#"{"t":"DrmFrame","c":{"width":8,"height":8}}"#;
match serde_json::from_str::<Data>(legacy).expect("legacy DrmFrame must deserialize") {
Data::DrmFrame {
width,
height,
cursor_pos,
..
} => {
assert_eq!((width, height), (8, 8));
assert_eq!(cursor_pos, None);
}
other => panic!("expected DrmFrame, got {other:?}"),
}
let modern = r#"{"t":"DrmFrame","c":{"width":8,"height":8,"cursor_pos":[3,4]}}"#;
match serde_json::from_str::<Data>(modern).expect("modern DrmFrame must deserialize") {
Data::DrmFrame { cursor_pos, .. } => assert_eq!(cursor_pos, Some((3, 4))),
other => panic!("expected DrmFrame, got {other:?}"),
}
}
}
+191 -15
View File
@@ -45,6 +45,21 @@ pub struct DmabufDesc {
pub hdr_max_nits: u32,
/// True: the fd rides this message's SCM_RIGHTS cmsg. False: import-once cache hit for `fb_id`.
pub has_fd: bool,
/// The DRM `rotation` bitmask the primary plane scanned this frame out with, from
/// `drmtap_plane_rotation()` (libdrmtap 0.5.8); a plane without the property is reported as
/// rotate-0. `None` when the library cannot say (older than 0.5.8, nothing bound, or the
/// property set unreadable). A frame from a plane that rotated in hardware is already
/// upright; one from a plane that did not is turned by the output transform. See
/// `frame_transform`.
#[serde(default)]
pub plane_rotation: Option<u32>,
/// Cursor plane position read right after this frame was grabbed, in scanout pixels of the
/// display this stream shows, so a few ms newer than the frame. `None` means the cursor is
/// hidden, the read failed or was rejected, or the producer predates this field. It rides
/// the frame instead of a stream of its own so it cannot queue and cannot backpressure the
/// capture worker; the consumer only acts on a position that held still for several frames.
#[serde(default)]
pub cursor_pos: Option<(i32, i32)>,
}
pub(crate) fn drm_ipc_path() -> String {
@@ -100,6 +115,11 @@ enum DrmProducerMsg {
width: u32,
height: u32,
data: Bytes,
/// See `DmabufDesc::plane_rotation`.
plane_rotation: Option<u32>,
/// See `DmabufDesc::cursor_pos`. The dmabuf path carries it inside the descriptor; this
/// one has no descriptor, so it travels beside the pixels.
cursor_pos: Option<(i32, i32)>,
},
Cursor {
id: u64,
@@ -107,10 +127,112 @@ enum DrmProducerMsg {
height: u32,
hotx: i32,
hoty: i32,
hot_measured: bool,
colors: Vec<u8>,
},
}
/// Put this tick's cursor plane position on the frame it was read next to. The hidden sentinel
/// carries no position; a shape message is left alone.
fn stamp_cursor_pos(msg: &mut DrmProducerMsg, c: Option<&scrap::drm_reader::CursorSnapshot>) {
let pos = c.and_then(|c| (c.id != scrap::drm_reader::HIDDEN_CURSOR_ID).then_some((c.x, c.y)));
match msg {
DrmProducerMsg::Frame { desc, .. } => desc.cursor_pos = pos,
DrmProducerMsg::FrameCpu { cursor_pos, .. } => *cursor_pos = pos,
DrmProducerMsg::Displays(_) | DrmProducerMsg::Cursor { .. } => {}
}
}
#[cfg(test)]
mod cursor_pos_tests {
use super::*;
fn desc() -> DmabufDesc {
DmabufDesc {
buffer_id: 0,
width: 4,
height: 4,
format: 0,
modifier: 0,
fb_id: 0,
num_planes: 1,
offsets: [0; 4],
pitches: [16, 0, 0, 0],
hdr_eotf: 0,
hdr_max_nits: 0,
has_fd: false,
plane_rotation: None,
cursor_pos: None,
}
}
fn snapshot(id: u64) -> scrap::drm_reader::CursorSnapshot {
scrap::drm_reader::CursorSnapshot {
id,
width: 2,
height: 2,
hotx: 0,
hoty: 0,
hot_measured: false,
colors: vec![0; 16],
x: 10,
y: 20,
}
}
#[test]
fn the_plane_position_rides_both_frame_kinds_and_a_hidden_cursor_rides_as_none() {
let visible = snapshot(7);
let hidden = snapshot(scrap::drm_reader::HIDDEN_CURSOR_ID);
let mut frame = DrmProducerMsg::Frame { desc: desc(), fd: None };
stamp_cursor_pos(&mut frame, Some(&visible));
assert!(matches!(&frame, DrmProducerMsg::Frame { desc, .. } if desc.cursor_pos == Some((10, 20))));
stamp_cursor_pos(&mut frame, Some(&hidden));
assert!(matches!(&frame, DrmProducerMsg::Frame { desc, .. } if desc.cursor_pos.is_none()));
let mut cpu = DrmProducerMsg::FrameCpu {
width: 4,
height: 4,
data: Bytes::new(),
plane_rotation: None,
cursor_pos: None,
};
stamp_cursor_pos(&mut cpu, Some(&visible));
assert!(matches!(&cpu, DrmProducerMsg::FrameCpu { cursor_pos: Some((10, 20)), .. }));
stamp_cursor_pos(&mut cpu, None);
assert!(matches!(&cpu, DrmProducerMsg::FrameCpu { cursor_pos: None, .. }));
let mut shape = DrmProducerMsg::Cursor {
id: 7,
width: 2,
height: 2,
hotx: 1,
hoty: 1,
hot_measured: false,
colors: vec![0; 16],
};
stamp_cursor_pos(&mut shape, Some(&visible));
assert!(matches!(&shape, DrmProducerMsg::Cursor { hotx: 1, hoty: 1, .. }));
}
// A producer that predates the field: the descriptor arrives without it and reads as None.
#[test]
fn a_descriptor_without_a_cursor_position_reads_as_none() {
let mut v = serde_json::to_value(desc()).unwrap();
v.as_object_mut().unwrap().remove("cursor_pos").expect("the field is serialized");
let d: DmabufDesc = serde_json::from_value(v).expect("a legacy descriptor must deserialize");
assert_eq!(d.cursor_pos, None);
let d: DmabufDesc = serde_json::from_value(serde_json::to_value(DmabufDesc {
cursor_pos: Some((3, 4)),
..desc()
})
.unwrap())
.unwrap();
assert_eq!(d.cursor_pos, Some((3, 4)));
}
}
struct DrmStopGuard(std::sync::Arc<std::sync::atomic::AtomicBool>);
impl Drop for DrmStopGuard {
fn drop(&mut self) {
@@ -915,6 +1037,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
height,
hotx,
hoty,
hot_measured,
colors,
} => {
conn.send_msg(
@@ -924,6 +1047,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
height,
hotx,
hoty,
hot_measured,
},
None,
)
@@ -957,8 +1081,19 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
width,
height,
data,
plane_rotation,
cursor_pos,
}) => {
conn.send_msg(&Data::DrmFrame { width, height }, None).await?;
conn.send_msg(
&Data::DrmFrame {
width,
height,
plane_rotation,
cursor_pos,
},
None,
)
.await?;
conn.send_raw(data).await?;
credit -= 1; // one frame in flight until the consumer acks it
}
@@ -1027,12 +1162,13 @@ fn drm_capture_worker(
let mut stalled: u32 = 0;
let mut logged_first = false;
while !stop.load(Ordering::Relaxed) {
let grabbed: Option<std::io::Result<DrmProducerMsg>> = if frames_gated.load(Ordering::Relaxed)
let mut grabbed: Option<std::io::Result<DrmProducerMsg>> = if frames_gated.load(Ordering::Relaxed)
{
// `stalled` is left untouched because the device is healthy -- the task bounds this
// state itself (CREDIT_STALL) since our watchdog cannot advance.
None
} else if use_dmabuf {
// Read right after the grab: the library answers for the plane that grab read from.
Some(match reader.grab_desc() {
Ok((fd, d)) => Ok(DrmProducerMsg::Frame {
desc: DmabufDesc {
@@ -1048,21 +1184,38 @@ fn drm_capture_worker(
hdr_eotf: d.hdr_eotf,
hdr_max_nits: d.hdr_max_nits,
has_fd: true, // every exported frame carries its fd; see the send below
plane_rotation: reader.plane_rotation(),
cursor_pos: None, // stamped below, from the one cursor read of this tick
},
fd: Some(fd),
}),
Err(err) => Err(err),
})
} else {
Some(match reader.grab() {
Ok((buf, w, h)) => Ok(DrmProducerMsg::FrameCpu {
width: w as u32,
height: h as u32,
data: Bytes::copy_from_slice(buf),
}),
Err(err) => Err(err),
})
// The mapped buffer borrows the reader: copy it out, then take the rotation the grab
// recorded.
let copied = reader
.grab()
.map(|(buf, w, h)| (Bytes::copy_from_slice(buf), w as u32, h as u32));
Some(copied.map(|(data, width, height)| DrmProducerMsg::FrameCpu {
width,
height,
data,
plane_rotation: reader.plane_rotation(),
cursor_pos: None,
}))
};
// ONE cursor read per tick, and none on a stalled or failed grab: the plane position rides
// the frame it was read next to, and the shape ships when it changes. The position is a
// few ms newer than the frame; the consumer only measures a plane that held still for
// several frames, so that skew never reaches a measurement.
let cursor = match &grabbed {
Some(Err(_)) => None,
_ => reader.cursor(),
};
if let Some(Ok(msg)) = grabbed.as_mut() {
stamp_cursor_pos(msg, cursor.as_ref());
}
match grabbed {
None => {}
Some(Ok(msg)) => {
@@ -1105,7 +1258,7 @@ fn drm_capture_worker(
}
// Ship the cursor shape only when it changes (id is a content hash or the hidden sentinel).
if let Some(c) = reader.cursor() {
if let Some(c) = cursor {
if c.id != last_cursor_id {
last_cursor_id = c.id;
if frame_tx
@@ -1115,6 +1268,7 @@ fn drm_capture_worker(
height: c.height,
hotx: c.hotx,
hoty: c.hoty,
hot_measured: c.hot_measured,
colors: c.colors,
})
.is_err()
@@ -1534,7 +1688,15 @@ mod drm_conn_tests {
let (a, b) = tokio::net::UnixStream::pair().unwrap();
let mut tx = DrmConn::new(a);
let mut rx = DrmConn::new(b);
tx.send_msg(&Data::DrmFrame { width: 1920, height: 1080 }, None)
tx.send_msg(
&Data::DrmFrame {
width: 1920,
height: 1080,
plane_rotation: None,
cursor_pos: None,
},
None,
)
.await
.unwrap();
let (data, fd) = rx.recv_msg().await.unwrap();
@@ -1542,7 +1704,9 @@ mod drm_conn_tests {
data,
Data::DrmFrame {
width: 1920,
height: 1080
height: 1080,
plane_rotation: None,
cursor_pos: None
}
));
assert!(fd.is_none(), "no fd was sent, none must be reported");
@@ -1554,7 +1718,15 @@ mod drm_conn_tests {
let mut tx = DrmConn::new(a);
let mut rx = DrmConn::new(b);
let (rd, wr) = pipe();
tx.send_msg(&Data::DrmFrame { width: 4, height: 4 }, Some(rd.as_fd()))
tx.send_msg(
&Data::DrmFrame {
width: 4,
height: 4,
plane_rotation: None,
cursor_pos: None,
},
Some(rd.as_fd()),
)
.await
.unwrap();
let (_data, fd) = rx.recv_msg().await.unwrap();
@@ -1668,6 +1840,8 @@ mod drm_conn_tests {
let payload = serde_json::to_vec(&Data::DrmFrame {
width: 8,
height: 8,
plane_rotation: None,
cursor_pos: None,
})
.unwrap();
let prefix = (payload.len() as u32).to_be_bytes();
@@ -1679,7 +1853,9 @@ mod drm_conn_tests {
data,
Data::DrmFrame {
width: 8,
height: 8
height: 8,
plane_rotation: None,
cursor_pos: None
}
));
let kept = fd.expect("the first surplus fd must be kept");
+43 -4
View File
@@ -33,7 +33,8 @@ mod lv;
mod nb;
mod nl;
mod pl;
mod ptbr;
mod pt_BR;
mod pt_PT;
mod ro;
mod ru;
mod sc;
@@ -63,7 +64,8 @@ pub const LANGS: &[(&str, &str)] = &[
("nb", "Norsk bokmål"),
("zh-cn", "简体中文"),
("zh-tw", "繁體中文"),
("pt", "Português"),
("pt-pt", "Português (Portugal)"),
("pt-br", "Português (Brasil)"),
("es", "Español"),
("et", "Eesti keel"),
("eu", "Euskara"),
@@ -143,6 +145,21 @@ fn resolve_lang(saved_lang: &str, locale: &str, cjk_fallback: bool) -> String {
.to_owned();
}
}
if lang.is_empty() {
// pt_PT on Linux, pt-PT on mac, pt_PT on Android.
// Per CLDR locale inheritance, every Portuguese-speaking locale
// besides bare "pt" and Brazil's own variants (pt-BR/pt_BR) has
// pt-PT as its parent (Angola, Mozambique, Cape Verde, etc.),
// so it should resolve to European Portuguese.
if locale.starts_with("pt") {
lang = (if locale == "pt" || locale.starts_with("pt-br") || locale.starts_with("pt_br") {
"pt-br"
} else {
"pt-pt"
})
.to_owned();
}
}
if lang.is_empty() {
lang = locale
.split("-")
@@ -185,8 +202,10 @@ pub fn translate_locale(name: String, locale: &str) -> String {
"ru" => ru::T.deref(),
"eo" => eo::T.deref(),
"id" => id::T.deref(),
"br" => ptbr::T.deref(),
"pt" => ptbr::T.deref(),
"br" => pt_BR::T.deref(),
"pt" => pt_BR::T.deref(),
"pt-br" => pt_BR::T.deref(),
"pt-pt" => pt_PT::T.deref(),
"tr" => tr::T.deref(),
"cs" => cs::T.deref(),
"da" => da::T.deref(),
@@ -344,4 +363,24 @@ mod test {
assert_eq!(f("", "zh_TW", false), "zh-tw");
assert_eq!(f("", "ja-JP", false), "ja");
}
#[test]
fn test_resolve_lang_detects_pt_pt_and_pt_br_from_locale() {
use super::resolve_lang as f;
assert_eq!(f("", "pt-PT", false), "pt-pt");
assert_eq!(f("", "pt_PT", false), "pt-pt");
assert_eq!(f("", "pt-BR", false), "pt-br");
assert_eq!(f("", "pt_BR", false), "pt-br");
assert_eq!(f("", "pt-AO", false), "pt-pt");
assert_eq!(f("", "pt-MZ", false), "pt-pt");
}
#[test]
fn test_resolve_lang_saved_lang_takes_precedence_over_locale() {
use super::resolve_lang as f;
assert_eq!(f("pt-br", "pt-PT", false), "pt-br");
assert_eq!(f("pt-pt", "pt-BR", false), "pt-pt");
}
}
+1 -1
View File
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk no ha podido cargar un componente de GStreamer necesario para capturar la pantalla ({})"),
("Relay fallback delay in seconds", "Retardo antes de usar el relé en segundos"),
("relay-fallback-delay-tip", "Cuánto tiempo espera una conexión de relé ya establecida a la conexión directa WebRTC antes de usarse en su lugar. Auméntelo para dar más tiempo a una conexión directa lenta; redúzcalo para recurrir antes al relé en redes donde no es posible una conexión directa. Déjelo vacío para el valor predeterminado de 2.5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Para comenzar una llamada de voz activar \"Captura de audio\" en la página \"Compartir pantalla\".")
].iter().cloned().collect();
}
+42 -42
View File
@@ -4,7 +4,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Status", "Estado"),
("Your Desktop", "Ambiente de Trabalho"),
("desk_tip", "O seu Ambiente de Trabalho pode ser acedido com este ID e palavra-passe."),
("Password", "Senha"),
("Password", "Palavra-passe"),
("Ready", "Pronto"),
("Established", "Estabelecido"),
("connecting_status", "A ligar à rede do RustDesk..."),
@@ -21,7 +21,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Confirmation", "Confirmação"),
("TCP tunneling", "Túnel TCP"),
("Remove", "Remover"),
("Refresh random password", "Actualizar palavra-chave"),
("Refresh random password", "Actualizar palavra-passe"),
("Set your own password", "Configure a sua palavra-passe"),
("Enable keyboard/mouse", "Activar Teclado/Rato"),
("Enable clipboard", "Activar Área de Transferência"),
@@ -68,10 +68,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Close", "Fechar"),
("Retry", "Tentar novamente"),
("OK", "Confirmar"),
("Password Required", "Palavra-chave Necessária"),
("Please enter your password", "Por favor introduza a sua palavra-chave"),
("Remember password", "Memorizar palavra-chave"),
("Wrong Password", "Palavra-chave inválida"),
("Password Required", "Palavra-passe Necessária"),
("Please enter your password", "Por favor introduza a sua palavra-passe"),
("Remember password", "Memorizar palavra-passe"),
("Wrong Password", "Palavra-passe inválida"),
("Do you want to enter again?", "Deseja tentar novamente??"),
("Connection Error", "Erro de Ligação"),
("Error", "Erro"),
@@ -102,9 +102,9 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Unselect All", "Desmarcar todos"),
("Empty Directory", "Directório Vazio"),
("Not an empty directory", "Directório não está vazio"),
("Are you sure you want to delete this file?", "Tem certeza que deseja apagar este ficheiro?"),
("Are you sure you want to delete this empty directory?", "Tem certeza que deseja apagar este directório vazio?"),
("Are you sure you want to delete the file of this directory?", "Tem certeza que deseja apagar este ficheiro deste directório?"),
("Are you sure you want to delete this file?", "Tem a certeza que deseja apagar este ficheiro?"),
("Are you sure you want to delete this empty directory?", "Tem a certeza que deseja apagar este diretório vazio?"),
("Are you sure you want to delete the file of this directory?", "Tem a certeza que deseja apagar este ficheiro deste diretório?"),
("Do this for all conflicts", "Fazer isto para todos os conflictos"),
("This is irreversible!", "Isto é irreversível!"),
("Deleting", "A apagar"),
@@ -142,21 +142,21 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Failed to connect to relay server", "Falha ao ligar ao servidor de relay"),
("Failed to connect via rendezvous server", "Falha ao ligar ao servidor de rendezvous"),
("Failed to connect via relay server", "Falha ao ligar através do servidor de relay"),
("Failed to make direct connection to remote desktop", "Falha ao fazer ligação directa ao desktop remoto"),
("Set Password", "Definir palavra-chave"),
("OS Password", "Senha do SO"),
("Failed to make direct connection to remote desktop", "Falha ao fazer ligação directa ao ambiente de trabalho remoto"),
("Set Password", "Definir palavra-passe"),
("OS Password", "Palavra-Passe do SO"),
("install_tip", "Devido ao UAC, o RustDesk não funciona correctamente em alguns casos. Para evitar o UAC, por favor clique no botão abaixo para instalar o RustDesk no sistema."),
("Click to upgrade", "Clique para atualizar"),
("Configure", "Configurar"),
("config_acc", "Para controlar o seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Acessibilidade\"."),
("config_screen", "Para aceder ao seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Gravar a Tela\"/"),
("config_screen", "Para aceder ao seu Ambiente de Trabalho remotamente, é preciso conceder ao RustDesk permissões de \"Gravar o Ecrã\"."),
("Installing ...", "A Instalar ..."),
("Install", "Instalar"),
("Installation", "Instalação"),
("Installation Path", "Caminho da Instalação"),
("Create start menu shortcuts", "Criar atalhos no menu iniciar"),
("Create desktop icon", "Criar ícone no ambiente de trabalho"),
("agreement_tip", "Ao iniciar a instalação, você concorda com o acordo de licença."),
("agreement_tip", "Ao iniciar a instalação, está a concordar com o acordo de licença."),
("Accept and Install", "Aceitar e Instalar"),
("End-user license agreement", "Acordo de licença do utilizador final"),
("Generating ...", "A Gerar ..."),
@@ -170,13 +170,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Local Port", "Porta Local"),
("Local Address", "Endereço local"),
("Change Local Port", "Alterar porta local"),
("setup_server_tip", "Para uma ligação mais rápida, por favor configure seu próprio servidor"),
("setup_server_tip", "Para uma ligação mais rápida, por favor configure o seu próprio servidor"),
("Too short, at least 6 characters.", "Muito curto, pelo menos 6 caracteres."),
("The confirmation is not identical.", "A confirmação não é idêntica."),
("Permissions", "Permissões"),
("Accept", "Aceitar"),
("Dismiss", "Dispensar"),
("Disconnect", "Desconectar"),
("Disconnect", "Desligar"),
("Enable file copy and paste", "Permitir copiar e mover ficheiros"),
("Connected", "Ligado"),
("Direct and encrypted connection", "Ligação directa e encriptada"),
@@ -184,10 +184,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Direct and unencrypted connection", "Ligação direta e não encriptada"),
("Relayed and unencrypted connection", "Ligação via relay e não encriptada"),
("Enter Remote ID", "Introduza o ID Remoto"),
("Enter your password", "Introduza a sua palavra-chave"),
("Enter your password", "Introduza a sua palavra-passe"),
("Logging in...", "A efectuar Login..."),
("Enable RDP session sharing", "Activar partilha de sessão RDP"),
("Auto Login", "Login Automático (Somente válido se você activou \"Bloquear após o fim da sessão\")"),
("Auto Login", "Login Automático (Apenas válido se tiver activado \"Bloquear após o fim da sessão\")"),
("Enable direct IP access", "Activar Acesso IP Directo"),
("Rename", "Renomear"),
("Space", "Espaço"),
@@ -197,7 +197,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Please enter the folder name", "Por favor introduza o nome do diretório"),
("Fix it", "Reparar"),
("Warning", "Aviso"),
("Login screen using Wayland is not supported", "Tela de Login com Wayland não é suportada"),
("Login screen using Wayland is not supported", "Ecrã de Início de Sessão com Wayland não é suportado"),
("Reboot required", "Reinicialização necessária"),
("Unsupported display server", "Servidor de display não suportado"),
("x11 expected", "x11 em falha"),
@@ -209,7 +209,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Enable remote configuration modification", "Habilitar modificações de configuração remotas"),
("Run without install", "Executar sem instalar"),
("Connect via relay", "Ligar via relay"),
("Always connect via relay", "Sempre conectar via relay"),
("Always connect via relay", "Ligar sempre via relay"),
("whitelist_tip", "Somente IPs na whitelist podem me acessar"),
("Login", "Login"),
("Verify", "Verificar"),
@@ -226,11 +226,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Unselect all tags", "Desselecionar todas as tags"),
("Network error", "Erro de rede"),
("Username missed", "Nome de utilizador em falta"),
("Password missed", "Palavra-chave em falta"),
("Wrong credentials", "Nome de utilizador ou palavra-chave incorrectos"),
("Password missed", "Palavra-passe em falta"),
("Wrong credentials", "Nome de utilizador ou palavra-passe incorrectos"),
("The verification code is incorrect or has expired", "O código de verificação está incorreto ou expirou"),
("Edit Tag", "Editar Tag"),
("Forget Password", "Esquecer Palavra-chave"),
("Forget Password", "Esquecer Palavra-passe"),
("Favorites", "Favoritos"),
("Add to Favorites", "Adicionar aos Favoritos"),
("Remove from Favorites", "Remover dos Favoritos"),
@@ -243,7 +243,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Remote ID", "ID Remoto"),
("Paste", "Colar"),
("Paste here?", "Colar aqui?"),
("Are you sure to close the connection?", "Tem certeza que deseja fechar a ligação?"),
("Are you sure to close the connection?", "Tem a certeza que deseja fechar a ligação?"),
("Download new version", "Transferir nova versão"),
("Touch mode", "Modo toque"),
("Mouse mode", "Modo rato"),
@@ -258,10 +258,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Three-Finger vertically", "Três dedos verticalmente"),
("Mouse Wheel", "Roda do rato"),
("Two-Finger Move", "Mover com dois dedos"),
("Canvas Move", "Mover Tela"),
("Canvas Move", "Mover Ecrã"),
("Pinch to Zoom", "Clique para ampliar"),
("Canvas Zoom", "Zoom na Tela"),
("Reset canvas", "Reiniciar tela"),
("Canvas Zoom", "Zoom no Ecrã"),
("Reset canvas", "Reiniciar ecrã"),
("No permission of file transfer", "Sem permissões de transferência de ficheiro"),
("Note", "Nota"),
("Connection", "Ligação"),
@@ -276,7 +276,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Do you accept?", "Aceita?"),
("Open System Setting", "Abrir Configurações do Sistema"),
("How to get Android input permission?", "Como activar a permissão de entrada do Android?"),
("android_input_permission_tip1", "Para que um dispositivo remoto controle o seu dispositivo Android via rato ou toque, você precisa permitir que o RustDesk use o serviço \"Acessibilidade\"."),
("android_input_permission_tip1", "Para que um dispositivo remoto controle o seu dispositivo Android via rato ou toque, é necessário permitir que o RustDesk use o serviço \"Acessibilidade\"."),
("android_input_permission_tip2", "Por favor vá para a próxima página de configuração do sistema, encontre e entre [Serviços Instalados], ACTIVE o serviço [RustDesk Input]."),
("android_new_connection_tip", "Nova requisição de controle recebida, solicita o controle do seu dispositivo atual."),
("android_service_will_start_tip", "Activar a Captura de Ecran irá automaticamente inicializar o serviço, permitindo que outros dispositivos solicitem uma ligação deste dispositivo."),
@@ -307,18 +307,18 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Legacy mode", "Modo antigo"),
("Map mode", "Modo de mapeamento"),
("Translate mode", "Modo de tradução"),
("Use permanent password", "Utilizar palavra-chave permanente"),
("Use permanent password", "Utilizar palavra-passe permanente"),
("Use both passwords", "Utilizar ambas as palavras-chave"),
("Set permanent password", "Definir palavra-chave permanente"),
("Set permanent password", "Definir palavra-passe permanente"),
("Enable remote restart", "Activar reiniciar remoto"),
("Restart remote device", "Reiniciar Dispositivo Remoto"),
("Are you sure you want to restart", "Tem a certeza que pretende reiniciar"),
("Restarting remote device", "A reiniciar sistema remoto"),
("remote_restarting_tip", "O dispositivo remoto está a reiniciar, feche esta caixa de mensagem e volte a ligar com a palavra-passe permanente daqui a momentos"),
("Copied", "Copiado"),
("Exit Fullscreen", "Sair da tela cheia"),
("Fullscreen", "Tela cheia"),
("Mobile Actions", "Ações para celular"),
("Exit Fullscreen", "Sair do Ecrã Inteiro"),
("Fullscreen", "Ecrã Inteiro"),
("Mobile Actions", "Ações para telemóvel"),
("Select Monitor", "Selecionar monitor"),
("Control Actions", "Ações de controle"),
("Display Settings", "Configurações do visor"),
@@ -327,10 +327,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Scroll Style", "Estilo de rolagem"),
("Show Toolbar", "Mostrar barra de ferramentas"),
("Hide Toolbar", "Ocultar barra de ferramentas"),
("Direct Connection", "Conexão direta"),
("Relay Connection", "Conexão de relé"),
("Secure Connection", "Conexão segura"),
("Insecure Connection", "Conexão insegura"),
("Direct Connection", "Ligação direta"),
("Relay Connection", "Ligação de relay"),
("Secure Connection", "Ligação segura"),
("Insecure Connection", "Ligação insegura"),
("Scale original", "Escala original"),
("Scale adaptive", "Escala adaptável"),
("General", "Geral"),
@@ -377,10 +377,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Full Access", "Controlo total"),
("Screen Share", "Partilha de ecrã"),
("ubuntu-21-04-required", "Wayland requer Ubuntu 21.04 ou versão superior."),
("wayland-requires-higher-linux-version", "Wayland requer uma versão superior da distribuição linux. Por favor, tente o desktop X11 ou mude seu sistema operacional."),
("wayland-requires-higher-linux-version", "Wayland requer uma versão superior da distribuição Linux. Por favor, tente o ambiente de trabalho X11 ou mude o seu sistema operativo."),
("xdp-portal-unavailable", "A captura de ecrã do Wayland falhou. O XDG Desktop Portal poderá ter falhado ou estar indisponível. Tente reiniciá-lo com `systemctl --user restart xdg-desktop-portal`."),
("JumpLink", "View"),
("Please Select the screen to be shared(Operate on the peer side).", "Por favor, selecione a tela a ser compartilhada (operar no lado do peer)."),
("Please Select the screen to be shared(Operate on the peer side).", "Por favor, selecione o ecrã a partilhar (operar no lado do par)."),
("Show RustDesk", "Mostrar RustDesk"),
("This PC", "Este PC"),
("or", "ou"),
@@ -760,11 +760,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("whitelist_cidr_tip", "A notação CIDR é suportada, por exemplo 192.168.1.0/24"),
("Continue", "Continuar"),
("Browser didn't open? Use the url below to sign in.", "O navegador não abriu? Utilize o URL abaixo para iniciar sessão."),
("Lock canvas", "Bloquear tela"),
("Lock canvas", "Bloquear ecrã"),
("Sync clipboard between sessions", "Sincronizar área de transferência entre sessões"),
("sync-clipboard-between-sessions-tip", "O texto ou as imagens copiados numa sessão remota também são enviados para a área de transferência das suas outras sessões ligadas."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Uma aplicação no terminal pretende copiar texto para a área de transferência deste dispositivo. Se autorizada, esta permissão aplica-se a aplicações de terminal em todas as ligações até a desativar nas Configurações. A cópia e colagem manuais não são afetadas."),
("Allow terminal apps to copy to clipboard", "Permitir cópia do terminal para a área de transferência"),
("Enable", "Ativar"),
("Reuse one connection for port forwarding", "Reutilizar uma ligação para o reencaminhamento de portas"),
("port-forward-mux-tip", "Encaminhar todas as ligações de um reencaminhamento de portas por uma única ligação ao outro computador, em vez de ligar e iniciar sessão novamente para cada uma."),
+3 -3
View File
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Bloca sa tela"),
("Sync clipboard between sessions", "Sincroniza sa punta de billete intre is sessiones"),
("sync-clipboard-between-sessions-tip", "Su testu o is immàgines copiadas in una sessione remota sunt imbiadas fintzas a sa punta de billete de is àteras sessiones connètidas."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Un’aplicatzione in su terminale bolet copiare testu in sa punta de billete de custu dispositivu. Si benit frunidu, custu permissu s’àplicat a sas aplicatziones de terminale in totu sas connessiones finas a cando non nche l’istudas in sas Impostatziones. Sas operatziones de còpia e incolla manuales non benint influentzadas."),
("Allow terminal apps to copy to clipboard", "Permite a sas aplicatziones de terminale de copiare in punta de billete"),
("Enable", "Abìlita"),
("Reuse one connection for port forwarding", "Torra a impreare una connessione pro s'imbiu de is portas"),
("port-forward-mux-tip", "Totu is connessiones de un'imbiu de portas passant in una connessione ebbia a s'àteru computadore, in logu de si connètere e intrare torra pro dontzi una."),
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk no at pòdidu carrigare unu cumponente de GStreamer netzessàriu pro registrare sa schermada ({})"),
("Relay fallback delay in seconds", "Tardu prima de impreare su relè in segundos"),
("relay-fallback-delay-tip", "Cantu tempus una connessione de relè giai istabilida abetat sa connessione direta WebRTC prima de èssere impreada in su postu suo. Aumenta pro dare prus tempus a una connessione direta lenta; diminuì pro colare prima a su relè in sas retes in ue non si podet fàghere una connessione direta. Lassa bòidu pro su valore predefinidu de 2.5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Pro aviare una mutida de boghe, ativa in sa pàgina \"Cumpartzidura de ischermu\" s’elementu \"Catura de s’àudio\".")
].iter().cloned().collect();
}
+3 -3
View File
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "鎖定畫布"),
("Sync clipboard between sessions", "在工作階段間同步剪貼簿"),
("sync-clipboard-between-sessions-tip", "在一個遠端工作階段中複製的文字或圖片也會傳送到其他已連線工作階段的剪貼簿。"),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "終端機中的應用程式想要將文字複製到本機的剪貼簿。若授權,此權限將套用於所有連線中的終端機應用程式,直到您在設定中關閉為止。手動複製與貼上不受影響。"),
("Allow terminal apps to copy to clipboard", "允許終端機應用程式複製到剪貼簿"),
("Enable", "啟用"),
("Reuse one connection for port forwarding", "連接埠轉送重複使用同一條連線"),
("port-forward-mux-tip", "同一條連接埠轉送規則上的所有連線共用一條到對方的連線,而不是每條連線都重新連線並登入一次。"),
@@ -780,6 +780,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("RustDesk could not load a GStreamer component needed for screen capture ({})", "RustDesk 無法載入螢幕擷取所需的 GStreamer 元件 ({})"),
("Relay fallback delay in seconds", "回退到中繼前的等待時間(秒)"),
("relay-fallback-delay-tip", "已經建立的中繼連線會等待直連的 WebRTC 多久,超過這個時間就改用中繼。調大可以讓較慢的直連有更多機會勝出;調小則在無法直連的網路上更快回退到中繼。留空表示使用預設值 2.5 秒。"),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "若要開始語音通話,請在「僅分享螢幕畫面」頁面啟用「音訊錄製」。")
].iter().cloned().collect();
}
+9 -52
View File
@@ -559,6 +559,9 @@ pub fn get_cursor() -> ResultType<Option<u64>> {
autoreleasepool(|| unsafe_get_cursor())
}
// The seed names a change of cursor, not a cursor: the shape is named by its content once
// captured, as on every platform. A fingerprint of its size, hotspot and two pixels named the open
// and the closed hand alike, and the arrows with a badge, so a switch between them went unsent.
fn unsafe_get_cursor() -> ResultType<Option<u64>> {
unsafe {
let seed = CGSCurrentCursorSeed();
@@ -566,9 +569,8 @@ fn unsafe_get_cursor() -> ResultType<Option<u64>> {
return Ok(None);
}
LATEST_SEED = seed;
Ok(Some(seed as u32 as u64))
}
let c = get_cursor_id()?;
Ok(Some(c.1))
}
pub fn reset_input_cache() {
@@ -577,53 +579,6 @@ pub fn reset_input_cache() {
}
}
fn get_cursor_id() -> ResultType<(id, u64)> {
unsafe {
let c: id = msg_send![class!(NSCursor), currentSystemCursor];
if c == nil {
bail!("Failed to call [NSCursor currentSystemCursor]");
}
let hotspot: NSPoint = msg_send![c, hotSpot];
let img: id = msg_send![c, image];
if img == nil {
bail!("Failed to call [NSCursor image]");
}
let size: NSSize = msg_send![img, size];
let tif: id = msg_send![img, TIFFRepresentation];
if tif == nil {
bail!("Failed to call [NSImage TIFFRepresentation]");
}
let rep: id = msg_send![class!(NSBitmapImageRep), imageRepWithData: tif];
if rep == nil {
bail!("Failed to call [NSBitmapImageRep imageRepWithData]");
}
let rep_size: NSSize = msg_send![rep, size];
let mut hcursor =
size.width + size.height + hotspot.x + hotspot.y + rep_size.width + rep_size.height;
let x = (rep_size.width * hotspot.x / size.width) as usize;
let y = (rep_size.height * hotspot.y / size.height) as usize;
for i in 0..2 {
let mut x2 = x + i;
if x2 >= rep_size.width as usize {
x2 = rep_size.width as usize - 1;
}
let mut y2 = y + i;
if y2 >= rep_size.height as usize {
y2 = rep_size.height as usize - 1;
}
let color: id = msg_send![rep, colorAtX:x2 y:y2];
if color != nil {
let r: f64 = msg_send![color, redComponent];
let g: f64 = msg_send![color, greenComponent];
let b: f64 = msg_send![color, blueComponent];
let a: f64 = msg_send![color, alphaComponent];
hcursor += (r + g + b + a) * (255 << i) as f64;
}
}
Ok((c, hcursor as _))
}
}
pub fn get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
autoreleasepool(|| unsafe_get_cursor_data(hcursor))
}
@@ -631,9 +586,11 @@ pub fn get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
// https://github.com/stweil/OSXvnc/blob/master/OSXvnc-server/mousecursor.c
fn unsafe_get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
unsafe {
let (c, hcursor2) = get_cursor_id()?;
if hcursor != hcursor2 {
bail!("cursor changed");
// The cursor shown is captured even if it changed after get_cursor read the seed: the
// content names the shape, and that change moved the seed on, so the next poll captures it.
let c: id = msg_send![class!(NSCursor), currentSystemCursor];
if c == nil {
bail!("Failed to call [NSCursor currentSystemCursor]");
}
let hotspot: NSPoint = msg_send![c, hotSpot];
let img: id = msg_send![c, image];
+32
View File
@@ -0,0 +1,32 @@
pub(crate) fn mobile_wheel_delta(xy: (i32, i32), reverse_mouse_wheel: &str) -> (i32, i32) {
if reverse_mouse_wheel == "Y" {
(xy.0.saturating_neg(), xy.1.saturating_neg())
} else {
xy
}
}
#[cfg(test)]
mod tests {
use super::mobile_wheel_delta;
#[test]
fn reverses_both_axes_when_enabled() {
assert_eq!(mobile_wheel_delta((2, -3), "Y"), (-2, 3));
assert_eq!(mobile_wheel_delta((0, 4), "Y"), (0, -4));
}
#[test]
fn preserves_both_axes_when_disabled() {
assert_eq!(mobile_wheel_delta((2, -3), "N"), (2, -3));
assert_eq!(mobile_wheel_delta((2, -3), ""), (2, -3));
}
#[test]
fn reversing_minimum_delta_does_not_overflow() {
assert_eq!(
mobile_wheel_delta((i32::MIN, i32::MIN), "Y"),
(i32::MAX, i32::MAX)
);
}
}
+8
View File
@@ -228,6 +228,14 @@ mod tests {
#[cfg(target_os = "macos")]
macos::is_process_trusted(false);
}
// A macOS capture takes the cursor shown, whatever seed it is asked for.
#[cfg(target_os = "macos")]
{
macos::reset_input_cache();
if let Some(change) = get_cursor().unwrap() {
assert!(get_cursor_data(change.wrapping_add(1)).is_ok());
}
}
}
#[test]
fn test_get_cursor_pos() {
+11
View File
@@ -97,6 +97,17 @@ mod pa_impl {
pub async fn run(sp: EmptyExtraFieldService) -> ResultType<()> {
hbb_common::sleep(0.1).await; // one moment to wait for _pa ipc
RESTARTING.store(false, Ordering::SeqCst);
// The `_pa` ipc is served by the cm, which is not started at a login
// screen, so connecting there fails and logs an error every second.
// Wait here instead; audio starts once a user logs in. Poll slowly,
// `is_prelogin` spawns a process on every call.
#[cfg(target_os = "linux")]
while crate::platform::is_prelogin() {
if !sp.ok() {
return Ok(());
}
hbb_common::sleep(3.).await;
}
#[cfg(target_os = "linux")]
let mut stream = crate::ipc::connect(1000, "_pa").await?;
let mut encoder = AudioEncoder::new(Encoder::new(
+7 -6
View File
@@ -1,6 +1,6 @@
use super::*;
#[cfg(not(target_os = "android"))]
use crate::clipboard::clipboard_listener;
use crate::clipboard::clipboard_listener::{self, ClipboardEvent};
#[cfg(not(target_os = "android"))]
pub use crate::clipboard::{ClipboardContext, ClipboardSide};
pub use crate::clipboard::{CLIPBOARD_INTERVAL as INTERVAL, CLIPBOARD_NAME as NAME};
@@ -15,8 +15,6 @@ pub use crate::{
use base::config::keys;
#[cfg(all(feature = "unix-file-copy-paste", target_os = "linux"))]
use clipboard::platform::unix::fuse::{init_fuse_context, uninit_fuse_context};
#[cfg(not(target_os = "android"))]
use clipboard_master::CallbackResult;
#[cfg(target_os = "android")]
use hbb_common::config::option2bool;
#[cfg(target_os = "android")]
@@ -81,7 +79,7 @@ fn run(sp: EmptyExtraFieldService) -> ResultType<()> {
while sp.ok() {
match rx_cb_result.recv_timeout(Duration::from_millis(INTERVAL)) {
Ok(CallbackResult::Next) => {
Ok(ClipboardEvent::Changed) => {
#[cfg(feature = "unix-file-copy-paste")]
if sp.name() == FILE_NAME {
handler.check_clipboard_file();
@@ -91,11 +89,14 @@ fn run(sp: EmptyExtraFieldService) -> ResultType<()> {
sp.send(msg);
}
}
Ok(CallbackResult::Stop) => {
// Host startup state must not supersede a client's explicit initial snapshot.
#[cfg(all(target_os = "linux", feature = "unix-file-copy-paste"))]
Ok(ClipboardEvent::InitialSelection) => {}
Ok(ClipboardEvent::Stop) => {
log::debug!("Clipboard listener stopped");
break;
}
Ok(CallbackResult::StopWithError(err)) => {
Ok(ClipboardEvent::StopWithError(err)) => {
bail!("Clipboard listener stopped with error: {}", err);
}
Err(RecvTimeoutError::Timeout) => {}
+27 -1
View File
@@ -914,6 +914,11 @@ impl Connection {
if !conn.is_remote() {
continue;
}
// The CM can send MonitorReady before this connection is authorized.
if !conn.authorized {
log::debug!("Discarding file clipboard message before authorization");
continue;
}
match clip {
clipboard::ClipboardFile::Files { files } => {
let files = files.into_iter().map(|(f, s)| {
@@ -3387,13 +3392,19 @@ impl Connection {
.collect::<Vec<(String, i64)>>(),
json!({}),
);
} else if is_file_data_request(&clip)
&& crate::get_builtin_option(keys::OPTION_ONE_WAY_FILE_TRANSFER) == "Y"
{
// One-way file transfer: never serve this side's clipboard files to the peer.
} else if let Some(clip) = msg_2_clip(clip) {
#[cfg(target_os = "windows")]
{
self.send_to_cm(ipc::Data::ClipboardFile(clip));
}
#[cfg(feature = "unix-file-copy-paste")]
if crate::is_support_file_copy_paste(&self.lr.version) {
if crate::is_support_file_copy_paste(&self.lr.version)
&& self.file_transfer_enabled()
{
let mut out_msgs = vec![];
#[cfg(target_os = "macos")]
@@ -3990,6 +4001,17 @@ impl Connection {
self.send(msg_out).await;
}
}
// Only to a connection the cursor service would send the shape to.
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Some(misc::Union::RequestCursorData(id)) => {
if self.is_remote()
&& (self.peer_keyboard_enabled() || self.show_remote_cursor)
{
if let Some(msg) = input_service::cursor_data_message(id) {
self.send((*msg).clone()).await;
}
}
}
_ => {}
},
Some(message::Union::AudioFrame(frame)) => {
@@ -6108,6 +6130,10 @@ impl Connection {
#[cfg(feature = "unix-file-copy-paste")]
async fn handle_file_clip(&mut self, clip: clipboard::ClipboardFile) {
if !self.authorized {
log::debug!("Discarding file clipboard message before authorization");
return;
}
let is_stopping_allowed = clip.is_stopping_allowed();
let file_transfer_enabled = self.file_transfer_enabled();
let stop = is_stopping_allowed && !file_transfer_enabled;
+335 -46
View File
@@ -136,11 +136,147 @@ impl WaylandLayout {
#[cfg(target_os = "linux")]
static WAYLAND_LAYOUT_DRIFTED: AtomicBool = AtomicBool::new(false);
/// True while the layout has drifted from the session-init baseline AND the matching uinput
/// range was applied, which is the condition `remap_wayland_uinput_coord` remaps under. While
/// it holds, an injected point has been moved onto the live layout and no longer lives in the
/// layout the DRM cursor calibration resolved its geometry from, so the calibration declines
/// to measure. It is a secondary guard: the snapshot generation is what stops a measurement
/// once the layout moved, and this covers the window in which the remap is active and the
/// promotion that re-baselines is still owed. Both are written by the poll below, so a layout
/// change is seen up to one check interval late; inside that window the bitmap bound in the
/// measurement is the only guard, and a value that passes it is replaced by the next confirmed
/// pair. A failed range apply stores false, and then nothing is remapped either.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(crate) fn wayland_layout_drifted() -> bool {
WAYLAND_LAYOUT_DRIFTED.load(Ordering::Relaxed)
}
#[cfg(target_os = "linux")]
pub(super) fn set_wayland_uinput_rect(rect: (i32, i32, i32, i32)) {
WAYLAND_UINPUT_RECT.lock().unwrap().rect = Some(rect);
}
/// The layout generation whose uinput range the device runs, and a count raised when an apply
/// starts and when the device acknowledges one. The DRM cursor calibration measures only under its
/// own generation and against a sample injected under the current count: a stale range maps the
/// point elsewhere, and two stops share that error, so agreement cannot reject it.
#[cfg(all(target_os = "linux", feature = "drm"))]
static INPUT_MAP_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
#[cfg(all(target_os = "linux", feature = "drm"))]
static INPUT_MAP_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Read before `input_map_epoch`: seeing a generation means seeing the count its adoption raised.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(crate) fn input_map_gen() -> u64 {
INPUT_MAP_GEN.load(Ordering::Acquire)
}
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(crate) fn input_map_epoch() -> u64 {
INPUT_MAP_EPOCH.load(Ordering::Relaxed)
}
/// The device acknowledged a range for generation `gen` (on the session-init path, the one read
/// before the rect was computed, which can predate a move the poll has not seen yet). Samples
/// injected before now were mapped by the previous range; the count moves first.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(super) fn note_input_map_adopted(gen: u64) {
INPUT_MAP_EPOCH.fetch_add(1, Ordering::Relaxed);
INPUT_MAP_GEN.store(gen, Ordering::Release);
}
/// The range the device already runs fits the layout of `gen`. Not an adoption: the samples
/// injected under it stay valid.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(super) fn note_input_map_ready(gen: u64) {
INPUT_MAP_GEN.store(gen, Ordering::Release);
}
/// An apply is starting: until the device acknowledges it no range is ready, samples from before
/// now do not count, and the recorded rect is forgotten, so a failed or timed-out apply (the device
/// may still take the range late) leaves nothing ready and the next check applies again.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(super) fn note_input_map_unknown() {
WAYLAND_UINPUT_RECT.lock().unwrap().rect = None;
note_input_map_adopted(u64::MAX);
}
/// The layout poll asks the apply thread for a job every check, so a thread that cannot start fails
/// every one of them.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(super) const UINPUT_APPLY_LOG_INTERVAL: Duration = Duration::from_secs(600);
/// Runs `job` on the one thread that checks, applies and records uinput ranges on the DRM paths,
/// after every job asked for before it. Two applies must not overlap: the uinput service keeps the
/// range of whichever request reached it last, and that must be the one recorded. The caller waits
/// for the answer holding no lock; the job gets the runtime of that thread for its IPC.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(super) fn run_uinput_apply<R: Send + 'static>(
job: impl FnOnce(&tokio::runtime::Runtime) -> R + Send + 'static,
) -> tokio::sync::oneshot::Receiver<R> {
type Job = Box<dyn FnOnce(&tokio::runtime::Runtime) + Send>;
static JOBS: Mutex<Option<std::sync::mpsc::Sender<Job>>> = Mutex::new(None);
fn start() -> Option<std::sync::mpsc::Sender<Job>> {
let (tx, rx) = std::sync::mpsc::channel::<Job>();
let spawned = std::thread::Builder::new()
.name("uinput-apply".to_owned())
.spawn(move || {
let rt = match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(err) => {
hbb_common::throttled_log!(
UINPUT_APPLY_LOG_INTERVAL,
error,
"uinput apply thread: failed to build a runtime: {err}"
);
return;
}
};
for job in rx {
job(&rt);
}
});
match spawned {
Ok(_) => Some(tx),
Err(err) => {
hbb_common::throttled_log!(
UINPUT_APPLY_LOG_INTERVAL,
error,
"failed to start the uinput apply thread: {err}"
);
None
}
}
}
let (tx, rx) = tokio::sync::oneshot::channel();
let job: Job = Box::new(move |rt| {
let _ = tx.send(job(rt));
});
// A thread that never started or is gone is started again when a job finds it gone, so one
// failure does not stop every later apply. A job that cannot be sent, or that was queued as the
// thread went away, is dropped with its `tx`, and the caller reads an error.
let mut jobs = JOBS.lock().unwrap();
let job = match jobs.as_ref() {
Some(sender) => match sender.send(job) {
Ok(()) => return rx,
Err(std::sync::mpsc::SendError(job)) => job,
},
None => job,
};
*jobs = start();
if let Some(tx) = jobs.as_ref() {
let _ = tx.send(job);
}
rx
}
/// The generation a range is recorded under: none for the raw DRM union, which is not a compositor
/// layout any stream was built from.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(super) fn input_map_label(gen: u64, from_compositor: bool) -> u64 {
if from_compositor {
gen
} else {
u64::MAX
}
}
// The uinput ABS range currently programmed into the device, for the DRM path's "reapply only when
// it changed" check. The PipeWire path compares it inline in refresh_wayland_uinput_rect_if_changed.
#[cfg(all(target_os = "linux", feature = "drm"))]
@@ -249,60 +385,113 @@ fn refresh_wayland_uinput_rect_if_changed() {
}
#[cfg(not(feature = "drm"))]
let _ = live_changed;
// At a login screen the DRM path owns the rect; only the range/remap update is skipped,
// the snapshot invalidation above must still run (a greeter session has no other trigger).
#[cfg(feature = "drm")]
if crate::platform::linux::is_login_screen_wayland_cached() {
return;
}
// The remap corrects for per-display origin shifts; the uinput ABS range corrects for
// the overall bounding box. Only enable the remap once the range matches the live
// layout, otherwise moves would be remapped into a range the device is not yet using.
// A drift with no bbox change (origins swapped) needs no range update and enables now.
let mut range_ok = WAYLAND_UINPUT_RECT.lock().unwrap().rect == Some(rect);
if !range_ok {
let (minx, maxx, miny, maxy) = rect;
log::info!(
"desktop layout changed, update mouse resolution: ({}, {}), ({}, {})",
minx,
maxx,
miny,
maxy
);
match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => {
// Bound the IPC wait, this runs on the display service loop and
// `set_resolution()` has no timeout on the response read.
// timeout must be built inside the runtime, or it panics
// "there is no reactor running". See clipboard_service.rs.
match rt.block_on(async {
timeout(
3_000,
crate::input_service::update_mouse_resolution(minx, maxx, miny, maxy),
)
.await
}) {
// Record the rect only after a successful apply, so a transient
// failure is retried on the next check.
Ok(Ok(())) => {
WAYLAND_UINPUT_RECT.lock().unwrap().rect = Some(rect);
range_ok = true;
}
Ok(Err(err)) => log::error!("Failed to update mouse resolution: {}", err),
Err(err) => log::error!("Failed to update mouse resolution: {}", err),
// The check, the apply, what they record and the flag below run on the uinput apply thread,
// in turn with the other paths; this loop waits for its answer.
#[cfg(feature = "drm")]
if run_uinput_apply(move |rt| {
let mut range_ok = WAYLAND_UINPUT_RECT.lock().unwrap().rect == Some(rect);
// The device already runs a range that fits this layout: the DRM calibration may measure.
if range_ok {
note_input_map_ready(scrap::wayland::display::wayland_snapshot_generation());
}
// At a login screen the DRM path owns the rect; only the range/remap update is skipped,
// the snapshot invalidation above must still run (a greeter session has no other trigger).
if crate::platform::linux::is_login_screen_wayland_cached() {
return;
}
if !range_ok {
let (minx, maxx, miny, maxy) = rect;
log::info!(
"desktop layout changed, update mouse resolution: ({}, {}), ({}, {})",
minx,
maxx,
miny,
maxy
);
note_input_map_unknown();
// Bound the IPC wait: `set_resolution()` has no timeout on the response read.
match rt.block_on(async {
timeout(
3_000,
crate::input_service::update_mouse_resolution(minx, maxx, miny, maxy),
)
.await
}) {
// Record the rect only after a successful apply, so a transient
// failure is retried on the next check.
Ok(Ok(())) => {
WAYLAND_UINPUT_RECT.lock().unwrap().rect = Some(rect);
note_input_map_adopted(scrap::wayland::display::wayland_snapshot_generation());
range_ok = true;
}
}
Err(err) => {
log::error!("Failed to build tokio runtime: {}", err);
Ok(Err(err)) => log::error!("Failed to update mouse resolution: {}", err),
Err(err) => log::error!("Failed to update mouse resolution: {}", err),
}
}
// Publish the flag last: a `true` read is always backed by a current `live` and a
// matching uinput range. A failed range apply leaves this false and retries next poll.
WAYLAND_LAYOUT_DRIFTED.store(drifted && range_ok, Ordering::Relaxed);
})
.blocking_recv()
.is_err()
{
hbb_common::throttled_log!(
UINPUT_APPLY_LOG_INTERVAL,
error,
"Failed to check the uinput range: the uinput apply thread is gone"
);
}
#[cfg(not(feature = "drm"))]
{
let mut range_ok = WAYLAND_UINPUT_RECT.lock().unwrap().rect == Some(rect);
if !range_ok {
let (minx, maxx, miny, maxy) = rect;
log::info!(
"desktop layout changed, update mouse resolution: ({}, {}), ({}, {})",
minx,
maxx,
miny,
maxy
);
match tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
{
Ok(rt) => {
// Bound the IPC wait, this runs on the display service loop and
// `set_resolution()` has no timeout on the response read.
// timeout must be built inside the runtime, or it panics
// "there is no reactor running". See clipboard_service.rs.
match rt.block_on(async {
timeout(
3_000,
crate::input_service::update_mouse_resolution(minx, maxx, miny, maxy),
)
.await
}) {
// Record the rect only after a successful apply, so a transient
// failure is retried on the next check.
Ok(Ok(())) => {
WAYLAND_UINPUT_RECT.lock().unwrap().rect = Some(rect);
range_ok = true;
}
Ok(Err(err)) => log::error!("Failed to update mouse resolution: {}", err),
Err(err) => log::error!("Failed to update mouse resolution: {}", err),
}
}
Err(err) => {
log::error!("Failed to build tokio runtime: {}", err);
}
}
}
// Publish the flag last: a `true` read is always backed by a current `live` and a
// matching uinput range. A failed range apply leaves this false and retries next poll.
WAYLAND_LAYOUT_DRIFTED.store(drifted && range_ok, Ordering::Relaxed);
}
// Publish the flag last: a `true` read is always backed by a current `live` and a
// matching uinput range. A failed range apply leaves this false and retries next poll.
WAYLAND_LAYOUT_DRIFTED.store(drifted && range_ok, Ordering::Relaxed);
}
// https://github.com/rustdesk/rustdesk/pull/8537
@@ -849,6 +1038,106 @@ mod tests {
}
}
#[cfg(all(test, target_os = "linux", feature = "drm"))]
mod input_map_tests {
use super::{
input_map_epoch, input_map_gen, input_map_label, note_input_map_adopted,
note_input_map_ready, note_input_map_unknown, run_uinput_apply, set_wayland_uinput_rect,
wayland_uinput_rect,
};
// The input-map statics are process-wide and libtest runs tests concurrently.
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn an_apply_leaves_no_range_ready_until_it_is_acknowledged() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
set_wayland_uinput_rect((0, 1920, 0, 1080));
note_input_map_adopted(41);
let before = input_map_epoch();
note_input_map_unknown();
assert_eq!(input_map_gen(), u64::MAX, "no generation is ready");
assert_eq!(input_map_epoch(), before + 1, "samples from before do not count");
assert_eq!(wayland_uinput_rect(), None, "the poll applies again");
}
#[test]
fn the_raw_drm_union_labels_a_range_with_no_generation() {
assert_eq!(input_map_label(5, true), 5);
assert_eq!(input_map_label(5, false), u64::MAX);
}
#[test]
fn an_acknowledged_range_is_an_adoption_and_a_fitting_one_is_not() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let before = input_map_epoch();
note_input_map_adopted(41);
assert_eq!((input_map_gen(), input_map_epoch()), (41, before + 1));
note_input_map_ready(42);
assert_eq!(
(input_map_gen(), input_map_epoch()),
(42, before + 1),
"a range that already fits is not an adoption"
);
}
// The apply thread is process-wide, and one test kills it on purpose.
static WORKER: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn uinput_applies_run_one_at_a_time_in_the_order_asked() {
let _worker = WORKER.lock().unwrap_or_else(|p| p.into_inner());
let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let answers: Vec<_> = (0..4)
.map(|i| {
let log = log.clone();
run_uinput_apply(move |_| {
log.lock().unwrap().push(("start", i));
std::thread::sleep(std::time::Duration::from_millis(20));
log.lock().unwrap().push(("end", i));
i * 10
})
})
.collect();
let got: Vec<i32> = answers
.into_iter()
.map(|a| a.blocking_recv().unwrap())
.collect();
assert_eq!(got, vec![0, 10, 20, 30]);
let want: Vec<_> = (0..4).flat_map(|i| [("start", i), ("end", i)]).collect();
assert_eq!(*log.lock().unwrap(), want, "one job at a time, in order");
}
#[test]
fn a_uinput_apply_job_can_bound_its_ipc_with_a_timeout() {
let _worker = WORKER.lock().unwrap_or_else(|p| p.into_inner());
let timed_out = run_uinput_apply(|rt| {
rt.block_on(async {
hbb_common::timeout(10, std::future::pending::<()>())
.await
.is_err()
})
});
assert!(timed_out.blocking_recv().unwrap());
}
#[test]
fn a_uinput_apply_thread_that_died_is_started_again() {
let _worker = WORKER.lock().unwrap_or_else(|p| p.into_inner());
let died = run_uinput_apply(|_| panic!("the apply thread dies here"));
assert!(died.blocking_recv().is_err(), "the job that killed it has no answer");
// A job asked while the dying thread still unwinds is lost with it; a later one runs.
let answered = (0..50).find_map(|_| {
let answer = run_uinput_apply(|_| 7).blocking_recv().ok();
if answer.is_none() {
std::thread::sleep(std::time::Duration::from_millis(10));
}
answer
});
assert_eq!(answered, Some(7));
}
}
#[cfg(all(test, target_os = "linux"))]
mod wayland_layout_tests {
use super::WaylandLayout;
+2054 -44
View File
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
// Generated from the installed cursor theme by `adwaita_hotspot_survey` (the ignored test in
// `drm_capturer.rs`); see its doc comment for the command. adwaita-icon-theme 50.0-1, every shape
// the theme ships as a real file, at its 24 px nominal size - the GNOME default cursor size.
//
// Each entry is the shape name, the hotspot the THEME declares, and the sprite's alpha mask: one
// bit per pixel, row-major, most significant bit first, set where alpha >= 128. The mask is all
// the hotspot guess reads, and rotating a mask is exact, so it is the whole fixture.
//
// The point of carrying these is that the expected value comes from the theme author, not from
// our own heuristic: a test that compares the guess against the guess cannot say whether the
// guess is right.
const THEME_SHAPES: &[(&str, u32, u32, i32, i32, &str)] = &[
("X_cursor", 24, 24, 11, 12, "00000000000000000000000000000001830003c78007ffc007ffc007ffc003ff8001ff0001ff8003ff8007ffc007ffc003ef8003c780000000000000000000000000000000000000"),
("alias", 24, 24, 18, 5, "00000000000000000001ffc000ffc0007fc0003fc0007fc0007fc000ffc000ffc001fdc001f8c001f04001e00001e00001e00000e00000e000007000003000000000000000000000"),
("all-resize", 24, 24, 12, 11, "001800003c00007e0000ff0001ff8003ffc007ffe00f3cf01f3cf83ffffc7ffffe7ffffe3ffffc1f3cf80f3cf007ffe003ffc001ff8000ff00007e00003c00001800000000000000"),
("all-scroll", 24, 24, 11, 11, "00000000300000780000fc0001fe0003ff0007ff800e01c01e79e03efdf07efdf87efdf83efdf01e79e00e01c007ff8003ff0001fe0000fc00007800003000000000000000000000"),
("cell", 24, 24, 11, 11, "0000000078000078000078000078000078000078000078000030007f03f87f87f87f87f87f03f8003000007800007800007800007800007800007800007800000000000000000000"),
("col-resize", 24, 24, 12, 12, "0000000038000038000038000038000139000339800739c00f39e01ffff03ffff87ffffc3ffff83ffff80f39f00739e00739c0013900003800003800003800003800000000000000"),
("context-menu", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f00001f80001fc0001fe7fe1ff7fe1ffffe1ffffe1ffffe1fe7fe1fe7fe1ff7fe1df7fe10fffe00fffe007ffe007800000000000000"),
("copy", 24, 24, 3, 1, "0000000000000000001000001800001c00001e00001f00001f80001fc0001fe3c01ffff01ffff81ffff81ffffc1f3ffc1e3ffc1c3ffc183ffc101ff8000ff00007e0000000000000"),
("crosshair", 24, 24, 11, 11, "0000000078000078000078000078000078000078000078000078007ffff87ffff87ffff87ffff8007800007800007800007800007800007800007800007800000000000000000000"),
("default", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f00001f80001fc0001fe0001ff0001ff8001ffc001ffe001fe0001fe0001ff0001df00010f80000f800007800007800000000000000"),
("e-resize", 24, 24, 19, 13, "000000000000000000000000000078001078001878001c78001e78001f781ffff81ffff81ffff81ffff81ffff8001ff8001e78001c78001878001078000078000000000000000000"),
("ew-resize", 24, 24, 12, 12, "0000000000000000000000000000000081000181800381c00781e00ffff01ffff83ffffc1ffff81ffff80781f00381e00381c0008100000000000000000000000000000000000000"),
("grab", 24, 24, 11, 2, "000000000000001800003c0000ff0001ff8001ffe001fff001fff001fff001fff001fff00dfff01ffff01ffff00ffff00ffff007fff007fff003fff001fff000ffe0000000000000"),
("grabbing", 24, 24, 9, 5, "000000000000000000000000000000001f0000ff8001ffe001fff007fff00ffff00ffff00ffff00ffff007fff007fff003fff003fff001ffe0000000000000000000000000000000"),
("help", 24, 24, 12, 21, "000000007e0001ff8003ffc007ffc007ffe00fc7e00fc7e00fc7e0000fe0003fc0003f80007f00007e00007c00007c00000000007c00007c00007c00007c00007c00000000000000"),
("n-resize", 24, 24, 13, 6, "0000000000000000000ffff80ffff80ffff80ffff8007f00007f0000ff8001ffc003ffe007fff0003e00003e00003e00003e00003e00003e00003e00003e00000000000000000000"),
("ne-resize", 24, 24, 15, 10, "0000000000000000000000001ffff01ffff01ffff01ffff00000f00ffef007fef003fef001fef001fef003fef007fef00ffef01fcef01f86f01f02f01e00f00c0000000000000000"),
("nesw-resize", 24, 24, 11, 11, "00000000000000000000ffc0007fc0003fc0003fc0003fc0107fc018ffc01dffc01ff9c01ff0401fe0001fe0001fe0001ff0001ff800000000000000000000000000000000000000"),
("no-drop", 24, 24, 3, 1, "0000000000000000001000001800001c00001e00001f00001f80001fc0001fe3c01ffff01ffff81ffff81ffffc1f3ffc1e3ffc1c3ffc183ffc101ff8000ff00007e0000000000000"),
("not-allowed", 24, 24, 12, 12, "000000000000000000007e0001ff8003ffc007ffe00ffff00ffff01ffff81ffff81ffff81ffff81ffff81ffff80ffff00ffff007ffe003ffc001ff8000ff00000000000000000000"),
("ns-resize", 24, 24, 12, 13, "000000000000001000003800007c0000fe0001ff0003ff8007ffc0007c00007c00007c00007c00007c00007c0007ffc003ff8001ff8001ff0000fe00007c00003800000000000000"),
("nw-resize", 24, 24, 10, 10, "0000000000000000000000000ffff80ffff80ffff80ffff80f00000f7ff00f7fe00f7fc00f7f800f7f800f7fc00f7fe00f7ff00f73f80f61f80f40f80f0078000030000000000000"),
("nwse-resize", 24, 24, 11, 11, "0000000000000000001ff8001ff0001ff0001fe0001fe0001ff0401ff8c01ffdc01cffc0107fc0003fc0003fc0003fc0007fc000ffc0000000000000000000000000000000000000"),
("pointer", 24, 24, 7, 5, "00000000000000000000000000c00001e00001e00001e00001e00001ff0001ffe001fff001fff01dfff03ffff03ffff01ffff00ffff007fff003fff001fff000ffe0000000000000"),
("progress", 24, 24, 3, 1, "0000000000001000001800001c00001e00001f3e001fff801fffc01fffc01fffe01fffe01fffe01fffe01fffe01fffc01fffc01cff80103f00000000000000000000000000000000"),
("row-resize", 24, 24, 12, 13, "000000001000003800007c0000fe0001ff0003ff8007ffc0007c00007c007ffffc7ffffc7ffffc007c00007c0007ffc003ff8001ff8000ff00007e00007c00003800000000000000"),
("s-resize", 24, 24, 13, 18, "000000000000003e00003e00003e00003e00003e00003e00003e00003e0007fff003ffe001ffc000ff80007f00003e000ffff80ffff80ffff80ffff8000000000000000000000000"),
("se-resize", 24, 24, 15, 15, "0000000000000000001e00f01f02f01f86f01fcef00ffef007fef003fef001fef001fef003fef007fef00ffef00000f01ffff01ffff01ffff01ffff0000000000000000000000000"),
("sw-resize", 24, 24, 10, 15, "0000000000000000000f00780f40f80f61f80f73f80f7ff00f7fe00f7fc00f7f800f7f800f7fc00f7fe00f7ff00f00000ffff80ffff80ffff80ffff8000000000000000000000000"),
("text", 24, 24, 11, 12, "00000000000003de0003fe0003fe0000700000700000700000700000700000700000700000700000700000700000700000700000700000700003fe0003fe0003fe00000000000000"),
("vertical-text", 24, 24, 12, 11, "00000000000000000000000000000000000038001c38001c38001c3ffffc3ffffc3ffffc38001c38001c38001c000000000000000000000000000000000000000000000000000000"),
("w-resize", 24, 24, 6, 13, "0000000000000000000000001e00001e08001e18001e38001e78001ef8001ffff81ffff81ffff81ffff81ffff81ff8001e78001e38001e18001e08001e0000000000000000000000"),
("wait", 24, 24, 11, 11, "000000000000000000007e0001ff8003ffc007ffe00ffff00ffff01ffff81ffff81ffff81ffff81ffff81ffff80ffff00ffff007ffe003ffc001ff8000ff00000000000000000000"),
("zoom-in", 24, 24, 11, 10, "00000000000000000000fc0003ff0007ff800fffc00fffc01fffe01fffe01fffe01fffe01fffe01fffe00fffc00fffc007ffe003ffe000fff00000f80000f8000078000000000000"),
("zoom-out", 24, 24, 11, 10, "000000000000000000007e0001ff8003ffc007ffe007ffe00ffff00ffff00ffff00ffff00ffff00ffff007ffe007ffe003fff001fff0007ff800007c00007c00003c000000000000"),
];
+339 -8
View File
@@ -42,6 +42,7 @@ struct StateCursor {
impl super::service::Reset for StateCursor {
fn reset(&mut self) {
*self = Default::default();
CURSOR_SHAPES.lock().unwrap().clear();
crate::platform::reset_input_cache();
fix_key_down_timeout(true);
}
@@ -406,7 +407,7 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
super::log::trace!("Cursor data cached, hcursor: {}", hcursor);
msg = cached.clone();
} else {
let mut data = crate::get_cursor_data(hcursor)?;
let data = crate::get_cursor_data(hcursor)?;
// File the shape under the id ACTUALLY served, not the one requested. Deliberately a
// NEW name rather than shadowing `hcursor`: the insert below reads as the requested
// id everywhere else in this function, and a cfg-gated shadow would make the two
@@ -421,10 +422,7 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
let cache_key = served_id;
#[cfg(not(all(target_os = "linux", feature = "drm")))]
let cache_key = hcursor;
data.colors = hbb_common::compress::compress(&data.colors[..]).into();
let mut tmp = Message::new();
tmp.set_cursor_data(data);
msg = Arc::new(tmp);
msg = cursor_shape_message(data, hbb_common::compress::compress);
// A DRM cursor id is derived from the shape's pixels plus geometry, so an animated
// pointer mints a new id on every shape change and this map would grow for the life
// of the service, each entry pinning a compressed cursor message. (Upstream's X11
@@ -438,8 +436,15 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
const CURSOR_CACHE_MAX: usize = 64;
if state.cached_cursor_data.len() >= CURSOR_CACHE_MAX {
state.cached_cursor_data.clear();
CURSOR_SHAPES.lock().unwrap().clear();
// The shape being sent was kept above; keep it past the clear.
shared_cursor_shape(msg.clone());
}
}
limit_cursor_handles(&mut state.cached_cursor_data, &msg);
// A macOS seed marks a change, never the same one twice: filing it would only
// fill the map.
#[cfg(not(target_os = "macos"))]
state.cached_cursor_data.insert(cache_key, msg.clone());
super::log::trace!("Cursor data updated, hcursor: {}", cache_key);
}
@@ -451,8 +456,12 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
{
state.hcursor = drm_served_id;
}
sp.send_shared(msg.clone());
state.cursor_data = msg;
// A new handle or seed for the shape already shown changes nothing a controller sees;
// a shape is one message however many handles name it.
if !Arc::ptr_eq(&msg, &state.cursor_data) {
sp.send_shared(msg.clone());
state.cursor_data = msg;
}
}
}
sp.snapshot(|sps| {
@@ -499,6 +508,95 @@ lazy_static::lazy_static! {
static ref RELATIVE_MOUSE_CONNS: Arc<Mutex<std::collections::HashSet<i32>>> = Default::default();
}
lazy_static::lazy_static! {
// Every shape the service has sent, by content id, for a controller that asks for one
// again. A shape under several handles is one message here, shared with `cached_cursor_data`,
// and cleared with it; see `limit_cursor_handles` for the ceilings. A shape dropped is
// rebuilt here the next time it is shown, in `run_cursor`, before any connection sends its
// `cursor_id`: whatever a controller has just been told to show, it can ask for.
static ref CURSOR_SHAPES: Mutex<CursorShapes> = Default::default();
}
/// The shapes sent, by content id, and the bytes they hold compressed.
#[derive(Default)]
struct CursorShapes {
shapes: HashMap<u64, Arc<Message>>,
bytes: usize,
}
impl CursorShapes {
fn get(&self, id: &u64) -> Option<&Arc<Message>> {
self.shapes.get(id)
}
fn clear(&mut self) {
self.shapes.clear();
self.bytes = 0;
}
/// The message kept for this shape, `msg` if there was none.
fn keep(&mut self, cd: &CursorData, msg: &Arc<Message>) -> Arc<Message> {
let bytes = &mut self.bytes;
self.shapes
.entry(cd.id)
.or_insert_with(|| {
*bytes += cd.colors.len();
msg.clone()
})
.clone()
}
}
/// The message for a shape the platform gave, named by content, so the per-connection send sends
/// a shape once however many handles the platform gives it; see
/// `is_peer_naming_cursors_by_content`. A shape sent before, under any handle, is reused without
/// being compressed again.
fn cursor_shape_message(
mut data: CursorData,
compress: impl FnOnce(&[u8]) -> Vec<u8>,
) -> Arc<Message> {
data.id = crate::cursor_content_id(data.width, data.height, data.hotx, data.hoty, &data.colors);
if let Some(msg) = cursor_data_message(data.id) {
return msg;
}
data.colors = compress(&data.colors[..]).into();
let mut msg = Message::new();
msg.set_cursor_data(data);
shared_cursor_shape(Arc::new(msg))
}
// A platform may mint a new handle each time it shows a shape (Chrome, Electron), so the handles
// filed would grow for the life of the service, each entry a u64 and an Arc even when every one
// names the same shape. Past this many handles, or this many bytes of compressed shapes, however
// few, the handles and the shapes start over together: a handle shown again is captured and named
// again. macOS files no handles, so there the bytes alone bound the shapes.
const CURSOR_HANDLES_MAX: usize = 4096;
const CURSOR_SHAPES_BYTES_MAX: usize = 32 << 20;
fn limit_cursor_handles(handles: &mut HashMap<u64, Arc<Message>>, sending: &Arc<Message>) {
if handles.len() >= CURSOR_HANDLES_MAX
|| CURSOR_SHAPES.lock().unwrap().bytes >= CURSOR_SHAPES_BYTES_MAX
{
handles.clear();
CURSOR_SHAPES.lock().unwrap().clear();
// The shape being sent was kept; keep it past the clear.
shared_cursor_shape(sending.clone());
}
}
/// The message already kept for this shape if there is one, so every handle for it shares it.
fn shared_cursor_shape(msg: Arc<Message>) -> Arc<Message> {
let Some(message::Union::CursorData(cd)) = &msg.union else {
return msg;
};
CURSOR_SHAPES.lock().unwrap().keep(cd, &msg)
}
/// The CursorData message of a shape the service has sent, for `Misc::request_cursor_data`.
pub fn cursor_data_message(id: u64) -> Option<Arc<Message>> {
CURSOR_SHAPES.lock().unwrap().get(&id).cloned()
}
#[cfg(target_os = "linux")]
lazy_static::lazy_static! {
static ref WAYLAND_CLIPBOARD_INPUT_RECORDS: Arc<Mutex<Vec<(Instant, String)>>> =
@@ -979,6 +1077,77 @@ fn fix_modifiers(modifiers: &[EnumOrUnknown<ControlKey>], en: &mut Enigo, ck: i3
}
}
/// The last ABSOLUTE peer-injected pointer position, in the post-remap uinput layout space, with
/// when it was injected, a sequence number and the wayland snapshot generation it was mapped
/// against. Deliberately NOT `LATEST_PEER_INPUT_CURSOR`: its relative arm stores
/// `get_cursor_pos()`, an X-server coordinate that never went through the layout remap, and the
/// DRM cursor calibration subtracts a cursor-plane position from this, so the two spaces must
/// match. Only the uinput absolute path writes here.
#[cfg(all(target_os = "linux", feature = "drm"))]
static LATEST_PEER_ABS_POS: std::sync::Mutex<
Option<((i32, i32), std::time::Instant, u64, u64, u64)>,
> = std::sync::Mutex::new(None);
#[cfg(all(target_os = "linux", feature = "drm"))]
static PEER_ABS_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// One absolute peer sample, as the calibration reads it.
#[cfg(all(target_os = "linux", feature = "drm"))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PeerAbsSample {
pub pos: (i32, i32),
pub age_ms: u64,
/// Distinct per injected move. Two measurements taken against the same sample are not
/// independent, whatever the cursor plane did in between.
pub seq: u64,
/// The layout generation the point was mapped against.
pub gen: u64,
/// The input-mapping epoch at injection: a sample from before a range adoption was mapped by
/// the old range. See `display_service::input_map_epoch`.
pub map_epoch: u64,
}
/// The peer moved the pointer to an absolute, post-remap position. Called under the ENIGO guard
/// of the move, which an adoption also needs for its refresh: a move stamped with the count of an
/// adoption was injected after that adoption's refresh.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(crate) fn note_peer_absolute_move(x: i32, y: i32) {
let seq = PEER_ABS_SEQ.fetch_add(1, Ordering::Relaxed) + 1;
let gen = scrap::wayland::display::wayland_snapshot_generation();
let map_epoch = super::display_service::input_map_epoch();
*LATEST_PEER_ABS_POS.lock().unwrap() =
Some(((x, y), std::time::Instant::now(), seq, gen, map_epoch));
}
/// The pointer moved by a path that has no post-remap absolute position to offer: a relative
/// delta from the peer, or a move this process made on its own. The last sample no longer says
/// where the pointer is; forget it, the next absolute move restores it.
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(crate) fn note_pointer_moved_without_absolute_sample() {
*LATEST_PEER_ABS_POS.lock().unwrap() = None;
}
/// A move this process makes on its own. The forget runs once `lock` returned the guard the peer
/// move records its sample under, so no peer move lands between the forget and this move and
/// leaves its sample describing a pointer that has moved since.
#[cfg(all(target_os = "linux", feature = "drm"))]
fn forget_sample_and_move<G>(lock: impl FnOnce() -> G, move_to: impl FnOnce(G)) {
let guard = lock();
note_pointer_moved_without_absolute_sample();
move_to(guard);
}
#[cfg(all(target_os = "linux", feature = "drm"))]
pub(crate) fn last_peer_abs_sample() -> Option<PeerAbsSample> {
let (pos, at, seq, gen, map_epoch) = (*LATEST_PEER_ABS_POS.lock().unwrap())?;
Some(PeerAbsSample {
pos,
age_ms: at.elapsed().as_millis() as u64,
seq,
gen,
map_epoch,
})
}
// Update time to avoid send cursor position event to the peer.
// See `run_pos` --> `set_cursor_position` --> `exclude`
#[inline]
@@ -1151,7 +1320,9 @@ pub fn handle_mouse_simulation_(evt: &MouseEvent, conn: i32) {
// told at session init. If the compositor has since moved a monitor, correct
// them onto the current layout. https://github.com/rustdesk/rustdesk/issues/15601
#[cfg(target_os = "linux")]
let (mx, my) = if wayland_use_uinput() {
let uinput = wayland_use_uinput();
#[cfg(target_os = "linux")]
let (mx, my) = if uinput {
super::display_service::remap_wayland_uinput_coord(evt.x, evt.y)
} else {
(evt.x, evt.y)
@@ -1159,6 +1330,11 @@ pub fn handle_mouse_simulation_(evt: &MouseEvent, conn: i32) {
#[cfg(not(target_os = "linux"))]
let (mx, my) = (evt.x, evt.y);
en.mouse_move_to(mx, my);
// Only the uinput point is in the layout space the calibration measures in.
#[cfg(all(target_os = "linux", feature = "drm"))]
if uinput {
note_peer_absolute_move(mx, my);
}
*LATEST_PEER_INPUT_CURSOR.lock().unwrap() = Input {
conn,
time: get_time(),
@@ -1181,6 +1357,10 @@ pub fn handle_mouse_simulation_(evt: &MouseEvent, conn: i32) {
let dy = evt
.y
.clamp(-MAX_RELATIVE_MOUSE_DELTA, MAX_RELATIVE_MOUSE_DELTA);
// The absolute sample stops describing the pointer the moment a delta lands. Drop it
// BEFORE the move, so no frame in between can measure the plane against it.
#[cfg(all(target_os = "linux", feature = "drm"))]
note_pointer_moved_without_absolute_sample();
en.mouse_move_relative(dx, dy);
// Get actual cursor position after relative movement for tracking
if let Some((x, y)) = crate::get_cursor_pos() {
@@ -2398,6 +2578,10 @@ impl TemporaryMouseMoveHandle {
let thread_handle = std::thread::spawn(move || {
log::debug!("TemporaryMouseMoveHandle thread started");
for (x, y) in rx {
// Not the peer's position: the calibration must not subtract from it.
#[cfg(feature = "drm")]
forget_sample_and_move(|| ENIGO.lock().unwrap(), |mut en| en.mouse_move_to(x, y));
#[cfg(not(feature = "drm"))]
ENIGO.lock().unwrap().mouse_move_to(x, y);
}
log::debug!("TemporaryMouseMoveHandle thread exiting");
@@ -2533,3 +2717,150 @@ lazy_static::lazy_static! {
(ControlKey::Delete, true),
].iter().map(|(a, b)| (a.value(), b.clone())).collect();
}
#[cfg(test)]
mod cursor_shape_tests {
use super::*;
fn shape(id: u64) -> Arc<Message> {
let mut msg = Message::new();
msg.set_cursor_data(CursorData {
id,
..Default::default()
});
Arc::new(msg)
}
// One test, since the shapes are kept process-wide.
#[test]
fn a_shape_is_kept_once_and_can_be_asked_for_again() {
let first = shared_cursor_shape(shape(u64::MAX - 1));
let again = shared_cursor_shape(shape(u64::MAX - 1));
assert!(Arc::ptr_eq(&first, &again), "a second handle shares it");
let asked = cursor_data_message(u64::MAX - 1).expect("a sent shape is kept");
assert!(Arc::ptr_eq(&asked, &first));
assert!(cursor_data_message(u64::MAX - 2).is_none());
let raw = |handle| CursorData {
id: handle,
width: 4,
height: 4,
colors: vec![9u8; 4 * 4 * 4].into(),
..Default::default()
};
let mut compressed = 0;
let mut compress = |rgba: &[u8]| {
compressed += 1;
hbb_common::compress::compress(rgba)
};
let shown = cursor_shape_message(raw(1), &mut compress);
let again = cursor_shape_message(raw(2), &mut compress);
assert!(Arc::ptr_eq(&shown, &again), "a new handle, the same shape");
assert_eq!(compressed, 1, "a shape sent before is not compressed again");
let sending = shared_cursor_shape(shape(u64::MAX - 3));
let mut few = HashMap::from([(1, shown.clone())]);
limit_cursor_handles(&mut few, &sending);
assert_eq!(few.len(), 1, "below the ceiling nothing goes");
let mut handles: HashMap<u64, Arc<Message>> = (0..CURSOR_HANDLES_MAX as u64)
.map(|handle| (handle, shown.clone()))
.collect();
limit_cursor_handles(&mut handles, &sending);
assert!(
handles.is_empty(),
"past the ceiling the handles start over"
);
let Some(message::Union::CursorData(cd)) = &shown.union else {
panic!("a cursor shape");
};
assert!(
cursor_data_message(cd.id).is_none(),
"and the shapes with them"
);
assert!(
cursor_data_message(u64::MAX - 3).is_some(),
"but the shape being sent is kept"
);
let big = |id| {
let mut msg = Message::new();
msg.set_cursor_data(CursorData {
id,
colors: vec![0u8; CURSOR_SHAPES_BYTES_MAX / 2 + 1].into(),
..Default::default()
});
Arc::new(msg)
};
shared_cursor_shape(big(u64::MAX - 4));
let sending = shared_cursor_shape(big(u64::MAX - 5));
let mut few = HashMap::from([(1, shown.clone())]);
limit_cursor_handles(&mut few, &sending);
assert!(
few.is_empty(),
"past the byte ceiling the handles start over"
);
assert!(cursor_data_message(u64::MAX - 4).is_none());
assert!(cursor_data_message(u64::MAX - 5).is_some());
super::super::service::Reset::reset(&mut StateCursor::default());
assert!(
cursor_data_message(u64::MAX - 1).is_none(),
"a reset forgets them"
);
}
}
#[cfg(all(test, target_os = "linux", feature = "drm"))]
mod peer_abs_sample_tests {
use super::*;
// The two writers share one static and libtest runs tests concurrently.
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn a_move_without_an_absolute_sample_forgets_the_last_one() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
note_peer_absolute_move(20, 30);
let s = last_peer_abs_sample().expect("an absolute move leaves a sample");
assert_eq!(s.pos, (20, 30));
assert!(s.age_ms < 1_000);
note_pointer_moved_without_absolute_sample();
assert_eq!(last_peer_abs_sample(), None);
}
#[test]
fn every_absolute_move_is_a_new_sample() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
note_peer_absolute_move(1, 1);
let a = last_peer_abs_sample().unwrap().seq;
note_peer_absolute_move(1, 1);
let b = last_peer_abs_sample().unwrap().seq;
assert!(b > a, "same point, distinct sample");
note_pointer_moved_without_absolute_sample();
}
#[test]
fn a_move_of_this_process_forgets_the_sample_of_a_peer_move_it_waited_for() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let mouse = std::sync::Arc::new(std::sync::Mutex::new(()));
note_peer_absolute_move(5, 5);
// The peer holds the mouse lock when the move of this process starts.
let peer = mouse.lock().unwrap();
let (asked, asking) = std::sync::mpsc::channel();
let m = mouse.clone();
let mover = std::thread::spawn(move || {
let lock = || {
asked.send(()).unwrap();
m.lock().unwrap()
};
forget_sample_and_move(lock, |_| {})
});
asking.recv().unwrap();
assert!(last_peer_abs_sample().is_some(), "nothing forgotten before the lock");
note_peer_absolute_move(50, 50);
drop(peer);
mover.join().unwrap();
assert_eq!(last_peer_abs_sample(), None, "the move of this process came last");
}
}
+8 -2
View File
@@ -1069,7 +1069,13 @@ mod mouce {
pub const BTN_TASK: c_int = 0x117;
const SYN_REPORT: c_int = 0x00;
const EV_SYN: c_int = 0x00;
const BUS_USB: c_ushort = 0x03;
// libinput's evdev_tag_external_mouse() tags any BUS_USB/BUS_BLUETOOTH
// pointer as an external mouse, which makes desktop environments'
// "disable touchpad when an external mouse is present" setting suspend
// the real touchpad whenever this virtual device is created, even
// though nothing is physically plugged in. BUS_VIRTUAL correctly
// identifies this as the software-only device it is.
const BUS_VIRTUAL: c_ushort = 0x06;
/// uinput types
#[repr(C)]
@@ -1208,7 +1214,7 @@ mod mouce {
let mut usetup = UInputSetup {
id: InputId {
bustype: BUS_USB,
bustype: BUS_VIRTUAL,
// Random vendor and product
vendor: 0x2222,
product: 0x3333,
+81 -19
View File
@@ -371,6 +371,10 @@ pub(super) async fn update_uinput_resolution() {
// runs on current-thread runtimes (session init and the hotplug worker). The layout baseline
// is computed in the SAME task: a failed lookup is not cached, so asking for the rects
// afterwards would rerun the whole socket probe synchronously.
//
// The generation read before the rect is computed labels the range for the DRM cursor
// calibration; the raw DRM union below is no compositor layout and is labelled with none.
let gen = scrap::wayland::display::wayland_snapshot_generation();
let (rect, layout) = match hbb_common::tokio::task::spawn_blocking(|| {
scrap::wayland::display::clear_wayland_displays_cache();
match scrap::wayland::display::get_desktop_rect_for_uinput() {
@@ -393,34 +397,48 @@ pub(super) async fn update_uinput_resolution() {
return;
}
};
let gen = super::display_service::input_map_label(gen, !layout.is_empty());
// Re-snapshot the baseline on every call: this runs at session init and after every hotplug, and
// the baseline is what the client's coordinates are measured against.
let snapshot_layout = || {
let snapshot_layout = move || {
super::display_service::set_wayland_layout_baseline(layout.clone());
};
// Reprogram the device only when the range actually changes. A display stuck in a rebuild loop
// calls this about once a second, and reapplying an identical range is an IPC roundtrip plus a
// uinput device reconfiguration under a user who may be at the console.
if super::display_service::wayland_uinput_rect() == Some(rect) {
snapshot_layout();
return;
}
let (minx, maxx, miny, maxy) = rect;
log::info!("update mouse resolution: ({minx}, {maxx}), ({miny}, {maxy})");
match timeout(
3_000,
input_service::update_mouse_resolution(minx, maxx, miny, maxy),
)
.await
{
// Record the rect only after a successful apply, so a transient failure is retried on the
// next call instead of being remembered as applied.
Ok(Ok(())) => {
super::display_service::set_wayland_uinput_rect(rect);
let job = move |rt: &tokio::runtime::Runtime| {
if super::display_service::wayland_uinput_rect() == Some(rect) {
super::display_service::note_input_map_ready(gen);
snapshot_layout();
return;
}
Ok(Err(err)) => log::error!("Failed to update mouse resolution: {}", err),
Err(err) => log::error!("Failed to update mouse resolution: {}", err),
let (minx, maxx, miny, maxy) = rect;
log::info!("update mouse resolution: ({minx}, {maxx}), ({miny}, {maxy})");
super::display_service::note_input_map_unknown();
match rt.block_on(async {
timeout(
3_000,
input_service::update_mouse_resolution(minx, maxx, miny, maxy),
)
.await
}) {
// Record the rect only after a successful apply, so a transient failure is retried on
// the next call instead of being remembered as applied.
Ok(Ok(())) => {
super::display_service::set_wayland_uinput_rect(rect);
super::display_service::note_input_map_adopted(gen);
snapshot_layout();
}
Ok(Err(err)) => log::error!("Failed to update mouse resolution: {}", err),
Err(err) => log::error!("Failed to update mouse resolution: {}", err),
}
};
if super::display_service::run_uinput_apply(job).await.is_err() {
hbb_common::throttled_log!(
super::display_service::UINPUT_APPLY_LOG_INTERVAL,
error,
"Failed to update mouse resolution: the uinput apply thread is gone"
);
}
}
@@ -468,6 +486,10 @@ pub(super) async fn check_init() -> ResultType<()> {
if crate::input_service::wayland_use_uinput() {
// The cached layout may predate compositor changes made while no session
// was active, https://github.com/rustdesk/rustdesk/issues/15601
// Read before the rect: an apply that races a layout move is recorded under the
// older generation, which only streams built before the move measure under.
#[cfg(feature = "drm")]
let gen = scrap::wayland::display::wayland_snapshot_generation();
scrap::wayland::display::clear_wayland_displays_cache();
if let Some((minx, maxx, miny, maxy)) =
scrap::wayland::display::get_desktop_rect_for_uinput()
@@ -479,8 +501,48 @@ pub(super) async fn check_init() -> ResultType<()> {
miny,
maxy
);
// A display that falls back to PipeWire in a DRM session runs this apply
// too: it goes through the uinput apply thread, in turn with the DRM paths.
#[cfg(feature = "drm")]
{
let job = move |rt: &tokio::runtime::Runtime| {
super::display_service::note_input_map_unknown();
match rt.block_on(async {
timeout(
3_000,
input_service::update_mouse_resolution(minx, maxx, miny, maxy),
)
.await
}) {
Ok(Ok(())) => {
super::display_service::set_wayland_uinput_rect((
minx, maxx, miny, maxy,
));
super::display_service::note_input_map_adopted(gen);
// Snapshot the per-display layout the client's coordinates
// will be based on, so the mouse path can correct them if
// the compositor moves a monitor mid-session.
super::display_service::set_wayland_layout_baseline(
scrap::wayland::display::get_display_rects_for_uinput(),
);
}
Ok(Err(err)) => {
log::error!("Failed to update mouse resolution: {}", err)
}
Err(err) => log::error!("Failed to update mouse resolution: {}", err),
}
};
if super::display_service::run_uinput_apply(job).await.is_err() {
hbb_common::throttled_log!(
super::display_service::UINPUT_APPLY_LOG_INTERVAL,
error,
"Failed to update mouse resolution: the uinput apply thread is gone"
);
}
}
// Bound the IPC wait like the periodic refresh does, so a hung
// response can't stall session init.
#[cfg(not(feature = "drm"))]
match timeout(
3_000,
input_service::update_mouse_resolution(minx, maxx, miny, maxy),
+14
View File
@@ -51,6 +51,10 @@ use crate::common::GrabState;
use crate::keyboard;
use crate::{client::Data, client::Interface};
#[cfg(any(target_os = "android", target_os = "ios", test))]
#[path = "platform/mobile_wheel.rs"]
mod mobile_wheel;
const CHANGE_RESOLUTION_VALID_TIMEOUT_SECS: u64 = 15;
#[derive(Clone, Default)]
@@ -72,6 +76,10 @@ pub struct Session<T: InvokeUiSession> {
pub reconnect_count: Arc<AtomicUsize>,
pub last_audit_note: Arc<Mutex<String>>,
pub audit_guid: Arc<Mutex<String>>,
// Every cursor shape as the peer sent it, compressed, by the id the UI knows it by. The
// peer sends a shape once, and a window asks for it whenever it has to draw it again.
#[cfg(feature = "flutter")]
pub cursor_shapes: Arc<RwLock<HashMap<u64, CursorData>>>,
}
#[derive(Clone)]
@@ -1234,6 +1242,12 @@ impl<T: InvokeUiSession> Session<T> {
} else {
(x, y)
};
#[cfg(any(target_os = "android", target_os = "ios"))]
let (x, y) = if event_type == MOUSE_TYPE_WHEEL || event_type == MOUSE_TYPE_TRACKPAD {
mobile_wheel::mobile_wheel_delta((x, y), &self.lc.read().unwrap().reverse_mouse_wheel)
} else {
(x, y)
};
// #[cfg(not(any(target_os = "android", target_os = "ios")))]
let (alt, ctrl, shift, command) =