Compare commits

..
Author SHA1 Message Date
rustdeskandClaude Opus 5.5 f48b6c0d72 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
2026-09-25 11:55:39 +08:00
rustdeskandClaude Opus 5.5 547acba702 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
2026-09-25 11:45:46 +08:00
rustdeskandClaude Opus 5.5 e5629f3b66 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
2026-09-25 11:15:46 +08:00
rustdeskandClaude Opus 5.5 f0acecb8af 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
2026-09-25 10:11:54 +08:00
rustdeskandClaude Opus 5.5 c0351e3178 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
2026-09-25 10:11:52 +08:00
rustdeskandClaude Opus 5.5 eeeb87043c 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
2026-09-24 23:34:10 +08:00
rustdeskandClaude Opus 5.5 59931e19d1 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
2026-09-24 23:34:10 +08:00
rustdeskandClaude Opus 5.5 82820c7d1d 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
2026-09-24 23:34:10 +08:00
rustdeskandClaude Opus 5.5 7772fa91a2 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
2026-09-24 17:22:10 +08:00
rustdeskandClaude Opus 5.5 8536be457e 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
2026-09-24 15:36:10 +08:00
rustdeskandClaude Opus 5.5 7cefbfc7a7 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
2026-09-24 15:27:05 +08:00
rustdeskandClaude Opus 5.5 1e4388771f 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
2026-09-24 14:16:46 +08:00
rustdeskandClaude Opus 5.5 a39fe47863 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
2026-09-24 13:58:03 +08:00
rustdeskandClaude Opus 5.5 d1f566a143 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
2026-09-24 10:58:45 +08:00
rustdeskandClaude Opus 5.5 5414eaf702 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
2026-09-24 10:56:27 +08:00
rustdeskandClaude Opus 5.5 cefb463acd 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
2026-09-24 09:50:53 +08:00
rustdeskandClaude Opus 5.5 cb4f35a540 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
2026-09-24 02:46:53 +08:00
rustdeskandClaude Opus 5.5 11d0b32757 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
2026-09-24 02:11:25 +08:00
rustdeskandClaude Opus 5.5 d677bbebf6 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
2026-09-23 23:02:53 +08:00
rustdeskandClaude Opus 5.5 86800194cb 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
2026-09-23 22:58:24 +08:00
rustdeskandClaude Fable 5.1 fa334d2727 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
2026-09-23 22:06:22 +08:00
rustdeskandClaude Fable 5.1 01923fb281 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
2026-09-23 22:06:22 +08:00
rustdeskandClaude Fable 5.1 26af07a5c9 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
2026-09-23 21:52:52 +08:00
rustdeskandClaude Fable 5.1 ce614b5fa9 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
2026-09-23 20:39:29 +08:00
rustdeskandClaude Fable 5.1 22ec5e3f97 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
2026-09-23 20:27:25 +08:00
rustdeskandClaude Fable 5.1 b93d71899f 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
2026-09-23 19:58:58 +08:00
rustdeskandClaude Fable 5.1 0f67165689 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
2026-09-23 19:52:43 +08:00
rustdeskandClaude Fable 5.1 9f521537dd 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
2026-09-23 19:52:43 +08:00
rustdeskandClaude Fable 5.1 7f845af13b 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
2026-09-23 19:52:43 +08:00
rustdeskandClaude Fable 5.1 611c5b4aad 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
2026-09-23 19:52:43 +08:00
rustdeskandClaude Fable 5.1 6cf2ef387a 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Fable 5.1 7a91b0c91a 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 024ba94c78 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Fable 5.1 3d0b80b3de 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Fable 5.1 6ad1bc7895 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 504de6debf 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 3b036d2015 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 77242d52a7 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 a77de619c2 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 18ebd9cf17 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 85214000b5 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 3a1785d3c3 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 1007d29687 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 d9223ae333 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 0c95a2af9c 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 49710e45ee 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 f88407472b 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 7825168f84 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
2026-09-23 19:52:42 +08:00
rustdeskandClaude Opus 5.5 d64ff4961b 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
2026-09-23 19:52:42 +08:00
118 changed files with 505 additions and 6470 deletions
-10
View File
@@ -2080,18 +2080,10 @@ jobs:
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
@@ -2452,9 +2444,7 @@ jobs:
sudo pip3 install git+https://github.com/rustdesk-org/appimage-builder.git
# run appimage-builder
pushd appimage
./build-apprun.sh ${{ matrix.job.arch }}
sudo appimage-builder --skip-tests --recipe ./AppImageBuilder-${{ matrix.job.arch }}.yml
cmp AppDir/AppRun appimage-build/AppRun/v2.0.0/AppRun-Release-${{ matrix.job.arch }}
- name: Publish appimage package
if: env.UPLOAD_ARTIFACT == 'true'
-38
View File
@@ -48,20 +48,6 @@ workspace member. `base::config::keys` re-exports the handful of keys
* Do not add dependencies unless needed.
* Keep code simple and idiomatic.
### Logging
* `debug` and above are written to the log file. A log call that can fire
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
peer controls) must not use `debug` or higher unthrottled.
* For such a site, pick one:
* `log::trace!` when the event is expected and the line only helps while
actively debugging;
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
that should still show up in a user's log. It keeps one line per interval
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
directly only when the decision drives more than one log call.
## Tokio Rules
* Assume a Tokio runtime already exists.
@@ -141,36 +127,12 @@ Before considering any implementation complete, perform a minimization pass over
* Before finalizing, explicitly report the regression surface: list the existing files and existing runtime paths whose behavior changed, and explain why each change is unavoidable.
* During review, treat an unnecessarily modified legacy path as a review finding even if tests pass and the rewritten behavior appears equivalent.
### Corner cases raised in review
A refactor added to cover a corner case rarely converges. Each new counter, timestamp, cache or eviction/expiry rule interacts with state that existing code relies on, and the next review round finds the problems it introduced.
* A corner case is still worth fixing when the fix is easy and low-risk: a local change of a few lines that adds no state and changes no existing lookup, such as moving a check or refusing bad input earlier.
* When the only fix needs new state, a new lifecycle rule or a restructure, and the code already fails cleanly there or behaves as master does, document it as a known limit in the PR instead. Anything beyond the easy fix needs the maintainer's explicit go-ahead first.
* Before adding state that reorders, expires or reuses existing data, list every lookup that reads that data and check each one still holds.
* Prefer a clean failure, where the operation reports an error, over machinery that tries to make a rare case succeed.
* A severity label from any reviewer (P1, Critical, Major) is not a triage result. Apply the next rule by consequence, not by label.
* A corner case whose fix needs new state is fixed only when it crashes, loses data, weakens security, or a user has reported it. A rare cosmetic or layout glitch (e.g. rotation during an active drag, a feature that is off by default) is a known limit: reply once, list it under "Known limits" in the PR body, and leave the code alone.
* When a finding is about behavior an earlier commit of this same PR introduced, fix it by removing or simplifying that commit, not by adding a layer on top.
* Judge growth across all rounds, not per round. If review follow-ups have grown the non-test diff by more than half of the first fix, or added a new kind of state (handles into another component, cross-component references, deferred / post-frame callbacks, timers, caches, flags), stop and ask the maintainer before pushing.
* When keeping the user's preferred state is hard in a rare case, fall back to a deterministic default computed from the current inputs. Do not coordinate mutable state across components or frames to preserve the preference.
## Tests
* A fix gets regression tests for the reported behavior only: they fail on master and pass with the fix. One to three tests is normal.
* Assert what the user sees or what the API returns. Do not test private state, the order an algorithm runs its steps in, or each corner case raised in review.
* Do not add test infrastructure (browser runners, golden/screenshot harnesses, new mock layers, test-only hooks in production code) for a bug fix unless the maintainer asks.
* If the test diff is more than twice the fix, cut it back to the tests that pin the reported behavior. A state that needs long setup to reach is usually too rare to fix.
* When the number of tests needed to describe the behavior keeps growing, the implementation is too complex: simplify it instead of adding tests.
## 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
+19 -14
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#522fafb65edfe7939cf63fa797f916569ecab595"
source = "git+https://github.com/rustdesk-org/clipboard-master#7762d74e38db37cfeb6ded88c964b9cdbddfb6db"
dependencies = [
"objc",
"objc-foundation",
@@ -4163,6 +4163,16 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "iri-string"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
dependencies = [
"memchr",
"serde 1.0.228",
]
[[package]]
name = "is-terminal"
version = "0.4.16"
@@ -6762,7 +6772,7 @@ dependencies = [
[[package]]
name = "rdev"
version = "0.5.0-2"
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
dependencies = [
"cocoa 0.24.1",
"core-foundation 0.9.4",
@@ -6891,10 +6901,11 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.12.28"
version = "0.12.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
dependencies = [
"async-compression",
"base64 0.22.1",
"bytes",
"futures-channel",
@@ -6923,6 +6934,7 @@ dependencies = [
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
@@ -7175,7 +7187,6 @@ dependencies = [
"uuid",
"virtual_display",
"wallpaper",
"wayland-client",
"winapi 0.3.9",
"windows 0.61.1",
"windows-service",
@@ -7185,7 +7196,6 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xkbcommon-dl",
"xxhash-rust",
"zstd",
]
@@ -8734,25 +8744,20 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.11"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
dependencies = [
"async-compression",
"bitflags 2.9.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
"iri-string",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
-2
View File
@@ -202,8 +202,6 @@ gtk = "0.18"
termios = "0.3"
terminfo = "0.8"
winit = "0.30"
wayland-client = "0.31"
xkbcommon-dl = { version = "0.4", features = ["x11"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
-55
View File
@@ -1,55 +0,0 @@
--- a/src/common/shell_utils.c
+++ b/src/common/shell_utils.c
@@ -201,7 +201,8 @@
const char *begin = str;
const char *end = str;
- char buffer[1024] = {0x0};
+ size_t buffer_size = strlen(str) + 1;
+ char *buffer = calloc(buffer_size, sizeof(char));
while (*begin != '\0') {
begin = apprun_string_consume_spaces(begin);
@@ -209,7 +210,7 @@
if (*begin == '\\') {
strncat(buffer, begin + 1, 1);
- end = begin + 2;
+ end = begin[1] != '\0' ? begin + 2 : begin + 1;
consumed = true;
}
@@ -218,7 +219,8 @@
strncat(buffer, begin + 1, end - begin - 1);
consumed = true;
- end++;
+ if (*end != '\0')
+ end++;
}
if (!consumed && *begin == '\"') {
@@ -226,7 +228,8 @@
strncat(buffer, begin + 1, end - begin - 1);
consumed = true;
- end++;
+ if (*end != '\0')
+ end++;
}
if (!consumed && *begin != '\'' && *begin != '\"' && *begin != '\\') {
@@ -240,11 +243,12 @@
split_count++;
}
- memset(buffer, 0, 1024);
+ buffer[0] = '\0';
}
begin = end;
}
+ free(buffer);
return splits;
}
-38
View File
@@ -1,38 +0,0 @@
#!/usr/bin/env bash
# AppRun v2.0.0, which appimage-builder downloads, splits every argument into a 1 KiB stack
# buffer, so any argument of 1024 bytes or more aborts the AppImage before RustDesk starts.
# Build it with apprun-split-arguments.patch into the path appimage-builder checks before
# downloading. ubuntu:16.04 is what upstream released from, so the host glibc floor is unchanged.
set -euo pipefail
arch=$1
version=v2.0.0
commit=407700ccef58e1a64cc49856074aee4b1c75d599
sha256=05729f2ae0a744369d2d19d0f37acfbdcb1ee064172955b7576883ccef5113b3
image=ubuntu:16.04@sha256:1f1a2d56de1d604801a9671f301190704c25d604a416f59e03c04f5c6ffee0d6
here=$(cd "$(dirname "$0")" && pwd)
case $arch in
x86_64) packages="cmake make g++" ;;
aarch64) packages="cmake make g++ g++-aarch64-linux-gnu" ;;
*) echo "Unsupported arch: $arch" >&2; exit 1 ;;
esac
tmp=$(mktemp -d)
src=$tmp/src
curl -fsSL -o "$tmp/apprun.tar.gz" "https://github.com/AppImageCrafters/AppRun/archive/$commit.tar.gz"
echo "$sha256 $tmp/apprun.tar.gz" | sha256sum -c -
mkdir "$src"
tar -xzf "$tmp/apprun.tar.gz" -C "$src" --strip-components=1
patch -d "$src" -p1 < "$here/apprun-split-arguments.patch"
docker run --rm -v "$src:/src" -w /src -e DEBIAN_FRONTEND=noninteractive "$image" bash -c "
set -e
apt-get update
apt-get install -y --no-install-recommends $packages
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=../cmake/$arch-toolchain.cmake
cmake --build . --target AppRun"
mkdir -p "$here/appimage-build/AppRun/$version"
cp "$src/build/src/apprun/AppRun" "$here/appimage-build/AppRun/$version/AppRun-Release-$arch"
+2 -2
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.8.
# libs/scrap/Cargo.toml). This commit is libdrmtap v0.5.6.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
LIBDRMTAP_SHA_PINNED = '49b204f275af1a2d6dfead94effb4036c7d50a3a'
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
@@ -199,7 +199,7 @@ class AudioRecordHandle(private var context: Context, private var isVideoStart:
context,
Manifest.permission.RECORD_AUDIO
) != PackageManager.PERMISSION_GRANTED) {
"To start a voice call, enable \"Audio capture\" on the \"Share screen\" page."
"To start a voice call, enable \"Audio capture\" on the \"Screen share\" page."
} else {
"Failed to start voice call."
}
@@ -480,10 +480,6 @@ class _DesktopHomePageState extends State<DesktopHomePage>
return buildInstallCard("Permissions", "config_screen", "Configure",
() async {
bind.mainIsCanScreenRecording(prompt: true);
// macOS shows the request prompt only once per app, so later
// presses would do nothing without opening the settings pane.
launchUrl(Uri.parse(
'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'));
watchIsCanScreenRecording = true;
}, help: 'Help', link: translate("doc_mac_permission"));
} else if (!isOutgoingOnly && !bind.mainIsProcessTrusted(prompt: false)) {
+2 -30
View File
@@ -62,15 +62,12 @@ class _InstallPageBody extends StatefulWidget {
class _InstallPageBodyState extends State<_InstallPageBody>
with WindowListener {
static const _printerStatusTimeout = Duration(seconds: 5);
late final TextEditingController controller;
final RxBool startmenu = true.obs;
final RxBool desktopicon = true.obs;
final RxBool printer = false.obs;
final RxBool showProgress = false.obs;
final RxBool btnEnabled = true.obs;
final RxBool cancelEnabled = true.obs;
// todo move to theme.
final buttonStyle = OutlinedButton.styleFrom(
@@ -86,33 +83,10 @@ class _InstallPageBodyState extends State<_InstallPageBody>
printer.value = installOptions['PRINTER'] == '1';
}
Future<void> _loadPrinterStatus() async {
btnEnabled.value = false;
showProgress.value = true;
try {
final status = await bind
.mainGetCommon(key: 'is-printer-installed')
.timeout(_printerStatusTimeout);
printer.value = status == 'true';
if (status != 'true' && status != 'false') {
debugPrint('Failed to check printer installation status: $status');
}
} catch (e) {
printer.value = false;
debugPrint('Failed to check printer installation status: $e');
} finally {
showProgress.value = false;
btnEnabled.value = true;
}
}
@override
void initState() {
windowManager.addListener(this);
super.initState();
if (printer.value) {
_loadPrinterStatus();
}
}
@override
@@ -243,9 +217,8 @@ class _InstallPageBodyState extends State<_InstallPageBody>
() => OutlinedButton.icon(
icon: Icon(Icons.close_rounded, size: 16),
label: Text(translate('Cancel')),
onPressed: cancelEnabled.value
? () => windowManager.close()
: null,
onPressed:
btnEnabled.value ? () => windowManager.close() : null,
style: buttonStyle,
).marginOnly(right: 10),
),
@@ -280,7 +253,6 @@ class _InstallPageBodyState extends State<_InstallPageBody>
void install() {
do_install() {
btnEnabled.value = false;
cancelEnabled.value = false;
showProgress.value = true;
String args = '';
if (startmenu.value) args += ' startmenu';
@@ -335,10 +335,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
} else if (newValue.length < oldValue.length) {
+2 -2
View File
@@ -1427,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.
// New monitor windows keep their selection in currentDisplay.
final last = lastUserDisplay ?? _pi.currentDisplay;
final last = lastUserDisplay;
pendingMonitorRestore = (!isCache &&
last != null &&
last != currentDisplay &&
bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
sessionId: sessionId) !=
+2 -2
View File
@@ -339,8 +339,8 @@ packages:
dependency: "direct main"
description:
path: "."
ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
resolved-ref: "cddc2e64f8fefce4f80db87b20bcda2dd019bed6"
ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
resolved-ref: "8b774a66671cbb9bcb2631af6ac28f9bdd469ce3"
url: "https://github.com/rustdesk-org/rustdesk_desktop_multi_window"
source: git
version: "0.1.0"
+1 -1
View File
@@ -58,7 +58,7 @@ dependencies:
desktop_multi_window:
git:
url: https://github.com/rustdesk-org/rustdesk_desktop_multi_window
ref: cddc2e64f8fefce4f80db87b20bcda2dd019bed6
ref: 8b774a66671cbb9bcb2631af6ac28f9bdd469ce3
freezed_annotation: ^2.0.3
flutter_custom_cursor:
git:
+5 -8
View File
@@ -59,22 +59,19 @@ constexpr UINT kForceRedrawMaxTries = 25;
// per call (each nudge re-enters the 100ms resize wait).
constexpr UINT kForceRedrawCheapTries = 2;
// 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.
// 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.
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, 0, height,
SetWindowPos(child, nullptr, 0, 0, width + 1, 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,14 +104,6 @@ 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 {
-2
View File
@@ -1030,7 +1030,5 @@ message Message {
TerminalAction terminal_action = 31;
TerminalResponse terminal_response = 32;
PortForwardChannel port_forward_channel = 33;
// Auto Login: the peer types the password only if it is at its logon or lock screen.
OSLogin os_login = 34;
}
}
+5 -95
View File
@@ -48,19 +48,6 @@ 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> {
@@ -82,7 +69,6 @@ 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
@@ -140,13 +126,12 @@ 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
};
@@ -169,11 +154,8 @@ 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;
let last_write_time = Duration::new(
last_write_time / 10_000_000,
(last_write_time % 10_000_000) as u32 * 100,
);
let last_write_time = (last_write_time - LDAP_EPOCH_DELTA) * 100;
let last_write_time = Duration::from_nanos(last_write_time);
SystemTime::UNIX_EPOCH + last_write_time
} else {
SystemTime::UNIX_EPOCH
@@ -193,7 +175,6 @@ impl FileDescription {
creation_time: last_modified,
size,
perm,
clip_data_id,
};
Ok(desc)
@@ -205,7 +186,6 @@ 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 {
@@ -226,7 +206,7 @@ impl FileDescription {
let mut files = Vec::with_capacity(count);
for _ in 0..count {
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
files.push(desc);
}
@@ -242,7 +222,6 @@ 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;
@@ -303,22 +282,6 @@ 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);
@@ -327,57 +290,4 @@ 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
);
}
}
+2 -8
View File
@@ -549,8 +549,8 @@ impl FuseServer {
n_position_low,
n_position_high,
cb_requested,
have_clip_data_id: true,
clip_data_id: node.clip_data_id,
have_clip_data_id: false,
clip_data_id: 0,
};
send_data(node.conn_id, request.clone()).map_err(|e| {
@@ -611,9 +611,6 @@ 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
@@ -637,7 +634,6 @@ 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
@@ -654,7 +650,6 @@ impl FuseNode {
pub fn new_root() -> Self {
Self {
conn_id: 0,
clip_data_id: 0,
index: 0,
name: String::from("/"),
parent: None,
@@ -903,7 +898,6 @@ mod fuse_test {
size: 0,
perm: 0,
clip_data_id: 0,
}
}
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
+3 -46
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()
/ 100) as u64
.as_nanos() as u64
/ 100
+ LDAP_EPOCH_DELTA;
let size_high = (self.size >> 32) as u32;
@@ -323,7 +323,6 @@ mod file_list_test {
use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
time::{Duration, SystemTime},
};
use hbb_common::bytes::{BufMut, BytesMut};
@@ -491,46 +490,4 @@ 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,8 +4,6 @@ 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},
@@ -17,7 +15,7 @@ use std::{
Arc, Mutex,
},
thread,
time::Duration,
time::{Duration, SystemTime},
};
const RECV_RETRY_TIMES: usize = 3;
@@ -25,16 +23,15 @@ 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,
@@ -56,7 +53,6 @@ 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,
}
@@ -120,7 +116,6 @@ impl PasteTask {
download_file_path: "".to_owned(),
download_file_current_size: 0,
file_handle: None,
finder_progress: None,
error: None,
is_canceled: false,
},
@@ -323,7 +318,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;
@@ -334,52 +329,44 @@ impl PasteTaskHandle {
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 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 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(())
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();
}
#[inline]
fn remove_progress_completed(&mut self) {
use objc2::rc::autoreleasepool;
if let Some(progress) = self.progress.finder_progress.take() {
autoreleasepool(|_| unsafe { progress.unpublish() });
fn remove_progress_completed(path: &str) {
if !path.is_empty() {
xattr::remove(path, ATTR_PROGRESS_FRACTION_COMPLETED).ok();
}
}
@@ -429,7 +416,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 {
@@ -535,12 +522,14 @@ 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(());
};
@@ -553,11 +542,6 @@ 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
@@ -633,7 +617,6 @@ 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,
@@ -646,8 +629,8 @@ impl PasteTaskHandle {
n_position_low,
n_position_high,
cb_requested: cb_requested as _,
have_clip_data_id: true,
clip_data_id,
have_clip_data_id: false,
clip_data_id: 0,
};
allow_err!(send_data(conn_id, request));
self.progress.last_sent_time = Instant::now();
@@ -686,16 +669,10 @@ impl PasteTaskHandle {
}
}
impl Drop for PasteTaskHandle {
fn drop(&mut self) {
self.remove_progress_completed();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::{os::unix::fs::symlink, time::SystemTime};
use std::os::unix::fs::symlink;
struct TestDirectory(PathBuf);
@@ -726,7 +703,6 @@ mod tests {
creation_time: SystemTime::UNIX_EPOCH,
size,
perm: 0,
clip_data_id: 0,
}
}
@@ -743,7 +719,6 @@ mod tests {
download_file_path: String::new(),
download_file_current_size: 0,
file_handle: None,
finder_progress: None,
error: None,
is_canceled: false,
},
@@ -752,75 +727,6 @@ mod tests {
}
}
#[test]
fn finder_progress_completes_single_response_transfer() {
let (_temp, target, _) = test_directories();
let data = b"single response";
let file = file_description("small.txt", FileType::File, data.len() as u64);
let mut task = paste_task_handle(target.clone(), vec![file]);
task.update_next(0).unwrap();
let download_path = PathBuf::from(&task.progress.download_file_path);
let progress = task.progress.finder_progress.as_ref().unwrap().clone();
assert_eq!(unsafe { progress.completedUnitCount() }, 0);
task.handle_file_contents_response(FileContentsResponse {
conn_id: 0,
msg_flags: 1,
stream_id: 0,
requested_data: data.to_vec(),
})
.unwrap();
unsafe {
assert_eq!(progress.totalUnitCount(), data.len() as i64);
assert_eq!(progress.completedUnitCount(), progress.totalUnitCount());
assert!(progress.isFinished());
}
assert!(task.progress.finder_progress.is_none());
assert!(task.progress.file_handle.is_none());
assert!(task.is_finished());
assert!(task.progress.error.is_none());
assert!(!download_path.exists());
assert_eq!(std::fs::read(target.join("small.txt")).unwrap(), data);
}
#[test]
fn finder_progress_reports_bytes_below_one_percent() {
let (_temp, target, _) = test_directories();
let size = u32::MAX as u64 + 1;
let file = file_description("large.bin", FileType::File, size);
let mut task = paste_task_handle(target, vec![file]);
task.update_next(0).unwrap();
task.handle_file_contents_response(FileContentsResponse {
conn_id: 0,
msg_flags: 1,
stream_id: 0,
requested_data: vec![1],
})
.unwrap();
let progress = task.progress.finder_progress.as_ref().unwrap();
unsafe {
assert_eq!(progress.totalUnitCount(), size as i64);
assert_eq!(progress.completedUnitCount(), 1);
}
task.on_cancelled();
assert!(task.progress.finder_progress.is_none());
assert!(!Path::new(&task.progress.download_file_path).exists());
}
#[test]
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();
+1 -2
View File
@@ -40,8 +40,7 @@ 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
// 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;
const LDAP_EPOCH_DELTA: u64 = 116444772610000000;
lazy_static! {
static ref REMOTE_FORMAT_MAP: DashMap<i32, String> = DashMap::from_iter(
+13 -610
View File
@@ -1,27 +1,11 @@
use crate::{
platform::unix::{
filetype::file_list_id,
local_file::{construct_file_list, LocalFile},
},
ClipboardFile, CliprdrError,
};
use super::local_file::LocalFile;
use crate::{platform::unix::local_file::construct_file_list, ClipboardFile, CliprdrError};
use hbb_common::{
bytes::{BufMut, BytesMut},
log,
};
use parking_lot::Mutex;
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;
use std::{path::PathBuf, sync::Arc, time::SystemTime, usize};
lazy_static::lazy_static! {
// local files are cached, this value should not be changed when copying files
@@ -29,18 +13,8 @@ lazy_static::lazy_static! {
// We need to keep the file list in the same order as the remote side.
// We 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 {
@@ -88,10 +62,6 @@ 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 {
@@ -101,8 +71,6 @@ 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(
@@ -132,54 +100,9 @@ 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, ..
@@ -290,21 +213,12 @@ impl ClipFiles {
),
});
}
let read_size = if length > file.size - offset {
let read_size = if offset + length > file.size {
file.size - offset
} 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)?;
@@ -324,10 +238,7 @@ impl ClipFiles {
// hot reload next file
for next_file in self.file_list.iter_mut().skip(file_idx + 1) {
if !next_file.is_dir {
// 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);
}
next_file.load_handle()?;
break;
}
}
@@ -338,44 +249,6 @@ 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(
@@ -386,7 +259,6 @@ 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 {
@@ -394,11 +266,8 @@ pub fn read_file_contents(
file_idx: list_index as usize,
}
} else if dw_flags == 0x2 {
// 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;
let offset = (n_position_high as u64) << 32 | n_position_low as u64;
let length = cb_requested as u64;
FileContentsRequest::Range {
stream_id,
@@ -412,23 +281,7 @@ pub fn read_file_contents(
})];
};
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 clip_files = CLIP_FILES.lock();
let mut res = vec![];
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
res.push(Ok(files_res));
@@ -448,21 +301,12 @@ pub fn sync_files(files: &[String]) -> Result<(), CliprdrError> {
{
return Ok(());
}
// 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(())
files_lock.sync_files(files, current)?;
files_lock.build_file_list_pdu()
}
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()
pub fn get_file_list_pdu() -> Vec<u8> {
CLIP_FILES.lock().files_pdu.clone()
}
#[cfg(test)]
@@ -499,30 +343,6 @@ 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");
@@ -573,8 +393,7 @@ mod sig_test {
let files = vec![path_str(&file)];
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
// reset first.
let _guard = lock_clip_files();
// reset first (this is the only test that touches the global).
clear_files();
sync_files(&files).unwrap();
@@ -596,420 +415,4 @@ 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");
}
}
+13 -361
View File
@@ -54,12 +54,6 @@
/* 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"<>:\"|?*";
@@ -219,21 +213,6 @@ 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
*/
@@ -379,7 +358,6 @@ 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;
@@ -399,21 +377,6 @@ 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;
@@ -461,10 +424,6 @@ 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;
@@ -492,8 +451,8 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
static UINT cliprdr_send_lock(wfClipboard *clipboard);
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
UINT32 clipDataId, ULONG index, UINT32 flag,
DWORD positionhigh, DWORD positionlow, ULONG request);
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);
@@ -505,7 +464,6 @@ 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)
{
@@ -592,11 +550,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
return S_FALSE;
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,
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId, instance->m_lIndex,
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
instance->m_lOffset.LowPart, cb);
@@ -637,26 +591,6 @@ 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)
{
@@ -802,8 +736,7 @@ 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,
UINT32 clipDataId)
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc)
{
IStream *iStream = NULL;
BOOL success = FALSE;
@@ -846,7 +779,6 @@ 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)
{
@@ -858,8 +790,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_clipDataId, instance->m_lIndex,
FILECONTENTS_SIZE, 0, 0, 8) == CHANNEL_RC_OK)
instance->m_lIndex, FILECONTENTS_SIZE, 0, 0,
8) == CHANNEL_RC_OK)
{
success = TRUE;
}
@@ -1075,7 +1007,6 @@ 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)
@@ -1122,11 +1053,10 @@ 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], clipDataId);
streams[i] =
(IStream *)CliprdrStream_New(instance->m_connID, i, clipboard, &dsc->fgd[i]);
if (!streams[i])
{
return wf_cliprdr_fail_locked_file_descriptor_data(
@@ -2066,9 +1996,9 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
}
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
UINT32 clipDataId, ULONG index, UINT32 flag,
DWORD positionhigh, DWORD positionlow, ULONG nreq)
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId, ULONG index,
UINT32 flag, DWORD positionhigh, DWORD positionlow,
ULONG nreq)
{
UINT rc;
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
@@ -2093,8 +2023,7 @@ static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 con
fileContentsRequest.nPositionLow = positionlow;
fileContentsRequest.nPositionHigh = positionhigh;
fileContentsRequest.cbRequested = nreq;
fileContentsRequest.haveClipDataId = TRUE;
fileContentsRequest.clipDataId = clipDataId;
fileContentsRequest.clipDataId = 0;
fileContentsRequest.msgFlags = 0;
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
if (rc != ERROR_SUCCESS)
@@ -2495,242 +2424,6 @@ 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)
{
@@ -3335,8 +3028,6 @@ 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))
@@ -3473,10 +3164,6 @@ 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
{
@@ -3689,18 +3376,6 @@ 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:
@@ -3726,22 +3401,6 @@ 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);
@@ -3771,13 +3430,7 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
vFormatEtc.lindex = fileContentsRequest->listIndex;
vFormatEtc.ptd = NULL;
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) ||
if ((uStreamIdStc != fileContentsRequest->streamId) ||
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
{
LPENUMFORMATETC pEnumFormatEtc;
@@ -4189,7 +3842,6 @@ 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;
-55
View File
@@ -36,7 +36,6 @@ const kUCKeyActionDisplay: u16 = 3;
#[allow(non_upper_case_globals)]
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
const BUF_LEN: usize = 4;
const KEYBOARD_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
const MOUSE_EVENT_BUTTON_NUMBER_BACK: i64 = 3;
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
@@ -429,19 +428,7 @@ impl KeyboardControllable for Enigo {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
event.set_string(cluster);
self.post(event, None);
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: event source is not initialized"
);
}
}
}
@@ -449,40 +436,17 @@ impl KeyboardControllable for Enigo {
fn key_click(&mut self, key: Key) {
let keycode = self.key_to_keycode(key);
if keycode == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: keycode mapping is unavailable"
);
return;
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-down in key-click: could not create keyboard event"
);
}
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up in key-click: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: event source is not initialized"
);
}
}
@@ -501,29 +465,10 @@ impl KeyboardControllable for Enigo {
fn key_up(&mut self, key: Key) {
let code = self.key_to_keycode(key);
if code == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Cannot map macOS Enigo key-up to a keycode"
);
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
self.post(event, Some(code));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: event source is not initialized"
);
}
}
+4 -30
View File
@@ -39,17 +39,6 @@ fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) -> DWORD {
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
}
// `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 {
@@ -137,28 +126,13 @@ 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,
dx,
dy,
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535
/ unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535
/ unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
);
}
+15 -44
View File
@@ -5,7 +5,7 @@ use winapi::{
shared::{
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
ntdef::HANDLE,
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
winerror::ERROR_INVALID_PRINTER_NAME,
},
um::winspool::{
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
@@ -42,49 +42,20 @@ fn enum_local_printer(
#[inline]
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
const PRINTER_INFO_LEVEL: DWORD = 1;
let mut needed = 0;
let mut returned = 0;
if enum_local_printer(
PRINTER_INFO_LEVEL,
null_mut(),
0,
&mut needed,
&mut returned,
) == FALSE
{
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
bail!("Failed to query EnumPrintersW buffer size: {error}");
}
}
if needed == 0 {
return Ok(false);
}
let mut buffer = vec![0u8; needed as usize];
if enum_local_printer(
PRINTER_INFO_LEVEL,
buffer.as_mut_ptr(),
needed,
&mut needed,
&mut returned,
) == FALSE
{
bail!(
"Failed to call EnumPrintersW, error: {}",
io::Error::last_os_error()
);
}
let printers = buffer.as_ptr() as *const PRINTER_INFO_1W;
for index in 0..returned {
let printer = unsafe { &*printers.add(index as usize) };
if is_name_equal(name, printer.pName) {
return Ok(true);
}
}
Ok(false)
let r = common_enum(
"EnumPrintersW",
enum_local_printer,
1,
|info: &PRINTER_INFO_1W| {
if is_name_equal(name, info.pName) {
Some(true)
} else {
None
}
},
|| None,
)?;
Ok(r.unwrap_or(false))
}
// Only return the first matched printer
+1 -1
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.8). We deliberately do
# `DRMTAP_SHA` in build.py, which fetches that exact commit (libdrmtap v0.5.6). We deliberately do
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
# 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
-130
View File
@@ -36,9 +36,6 @@ pub struct CursorSnapshot {
/// 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.
@@ -377,9 +374,6 @@ pub struct DrmReader {
/// 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 {
@@ -417,7 +411,6 @@ impl DrmReader {
lib,
ctx,
buf: Vec::new(),
last_plane_rotation: None,
})
}
@@ -441,7 +434,6 @@ 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());
@@ -536,29 +528,6 @@ 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)
}
/// The primary plane's rotation read NOW, for a caller that has not grabbed (enumeration):
/// `plane_rotation()` only reflects the last grab.
pub fn query_plane_rotation(&mut self) -> Option<u32> {
self.read_plane_rotation()
}
/// Zero-copy EXPORT grab: fills a `drmtap_dmabuf_desc` (dma-buf fd, plane layout, HDR metadata) WITHOUT mapping, detiling or copying pixels, so on this
/// path the root process never loads libEGL/libGLESv2. The exported fd is READ-ONLY (libdrmtap drops `DRM_RDWR` and `dup` shares that open file
/// description), so the `--server` that receives it can map the scanout but never write the live framebuffer. Validation here is METADATA ONLY.
@@ -590,7 +559,6 @@ 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
@@ -671,8 +639,6 @@ impl DrmReader {
hoty: 0,
hot_measured: false,
colors: vec![0, 0, 0, 0],
x: 0,
y: 0,
})
} else if !c.pixels.is_null()
&& c.width > 0
@@ -725,8 +691,6 @@ impl DrmReader {
hoty,
hot_measured,
colors,
x: c.x,
y: c.y,
})
} else {
None
@@ -1014,97 +978,3 @@ mod hotspot_guess_tests {
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");
}
}
-72
View File
@@ -140,12 +140,6 @@ 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;
@@ -168,64 +162,9 @@ pub struct DrmtapLib {
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 {}
@@ -351,8 +290,6 @@ impl DrmtapLib {
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()
@@ -396,14 +333,6 @@ impl DrmtapLib {
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,
@@ -419,7 +348,6 @@ impl DrmtapLib {
open_render,
convert_dmabuf,
render_node,
plane_rotation,
version: (major, minor, patch),
})
}
+5 -160
View File
@@ -23,7 +23,7 @@ use gstreamer_app::AppSink;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use base::platform::linux::{WaylandDisplayInfo, CMD_SH};
use base::platform::linux::CMD_SH;
use hbb_common::{anyhow::anyhow, bail, config, serde_json, tokio, ResultType};
use super::capturable::PixelProvider;
@@ -157,9 +157,6 @@ pub struct PipeWireCapturable {
pub position: (i32, i32),
pub logical_size: (usize, usize),
pub physical_size: (usize, usize),
// False when `physical_size` is the portal size standing in for a resolution get_res() could
// not read.
physical_size_measured: bool,
}
impl PipeWireCapturable {
@@ -171,7 +168,7 @@ impl PipeWireCapturable {
) -> Self {
// alternative to get screen resolution as stream.size is not always correct ex: on fractional scaling
// https://github.com/rustdesk/rustdesk/issues/6116#issuecomment-1817724244
let measured = get_res(Self {
let physical_size = get_res(Self {
dbus_conn: conn.clone(),
fd: fd.clone(),
path: stream.path,
@@ -180,10 +177,8 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size: (0, 0),
physical_size_measured: false,
});
let physical_size_measured = measured.is_ok();
let physical_size = measured.unwrap_or(stream.size);
})
.unwrap_or(stream.size);
*resolution.lock().unwrap() = Some(physical_size);
Self {
dbus_conn: conn,
@@ -194,7 +189,6 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size,
physical_size_measured,
}
}
}
@@ -283,8 +277,6 @@ fn gst_element(name: &str) -> ResultType<gst::Element> {
impl PipeWireRecorder {
pub fn new(capturable: PipeWireCapturable) -> ResultType<Self> {
let pipeline = gst::Pipeline::new(None);
// Clock waits on stale capture timestamps can exhaust the compositor's buffers.
pipeline.use_clock(None::<&gst::Clock>);
let src = gst_element("pipewiresrc")?;
src.set_property("fd", &capturable.fd.as_raw_fd())?;
@@ -1297,26 +1289,6 @@ pub fn fill_displays(
}
if all_displays.displays.len() > 1 {
for (i, sd) in shared_displays.iter_mut().enumerate() {
if let crate::Display::WAYLAND(d) = sd {
let capturable = &mut d.0;
if let Some(origin) = reconciled_origin(
capturable.position,
capturable.physical_size,
capturable.physical_size_measured,
&all_displays.displays,
) {
warn!(
"Position {:?} names no output of size {:?}, using {:?}.",
capturable.position, capturable.physical_size, origin
);
capturable.position = origin;
if let Some(pw_stream) = rdp_info.streams.get_mut(i) {
pw_stream.position = origin;
}
}
}
}
sort_streams(&all_displays, shared_displays, &mut rdp_info.streams);
}
@@ -1329,50 +1301,6 @@ pub fn fill_displays(
Ok(())
}
// The origin a stream takes when its position names no output of its size. Only a measured size
// moves a position: when get_res() failed, the size is the portal size, which can be the mode of
// another output and says less than the position does, whether the portal sent that position or
// try_fill_positions restored it from its cache.
fn reconciled_origin(
position: (i32, i32),
size: (usize, usize),
size_measured: bool,
outputs: &[WaylandDisplayInfo],
) -> Option<(i32, i32)> {
if !size_measured {
return None;
}
corrected_origin(position, size, outputs)
}
// The origin for a stream whose position names no output of the stream's size (a rotated output
// counts in either orientation), when exactly one output has that size. xdg-desktop-portal-hyprland reports every stream at (0, 0):
// with no output there `sort_streams` dropped the stream, and with another output there the
// stream took its origin and missed `try_fix_logical_size`, so the pointer landed on the wrong
// output (#15731). With several outputs of that size the position is kept.
fn corrected_origin(
position: (i32, i32),
size: (usize, usize),
outputs: &[WaylandDisplayInfo],
) -> Option<(i32, i32)> {
let has_size = |o: &&WaylandDisplayInfo| {
let mode = (o.width as usize, o.height as usize);
mode == size || (o.transform % 180 != 0 && (mode.1, mode.0) == size)
};
if outputs
.iter()
.filter(has_size)
.any(|o| (o.x, o.y) == position)
{
return None;
}
let mut same_size = outputs.iter().filter(has_size);
match (same_size.next(), same_size.next()) {
(Some(o), None) => Some((o.x, o.y)),
_ => None,
}
}
fn try_fill_positions(
mouse_move_to: impl Fn(i32, i32),
get_cursor_pos: fn() -> Option<(i32, i32)>,
@@ -1675,7 +1603,6 @@ fn fill_multi_matched_positions_cursor(
position: pw_stream_with_cursor.position,
logical_size: pw_stream_with_cursor.size,
physical_size: (0, 0),
physical_size_measured: false,
})?;
// Take first frame and copy owned buffer to avoid borrow across second capture
let (is_bgr, w, first_buf): (bool, usize, Vec<u8>) =
@@ -1802,89 +1729,7 @@ fn sort_streams(
#[cfg(test)]
mod tests {
use super::{corrected_origin, reconciled_origin, stage_err, WaylandDisplayInfo};
fn output(x: i32, y: i32, mode: (i32, i32)) -> WaylandDisplayInfo {
WaylandDisplayInfo {
name: String::new(),
x,
y,
width: mode.0,
height: mode.1,
logical_size: None,
refresh_rate: 60,
transform: 0,
}
}
#[test]
fn a_portal_position_naming_no_output_of_its_size_moves_to_the_only_one() {
// 1920x1080 at the origin, 2880x1800 to its right: xdph puts the right one at (0, 0).
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
assert_eq!(
corrected_origin((0, 0), (2880, 1800), &pair),
Some((1920, 0))
);
// A real origin is kept.
assert_eq!(corrected_origin((1920, 0), (2880, 1800), &pair), None);
// Nothing starts at the origin (the hyprland layout in #15731).
let three = [
output(0, 120, (1920, 1200)),
output(1920, 0, (3440, 1440)),
output(5360, 180, (1920, 1080)),
];
assert_eq!(
corrected_origin((0, 0), (3440, 1440), &three),
Some((1920, 0))
);
// Two outputs of that size cannot be told apart: the position is kept.
let twins = [
output(0, 0, (2560, 1600)),
output(2560, 0, (1920, 1080)),
output(4480, 0, (1920, 1080)),
];
assert_eq!(corrected_origin((0, 0), (1920, 1080), &twins), None);
// A portrait panel turned to landscape keeps its position next to a 1920x1080 output.
let turned = [
WaylandDisplayInfo {
transform: 90,
..output(0, 0, (1080, 1920))
},
output(1920, 0, (1920, 1080)),
];
assert_eq!(corrected_origin((0, 0), (1920, 1080), &turned), None);
// A rotated output that try_fill_positions could not match by its mode is found in its
// delivered orientation.
let turned_right = [
output(0, 0, (2560, 1440)),
WaylandDisplayInfo {
transform: 90,
..output(2560, 0, (1080, 1920))
},
];
assert_eq!(
corrected_origin((0, 0), (1920, 1080), &turned_right),
Some((2560, 0))
);
}
#[test]
fn a_cached_position_is_not_overridden_by_an_unmeasured_size() {
let outputs = [output(0, 0, (1440, 900)), output(1920, 0, (2880, 1800))];
// Restored from the cache, or sent by the portal: get_res() failed, so the size is the
// portal size, here the mode of the other output, and it moves nothing.
assert_eq!(
reconciled_origin((1920, 0), (1440, 900), false, &outputs),
None
);
// A measured size still moves a position that names no output of that size: xdph sends
// (0, 0) for every stream.
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
assert_eq!(
reconciled_origin((0, 0), (2880, 1800), true, &pair),
Some((1920, 0))
);
}
use super::stage_err;
#[test]
fn stage_err_keeps_the_detail_safe_for_a_placeholder() {
-1
View File
@@ -14,4 +14,3 @@ EXPORTS
RemoveAmyuniIdd
InstallPrinter
UninstallPrinter
SetPrinterInstallDefault
-66
View File
@@ -3,7 +3,6 @@
#include <Windows.h>
#include <winspool.h>
#include <setupapi.h>
#include <strutil.h>
#include <memory>
#include <string>
#include <functional>
@@ -357,42 +356,6 @@ namespace RemotePrinter
return EnumPrintersW(PRINTER_ENUM_LOCAL, NULL, level, pPrinterInfo, cbBuf, pcbNeeded, pcReturned);
}
static HRESULT queryPrinterPresence(LPCWSTR name)
{
constexpr DWORD printerInfoLevel = 1;
DWORD needed = 0;
DWORD returned = 0;
if (!enumLocalPrinter(printerInfoLevel, NULL, 0, &needed, &returned))
{
const DWORD error = GetLastError();
if (error != ERROR_INSUFFICIENT_BUFFER || needed == 0)
{
return error == ERROR_SUCCESS ? E_FAIL : HRESULT_FROM_WIN32(error);
}
}
if (needed == 0)
{
return S_FALSE;
}
std::vector<BYTE> buffer(needed);
if (!enumLocalPrinter(printerInfoLevel, buffer.data(), needed, &needed, &returned))
{
const DWORD error = GetLastError();
return error == ERROR_SUCCESS ? E_FAIL : HRESULT_FROM_WIN32(error);
}
const auto printers = reinterpret_cast<const PRINTER_INFO_1W *>(buffer.data());
for (DWORD i = 0; i < returned; i++)
{
if (isNameEqual(name, printers[i].pName))
{
return S_OK;
}
}
return S_FALSE;
}
BOOL isPrinterAdded(LPCWSTR name)
{
auto onData = [name](const PRINTER_INFO_1W &info)
@@ -565,32 +528,3 @@ namespace RemotePrinter
WcaLog(LOGMSG_STANDARD, "Deleted the local port\n");
}
}
extern "C" UINT __stdcall SetPrinterInstallDefault(__in MSIHANDLE hInstall)
{
HRESULT hr = S_OK;
LPWSTR appName = NULL;
hr = WcaInitialize(hInstall, "SetPrinterInstallDefault");
ExitOnFailure(hr, "Failed to initialize printer detection");
hr = WcaGetProperty(L"ProductName", &appName);
ExitOnFailure(hr, "Failed to get the printer's application name");
hr = RemotePrinter::queryPrinterPresence(RemotePrinter::printerNameOf(appName).c_str());
if (FAILED(hr))
{
WcaLog(LOGMSG_STANDARD, "Failed to detect the existing printer (0x%08X); skipping printer installation.", static_cast<UINT>(hr));
}
if (hr != S_OK)
{
hr = WcaSetProperty(L"INSTALLPRINTER", L"0");
ExitOnFailure(hr, "Failed to disable printer installation");
WcaLog(LOGMSG_STANDARD, "The application's printer was not confirmed present; leaving printer installation disabled by default.");
}
LExit:
ReleaseStr(appName);
return WcaFinalize(SUCCEEDED(hr) ? ERROR_SUCCESS : ERROR_INSTALL_FAILURE);
}
@@ -74,22 +74,13 @@
<SetProperty Action="RestoreSavedDesktopShortcutsValue" Id="CREATEDESKTOPSHORTCUTS" Value="[SavedDesktopShortcutsCmdLineValue]" After="AppSearch" Sequence="first" Condition="SavedDesktopShortcutsCmdLineValue" />
<SetProperty Action="RestoreSavedPrinterValue" Id="INSTALLPRINTER" Value="[SavedPrinterCmdLineValue]" After="AppSearch" Sequence="first" Condition="SavedPrinterCmdLineValue" />
<!-- Check before the old product removes its printer. firstSequence preserves later UI choices. -->
<CustomAction Id="SetPrinterInstallDefault" DllEntry="SetPrinterInstallDefault" Execute="firstSequence" Return="check" BinaryRef="Custom_Actions_Dll" />
<InstallUISequence>
<Custom Action="SetPrinterInstallDefault" After="RestoreSavedPrinterValue" Condition="WIX_UPGRADE_DETECTED AND NOT SavedPrinterCmdLineValue AND (INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;)" />
</InstallUISequence>
<InstallExecuteSequence>
<Custom Action="SetPrinterInstallDefault" After="RestoreSavedPrinterValue" Condition="WIX_UPGRADE_DETECTED AND NOT SavedPrinterCmdLineValue AND (INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;)" />
</InstallExecuteSequence>
<!-- If a command line value or registry value was set, update the main properties with the value -->
<SetProperty Id="STARTMENUSHORTCUTS" Value="" After="RestoreSavedStartMenuShortcutsValue" Sequence="first" Condition="CREATESTARTMENUSHORTCUTS AND NOT (CREATESTARTMENUSHORTCUTS = 1 OR CREATESTARTMENUSHORTCUTS = &quot;Y&quot; OR CREATESTARTMENUSHORTCUTS = &quot;y&quot;)" />
<SetProperty Id="DESKTOPSHORTCUTS" Value="" After="RestoreSavedDesktopShortcutsValue" Sequence="first" Condition="CREATEDESKTOPSHORTCUTS AND NOT (CREATEDESKTOPSHORTCUTS = 1 OR CREATEDESKTOPSHORTCUTS = &quot;Y&quot; OR CREATEDESKTOPSHORTCUTS = &quot;y&quot;)" />
<!-- PRINTER defaults to empty now, so a saved or command-line INSTALLPRINTER=1
must explicitly enable the main PRINTER property. Non-truthy INSTALLPRINTER
values still clear PRINTER so upgrades preserve an explicit disabled choice. -->
<SetProperty Action="SetPrinterValueEnabled" Id="PRINTER" Value="1" After="SetPrinterInstallDefault" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;" />
<SetProperty Action="SetPrinterValueEnabled" Id="PRINTER" Value="1" After="RestoreSavedPrinterValue" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;" />
<SetProperty Action="SetPrinterValueDisabled" Id="PRINTER" Value="" After="SetPrinterValueEnabled" Sequence="first" Condition="INSTALLPRINTER AND NOT (INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;)" />
</Fragment>
+17 -57
View File
@@ -1,7 +1,9 @@
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use crate::clipboard::clipboard_listener::{self, ClipboardEvent};
use crate::clipboard::clipboard_listener;
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},
@@ -1940,19 +1942,14 @@ impl Client {
break;
}
match rx_cb_result.recv_timeout(Duration::from_millis(CLIPBOARD_INTERVAL)) {
Ok(ClipboardEvent::Changed) => {
handler.check_clipboard(true);
Ok(CallbackResult::Next) => {
handler.check_clipboard();
}
#[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) => {
Ok(CallbackResult::Stop) => {
log::debug!("Clipboard listener stopped");
break;
}
Ok(ClipboardEvent::StopWithError(err)) => {
Ok(CallbackResult::StopWithError(err)) => {
log::error!("Clipboard listener stopped with error: {}", err);
break;
}
@@ -2054,16 +2051,16 @@ impl ClientClipboardHandler {
}
}
fn check_clipboard(&mut self, check_text: bool) {
fn check_clipboard(&mut self) {
if CLIPBOARD_STATE.lock().unwrap().running {
#[cfg(feature = "unix-file-copy-paste")]
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;
}
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() {
match clipboard::platform::unix::serv_files::sync_files(&urls) {
Ok(()) => {
let msg = crate::clipboard_file::clip_2_msg(
@@ -2080,8 +2077,8 @@ impl ClientClipboardHandler {
}
}
if check_text && self.is_text_required() {
if let Some(msg) = check_clipboard(&mut self.ctx, ClipboardSide::Client, false) {
if let Some(msg) = check_clipboard(&mut self.ctx, ClipboardSide::Client, false) {
if self.is_text_required() {
self.send_msg(msg, false);
}
}
@@ -4467,32 +4464,6 @@ fn _input_os_password(p: String, activate: bool, interface: impl Interface) {
interface.send(Data::Message(msg_out));
}
/// Auto Login. A peer that can check for its logon or lock screen gets the password and types it
/// itself, only if it is there right then. Keys typed from here land in whatever has focus if the
/// screen is not locked by the time they arrive.
pub fn auto_login(p: String, pi: &PeerInfo, interface: impl Interface) {
if !is_peer_handling_os_login(pi) {
input_os_password(p, true, interface);
return;
}
std::thread::spawn(move || {
activate_os(&interface, true);
std::thread::sleep(Duration::from_millis(1200));
let mut msg_out = Message::new();
msg_out.set_os_login(OSLogin {
password: p,
..Default::default()
});
interface.send(Data::Message(msg_out));
});
}
/// Windows and macOS peers from the 1.5.1 release handle `os_login`.
fn is_peer_handling_os_login(pi: &PeerInfo) -> bool {
(pi.platform == crate::common::PLATFORM_WINDOWS || pi.platform == crate::common::PLATFORM_MACOS)
&& hbb_common::get_version_number(&pi.version) >= hbb_common::get_version_number("1.5.1")
}
#[derive(Copy, Clone)]
struct LoginErrorMsgBox {
msgtype: &'static str,
@@ -5002,8 +4973,6 @@ 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)),
@@ -5400,15 +5369,6 @@ 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() {
+28 -169
View File
@@ -1,5 +1,5 @@
#[cfg(not(any(target_os = "android", target_os = "ios")))]
use crate::clipboard::{clipboard_listener, update_clipboard, ClipboardSide};
use crate::clipboard::{update_clipboard, ClipboardSide};
#[cfg(not(any(target_os = "ios")))]
use crate::{audio_service, clipboard::CLIPBOARD_INTERVAL, ConnInner, CLIENT_SERVER};
use crate::{
@@ -84,12 +84,7 @@ 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
@@ -138,8 +133,6 @@ 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,
@@ -441,11 +434,6 @@ 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();
}
@@ -459,7 +447,7 @@ impl<T: InvokeUiSession> Remote<T> {
#[cfg(any(target_os = "windows", feature = "unix-file-copy-paste"))]
async fn handle_local_clipboard_msg(
&mut self,
&self,
peer: &mut Stream,
msg: Option<clipboard::ClipboardFile>,
) {
@@ -472,10 +460,6 @@ 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 =
@@ -484,7 +468,9 @@ 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 || !(server_file_transfer_enabled && file_transfer_enabled));
&& (view_only
|| !self.is_connected
|| !(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
@@ -501,10 +487,6 @@ 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);
}
@@ -645,82 +627,6 @@ 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 => {
@@ -736,27 +642,6 @@ 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
@@ -772,20 +657,6 @@ 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)| {
@@ -1598,14 +1469,6 @@ 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);
@@ -1627,18 +1490,31 @@ 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.is_connected
&& self.handler.is_text_clipboard_required()
&& self.handler.lc.read().unwrap().sync_init_clipboard.v
{
self.start_initial_clipboard_sync();
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();
}
});
}
}
// 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() {
@@ -1699,10 +1575,7 @@ 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")))]
{
self.initial_clipboard_pending = false;
update_clipboard(vec![cb], ClipboardSide::Client);
}
update_clipboard(vec![cb], ClipboardSide::Client);
#[cfg(target_os = "ios")]
{
let content = if cb.compress {
@@ -1737,10 +1610,7 @@ 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")))]
{
self.initial_clipboard_pending = false;
update_clipboard(_mcb.clipboards, ClipboardSide::Client);
}
update_clipboard(_mcb.clipboards, ClipboardSide::Client);
#[cfg(target_os = "ios")]
{
if let Some(cb) = _mcb
@@ -2567,10 +2437,6 @@ 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 {
@@ -2602,9 +2468,6 @@ 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)
@@ -2613,10 +2476,6 @@ 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")]
+16 -107
View File
@@ -34,6 +34,8 @@ 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.
@@ -77,7 +79,8 @@ pub fn check_clipboard(
side: ClipboardSide,
force: bool,
) -> Option<Message> {
let (msg, _) = read_clipboard_message(ctx, side, force)?;
let (msg, clipboards) = read_clipboard_message(ctx, side, force)?;
*LAST_MULTI_CLIPBOARDS.lock().unwrap() = clipboards;
Some(msg)
}
@@ -561,25 +564,18 @@ pub fn get_current_clipboard_msg(
peer_platform: &str,
side: ClipboardSide,
) -> Option<Message> {
// 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 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()?);
}
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.
@@ -892,13 +888,10 @@ 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,
@@ -908,83 +901,15 @@ 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<ClipboardEvent>>>>,
#[cfg(target_os = "linux")]
ready: Option<watch::Sender<bool>>,
subscribers: Arc<Mutex<HashMap<String, Sender<CallbackResult>>>>,
}
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(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);
}
tx.send(CallbackResult::Next).ok();
}
CallbackResult::Next
}
@@ -993,30 +918,23 @@ 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(ClipboardEvent::StopWithError(io::Error::new(
tx.send(CallbackResult::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<ClipboardEvent>>>>,
subscribers: Arc<Mutex<HashMap<String, Sender<CallbackResult>>>>,
handle: Option<(Shutdown, JoinHandle<()>)>,
#[cfg(target_os = "linux")]
ready: Option<watch::Receiver<bool>>,
}
pub fn subscribe(name: String, tx: Sender<ClipboardEvent>) -> ResultType<()> {
pub fn subscribe(name: String, tx: Sender<CallbackResult>) -> ResultType<()> {
log::info!("Subscribe clipboard listener: {}", &name);
let mut listener_lock = CLIPBOARD_LISTENER.lock().unwrap();
listener_lock
@@ -1028,12 +946,8 @@ 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);
@@ -1048,11 +962,6 @@ 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");
}
@@ -1084,7 +993,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(ClipboardEvent::Stop).ok();
tx.send(CallbackResult::Stop).ok();
}
sub_lock.is_empty()
};
+3 -66
View File
@@ -224,13 +224,6 @@ 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::*;
@@ -321,7 +314,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(conn_id);
let format_data = serv_files::get_file_list_pdu();
if !format_data.is_empty() {
return vec![clip_2_msg(ClipboardFile::FormatDataResponse {
msg_flags: 1,
@@ -372,8 +365,7 @@ 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(
@@ -384,18 +376,12 @@ 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) => {
hbb_common::throttled_log!(
std::time::Duration::from_secs(5),
error,
"failed to read file contents: {:?}",
e
);
log::error!("failed to read file contents: {:?}", e);
resp_file_contents_fail(stream_id)
}
})
@@ -447,52 +433,3 @@ 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![] }));
}
}
+7
View File
@@ -737,6 +737,13 @@ async fn test_nat_type_() -> ResultType<bool> {
} else {
port2 = tnr.port;
}
if let Some(cu) = tnr.cu.as_ref() {
Config::set_option(
"rendezvous-servers".to_owned(),
cu.rendezvous_servers.join(","),
);
Config::set_serial(cu.serial);
}
}
} else {
break;
-2
View File
@@ -1415,7 +1415,6 @@ 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);
@@ -1426,7 +1425,6 @@ 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);
}
+2 -83
View File
@@ -267,8 +267,6 @@ pub enum DataKeyboard {
#[serde(tag = "t", content = "c")]
pub enum DataKeyboardResponse {
GetKeyState(bool),
#[cfg(target_os = "linux")]
GetKeyStateError(String),
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
@@ -515,17 +513,13 @@ pub enum Data {
CmWindowClosed,
// --- DRM/KMS capture (opt-in `drm` feature) over the `_drm` service-scoped channel ---
// All of the following are `cfg(all(linux, drm))`, so the drm-off IPC wire is byte-identical
// to upstream. `_drm` protocol: the client sends `DrmHello`, the service `DrmDisplayList`, the
// to upstream. Protocol on `_drm`: on connect the root service sends `DrmDisplayList`, the
// client replies `DrmStart{display}`, then the service streams `DrmFrame` + send_raw(BGRA) and
// `DrmCursor` + send_raw(RGBA). A frame/cursor header is ALWAYS immediately followed by exactly
// one `send_raw()` payload (the same header-then-raw pairing as `FileBlockFromCM`). This keeps
// the header extensible. The zero-copy `DrmFrameDmabuf(DmabufDesc)` sibling below carries only a
// small JSON metadata descriptor; the scanout dma-buf fd rides an SCM_RIGHTS ancillary message on
// the same `DrmConn` send (see `DrmConn::send_msg`), so it has NO trailing `send_raw()` body.
/// Client -> service, first on `_drm`: whether the service may wake sleeping displays before
/// it answers. The cache warm at every `--server` start says no: no peer is waiting for it.
#[cfg(all(target_os = "linux", feature = "drm"))]
DrmHello { wake: bool },
/// Client -> service: begin streaming the chosen display.
#[cfg(all(target_os = "linux", feature = "drm"))]
// `need_cpu` is set by an unprivileged consumer that could not open a render-node convert context
@@ -546,17 +540,7 @@ 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,
/// 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)>,
},
DrmFrame { width: u32, height: u32 },
/// 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
@@ -2385,69 +2369,4 @@ mod test {
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:?}"),
}
}
}
+17 -245
View File
@@ -23,10 +23,6 @@ pub struct DrmDisplayInfo {
/// alone is ambiguous across cards. Empty = the single auto-detected device.
#[serde(default)]
pub device: String,
/// The primary plane rotates its framebuffer by 90/270 in hardware, so every frame is this
/// mode TRANSPOSED whatever the compositor reports (gamescope's wl_output has no transform).
#[serde(default)]
pub plane_transposed: bool,
}
/// Mirrors `scrap::drm_reader::drmtap_dmabuf_desc` except `dma_buf_fd` (never serializes — it rides
@@ -49,21 +45,6 @@ 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 {
@@ -119,11 +100,6 @@ 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,
@@ -136,107 +112,6 @@ enum DrmProducerMsg {
},
}
/// 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) {
@@ -284,7 +159,6 @@ fn drm_displays_from_reader(
true
})
.map(|d| DrmDisplayInfo {
plane_transposed: plane_transposed(device, d.crtc_id),
name: d.name,
crtc_id: d.crtc_id,
x: d.x,
@@ -299,33 +173,6 @@ fn drm_displays_from_reader(
(displays, undriven)
}
const DRM_MODE_ROTATE_90: u32 = 0x2;
const DRM_MODE_ROTATE_270: u32 = 0x8;
/// Through a reader bound to `crtc_id`: the enumerating reader is bound to whichever crtc
/// auto-select picked.
fn plane_transposed(device: &str, crtc_id: u32) -> bool {
let dev = (!device.is_empty()).then_some(device);
let Some(mut r) = scrap::drm_reader::DrmReader::open(dev, crtc_id) else {
return false;
};
let transposed = match r.query_plane_rotation() {
Some(m) => m & (DRM_MODE_ROTATE_90 | DRM_MODE_ROTATE_270) != 0,
None => {
hbb_common::throttled_log!(
std::time::Duration::from_secs(600),
debug,
"drm: crtc {crtc_id} ({device:?}): plane rotation unreadable; sized as unrotated"
);
false
}
};
if transposed {
log::trace!("drm: crtc {crtc_id} ({device:?}) is rotated 90/270 by its plane");
}
transposed
}
/// Active displays of every DRM device + the connected-but-undriven identities, from ONE look.
fn drm_enumerate_all_displays() -> (Vec<DrmDisplayInfo>, Vec<String>) {
if let Some(devices) = scrap::drm_reader::list_devices() {
@@ -946,20 +793,6 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
let mut conn = dup_to_drm_conn(&stream)?;
drop(stream);
let wake = match conn.recv_msg_timeout2(3_000).await {
Some(Ok((Data::DrmHello { wake }, _fd))) => wake,
Some(Ok((_, _fd))) => {
hbb_common::throttled_log!(
std::time::Duration::from_secs(5),
info,
"drm: peer did not open with DrmHello; closing"
);
return Ok(());
}
Some(Err(e)) => return Err(e),
None => return Ok(()),
};
let (frame_tx, mut frame_rx) = tokio::sync::mpsc::channel::<DrmProducerMsg>(2);
let (crtc_tx, crtc_rx) = std::sync::mpsc::channel::<(String, u32, bool)>();
let stop = Arc::new(AtomicBool::new(false));
@@ -969,7 +802,7 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
let worker_gate = frames_gated.clone();
std::thread::Builder::new()
.name("drm-capture".into())
.spawn(move || drm_capture_worker(frame_tx, crtc_rx, worker_stop, worker_gate, wake))
.spawn(move || drm_capture_worker(frame_tx, crtc_rx, worker_stop, worker_gate))
.map_err(|err| anyhow::anyhow!("could not spawn the drm capture worker: {err}"))?;
let displays = match frame_rx.recv().await {
@@ -1127,19 +960,8 @@ async fn handle_drm_conn(stream: Connection) -> ResultType<()> {
width,
height,
data,
plane_rotation,
cursor_pos,
}) => {
conn.send_msg(
&Data::DrmFrame {
width,
height,
plane_rotation,
cursor_pos,
},
None,
)
.await?;
conn.send_msg(&Data::DrmFrame { width, height }, None).await?;
conn.send_raw(data).await?;
credit -= 1; // one frame in flight until the consumer acks it
}
@@ -1154,7 +976,6 @@ fn drm_capture_worker(
crtc_rx: std::sync::mpsc::Receiver<(String, u32, bool)>,
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
frames_gated: std::sync::Arc<std::sync::atomic::AtomicBool>,
wake: bool,
) {
use std::sync::atomic::Ordering;
use std::time::Duration;
@@ -1165,15 +986,7 @@ fn drm_capture_worker(
let t_conn = std::time::Instant::now();
// Enumerate FRESH rather than serve the cache: a cached display may no longer be driven.
let displays = if wake {
drm_enumerate_settled("a consumer connected")
} else {
let (displays, _undriven) = drm_enumerate_all_displays();
// Seen lit, a connector a failed wake gave up on is wakeable again.
#[cfg(feature = "drm-wake")]
drm_wakeable_undriven(&displays, &_undriven);
displays
};
let displays = drm_enumerate_settled("a consumer connected");
if frame_tx
.blocking_send(DrmProducerMsg::Displays(displays))
.is_err()
@@ -1217,13 +1030,12 @@ fn drm_capture_worker(
let mut stalled: u32 = 0;
let mut logged_first = false;
while !stop.load(Ordering::Relaxed) {
let mut grabbed: Option<std::io::Result<DrmProducerMsg>> = if frames_gated.load(Ordering::Relaxed)
let 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 {
@@ -1239,38 +1051,21 @@ 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 {
// 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,
}))
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),
})
};
// 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)) => {
@@ -1313,7 +1108,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) = cursor {
if let Some(c) = reader.cursor() {
if c.id != last_cursor_id {
last_cursor_id = c.id;
if frame_tx
@@ -1705,7 +1500,6 @@ mod drm_conn_tests {
active: true,
render_node: "/dev/dri/renderD129".to_owned(),
device: "/dev/dri/card2".to_owned(),
plane_transposed: false,
};
let wire = serde_json::to_vec(&current).unwrap();
let back: DrmDisplayInfo = serde_json::from_slice(&wire).unwrap();
@@ -1744,15 +1538,7 @@ 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,
plane_rotation: None,
cursor_pos: None,
},
None,
)
tx.send_msg(&Data::DrmFrame { width: 1920, height: 1080 }, None)
.await
.unwrap();
let (data, fd) = rx.recv_msg().await.unwrap();
@@ -1760,9 +1546,7 @@ mod drm_conn_tests {
data,
Data::DrmFrame {
width: 1920,
height: 1080,
plane_rotation: None,
cursor_pos: None
height: 1080
}
));
assert!(fd.is_none(), "no fd was sent, none must be reported");
@@ -1774,15 +1558,7 @@ 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,
plane_rotation: None,
cursor_pos: None,
},
Some(rd.as_fd()),
)
tx.send_msg(&Data::DrmFrame { width: 4, height: 4 }, Some(rd.as_fd()))
.await
.unwrap();
let (_data, fd) = rx.recv_msg().await.unwrap();
@@ -1896,8 +1672,6 @@ 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();
@@ -1909,9 +1683,7 @@ mod drm_conn_tests {
data,
Data::DrmFrame {
width: 8,
height: 8,
plane_rotation: None,
cursor_pos: None
height: 8
}
));
let kept = fd.expect("the first surplus fd must be kept");
+4 -4
View File
@@ -33,7 +33,7 @@ mod lv;
mod nb;
mod nl;
mod pl;
mod pt_BR;
mod ptbr;
mod pt_PT;
mod ro;
mod ru;
@@ -202,9 +202,9 @@ pub fn translate_locale(name: String, locale: &str) -> String {
"ru" => ru::T.deref(),
"eo" => eo::T.deref(),
"id" => id::T.deref(),
"br" => pt_BR::T.deref(),
"pt" => pt_BR::T.deref(),
"pt-br" => pt_BR::T.deref(),
"br" => ptbr::T.deref(),
"pt" => ptbr::T.deref(),
"pt-br" => ptbr::T.deref(),
"pt-pt" => pt_PT::T.deref(),
"tr" => tr::T.deref(),
"cs" => cs::T.deref(),
+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 تحميل مكوّن GStreamer اللازم لالتقاط الشاشة ({})"),
("Relay fallback delay in seconds", "مهلة التراجع إلى الترحيل بالثواني"),
("relay-fallback-delay-tip", "المدة التي ينتظرها اتصال الترحيل القائم بالفعل الاتصالَ المباشر عبر WebRTC قبل أن يُستخدم بدلًا منه. زِدها لمنح الاتصال المباشر البطيء فرصة أكبر للفوز؛ وقلّلها للاستقرار على الترحيل أسرع في الشبكات التي يتعذر فيها الاتصال المباشر. اتركها فارغة للقيمة الافتراضية 2.5 ثانية."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", ""),
("Relay fallback delay in seconds", "Ötürücüyə keçid gecikməsi, saniyə"),
("relay-fallback-delay-tip", "Artıq qurulmuş ötürücü bağlantı birbaşa WebRTC bağlantısını nə qədər gözləyir, sonra onun əvəzinə istifadə olunur. Yavaş birbaşa bağlantıya daha çox vaxt vermək üçün artırın; birbaşa bağlantının mümkün olmadığı şəbəkələrdə ötürücüyə daha tez keçmək üçün azaldın. Standart 2.5 saniyə üçün boş buraxın."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 не змог загрузіць кампанент GStreamer, патрэбны для захопу экрана ({})"),
("Relay fallback delay in seconds", "Затрымка пераходу на рэтранслятар у секундах"),
("relay-fallback-delay-tip", "Колькі часу ўжо ўсталяванае злучэнне праз рэтранслятар чакае прамога злучэння WebRTC, перш чым будзе выкарыстана замест яго. Павялічце, каб даць павольнаму прамому злучэнню больш часу; паменшыце, каб хутчэй пераходзіць на рэтранслятар у сетках, дзе прамое злучэнне немагчымае. Пакіньце пустым для значэння па змаўчанні 2.5 секунды."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 не можа да зареди компонент на GStreamer, необходим за заснемане на екрана ({})"),
("Relay fallback delay in seconds", "Забавяне преди преминаване към препредаване в секунди"),
("relay-fallback-delay-tip", "Колко време вече установената връзка чрез препредаване изчаква директната WebRTC връзка, преди да бъде използвана вместо нея. Увеличете, за да дадете повече време на бавна директна връзка; намалете, за да се премине по-бързо към препредаване в мрежи, където директна връзка е невъзможна. Оставете празно за стойността по подразбиране 2.5 секунди."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", "El RustDesk no ha pogut carregar un component del GStreamer necessari per capturar la pantalla ({})"),
("Relay fallback delay in seconds", "Retard abans de recórrer al relé en segons"),
("relay-fallback-delay-tip", "Quant de temps espera una connexió de relé ja establerta la connexió directa WebRTC abans d'utilitzar-se en lloc seu. Augmenteu-lo per donar més temps a una connexió directa lenta; reduïu-lo per passar abans al relé en xarxes on no es pot fer una connexió directa. Deixeu-lo buit per al valor predeterminat de 2.5 segons."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 无法加载屏幕捕获所需的 GStreamer 组件 ({})"),
("Relay fallback delay in seconds", "回落到中继前的等待时间(秒)"),
("relay-fallback-delay-tip", "已经建立的中继连接会等待直连的 WebRTC 多久,超过这个时间就改用中继。调大可以让较慢的直连有更多机会胜出;调小则在无法直连的网络上更快回落到中继。留空表示使用默认值 2.5 秒。"),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "开始语音通话前请在\"共享屏幕\"页面启用\"音频录制\"。")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "开始语音通话前请在\"仅共享屏幕\"页面启用\"音频录制\"。")
].iter().cloned().collect();
}
+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 nemohl načíst komponentu GStreameru potřebnou k zachycení obrazovky ({})"),
("Relay fallback delay in seconds", "Prodleva před přepnutím na přenos v sekundách"),
("relay-fallback-delay-tip", "Jak dlouho již navázané spojení přes přenos čeká na přímé spojení WebRTC, než bude použito místo něj. Zvyšte, aby pomalé přímé spojení mělo více času uspět; snižte, aby se v sítích, kde přímé spojení není možné, dříve přešlo na přenos. Ponechte prázdné pro výchozí hodnotu 2.5 sekundy."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 kunne ikke indlæse en GStreamer-komponent, der kræves til skærmoptagelse ({})"),
("Relay fallback delay in seconds", "Forsinkelse før brug af relæ i sekunder"),
("relay-fallback-delay-tip", "Hvor længe en allerede oprettet relæforbindelse venter på den direkte WebRTC-forbindelse, før den bruges i stedet. Forøg for at give en langsom direkte forbindelse mere tid; sænk for hurtigere at falde tilbage til relæet på netværk, hvor en direkte forbindelse ikke kan oprettes. Lad feltet stå tomt for standardværdien 2.5 sekunder."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 konnte eine für die Bildschirmaufnahme benötigte GStreamer-Komponente nicht laden ({})"),
("Relay fallback delay in seconds", "Verzögerung bis zum Relais in Sekunden"),
("relay-fallback-delay-tip", "Wie lange eine bereits aufgebaute Relaisverbindung auf die direkte WebRTC-Verbindung wartet, bevor sie stattdessen verwendet wird. Erhöhen Sie den Wert, um einer langsamen direkten Verbindung mehr Zeit zu geben; verringern Sie ihn, um in Netzwerken ohne mögliche Direktverbindung schneller auf das Relais zurückzufallen. Leer lassen für den Standardwert von 2.5 Sekunden."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 δεν μπόρεσε να φορτώσει ένα στοιχείο του GStreamer που απαιτείται για την καταγραφή οθόνης ({})"),
("Relay fallback delay in seconds", "Καθυστέρηση πριν από τη χρήση αναμεταδότη σε δευτερόλεπτα"),
("relay-fallback-delay-tip", "Πόσο χρόνο περιμένει μια ήδη ενεργή σύνδεση αναμεταδότη την απευθείας σύνδεση WebRTC πριν χρησιμοποιηθεί στη θέση της. Αυξήστε το για να δώσετε σε μια αργή απευθείας σύνδεση περισσότερο χρόνο. Μειώστε το για ταχύτερη επιστροφή στον αναμεταδότη σε δίκτυα όπου δεν είναι δυνατή η απευθείας σύνδεση. Αφήστε το κενό για την προεπιλογή των 2.5 δευτερολέπτων."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ne povis ŝargi komponanton de GStreamer necesan por ekrankapto ({})"),
("Relay fallback delay in seconds", "Prokrasto antaŭ retransmisio en sekundoj"),
("relay-fallback-delay-tip", "Kiom longe jam establita retransmisia konekto atendas la rektan WebRTC-konekton antaŭ ol esti uzata anstataŭe. Pligrandigu ĝin por doni al malrapida rekta konekto pli da tempo; malpligrandigu ĝin por pli frue uzi la retransmision en retoj kie rekta konekto ne eblas. Lasu malplena por la defaŭlta valoro de 2.5 sekundoj."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 \"Share screen\" page.", "Para comenzar una llamada de voz activar \"Captura de audio\" en la página \"Compartir pantalla\".")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ei suutnud laadida ekraani jäädvustamiseks vajalikku GStreameri komponenti ({})"),
("Relay fallback delay in seconds", "Viivitus enne relee kasutamist sekundites"),
("relay-fallback-delay-tip", "Kui kaua juba loodud releeühendus ootab otsest WebRTC-ühendust, enne kui seda selle asemel kasutatakse. Suurendage, et anda aeglasele otseühendusele rohkem aega; vähendage, et võrkudes, kus otseühendust luua ei saa, releele kiiremini üle minna. Jätke tühjaks vaikeväärtuse 2.5 sekundit kasutamiseks."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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-ek ezin izan du pantaila kapturatzeko beharrezkoa den GStreamer osagai bat kargatu ({})"),
("Relay fallback delay in seconds", "Errelera itzultzeko atzerapena segundotan"),
("relay-fallback-delay-tip", "Dagoeneko ezarritako errele-konexio batek WebRTC konexio zuzenari zenbat denbora itxaroten dion, haren ordez erabili aurretik. Handitu konexio zuzen motel bati denbora gehiago emateko; txikitu konexio zuzena egin ezin den sareetan lehenago errelera itzultzeko. Utzi hutsik 2.5 segundoko balio lehenetsirako."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 نتوانست مؤلفه GStreamer موردنیاز برای ضبط صفحه را بارگذاری کند ({})"),
("Relay fallback delay in seconds", "تأخیر بازگشت به رله بر حسب ثانیه"),
("relay-fallback-delay-tip", "یک اتصال رله که از قبل برقرار شده چقدر منتظر اتصال مستقیم WebRTC می ماند پیش از آنکه به جای آن استفاده شود. آن را افزایش دهید تا به اتصال مستقیم کند فرصت بیشتری داده شود؛ کاهش دهید تا در شبکه هایی که اتصال مستقیم ممکن نیست، زودتر به رله بازگردد. برای مقدار پیش فرض 2.5 ثانیه خالی بگذارید."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ei voinut ladata näytön kaappaukseen tarvittavaa GStreamer-osaa ({})"),
("Relay fallback delay in seconds", "Viive ennen välitykseen siirtymistä sekunteina"),
("relay-fallback-delay-tip", "Kuinka kauan jo muodostettu välitysyhteys odottaa suoraa WebRTC-yhteyttä ennen kuin sitä käytetään sen sijaan. Kasvata arvoa antaaksesi hitaalle suoralle yhteydelle enemmän aikaa; pienennä sitä siirtyäksesi nopeammin välitykseen verkoissa, joissa suoraa yhteyttä ei voi muodostaa. Jätä tyhjäksi käyttääksesi oletusarvoa 2.5 sekuntia."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 n'a pas pu charger un composant GStreamer nécessaire à la capture d'écran ({})"),
("Relay fallback delay in seconds", "Délai avant bascule vers le relais en secondes"),
("relay-fallback-delay-tip", "Durée pendant laquelle une connexion relais déjà établie attend la connexion directe WebRTC avant d'être utilisée à sa place. Augmentez-la pour laisser plus de temps à une connexion directe lente ; diminuez-la pour basculer plus tôt vers le relais sur les réseaux où une connexion directe est impossible. Laissez vide pour la valeur par défaut de 2.5 secondes."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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-მა ვერ ჩატვირთა ეკრანის ჩაწერისთვის საჭირო GStreamer-ის კომპონენტი ({})"),
("Relay fallback delay in seconds", "რელეზე გადასვლის დაყოვნება წამებში"),
("relay-fallback-delay-tip", "რამდენ ხანს ელოდება უკვე დამყარებული რელე-კავშირი პირდაპირ WebRTC კავშირს, სანამ მის ნაცვლად გამოიყენება. გაზარდეთ, რომ ნელ პირდაპირ კავშირს მეტი დრო მისცეთ; შეამცირეთ, რომ ქსელებში, სადაც პირდაპირი კავშირი შეუძლებელია, უფრო სწრაფად გადავიდეს რელეზე. დატოვეთ ცარიელი ნაგულისხმევი 2.5 წამისთვის."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 non puido cargar un compoñente de GStreamer necesario para capturar a pantalla ({})"),
("Relay fallback delay in seconds", "Atraso antes de usar o relé en segundos"),
("relay-fallback-delay-tip", "Canto tempo agarda unha conexión de relé xa establecida pola conexión directa WebRTC antes de usarse no seu lugar. Auménteo para darlle máis tempo a unha conexión directa lenta; redúzao para recorrer antes ao relé en redes onde non é posible unha conexión directa. Déixeo baleiro para o valor predeterminado de 2.5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 સ્ક્રીન કૅપ્ચર માટે જરૂરી GStreamer ઘટક લોડ કરી શક્યું નથી ({})"),
("Relay fallback delay in seconds", "રિલે પર પાછા ફરવામાં વિલંબ સેકન્ડમાં"),
("relay-fallback-delay-tip", "પહેલેથી સ્થાપિત રિલે કનેક્શન સીધા WebRTC કનેક્શનની કેટલો સમય રાહ જુએ છે, ત્યાર બાદ તેના બદલે વપરાય છે. ધીમા સીધા કનેક્શનને વધુ સમય આપવા માટે વધારો; જ્યાં સીધું કનેક્શન શક્ય નથી તેવા નેટવર્ક પર વહેલા રિલે પર જવા માટે ઘટાડો. મૂળભૂત 2.5 સેકન્ડ માટે ખાલી રાખો."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 לא הצליח לטעון רכיב GStreamer הדרוש ללכידת מסך ({})"),
("Relay fallback delay in seconds", "השהיה לפני מעבר לממסר בשניות"),
("relay-fallback-delay-tip", "כמה זמן חיבור ממסר שכבר נוצר ממתין לחיבור WebRTC הישיר לפני שישמש במקומו. הגדל כדי לתת לחיבור ישיר איטי יותר זמן; הקטן כדי לעבור מהר יותר לממסר ברשתות שבהן לא ניתן ליצור חיבור ישיר. השאר ריק לערך ברירת המחדל של 2.5 שניות."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 स्क्रीन कैप्चर के लिए आवश्यक GStreamer घटक लोड नहीं कर सका ({})"),
("Relay fallback delay in seconds", "रिले पर लौटने में विलंब सेकंड में"),
("relay-fallback-delay-tip", "पहले से स्थापित रिले कनेक्शन सीधे WebRTC कनेक्शन की कितनी देर प्रतीक्षा करता है, उसके बाद उसके स्थान पर उपयोग किया जाता है। धीमे सीधे कनेक्शन को अधिक समय देने के लिए बढ़ाएँ; जिन नेटवर्क पर सीधा कनेक्शन संभव नहीं है वहाँ जल्दी रिले पर जाने के लिए घटाएँ। डिफ़ॉल्ट 2.5 सेकंड के लिए खाली छोड़ें।"),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 nije mogao učitati GStreamer komponentu potrebnu za snimanje zaslona ({})"),
("Relay fallback delay in seconds", "Odgoda prije prelaska na relej u sekundama"),
("relay-fallback-delay-tip", "Koliko dugo već uspostavljena relejna veza čeka izravnu WebRTC vezu prije nego što se upotrijebi umjesto nje. Povećajte da sporoj izravnoj vezi date više vremena; smanjite da se na mrežama gdje izravna veza nije moguća brže prijeđe na relej. Ostavite prazno za zadanu vrijednost od 2.5 sekunde."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", "A RustDesk nem tudta betölteni a képernyőrögzítéshez szükséges GStreamer összetevőt ({})"),
("Relay fallback delay in seconds", "Késleltetés a továbbítóra váltás előtt másodpercben"),
("relay-fallback-delay-tip", "Mennyi ideig vár a már létrejött továbbító kapcsolat a közvetlen WebRTC kapcsolatra, mielőtt helyette használnák. Növelje, hogy a lassú közvetlen kapcsolatnak több ideje legyen; csökkentse, hogy olyan hálózatokon, ahol közvetlen kapcsolat nem hozható létre, hamarabb váltson továbbítóra. Hagyja üresen az alapértelmezett 2.5 másodperchez."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 tidak dapat memuat komponen GStreamer yang diperlukan untuk merekam layar ({})"),
("Relay fallback delay in seconds", "Jeda sebelum beralih ke relai dalam detik"),
("relay-fallback-delay-tip", "Berapa lama koneksi relai yang sudah terbentuk menunggu koneksi langsung WebRTC sebelum digunakan sebagai gantinya. Perbesar untuk memberi koneksi langsung yang lambat lebih banyak waktu; perkecil agar lebih cepat beralih ke relai pada jaringan yang tidak memungkinkan koneksi langsung. Biarkan kosong untuk nilai bawaan 2.5 detik."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 non è riuscito a caricare un componente GStreamer necessario per l'acquisizione dello schermo ({})"),
("Relay fallback delay in seconds", "Ritardo fallback relay (secondi)"),
("relay-fallback-delay-tip", "Quanto tempo una connessione relay già attiva attende la connessione WebRTC diretta prima di essere usata. Aumentalo per dare a una connessione diretta lenta più tempo per funzionare; diminuiscilo per passare prima al relay sulle reti in cui non è possibile effettuare una connessione diretta. Lascia vuoto per il valore predefinito di 2,5 secondi."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Per avviare una chiamata vocale, attiva nella pagina 'Condividi schermo' la voce 'Cattura audio'.")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Per avviare una chiamata vocale, attiva nella pagina 'Condivisione schermo' la voce 'Cattura audio'.")
].iter().cloned().collect();
}
+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 は画面キャプチャに必要な GStreamer コンポーネントを読み込めませんでした ({})"),
("Relay fallback delay in seconds", "中継に切り替えるまでの待ち時間 (秒)"),
("relay-fallback-delay-tip", "すでに確立された中継接続が、直接の WebRTC 接続をどれだけ待ってから代わりに使用されるかを指定します。値を大きくすると遅い直接接続に時間を与えられ、小さくすると直接接続できないネットワークで早く中継に切り替わります。空欄にすると既定値の 2.5 秒になります。"),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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가 화면 캡처에 필요한 GStreamer 구성 요소를 불러오지 못했습니다 ({})"),
("Relay fallback delay in seconds", "릴레이 대체 작동 지연 시간 (초)"),
("relay-fallback-delay-tip", "이미 연결된 중계 연결이 직접 WebRTC 연결을 얼마나 기다린 후 대신 사용되는지입니다. 값을 늘리면 느린 직접 연결에 더 많은 시간을 주고, 줄이면 직접 연결이 불가능한 네트워크에서 더 빨리 중계로 전환합니다. 비워 두면 기본값 2.5초가 사용됩니다."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "음성 통화를 시작하려면 '화면 공유' 페이지에서 '오디오 캡처'를 사용함으로 하세요.")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "음성 통화를 시작하려면 '화면 공유' 페이지에서 '오디오 캡처'를 사용함으로 하세요.")
].iter().cloned().collect();
}
+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 экранды түсіру үшін қажет GStreamer компонентін жүктей алмады ({})"),
("Relay fallback delay in seconds", "Релеге ауысу кідірісі, секундпен"),
("relay-fallback-delay-tip", "Бұрыннан орнатылған реле байланысы тікелей WebRTC байланысын қанша уақыт күтеді, содан кейін оның орнына қолданылады. Баяу тікелей байланысқа көбірек уақыт беру үшін үлкейтіңіз; тікелей байланыс мүмкін емес желілерде релеге тезірек ауысу үшін кішірейтіңіз. Әдепкі 2.5 секунд үшін бос қалдырыңыз."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 nepavyko įkelti ekrano įrašymui reikalingo GStreamer komponento ({})"),
("Relay fallback delay in seconds", "Delsa prieš pereinant prie perdavimo sekundėmis"),
("relay-fallback-delay-tip", "Kiek laiko jau užmegztas perdavimo ryšys laukia tiesioginio WebRTC ryšio, kol bus panaudotas vietoj jo. Padidinkite, kad lėtam tiesioginiam ryšiui būtų skirta daugiau laiko; sumažinkite, kad tinkluose, kuriuose tiesioginis ryšys neįmanomas, greičiau būtų pereinama prie perdavimo. Palikite tuščią numatytajai 2.5 sekundės reikšmei."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 nevarēja ielādēt ekrāna tveršanai nepieciešamo GStreamer komponentu ({})"),
("Relay fallback delay in seconds", "Aizkave pirms pārslēgšanās uz retranslatoru sekundēs"),
("relay-fallback-delay-tip", "Cik ilgi jau izveidots retranslatora savienojums gaida tiešo WebRTC savienojumu, pirms tiek izmantots tā vietā. Palieliniet, lai lēnam tiešajam savienojumam dotu vairāk laika; samaziniet, lai tīklos, kur tiešais savienojums nav iespējams, ātrāk pārslēgtos uz retranslatoru. Atstājiet tukšu noklusējuma 2.5 sekunžu vērtībai."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", "സ്ക്രീൻ പകർത്താൻ ആവശ്യമായ GStreamer ഘടകം RustDesk-ന് ലോഡ് ചെയ്യാനായില്ല ({})"),
("Relay fallback delay in seconds", "റിലേയിലേക്ക് മാറുന്നതിനുള്ള കാലതാമസം സെക്കൻഡിൽ"),
("relay-fallback-delay-tip", "ഇതിനകം സ്ഥാപിതമായ റിലേ കണക്ഷൻ നേരിട്ടുള്ള WebRTC കണക്ഷനായി എത്ര നേരം കാത്തിരിക്കുന്നു, അതിനുശേഷം അതിനുപകരം ഉപയോഗിക്കുന്നു. മന്ദഗതിയിലുള്ള നേരിട്ടുള്ള കണക്ഷന് കൂടുതൽ സമയം നൽകാൻ വർദ്ധിപ്പിക്കുക; നേരിട്ടുള്ള കണക്ഷൻ സാധ്യമല്ലാത്ത നെറ്റ്‌വർക്കുകളിൽ വേഗത്തിൽ റിലേയിലേക്ക് മാറാൻ കുറയ്ക്കുക. സ്ഥിരസ്ഥിതിയായ 2.5 സെക്കൻഡിനായി ശൂന്യമാക്കിയിടുക."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 kunne ikke laste en GStreamer-komponent som kreves for skjermopptak ({})"),
("Relay fallback delay in seconds", "Forsinkelse før bruk av relé i sekunder"),
("relay-fallback-delay-tip", "Hvor lenge en allerede opprettet reléforbindelse venter på den direkte WebRTC-forbindelsen før den brukes i stedet. Øk verdien for å gi en treg direkteforbindelse mer tid; senk den for å gå raskere over til reléet på nettverk der direkte forbindelse ikke er mulig. La stå tom for standardverdien på 2.5 sekunder."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+25 -25
View File
@@ -7,11 +7,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Password", "Wachtwoord"),
("Ready", "Gereed"),
("Established", "Opgezet"),
("connecting_status", "Verbinding maken met het RustDesk-netwerk…"),
("connecting_status", "Verbinding maken met het RustDesk-netwerk..."),
("Enable service", "Service inschakelen"),
("Start service", "Service starten"),
("Service is running", "Service loopt."),
("Service is not running", "Service loopt niet"),
("Service is running", "De service loopt."),
("Service is not running", "De service loopt niet"),
("not_ready_status", "Niet verbonden met de server, controleer de netwerkverbinding"),
("Control Remote Desktop", "Extern Bureaublad beheren"),
("Transfer file", "Bestand overzetten"),
@@ -76,12 +76,12 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Connection Error", "Fout bij verbinding"),
("Error", "Fout"),
("Reset by the peer", "Door de peer gereset"),
("Connecting...", "Verbinding maken…"),
("Connecting...", "Verbinding maken..."),
("Connection in progress. Please wait.", "Verbinding wordt gemaakt. Even geduld."),
("Please try 1 minute later", "Probeer opnieuw over 1 minuut"),
("Login Error", "Loginfout"),
("Successful", "Geslaagd"),
("Connected, waiting for image...", "Verbonden, wachten op beeld…"),
("Connected, waiting for image...", "Verbonden, wachten op beeld..."),
("Name", "Naam"),
("Type", "Type"),
("Modified", "Gewijzigd"),
@@ -94,7 +94,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Remote", "Op afstand"),
("Remote Computer", "Externe computer"),
("Local Computer", "Lokale computer"),
("Confirm Delete", "Verwijdering bevestigen"),
("Confirm Delete", "Verwijderen bevestigen"),
("Delete", "Verwijderen"),
("Properties", "Eigenschappen"),
("Multi Select", "Meervoudige selectie"),
@@ -127,7 +127,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Optimize reaction time", "Responstijd optimaliseren"),
("Custom", "Aangepast"),
("Show remote cursor", "Cursor van extern bureaublad weergeven"),
("Show quality monitor", "Kwaliteitsmonitor weergeven"),
("Show quality monitor", "Kwaliteitsmonitor tonen"),
("Disable clipboard", "Klembord uitschakelen"),
("Lock after session end", "Vergrendelen na einde sessie"),
("Insert Ctrl + Alt + Del", "Ctrl + Alt + Del invoeren"),
@@ -150,7 +150,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Configure", "Configureren"),
("config_acc", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Toegankelijkheid."),
("config_screen", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Schermopname."),
("Installing ...", "Installeren…"),
("Installing ...", "Installeren ..."),
("Install", "Installeren"),
("Installation", "Installatie"),
("Installation Path", "Locatie"),
@@ -159,10 +159,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("agreement_tip", "Het starten van de installatie betekent het accepteren van de licentieovereenkomst."),
("Accept and Install", "Accepteren en installeren"),
("End-user license agreement", "Eindgebruikerslicentieovereenkomst"),
("Generating ...", "Genereren…"),
("Generating ...", "Genereren ..."),
("Your installation is lower version.", "Uw installatie is een lagere versie."),
("not_close_tcp_tip", "Sluit dit venster niet zolang u de tunnel gebruikt"),
("Listening ...", "Luisteren…"),
("Listening ...", "Luisteren ..."),
("Remote Host", "Externe host"),
("Remote Port", "Externe poort"),
("Action", "Actie"),
@@ -185,7 +185,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relayed and unencrypted connection", "Doorgeschakelde en niet-versleutelde verbinding"),
("Enter Remote ID", "Extern ID invoeren"),
("Enter your password", "Wachtwoord invoeren"),
("Logging in...", "Aanmelden…"),
("Logging in...", "Aanmelden..."),
("Enable RDP session sharing", "Delen van RDP-sessie inschakelen"),
("Auto Login", "Automatisch aanmelden"),
("Enable direct IP access", "Directe IP-toegang inschakelen"),
@@ -368,11 +368,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Deny LAN discovery", "LAN-detectie weigeren"),
("Write a message", "Schrijf een bericht"),
("Prompt", "Melding"),
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging…"),
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging..."),
("elevated_foreground_window_tip", "Het momenteel geopende venster van de op afstand bediende computer vereist hogere rechten. Daarom is het momenteel niet mogelijk de muis en het toetsenbord te gebruiken. Vraag de gebruiker wiens computer u op afstand bedient om het venster te minimaliseren of de rechten te verhogen. Om dit probleem in de toekomst te voorkomen, wordt aanbevolen de software te installeren op de op afstand bediende computer."),
("Disconnected", "Afgesloten"),
("Other", "Andere"),
("Confirm before closing multiple tabs", "Bevestiging geven bij sluiten van meerdere tabbladen"),
("Confirm before closing multiple tabs", "Bevestig voordat u meerdere tabbladen sluit"),
("Keyboard Settings", "Toetsenbordinstellingen"),
("Full Access", "Volledige toegang"),
("Screen Share", "Scherm delen"),
@@ -381,7 +381,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("xdp-portal-unavailable", "Wayland schermopname is mislukt. De XDG Desktop Portal kan gecrashed zijn of is onbeschikbaar. Probeer het opnieuw te starten met `systemctl --user restart xdg-desktop-portal`."),
("JumpLink", "JumpLink"),
("Please Select the screen to be shared(Operate on the peer side).", "Selecteer het scherm dat moet worden gedeeld (Bediening aan de kant van de peer)."),
("Show RustDesk", "RustDesk weergeven"),
("Show RustDesk", "Toon RustDesk"),
("This PC", "Deze PC"),
("or", "of"),
("Elevate", "Verhogen"),
@@ -389,7 +389,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Accept sessions via password", "Sessies accepteren via wachtwoord"),
("Accept sessions via click", "Sessies accepteren via klik"),
("Accept sessions via both", "Accepteer sessies via klik of wachtwoord"),
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert…"),
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert..."),
("One-time Password", "Eenmalig wachtwoord"),
("Use one-time password", "Eenmalig wachtwoord gebruiken"),
("One-time password length", "Lengte eenmalig wachtwoord"),
@@ -428,7 +428,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Medium", "Middelmatig"),
("Strong", "Sterk"),
("Switch Sides", "Van kant wisselen"),
("Please confirm if you want to share your desktop?", "Weet u zeker dat u uw bureaublad wilt delen?"),
("Please confirm if you want to share your desktop?", "Bevestig dat u uw bureaublad wilt delen?"),
("Display", "Weergave"),
("Default View Style", "Standaard Weergavestijl"),
("Default Scroll Style", "Standaard Scrollstijl"),
@@ -649,13 +649,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("use-the-default-printer-tip", "Standaard printer gebruiken"),
("use-the-selected-printer-tip", "Geselecteerde printer gebruiken"),
("auto-print-tip", "Automatisch afdrukken op de geselecteerde printer."),
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet deze lokaal worden afgedrukt?"),
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is niet toegestaan"),
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet ik deze lokaal afdrukken?"),
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is verboden"),
("remote-printing-disallowed-text-tip", "Machtigingsinstellingen aan beheerde zijde verhinderen afdrukken op afstand."),
("save-settings-tip", "Instellingen opslaan"),
("dont-show-again-tip", "Dit bericht wordt niet meer weergegeven"),
("Take screenshot", "Schermopname maken"),
("Taking screenshot", "Schermopname maken…"),
("Taking screenshot", "Schermopname maken..."),
("screenshot-merged-screen-not-supported-tip", "Schermopnames van meerdere schermen samenvoegen wordt momenteel niet ondersteund. Schakel over naar een enkel scherm en herhaal de actie."),
("screenshot-action-tip", "Kies wat je met de gemaakte schermopname wilt doen."),
("Save as", "Opslaan als"),
@@ -693,7 +693,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Failed to check if the user is an administrator.", "Fout bij het controleren of de gebruiker een beheerder is."),
("Supported only in the installed version.", "Alleen ondersteund in de geïnstalleerde versie."),
("elevation_username_tip", "Voer je gebruikersnaam of domeinnaam in"),
("Preparing for installation ...", "Installatie voorbereiden…"),
("Preparing for installation ...", "Installatie voorbereiden ..."),
("Show my cursor", "Mijn cursor weergeven"),
("Scale custom", "Aangepaste schaal"),
("Custom scale slider", "Aangepaste schuifregelaar voor schaal"),
@@ -713,8 +713,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("disable-udp-tip", "Controleert of alleen TCP moet worden gebruikt. Als deze optie is ingeschakeld, gebruikt RustDesk niet langer UDP 21116, maar TCP 21116."),
("server-oss-not-support-tip", "Opmerking: Deze functie is niet beschikbaar in de open-sourceversie van de RustDesk-server."),
("input note here", "voeg hier een opmerking toe"),
("note-at-conn-end-tip", "Om een opmerking vragen aan het einde van de verbinding"),
("Show terminal extra keys", "Extra toetsen voor terminal weergeven"),
("note-at-conn-end-tip", "Vraag om een opmerking aan het einde van de verbinding"),
("Show terminal extra keys", "Toon extra toetsen voor terminal"),
("Relative mouse mode", "Relatieve muismodus"),
("rel-mouse-not-supported-peer-tip", "De relatieve muismodus wordt niet ondersteund door het externe apparaat."),
("rel-mouse-not-ready-tip", "De relatieve muismodus was nog niet klaar, probeer het later opnieuw."),
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Canvas vergrendelen"),
("Sync clipboard between sessions", "Klembord synchroniseren tussen sessies"),
("sync-clipboard-between-sessions-tip", "Tekst of afbeeldingen die in één externe sessie worden gekopieerd, worden ook naar het klembord van uw andere verbonden sessies gestuurd."),
("terminal-clipboard-write-tip", "Een app in de terminal wil tekst naar het klembord van dit apparaat kopiëren. Indien verleend, is deze toestemming van toepassing op terminal-apps in alle verbindingen totdat u deze uitschakelt in Instellingen. Handmatig kopiëren en plakken wordt niet beïnvloed."),
("Allow terminal apps to copy to clipboard", "Terminal-apps toestaan om naar klembord te kopiëren"),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("Enable", "Inschakelen"),
("Reuse one connection for port forwarding", "Eén verbinding hergebruiken voor poortdoorschakeling"),
("port-forward-mux-tip", "Alle verbindingen van een poortdoorschakeling via één enkele verbinding met de andere computer laten lopen, in plaats van voor elke verbinding opnieuw verbinding te maken en in te loggen."),
@@ -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 kon een GStreamer-component die nodig is voor schermopname niet laden ({})"),
("Relay fallback delay in seconds", "Vertraging voordat relay wordt gebruikt in seconden"),
("relay-fallback-delay-tip", "Hoe lang een al tot stand gekomen relayverbinding wacht op de directe WebRTC-verbinding voordat deze in plaats daarvan wordt gebruikt. Verhoog de waarde om een trage directe verbinding meer tijd te geven; verlaag deze om op netwerken waar een directe verbinding niet mogelijk is sneller op de relay terug te vallen. Laat leeg voor de standaardwaarde van 2.5 seconden."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Om een spraakgesprek te starten, schakel je \"Audio-opname\" in op de pagina \"Scherm delen\".")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Om een spraakgesprek te starten, schakel je \"Audio-opname\" in op de pagina \"Scherm delen\".")
].iter().cloned().collect();
}
+3 -3
View File
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Zablokuj ekran"),
("Sync clipboard between sessions", "Synchronizuj schowek między sesjami"),
("sync-clipboard-between-sessions-tip", "Tekst lub obrazy skopiowane w jednej sesji zdalnej są wysyłane także do schowka pozostałych połączonych sesji."),
("terminal-clipboard-write-tip", "Aplikacja w terminalu chce skopiować tekst do schowka tego urządzenia. Jeśli wyrazisz na to zgodę, uprawnienie to będzie dotyczyć aplikacji terminalowych we wszystkich połączeniach, dopóki nie wyłączysz go w Ustawieniach. Ręczne kopiowanie i wklejanie pozostanie bez zmian."),
("Allow terminal apps to copy to clipboard", "Zezwól aplikacjom terminalowym na kopiowanie do schowka"),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("Enable", "Włącz"),
("Reuse one connection for port forwarding", "Użyj ponownie jednego połączenia do przekierowania portów"),
("port-forward-mux-tip", "Przekazuj wszystkie połączenia jednego przekierowania portów przez jedno połączenie ze zdalnym komputerem, zamiast łączyć się i logować od nowa dla każdego z nich."),
@@ -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 nie mógł załadować składnika GStreamer wymaganego do przechwytywania ekranu ({})"),
("Relay fallback delay in seconds", "Opóźnienie przed przejściem na przekaźnik w sekundach"),
("relay-fallback-delay-tip", "Jak długo nawiązane już połączenie przez przekaźnik czeka na bezpośrednie połączenie WebRTC, zanim zostanie użyte zamiast niego. Zwiększ, aby dać wolnemu połączeniu bezpośredniemu więcej czasu; zmniejsz, aby w sieciach, w których połączenie bezpośrednie jest niemożliwe, szybciej przechodzić na przekaźnik. Pozostaw puste, aby użyć wartości domyślnej 2.5 sekundy."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Aby rozpocząć połączenie głosowe, włącz opcję \"Przechwytywanie dźwięku\" na stronie \"Udostępnianie ekranu\".")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", "O RustDesk não conseguiu carregar um componente do GStreamer necessário para capturar o ecrã ({})"),
("Relay fallback delay in seconds", "Atraso antes de recorrer ao retransmissor em segundos"),
("relay-fallback-delay-tip", "Quanto tempo uma ligação de retransmissão já estabelecida aguarda pela ligação direta WebRTC antes de ser usada em vez dela. Aumente para dar mais tempo a uma ligação direta lenta; diminua para recorrer mais cedo ao retransmissor em redes onde não é possível uma ligação direta. Deixe vazio para o valor predefinido de 2.5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de Áudio\" na página \"Partilhar ecrã\".")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", "O RustDesk não conseguiu carregar um componente do GStreamer necessário para a captura de tela ({})."),
("Relay fallback delay in seconds", "Atraso antes de recorrer ao retransmissor em segundos"),
("relay-fallback-delay-tip", "Tempo que a conexão de retransmissão aguarda pela conexão direta WebRTC. Aumente para dar mais tempo a conexões lentas; diminua para usar o retransmissor mais cedo. Deixe vazio para usar o padrão de 2,5 segundos."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Para iniciar uma chamada de voz, ative \"Captura de áudio\" na página \"Compartilhar Tela\".")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Para iniciar uma chamada de voz, ative \"Captura de áudio\" na página \"Compartilhamento de tela\".")
].iter().cloned().collect();
}
+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 nu a putut încărca o componentă GStreamer necesară pentru capturarea ecranului ({})"),
("Relay fallback delay in seconds", "Întârziere înainte de trecerea la releu în secunde"),
("relay-fallback-delay-tip", "Cât timp așteaptă o conexiune prin releu deja stabilită conexiunea directă WebRTC înainte de a fi folosită în locul ei. Măriți valoarea pentru a acorda mai mult timp unei conexiuni directe lente; micșorați-o pentru a trece mai repede la releu în rețelele în care o conexiune directă nu este posibilă. Lăsați gol pentru valoarea implicită de 2.5 secunde."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 не удалось загрузить компонент GStreamer, необходимый для захвата экрана ({})"),
("Relay fallback delay in seconds", "Задержка перед переходом на ретранслятор в секундах"),
("relay-fallback-delay-tip", "Сколько времени уже установленное соединение через ретранслятор ждёт прямое соединение WebRTC, прежде чем будет использовано вместо него. Увеличьте, чтобы дать медленному прямому соединению больше времени; уменьшите, чтобы быстрее переходить на ретранслятор в сетях, где прямое соединение невозможно. Оставьте пустым для значения по умолчанию 2.5 секунды."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Чтобы начать голосовой вызов, включите \"Захват аудио\" на странице \"Демонстрация экрана\".")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Чтобы начать голосовой вызов, включите \"Захват аудио\" на странице \"Демонстрация экрана\" настроек.")
].iter().cloned().collect();
}
+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 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 \"Share screen\" page.", "Pro aviare una mutida de boghe, ativa in sa pàgina \"Cumpartzi ischermu\" s’elementu \"Catura de s’àudio\".")
("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();
}
+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 nedokázal načítať komponent GStreamera potrebný na zachytenie obrazovky ({})"),
("Relay fallback delay in seconds", "Oneskorenie pred prepnutím na prenos v sekundách"),
("relay-fallback-delay-tip", "Ako dlho už nadviazané spojenie cez prenos čaká na priame spojenie WebRTC, kým sa použije namiesto neho. Zvýšte, aby pomalé priame spojenie malo viac času; znížte, aby sa v sieťach, kde priame spojenie nie je možné, skôr prešlo na prenos. Nechajte prázdne pre predvolenú hodnotu 2.5 sekundy."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ni mogel naložiti komponente GStreamer, potrebne za zajem zaslona ({})"),
("Relay fallback delay in seconds", "Zakasnitev pred preklopom na posrednika v sekundah"),
("relay-fallback-delay-tip", "Kako dolgo že vzpostavljena posredniška povezava čaka na neposredno povezavo WebRTC, preden se uporabi namesto nje. Povečajte, da počasni neposredni povezavi date več časa; zmanjšajte, da v omrežjih, kjer neposredna povezava ni mogoča, hitreje preklopite na posrednika. Pustite prazno za privzeto vrednost 2.5 sekunde."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 nuk mundi të ngarkojë një komponent të GStreamer të nevojshëm për regjistrimin e ekranit ({})"),
("Relay fallback delay in seconds", "Vonesa para kalimit te releja në sekonda"),
("relay-fallback-delay-tip", "Sa gjatë pret një lidhje releje tashmë e vendosur lidhjen e drejtpërdrejtë WebRTC përpara se të përdoret në vend të saj. Rriteni për t'i dhënë më shumë kohë një lidhjeje të drejtpërdrejtë të ngadaltë; uleni për të kaluar më shpejt te releja në rrjete ku lidhja e drejtpërdrejtë nuk është e mundur. Lëreni bosh për vlerën e parazgjedhur prej 2.5 sekondash."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 nije mogao da učita GStreamer komponentu potrebnu za snimanje ekrana ({})"),
("Relay fallback delay in seconds", "Кашњење пре преласка на релеј у секундама"),
("relay-fallback-delay-tip", "Колико дуго већ успостављена релејна веза чека на директну WebRTC везу пре него што се употреби уместо ње. Повећајте да бисте спорој директној вези дали више времена; смањите да бисте на мрежама где директна веза није могућа брже прешли на релеј. Оставите празно за подразумевану вредност од 2.5 секунде."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 kunde inte läsa in en GStreamer-komponent som krävs för skärminspelning ({})"),
("Relay fallback delay in seconds", "Fördröjning innan relä används i sekunder"),
("relay-fallback-delay-tip", "Hur länge en redan upprättad reläanslutning väntar på den direkta WebRTC-anslutningen innan den används i stället. Öka värdet för att ge en långsam direktanslutning mer tid; sänk det för att snabbare falla tillbaka på reläet i nätverk där direktanslutning inte är möjlig. Lämna tomt för standardvärdet 2.5 sekunder."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", "திரைப் பதிவுக்குத் தேவையான GStreamer கூறை RustDesk ஏற்ற முடியவில்லை ({})"),
("Relay fallback delay in seconds", "ரிலேக்கு மாறுவதற்கான தாமதம் வினாடிகளில்"),
("relay-fallback-delay-tip", "ஏற்கனவே நிறுவப்பட்ட ரிலே இணைப்பு நேரடி WebRTC இணைப்புக்காக எவ்வளவு நேரம் காத்திருக்கிறது, அதன் பிறகு அதற்குப் பதிலாகப் பயன்படுத்தப்படுகிறது. மெதுவான நேரடி இணைப்புக்கு அதிக நேரம் வழங்க அதிகரிக்கவும்; நேரடி இணைப்பு சாத்தியமில்லாத பிணையங்களில் விரைவாக ரிலேக்கு மாற குறைக்கவும். இயல்புநிலை 2.5 வினாடிகளுக்கு காலியாக விடவும்."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ({})", ""),
("Relay fallback delay in seconds", ""),
("relay-fallback-delay-tip", ""),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ไม่สามารถโหลดส่วนประกอบ GStreamer ที่จำเป็นสำหรับการบันทึกหน้าจอได้ ({})"),
("Relay fallback delay in seconds", "เวลารอก่อนเปลี่ยนไปใช้รีเลย์ (วินาที)"),
("relay-fallback-delay-tip", "การเชื่อมต่อผ่านรีเลย์ที่สร้างไว้แล้วจะรอการเชื่อมต่อ WebRTC โดยตรงนานเท่าใดก่อนที่จะถูกใช้แทน เพิ่มค่าเพื่อให้การเชื่อมต่อโดยตรงที่ช้ามีเวลามากขึ้น ลดค่าเพื่อเปลี่ยนไปใช้รีเลย์เร็วขึ้นในเครือข่ายที่ไม่สามารถเชื่อมต่อโดยตรงได้ เว้นว่างไว้เพื่อใช้ค่าเริ่มต้น 2.5 วินาที"),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 ekran yakalama için gereken GStreamer bileşenini yükleyemedi ({})"),
("Relay fallback delay in seconds", "Aktarıcıya geçiş gecikmesi (saniye)"),
("relay-fallback-delay-tip", "Zaten kurulmuş bir aktarıcı bağlantısının, onun yerine kullanılmadan önce doğrudan WebRTC bağlantısını ne kadar beklediğidir. Yavaş bir doğrudan bağlantıya daha fazla süre tanımak için artırın; doğrudan bağlantının kurulamadığı ağlarda aktarıcıya daha erken geçmek için azaltın. Varsayılan 2.5 saniye için boş bırakın."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Sesli arama başlatmak için \"Ekranı Paylaş\" sayfasındaki \"Ses yakalama\" seçeneğini açın.")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Sesli arama başlatmak için \"Ekran paylaşımı\" sayfasındaki \"Ses yakalama\" seçeneğini açın.")
].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 \"Share screen\" page.", "若要開始語音通話,請在「螢幕分享」頁面啟用「音訊錄製」。")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 не вдалося завантажити компонент GStreamer, потрібний для захоплення екрана ({})"),
("Relay fallback delay in seconds", "Затримка перед переходом на ретранслятор у секундах"),
("relay-fallback-delay-tip", "Скільки часу вже встановлене з'єднання через ретранслятор чекає на пряме з'єднання WebRTC, перш ніж буде використане замість нього. Збільште, щоб дати повільному прямому з'єднанню більше часу; зменште, щоб швидше переходити на ретранслятор у мережах, де пряме з'єднання неможливе. Залиште порожнім для типового значення 2.5 секунди."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "Щоб розпочати голосовий виклик, увімкніть «Захоплення аудіо» на сторінці «Поділитися екраном»."),
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "Щоб розпочати голосовий виклик, увімкніть «Захоплення аудіо» на сторінці «Демонстрація екрана»."),
].iter().cloned().collect();
}
+1 -1
View File
@@ -780,7 +780,7 @@ 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 \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
+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 không thể tải một thành phần GStreamer cần cho việc ghi màn hình ({})"),
("Relay fallback delay in seconds", "Độ trễ trước khi chuyển sang trung chuyển (giây)"),
("relay-fallback-delay-tip", "Kết nối trung chuyển đã thiết lập sẽ chờ kết nối WebRTC trực tiếp trong bao lâu trước khi được dùng thay thế. Tăng giá trị để cho kết nối trực tiếp chậm thêm thời gian; giảm để chuyển sang trung chuyển sớm hơn trên các mạng không thể kết nối trực tiếp. Để trống để dùng giá trị mặc định 2.5 giây."),
("To start a voice call, enable \"Audio capture\" on the \"Share screen\" page.", "")
("To start a voice call, enable \"Audio capture\" on the \"Screen share\" page.", "")
].iter().cloned().collect();
}
-4
View File
@@ -767,10 +767,6 @@ pub fn is_locked() -> bool {
}
}
pub fn is_logon_screen() -> bool {
is_prelogin() || is_locked()
}
pub fn is_root() -> bool {
crate::username() == "root"
}
-32
View File
@@ -1,32 +0,0 @@
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)
);
}
}
+5 -7
View File
@@ -604,16 +604,14 @@ extern "C"
return rdp_or_console;
}
// WTSInfoExLevel1.SessionFlags, or WTS_SESSIONSTATE_UNKNOWN when it cannot be read.
DWORD get_session_flags(DWORD session_id)
BOOL is_session_locked(DWORD session_id)
{
DWORD flags = WTS_SESSIONSTATE_UNKNOWN;
// WTS_CURRENT_SESSION, which would query the caller's session instead.
if (session_id == 0xFFFFFFFF) {
return flags;
return FALSE;
}
PWTSINFOEXW pInfo = NULL;
DWORD bytes = 0;
BOOL locked = FALSE;
if (WTSQuerySessionInformationW(
WTS_CURRENT_SERVER_HANDLE,
session_id,
@@ -621,13 +619,13 @@ extern "C"
(LPWSTR *)&pInfo,
&bytes)) {
if (pInfo && pInfo->Level == 1) {
flags = (DWORD)pInfo->Data.WTSInfoExLevel1.SessionFlags;
locked = (pInfo->Data.WTSInfoExLevel1.SessionFlags == WTS_SESSIONSTATE_LOCK);
}
if (pInfo) {
WTSFreeMemory(pInfo);
}
}
return flags;
return locked;
}
uint32_t get_active_user(PWSTR bufin, uint32_t nin, BOOL rdp)
+6 -77
View File
@@ -565,6 +565,7 @@ const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
extern "C" {
fn get_current_session(rdp: BOOL) -> DWORD;
fn is_session_locked(session_id: DWORD) -> BOOL;
fn LaunchProcessWin(
cmd: *const u16,
session_id: DWORD,
@@ -1268,7 +1269,7 @@ pub fn is_locked() -> bool {
let Some(session_id) = get_current_process_session_id() else {
return false;
};
is_session_locked_flag(session_id) == Some(true)
unsafe { is_session_locked(session_id) == TRUE }
}
#[inline]
@@ -1282,47 +1283,6 @@ pub fn is_logon_ui() -> ResultType<bool> {
.any(|pid| get_session_id_of_process(pid) == Some(current_sid)))
}
// Auto-login types the OS password on this, so a state that cannot be read counts as unlocked.
// `is_prelogin()` reads a failed query as no user signed in, and `is_logon_ui()` is left out
// because a LogonUI.exe can outlive the unlock.
pub fn is_logon_screen() -> bool {
let Some(session_id) = get_current_process_session_id() else {
return false;
};
is_session_prelogin(session_id) == Some(true)
|| is_session_locked_flag(session_id) == Some(true)
}
fn is_session_prelogin(session_id: u32) -> Option<bool> {
extern "C" {
fn get_session_user_info(path: *mut u16, n: u32, session_id: u32) -> u32;
}
let mut buff = [0u16; 256];
// The bytes copied include the terminating null, so 0 means the query failed.
let n = unsafe { get_session_user_info(buff.as_mut_ptr(), buff.len() as _, session_id) };
if n == 0 {
return None;
}
let username = String::from_utf16_lossy(&buff);
let username = username.trim_end_matches('\0');
Some(username.is_empty() || username == "SYSTEM")
}
// Windows 7 and Server 2008 R2 report LOCK and UNLOCK the other way round (see WTSINFOEX_LEVEL1).
fn is_session_locked_flag(session_id: u32) -> Option<bool> {
extern "C" {
fn get_session_flags(session_id: DWORD) -> DWORD;
}
const WTS_SESSIONSTATE_LOCK: DWORD = 0;
const WTS_SESSIONSTATE_UNLOCK: DWORD = 1;
let reversed = !base::platform::windows::is_windows_version_or_greater(6, 2, 0, 0, 0);
match unsafe { get_session_flags(session_id) } {
WTS_SESSIONSTATE_LOCK => Some(!reversed),
WTS_SESSIONSTATE_UNLOCK => Some(reversed),
_ => None,
}
}
pub fn is_root() -> bool {
// https://stackoverflow.com/questions/4023586/correct-way-to-find-out-if-a-service-is-running-as-the-system-user
unsafe { is_local_system() == TRUE }
@@ -1394,10 +1354,6 @@ pub fn get_install_options() -> String {
}
pub fn get_silent_install_options(printer_override: Option<bool>) -> &'static str {
if !is_win_10_or_greater() {
return "desktopicon startmenu";
}
let install_printer = match printer_override {
Some(override_value) => override_value,
None => {
@@ -1405,13 +1361,9 @@ pub fn get_silent_install_options(printer_override: Option<bool>) -> &'static st
let subkey = format!(".{}", app_name.to_lowercase());
let printer = get_reg_of_hkcr(&subkey, REG_NAME_INSTALL_PRINTER);
printer.as_deref() == Some("1")
&& remote_printer::is_rd_printer_installed(&app_name).unwrap_or_else(|err| {
log::warn!("Failed to check printer installation status: {err}; skipping printer installation");
false
})
}
};
if install_printer {
if install_printer && is_win_10_or_greater() {
"desktopicon startmenu printer"
} else {
"desktopicon startmenu"
@@ -3959,22 +3911,8 @@ pub fn update_to(file: &str) -> ResultType<()> {
// We need also to handle the command line parsing to find the tray processes.
pub fn update_me_msi(msi: &str, quiet: bool) -> ResultType<()> {
let quiet_args = if quiet { " /qn LAUNCH_TRAY_APP=N" } else { "" };
let app_name = crate::get_app_name();
let subkey = format!(".{}", app_name.to_lowercase());
let printer_installed = get_reg_of_hkcr(&subkey, REG_NAME_INSTALL_PRINTER).as_deref()
!= Some("0")
&& remote_printer::is_rd_printer_installed(&app_name).unwrap_or_else(|err| {
log::warn!(
"Failed to check printer installation status: {err}; skipping printer installation"
);
false
});
let printer_args = if printer_installed {
""
} else {
" INSTALLPRINTER=0"
};
let cmds = format!("chcp 65001 && msiexec /i \"{msi}\"{quiet_args}{printer_args} REBOOT=ReallySuppress /norestart");
let cmds =
format!("chcp 65001 && msiexec /i \"{msi}\"{quiet_args} REBOOT=ReallySuppress /norestart");
run_cmds(cmds, false, "update-msi")?;
Ok(())
}
@@ -4908,16 +4846,7 @@ mod tests {
#[test]
fn install_app_names_enforce_ascii_command_safety() {
assert!(validate_install_app_name("RustDesk-Admin1").is_ok());
for app_name in [
"",
"RustDesk_Admin",
"RustDesk&whoami",
"RustDesk应用",
"RustDesk앱",
"RustDeskBüro",
"RustDeskFrançais",
"RustDeskアプリ",
] {
for app_name in ["", "RustDesk_Admin", "RustDesk&whoami", "RustDesk应用"] {
assert!(
validate_install_app_name(app_name).is_err(),
"unsafe application name was accepted: {app_name}"

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