Compare commits

..
Author SHA1 Message Date
github-actions[bot] 0f9d6c67ee chore: update webpki-roots to latest Mozilla root store 2026-10-26 03:25:11 +00:00
VenusGirl❤ 1297da6d18 Update Korean language (#16687)
Update ko.rs
2026-10-24 17:28:24 +08:00
Lukas 8814503e06 fix(linux): pick up pulsectl's default source fix for voice calls (#16685) 2026-10-24 15:32:24 +08:00
Lukas c8a4e0680c fix(linux): capture the default output's monitor for remote audio (#16681)
* fix(linux): capture the default output's monitor for remote audio

With no audio input chosen, the _pa service recorded the first source whose name contains "monitor". Sources are listed in creation order, so on a host with more than one output, such as onboard audio plus HDMI, a USB headset or a Bluetooth speaker, that monitor can belong to an output the desktop does not play to, and the controlling side hears silence. Ask the server for the default sink and record its monitor, keeping the first monitor as the fallback.

* fix(linux): log the lookups that fall back to the first monitor

* fix(linux): fall back to the first monitor when the default sink has no monitor name

* fix(linux): throttle the default monitor lookup warnings
2026-10-24 14:56:09 +08:00
Cody SwartzandClaude Opus 5.5 ed6a1acce8 feat(address-book): add a toolbar button to open the web console (#16680)
The web console is only reachable from the "More on web console" item
in the menu beside the Tags heading, which is easy to miss and hidden
when the tags panel is turned off.

Add a button to the Address Book toolbar that opens the same URL and
reuses the same tooltip text. It shows under the same conditions as the
menu item: logged in, not in legacy address book mode, and write access
to the current book.

Signed-off-by: Cody Swartz <ctsstc@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 10:41:57 +08:00
21pages 4d37f00af9 fix(client): invalidate auto FPS state when updating FPS limits (#16283)
* fix(client): sync FPS control and reset limits on quality changes

  Track the last sent FPS across manual and automatic updates.
  Reset the FPS limit to 30 when leaving custom image quality,
  while preserving lower automatic limits when already capped at 30.

 fix(client): reset last sent FPS state on reconnect

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

fix(client): invalidate auto FPS state when updating FPS limits

  Clear last_auto_fps when setting custom FPS so the controller recomputes
  on its next tick. Restore the 30 FPS cap when switching to preset quality
  while preserving the saved custom FPS setting.

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

fix(client): reset auto FPS state after successful login

  Move last_auto_fps invalidation from login send paths to
  handle_peer_info, covering both normal and switch-side logins.

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

fix(client): scope auto FPS state to each connection

Keep automatic FPS state in the connection loop and invalidate it when processing manual FPS updates or successful login.

Validate queued automatic updates against the current FPS cap and record the value only after a successful send.

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

* test(client): cover FPS adjustment after manual updates

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

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-23 19:13:39 +08:00
Lukas 21c488b6ce fix(linux): recognize a login screen whose greeter uses another nologin path (#16675)
* fix(linux): recognize a login screen whose greeter uses another nologin path

is_prelogin() reads the active user's passwd entry and treats /bin/false or /usr/sbin/nologin as a greeter account. Greeter accounts on Arch use /usr/bin/nologin (gdm, sddm and lightdm) and others /sbin/nologin, so there a login screen was not detected: the audio service kept retrying the _pa ipc every second, which #16390 stopped at a login screen, and file transfer used the greeter's name. Match any nologin path.

* fix(linux): match nologin only in the shell field of the passwd entry

Checking the whole getent line also matched a home directory such as /home/nologin-test. Read the last field of each line and require it to end in /false or /nologin. Output with several lines, as getent prints for an empty name, still counts if any entry has such a shell, as before.

* fix(linux): compare the greeter shell with the known paths only

Match the shell field against /bin/false, /usr/bin/false, /usr/sbin/nologin, /sbin/nologin and /usr/bin/nologin instead of any path that ends in /false or /nologin, so a custom shell elsewhere is not taken for a login screen.
2026-10-23 18:09:08 +08:00
Lukas 01e1323e51 fix(linux): keep listing resolutions after an interlaced xrandr mode (#16672)
* fix(linux): keep listing resolutions after an interlaced xrandr mode

resolutions() reads the mode lines below an output with (\s*\d+x\d+\s+\d+.*\n)+, which needs whitespace right after the size. A TV usually lists 1920x1080i right after 1920x1080, so the list ended there and the resolution menu offered only the current mode. Allow a suffix after the size; the per-mode pattern still skips the interlaced lines, so only the following progressive modes are added.

* test(linux): check the resolutions parsed from xrandr output

Move the parsing of resolutions() into resolutions_from_xrandr(), which takes the xrandr output, so the test asserts the returned list instead of the captured mode lines. resolutions() runs xrandr and calls it; the parsing is unchanged.

* Revert "test(linux): check the resolutions parsed from xrandr output"

This reverts commit 854beb1. AGENTS.md asks not to reshape existing code only to enable a test, so resolutions() keeps its structure and the test checks the captured mode lines, as output_name_does_not_match_inside_another_name checks get_xrandr_conn_pat.
2026-10-23 17:23:02 +08:00
Lukas 106f700be4 fix(linux): read Debian's GDM config when checking for a Wayland login screen (#16674)
is_login_wayland() looks for WaylandEnable in /etc/gdm3/custom.conf and /etc/gdm/custom.conf. Debian's gdm3 package ships /etc/gdm3/daemon.conf instead (bookworm and trixie), whose default has '#WaylandEnable=false', so on Debian the function always returned false and the 'Login screen using Wayland is not supported' card never appeared. Read daemon.conf after the two custom.conf paths.
2026-10-23 16:58:52 +08:00
Lukas f7b0af78cb fix(lang): pick Traditional Chinese for Hong Kong and Macao system locales (#16671)
* fix(lang): pick Traditional Chinese for Hong Kong and Macao system locales

With no language chosen in Settings, resolve_lang picks zh-tw only when the system locale contains tw. Hong Kong and Macao locales (zh_HK, zh-Hant-HK, zh_HK_#Hant, zh_MO) and a bare zh-Hant got Simplified Chinese, although they write Traditional Chinese. Pick zh-tw for them too, unless the locale names the Hans script.

* test(lang): cover a bare zh-Hant locale
2026-10-23 16:49:51 +08:00
Lukas 25d2742273 fix(lang): pick the Kazakh and Georgian translations from the system locale (#16670)
With no language chosen in Settings, resolve_lang takes the language from the system locale prefix. Kazakh locales are kk_* and Georgian locales are ka_*, but their translation tables are keyed kz and ge, so both fell through to English. Map kk to kz and ka to ge for the locale-derived language. A language saved in Settings is unchanged.
2026-10-23 15:56:15 +08:00
Hüseyin Durna eb6c32bd57 l10n(tr): fill missing shortcut and API server translations (#16669)
Signed-off-by: Hüseyin Durna <76519526+husodrn46@users.noreply.github.com>
2026-10-23 15:48:35 +08:00
Rafał Sikora 398364fa18 fix(ios): keep background music playing during remote sessions (#16660)
Configure the iOS audio session with the ambient category so remote
playback mixes with other apps while respecting Silent mode and lock.
Log configuration errors and leave audio activation to playback.

Signed-off-by: Rafal <mrsikorarafal@gmail.com>
2026-10-23 11:23:08 +08:00
rustdeskandClaude Opus 5.5 828d1101af chore(deps): pin hwcodec to rustdesk-org/hwcodec#47
Move the locked hwcodec revision from febec27 to ec38eba, the merge of
rustdesk-org/hwcodec#47: GPU query failure handling, Windows resource
handling and recoverable fragmented MP4 recording. hwcodec's own
dependencies are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:48:28 +08:00
RustDeskandClaude Opus 5.5 3ec041644d fix(linux): gtk sudo shows no false "Sorry, try again." and retries with sudo-rs (#16652)
* fix(linux): no false "Sorry, try again." in gtk sudo after a PAM info line

The gtk sudo dialog takes the password before sudo starts and drops it
when sudo prints a non-prompt line first, such as pam_fprintd's "Place
your finger on the fingerprint reader". The real password prompt then
came up labelled as a retry, "Sorry, try again.", although no password
had been sent, so users took it as a rejected password.

Treat the next prompt as a first prompt when the typed password is
dropped. The dialog comes back prefilled and without the error.

Keeping the password and sending it to the next prompt instead is not
safe: when sudo authenticates without a prompt (fingerprint, NOPASSWD),
use_pty, the default since sudo 1.9.14, holds the tty in raw mode while
the command runs, so any output line ending in ':' would receive it.

Fixes #16647

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

* fix(linux): let gtk sudo retry after sudo-rs rejects a password

sudo-rs reports a rejected password with "sudo: Authentication failed,
try again." and then asks again. The line starts with "sudo:", so
ui_parent treated it as fatal: it showed it in an error dialog and
exited instead of offering a retry, as it does after classic sudo's
"Sorry, try again." (the second log in #16647).

Exempt exactly that line from the fatal check. It then goes through
the ordinary non-prompt branch, so the held-password drop rule still
applies. sudo-rs's final "maximum N incorrect authentication attempts"
stays fatal, and so does every other sudo:/su: line.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:27:35 +08:00
RustDeskandClaude Opus 5.5 d97351ad73 Custom websocket port (#16658)
* feat: let custom client settings set websocket-port

A domain endpoint becomes ws(s)://<domain>/ws/id with no port, so a
WebSocket reverse proxy that cannot listen on 443 (or 80) is
unreachable. hbb_common adds websocket-port for that; list it in
KEYS_SETTINGS so default-settings and override-settings carry it.

The hbb_common bump also brings in 20d5019 (quiets smithay client
toolkit logs, rustdesk/hbb_common#620).

https://github.com/rustdesk/rustdesk-server-pro/discussions/1029

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

* Update hbb_common for the websocket-port warning throttle

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

* Update hbb_common: match websocket-port only against configured servers

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

* Pin hbb_common to the merged websocket-port change

rustdesk/hbb_common#626 is merged as edefa08. The range from master's
pin 5d52530 also includes 20d5019 (quiets smithay client toolkit logs,
rustdesk/hbb_common#620).

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:58:00 +08:00
fufesou 2b6fedfc8e fix(windows): protect installer handoff and use native service control (#16562)
* fix(windows): use native APIs for manual service control

rustdesk/rustdesk#16557

Replace elevated service-control batch scripts with SCM operations
and native tray shortcuts. Preserve SYSTEM configuration import
and propagate helper failures.

* fix(windows): preserve service state during manual control

Keep existing service registration and synchronize failed operations with SCM state. Run the installed legacy importer directly as SYSTEM, bound its exit waits, and keep auxiliary cleanup errors separate from service lifecycle results.

* fix(windows): preserve legacy service import without debug privilege

* fix(windows): replace installer certutil and findstr

Use native SHA-256 verification and shortcut decoding, and execute the protected batch script in a single cmd process. Preserve protected staging, verification receipts and failure exit codes.

Restore the master service-control flow and remove the separate SCM and Task Scheduler implementation to keep the antivirus fix focused and preserve legacy configuration import.

Validation: Windows Rust library build, nine focused tests, and isolated single-cmd success, failure, tamper rejection and cleanup checks passed. Bitdefender validation remains pending.

* fix(windows): preserve installer helper path compatibility

* fix(windows): preserve caret-only installer helper paths

* fix(windows): protect installer data and use native service control

Stage installer scripts, shortcuts and verified updates with restricted ACLs
before elevation. Remove the elevated portable-verifier launch while keeping
certutil and findstr out of the shared installer handoff.

Use the installed Flutter runner for native normal-service create/start and
stop/delete operations. Preserve existing registrations on repeated setup,
legacy configuration import, and compatibility with older installed runners.
Report installer failures and document the security and compatibility reasons.

Validation: Windows Rust test build and Release runner build passed; six
isolated service checks and runner exit-code checks passed. Focused Rust
installer/update tests passed 8/9; the directory-cleanup ACL test also fails in
the earlier binary. Final service lifecycle and Bitdefender testing is pending.

* fix(windows): clean staged installer files on UAC cancellation

Retain DELETE handles until the elevated cmd connects to a local pipe, then
release the handles before allowing the BAT to run. This preserves protected
staging while allowing cancellation cleanup and cmd file access.

Handle interrupted handoffs, supply the byte-count pointer required on
Windows 7, and explain early service dispatch in the C++ runner. Keep the
staging tests inline with their implementation.

Validation: Windows Rust test build, focused installer-file and handoff
tests, rustfmt, and staged diff checks passed. The pre-existing directory
ACL test failure is unchanged. Actual UAC cancellation, Windows 7 runtime,
and final-build Bitdefender validation remain pending.

* fix(windows): roll back new service registration on start failure

Delete a registration created by this attempt if startup fails, while preserving existing services and already-running success. Keep the original startup error and report rollback failures separately.

Validation: eight isolated service checks and the Release Flutter runner build passed. Real service startup failure and final-build Bitdefender validation remain pending.

* fix(windows): continue uninstall after service stop errors

Log an unsuccessful stop and still request deletion so the uninstall
script can reach its existing taskkill and cleanup commands. Treat an
already marked service as a satisfied deletion request, while preserving
other deletion errors and the normal stop wait.

Validation: all twelve isolated service-control checks passed, including
already-marked, stop-rejected, stop-timeout and deletion-denied cases.
The Release Flutter runner build and existing argument/exit-code checks
passed. Real SCM failure scenarios and Bitdefender remain unverified.

* fix(windows): finish installer setup before service startup

Complete SAS policy and printer setup before native service activation so a startup failure cannot skip independent installation steps. Preserve the startup error, rollback and legacy command sequences, and document uninstall_service's continuation result.

Validation: Windows Rust test compilation, four isolated command cases and two existing installer handoff tests passed. CodeRabbit completed with no findings. Actual installer, SCM and Bitdefender validation remains pending.

* fix(windows): use native service control for Sciter

Share the existing native service operations with Sciter and dispatch
--service-control before UI initialization. Keep Flutter's entry point and
the legacy commands for a different installed executable unchanged.

Validated the Windows x64 Sciter build, Flutter-feature test build,
x86 C++ bridge compilation, and real EXE/BAT error propagation. Final
Bitdefender installation and service lifecycle validation remain pending.

* fix(windows): propagate negative service-control exit codes

Treat every nonzero service-control exit status as a failure so crash and loader error codes cannot be reported as success. Verified six real cmd.exe exit-code cases; CodeRabbit review completed with no findings. Actual service crashes were not exercised.

* fix(windows): handle UAC cancellation and scope service rollback

Preserve the typed elevation error and its diagnostic details so canceled UAC prompts do not show an installation-failure dialog.

Use create-service for normal installation and create-service-with-rollback for manual Start Service. Retain a new registration after a normal installation startup error; roll back only the manual path that restores stop-service=Y.

Validation: Windows Rust test compilation, Release Flutter runner and Sciter builds, cancellation/error-chain checks, isolated service-result cases, and real executable argument/exit propagation checks passed. Actual UAC cancellation and Bitdefender were not rerun.
2026-10-22 13:34:49 +08:00
CatzTimesandCatzTimes f010d33ca6 fix(android): wheel scrolling from the controller does not reach Android peers (#16409)
The controller sends a wheel tick as a MouseEvent whose type bits are
MOUSE_TYPE_WHEEL (src/common.rs) with the scroll delta in y, but
InputService only handles the legacy WHEEL_DOWN/WHEEL_UP masks
(523331/963) that current controllers never send. As a result the
mouse wheel does nothing on every Android controlled device.

Handle MOUSE_TYPE_WHEEL with the same stroke emulation the legacy
masks use, as a purely additive branch: a 90px vertical stroke
(MOUSE_WHEEL_STEP, three quarters of the legacy WHEEL_STEP - the full
120px felt too far per tick to reviewers on real devices) over
WHEEL_DURATION at the current cursor position, with the same top-edge
guard and queue consumption, mapped with the controller's sign
convention (y < 0 = wheel down; y == 0, a horizontal tick, is
ignored). The branch is gated to API 24+ like the rest of the gesture
path - below that, legacy devices take the Shizuku backend or a
no-op, not this class. The legacy WHEEL_DOWN/WHEEL_UP implementations
are untouched.

Community reports matching this gap on modern devices: #9321 (Pixel
8, Android 14) and #1466 (Android tablet).

Signed-off-by: CatzTimes <CatzTimes@users.noreply.github.com>
Co-authored-by: CatzTimes <CatzTimes@users.noreply.github.com>
2026-10-22 11:41:56 +08:00
Leo Camus bd92623972 fix(linux): match the xrandr output name at the start of its line (#16590)
The pattern resolutions() and current_resolution() build from the
output name is not anchored, so DP-1 also matches the eDP-1 line. On a
laptop where xrandr lists eDP-1 first, the external DP-1 reports the
built-in panel's current mode and mode list.
2026-10-21 18:59:13 +08:00
21pages 4e93a41ecc Tune MediaCodec static refresh budgets (#16579)
* Tune MediaCodec static refresh budgets

Use H.264 budgets 50/20/20/10 and H.265 budgets 90/20/20/20 from MT6855 1080p measurements with early stopping at 80% of observed-best improvement, not full convergence.

Retain the existing H.265 low-quality budget because the line-pattern sample did not confirm convergence within 150 repeat calls. Keep the existing ten latency-draining repeats, other backends, and refresh timing unchanged.

Extend output-budget and backend-selection regression coverage. Static refresh tests pass with hwcodec (17 tests) and default features (16 tests).

* fix(video): retain the largest static refresh budget per frame
2026-10-21 16:02:32 +08:00
21pages ce54e33c71 fix(ffmpeg): handle QSV encoder stalls and undersized buffers (#16303)
* fix(ffmpeg): bound QSV encoder retries

Limit QSV frame submission to 100 retries and synchronization to 10
retries so persistent SDK warnings return an error to the caller. Retain
queued buffers when synchronization reaches its retry limit, and allow
later calls to retry without latching an error.

Wait 1 ms between retryable submission warnings on Windows: the original
av_usleep(500) becomes Sleep(0), exhausting the retry budget before even
a brief device-busy interval can end. Preserve non-Windows wait behavior
and the existing negative SDK result handling.

Validated against FFmpeg 7.1.1 on Intel UHD 730 with 42 fault/control
cases, synchronization-timeout recovery and close cleanup, real H.264
and HEVC encoding, and separate QSV hardware decoding. Four concurrent
1080p encoders completed 2400 frames without errors.

* fix(ffmpeg): handle undersized QSV HEVC buffers

Reserve at least three bytes per aligned pixel for HEVC output, following
Intel's documented workaround for underestimated bitstream capacity. Check
the size before assigning it to AVPacket's integer capacity.

Report negative synchronization results before reading output metadata or
draining the FIFO, keeping failed tasks owned until encoder close.

On Intel UHD 730, the existing code fails at input 242 with real desktop
captures; the patched code encodes and decodes all 1,200 inputs. Inputs and
PTS match, and the first 241 encoded frames are byte-identical. H.264 also
passes 300 frames, and restoring the small buffer verifies error handling.

* fix(ffmpeg): refresh QSV HEVC capacity after reset and shorten sync waits

* fix(ffmpeg): apply QSV buffer sizing to H.264

* fix: backport FFmpeg hybrid MP4 finalization fix

Backport FFmpeg commit 36896af64a9ecf6835758186e7161a2e954c364d so hybrid MP4 finalization writes the final moov before hiding the original fragmented index. Preserve recoverable fragments when the final index cannot be written.
2026-10-21 16:00:34 +08:00
RustDeskandClaude Opus 5.5 2016f48dd7 fix(file-transfer): keyboard navigation in the desktop file list (#16642)
* fix(file-transfer): keyboard navigation in the desktop file list

Up/Down never moved the selection in the desktop file transfer list. The
arrow keys fell through to directional focus traversal instead, which
moved focus out of the list and stopped type-to-search until the mouse
entered the list again.

Handle the navigation keys on the list, as the Sciter grid did:
- Up/Down move the selection one row; Shift extends or shrinks a range
  from its anchor.
- PageUp/PageDown go to the edge of the visible rows first, then a page
  further; Home/End go to the first/last row. Shift extends with each.
- Enter/numpad Enter opens the selected folder, like a double click.
- Left/Right are consumed so focus does not jump to the other pane.

Type-to-search now ignores control characters. On macOS and Linux Enter
carries "\r", which matched no name and cleared the selection before
Enter could open it.

Fixes #16635

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

* fix(file-transfer): keep default keys on focused file list children

The navigation bindings wrapped the whole file list, sort headers
included, so a header focused with Tab lost Enter to sort and the arrow
keys to move between headers: Enter ran the open-folder binding instead.

Handle the bindings only while the list itself has primary focus and let
keys on a focused child take their default path.

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

* fix(file-transfer): focus the file list when a row is clicked

The navigation keys only act while the file list holds primary focus.
Keyboard focus was handed to the list only when the mouse entered it,
so after Tab moved focus to a sort header, clicking a row left the
arrow keys inert until the mouse left and re-entered the list.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:50:38 +08:00
fufesou b44b71cfab Fix/download path validation (#16601)
* fix: validate download destinations and peer filename rules

Reject unsafe or linked download destinations and validate empty-directory
paths before creating them. Bind overwrite approval to accepted transfer
entries and propagate receiver errors to the UI.

Validate remote listings using the peer's filename rules so Unix names
remain browsable on Windows. Reject locally unsafe basenames before
starting downloads from either the Flutter or legacy UI.

Finish the previous file before validating the next digest so rejecting
the next destination preserves the file already received.

Require confirmation before restarting interrupted downloads with stale
staging files. Preserve matching resumes and cover receiver recovery.

Retain explicit overwrite rejection for peers older than 1.1.10 that
cannot negotiate confirmation.

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

* comments

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

* fix: use async I/O for download preparation and resume

Use Tokio filesystem APIs for download setup and resume metadata checks. Run the Windows link-count query on the blocking pool and flush digest writes before returning.

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-21 11:55:00 +08:00
mvtbh eef1096395 Update fa.rs (#16587) 2026-10-21 11:45:01 +08:00
Andrzej Rudnikgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>RustDesk
8b61033178 Update pl.rs (#16588)
* Update pl.rs

Update Polish language (shortcuts screen).

* Update src/lang/pl.rs

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update src/lang/pl.rs

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update pl.rs

* Update pl.rs

Corrected typo.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: RustDesk <71636191+rustdesk@users.noreply.github.com>
2026-10-21 11:44:46 +08:00
Alex Rijckaert c29bef18bb Update Dutch translations for keyboard shortcuts (#16625) 2026-10-21 11:43:30 +08:00
fathur c6258f4166 Fix typo in Indonesian translation (#16630)
* docs(id): translate misuse disclaimer section

* docs(id): add Flathub download badge

* i18n(id): fix typo in Indonesian translation

* fix broken translation tuple in id.rs

* i18n(id): fix typo in Indonesian translation
2026-10-21 11:43:15 +08:00
bovirus 989beee17f Update Italian language (#16633) 2026-10-21 11:42:56 +08:00
Ricardo Simõesandgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> 4b1821d1ff Update pt pt translation + README.md to include Portuguese (Portugal) (docs/README-PTPT.md) (#16634)
* Update pt_PT.rs

* Add files via upload

* Update README-PTPT.md

* Update README-PTPT.md

* Update README.md to include new pt-PT (docs/README-PTPT.md)

* Update docs/README-PTPT.md

Corrected link libs/base

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update docs/README-PTPT.md

Corrected "área de trabalho" to "área de transferência"

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update pt_PT.rs

Fix api_server_connection_tip and api_server_empty_tip: translate from en.rs source

* Fix relative links in README-PTPT.md (remove extra docs/ prefix)

* Fix section anchors in README-PTPT.md to match PT-PT headings

* Fix typos and gender agreement in README-PTPT.md disclaimer

* Use European Portuguese terms in README-PTPT.md screenshot alt text

* Translate shortcut instructions from en.rs source

* Update pt_PT.rs

Align shortcut and API server strings with en.rs source (keep {} placeholders)

* Revert JumpLink to original value (out of scope for this PR

* Replace remaining Brazilian Portuguese terms in README-PTPT.md

Replaces leftover Brazilian Portuguese wording with European Portuguese
equivalents (e.g. "conosco" -> "connosco", "controle" -> "controlo",
"conexão" -> "ligação", "Você tem" -> "Tem", "amigável" -> "acessível",
"desktop" -> "ambiente de trabalho"), consistent with the terminology
already used in src/lang/pt_PT.rs.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-10-21 11:42:44 +08:00
Shaan Majid 3202d1764c chore(deps): update webpki-roots and rustls-webpki in Cargo.lock (#16639)
webpki-roots and webpki-root-certs 1.0.10 drop emSign ECC Root CA - G3, whose
eMudhra intermediates had their private keys compromised. rustls-webpki
0.103.16 rejects chains through those intermediates (RUSTSEC-2026-0382,
RUSTSEC-2026-0383); it needs rustls-pki-types >= 1.12.

Signed-off-by: Shaan Majid <70789625+shaanmajid@users.noreply.github.com>
2026-10-21 11:42:17 +08:00
fufesou c7f212df2c fix: warn about insecure custom API server connections (#16616)
* fix: warn about insecure custom API server connections

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

* fix: limit API server warning to HTTP addresses

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

* fix: resolve API warnings against effective server configuration

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

* fix: reuse common sync for API server previews

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

* fix: keep server settings usable on API preview errors

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-20 22:52:48 +08:00
fathur 7f5a401947 Update README-ID translations (#16626)
* docs(id): translate misuse disclaimer section

* docs(id): add Flathub download badge
2026-10-20 22:50:42 +08:00
Leo Camus bbffc1de5a fix: bracket a bare IPv6 ID server when deriving the API server (#16624)
With the API server field empty, get_api_server_ builds the URL from the
ID server as "http://{host}:21114". For an ID server entered as a bare
IPv6 address such as 2001:db8::1, which test_if_valid_server accepts,
increase_port leaves it unchanged and the result is
http://2001:db8::1:21114. That does not parse as a URL (InvalidPort), so
login and every other API request fail.

Wrap the address in brackets in that branch only. Hostnames, IPv4 and
"[addr]:port" take the same path as before.
2026-10-20 22:12:00 +08:00
Leo Camus 4b92080e3e fix(x11): keep the RandR monitors reply alive while iterating it (#16595)
DisplayIter::next_screen built the monitor iterator from the
xcb_randr_get_monitors reply and freed the reply on the next line.
The iterator's data pointer points into that reply, so next() read
every monitor's name atom, position and size from freed memory, and
xcb_randr_monitor_info_next() walked it too.

Keep the reply with the iterator and free it when moving to the next
screen or when the DisplayIter is dropped.
2026-10-20 17:29:30 +08:00
Chris21xandchg 0cbeb04730 Forward audio latency environment to Linux user server (#16597)
* Forward audio latency environment to Linux user server

Preserve PULSE_LATENCY_MSEC and PIPEWIRE_LATENCY when the root service spawns the per-user RustDesk server.

The systemd service defines these variables, but they were not included in the explicit environment passed to run_as_user(), causing the user server and connection manager to fall back to higher audio latency.

Forward the existing values without changing their defaults.

* Add regression test for Linux audio latency forwarding

---------

Co-authored-by: chg <chg@vis-ag.ch>
2026-10-20 17:13:11 +08:00
fathur 1042a26deb Add Flutter code section to README-ID (#16600)
* Add Flutter code section to README-ID

Added a section for Flutter code related to desktop and mobile platforms.

* Fix link formatting for Flutter code section
2026-10-20 16:13:13 +08:00
solokot 53996e3c40 Update ru.rs (#16570) 2026-10-16 11:18:21 +08:00
RustDesk e400bb7554 Enforce lockfile during pub get in build script 2026-10-15 22:39:27 +08:00
21pages 392188596c fix(video): improve clarity after scrolling by re-encoding static frames (#16128)
* fix(video): re-encode static frames for up to 10 seconds to improve clarity

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

fix(video): limit static re-encoding to 300 frames instead of 10 seconds

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

refactor(video): move static frame refresh into a dedicated module

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

fix(video): preserve stuck-encoder detection state across static repeats

test(video): cover cached texture lifetime across capture restarts

fix(video): reduce static re-encoding limit to 100 frames

fix(qos): lower qos_trace logging to trace level

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

fix(video): skip static frame re-encoding for AV1

perf(video): reuse VRAM encoder input for static refresh

Remove the DXGI repeat texture cache and use hwcodec's repeat entry point to avoid copying each captured frame. Isolate static refresh failures, pause after three errors, and resume after a real frame is sent successfully.

Cover cached input ownership, repeat failure recovery, refresh limits, and normal encoder failover with regression tests.

fix(vram): ignore cached SDK codec backends

chore(deps): temporarily use hwcodec re-encode branch

perf(video): wait 200ms before starting static refresh

chore(deps): update hwcodec for FFI exception handling

chore(deps): update hwcodec to 0.8.0

perf(video): start static refresh after 100ms

chore(deps): update hwcodec for exception-safe cleanup

chore(deps): update hwcodec for device-loss handling and noexcept FFI

chore(deps): update hwcodec to bbfc306

chore(qos): remove verbose diagnostics while retaining trace logs

* update hwcodec

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

* refactor(scrap): keep repeat encoding in the vram module

* perf(vram): avoid intermediate frame vectors

  - Drain normal and repeated encode output into protobuf messages.
  - Cover null-texture encoding failures.
  - Clarify the count-based static refresh budget.
  - Update hwcodec to fix RAM decode buffers on resolution changes.

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

* fix(scrap): preserve hardware encoder error codes

* test(video): remove uptime dependency from static refresh tests

* feat(video): configure static repeat limits by codec and quality

* fix(video): exempt VPx and AV1 from static repeat failure limit

* fix(video): count only successful static repeat frames

* fix(video): refine static repeat scheduling and VPx frame handling

Allow static refinement after a VP8/VP9 captured frame produces no output
without enabling it after a genuine encoding error. Carry this distinction
alongside the send result so the latest cached frame can still be sent when
capture becomes idle.

Keep VP8/VP9 repeats at a minimum of 100ms. Other codecs wait at least 100ms
initially, then follow the QoS frame interval aligned with the capture loop.
Use four quality bands, with VP8/VP9 limits of 30/20/20/0 and the tuned
H264/H265 limits. Include only production behavior and regression tests.

Validation: 16 static_refresh tests passed with hwcodec,vram,flutter enabled,
covering latest-frame recovery, genuine errors, timing, and repeat budgets.

* fix(video): tune static repeat limits by codec and backend

Use the measured obvious-improvement checkpoints for VP8/VP9 and separate
NVENC, QSV, and AMF H.264/HEVC limits for each quality tier. The checkpoints
recover 80% of the observed error improvement across the tested inputs.

Resolve the hardware backend from EncoderCfg during StaticRefresh
construction, including the VRAM adapter vendor. Keep the existing limits
for other hardware backends.

Validation: 19 static_refresh tests passed with hwcodec,vram,flutter.
The repeat measurements cover 192 series with no encode/decode errors.

* fix(video): refine static refresh budgets and cap repeat FPS

Add VideoToolbox HEVC budgets and tune quality bands from repeat-frame comparisons. Cap static refresh at 30 FPS and use the speed preset consistently at quality 0.5.

* remove unused variables

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

* fix(video): repair static refresh tests and throttle repeat logs

---------

Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-10-15 20:17:49 +08:00
RustDeskandClaude Opus 5.5 c0750fb50c fix(client): report one error when both WebRTC race legs fail (#16563)
Both legs of race_transports_prefer_webrtc send their own punch request
to the same rendezvous server for the same peer, so a refusal there
(offline, unknown ID, key mismatch, a server-supplied other_failure)
fails both with the same text. Joining them as "WebRTC failed: X;
fallback failed: X" showed it twice and broke the UI's whole-string
matching: the offline auto-retry needs exactly "Remote desktop is
offline", the message box translates the text as one string, and
check_if_retry hides the retry button for any text containing "failed".

Return the error of the leg that failed last, as select_ok did before
the race existed, and log the other one once.


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:52:19 +08:00
fufesou f705902ec3 fix(windows): move installer scripts into protected temp directories (#16554)
* fix(windows): move installer scripts into protected temp directories

Create a private directory under Windows Temp with its final DACL in
CreateDirectoryW. Grant Administrators and SYSTEM full access and use
OWNER RIGHTS to suppress the ordinary creator's implicit WRITE_DAC.

Keep the existing elevated system-cmd copy and SHA-256 verification flow.
Keep auxiliary files in the same directory, report cleanup failures, and
check command length before creating the directory.

This avoids PowerShell, helper executables, and application startup or DLL
linking changes. The Windows Temp parent must retain its standard protection
against deletion by unprivileged users. UAC cancellation can leave an empty
protected directory; the error reports its path.

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

* fix(windows): preserve installer results when cleanup fails

Keep the original installer exit code and report remaining temporary directories or inspection errors as warnings with their paths. Include the directory path in creation errors.

Restore the existing handoff assertions in a separate test module, add a locked-directory regression for successful and failed installers, and remove the unrelated ERRORLEVEL environment change.

Validation: scoped formatting and whitespace checks passed. Native cmd probes reproduced the failure before the fix and preserved both exit codes afterwards. No project build or Rust test execution was performed.
Signed-off-by: fufesou <linlong1266@gmail.com>

* fix(windows): clarify installer cleanup warnings

Describe protected directories as possibly remaining when cleanup cannot be verified. Remove the cleanup-only test added during review while retaining existing handoff coverage.

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

* test(windows): keep installer handoff tests inline

Restore the inline test module and original helper order to reduce the diff against master. Keep the directory cleanup assertions and original bootstrap checks.

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

* fix(windows): include paths in installer directory check errors

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

* fix(windows): clear inherited ERRORLEVEL before installation

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

* fix(windows): avoid duplicate directory error messages

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

* test(windows): verify installer directory permissions

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-15 17:33:35 +08:00
RustDeskandClaude Opus 5.5 0d36ac0cba fix(linux): stop using the window in onWindowClose once GTK destroyed it (#16561)
On Linux, GTK destroys the window on a close request unless prevent-close
is on. When the main window is the last active one, onActiveWindowChanged()
turns prevent-close off and calls close(), yet onWindowClose() still went
on to hide() the destroyed window, and the close event that close() emits
re-entered onWindowClose() to save the frame through isMaximized(). The cm
and install windows never turn prevent-close on, so their window is always
gone by the time onWindowClose() runs.

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

Fixes #16512


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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:33:42 +08:00
RustDeskandClaude Opus 5.5 f1fa432bc8 Fix fdroid bridge version (#16560)
* fix(fdroid): generate the bridge with the Flutter version bridge.yml uses

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

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

Fixes #16549

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

* update hbb_common

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

* fix: remove WebSocket proxy opt-in

* chore: restore proxy settings UI and translations

* fix: update hbb_common for proxy read progress

* fix: update hbb_common proxy connections and IPv6 parsing

* fix: update hbb_common WebSocket local address

* update to rustdesk/hbb_common

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

---------

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

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

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

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

* ci: run the Rust tests CI could not reach

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  Design principles applied during review:

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

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

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

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

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

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

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

* langs

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

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

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

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

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

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

* feat(keyboard): shortcuts, debug web

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

* fix(keyboard): iPad, icon

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: prevent lost input after remote session shortcuts

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: hide relative mouse mode shortcuts on Wayland

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

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

* fix: align shortcut availability with platform support

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

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

* fix: prevent held-key shortcut recording bypass

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

* fix: preserve keyboard input after shortcut dialogs

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

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

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

* fix: preserve remote key state during local shortcuts

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

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

* fix: suspend saved relative mouse shortcuts on Wayland

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

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

* fix: exclude unsupported Wayland shortcuts from Flutter matching

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

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

* fix: retain forwarded key ownership across shortcut repeats

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

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

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

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

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

* fix: filter active Flutter shortcuts by platform capabilities

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

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

* fix: filter native shortcut caches for mobile controllers

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

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

* fix: share filtered shortcut bindings with the Web matcher

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

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

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

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

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

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

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

* refact: remove the useless comments

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

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

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

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

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

* fix: prevent Alt menu activation in all keyboard modes

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

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

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

* fix: initialize outgoing chat before shortcut dispatch

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

* fix: guard Windows Alt release in Flutter legacy shortcuts

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

* fix: coordinate Web shortcut dispatch and Alt modifier cleanup

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

* fix: distinguish AltGraph from ordinary Alt shortcuts

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

* fix: dispatch macOS Web shortcuts without waiting for keyup

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

* fix: support legacy peers in privacy mode shortcut

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

* fix: exclude AltGraph from Flutter shortcut matching

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

* fix: exclude GTK AltGr input from raw shortcut matching

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

* test: trim redundant keyboard shortcut coverage

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

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

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

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

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

* fix(shortcuts): align recording and display routing

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

Refs #16510, #15261

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

* windows: drop the LogonUI.exe check from is_logon_screen

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* server: name os_login in scope-violation logs

A rejected os_login was logged as message.other.

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(update): prevent replacing published release assets

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

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

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

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

* refact: reduce the diffs

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

* refact(update): remove obsolete update paths

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

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

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

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

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

* fix(update): verify Windows installers with Authenticode

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

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

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

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

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

* refactor(update): remove OS signature sanity checks

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

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

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

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

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

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

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

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

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

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

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

* refact(update): remove some simple wrappers

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

* refact(update): simple refactor

* refact(update): comments on update.scpt

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

* refact(update): comments

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

* fix(update): create download destinations exclusively

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

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

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

* fix(msi): propagate MSI installation failures

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

* chore

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

Clear tracked buttons only after coordinate validation succeeds.

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

---------

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

Fixes #16506


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

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

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

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

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

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

* fix: disconnect other remote sessions when privacy mode starts

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

* fix: exclude privacy disconnect hook from iOS builds

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

* fix: validate privacy mode before disconnecting other sessions

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

* chore

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

---------

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

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

* fix(windows): distinguish printer detection failures

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

* fix(windows): skip printer detection when disabled

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

* fix(flutter): load printer status asynchronously

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

* refactor(flutter): remove printer status mounted checks

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

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

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

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

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

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

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

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

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

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

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

* fix(installer): allow cancellation during printer detection

Inline MSI update command construction without changing its arguments.

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

* fix(flutter): time out installer printer detection

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

* chore

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

* test(windows): cover multilingual install app names

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

---------

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

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

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

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

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

* fix(linux): harden Wayland keyboard layout detection

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

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

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

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

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

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

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

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

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

* docs(linux): record layout query latency measurements

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(linux): preserve missing punctuation shortcuts

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

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

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

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

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

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

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

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

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

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

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

* docs(linux): explain Xwayland layout synchronization limits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(linux): reject inactive IBus layout sources

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(uinput): remove unnecessary change

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

* refactor(linux): simplify uinput character releases

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

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

* fix(linux): normalize Unicode CapsLock shortcuts

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

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

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

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

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

* refactor(linux): remove CapsLock shortcut special cases

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

Refs #15731

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

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

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

Refs #15731

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

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

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

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

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

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

Fixes #16457

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

* Update video_service.rs

---------

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

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

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

* fix(macos): refine keyboard failure diagnostics

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

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

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

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

---------

Signed-off-by: fufesou <linlong1266@gmail.com>
2026-10-08 00:23:14 +08:00
Stephan Paternotte f0bd880fe7 Update nl.rs (#16485)
lang: Dutch language file updated
- various consistency fixes
- ... -> …
- empty values translated
2026-10-07 21:33:18 +08:00
255 changed files with 13957 additions and 10927 deletions
+1 -1
View File
@@ -234,7 +234,7 @@ jobs:
CARGO_TEST_OPTIONS="--lib --bin ${PROJECT_NAME}"
;;
*)
CARGO_TEST_OPTIONS="--workspace --no-fail-fast -- --skip test_get_cursor_pos --skip test_get_key_state"
CARGO_TEST_OPTIONS="--workspace --no-fail-fast"
;;
esac;
+299 -9
View File
@@ -9,6 +9,9 @@ on:
upload-tag:
type: string
default: "nightly"
publish-update-metadata:
type: boolean
default: false
# NOTE: F-Droid builder script 'flutter/build_fdroid.sh' reads environment
# variables from this workflow!
@@ -45,16 +48,54 @@ env:
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VCPKG_CMAKE_VERSION: "4.3.0"
ARMV7_VCPKG_COMMIT_ID: "6f29f12e82a8293156836ad81cc9bf5af41fe836" # 2025.01.13, got "/opt/artifacts/vcpkg/vcpkg: No such file or directory" with latest version
VERSION: "1.5.0"
VERSION: "1.5.1"
NDK_VERSION: "r28c"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
MACOS_P12_BASE64: "${{ secrets.MACOS_P12_BASE64 }}"
UPLOAD_ARTIFACT: "${{ inputs.upload-artifact }}"
PUBLISH_UPDATE_METADATA: "${{ inputs.publish-update-metadata }}"
SIGN_BASE_URL: "${{ secrets.SIGN_BASE_URL }}-2"
jobs:
validate-update-metadata-keys:
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- name: Checkout source code
if: ${{ inputs.publish-update-metadata }}
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
if: ${{ inputs.publish-update-metadata }}
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
if: ${{ inputs.publish-update-metadata }}
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Test update metadata signer
if: ${{ inputs.publish-update-metadata }}
run: |
python -m unittest \
res/update/test_generate_update_metadata.py \
res/update/test_update_metadata_cli.py \
res/update/test_macos_update_scripts.py
- name: Validate update metadata keys
if: ${{ inputs.publish-update-metadata }}
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: python res/update/generate_update_metadata.py check-key
generate-sbom:
needs: [validate-update-metadata-keys]
runs-on: ubuntu-latest
permissions:
@@ -83,9 +124,11 @@ jobs:
rustdesk.sbom.json
generate-bridge:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/bridge.yml
build-RustDeskTempTopMostWindow:
needs: [validate-update-metadata-keys]
uses: ./.github/workflows/third-party-RustDeskTempTopMostWindow.yml
strategy:
fail-fast: false
@@ -323,6 +366,17 @@ jobs:
Write-Host "Ingore the printer driver error."
}
- name: Run the Rust tests
# x86_64 only: the tests are the same code on arm64, and that runner is the slow one.
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'x86_64' }}
shell: bash
run: |
# The build's own features, so the tests see the code that ships.
FEATURES=$(python3 ./build.py --portable --flutter --skip-portable-pack --hwcodec ${{ matrix.job.build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Its Windows tests run nowhere else.
cargo test --locked --release -p clipboard
- name: find Runner.res
# Windows: find Runner.res (compiled from ./flutter/windows/runner/Runner.rc), copy to ./Runner.res
# Runner.rc does not contain actual version, but Runner.res does
@@ -360,6 +414,18 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./rustdesk/
- name: Verify Windows Flutter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\rustdesk\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
if: env.UPLOAD_ARTIFACT == 'true'
@@ -450,9 +516,25 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput
- name: Upload signed Windows Flutter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.exe
if-no-files-found: error
- name: Upload signed Windows Flutter MSI
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-flutter-${{ matrix.job.arch }}-msi
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.msi
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -463,6 +545,7 @@ jobs:
# The fallback for the flutter version, we use Sciter for 32bit Windows.
build-for-windows-sciter:
name: ${{ matrix.job.target }} (${{ matrix.job.os }})
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.os }}
# Temporarily disable this action due to additional test is needed.
# if: false
@@ -595,6 +678,18 @@ jobs:
pip3 install requests argparse
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./Release/
- name: Verify Windows Sciter version
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true'
shell: powershell
run: |
$reportedVersion = (& ".\Release\rustdesk.exe" --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) {
throw "rustdesk --version exited with $LASTEXITCODE"
}
if ($reportedVersion -cne $env:VERSION) {
throw "RustDesk reports version '$reportedVersion', expected '$env:VERSION'"
}
- name: Build self-extracted executable
shell: bash
run: |
@@ -612,9 +707,17 @@ jobs:
run: |
BASE_URL=${{ env.SIGN_BASE_URL }} SECRET_KEY=${{ secrets.SIGN_SECRET_KEY }} python3 res/job.py sign_files ./SignOutput/
- name: Upload signed Windows Sciter EXE
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.SIGN_BASE_URL != '-2'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: windows-sciter-x86-exe
path: ./SignOutput/rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}-sciter.exe
if-no-files-found: error
- name: Publish Release
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
with:
prerelease: true
tag_name: ${{ env.TAG_NAME }}
@@ -755,6 +858,7 @@ jobs:
target: x86_64-apple-darwin,
os: macos-15-intel, #macos-latest or macos-14 use M1 now, https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#:~:text=14%20GB-,macos%2Dlatest%20or%20macos%2D14,-The%20macos%2Dlatestlabel
extra-build-args: "",
extra-cargo-features: "",
arch: x86_64,
vcpkg-triplet: x64-osx,
}
@@ -763,6 +867,7 @@ jobs:
os: macos-14,
# extra-build-args: "--disable-flutter-texture-render", # disable this for mac, because we see a lot of users reporting flickering both on arm and x64, and we can not confirm if texture rendering has better performance if htere is no vram, https://github.com/rustdesk/rustdesk/issues/6296
extra-build-args: "--screencapturekit",
extra-cargo-features: ",screencapturekit",
arch: aarch64,
vcpkg-triplet: arm64-osx,
}
@@ -871,10 +976,10 @@ jobs:
name: bridge-artifact
path: ./
- name: Test cursor sizing
- name: Run the Dart tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
working-directory: flutter
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
run: flutter test --timeout 60s
- name: Setup vcpkg with Github Actions binary cache
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
@@ -916,9 +1021,28 @@ jobs:
sed -i -e "s/platform :osx, '.*'/platform :osx, '${MIN_MACOS_VERSION}'/" flutter/macos/Podfile
sed -i -e "s/osx_minimum_system_version = \"[0-9]*.[0-9]*\"/osx_minimum_system_version = \"${MIN_MACOS_VERSION}\"/" Cargo.toml
sed -i -e "s/MACOSX_DEPLOYMENT_TARGET = [0-9]*.[0-9]*;/MACOSX_DEPLOYMENT_TARGET = ${MIN_MACOS_VERSION};/" flutter/macos/Runner.xcodeproj/project.pbxproj
echo "MACOSX_DEPLOYMENT_TARGET=${MIN_MACOS_VERSION}" >> "$GITHUB_ENV"
fi
./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }}
- name: Test verified updates
if: env.PUBLISH_UPDATE_METADATA == 'true'
run: |
python3 -m unittest res/update/test_macos_update_scripts.py
cargo test --locked --release --lib platform::macos::update_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib verified_dmg_tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
cargo test --locked --release --lib update_metadata::tests --features "flutter,hwcodec,unix-file-copy-paste${{ matrix.job.extra-cargo-features }}"
- name: Run the Rust tests
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
run: |
# The build's own features, so the tests see the code that ships. MACOSX_DEPLOYMENT_TARGET
# comes from the build step's export.
FEATURES=$(./build.py --flutter --hwcodec --unix-file-copy-paste ${{ matrix.job.extra-build-args }} --print-features)
cargo test --locked --release --lib --features "$FEATURES"
# Opt-in, and its macOS tests run nowhere else.
cargo test --locked --release -p clipboard --features unix-file-copy-paste
- name: create unsigned dmg
if: env.UPLOAD_ARTIFACT == 'true'
run: |
@@ -951,6 +1075,13 @@ jobs:
./flutter/build/macos/Build/Products/Release/RustDesk.app \
${{ secrets.MACOS_CODESIGN_IDENTITY }} \
./flutter/macos/Runner/Release.entitlements
if [ "$PUBLISH_UPDATE_METADATA" = "true" ]; then
reported_version="$(./flutter/build/macos/Build/Products/Release/RustDesk.app/Contents/MacOS/RustDesk --version)"
if [ "$reported_version" != "$VERSION" ]; then
echo "::error::RustDesk reports version '$reported_version', expected '$VERSION'"
exit 1
fi
fi
create-dmg --icon "RustDesk.app" 200 190 --hide-extension "RustDesk.app" --window-size 800 400 --app-drop-link 600 185 rustdesk-${{ env.VERSION }}.dmg ./flutter/build/macos/Build/Products/Release/RustDesk.app
codesign --force --options runtime -s ${{ secrets.MACOS_CODESIGN_IDENTITY }} --deep --strict rustdesk-${{ env.VERSION }}.dmg -vvv
# notarize the rustdesk-${{ env.VERSION }}.dmg
@@ -958,13 +1089,26 @@ jobs:
- name: Rename rustdesk
if: env.UPLOAD_ARTIFACT == 'true'
shell: bash
env:
VERSION: ${{ env.VERSION }}
ARCH: ${{ matrix.job.arch }}
run: |
for name in rustdesk*??.dmg; do
mv "$name" "${name%%.dmg}-${{ matrix.job.arch }}.dmg"
done
if [ -f "rustdesk-${VERSION}.dmg" ]; then
mv "rustdesk-${VERSION}.dmg" "rustdesk-${VERSION}-${ARCH}.dmg"
fi
test -f "rustdesk-${VERSION}-${ARCH}.dmg"
- name: Upload signed macOS DMG
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA == 'true' && env.MACOS_P12_BASE64 != null
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: macos-${{ matrix.job.arch }}-dmg
path: ./rustdesk-${{ env.VERSION }}-${{ matrix.job.arch }}.dmg
if-no-files-found: error
- name: Publish DMG package
if: env.UPLOAD_ARTIFACT == 'true'
if: env.UPLOAD_ARTIFACT == 'true' && env.PUBLISH_UPDATE_METADATA != 'true'
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
@@ -972,6 +1116,141 @@ jobs:
files: |
rustdesk*-${{ matrix.job.arch }}.dmg
publish-signed-update-metadata:
needs: [build-for-windows-flutter, build-for-windows-sciter, build-for-macOS]
runs-on: ubuntu-22.04
if: ${{ inputs.upload-artifact && inputs.publish-update-metadata && github.repository == 'rustdesk/rustdesk' }}
concurrency:
group: signed-update-${{ inputs.upload-tag }}
cancel-in-progress: false
permissions:
# Required to inspect and publish signed release assets for the target tag.
contents: write
steps:
- name: Refuse to replace published update metadata
shell: bash
env:
GH_TOKEN: ${{ github.token }}
TAG_NAME: ${{ env.TAG_NAME }}
run: |
set -euo pipefail
releases="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases?per_page=100")"
release_id="$(
jq -r --arg tag "$TAG_NAME" '
[.[][] | select(.tag_name == $tag)] |
if length == 0 then ""
elif length == 1 then .[0].id
else error("multiple releases found for tag")
end
' <<<"$releases"
)"
if [ -z "$release_id" ]; then
exit 0
fi
assets="$(gh api --paginate --slurp "repos/${GITHUB_REPOSITORY}/releases/${release_id}/assets?per_page=100")"
if jq -e 'any(.[][]; .name == "rustdesk-update.json")' <<<"$assets" >/dev/null; then
echo "::error::Signed update metadata is already published for ${TAG_NAME}; use a new release tag for corrected artifacts."
exit 1
fi
- name: Checkout source code
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
persist-credentials: false
- name: Install Python
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- name: Install Python dependencies
run: 'python -m pip install --only-binary=:all: --require-hashes -r res/update/update_metadata_requirements.txt'
- name: Download Windows artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: windows-*
path: ./artifacts/
merge-multiple: true
- name: Download macOS artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: macos-*
path: ./artifacts/
merge-multiple: true
- name: Sign update metadata
env:
RUSTDESK_UPDATE_ED25519_SEED: ${{ secrets.RUSTDESK_UPDATE_ED25519_SEED }}
run: |
python res/update/generate_update_metadata.py sign \
--artifact windows x86_64 exe "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact windows x86_64 msi "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact windows aarch64 exe "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact windows aarch64 msi "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact windows x86 exe "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact macos aarch64 dmg "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact macos x86_64 dmg "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download \
--published-at "$(git log -1 --format=%cI)" \
--metadata-out ./rustdesk-update.json \
--signature-out ./rustdesk-update.json.sig
- name: Verify update metadata
env:
RUSTDESK_UPDATE_ED25519_PUBLIC_KEY: ${{ vars.RUSTDESK_UPDATE_ED25519_PUBLIC_KEY }}
run: |
python res/update/generate_update_metadata.py verify \
--metadata ./rustdesk-update.json \
--signature ./rustdesk-update.json.sig \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.msi" \
--artifact "./artifacts/rustdesk-${VERSION}-x86-sciter.exe" \
--artifact "./artifacts/rustdesk-${VERSION}-aarch64.dmg" \
--artifact "./artifacts/rustdesk-${VERSION}-x86_64.dmg" \
--version "$VERSION" --release-id "$TAG_NAME" \
--package-id rustdesk \
--release-base-url https://github.com/rustdesk/rustdesk/releases/download
- name: Upload signed update artifacts
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: |
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.exe
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.msi
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.msi
./artifacts/rustdesk-${{ env.VERSION }}-x86-sciter.exe
./artifacts/rustdesk-${{ env.VERSION }}-aarch64.dmg
./artifacts/rustdesk-${{ env.VERSION }}-x86_64.dmg
# The release action replaces same-name assets, so keep published sidecars
# until replacements are ready.
- name: Upload signed update metadata signature
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json.sig
# Clients discover the release through metadata, so publish it only after every referenced asset.
- name: Publish signed update metadata
uses: softprops/action-gh-release@de2c0eb89ae2a093876385947365aca7b0e5f844 # v1
with:
prerelease: true
fail_on_unmatched_files: true
tag_name: ${{ env.TAG_NAME }}
files: ./rustdesk-update.json
publish_unsigned:
needs:
- build-for-macOS
@@ -2086,12 +2365,21 @@ jobs:
cargo test --locked --lib --features drm peer_abs_sample_tests
run_drm_tests "rustdesk input_map_tests" \
cargo test --locked --lib --features drm input_map_tests
run_drm_tests "rustdesk drm_pacing_tests" \
cargo test --locked --lib --features drm drm_pacing_tests
run_drm_tests "scrap hotspot_provenance_tests" \
cargo test --locked -p scrap --features drm hotspot_provenance_tests
run_drm_tests "scrap hotspot_guess_tests" \
cargo test --locked -p scrap --features drm hotspot_guess_tests
run_drm_tests "scrap crtc_refresh_tests" \
cargo test --locked -p scrap --features drm crtc_refresh_tests
run_drm_tests "scrap plane_rotation_tests" \
cargo test --locked -p scrap --features drm plane_rotation_tests
run_drm_tests "scrap drmtap_dl::tests" \
cargo test --locked -p scrap --features drm drmtap_dl::tests
# Opt-in like drm, and this container already builds with it.
run_drm_tests "clipboard unix-file-copy-paste" \
cargo test --locked -p clipboard --features unix-file-copy-paste
cargo build --locked --lib --features "$FEATURES" --release
rm -rf target/release/deps target/release/build
rm -rf ~/.cargo
@@ -2172,6 +2460,7 @@ jobs:
build-rustdesk-linux-sciter:
if: ${{ inputs.upload-artifact }}
needs: [validate-update-metadata-keys]
runs-on: ${{ matrix.job.on }}
name: build-rustdesk-linux-sciter ${{ matrix.job.target }}
strategy:
@@ -2552,6 +2841,7 @@ jobs:
build-rustdesk-web:
if: False
needs: [validate-update-metadata-keys]
name: build-rustdesk-web
runs-on: ubuntu-22.04
permissions:
+2 -1
View File
@@ -15,4 +15,5 @@ jobs:
secrets: inherit
with:
upload-artifact: true
upload-tag: ${{ github.ref_name }}
upload-tag: ${{ github.ref_name }}
publish-update-metadata: ${{ github.repository == 'rustdesk/rustdesk' }}
+1 -1
View File
@@ -17,7 +17,7 @@ env:
TAG_NAME: "nightly"
VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite"
VCPKG_COMMIT_ID: "9e593bb18ea69cc5095e012465dcd675a822ed0d"
VERSION: "1.5.0"
VERSION: "1.5.1"
NDK_VERSION: "r26d"
#signing keys env variable checks
ANDROID_SIGNING_KEY: "${{ secrets.ANDROID_SIGNING_KEY }}"
+4
View File
@@ -186,6 +186,10 @@ A refactor added to cover a corner case rarely converges. Each new counter, time
* Do not add test infrastructure (browser runners, golden/screenshot harnesses, new mock layers, test-only hooks in production code) for a bug fix unless the maintainer asks.
* If the test diff is more than twice the fix, cut it back to the tests that pin the reported behavior. A state that needs long setup to reach is usually too rare to fix.
* When the number of tests needed to describe the behavior keeps growing, the implementation is too complex: simplify it instead of adding tests.
* Dart tests go in `flutter/test/*_test.dart`, nowhere else: CI runs `flutter test` over that directory and nothing outside it. It runs on the VM, so a `@TestOn('browser')` suite runs in no CI job.
* Rust unit tests go in a `#[cfg(test)]` module beside the code. CI runs `cargo test --workspace` with the default features on x86_64 Linux, `cargo test --lib` on the root package with the release feature set on macOS and Windows plus `-p clipboard` there, and on Linux the `drm` test modules by name plus the `clipboard` package with `unix-file-copy-paste`. On macOS and Windows, a platform-gated test in another workspace crate runs only if that platform's job names the crate with `-p`. Gate a test module on a feature or `target_os` only when the code under test is gated; a pure helper that only a gated path calls gets `#[cfg(any(feature = "...", test))]`, so its tests run everywhere.
* A test behind a feature that no CI build enables needs a `cargo test` line in `.github/workflows/flutter-build.yml` that names it. In the Linux drm job, wrap it in `run_drm_tests` so a filter that matches nothing fails instead of passing.
* Web core tests are `flutter/web/js/src/*.test.ts`, run by jest in that repository's own CI.
## Reviewing a PR
Generated
+31 -35
View File
@@ -3737,7 +3737,7 @@ dependencies = [
"url",
"users",
"uuid",
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
"webrtc",
"whoami",
"x11 2.21.0",
@@ -3888,8 +3888,8 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "hwcodec"
version = "0.7.1"
source = "git+https://github.com/rustdesk-org/hwcodec#778df1f99597722473b29443bac22ae6c23946fe"
version = "0.8.0"
source = "git+https://github.com/rustdesk-org/hwcodec#ec38ebaf2454269d4c5668a57e3813c6e5541be7"
dependencies = [
"bindgen 0.59.2",
"cc",
@@ -3935,7 +3935,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
]
[[package]]
@@ -4163,16 +4163,6 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
[[package]]
name = "iri-string"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2"
dependencies = [
"memchr",
"serde 1.0.228",
]
[[package]]
name = "is-terminal"
version = "0.4.16"
@@ -6772,7 +6762,7 @@ dependencies = [
[[package]]
name = "rdev"
version = "0.5.0-2"
source = "git+https://github.com/rustdesk-org/rdev#a361d86a8b0245f3618a9efb375c149530a6b599"
source = "git+https://github.com/rustdesk-org/rdev#0904f23ce496e255461a98848b85c11fa5a62eab"
dependencies = [
"cocoa 0.24.1",
"core-foundation 0.9.4",
@@ -6901,11 +6891,10 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.12.24"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"async-compression",
"base64 0.22.1",
"bytes",
"futures-channel",
@@ -6934,7 +6923,6 @@ dependencies = [
"tokio",
"tokio-native-tls",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tower-service",
@@ -6942,7 +6930,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
]
[[package]]
@@ -7053,7 +7041,7 @@ dependencies = [
[[package]]
name = "rust-pulsectl"
version = "0.2.12"
source = "git+https://github.com/rustdesk-org/pulsectl#aa34dde499aa912a3abc5289cc0b547bd07dd6e2"
source = "git+https://github.com/rustdesk-org/pulsectl#d2ec086b5770dce934a66956364d09df8cc9484c"
dependencies = [
"libpulse-binding",
]
@@ -7087,7 +7075,7 @@ dependencies = [
[[package]]
name = "rustdesk"
version = "1.5.0"
version = "1.5.1"
dependencies = [
"android-wakelock",
"android_logger",
@@ -7187,6 +7175,7 @@ dependencies = [
"uuid",
"virtual_display",
"wallpaper",
"wayland-client",
"winapi 0.3.9",
"windows 0.61.1",
"windows-service",
@@ -7196,13 +7185,14 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xkbcommon-dl",
"xxhash-rust",
"zstd",
]
[[package]]
name = "rustdesk-portable-packer"
version = "1.5.0"
version = "1.5.1"
dependencies = [
"brotli",
"dirs 5.0.1",
@@ -7306,11 +7296,12 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
version = "1.11.0"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"web-time",
"zeroize",
]
[[package]]
@@ -7342,9 +7333,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.3"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
@@ -8744,20 +8735,25 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.6"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"async-compression",
"bitflags 2.9.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"iri-string",
"http-body-util",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
@@ -9544,9 +9540,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.3"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05d651ec480de84b762e7be71e6efa7461699c19d9e2c272c8d93455f567786e"
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
dependencies = [
"rustls-pki-types",
]
@@ -9557,14 +9553,14 @@ version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.9",
"webpki-roots 1.0.11",
]
[[package]]
name = "webpki-roots"
version = "1.0.9"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
dependencies = [
"rustls-pki-types",
]
+4 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk"
version = "1.5.0"
version = "1.5.1"
authors = ["rustdesk <info@rustdesk.com>"]
edition = "2021"
build= "build.rs"
@@ -202,6 +202,8 @@ gtk = "0.18"
termios = "0.3"
terminfo = "0.8"
winit = "0.30"
wayland-client = "0.31"
xkbcommon-dl = { version = "0.4", features = ["x11"] }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
@@ -271,7 +273,7 @@ os-version = "0.2"
[dev-dependencies]
hound = "3.5"
docopt = "1.1"
tokio = { version = "1.44", features = ["test-util"] }
tokio = "1.44"
[package.metadata.bundle]
name = "RustDesk"
+1 -1
View File
@@ -4,7 +4,7 @@
<a href="#how-to-build-with-docker">Docker</a> •
<a href="#file-structure">Structure</a> •
<a href="#screenshots">Screenshots</a><br>
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
[<a href="docs/README-UA.md">Українська</a>] | [<a href="docs/README-CS.md">česky</a>] | [<a href="docs/README-ZH.md">中文</a>] | [<a href="docs/README-HU.md">Magyar</a>] | [<a href="docs/README-ES.md">Español</a>] | [<a href="docs/README-FA.md">فارسی</a>] | [<a href="docs/README-FR.md">Français</a>] | [<a href="docs/README-DE.md">Deutsch</a>] | [<a href="docs/README-PL.md">Polski</a>] | [<a href="docs/README-ID.md">Indonesian</a>] | [<a href="docs/README-FI.md">Suomi</a>] | [<a href="docs/README-ML.md">മലയാളം</a>] | [<a href="docs/README-JP.md">日本語</a>] | [<a href="docs/README-NL.md">Nederlands</a>] | [<a href="docs/README-IT.md">Italiano</a>] | [<a href="docs/README-RU.md">Русский</a>] | [<a href="docs/README-PTPT.md">Português (Portugal)</a>] | [<a href="docs/README-PTBR.md">Português (Brasil)</a>] | [<a href="docs/README-EO.md">Esperanto</a>] | [<a href="docs/README-KR.md">한국어</a>] | [<a href="docs/README-AR.md">العربي</a>] | [<a href="docs/README-VN.md">Tiếng Việt</a>] | [<a href="docs/README-DA.md">Dansk</a>] | [<a href="docs/README-GR.md">Ελληνικά</a>] | [<a href="docs/README-TR.md">Türkçe</a>] | [<a href="docs/README-NO.md">Norsk</a>] | [<a href="docs/README-RO.md">Română</a>]<br>
<b>We need your help to translate this README, <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> and <a href="https://github.com/rustdesk/doc.rustdesk.com">RustDesk Doc</a> to your native language</b>
</p>
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.0
version: 1.5.1
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+1 -1
View File
@@ -18,7 +18,7 @@ AppDir:
id: rustdesk
name: rustdesk
icon: rustdesk
version: 1.5.0
version: 1.5.1
exec: usr/share/rustdesk/rustdesk
exec_args: $@
apt:
+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.12.
LIBDRMTAP_REPO_PINNED = 'https://github.com/rustdesk-org/libdrmtap'
LIBDRMTAP_SHA_PINNED = '95d4d74549631aa5c39461300acfd2e106583cc9'
LIBDRMTAP_SHA_PINNED = '5936a7a88b94aa43516a3dd0eb509d2383f31e2d'
LIBDRMTAP_REPO = os.environ.get('DRMTAP_REPO', LIBDRMTAP_REPO_PINNED)
LIBDRMTAP_SHA = os.environ.get('DRMTAP_SHA', LIBDRMTAP_SHA_PINNED)
# Every way of getting a different .so than the pin needs the same explicit opt-in. Otherwise the
+6 -1
View File
@@ -2,7 +2,12 @@
fn build_windows() {
let file = "src/platform/windows.cc";
let file2 = "src/platform/windows_delete_test_cert.cc";
cc::Build::new().file(file).file(file2).compile("windows");
let mut build = cc::Build::new();
if !cfg!(feature = "flutter") {
build.cpp(true).std("c++17").define("RUSTDESK_SCITER", None);
println!("cargo:rerun-if-changed=flutter/windows/runner/service_control.h");
}
build.file(file).file(file2).compile("windows");
println!("cargo:rustc-link-lib=WtsApi32");
println!("cargo:rerun-if-changed={}", file);
println!("cargo:rerun-if-changed={}", file2);
+8 -1
View File
@@ -9,6 +9,10 @@
<b>Kami membutuhkan bantuanmu untuk menterjemahkan file README dan <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">RustDesk UI</a> ke Bahasa Indonesia</b>
</p>
> [!Caution]
> **Peringatan Penyalahgunaan:** <br>
> Pengembang RustDesk tidak membenarkan atau mendukung penggunaan perangkat lunak ini yang tidak etis atau melanggar hukum. Penyalahgunaan, seperti akses tanpa izin, pengambilalihan kendali, atau pelanggaran privasi, sangat dilarang berdasarkan pedoman kami. Para pengembang tidak bertanggung jawab atas penyalahgunaan aplikasi ini.
Mari mengobrol bersama kami: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Fitur%20Lanjutan-blue)](https://rustdesk.com/pricing.html)
@@ -30,6 +34,9 @@ RustDesk mengajak semua orang untuk ikut berkontribusi. Lihat [`docs/CONTRIBUTIN
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Get it on Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Dependensi
@@ -154,7 +161,7 @@ Harap pastikan bahwa kamu menjalankan perintah ini dari repositori root RustDesk
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: start a peer connection
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Komunikasi dengan [rustdesk-server](https://github.com/rustdesk/rustdesk-server), menunggu untuk remote direct (TCP hole punching) atau relayed connection
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: kode khusus platform
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: kode Flutter untuk platform desktop dan perangkat seluler
## Snapshots
![image](https://user-images.githubusercontent.com/71636191/113112362-ae4deb80-923b-11eb-957d-ff88daad4f06.png)
+179
View File
@@ -0,0 +1,179 @@
<p align="center">
<img src="../res/logo-header.svg" alt="RustDesk - O seu ambiente de trabalho remoto"><br>
<a href="#compilar">Compilar</a> •
<a href="#como-compilar-com-o-docker">Docker</a> •
<a href="#estrutura-de-ficheiros">Estrutura</a> •
<a href="#capturas-de-ecrã">Capturas de Ecrã</a><br>
[<a href="../README.md">Inglês</a>] | [<a href="README-UA.md">Ucraniano</a>] | [<a href="README-CS.md">Checo</a>] | [<a href="README-ZH.md">Chinês</a>] | [<a href="README-HU.md">Húngaro</a>] | [<a href="README-ES.md">Espanhol</a>] | [<a href="README-FA.md">Persa</a>] | [<a href="README-FR.md">Francês</a>] | [<a href="README-DE.md">Alemão</a>] | [<a href="README-PL.md">Polaco</a>] | [<a href="README-ID.md">Indonésio</a>] | [<a href="README-FI.md">Finlandês</a>] | [<a href="README-ML.md">Malaiala</a>] | [<a href="README-JP.md">Japonês</a>] | [<a href="README-NL.md">Holandês</a>] | [<a href="README-IT.md">Italiano</a>] | [<a href="README-RU.md">Russo</a>] | [<a href="README-EO.md">Esperanto</a>] | [<a href="README-KR.md">Coreano</a>] | [<a href="README-AR.md">Árabe</a>] | [<a href="README-VN.md">Vietnamita</a>] | [<a href="README-DA.md">Dinamarquês</a>] | [<a href="README-GR.md">Grego</a>] | [<a href="README-TR.md">Turco</a>] | [<a href="README-NO.md">Norueguês</a>] | [<a href="README-RO.md">Romeno</a>]<br>
<b>Precisamos da sua ajuda para traduzir este README, a <a href="https://github.com/rustdesk/rustdesk/tree/master/src/lang">Interface do RustDesk</a> e a <a href="https://github.com/rustdesk/doc.rustdesk.com">Documentação do RustDesk</a> para o seu idioma nativo</b>
</p>
> [!Caution]
> **Aviso de Isenção de Responsabilidade por Uso Indevido:** <br>
> Os programadores do RustDesk não toleram ou apoiam qualquer uso antiético ou ilegal deste software. O uso indevido, como acesso não autorizado, controlo ou invasão de privacidade, é estritamente contrário às nossas diretrizes. Os autores não se responsabilizam por qualquer uso indevido da aplicação.
Converse connosco: [Discord](https://discord.gg/nDceKgxnkV) | [Twitter](https://twitter.com/rustdesk) | [Reddit](https://www.reddit.com/r/rustdesk) | [YouTube](https://www.youtube.com/@rustdesk)
[![RustDesk Server Pro](https://img.shields.io/badge/RustDesk%20Server%20Pro-Advanced%20Features-blue)](https://rustdesk.com/pricing.html)
Mais uma solução de ambiente de trabalho remoto, escrita em Rust. Funciona imediatamente, sem necessidade de configuração. Tem controlo total dos seus dados, sem preocupações com a segurança. Pode usar o nosso servidor de ligação/retransmissão (rendezvous/relay), [configurar o seu próprio](https://rustdesk.com/server) ou [escrever o seu próprio servidor de ligação/retransmissão](https://github.com/rustdesk/rustdesk-server-demo).
![image](https://user-images.githubusercontent.com/71636191/171661982-430285f0-2e12-4b1d-9957-4a58e375304d.png)
O RustDesk agradece as contribuições de todos. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para obter ajuda para começar.
[**Perguntas Frequentes (FAQ)**](https://github.com/rustdesk/rustdesk/wiki/FAQ)
[**DOWNLOAD DOS BINÁRIOS**](https://github.com/rustdesk/rustdesk/releases)
[**VERSÕES NIGHTLY (EM DESENVOLVIMENTO)**](https://github.com/rustdesk/rustdesk/releases/tag/nightly)
[<img src="https://f-droid.org/badge/get-it-on.png"
alt="Transfira no F-Droid"
height="80">](https://f-droid.org/en/packages/com.carriez.flutter_hbb)
[<img src="https://flathub.org/api/badge?svg&locale=en"
alt="Transfira no Flathub"
height="80">](https://flathub.org/apps/com.rustdesk.RustDesk)
## Dependências
As versões para ambiente de trabalho usam Flutter ou Sciter (descontinuado) para a interface gráfica (GUI). Este tutorial é apenas para o Sciter, por ser mais fácil e acessível para começar. Consulte o nosso [CI](https://github.com/rustdesk/rustdesk/blob/master/.github/workflows/flutter-build.yml) para instruções de compilação da versão Flutter.
Por favor transfira a biblioteca dinâmica do Sciter por conta própria.
[Windows](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.win/x64/sciter.dll) |
[Linux](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so) |
[macOS](https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.osx/libsciter.dylib)
## Passos básicos para compilar
- Prepare o seu ambiente de desenvolvimento Rust e o ambiente de compilação C++
- Instale o [vcpkg](https://github.com/microsoft/vcpkg) e configure a variável de ambiente `VCPKG_ROOT` corretamente
- Windows: `vcpkg install libvpx:x64-windows-static libyuv:x64-windows-static opus:x64-windows-static aom:x64-windows-static`
- Linux/macOS: `vcpkg install libvpx libyuv opus aom`
- Execute `cargo run`
## [Compilar](https://rustdesk.com/docs/en/dev/build/)
## Como Compilar no Linux
### Ubuntu 18 (Debian 10)
```sh
sudo apt install -y zip g++ gcc git curl wget nasm yasm libgtk-3-dev clang libxcb-randr0-dev libxdo-dev libxfixes-dev libxcb-shape0-dev libxcb-xfixes0-dev libasound2-dev libpulse-dev cmake make libclang-dev ninja-build libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
```
### openSUSE Tumbleweed
```sh
sudo zypper install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libXfixes-devel cmake alsa-lib-devel gstreamer-devel gstreamer-plugins-base-devel xdotool-devel
```
### Fedora 28 (CentOS 8)
```sh
sudo yum -y install gcc-c++ git curl wget nasm yasm gcc gtk3-devel clang libxcb-devel libxdo-devel libXfixes-devel pulseaudio-libs-devel cmake alsa-lib-devel gstreamer1-devel gstreamer1-plugins-base-devel
```
### Arch (Manjaro)
```sh
sudo pacman -Syu --needed unzip git cmake gcc curl wget yasm nasm zip make pkg-config clang gtk3 xdotool libxcb libxfixes alsa-lib pipewire
```
### Instalar o vcpkg
```sh
git clone https://github.com/microsoft/vcpkg
cd vcpkg
git checkout 2023.04.15
cd ..
vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$HOME/vcpkg
vcpkg/vcpkg install libvpx libyuv opus aom
```
### Corrigir o libvpx (Para Fedora)
```sh
cd vcpkg/buildtrees/libvpx/src
cd *
./configure
sed -i 's/CFLAGS+=-I/CFLAGS+=-fPIC -I/g' Makefile
sed -i 's/CXXFLAGS+=-I/CXXFLAGS+=-fPIC -I/g' Makefile
make
cp libvpx.a $HOME/vcpkg/installed/x64-linux/lib/
cd
```
### Compilar
```sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
git clone --recurse-submodules https://github.com/rustdesk/rustdesk
cd rustdesk
mkdir -p target/debug
wget https://raw.githubusercontent.com/c-smile/sciter-sdk/master/bin.lnx/x64/libsciter-gtk.so
mv libsciter-gtk.so target/debug
VCPKG_ROOT=$HOME/vcpkg cargo run
```
## Como compilar com o Docker
Comece por clonar o repositório e construir o contentor Docker:
```sh
git clone https://github.com/rustdesk/rustdesk
cd rustdesk
git submodule update --init --recursive
docker build -t "rustdesk-builder" .
```
Depois, cada vez que precisar de compilar a aplicação, execute o seguinte comando:
```sh
docker run --rm -it -v $PWD:/home/user/rustdesk -v rustdesk-git-cache:/home/user/.cargo/git -v rustdesk-registry-cache:/home/user/.cargo/registry -e PUID="$(id -u)" -e PGID="$(id -g)" rustdesk-builder
```
Note que a primeira compilação pode demorar mais até que as dependências sejam armazenadas em cache, as compilações subsequentes serão mais rápidas. Além disso, se precisar especificar argumentos diferentes para o comando de compilação, poderá fazê-lo no final do comando na posição `<ARGUMENTOS-OPCIONAIS>`. Por exemplo, se quiser compilar uma versão de lançamento (release) otimizada, executaria o comando acima seguido de `--release`. O executável resultante estará disponível na pasta `target` do seu sistema e pode ser executado com:
```sh
target/debug/rustdesk
```
Ou, se estiver a correr o executável de lançamento:
```sh
target/release/rustdesk
```
Certifique-se de que executa estes comandos a partir da raiz do repositório do RustDesk, caso contrário a aplicação poderá não encontrar os recursos necessários. Note também que outros subcomandos do cargo, como `install` ou `run`, não são suportados atualmente por este método, pois instalariam ou executariam o programa dentro do contentor em vez de o fazerem no host.
## Estrutura de Ficheiros
- **[libs/hbb_common](https://github.com/rustdesk/rustdesk/tree/master/libs/hbb_common)**: codec de vídeo, configuração, wrapper TCP/UDP e algumas outras funções utilitárias partilhadas com o servidor
- **[libs/base](https://github.com/rustdesk/rustdesk/tree/master/libs/base)**: protobuf, funções fs para transferência de ficheiros, código relacionado com o teclado e com a plataforma utilizado exclusivamente por esta aplicação
- **[libs/scrap](https://github.com/rustdesk/rustdesk/tree/master/libs/scrap)**: captura de ecrã
- **[libs/enigo](https://github.com/rustdesk/rustdesk/tree/master/libs/enigo)**: controlo de teclado/rato específico da plataforma.
- **[libs/clipboard](https://github.com/rustdesk/rustdesk/tree/master/libs/clipboard)**: implementação de copiar e colar ficheiros para Windows, Linux e macOS.
- **[src/ui](https://github.com/rustdesk/rustdesk/tree/master/src/ui)**: interface Sciter obsoleta (descontinuada).
- **[src/server](https://github.com/rustdesk/rustdesk/tree/master/src/server)**: serviços de áudio, área de transferência, entrada e vídeo, e ligações de rede
- **[src/client.rs](https://github.com/rustdesk/rustdesk/tree/master/src/client.rs)**: inicia uma ligação entre pares
- **[src/rendezvous_mediator.rs](https://github.com/rustdesk/rustdesk/tree/master/src/rendezvous_mediator.rs)**: Comunica com o [rustdesk-server](https://github.com/rustdesk/rustdesk-server), aguarda por uma ligação direta remota (TCP hole punching) ou uma ligação retransmitida
- **[src/platform](https://github.com/rustdesk/rustdesk/tree/master/src/platform)**: código específico da plataforma
- **[flutter](https://github.com/rustdesk/rustdesk/tree/master/flutter)**: código Flutter para ambiente de trabalho e dispositivos móveis
## Capturas de Ecrã
![Gestor de Ligações](https://github.com/rustdesk/rustdesk/assets/28412477/db82d4e7-c4bc-4823-8e6f-6af7eadf7651)
![Ligado a um PC Windows](https://github.com/rustdesk/rustdesk/assets/28412477/9baa91e9-3362-4d06-aa1a-7518edcbd7ea)
![Transferência de Ficheiros](https://github.com/rustdesk/rustdesk/assets/28412477/39511ad3-aa9a-4f8c-8947-1cce286a46ad)
![Túnel TCP](https://github.com/rustdesk/rustdesk/assets/28412477/78e8708f-e87e-4570-8373-1360033ea6c5)
@@ -50,6 +50,15 @@ const val WHEEL_BUTTON_UP = 34
const val WHEEL_DOWN = 523331
const val WHEEL_UP = 963
// src/common.rs MOUSE_TYPE_WHEEL: the controller sends a wheel tick as a
// MouseEvent with these type bits and the scroll delta in y (y < 0 = down).
const val MOUSE_TYPE_WHEEL = 3
// Wheel-tick travel for MOUSE_TYPE_WHEEL events. Three quarters of the legacy
// WHEEL_STEP; tuned on real devices during review (the full 120px felt too
// far per tick).
const val MOUSE_WHEEL_STEP = 90
const val TOUCH_SCALE_START = 1
const val TOUCH_SCALE = 2
const val TOUCH_SCALE_END = 3
@@ -102,6 +111,12 @@ class InputService : AccessibilityService() {
private val volumeController: VolumeController by lazy { VolumeController(applicationContext.getSystemService(AUDIO_SERVICE) as AudioManager) }
/**
* Handles a remote mouse event on the gesture path. [mask] is the
* button/phase mask of the mouse protocol ([MOUSE_TYPE_WHEEL] ticks carry
* the scroll delta in [_y] instead of a position), x/y the screen-space
* position. Requires API 24 for the gesture APIs.
*/
@RequiresApi(Build.VERSION_CODES.N)
fun onMouseInput(mask: Int, _x: Int, _y: Int) {
val x = max(0, _x)
@@ -184,6 +199,38 @@ class InputService : AccessibilityService() {
return
}
// The controller sends a wheel tick as a MouseEvent with the type bits
// MOUSE_TYPE_WHEEL (src/common.rs) and the scroll delta in _y
// (y < 0 = wheel down); the WHEEL_DOWN/WHEEL_UP masks below are legacy
// values that current controllers never send. Gated to API 24+ like
// the rest of the gesture path - below that, legacy devices take the
// Shizuku backend or a no-op, not this class.
if (mask == MOUSE_TYPE_WHEEL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// A horizontal tick (the controller sends y = 0 when the
// horizontal delta dominates) or a delta truncated to zero is not
// a vertical swipe.
if (_y == 0) {
return
}
if (mouseY < MOUSE_WHEEL_STEP) {
return
}
val path = Path()
path.moveTo(mouseX.toFloat(), mouseY.toFloat())
val deltaY = if (_y < 0) -MOUSE_WHEEL_STEP else MOUSE_WHEEL_STEP
path.lineTo(mouseX.toFloat(), (mouseY + deltaY).toFloat())
val stroke = GestureDescription.StrokeDescription(
path,
0,
WHEEL_DURATION
)
val builder = GestureDescription.Builder()
builder.addStroke(stroke)
wheelActionsQueue.offer(builder.build())
consumeWheelActions()
return
}
if (mask == WHEEL_DOWN) {
if (mouseY < WHEEL_STEP) {
return
+66 -57
View File
@@ -154,7 +154,7 @@ prebuild)
.github/workflows/bridge.yml)"
FLUTTER_BRIDGE_VERSION="$(yq -r \
.env.FLUTTER_VERSION \
'.jobs.generate_bridge.strategy.matrix.job[] | select(.["artifact-name"] == "bridge-artifact") | .["flutter-version"]' \
.github/workflows/bridge.yml)"
FLUTTER_RUST_BRIDGE_VERSION="$(yq -r \
@@ -306,67 +306,69 @@ prebuild)
git apply res/fdroid/patches/*.patch
# If Flutter version used to generate bridge files differs from Flutter
# version used to compile Rustdesk library, generate bridge using the
# `FLUTTER_BRIDGE_VERSION` an restore the pubspec later
# Generate bridge files using `FLUTTER_BRIDGE_VERSION`, which may differ
# from the Flutter version used to compile RustDesk library, and restore
# the pubspec later
if [ "${FLUTTER_VERSION}" != "${FLUTTER_BRIDGE_VERSION}" ]; then
# Find first libclang.so and set BRIDGE_LLVM_PATH
# Find first libclang.so and set BRIDGE_LLVM_PATH
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
BRIDGE_LLVM_PATH="$(find /usr/lib/ -name libclang.so | head -n1)"
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
prepare_flutter "${FLUTTER_BRIDGE_VERSION}" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
if [ -z "${BRIDGE_LLVM_PATH}" ]; then
echo 'ERROR: Can not find libclang.so for bridge generator!' >&2
exit 1
fi
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
BRIDGE_LLVM_PATH="$(dirname "${BRIDGE_LLVM_PATH}")"
# Install Flutter bridge version
# Unbraced on purpose: F-Droid recipes rewrite the braced form with sed to
# pin a version, but the bridge generator only works with the Flutter
# version bridge.yml uses
prepare_flutter "$FLUTTER_BRIDGE_VERSION" "${HOME}/flutter"
# Save changes
git add .
# Edit pubspec to make flutter bridge version work
sed \
-i \
-e 's/extended_text: 14.0.0/extended_text: 13.0.0/g' \
flutter/pubspec.yaml
# Download Flutter dependencies
pushd flutter
flutter clean
flutter packages pub get --enforce-lockfile
popd # flutter
# Generate FFI bindings
flutter_rust_bridge_codegen \
--rust-input ./src/flutter_ffi.rs \
--dart-output ./flutter/lib/generated_bridge.dart \
--llvm-path "${BRIDGE_LLVM_PATH}"
# Add bridge files to save-list
git add -f ./flutter/lib/generated_bridge.* ./src/bridge_generated.*
# Restore everything
git checkout '*'
git clean -dffx
git reset
unset BRIDGE_LLVM_PATH
# Install Flutter version for RustDesk library build
prepare_flutter "${FLUTTER_VERSION}" "${HOME}/flutter"
@@ -379,6 +381,13 @@ prebuild)
flutter/android/build.gradle \
flutter/android/app/build.gradle
# Gradle 8 / AGP 8 thrash in the default 1 GiB heap; raise it as CI does
sed \
-i \
-e 's/org.gradle.jvmargs=-Xmx1024M/org.gradle.jvmargs=-Xmx2g/g' \
flutter/android/gradle.properties
# `firebase_analytics` is not in these files now, but we still keep the following lines.
sed \
+7
View File
@@ -1,5 +1,6 @@
import UIKit
import Flutter
import AVFoundation
@main
@objc class AppDelegate: FlutterAppDelegate {
@@ -8,6 +9,12 @@ import Flutter
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
do {
// Mix remote audio with other apps while still respecting silent mode.
try AVAudioSession.sharedInstance().setCategory(.ambient)
} catch {
NSLog("Failed to configure audio mixing: %@", error.localizedDescription)
}
dummyMethodToEnforceBundling();
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
@@ -0,0 +1,72 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/models/platform_model.dart';
String _resolveApiServer({required String api, required String custom}) {
final key = 'resolve-api-server:${jsonEncode([api, custom])}';
final response = jsonDecode(bind.mainGetCommonSync(key: key));
if (response['error'] != null) {
throw FormatException('Failed to resolve API server: ${response['error']}');
}
return response['url'] as String;
}
bool shouldWarnApiServer(String? apiServer) {
final uri = Uri.tryParse(apiServer?.trim() ?? '');
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
return false;
}
return !const {'localhost', '127.0.0.1', '::1'}.contains(uri.host);
}
class ApiServerWarning extends StatelessWidget {
final TextEditingController controller;
final TextEditingController idController;
final String message;
final String emptyMessage;
final String Function({required String api, required String custom})
resolveApiServer;
const ApiServerWarning({
super.key,
required this.controller,
required this.idController,
required this.message,
required this.emptyMessage,
this.resolveApiServer = _resolveApiServer,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: Listenable.merge([controller, idController]),
builder: (context, child) {
final apiServer = controller.text;
final idServer = idController.text;
final String effectiveApiServer;
try {
effectiveApiServer =
resolveApiServer(api: apiServer.trim(), custom: idServer.trim());
} catch (error, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: error,
stack: stack,
context: ErrorDescription('while resolving the API server warning'),
));
return const SizedBox.shrink();
}
if (!shouldWarnApiServer(effectiveApiServer)) {
return const SizedBox.shrink();
}
return Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
controller.text.trim().isEmpty ? emptyMessage : message,
style: TextStyle(color: Colors.orange.shade700),
),
);
},
);
}
}
@@ -271,11 +271,6 @@ class AllPeersLoader {
void updateOnlineStateForTesting(Map<String, dynamic> evt) {
_updateOnlineState(evt);
}
@visibleForTesting
bool applyLastOnlineStateForTesting(List<Peer> peers) {
return _applyLastOnlineState(peers);
}
}
class AutocompletePeerTile extends StatefulWidget {
@@ -21,6 +21,7 @@ import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:pull_down_button/pull_down_button.dart';
import 'package:url_launcher/url_launcher_string.dart';
import '../../common.dart';
import '../../models/platform_model.dart';
@@ -549,6 +550,28 @@ class _PeerTabPageState extends State<PeerTabPage>
});
}
Widget _openWebConsole() {
return _hoverAction(
context: context,
toolTip: translate('ab_web_console_tip'),
child: Icon(
Icons.open_in_new,
size: 18,
),
onTap: () async {
final url = await bind.mainGetApiServer();
if (await canLaunchUrlString(url)) {
launchUrlString(url);
}
});
}
bool _showWebConsole(PeerTabModel model) =>
model.currentTab == PeerTabIndex.ab.index &&
gFFI.userModel.isLogin &&
!gFFI.abModel.legacyMode.value &&
gFFI.abModel.current.canWrite();
List<Widget> _landscapeRightActions(BuildContext context) {
final model = Provider.of<PeerTabModel>(context);
return [
@@ -566,6 +589,10 @@ class _PeerTabPageState extends State<PeerTabPage>
offstage: model.currentTab == PeerTabIndex.recent.index,
child: PeerSortDropdown(),
),
Offstage(
offstage: !_showWebConsole(model),
child: _openWebConsole(),
),
Offstage(
offstage: model.currentTab != PeerTabIndex.ab.index,
child: _toggleTags(),
@@ -630,6 +657,7 @@ class _PeerTabPageState extends State<PeerTabPage>
final List<Widget> dynamicActions = [
if (model.currentTabCachedPeers.isNotEmpty) _createMultiSelection(),
if (model.currentTab != PeerTabIndex.recent.index) PeerSortDropdown(),
if (_showWebConsole(model)) _openWebConsole(),
if (model.currentTab == PeerTabIndex.ab.index) _toggleTags()
];
final rightWidth = availableWidth -
@@ -497,7 +497,12 @@ class _FileManagerViewState extends State<FileManagerView> {
},
onExit: (evt) =>
widget._mouseFocusScope.value = MouseFocusScope.none,
child: _buildFileList(context, _fileListScrollController),
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: _onFileListKeyEvent,
child: _buildFileList(context, _fileListScrollController),
),
))
],
),
@@ -1135,6 +1140,7 @@ class _FileManagerViewState extends State<FileManagerView> {
: "${entry.lastModified().toString().replaceAll(".000", "")} ";
var secondaryPosition = RelativeRect.fromLTRB(0, 0, 0, 0);
onTap() {
_keyboardNode.requestFocus();
final items = selectedItems;
// handle double click
if (_checkDoubleClick(entry)) {
@@ -1363,6 +1369,102 @@ class _FileManagerViewState extends State<FileManagerView> {
debugPrint("focused on ${searchResult.first.name}");
}
KeyEventResult _onFileListKeyEvent(FocusNode node, KeyEvent event) {
// A focused child such as a sort header keeps its default keys, e.g.
// Enter to sort.
if (!_keyboardNode.hasPrimaryFocus) return KeyEventResult.ignored;
for (final binding in _fileListKeyBindings().entries) {
if (binding.key.accepts(event, HardwareKeyboard.instance)) {
binding.value();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
Map<ShortcutActivator, VoidCallback> _fileListKeyBindings() {
int all() => controller.directory.value.entries.length;
return {
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSelectionByKey(-1, false),
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSelectionByKey(1, false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): () =>
_moveSelectionByKey(-1, true),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): () =>
_moveSelectionByKey(1, true),
// Unhandled, they would move keyboard focus to the other pane.
const SingleActivator(LogicalKeyboardKey.arrowLeft): () {},
const SingleActivator(LogicalKeyboardKey.arrowRight): () {},
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
_moveSelectionByKey(_pageDelta(false), false),
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
_moveSelectionByKey(_pageDelta(true), false),
const SingleActivator(LogicalKeyboardKey.home): () =>
_moveSelectionByKey(-all(), false),
const SingleActivator(LogicalKeyboardKey.end): () =>
_moveSelectionByKey(all(), false),
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): () =>
_moveSelectionByKey(_pageDelta(false), true),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): () =>
_moveSelectionByKey(_pageDelta(true), true),
const SingleActivator(LogicalKeyboardKey.home, shift: true): () =>
_moveSelectionByKey(-all(), true),
const SingleActivator(LogicalKeyboardKey.end, shift: true): () =>
_moveSelectionByKey(all(), true),
const SingleActivator(LogicalKeyboardKey.enter): _openSelectedDirectory,
const SingleActivator(LogicalKeyboardKey.numpadEnter):
_openSelectedDirectory,
};
}
void _openSelectedDirectory() {
final items = selectedItems.items;
if (items.length != 1 || items.first.isFile) return;
controller.openDirectory(items.first.path);
selectedItems.clear();
}
List<Entry> _filteredEntries() {
final entries = controller.directory.value.entries;
return _searchText.isNotEmpty
? entries.where((element) {
return element.name.contains(_searchText.value);
}).toList(growable: false)
: entries;
}
int _pageDelta(bool down) {
final entries = _filteredEntries();
final items = selectedItems.items;
final index = items.isEmpty ? -1 : entries.indexOf(items.last);
final position = _fileListScrollController.position;
final first = (position.pixels / kDesktopFileTransferRowHeight).ceil();
final last = ((position.pixels + position.viewportDimension) /
kDesktopFileTransferRowHeight)
.floor() -
1;
return pageDelta(
index >= 0 ? index : (down ? -1 : entries.length), first, last, down);
}
void _moveSelectionByKey(int delta, bool extend) {
final filteredEntries = _filteredEntries();
final selection =
navigateSelection(filteredEntries, selectedItems.items, delta, extend);
if (selection.isEmpty) return;
selectedItems.items.assignAll(selection.where((e) => !e.isDrive));
final position = _fileListScrollController.position;
final top =
filteredEntries.indexOf(selection.last) * kDesktopFileTransferRowHeight;
final bottom = top + kDesktopFileTransferRowHeight;
if (top < position.pixels) {
_fileListScrollController.jumpTo(top);
} else if (bottom > position.pixels + position.viewportDimension) {
_fileListScrollController.jumpTo(bottom - position.viewportDimension);
}
}
void _onSelectedChanged(SelectedItems selectedItems, List<Entry> entries,
Entry entry, bool isLocal) {
final isCtrlDown = RawKeyboard.instance.keysPressed
@@ -1717,6 +1819,36 @@ class _FileManagerViewState extends State<FileManagerView> {
// }
}
/// Selection after a navigation key moves it by [delta] rows. A shift range is
/// returned ordered from its anchor to the moved end, so the first and last
/// items of [selected] stand for those two ends on the next press without
/// separate state.
@visibleForTesting
List<Entry> navigateSelection(
List<Entry> entries, List<Entry> selected, int delta, bool extend) {
if (entries.isEmpty) return [];
final current = selected.isEmpty ? -1 : entries.indexOf(selected.last);
// With nothing selected, moving down starts above the first row and moving
// up below the last one, as the Sciter grid did.
final lead = current >= 0 ? current : (delta > 0 ? -1 : entries.length);
final next = (lead + delta).clamp(0, entries.length - 1);
if (!extend || current < 0) return [entries[next]];
final first = entries.indexOf(selected.first);
final anchor = first < 0 ? current : first;
final step = next < anchor ? -1 : 1;
return [for (var i = anchor; i != next + step; i += step) entries[i]];
}
/// Rows a PageUp/PageDown press moves from [lead] while rows [first]..[last]
/// are fully visible: to that edge first, then a page further, as list views
/// do.
@visibleForTesting
int pageDelta(int lead, int first, int last, bool down) {
final page = max(1, last - first);
if (down) return lead < last ? last - lead : page;
return lead > first ? first - lead : -page;
}
Widget buildWindowsThisPC(BuildContext context, [TextStyle? textStyle]) {
final color = Theme.of(context).iconTheme.color?.withOpacity(0.7);
return Row(children: [
+30 -2
View File
@@ -62,12 +62,15 @@ class _InstallPageBody extends StatefulWidget {
class _InstallPageBodyState extends State<_InstallPageBody>
with WindowListener {
static const _printerStatusTimeout = Duration(seconds: 5);
late final TextEditingController controller;
final RxBool startmenu = true.obs;
final RxBool desktopicon = true.obs;
final RxBool printer = false.obs;
final RxBool showProgress = false.obs;
final RxBool btnEnabled = true.obs;
final RxBool cancelEnabled = true.obs;
// todo move to theme.
final buttonStyle = OutlinedButton.styleFrom(
@@ -83,10 +86,33 @@ class _InstallPageBodyState extends State<_InstallPageBody>
printer.value = installOptions['PRINTER'] == '1';
}
Future<void> _loadPrinterStatus() async {
btnEnabled.value = false;
showProgress.value = true;
try {
final status = await bind
.mainGetCommon(key: 'is-printer-installed')
.timeout(_printerStatusTimeout);
printer.value = status == 'true';
if (status != 'true' && status != 'false') {
debugPrint('Failed to check printer installation status: $status');
}
} catch (e) {
printer.value = false;
debugPrint('Failed to check printer installation status: $e');
} finally {
showProgress.value = false;
btnEnabled.value = true;
}
}
@override
void initState() {
windowManager.addListener(this);
super.initState();
if (printer.value) {
_loadPrinterStatus();
}
}
@override
@@ -217,8 +243,9 @@ class _InstallPageBodyState extends State<_InstallPageBody>
() => OutlinedButton.icon(
icon: Icon(Icons.close_rounded, size: 16),
label: Text(translate('Cancel')),
onPressed:
btnEnabled.value ? () => windowManager.close() : null,
onPressed: cancelEnabled.value
? () => windowManager.close()
: null,
style: buttonStyle,
).marginOnly(right: 10),
),
@@ -253,6 +280,7 @@ class _InstallPageBodyState extends State<_InstallPageBody>
void install() {
do_install() {
btnEnabled.value = false;
cancelEnabled.value = false;
showProgress.value = true;
String args = '';
if (startmenu.value) args += ' startmenu';
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ListSearchActionListener extends StatelessWidget {
final FocusNode node;
@@ -22,7 +23,7 @@ class ListSearchActionListener extends StatelessWidget {
autofocus: true,
onKeyEvent: (kv) {
final ch = kv.character;
if (ch == null) {
if (ch == null || LogicalKeyboardKey.isControlCharacter(ch)) {
return;
}
final action = buffer.input(ch);
@@ -418,6 +418,13 @@ class _DesktopTabState extends State<DesktopTab>
}
}
// On Linux, GTK destroys the window on a close request unless prevent-close
// is on. It is off for the cm and install windows, and onActiveWindowChanged()
// turns it off to quit, so the window can no longer be saved or hidden.
// https://github.com/rustdesk/rustdesk/issues/16512
Future<bool> _isLinuxWindowClosed() async =>
isLinux && isMainWindow && !await windowManager.isPreventClose();
@override
void onWindowMoved() {
_saveFrame();
@@ -465,6 +472,8 @@ class _DesktopTabState extends State<DesktopTab>
});
}
if (await _isLinuxWindowClosed()) return;
await _saveFrame(flush: true);
// hide window on close
@@ -472,6 +481,7 @@ class _DesktopTabState extends State<DesktopTab>
if (rustDeskWinManager.getActiveWindows().contains(kMainWindowId)) {
await rustDeskWinManager.unregisterActiveWindow(kMainWindowId);
}
if (await _isLinuxWindowClosed()) return;
// macOS specific workaround, the window is not hiding when in fullscreen.
if (isMacOS && await windowManager.isFullScreen()) {
await windowManager.setFullScreen(false);
@@ -7,36 +7,49 @@ import 'package:flutter_hbb/models/platform_model.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
final _isExtracting = false.obs;
const _eventKeyUpdateMe = 'update-me';
void handleUpdate(String releasePageUrl) {
_isExtracting.value = false;
String downloadUrl = releasePageUrl.replaceAll('tag', 'download');
String version = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
final String downloadFile =
bind.mainGetCommonSync(key: 'download-file-$version');
if (downloadFile.startsWith('error:')) {
final error = downloadFile.replaceFirst('error:', '');
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
Future<void> _handleUpdateMe(
String releasePageUrl, Map<String, dynamic> evt) async {
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
if (evt.containsKey('error')) {
_showUpdateError(releasePageUrl, evt['error'] as String);
}
}
Future<void> handleUpdate(String releasePageUrl) async {
final dialogClosed = _showVerifyingUpdate();
final String? downloadUrl;
try {
downloadUrl = await waitForUpdateVerification(
bind.mainGetCommon(key: 'verified-download-url-$releasePageUrl'),
dialogClosed,
);
} catch (error) {
_showUpdateError(releasePageUrl, error.toString());
return;
}
if (downloadUrl == null) {
return;
}
final verifiedDownloadUrl = downloadUrl;
if (downloadUrl.startsWith('error:')) {
_showUpdateError(releasePageUrl, downloadUrl.replaceFirst('error:', ''));
return;
}
downloadUrl = '$downloadUrl/$downloadFile';
SimpleWrapper downloadId = SimpleWrapper('');
SimpleWrapper<VoidCallback> onCanceled = SimpleWrapper(() {});
gFFI.dialogManager.dismissAll();
gFFI.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
title: Obx(() => Text(translate(_isExtracting.isTrue
? 'Preparing for installation ...'
: 'Downloading {$appName}'))),
content:
UpdateProgress(releasePageUrl, downloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
title: Text(translate('Downloading {$appName}')),
content: UpdateProgress(
releasePageUrl, verifiedDownloadUrl, downloadId, onCanceled)
.marginSymmetric(horizontal: 8)
.paddingOnly(top: 12),
actions: [
if (_isExtracting.isFalse) dialogButton(translate('Cancel'), onPressed: () async {
dialogButton('Cancel', onPressed: () async {
onCanceled.value();
await bind.mainSetCommon(
key: 'cancel-downloader', value: downloadId.value);
@@ -56,6 +69,40 @@ void handleUpdate(String releasePageUrl) {
});
}
Future<T?> waitForUpdateVerification<T extends Object>(
Future<T> verification,
Future<void> dialogClosed,
) async {
final dialogClosedMarker = Object();
final result = await Future.any<Object>([
verification.then<Object>((value) => value),
dialogClosed.then<Object>((_) => dialogClosedMarker),
]);
return identical(result, dialogClosedMarker) ? null : result as T;
}
Future<void> _showVerifyingUpdate() async {
gFFI.dialogManager.dismissAll();
await gFFI.dialogManager.show<void>(
(setState, close, context) => CustomAlertDialog(
title: Text(translate('Preparing for installation ...')),
content: const LinearProgressIndicator(),
actions: [
dialogButton('Close', onPressed: close, isOutline: true),
],
onCancel: close,
),
tag: 'verifying-update',
);
}
void _showUpdateError(String releasePageUrl, String error) {
debugPrint('Update error: $error');
gFFI.dialogManager.dismissAll();
msgBox(gFFI.sessionId, 'custom-nocancel-nook-hasclose', 'Error', error,
releasePageUrl, gFFI.dialogManager);
}
class UpdateProgress extends StatefulWidget {
final String releasePageUrl;
final String downloadUrl;
@@ -74,9 +121,9 @@ class UpdateProgressState extends State<UpdateProgress> {
Timer? _timer;
int? _totalSize;
int _downloadedSize = 0;
bool _downloadFinished = false;
int _getDataFailedCount = 0;
final String _eventKeyDownloadNewVersion = 'download-new-version';
final String _eventKeyExtractUpdateDmg = 'extract-update-dmg';
@override
void initState() {
@@ -88,11 +135,6 @@ class UpdateProgressState extends State<UpdateProgress> {
_eventKeyDownloadNewVersion, handleDownloadNewVersion,
replace: true);
bind.mainSetCommon(key: 'download-new-version', value: widget.downloadUrl);
if (isMacOS) {
platformFFI.registerEventHandler(_eventKeyExtractUpdateDmg,
_eventKeyExtractUpdateDmg, handleExtractUpdateDmg,
replace: true);
}
}
@override
@@ -100,10 +142,7 @@ class UpdateProgressState extends State<UpdateProgress> {
cancelQueryTimer();
platformFFI.unregisterEventHandler(
_eventKeyDownloadNewVersion, _eventKeyDownloadNewVersion);
if (isMacOS) {
platformFFI.unregisterEventHandler(
_eventKeyExtractUpdateDmg, _eventKeyExtractUpdateDmg);
}
platformFFI.unregisterEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe);
super.dispose();
}
@@ -128,35 +167,33 @@ class UpdateProgressState extends State<UpdateProgress> {
}
}
// `isExtractDmg` is true when handling extract-update-dmg event.
// It's a rare case that the dmg file is corrupted and cannot be extracted.
void _onError(String error, {bool isExtractDmg = false}) {
void _onError(String error) {
cancelQueryTimer();
debugPrint(
'${isExtractDmg ? "Extract" : "Download"} new version error: $error');
debugPrint('Download new version error: $error');
final msgBoxType = 'custom-nocancel-nook-hasclose';
final msgBoxTitle = 'Error';
final msgBoxText = 'download-new-version-failed-tip';
final dialogManager = gFFI.dialogManager;
final releasePageUrl = widget.releasePageUrl;
close() {
dialogManager.dismissAll();
}
jumplink() {
launchUrl(Uri.parse(widget.releasePageUrl));
launchUrl(Uri.parse(releasePageUrl));
dialogManager.dismissAll();
}
retry() {
dialogManager.dismissAll();
handleUpdate(widget.releasePageUrl);
handleUpdate(releasePageUrl);
}
final List<Widget> buttons = [
dialogButton('Download', onPressed: jumplink),
if (!isExtractDmg) dialogButton('Retry', onPressed: retry),
dialogButton('Retry', onPressed: retry),
dialogButton('Close', onPressed: close),
];
dialogManager.dismissAll();
@@ -186,6 +223,8 @@ class UpdateProgressState extends State<UpdateProgress> {
}
} else if (key == 'downloaded_size') {
_downloadedSize = value as int;
} else if (key == 'finished') {
_downloadFinished = value as bool;
} else if (key == 'error') {
if (value != null) {
err = value.toString();
@@ -204,7 +243,9 @@ class UpdateProgressState extends State<UpdateProgress> {
if (err != '') {
_onError(err);
} else {
if (_totalSize != null && _downloadedSize >= _totalSize!) {
if (_downloadFinished &&
_totalSize != null &&
_downloadedSize >= _totalSize!) {
cancelQueryTimer();
bind.mainSetCommon(
key: 'remove-downloader', value: widget.downloadId.value);
@@ -212,13 +253,7 @@ class UpdateProgressState extends State<UpdateProgress> {
_onError('The download file size is 0.');
} else {
setState(() {});
if (isMacOS) {
bind.mainSetCommon(
key: 'extract-update-dmg', value: widget.downloadUrl);
_isExtracting.value = true;
} else {
updateMsgBox();
}
updateMsgBox();
}
} else {
setState(() {});
@@ -227,6 +262,8 @@ class UpdateProgressState extends State<UpdateProgress> {
}
void updateMsgBox() {
final releasePageUrl = widget.releasePageUrl;
final downloadUrl = widget.downloadUrl;
msgBox(
gFFI.sessionId,
'custom-nocancel',
@@ -234,30 +271,30 @@ class UpdateProgressState extends State<UpdateProgress> {
'{$appName}-to-update-tip',
'',
gFFI.dialogManager,
onSubmit: () {
onSubmit: () async {
debugPrint('Downloaded, update to new version now');
bind.mainSetCommon(key: 'update-me', value: widget.downloadUrl);
platformFFI.registerEventHandler(_eventKeyUpdateMe, _eventKeyUpdateMe,
(evt) => _handleUpdateMe(releasePageUrl, evt),
replace: true);
try {
await bind.mainSetCommon(key: 'update-me', value: downloadUrl);
} catch (error) {
platformFFI.unregisterEventHandler(
_eventKeyUpdateMe, _eventKeyUpdateMe);
_showUpdateError(releasePageUrl, error.toString());
}
},
submitTimeout: 5,
);
}
Future<void> handleExtractUpdateDmg(Map<String, dynamic> evt) async {
_isExtracting.value = false;
if (evt.containsKey('err') && (evt['err'] as String).isNotEmpty) {
_onError(evt['err'] as String, isExtractDmg: true);
} else {
updateMsgBox();
}
}
@override
Widget build(BuildContext context) {
getValue() => _totalSize == null
? 0.0
: (_totalSize == 0 ? 1.0 : _downloadedSize / _totalSize!);
return LinearProgressIndicator(
value: _isExtracting.isTrue ? null : getValue(),
value: getValue(),
minHeight: 20,
borderRadius: BorderRadius.circular(5),
backgroundColor: Colors.grey[300],
@@ -377,6 +377,10 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
} else if (newValue.length < oldValue.length) {
@@ -11,10 +11,3 @@ const terminalKeyboardKeySpacing = 2.0;
/// Empty 48dp slots keep expanded Row3 aligned with the two rows above it.
const terminalKeyboardRow3TrailingPlaceholderCount = 2;
/// Returns the fixed width occupied by a row of equally sized key slots.
double terminalKeyboardRowWidth(int slotCount) {
if (slotCount <= 0) return 0;
return slotCount * terminalKeyboardKeyWidth +
(slotCount - 1) * terminalKeyboardKeySpacing;
}
+16 -2
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
import 'package:flutter_hbb/common/widgets/toolbar.dart';
import 'package:get/get.dart';
@@ -69,6 +70,8 @@ void showServerSettingsWithValue(
ServerConfig serverConfig,
OverlayDialogManager dialogManager,
void Function(VoidCallback)? upSetState) async {
const labelWidth = 120.0;
const labelSpacing = 8.0;
var isInProgress = false;
final idCtrl = TextEditingController(text: serverConfig.idServer);
final relayCtrl = TextEditingController(text: serverConfig.relayServer);
@@ -112,10 +115,10 @@ void showServerSettingsWithValue(
return Row(
children: [
SizedBox(
width: 120,
width: labelWidth,
child: Text(label),
),
SizedBox(width: 8),
SizedBox(width: labelSpacing),
Expanded(
child: serverSettingsTextFormField(
label: label,
@@ -175,6 +178,17 @@ void showServerSettingsWithValue(
return null;
},
),
Padding(
padding: EdgeInsetsDirectional.only(
start: isDesktop || isWeb ? labelWidth + labelSpacing : 0,
),
child: ApiServerWarning(
controller: apiCtrl,
idController: idCtrl,
message: translate('api_server_connection_tip'),
emptyMessage: translate('api_server_empty_tip'),
),
),
SizedBox(height: 8),
buildField('Key', keyCtrl, ''),
if (isInProgress)
@@ -372,6 +372,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
Offset _position = Offset.zero;
bool _isInitialized = false;
bool _isDown = false;
Object? _activePress;
bool _remoteButtonDown = false;
Rect? _lastBlockedRect;
Orientation? _previousOrientation;
@@ -398,6 +400,11 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
@override
void dispose() {
_activePress = null;
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
if (_lastBlockedRect != null) {
_cursorModel.removeBlockedRect(_lastBlockedRect!);
}
@@ -569,6 +576,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
child: Listener(
onPointerMove: _onBodyPointerMoveUpdate,
onPointerDown: (event) async {
final press = Object();
_activePress = press;
_isDragging = false;
setState(() {
_isDown = true;
@@ -579,6 +588,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = true;
() async {
await _cursorModel.syncCursorPosition();
if (!mounted || !identical(_activePress, press)) return;
_remoteButtonDown = true;
await _inputModel
.tapDown(_isLeft ? MouseButtons.left : MouseButtons.right);
}();
@@ -586,6 +597,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
});
},
onPointerUp: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
@@ -604,8 +617,8 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
}));
} else {
// If it's not a quick tap, it could be a hold or drag.
// If it was a hold, isSpecialHoldDragActive is true.
if (isSpecialHoldDragActive) {
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel
.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
@@ -617,13 +630,16 @@ class _FloatingLeftRightButtonState extends State<FloatingLeftRightButton> {
isSpecialHoldDragActive = false;
},
onPointerCancel: (event) {
if (!mounted) return;
_activePress = null;
_cursorModel.blockEvents = false;
setState(() {
_isDown = false;
});
_tapDownTimer?.cancel();
_tapDownTimer = null;
if (isSpecialHoldDragActive) {
if (_remoteButtonDown) {
_remoteButtonDown = false;
_inputModel.tapUp(_isLeft ? MouseButtons.left : MouseButtons.right);
}
isSpecialHoldDragActive = false;
+55
View File
@@ -4,6 +4,7 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common.dart';
import 'package:flutter_hbb/common/widgets/dialog.dart';
import 'package:flutter_hbb/utils/download_paths.dart';
import 'package:flutter_hbb/utils/event_loop.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as path;
@@ -627,6 +628,17 @@ class FileController {
final transferJobIds = <int>[];
for (var from in items.items) {
final jobID = jobController.addTransferJob(from, isRemoteToLocal);
// Keep this check before PathUtil.join: Rust does not receive the selected
// root separately, and Web transfers bypass Rust validation.
if (isRemoteToLocal &&
!DownloadPaths.validName(from.name, windows: isWindows)) {
jobController.jobError({
'id': '$jobID',
'file_num': '0',
'err': 'Invalid file name: ${from.name}',
});
continue;
}
transferJobs.add((from, jobID));
transferJobIds.add(jobID);
}
@@ -651,6 +663,15 @@ class FileController {
return;
}
if (isRemoteToLocal) {
for (final (entry, jobID) in transferJobs) {
if (entry.isDirectory) {
await _downloadEmptyDirectories(entry, jobID, otherSideData);
}
}
return;
}
final List<Entry> entrys = items.items.toList();
var isRemote = isLocal == true ? true : false;
@@ -683,6 +704,35 @@ class FileController {
});
}
Future<void> _downloadEmptyDirectories(
Entry entry, int jobID, DirectoryData destination) async {
try {
final emptyDirs = await fileFetcher.readEmptyDirs(
entry.path, false, destination.options.showHidden);
final localRoot = PathUtil.join(destination.directory.path, entry.name,
destination.options.isWindows);
final paths = emptyDirs
.map((dir) => DownloadPaths.mapDirectory(
entry.path, dir.path, localRoot,
remoteWindows: options.value.isWindows,
localWindows: destination.options.isWindows))
.toList();
for (final path in paths) {
await DownloadPaths.ensureNoLinks(destination.directory.path, path);
}
for (final path in paths) {
await createDirWithRemote(path, false);
}
} on FormatException catch (err) {
await bind.sessionCancelJob(sessionId: sessionId, actId: jobID);
jobController.jobError({
'id': '$jobID',
'file_num': '0',
'err': err.message,
});
}
}
bool _removeCheckboxRemember = false;
Future<void> removeAction(SelectedItems items) async {
@@ -1120,6 +1170,11 @@ class JobController {
return true;
}
final job = jobTable[jobIndex];
if (job.type == JobType.transfer &&
job.isRemoteToLocal &&
job.state == JobState.error) {
return true;
}
job.recvJobRes = true;
if (job.type == JobType.deleteFile) {
job.state = JobState.done;
+21 -2
View File
@@ -459,6 +459,7 @@ class InputModel {
// mouse
final isPhysicalMouse = false.obs;
int _lastButtons = 0;
int _pressedMouseButtons = 0;
Offset lastMousePos = Offset.zero;
int _lastWheelTsUs = 0;
@@ -1388,6 +1389,10 @@ class InputModel {
}
}
_lastButtons = hasStaleButtonsOnMouseUp ? 0 : evt.buttons;
if (isDesktop && _relativeMouse.enabled.value && type == _kMouseEventUp) {
// A relative up can finish a press sent before the mode switch.
_pressedMouseButtons &= ~buttons;
}
out['buttons'] = buttons;
out['type'] = type;
@@ -2134,9 +2139,16 @@ class InputModel {
bool edgeScroll = false,
}) {
if (isViewCamera) return null;
final buttons = evt['buttons'];
final isMatchingMouseUp = (isDesktop || isWebDesktop) &&
evt['type'] == _kMouseEventUp &&
buttons is int &&
mouseButtonsToPeer(buttons).isNotEmpty &&
_pressedMouseButtons & buttons != 0;
double x = offset.dx;
double y = max(0.0, offset.dy);
if (_checkPeerControlProtected(x, y)) {
// Cursor ownership may change between a forwarded down and its up.
if (_checkPeerControlProtected(x, y) && !isMatchingMouseUp) {
return null;
}
@@ -2178,6 +2190,9 @@ class InputModel {
if (pos == null) {
return null;
}
if (isMatchingMouseUp) {
_pressedMouseButtons &= ~buttons;
}
if (type != '') {
evt['x'] = '0';
evt['y'] = '0';
@@ -2186,9 +2201,13 @@ class InputModel {
evt['y'] = '${pos.y.toInt()}';
}
final buttons = evt['buttons'];
if (buttons is int) {
evt['buttons'] = mouseButtonsToPeer(buttons);
if ((isDesktop || isWebDesktop) &&
type == kMouseEventTypeDown &&
evt['buttons'] != '') {
_pressedMouseButtons |= buttons;
}
} else {
// Log warning if buttons exists but is not an int (unexpected caller).
// Keep empty string fallback for missing buttons to preserve move/hover behavior.
-4
View File
@@ -70,10 +70,6 @@ class TerminalModel with ChangeNotifier {
final _inputBuffer = <String>[];
/// Exposes buffered input only for lifecycle regression tests.
@visibleForTesting
int get debugBufferedInputCount => _inputBuffer.length;
// Buffer for output data received before terminal view has valid dimensions.
// This prevents NaN errors when writing to terminal before layout is complete.
final _pendingOutputChunks = <String>[];
+52
View File
@@ -0,0 +1,52 @@
import 'dart:io';
import 'package:path/path.dart' as path;
class DownloadPaths {
static Future<void> ensureNoLinks(String root, String destination) async {
if (!path.isWithin(root, destination)) {
throw FormatException('Invalid download directory: $destination');
}
var current = root;
for (final name in path.split(path.relative(destination, from: root))) {
current = path.join(current, name);
if (await FileSystemEntity.type(current, followLinks: false) ==
FileSystemEntityType.link) {
throw FormatException('Download directory contains a link: $current');
}
}
}
static bool validName(String name, {required bool windows}) {
if (name.isEmpty || name == '.' || name == '..' || name.contains('\x00')) {
return false;
}
if (name.contains('/')) return false;
return !windows ||
(!name.contains(RegExp(r'[<>:"\\|?*]')) &&
!name.endsWith('.') &&
!name.endsWith(' '));
}
static String mapDirectory(
String remoteRoot, String remotePath, String localRoot,
{required bool remoteWindows, required bool localWindows}) {
final remote = path.Context(
style: remoteWindows ? path.Style.windows : path.Style.posix);
final local = path.Context(
style: localWindows ? path.Style.windows : path.Style.posix);
if (remotePath.contains('\x00') ||
remote.split(remotePath).contains('..') ||
(!remote.equals(remoteRoot, remotePath) &&
!remote.isWithin(remoteRoot, remotePath))) {
throw FormatException('Invalid download directory: $remotePath');
}
final relative = remote.relative(remotePath, from: remoteRoot);
if (relative == '.') return localRoot;
final names = remote.split(relative);
if (names.any((name) => !validName(name, windows: localWindows))) {
throw FormatException('Invalid download directory: $remotePath');
}
return local.joinAll([localRoot, ...names]);
}
}
+5
View File
@@ -1928,6 +1928,11 @@ class RustdeskImpl {
}
String mainGetCommonSync({required String key, dynamic hint}) {
const prefix = 'resolve-api-server:';
if (key.startsWith(prefix)) {
return js.context
.callMethod('getByName', ['api_server', key.substring(prefix.length)]);
}
throw UnimplementedError("mainGetCommonSync");
}
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# 1.1.9-1 works for android, but for ios it becomes 1.1.91, need to set it to 1.1.9-a.1 for iOS, will get 1.1.9.1, but iOS store not allow 4 numbers
version: 1.5.0+68
version: 1.5.1+68
environment:
sdk: '^3.1.0'
+80
View File
@@ -0,0 +1,80 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_hbb/common/widgets/api_server_warning.dart';
void main() {
test('warns only for remote HTTP endpoints', () {
final cases = <String?, bool>{
null: false,
'': false,
'https://api.example.com': false,
'http://api.example.com': true,
'http://192.168.1.13:13000': true,
'http://localhost:21114': false,
'http://127.0.0.1:21114': false,
'http://[::1]:21114': false,
};
for (final entry in cases.entries) {
expect(shouldWarnApiServer(entry.key), entry.value, reason: entry.key);
}
});
testWidgets('warning follows API and ID changes using the resolved endpoint',
(tester) async {
final api = TextEditingController();
final id = TextEditingController(text: 'id.example.com');
addTearDown(api.dispose);
addTearDown(id.dispose);
await tester.pumpWidget(MaterialApp(
home: ApiServerWarning(
controller: api,
idController: id,
message: 'HTTP warning',
emptyMessage: 'Default HTTP warning',
resolveApiServer: ({required api, required custom}) =>
api.isNotEmpty ? api : 'http://$custom',
),
));
expect(find.text('Default HTTP warning'), findsOneWidget);
id.text = 'localhost';
await tester.pump();
expect(find.text('Default HTTP warning'), findsNothing);
api.text = 'http://api.example.com';
await tester.pump();
expect(find.text('HTTP warning'), findsOneWidget);
api.text = 'https://api.example.com';
await tester.pump();
expect(find.text('HTTP warning'), findsNothing);
});
testWidgets('resolver failures are reported without breaking the server form',
(tester) async {
final api = TextEditingController();
final id = TextEditingController();
addTearDown(api.dispose);
addTearDown(id.dispose);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Column(children: [
TextField(controller: api),
Expanded(
child: ApiServerWarning(
controller: api,
idController: id,
message: 'HTTP warning',
emptyMessage: 'Default HTTP warning',
resolveApiServer: ({required api, required custom}) =>
throw const FormatException('API preview failed'),
)),
]),
),
));
expect(tester.takeException(), isA<FormatException>());
expect(find.byType(ErrorWidget), findsNothing);
expect(find.text('Default HTTP warning'), findsNothing);
expect(find.byType(TextField), findsOneWidget);
});
}
@@ -48,74 +48,6 @@ void main() {
expect(peers.single.online, isTrue);
});
test('peer copies preserve online state', () {
final peer = _peer(id: '987654321', online: true);
expect(Peer.copy(peer).online, isTrue);
});
test('online callbacks update autocomplete-only peers', () {
final peers = mergeAutocompletePeers(restRecentPeerIds: ['112233445']);
final changed = updateAutocompletePeerOnlineStates(
peers,
onlines: {'112233445'},
offlines: {},
);
expect(changed, isTrue);
expect(peers.single.online, isTrue);
});
test('online query ids are deduplicated and limited', () {
final peers = List.generate(
25,
(index) => _peer(id: index.toString()),
)..insert(1, _peer(id: '0'));
final ids = autocompleteOnlineQueryIds(peers, limit: 20);
expect(ids, hasLength(20));
expect(ids.first, '0');
expect(ids.where((id) => id == '0'), hasLength(1));
expect(ids.last, '19');
});
test('empty online query ids cancel pending debounce', () async {
final queriedIds = <List<String>>[];
final loader = AllPeersLoader(
queryOnlines: (ids) async {
queriedIds.add(ids);
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
loader.queryOnlines([]);
await Future.delayed(Duration(milliseconds: 2));
expect(queriedIds, isEmpty);
});
test('failed online query enqueue does not suppress retry', () async {
var queryCount = 0;
final loader = AllPeersLoader(
queryOnlines: (ids) {
queryCount += 1;
return Future<void>.error(Exception('queue full'));
},
queryOnlineDebounce: Duration(milliseconds: 1),
);
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
loader.queryOnlines([_peer(id: '123456789')]);
await Future.delayed(Duration(milliseconds: 2));
expect(queryCount, 2);
});
test('online callback updates currently displayed options', () async {
final loader = AllPeersLoader(
queryOnlines: (ids) async {},
@@ -132,17 +64,4 @@ void main() {
expect(displayedOptions.single.online, isTrue);
await Future.delayed(Duration(milliseconds: 2));
});
test('cached online callback state is reapplied after peers merge', () {
final loader = AllPeersLoader();
loader.updateOnlineStateForTesting({
'onlines': '123456789',
'offlines': '',
});
final mergedPeers = [_peer(id: '123456789')];
loader.applyLastOnlineStateForTesting(mergedPeers);
expect(mergedPeers.single.online, isTrue);
});
}
-20
View File
@@ -1,20 +0,0 @@
import 'package:flutter_test/flutter_test.dart';
import 'cm_demo.dart' as cm_demo;
void main() {
test('connection manager demo clients match the current Client API', () {
expect(cm_demo.testClients, hasLength(4));
expect(cm_demo.testClients.map((client) => client.name), [
'UserAAAAAA',
'UserBBBBB',
'UserC',
'UserDDDDDDDDDDDd',
]);
expect(
cm_demo.testClients.every(
(client) => client.keyboard && !client.clipboard && !client.audio),
isTrue,
);
});
}
+2 -460
View File
@@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
@@ -15,36 +14,14 @@ class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final core = <String, CursorShape>{};
final fetched = <String>[];
// While set, a fetch answers only when [answerFetches] is called.
bool holdFetches = false;
// While set, a fetch throws before it returns a future.
bool throwAtOnce = false;
final _held = <Completer<CursorShape?>, String>{};
@override
Future<CursorShape?> fetchCursorShape(String id) {
fetched.add(id);
if (throwAtOnce) throw StateError('no core');
if (!holdFetches) return Future.value(core[id]);
final answer = Completer<CursorShape?>();
_held[answer] = id;
return answer.future;
return Future.value(core[id]);
}
void answerFetches() {
final held = Map.of(_held);
_held.clear();
held.forEach((answer, id) => answer.complete(core[id]));
}
void failFetches() {
final held = Map.of(_held);
_held.clear();
held.forEach((answer, _) => answer.completeError(StateError('failed')));
}
bool showRemoteCursor = false;
@override
bool get showsRemoteCursor => showRemoteCursor;
bool get showsRemoteCursor => false;
}
String? _key(MouseCursor cursor) =>
@@ -181,28 +158,6 @@ void main() {
expect(registered.length, 100);
});
test(
'a raster made before is found again after the shape was switched away from',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'A', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
final first = registered.single;
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
await _feed(ffi, 'B');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
final count = registered.length;
_select(ffi, 'A'); // its pixels went; its cursors at both rasters stay
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), first);
await _settle();
expect(ffi.cursor.fetched, isEmpty);
expect(registered.length, count);
});
test('a new raster of a shape without pixels keeps the cursor shown before',
() async {
final cursor = ffi.cursorModel;
@@ -220,134 +175,6 @@ void main() {
cursor.nativeKey(cursor.cache!, 0.5));
});
test('shapes that keep decoding late still get their native cursors',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'arrow');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
// A and B arrive, each decoding only after the peer moved on.
for (final (id, seed) in [('A', 1), ('B', 2)]) {
final pixels = _pixels(8, seed);
ffi.cursor.core[id] =
CursorShape(hotx: 0, hoty: 0, width: 8, height: 8, colors: pixels);
final decoding = ffi.ffiModel.handleCursorData(id, 0, 0, 8, 8, pixels);
_select(ffi, 'arrow');
await decoding;
}
// Each fetch answers only after the next switch.
ffi.cursor.holdFetches = true;
for (var i = 0; i < 6; i++) {
_select(ffi, i.isEven ? 'A' : 'B');
ffi.cursor.answerFetches();
await _settle();
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(registered.where((key) => key.contains('_A_')), isNotEmpty);
expect(registered.where((key) => key.contains('_B_')), isNotEmpty);
});
test('a zoom still gets native cursors for shapes that keep decoding late',
() async {
final cursor = ffi.cursorModel;
// An animation whose frames have native cursors at 1.0 only.
for (final (id, seed) in [('A', 1), ('B', 2)]) {
await _feed(ffi, id, size: 32, seed: seed);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
// At 0.5 each frame is fetched again, and each fetch answers after the next switch.
ffi.cursor.holdFetches = true;
for (var i = 0; i < 6; i++) {
_select(ffi, i.isEven ? 'A' : 'B');
ffi.cursor.answerFetches();
await _settle();
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
}
expect(
registered
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
isNotEmpty);
expect(
registered
.where((key) => key.contains('_B_') && key.endsWith('_16_16')),
isNotEmpty);
});
test(
'a raster still missing keeps a late restore, whatever was shown meanwhile',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, 'A', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, 'B');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
_select(ffi, 'A');
ffi.cursor.holdFetches = true;
buildCursorOfCache(cursor, 0.5, cursor.cache); // no cursor at 0.5: fetched
buildCursorOfCache(cursor, 1.0, cursor.cache); // 1.0 has one meanwhile
_select(ffi, 'B');
ffi.cursor.answerFetches();
await _settle();
ffi.cursor.fetched.clear();
_select(ffi, 'A');
buildCursorOfCache(cursor, 0.5, cursor.cache);
await _settle();
expect(ffi.cursor.fetched, isEmpty,
reason: 'its pixels waited for the cursor at 0.5');
expect(
registered
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
isNotEmpty);
});
test('shapes waiting for a native cursor keep their pixels, within the limit',
() async {
const max = CursorModel.kRecentShapes;
for (var i = 0; i <= max + 1; i++) {
await _feed(ffi, '$i');
}
expect(ffi.cursorModel.cachedShape('0')!.hasPixels, isFalse,
reason: 'the one waiting longest is let go');
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue);
expect(ffi.cursorModel.cachedShape('$max')!.hasPixels, isTrue);
});
test('two animated cursors and the everyday set keep their native cursors',
() async {
// Each frame is a shape of its own: 18 for the Windows busy cursor, 23 for
// KDE Breeze's wait and progress cursors on X11.
const frames = 23;
const statics = 12;
final cursor = ffi.cursorModel;
final shapes = [
for (var i = 0; i < statics; i++) 's$i',
for (var i = 0; i < frames; i++) 'wait$i',
for (var i = 0; i < frames; i++) 'progress$i',
];
for (var i = 0; i < shapes.length; i++) {
await _feed(ffi, shapes[i], seed: i);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
ffi.cursor.fetched.clear();
for (final id in shapes) {
_select(ffi, id);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
}
expect(ffi.cursor.fetched, isEmpty,
reason: 'every shape kept its native cursor');
expect(registered.length, shapes.length);
expect(deleted, isEmpty);
});
test('a shape painted again is decoded again, the last one shown meanwhile',
() async {
await _feed(ffi, '1', size: 16);
@@ -360,89 +187,6 @@ void main() {
expect(ffi.cursorModel.shapeIds, ['1']);
});
test('a shape the core gives but that does not decode is asked for once',
() async {
await _feed(ffi, '1');
await _feed(ffi, '2');
ffi.cursor.core['1'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
_select(ffi, '1');
for (var i = 0; i < 5; i++) {
ffi.cursorModel.image;
await _settle();
}
expect(ffi.cursor.fetched, ['1']);
});
test('a shape switched away from while it decoded is asked for again',
() async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
ffi.cursorModel.image; // asks the core
// The core has answered and the shape is decoding when the peer moves on.
await Future<void>.delayed(Duration.zero);
_select(ffi, '2');
await _settle();
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue,
reason:
'decoded after the peer moved on, it waits for its native cursor');
_select(ffi, '1');
ffi.cursorModel.image;
await _settle();
expect(ffi.cursor.fetched, ['1', '1']);
expect(ffi.cursorModel.image?.width, 16);
});
test('a shape decoded after the session was cleared is not kept', () async {
await _feed(ffi, '1', size: 16);
await _feed(ffi, '2');
_select(ffi, '1');
ffi.cursorModel.image; // asks the core
ffi.cursorModel.clear();
await _settle();
expect(ffi.cursorModel.shapeIds, isEmpty);
expect(ffi.cursorModel.cache, isNull);
});
test('a shape the core does not have is asked for once', () async {
await _feed(ffi, '1');
await _feed(ffi, '2');
ffi.cursor.core.remove('1');
_select(ffi, '1');
for (var i = 0; i < 5; i++) {
ffi.cursorModel.image;
await _settle();
}
expect(ffi.cursor.fetched, ['1']);
});
test('a shape the core lacks is remembered only while it is in use',
() async {
await _feed(ffi, '1');
for (var i = 0; i < 1000; i++) {
_select(ffi, 'missing$i');
ffi.cursorModel.image;
}
await _settle();
expect(ffi.cursor.fetched.length, 1000, reason: 'each is asked for once');
_select(ffi, 'missing0');
await _settle();
expect(ffi.cursor.fetched.length, 1001,
reason: 'nothing is kept for a shape no longer in use');
});
test('a shape the core lacks is asked for again after another was in use',
() async {
await _feed(ffi, '1');
_select(ffi, 'missing0');
await _settle();
_select(ffi, '1');
_select(ffi, 'missing0');
await _settle();
expect(ffi.cursor.fetched, ['missing0', 'missing0']);
});
test('a moved tab carries the id in use, and its window asks the core',
() async {
await _feed(ffi, '1', size: 16);
@@ -463,30 +207,6 @@ void main() {
expect(moved.cursorModel.image?.width, 16);
});
test('a shape keeps a native cursor for each raster it was shown at',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1', size: 32);
for (final scale in [1.0, 0.5, 1.0, 0.5]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await _settle();
}
expect(registered.length, 2, reason: 'a raster returned to is reused');
expect(deleted, isEmpty);
expect(cursor.cachedKeys, registered.toSet());
});
test('a cleared session forgets the native cursors it deleted', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
cursor.clear();
await _settle();
expect(deleted, registered);
expect(cursor.cachedKeys, isEmpty);
});
test('a tab closing does not delete the cursors of another tab', () async {
final other = _FFI();
addTearDown(other.cursorModel.disposeImages);
@@ -502,182 +222,4 @@ void main() {
await _settle();
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
});
test('a shape given as a view into a larger buffer is read from the view',
() async {
final pixels = _pixels(8, 3);
final padded = Uint8List(16 + pixels.length)
..setRange(16, 16 + pixels.length, pixels);
await ffi.ffiModel
.handleCursorData('1', 0, 0, 8, 8, Uint8List.sublistView(padded, 16));
final p = ffi.cursorModel.cache!.image.getPixel(0, 0);
expect([p.r, p.g, p.b, p.a], [3, 4, 5, 6]);
});
test('a shape still decoding leaves the one shown before in place', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
_select(ffi, '2'); // its shape has not decoded yet
expect(cursor.cache?.id, '1');
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), shown);
expect(cursor.image, isNotNull);
await _feed(ffi, '2');
expect(cursor.cache?.id, '2');
});
for (final how in ['does not have', 'cannot decode']) {
test('a shape the core $how leaves the default cursor, not the one before',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
if (how == 'cannot decode') {
ffi.cursor.core['2'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
}
_select(ffi, '2');
expect(cursor.cache?.id, '1', reason: 'kept while the shape may come');
var notified = 0;
cursor.addListener(() => notified++);
await _settle();
expect(cursor.cache, isNull,
reason: 'the desktop shows preDefaultCursor');
expect(cursor.image, isNull, reason: 'and so does a painted cursor');
expect(notified, greaterThan(0));
});
}
test('a shape sent that does not decode leaves the default cursor', () async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
ffi.cursor.core['2'] = CursorShape(
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
await ffi.ffiModel.handleCursorData('2', 0, 0, 8, 8, Uint8List(3));
expect(cursor.cache, isNull);
expect(cursor.image, isNull);
_select(ffi, '2');
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'it is not asked for either');
});
test('a fetch failing after the session was cleared marks nothing in it',
() async {
final cursor = ffi.cursorModel;
ffi.cursor.holdFetches = true;
_select(ffi, '1'); // not decoded here yet, so it is asked for
cursor.clear();
ffi.cursor.failFetches();
await _settle();
ffi.cursor.holdFetches = false;
_select(ffi, '1'); // the same id, now in the new session
await _settle();
expect(ffi.cursor.fetched, ['1', '1']);
});
test('a fetch that throws at once tells the listeners after the build',
() async {
final cursor = ffi.cursorModel;
await _feed(ffi, '1');
ffi.cursor.throwAtOnce = true;
cursor.id = '2';
var notified = 0;
cursor.addListener(() => notified++);
cursor.restorePixels('2');
expect(notified, 0, reason: 'a build may be what asked');
await _settle();
expect(notified, greaterThan(0));
expect(cursor.cache, isNull);
});
test('a raster still being made falls back to a shape, not the forbidden one',
() async {
final cursor = ffi.cursorModel;
for (var i = 0; preForbiddenCursor.cache == null && i < 100; i++) {
await _settle();
}
expect(preForbiddenCursor.cache, isNotNull);
await _feed(ffi, '1', size: 32);
buildCursorOfCache(cursor, 1.0, cursor.cache);
await _settle();
await _feed(ffi, '2', size: 32);
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
await _settle();
buildCursorOfCache(cursor, 1.0, preForbiddenCursor.cache); // input disabled
_select(ffi, '1'); // its native cursor held its pixels, so they went
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
});
group('a painted cursor', () {
void painted(String how) {
if (how == 'mobile') {
final was = isMobile;
isMobile = true;
addTearDown(() => isMobile = was);
} else {
ffi.cursor.showRemoteCursor = true;
}
}
for (final how in ['mobile', 'remote cursor shown']) {
test('keeps the images of two animations and the everyday set ($how)',
() async {
painted(how);
final cursor = ffi.cursorModel;
final shapes = [
for (var i = 0; i < 12; i++) 's$i',
for (var i = 0; i < 23; i++) 'wait$i',
for (var i = 0; i < 23; i++) 'progress$i',
];
for (var i = 0; i < shapes.length; i++) {
await _feed(ffi, shapes[i], seed: i);
}
for (final id in shapes) {
_select(ffi, id);
expect(cursor.shapeIds.last, id, reason: 'its image is at hand');
}
await _settle();
expect(ffi.cursor.fetched, isEmpty);
});
}
test('keeps the images used last, and decodes the others again', () async {
painted('mobile');
const max = CursorModel.kRecentShapes;
final cursor = ffi.cursorModel;
for (var i = 0; i <= max; i++) {
await _feed(ffi, '$i');
}
expect(cursor.shapeIds.length, max);
_select(ffi, '$max');
_select(ffi, '1');
await _settle();
expect(ffi.cursor.fetched, isEmpty, reason: 'shape 1 was used lately');
_select(ffi, '0');
expect(cursor.image, isNotNull, reason: 'shape 1 until 0 is back');
await _settle();
expect(ffi.cursor.fetched, ['0']);
expect(cursor.shapeIds.length, max);
});
test('keeps a shape that finished decoding after the peer moved on',
() async {
painted('mobile');
const max = CursorModel.kRecentShapes;
final cursor = ffi.cursorModel;
for (var i = 0; i <= max; i++) {
await _feed(ffi, '$i');
}
_select(ffi, '0');
cursor.image; // let go, so it is asked for
await Future<void>.delayed(Duration.zero);
_select(ffi, '1');
await _settle();
_select(ffi, '0');
cursor.image;
await _settle();
expect(ffi.cursor.fetched, ['0'], reason: 'the late one was kept');
expect(cursor.shapeIds.last, '0');
});
});
}
+8 -39
View File
@@ -108,17 +108,11 @@ void main() {
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
for (final scenario in [
((4, 64), 0.5, (2, 32)),
((64, 4), 0.5, (32, 2)),
((1, 64), 0.25, (1, 16)),
((8, 8), 0.5, (12, 12)),
((4, 64), 1.0, (4, 64)),
((1, 512), 10.0, (1, 512)),
]) {
test('native cursor size $scenario',
() => _checkSize(scenario, registrations));
}
test('native raster boundaries rebuild buffers and distinguish cache keys',
() => _checkRasterTransitions(registrations));
test('cursor resize limits preserve the last valid raster', () async {
for (final size in [(30, 20), (20, 30)]) {
await _checkResizeLimits(size, registrations);
@@ -132,15 +126,15 @@ void main() {
test('Windows peer cursor alpha survives resizing $pattern',
() => _checkWindowsPeerAlpha(pattern, registrations));
}
for (final style in [
kRemoteViewStyleOriginal,
kRemoteViewStyleAdaptive,
kRemoteViewStyleCustom
for (final (style, zoom) in [
(kRemoteViewStyleOriginal, false),
(kRemoteViewStyleAdaptive, false),
(kRemoteViewStyleAdaptive, true),
(kRemoteViewStyleCustom, false),
(kRemoteViewStyleCustom, true),
]) {
for (final zoom in [false, true]) {
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
testWidgets('$style zoom=$zoom follows the live DPR and peer scale',
(tester) => _checkView(tester, (style, zoom), registrations));
}
}
@@ -241,31 +235,6 @@ void _expectSize(Map<dynamic, dynamic> args, (int, int) expected) {
}
}
Future<void> _checkRasterTransitions(
List<Map<dynamic, dynamic>> registrations) async {
const delta = 3e-8;
const scaleAboveOne = (2.25 / 1.75) / 2.25 * 1.75;
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
final cursor = _Cursor(_data((64, 64)), ffi);
addTearDown(() => _dispose(cursor));
addTearDown(ffi.canvasModel.dispose);
for (final (scale, expected) in [
(scaleAboveOne, (65, 65)),
(0.5 - delta, (32, 32)),
(0.5 + delta, (33, 33)),
(1.0, (64, 64)),
(scaleAboveOne, (65, 65)),
(1.0, (64, 64)),
]) {
buildCursorOfCache(cursor, scale, cursor.cache);
await Future<void>.delayed(Duration.zero);
final key = cursor.nativeKey(cursor.cache, scale);
_expectSize(
registrations.singleWhere((args) => args['name'] == key), expected);
}
expect(registrations.length, 4);
}
Future<void> _checkResizeLimits(
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
const maxSide = 512;
+174
View File
@@ -0,0 +1,174 @@
import 'dart:io';
import 'package:flutter_hbb/generated_bridge.dart';
import 'package:flutter_hbb/models/file_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
final _sessionId = UuidValue('00000000-0000-4000-8000-000000000001');
class _Binding extends Fake implements RustdeskImpl {
final sent = <String>[];
final created = <String>[];
int nextId = 0;
@override
String mainGetCommonSync({required String key, dynamic hint}) =>
'${++nextId}';
@override
int versionToNumber({required String v, dynamic hint}) =>
v == '1.3.3' ? 1 : 2;
@override
Future<void> sessionSendFiles({
required UuidValue sessionId,
required int actId,
required String path,
required String to,
required int fileNum,
required bool includeHidden,
required bool isRemote,
required bool isDir,
dynamic hint,
}) async {
expect(isRemote, isTrue);
sent.add(to);
}
@override
Future<void> sessionCreateDir({
required UuidValue sessionId,
required int actId,
required String path,
required bool isRemote,
dynamic hint,
}) async {
expect(isRemote, isFalse);
created.add(path);
}
@override
Future<void> sessionCancelJob({
required UuidValue sessionId,
required int actId,
dynamic hint,
}) async {}
}
class _Session extends Fake implements FFI {
@override
final String id = 'download-test';
@override
UuidValue get sessionId => _sessionId;
@override
late final ffiModel = FfiModel(WeakReference(this));
}
class _Fetcher extends FileFetcher {
_Fetcher() : super(() => _sessionId);
List<String> emptyDirectories = [];
@override
Future<List<FileDirectory>> readEmptyDirs(
String path, bool isLocal, bool showHidden) async =>
emptyDirectories.map((path) => FileDirectory()..path = path).toList();
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late _Binding binding;
late _Session session;
late _Fetcher fetcher;
late FileController controller;
late DirectoryData destination;
setUp(() {
binding = _Binding();
platformFFI.setBindingForTesting(binding);
session = _Session();
session.ffiModel.pi.version = '1.5.1';
fetcher = _Fetcher();
destination =
DirectoryData(FileDirectory()..path = '/downloads', DirectoryOptions());
controller = FileController(
isLocal: false,
getSessionID: () => _sessionId,
rootState: WeakReference(session),
jobController: JobController(() => _sessionId, () => null),
fileFetcher: fetcher,
getOtherSideDirectoryData: () => destination,
);
controller.directory.value.path = '/remote';
});
tearDown(() => session.ffiModel.dispose());
Future<void> download(String name, {bool directory = false}) async {
final entry = Entry()
..name = name
..path = '/remote/$name'
..entryType = directory ? 0 : 4;
final items = SelectedItems(isLocal: false)..add(entry);
await controller.sendFiles(items, destination);
}
test('downloads refuse peer listing names that escape the local folder',
() async {
await download('report.txt');
expect(binding.sent, ['/downloads/report.txt']);
binding.sent.clear();
for (final windows in [false, true]) {
destination.options.isWindows = windows;
destination.directory.path = windows ? r'C:\downloads' : '/downloads';
for (final name in [
'../outside.txt',
'/outside.txt',
'.',
'..',
'',
'bad\x00name',
if (windows) ...[r'..\outside.txt', r'C:\outside.txt', r'\\host\share'],
]) {
await download(name);
expect(binding.sent, isEmpty, reason: name);
expect(controller.jobController.jobTable.last.state, JobState.error);
}
}
await controller.jobController.jobDone({
'id': '${controller.jobController.jobTable.last.id}',
'file_num': '0',
});
expect(controller.jobController.jobTable.last.state, JobState.error);
});
test('empty-directory downloads reject paths outside the selected folder',
() async {
for (final path in ['/remote/other/empty', '/remote/docs/../out']) {
fetcher.emptyDirectories = ['/remote/docs/ok', path];
await download('docs', directory: true);
expect(binding.created, isEmpty, reason: path);
expect(controller.jobController.jobTable.last.state, JobState.error);
}
fetcher.emptyDirectories = ['/remote/docs', '/remote/docs/sub/empty'];
await download('docs', directory: true);
expect(binding.created, ['/downloads/docs', '/downloads/docs/sub/empty']);
});
test('empty-directory downloads refuse existing local links', () async {
final temporary =
await Directory.systemTemp.createTemp('rustdesk_download_');
addTearDown(() => temporary.delete(recursive: true));
final outside = await Directory('${temporary.path}/outside').create();
final downloads = await Directory('${temporary.path}/downloads').create();
await Link('${downloads.path}/docs').create(outside.path);
destination.directory.path = downloads.path;
destination.options.isWindows = Platform.isWindows;
fetcher.emptyDirectories = ['/remote/docs/empty'];
await download('docs', directory: true);
expect(binding.created, isEmpty);
expect(controller.jobController.jobTable.last.state, JobState.error);
});
}
@@ -0,0 +1,71 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/desktop/pages/file_manager_page.dart';
import 'package:flutter_hbb/desktop/widgets/list_search_action_listener.dart';
import 'package:flutter_hbb/models/file_model.dart';
import 'package:flutter_test/flutter_test.dart';
List<Entry> _entries(int count) => [
for (var i = 0; i < count; i++)
Entry()
..name = 'f$i'
..path = '/f$i'
];
List<String> _names(List<Entry> entries) =>
entries.map((e) => e.name).toList()..sort();
void main() {
test('navigation keys move the selection and stop at the ends', () {
final entries = _entries(5);
expect(_names(navigateSelection(entries, [], 1, false)), ['f0']);
expect(_names(navigateSelection(entries, [], -1, false)), ['f4']);
var selected = navigateSelection(entries, [entries[1]], 1, false);
expect(_names(selected), ['f2']);
selected = navigateSelection(entries, selected, -1, false);
expect(_names(selected), ['f1']);
expect(_names(navigateSelection(entries, selected, -3, false)), ['f0']);
expect(_names(navigateSelection(entries, selected, 5, false)), ['f4']);
});
test('shift extends and shrinks the range from the anchor', () {
final entries = _entries(5);
var selected = [entries[2]];
selected = navigateSelection(entries, selected, 1, true);
selected = navigateSelection(entries, selected, 1, true);
expect(_names(selected), ['f2', 'f3', 'f4']);
selected = navigateSelection(entries, selected, -1, true);
selected = navigateSelection(entries, selected, -1, true);
selected = navigateSelection(entries, selected, -1, true);
expect(_names(selected), ['f1', 'f2']);
selected = navigateSelection(entries, selected, 1, false);
expect(_names(selected), ['f2']);
});
test('page keys go to the visible edge before paging', () {
// Rows 10..19 are fully visible.
expect(pageDelta(12, 10, 19, true), 7);
expect(pageDelta(19, 10, 19, true), 9);
expect(pageDelta(12, 10, 19, false), -2);
expect(pageDelta(10, 10, 19, false), -9);
});
testWidgets('Enter does not reach type-to-search', (tester) async {
final node = FocusNode();
addTearDown(node.dispose);
final searched = <String>[];
await tester.pumpWidget(MaterialApp(
home: ListSearchActionListener(
node: node,
buffer: TimeoutStringBuffer(),
onNext: searched.add,
onSearch: searched.add,
child: const SizedBox(),
),
));
node.requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter, character: '\r');
expect(searched, isEmpty);
});
}
-72
View File
@@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter_hbb/models/file_model.dart';
@@ -62,19 +61,6 @@ void main() {
expect(directory.path, '/fast');
});
test('a send failure fails and removes its registered task', () async {
final failure = StateError('send failed');
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, __, ___) => Future<void>.error(failure),
);
await expectLater(
fileFetcher.fetchDirectory('/failed', false, false),
throwsA(same(failure)),
);
expect(fileFetcher.hasPendingRemoteRead('/failed'), isFalse);
});
test('a resolved Home path completes the sole empty-path request', () async {
final sent = <_SentRead>[];
final fileFetcher = FileFetcher(
@@ -107,35 +93,6 @@ void main() {
expect(controller.directory.value.path, '/home/user');
});
test('an exact path response is not taken by a pending Home request',
() async {
final sent = <_SentRead>[];
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, path, includeHidden) async {
sent.add(_SentRead(path, includeHidden));
},
);
final home = fileFetcher.fetchDirectory('', false, false);
final regular = fileFetcher.fetchDirectory('/regular', false, false);
await Future<void>.delayed(Duration.zero);
var homeCompleted = false;
home.then<void>((_) => homeCompleted = true);
fileFetcher.tryCompleteTask(_directoryJson('/unmatched'), 'false');
await Future<void>.delayed(Duration.zero);
expect(homeCompleted, isFalse);
fileFetcher.tryCompleteTask(_directoryJson('/regular'), 'false');
expect((await regular).path, '/regular');
await Future<void>.delayed(Duration.zero);
expect(homeCompleted, isFalse);
fileFetcher.tryCompleteTask(_directoryJson('/home/user'), 'false');
expect((await home).path, '/home/user');
expect(sent.map((request) => request.path), ['', '/regular']);
});
test('a read error completes the sole pending request', () async {
final fileFetcher = FileFetcher(
() => _sessionId,
@@ -230,35 +187,6 @@ void main() {
expect((await replacement).path, '/same');
});
test('a late dispatch failure cannot remove a replacement task', () async {
final dispatches = <Completer<void>>[];
final fileFetcher = FileFetcher(
() => _sessionId,
readRemoteDirectory: (_, __, ___) {
final dispatch = Completer<void>();
dispatches.add(dispatch);
return dispatch.future;
},
);
final first = fileFetcher.fetchDirectory('/same', false, false);
await Future<void>.delayed(Duration.zero);
final firstError = expectLater(first, throwsA(isA<StateError>()));
fileFetcher.beginRemoteSession();
await firstError;
final replacement = fileFetcher.fetchDirectory('/same', false, false);
await Future<void>.delayed(Duration.zero);
expect(dispatches, hasLength(2));
dispatches.first.completeError(StateError('late dispatch failure'));
await Future<void>.delayed(Duration.zero);
expect(fileFetcher.hasPendingRemoteRead('/same'), isTrue);
fileFetcher.tryCompleteTask(_directoryJson('/same'), 'false');
expect((await replacement).path, '/same');
dispatches.last.complete();
await Future<void>.delayed(Duration.zero);
});
test('navigation ignores stale directory responses', () async {
final fileFetcher = FileFetcher(
() => _sessionId,
@@ -0,0 +1,99 @@
@TestOn('browser')
import 'dart:async';
import 'dart:js' as js;
import 'package:flutter/material.dart';
import 'package:flutter_hbb/common/widgets/remote_input.dart';
import 'package:flutter_hbb/mobile/widgets/floating_mouse_widgets.dart';
import 'package:flutter_hbb/models/input_model.dart';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_test/flutter_test.dart';
class _Input extends Fake implements InputModel {
final events = <(String, MouseButtons)>[];
@override
Future<void> tapDown(MouseButtons button) async =>
events.add(('down', button));
@override
Future<void> tapUp(MouseButtons button) async => events.add(('up', button));
}
class _FFI extends Fake implements FFI {}
class _Cursor extends CursorModel {
_Cursor(FFI ffi) : super(WeakReference(ffi));
final syncs = <Completer<void>>[];
@override
Future<void> syncCursorPosition() {
final sync = Completer<void>();
syncs.add(sync);
return sync.future;
}
}
void main() {
setUp(() {
isSpecialHoldDragActive = false;
js.context['isMobile'] = js.allowInterop(() => true);
js.context['getByName'] =
js.allowInterop((String name, [String? key]) => '');
js.context['setByName'] = js.allowInterop((String name, dynamic value) {});
});
tearDown(() {
isSpecialHoldDragActive = false;
for (final name in ['isMobile', 'getByName', 'setByName']) {
js.context.deleteProperty(name);
}
});
for (final end in ['release', 'cancel', 'dispose']) {
testWidgets('pending hold cannot press after $end', (tester) async {
final cancel = end == 'cancel';
final ffi = _FFI();
final input = _Input();
final cursor = _Cursor(ffi);
final button = cancel ? MouseButtons.right : MouseButtons.left;
await tester.pumpWidget(MaterialApp(
home: Stack(children: [
FloatingLeftRightButton(
isLeft: !cancel, inputModel: input, cursorModel: cursor),
]),
));
await tester.pump();
final target = find.byType(FloatingLeftRightButton);
final first = await tester.startGesture(tester.getCenter(target));
await tester.pump(const Duration(milliseconds: 201));
expect(cursor.syncs, hasLength(1));
if (end == 'dispose') {
await tester.pumpWidget(const SizedBox());
cursor.syncs.single.complete();
await tester.pump(const Duration(milliseconds: 1));
expect(input.events, isEmpty);
return;
}
if (cancel) {
await first.cancel();
} else {
await first.up();
}
// A new press must not make the old synchronization valid again.
final second = await tester.startGesture(tester.getCenter(target));
await tester.pump(const Duration(milliseconds: 201));
cursor.syncs.first.complete();
await tester.pump();
expect(input.events, isEmpty);
cursor.syncs.last.complete();
await tester.pump();
expect(input.events, [('down', button)]);
await second.up();
expect(input.events, [('down', button), ('up', button)]);
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(milliseconds: 1));
expect(input.events, [('down', button), ('up', button)]);
});
}
}
+1 -319
View File
@@ -4,19 +4,6 @@ import 'package:flutter_hbb/models/input_modifier_utils.dart';
void main() {
group('shouldReleaseStaleMobileShift', () {
test('does not release when cached shift is already false', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: false,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('releases one-shot mobile shift after a text key', () {
expect(
shouldReleaseStaleMobileShift(
@@ -30,20 +17,6 @@ void main() {
);
});
test('does not release manually toggled shift without tracked key down',
() {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: false,
),
isFalse,
);
});
test('does not release when shift is still physically pressed', () {
expect(
shouldReleaseStaleMobileShift(
@@ -56,84 +29,9 @@ void main() {
isFalse,
);
});
test('does not release on non-mobile platforms', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: false,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.keyD,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('releases on enter key', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.enter,
hasTrackedShiftKeyDown: true,
),
isTrue,
);
});
test('releases on arrow key', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.arrowLeft,
hasTrackedShiftKeyDown: true,
),
isTrue,
);
});
test('does not release on modifier events', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.shiftLeft,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
test('does not release on shiftRight modifier events', () {
expect(
shouldReleaseStaleMobileShift(
isMobile: true,
cachedShiftPressed: true,
actualShiftPressed: false,
logicalKey: LogicalKeyboardKey.shiftRight,
hasTrackedShiftKeyDown: true,
),
isFalse,
);
});
});
group('shouldApplyTerminalInputModifiers', () {
test('accepts ordinary single-character keyboard input', () {
expect(shouldApplyTerminalInputModifiers('a'), isTrue);
expect(shouldApplyTerminalInputModifiers(' '), isTrue);
expect(shouldApplyTerminalInputModifiers('/'), isTrue);
});
test('accepts supplementary-plane single-character keyboard input', () {
expect(shouldApplyTerminalInputModifiers('😀'), isTrue);
});
test('rejects terminal control bytes and multi-character sequences', () {
for (final input in ['\x00', '\x03', '\t', '\n', '\r', '\x1B', '\x7F']) {
expect(
@@ -147,43 +45,6 @@ void main() {
});
group('applyTerminalInputModifiers', () {
test('keeps decomposed graphemes intact under Ctrl', () {
const decomposedEAcute = 'e\u0301';
expect(
applyTerminalInputModifiers(
decomposedEAcute,
ctrlLocked: true,
altLocked: false,
),
decomposedEAcute,
);
});
test('keeps non-ASCII graphemes intact under Ctrl', () {
for (final input in ['é', '😀']) {
expect(
applyTerminalInputModifiers(
input,
ctrlLocked: true,
altLocked: false,
),
input,
);
}
});
test('maps Ctrl underscore to unit separator', () {
expect(
applyTerminalInputModifiers(
'_',
ctrlLocked: true,
altLocked: false,
),
'\x1F',
);
});
test('maps the complete Ctrl symbol range', () {
const mappings = {
'[': '\x1B',
@@ -219,22 +80,6 @@ void main() {
});
});
group('terminalPastePayload', () {
test('wraps paste text when bracketed paste mode is active', () {
expect(
terminalPastePayload('d', bracketedPasteMode: true),
'\x1B[200~d\x1B[201~',
);
});
test('keeps a lone newline unchanged when bracketed paste is disabled', () {
expect(
terminalPastePayload('\n', bracketedPasteMode: false),
'\n',
);
});
});
group('prepareTerminalInputPayload', () {
test('normalizes a mobile keyboard Enter to carriage return', () {
expect(
@@ -278,26 +123,9 @@ void main() {
);
});
test('keeps large keyboard payloads unchanged when modifiers are inactive',
() {
final payload = 'd' * (1024 * 1024);
expect(
prepareTerminalInputPayload(
payload,
source: TerminalInputSource.keyboard,
isMobileOrWebMobile: false,
bracketedPasteMode: false,
ctrlLocked: false,
altLocked: false,
),
payload,
);
});
test('keeps decomposed graphemes intact with locked keyboard modifiers',
() {
const decomposedEAcute = 'e\u0301';
const decomposedEAcute = 'é';
expect(
prepareTerminalInputPayload(
@@ -312,20 +140,6 @@ void main() {
);
});
test('preserves a lone pasted newline when modifiers are locked', () {
expect(
prepareTerminalInputPayload(
'\n',
source: TerminalInputSource.paste,
isMobileOrWebMobile: true,
bracketedPasteMode: false,
ctrlLocked: true,
altLocked: true,
),
'\n',
);
});
test('wraps paste without applying locked modifiers', () {
expect(
prepareTerminalInputPayload(
@@ -373,25 +187,6 @@ void main() {
);
});
test(
'keeps default xterm paste behavior when virtual modifiers are inactive',
() {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: false,
),
isFalse,
);
});
test('handles Ctrl+V and Meta+V when a virtual modifier lock is active',
() {
expect(
@@ -423,95 +218,6 @@ void main() {
isTrue,
);
});
test('handles paste shortcut repeats while a virtual lock is active', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: false,
isKeyRepeat: true,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isTrue,
);
});
test('ignores key-up and unmodified V events', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: false,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: false,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
});
test('ignores paste shortcuts with extra modifiers', () {
for (final state in [
(control: true, meta: false, alt: true, shift: false),
(control: true, meta: false, alt: false, shift: true),
(control: false, meta: true, alt: false, shift: true),
(control: true, meta: true, alt: false, shift: false),
]) {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyV,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: state.control,
metaPressed: state.meta,
altPressed: state.alt,
shiftPressed: state.shift,
modifierLockActive: true,
),
isFalse,
);
}
});
test('ignores non-V key events', () {
expect(
shouldHandleTerminalPasteShortcut(
platform: TargetPlatform.windows,
logicalKey: LogicalKeyboardKey.keyC,
isKeyDown: true,
isKeyRepeat: false,
controlPressed: true,
metaPressed: false,
altPressed: false,
shiftPressed: false,
modifierLockActive: true,
),
isFalse,
);
});
});
group('shouldClearTerminalModifiersWhenRow3Collapses', () {
@@ -526,29 +232,5 @@ void main() {
isTrue,
);
});
test('does not clear modifiers when row expands', () {
expect(
shouldClearTerminalModifiersWhenRow3Collapses(
wasExpanded: false,
willExpand: true,
ctrlLocked: true,
altLocked: true,
),
isFalse,
);
});
test('clears Alt state when expanded row is collapsed', () {
expect(
shouldClearTerminalModifiersWhenRow3Collapses(
wasExpanded: true,
willExpand: false,
ctrlLocked: false,
altLocked: true,
),
isTrue,
);
});
});
}
@@ -50,54 +50,20 @@ void main() {
await tester.pump();
}
for (final trackpad in [false, true]) {
final device = trackpad ? 'trackpad' : 'wheel';
testWidgets('alternate screen reports $device after main-screen history',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
final render = view.renderTerminal;
final point = render.localToGlobal(
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
if (trackpad) {
await scrollTrackpad(tester, point, render.lineHeight * 3);
} else {
await tester.sendEventToBinding(PointerScrollEvent(
position: point,
scrollDelta: Offset(0, -render.lineHeight * 3),
));
await tester.pump();
}
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[<64;3;2M'));
expect(view.widget.scrollController!.offset, 0);
expect(controller.selection, isNull);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
}
testWidgets('trackpad scrolling keeps subsequent drag coordinates aligned',
testWidgets('alternate screen reports trackpad after main-screen history',
(tester) async {
final view = await mount(tester);
terminal.write('\x1b[?1049h$_captureMouse');
await tester.pump();
final render = view.renderTerminal;
final start = render.localToGlobal(
final point = render.localToGlobal(
Offset(render.cellSize.width * 2.5, render.lineHeight * 1.5));
final end = render.localToGlobal(
Offset(render.cellSize.width * 6.5, render.lineHeight * 2.5));
await scrollTrackpad(tester, start, render.lineHeight * 3);
output.clear();
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.down(start);
await mouse.moveTo(end);
await mouse.up();
await tester.pump(kDoubleTapTimeout);
await scrollTrackpad(tester, point, render.lineHeight * 3);
expect(output, ['\x1b[<0;3;2M', '\x1b[<32;7;3M', '\x1b[<0;7;3m']);
expect(output, isNotEmpty);
expect(output, everyElement('\x1b[<64;3;2M'));
expect(view.widget.scrollController!.offset, 0);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isFalse);
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
testWidgets('leaving alternate screen restores local trackpad scrollback',
@@ -17,24 +17,5 @@ void main() {
['Ctrl', 'Alt', '-', 'PgUp', 'PgDn'],
);
});
test('keeps two trailing Row3 placeholders for row alignment', () {
expect(terminalKeyboardRow3TrailingPlaceholderCount, 2);
});
test('keeps every expanded row aligned at 348dp', () {
final rowWidths = [
terminalKeyboardRowWidth(terminalKeyboardRow1Keys.length),
terminalKeyboardRowWidth(terminalKeyboardRow2Keys.length + 1),
terminalKeyboardRowWidth(
terminalKeyboardRow3Keys.length +
terminalKeyboardRow3TrailingPlaceholderCount,
),
];
expect(terminalKeyboardKeyWidth, 48);
expect(terminalKeyboardKeySpacing, 2);
expect(rowWidths, everyElement(348));
});
});
}
@@ -1,5 +1,3 @@
import 'dart:async';
import 'package:flutter_hbb/models/model.dart';
import 'package:flutter_hbb/models/terminal_model.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -14,42 +12,6 @@ class _FakeFFI implements FFI {
}
void main() {
test('ignores paste that completes after the terminal model is disposed',
() async {
final model = TerminalModel(_FakeFFI());
final delayedClipboardText = Completer<String>();
// This mirrors Ctrl/Cmd+V: clipboard access starts first, then the page and
// model are disposed before the asynchronous read supplies its text.
final paste = delayedClipboardText.future.then(model.pasteText);
model.dispose();
delayedClipboardText.complete('late clipboard text');
await paste;
expect(model.debugBufferedInputCount, 0);
});
test('ignores terminal text input after the terminal model is disposed', () {
final model = TerminalModel(_FakeFFI());
var checkedCtrlLock = false;
var clearedCtrlLock = false;
model.isCtrlLocked = () {
checkedCtrlLock = true;
return true;
};
model.clearCtrlLock = () {
clearedCtrlLock = true;
};
model.dispose();
model.terminal.textInput('d');
expect(checkedCtrlLock, isFalse);
expect(clearedCtrlLock, isFalse);
expect(model.debugBufferedInputCount, 0);
});
test('builds its terminal with the wheel button fix', () {
final model = TerminalModel(_FakeFFI());
addTearDown(model.dispose);
+1 -95
View File
@@ -71,10 +71,9 @@ void main() {
String? report(
TerminalMouseButton button, [
TerminalMouseButtonState state = TerminalMouseButtonState.down,
CellOffset position = const CellOffset(10, 5),
]) {
output.clear();
terminal.mouseInput(button, state, position);
terminal.mouseInput(button, state, const CellOffset(10, 5));
return output.isEmpty ? null : output.single;
}
@@ -102,40 +101,6 @@ void main() {
);
});
test('reports utf-encoding wheel buttons beyond the normal-mode range', () {
terminal.write('\x1b[?1000h\x1b[?1005h');
expect(
report(
TerminalMouseButton.wheelDown,
TerminalMouseButtonState.down,
const CellOffset(400, 300),
),
'\x1b[M${String.fromCharCode(32 + 65)}'
'${String.fromCharCode(32 + 401)}${String.fromCharCode(32 + 301)}',
);
});
test('reports urxvt-encoding wheel buttons shifted by 32', () {
terminal.write('\x1b[?1000h\x1b[?1015h');
expect(report(TerminalMouseButton.wheelUp), '\x1b[96;11;6M');
expect(report(TerminalMouseButton.wheelDown), '\x1b[97;11;6M');
});
test('sends a null byte for coordinates past the encoding limit', () {
terminal.write('\x1b[?1000h');
expect(
report(
TerminalMouseButton.wheelUp,
TerminalMouseButtonState.down,
const CellOffset(300, 300),
),
'\x1b[M${String.fromCharCode(32 + 64)}\x00\x00',
);
});
test('leaves non-wheel buttons to the upstream handler', () {
terminal.write('\x1b[?1000h\x1b[?1006h');
@@ -147,27 +112,6 @@ void main() {
);
});
test('stays silent when the peer has not enabled mouse reporting', () {
expect(report(TerminalMouseButton.wheelDown), isNull);
expect(report(TerminalMouseButton.left), isNull);
});
test('stays silent for the wheel in click-only mode', () {
terminal.write('\x1b[?9h\x1b[?1006h');
expect(report(TerminalMouseButton.wheelDown), isNull);
expect(report(TerminalMouseButton.left), '\x1b[<0;11;6M');
});
test('does not report wheel button releases', () {
terminal.write('\x1b[?1000h\x1b[?1006h');
expect(
report(TerminalMouseButton.wheelDown, TerminalMouseButtonState.up),
isNull,
);
});
testWidgets('dragging below scrolls and extends selection', (tester) async {
final controller = TerminalController();
_writeLines(terminal, 80);
@@ -258,42 +202,4 @@ void main() {
expect(output.last, '\x1b[<0;${endCell.x + 1};${endCell.y + 1}m');
expect(controller.suspendedPointerInputs, isFalse);
});
testWidgets('tmux drag stays suppressed after mouse mode is disabled',
(tester) async {
final controller = TerminalController();
terminal.write('\x1b[?1049h\x1b[?1002h\x1b[?1006hword');
await tester.pumpWidget(_terminalHarness(terminal, controller));
final renderTerminal = tester
.state<TerminalViewState>(find.byType(TerminalView))
.renderTerminal;
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
final start = renderTerminal.localToGlobal(const Offset(40, 40));
final end = renderTerminal.localToGlobal(const Offset(240, 80));
await mouse.down(start);
output.clear();
terminal.write('\x1b[?1002l');
await mouse.moveTo(end);
expect(output, isEmpty);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isTrue);
terminal.write('\x1b[?1002h');
await mouse.moveTo(start);
expect(output, isEmpty);
expect(controller.selection, isNull);
await mouse.up();
expect(output, isEmpty);
expect(controller.suspendedPointerInputs, isFalse);
await mouse.down(start);
output.clear();
terminal.write('\x1b[?1002l');
await mouse.up();
await tester.pump(kDoubleTapTimeout);
expect(output, isEmpty);
expect(controller.selection, isNull);
expect(controller.suspendedPointerInputs, isFalse);
});
}
+4
View File
@@ -10,6 +10,7 @@
#include "win32_desktop.h"
#include "flutter_window.h"
#include "utils.h"
#include "service_control.h"
typedef char** (*FUNC_RUSTDESK_CORE_MAIN)(int*);
typedef void (*FUNC_RUSTDESK_FREE_ARGS)( char**, int);
@@ -23,6 +24,9 @@ const wchar_t* getWindowClassName();
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command)
{
if (auto result = service_control::HandleCommand(command_line)) {
return static_cast<int>(*result);
}
HINSTANCE hInstance = LoadLibraryA("librustdesk.dll");
if (!hInstance)
{
+183
View File
@@ -0,0 +1,183 @@
#ifndef RUSTDESK_RUNNER_SERVICE_CONTROL_H_
#define RUSTDESK_RUNNER_SERVICE_CONTROL_H_
#include <windows.h>
#include <shellapi.h>
#include <winsvc.h>
#include <cstdio>
#include <cwchar>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
namespace service_control {
using ServiceHandle = std::unique_ptr<std::remove_pointer_t<SC_HANDLE>,
decltype(&CloseServiceHandle)>;
constexpr DWORD kStopTimeoutMilliseconds = 30000;
constexpr DWORD kPollIntervalMilliseconds = 100;
inline DWORD StopService(SC_HANDLE service) {
SERVICE_STATUS_PROCESS status{};
DWORD bytes_needed = 0;
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
reinterpret_cast<BYTE*>(&status), sizeof(status),
&bytes_needed)) {
return GetLastError();
}
if (status.dwCurrentState == SERVICE_STOPPED) {
return ERROR_SUCCESS;
}
if (status.dwCurrentState != SERVICE_STOP_PENDING) {
SERVICE_STATUS stopped{};
if (!ControlService(service, SERVICE_CONTROL_STOP, &stopped)) {
const DWORD error = GetLastError();
return error == ERROR_SERVICE_NOT_ACTIVE ? ERROR_SUCCESS : error;
}
}
// The installer may remove files next; accepting STOP alone does not mean
// the service has reached SERVICE_STOPPED.
const ULONGLONG started = GetTickCount64();
while (status.dwCurrentState != SERVICE_STOPPED) {
if (GetTickCount64() - started >= kStopTimeoutMilliseconds) {
return ERROR_TIMEOUT;
}
Sleep(kPollIntervalMilliseconds);
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
reinterpret_cast<BYTE*>(&status), sizeof(status),
&bytes_needed)) {
return GetLastError();
}
}
return ERROR_SUCCESS;
}
inline DWORD RemoveService(const wchar_t* name) {
ServiceHandle manager(OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT),
CloseServiceHandle);
if (!manager) {
return GetLastError();
}
ServiceHandle service(
OpenServiceW(manager.get(), name,
SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE),
CloseServiceHandle);
if (!service) {
const DWORD error = GetLastError();
return error == ERROR_SERVICE_DOES_NOT_EXIST ? ERROR_SUCCESS : error;
}
const DWORD stopped = StopService(service.get());
if (stopped != ERROR_SUCCESS) {
// The uninstall script must still reach its taskkill cleanup.
std::fwprintf(stderr,
L"Service did not stop cleanly: Windows error %lu\n", stopped);
}
if (DeleteService(service.get())) {
return ERROR_SUCCESS;
}
const DWORD error = GetLastError();
return error == ERROR_SERVICE_MARKED_FOR_DELETE ? ERROR_SUCCESS : error;
}
inline DWORD InstallService(const wchar_t* name, const wchar_t* executable,
bool rollback_on_failure) {
if (!*executable || wcschr(executable, L'"')) {
return ERROR_INVALID_PARAMETER;
}
const std::wstring binary_path =
L"\"" + std::wstring(executable) + L"\" --service";
const std::wstring display_name = std::wstring(name) + L" Service";
ServiceHandle manager(
OpenSCManagerW(nullptr, nullptr,
SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE),
CloseServiceHandle);
if (!manager) {
return GetLastError();
}
ServiceHandle service(
CreateServiceW(manager.get(), name, display_name.c_str(),
SERVICE_START | DELETE, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
binary_path.c_str(), nullptr,
nullptr, nullptr, nullptr, nullptr),
CloseServiceHandle);
const bool created = service != nullptr;
// --after-install can reuse a registration. Preserve its executable and
// account, as the previous create-then-start script did.
if (!service && GetLastError() == ERROR_SERVICE_EXISTS) {
service.reset(OpenServiceW(manager.get(), name, SERVICE_START));
}
if (!service) {
return GetLastError();
}
if (StartServiceW(service.get(), 0, nullptr)) {
return ERROR_SUCCESS;
}
const DWORD error = GetLastError();
// Only manual Start Service restores stop-service=Y on failure. Other
// installation paths retain the registration for a later startup attempt.
if (rollback_on_failure && created && error != ERROR_SERVICE_ALREADY_RUNNING &&
!DeleteService(service.get())) {
const DWORD rollback_error = GetLastError();
std::fwprintf(stderr,
L"Failed to roll back newly created service: Windows error %lu\n",
rollback_error);
}
return error == ERROR_SERVICE_ALREADY_RUNNING ? ERROR_SUCCESS : error;
}
inline DWORD RunCommand(int count, wchar_t** args) {
constexpr int kRemoveArgumentCount = 4;
constexpr int kInstallArgumentCount = 5;
if (count < kRemoveArgumentCount) {
return ERROR_BAD_ARGUMENTS;
}
if (!*args[3]) {
return ERROR_INVALID_PARAMETER;
}
const std::wstring_view operation(args[2]);
const bool rollback_on_failure = operation == L"create-service-with-rollback";
if ((operation == L"create-service" || rollback_on_failure) &&
count == kInstallArgumentCount) {
return InstallService(args[3], args[4], rollback_on_failure);
}
if (operation == L"remove" && count == kRemoveArgumentCount) {
return RemoveService(args[3]);
}
return ERROR_BAD_ARGUMENTS;
}
// Keep these commands in the existing runner so installation/removal can control
// services before loading librustdesk.dll or initializing the UI. A Rust-side
// handler would first require that DLL to load. The header-only implementation
// keeps main.cpp as a dispatch hook without adding a CMake source entry; it is
// compiled into the existing EXE, not a separately packaged helper.
inline std::optional<DWORD> HandleCommand(const wchar_t* command_line) {
constexpr std::wstring_view option = L"--service-control";
const std::wstring_view arguments(command_line);
if (arguments.compare(0, option.size(), option) != 0 ||
(arguments.size() > option.size() && arguments[option.size()] != L' ' &&
arguments[option.size()] != L'\t')) {
return std::nullopt;
}
int count = 0;
wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
if (!args) {
return GetLastError();
}
const DWORD result = RunCommand(count, args);
LocalFree(args);
if (result != ERROR_SUCCESS) {
std::fwprintf(stderr,
L"RustDesk service control failed with Windows error %lu\n",
result);
}
return result;
}
} // namespace service_control
#endif // RUSTDESK_RUNNER_SERVICE_CONTROL_H_
+2
View File
@@ -1030,5 +1030,7 @@ message Message {
TerminalAction terminal_action = 31;
TerminalResponse terminal_response = 32;
PortForwardChannel port_forward_channel = 33;
// Auto Login: the peer types the password only if it is at its logon or lock screen.
OSLogin os_login = 34;
}
}
+1
View File
@@ -311,6 +311,7 @@ pub const KEYS_SETTINGS: &[&str] = &[
OPTION_API_SERVER,
OPTION_KEY,
OPTION_ALLOW_WEBSOCKET,
OPTION_WEBSOCKET_PORT,
OPTION_PRESET_ADDRESS_BOOK_NAME,
OPTION_PRESET_ADDRESS_BOOK_TAG,
OPTION_PRESET_ADDRESS_BOOK_ALIAS,
+37 -63
View File
@@ -27,6 +27,12 @@ use hbb_common::{
static NEXT_JOB_ID: AtomicI32 = AtomicI32::new(1);
pub mod download;
#[cfg(test)]
#[path = "fs/download_tests.rs"]
mod download_tests;
pub fn get_next_job_id() -> i32 {
NEXT_JOB_ID.fetch_add(1, Ordering::SeqCst)
}
@@ -417,6 +423,8 @@ pub struct TransferJob {
default_overwrite_strategy: Option<bool>,
#[serde(skip_serializing)]
digest: FileDigest,
#[serde(skip)]
download: Option<download::DownloadState>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
@@ -587,6 +595,7 @@ impl TransferJob {
files: Vec::new(),
total_size: 0,
enable_overwrite_detection,
download: (is_remote && r#type == JobType::Generic).then(Default::default),
..Default::default()
}
}
@@ -648,6 +657,9 @@ impl TransferJob {
#[inline]
pub fn set_files(&mut self, files: Vec<FileEntry>) -> ResultType<()> {
if self.is_download() && !self.files.is_empty() {
bail!("cannot replace an accepted download file list");
}
validate_transfer_file_names(&files)?;
if let DataSource::FilePath(base) = &self.data_source {
for file in &files {
@@ -692,7 +704,12 @@ impl TransferJob {
fn resolve_entry_path(&self, base: &PathBuf, name: &str) -> Option<PathBuf> {
if self.r#type == JobType::Generic {
match join_validated_path(base, name) {
let result = if self.is_download() {
download::validated_target(base, name)
} else {
join_validated_path(base, name)
};
match result {
Ok(path) => Some(path),
Err(err) => {
log::error!("Invalid file name in transfer job {}: {}", self.id, err);
@@ -705,6 +722,12 @@ impl TransferJob {
}
pub fn modify_time(&self) {
if self.is_download() {
if let Err(err) = self.finish_download() {
log::error!("Failed to finish download {}: {}", self.id, err);
}
return;
}
if self.r#type == JobType::Printer {
return;
}
@@ -729,6 +752,9 @@ impl TransferJob {
}
pub fn remove_download_file(&self) {
if self.is_download() && self.data_stream.is_none() {
return;
}
if self.r#type == JobType::Printer {
return;
}
@@ -761,6 +787,9 @@ impl TransferJob {
}
pub async fn write(&mut self, block: FileTransferBlock) -> ResultType<()> {
if self.is_download() {
return self.write_download(block).await;
}
if block.id != self.id {
bail!("Wrong id");
}
@@ -1160,6 +1189,13 @@ impl TransferJob {
}
pub async fn confirm(&mut self, r: &FileTransferSendConfirmRequest) -> bool {
if self.is_download() {
self.confirm_download(r);
// Open receiver resume streams in write() so validation errors reach the caller.
if matches!(r.union, Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) if offset > 0) {
return true;
}
}
if self.file_num() != r.file_num {
// This branch will always be hit if:
// 1. `confirm()` is called in `ui_cm_interface.rs`
@@ -1677,15 +1713,6 @@ mod tests {
assert_err_contains(err, "empty file name");
}
#[test]
fn set_files_rejects_null_byte_name() {
let mut job = new_validation_job(103);
let err = job
.set_files(vec![new_file_entry("bad\0name.txt")])
.expect_err("null byte in file name must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn set_files_rejects_mixed_entries_when_one_is_traversal() {
let mut job = new_validation_job(104);
@@ -1708,39 +1735,6 @@ mod tests {
assert_err_contains(err, "absolute path");
}
#[cfg(not(windows))]
#[test]
fn set_files_allows_backslash_prefixed_name_on_unix() {
let mut job = new_validation_job(105);
assert!(job
.set_files(vec![new_file_entry("\\\\server\\share\\payload.txt")])
.is_ok());
}
#[test]
fn remove_file_rejects_empty_path() {
let err = remove_file("").expect_err("empty file path must be rejected");
assert_err_contains(err, "cannot be empty");
}
#[test]
fn remove_file_rejects_null_byte_path() {
let err = remove_file("bad\0path").expect_err("null byte path must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn create_dir_rejects_empty_path() {
let err = create_dir("").expect_err("empty directory path must be rejected");
assert_err_contains(err, "cannot be empty");
}
#[test]
fn create_dir_rejects_null_byte_path() {
let err = create_dir("bad\0path").expect_err("null byte path must be rejected");
assert_err_contains(err, "null bytes");
}
#[test]
fn rename_file_rejects_invalid_new_name() {
let tmp_root = TestTempDir::new("rustdesk_rename_invalid");
@@ -1790,24 +1784,4 @@ mod tests {
assert!(!src.exists());
assert!(dst.exists());
}
#[cfg(windows)]
#[test]
fn set_files_rejects_windows_drive_absolute_path() {
let mut job = new_validation_job(106);
let err = job
.set_files(vec![new_file_entry("C:\\Windows\\Temp\\payload.txt")])
.expect_err("drive-letter absolute path must be rejected");
assert_err_contains(err, "absolute path");
}
#[cfg(windows)]
#[test]
fn set_files_rejects_windows_verbatim_drive_absolute_path() {
let mut job = new_validation_job(1061);
let err = job
.set_files(vec![new_file_entry(r"\\?\C:\Windows\Temp\x.txt")])
.expect_err("verbatim drive absolute path must be rejected");
assert_err_contains(err, "absolute path");
}
}
+331
View File
@@ -0,0 +1,331 @@
use super::{
get_string, is_write_need_confirmation, join_validated_path, validate_file_name_no_traversal,
validate_no_symlink_components, DataSource, DataStream, DigestCheckResult, TransferJob,
};
use crate::message_proto::{
file_transfer_send_confirm_request, FileEntry, FileTransferBlock, FileTransferDigest,
FileTransferSendConfirmRequest, FileType,
};
use hbb_common::{anyhow::anyhow, bail, compress::decompress, ResultType};
use std::{
borrow::Cow,
io::ErrorKind,
path::{Path, PathBuf},
};
use tokio::{
fs::{self, OpenOptions},
io::{AsyncSeekExt, AsyncWriteExt},
};
const SINGLE_LINK_COUNT: u64 = 1;
#[derive(Default, Debug)]
pub(super) struct DownloadState {
pub(super) confirmation: Option<(i32, u32)>,
}
pub fn validate_listing(entries: &[FileEntry], peer_windows: bool) -> ResultType<()> {
for entry in entries {
let name = &entry.name;
if entry.entry_type.enum_value() == Ok(FileType::DirDrive)
&& matches!(name.as_bytes(), [drive, b':'] if drive.is_ascii_alphabetic())
{
continue;
}
if name.is_empty()
|| name == "."
|| name == ".."
|| name.contains('\0')
|| name.contains('/')
|| (peer_windows
&& (name.contains('\\')
|| matches!(name.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic())))
{
bail!("invalid file name in remote directory listing: {name}");
}
}
Ok(())
}
pub fn validate_download_name(path: &str, peer_windows: bool) -> ResultType<()> {
let separator = |c| c == '/' || (peer_windows && c == '\\');
let path = path.trim_end_matches(separator);
validate_component(path.rsplit(separator).next().unwrap_or(""))
}
fn validate_component(name: &str) -> ResultType<()> {
validate_file_name_no_traversal(name)?;
if name.is_empty() || name == "." || name.contains('/') {
bail!("invalid download file name: {name}");
}
#[cfg(windows)]
if name.contains(['\\', ':', '<', '>', '"', '|', '?', '*'])
|| name.ends_with('.')
|| name.ends_with(' ')
{
bail!("invalid Windows download file name: {name}");
}
Ok(())
}
pub(super) fn validated_target(base: &PathBuf, name: &str) -> ResultType<PathBuf> {
let parent = base
.parent()
.ok_or_else(|| anyhow!("download destination has no parent"))?;
let leaf = base
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| anyhow!("invalid download destination"))?;
validate_component(leaf)?;
#[cfg(windows)]
for component in name.split(['/', '\\']).filter(|part| !part.is_empty()) {
validate_component(component)?;
}
validate_no_symlink_components(&parent.to_path_buf(), leaf)?;
let target = join_validated_path(base, name)?;
let parent = target
.parent()
.ok_or_else(|| anyhow!("download file has no parent"))?;
let leaf = target
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| anyhow!("invalid download file name"))?;
for suffix in ["download", "digest"] {
validate_no_symlink_components(&parent.to_path_buf(), &format!("{leaf}.{suffix}"))?;
}
Ok(target)
}
fn remove_if_exists(path: &Path) -> ResultType<()> {
match std::fs::remove_file(path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
async fn remove_if_exists_async(path: &Path) -> ResultType<()> {
match fs::remove_file(path).await {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
async fn validate_resume_file(file: &tokio::fs::File) -> ResultType<()> {
let metadata = file.metadata().await?;
if !metadata.is_file() {
bail!("download resume staging path is not a regular file");
}
#[cfg(unix)]
let links = std::os::unix::fs::MetadataExt::nlink(&metadata);
#[cfg(windows)]
let links = {
use std::{mem::MaybeUninit, os::windows::io::AsRawHandle};
use winapi::{
shared::minwindef::FALSE,
um::fileapi::{GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION},
};
let file = file.try_clone().await?;
tokio::task::spawn_blocking(move || -> ResultType<u64> {
let mut information = MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
if unsafe {
GetFileInformationByHandle(file.as_raw_handle() as _, information.as_mut_ptr())
} == FALSE
{
return Err(std::io::Error::last_os_error().into());
}
Ok(u64::from(
unsafe { information.assume_init() }.nNumberOfLinks,
))
})
.await??
};
if links != SINGLE_LINK_COUNT {
bail!("hard-linked download resume staging file is not allowed");
}
Ok(())
}
impl TransferJob {
pub(super) fn is_download(&self) -> bool {
self.download.is_some()
}
pub fn download_target(&self, file_num: i32) -> ResultType<PathBuf> {
let entry = self
.files
.get(file_num as usize)
.ok_or_else(|| anyhow!("Wrong file number"))?;
let DataSource::FilePath(base) = &self.data_source else {
bail!("download destination is not a file path");
};
validated_target(base, &entry.name)
}
pub fn download_digest(
&mut self,
can_resume: bool,
digest: &FileTransferDigest,
) -> ResultType<DigestCheckResult> {
if self.file_num != digest.file_num && self.data_stream.is_some() {
let result = self.finish_download();
self.data_stream.take();
result?;
}
let target = self.download_target(digest.file_num)?;
let resume = can_resume && self.is_resume && !target.try_exists()?;
let result = is_write_need_confirmation(resume, &get_string(&target), digest)?;
if matches!(result, DigestCheckResult::NoSuchFile)
&& (Path::new(&format!("{}.download", target.display())).try_exists()?
|| Path::new(&format!("{}.digest", target.display())).try_exists()?)
{
return Ok(DigestCheckResult::NeedConfirm(FileTransferDigest {
id: digest.id,
file_num: digest.file_num,
..Default::default()
}));
}
Ok(result)
}
pub(super) fn confirm_download(&mut self, request: &FileTransferSendConfirmRequest) {
if request.id != self.id {
return;
}
let Some(download) = self.download.as_mut() else {
return;
};
download.confirmation = self.files.get(request.file_num as usize).and_then(|_| {
let offset = match request.union {
Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)) => offset,
Some(file_transfer_send_confirm_request::Union::Skip(false)) => 0,
_ => return None,
};
Some((request.file_num, offset))
});
}
fn download_confirmation_offset(&self, file_num: i32) -> Option<u32> {
let (confirmed, offset) = self.download.as_ref()?.confirmation.as_ref()?;
(*confirmed == file_num).then_some(*offset)
}
async fn start_download_file(&mut self, file_num: i32) -> ResultType<()> {
let result = self.finish_download();
self.data_stream.take();
result?;
let target = self.download_target(file_num)?;
let staging = PathBuf::from(format!("{}.download", target.display()));
let digest = PathBuf::from(format!("{}.digest", target.display()));
let confirmation = self.download_confirmation_offset(file_num);
if (fs::try_exists(&target).await?
|| fs::try_exists(&staging).await?
|| fs::try_exists(&digest).await?)
&& confirmation.is_none()
{
bail!("download overwrite requires confirmation");
}
if let Some(offset) = confirmation.filter(|offset| *offset > 0) {
return self.resume_download(file_num, offset).await;
}
if let Some(parent) = target.parent() {
fs::create_dir_all(parent).await?;
}
remove_if_exists_async(&staging).await?;
let file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&staging)
.await?;
self.file_num = file_num;
self.data_stream = Some(DataStream::FileStream(file));
remove_if_exists_async(&digest).await?;
let mut metadata = OpenOptions::new()
.write(true)
.create_new(true)
.open(&digest)
.await?;
metadata
.write_all(serde_json::to_string(&self.digest)?.as_bytes())
.await?;
metadata.flush().await?;
Ok(())
}
async fn resume_download(&mut self, file_num: i32, offset: u32) -> ResultType<()> {
let target = self.download_target(file_num)?;
if fs::try_exists(&target).await? {
bail!("download overwrite requires confirmation");
}
let digest = fs::metadata(format!("{}.digest", target.display())).await?;
if !digest.is_file() {
bail!("download resume metadata is not a regular file");
}
let mut file = OpenOptions::new()
.write(true)
.open(format!("{}.download", target.display()))
.await?;
validate_resume_file(&file).await?;
if file.metadata().await?.len() != u64::from(offset) {
bail!("download resume offset does not match staging file size");
}
file.seek(std::io::SeekFrom::Start(u64::from(offset)))
.await?;
self.file_num = file_num;
self.data_stream = Some(DataStream::FileStream(file));
self.transferred += u64::from(offset);
self.finished_size += u64::from(offset);
Ok(())
}
pub(super) async fn write_download(&mut self, block: FileTransferBlock) -> ResultType<()> {
if block.id != self.id {
bail!("Wrong id");
}
if block.file_num as usize >= self.files.len() {
bail!("Wrong file number");
}
if block.file_num != self.file_num || self.data_stream.is_none() {
self.start_download_file(block.file_num).await?;
}
let data = if block.compressed {
Cow::Owned(decompress(&block.data))
} else {
Cow::Borrowed(block.data.as_ref())
};
let Some(DataStream::FileStream(stream)) = self.data_stream.as_mut() else {
bail!("download file stream is missing");
};
stream.write_all(&data).await?;
stream.flush().await?;
self.finished_size += data.len() as u64;
self.transferred += block.data.len() as u64;
Ok(())
}
pub fn finish_download(&self) -> ResultType<()> {
if !self.is_download() {
self.modify_time();
return Ok(());
}
if self.data_stream.is_none() {
return Ok(());
}
let target = self.download_target(self.file_num)?;
if target.try_exists()? && self.download_confirmation_offset(self.file_num) != Some(0) {
bail!("download overwrite requires confirmation");
}
std::fs::rename(format!("{}.download", target.display()), &target)?;
remove_if_exists(&PathBuf::from(format!("{}.digest", target.display())))?;
let entry = self
.files
.get(self.file_num as usize)
.ok_or_else(|| anyhow!("Wrong file number"))?;
filetime::set_file_mtime(
&target,
filetime::FileTime::from_unix_time(entry.modified_time as _, 0),
)?;
Ok(())
}
}
+324
View File
@@ -0,0 +1,324 @@
use super::*;
struct DownloadDir(PathBuf);
impl DownloadDir {
fn new() -> Self {
static NEXT_DIRECTORY: AtomicI32 = AtomicI32::new(1);
let sequence = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rustdesk_download_{}_{nonce}_{sequence}",
std::process::id()
));
std::fs::create_dir(&path).unwrap();
Self(path)
}
fn job(&self) -> TransferJob {
self.job_with_files(vec![FileEntry::default()])
}
fn job_with_files(&self, files: Vec<FileEntry>) -> TransferJob {
TransferJob::new_write(
1,
JobType::Generic,
"/remote/file.txt".into(),
DataSource::FilePath(self.0.join("file.txt")),
0,
false,
true,
true,
)
.with_files(files)
.unwrap()
}
}
impl Drop for DownloadDir {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
fn block() -> FileTransferBlock {
FileTransferBlock {
id: 1,
file_num: 0,
data: b"received".to_vec().into(),
..Default::default()
}
}
fn approval(file_num: i32, offset: u32) -> FileTransferSendConfirmRequest {
FileTransferSendConfirmRequest {
id: 1,
file_num,
union: Some(file_transfer_send_confirm_request::Union::OffsetBlk(offset)),
..Default::default()
}
}
#[test]
fn download_listing_rejects_unsafe_names_and_keeps_drive_rows() {
for name in ["../outside", "/outside", ".", "..", "", "dir/file"] {
let entry = FileEntry {
name: name.into(),
..Default::default()
};
assert!(
download::validate_listing(&[entry], false).is_err(),
"{}",
name
);
}
let entries = [
FileEntry {
name: "report.txt".into(),
..Default::default()
},
FileEntry {
name: "report:notes".into(),
..Default::default()
},
FileEntry {
name: "C:".into(),
entry_type: FileType::DirDrive.into(),
..Default::default()
},
];
download::validate_listing(&entries, true).unwrap();
}
#[tokio::test]
async fn download_requires_confirmation_to_overwrite() {
let dir = DownloadDir::new();
let target = dir.0.join("file.txt");
std::fs::write(&target, b"original").unwrap();
let mut job = dir.job();
assert!(job.write(block()).await.is_err());
assert_eq!(std::fs::read(&target).unwrap(), b"original");
assert!(!dir.0.join("file.txt.download").exists());
job.confirm(&approval(0, 0)).await;
job.write(block()).await.unwrap();
assert!(job.set_files(vec![FileEntry::default()]).is_err());
job.finish_download().unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"received");
}
#[tokio::test]
async fn download_requires_separate_confirmation_for_each_existing_file() {
let dir = DownloadDir::new();
let mut job = dir.job_with_files(vec![
FileEntry {
name: "first.txt".into(),
..Default::default()
},
FileEntry {
name: "second.txt".into(),
..Default::default()
},
]);
job.write(block()).await.unwrap();
let second = dir.0.join("file.txt/second.txt");
std::fs::write(&second, b"original").unwrap();
assert!(job
.write(FileTransferBlock {
file_num: 1,
..block()
})
.await
.is_err());
assert_eq!(std::fs::read(&second).unwrap(), b"original");
assert_eq!(
std::fs::read(dir.0.join("file.txt/first.txt")).unwrap(),
b"received"
);
job.confirm(&approval(1, 0)).await;
job.write(FileTransferBlock {
file_num: 1,
..block()
})
.await
.unwrap();
job.finish_download().unwrap();
assert_eq!(std::fs::read(&second).unwrap(), b"received");
}
#[tokio::test]
async fn download_preserves_received_files_when_publication_fails() {
for next_is_digest in [false, true] {
let dir = DownloadDir::new();
let files = ["first.txt", "second.txt"]
.iter()
.map(|&name| FileEntry {
name: name.into(),
..Default::default()
})
.collect();
let mut job = dir.job_with_files(files);
job.write(block()).await.unwrap();
let target = dir.0.join("file.txt/first.txt");
std::fs::write(&target, b"existing").unwrap();
if next_is_digest {
assert!(job
.download_digest(
true,
&FileTransferDigest {
id: 1,
file_num: 1,
..Default::default()
},
)
.is_err());
} else {
assert!(job
.write(FileTransferBlock {
file_num: 1,
..block()
})
.await
.is_err());
}
job.remove_download_file();
assert_eq!(std::fs::read(target).unwrap(), b"existing");
assert_eq!(
std::fs::read(dir.0.join("file.txt/first.txt.download")).unwrap(),
b"received"
);
assert!(dir.0.join("file.txt/first.txt.digest").exists());
}
}
#[tokio::test]
async fn download_recovers_interrupted_transfer() {
for (resuming, changed) in [(false, false), (true, true), (true, false)] {
let dir = DownloadDir::new();
let mut digest = FileTransferDigest {
id: 1,
file_size: block().data.len() as _,
last_modified: 1,
..Default::default()
};
let mut interrupted = dir.job();
interrupted.set_digest(digest.file_size, digest.last_modified);
let partial = FileTransferBlock {
data: b"rec".to_vec().into(),
..block()
};
interrupted.write(partial).await.unwrap();
drop(interrupted);
let mut job = dir.job();
job.is_resume = resuming;
digest.last_modified += u64::from(changed);
job.set_digest(digest.file_size, digest.last_modified);
let confirmation = match job.download_digest(true, &digest).unwrap() {
DigestCheckResult::NeedConfirm(confirmation) => confirmation,
_ => panic!("interrupted download must require confirmation"),
};
let offset = if resuming && !changed {
b"rec".len()
} else {
0
};
assert_eq!(confirmation.is_identical, offset > 0);
assert_eq!(confirmation.transferred_size, offset as u64);
assert!(job.write(block()).await.is_err());
assert_eq!(
std::fs::read(dir.0.join("file.txt.download")).unwrap(),
b"rec"
);
job.confirm(&approval(0, offset as _)).await;
job.write(FileTransferBlock {
data: block().data.slice(offset..),
..block()
})
.await
.unwrap();
job.finish_download().unwrap();
assert_eq!(std::fs::read(dir.0.join("file.txt")).unwrap(), b"received");
}
}
#[tokio::test]
async fn download_does_not_publish_or_remove_unreceived_staging_files() {
let dir = DownloadDir::new();
let target = dir.0.join("file.txt");
let staging = dir.0.join("file.txt.download");
std::fs::write(&target, b"original").unwrap();
std::fs::write(&staging, b"another transfer").unwrap();
let job = dir.job();
job.modify_time();
job.remove_download_file();
assert_eq!(std::fs::read(&target).unwrap(), b"original");
assert_eq!(std::fs::read(&staging).unwrap(), b"another transfer");
let metadata_only = DownloadDir::new();
let metadata = metadata_only.0.join("file.txt.digest");
std::fs::write(&metadata, b"unrelated file").unwrap();
assert!(metadata_only.job().write(block()).await.is_err());
assert_eq!(std::fs::read(metadata).unwrap(), b"unrelated file");
}
#[test]
#[cfg(windows)]
fn download_rejects_windows_streams_and_ambiguous_components() {
let dir = DownloadDir::new();
for name in ["nested/file:stream", "nested/.. /outside", "nested/file."] {
assert!(
download::validated_target(&dir.0.join("docs"), name).is_err(),
"{}",
name
);
}
}
#[tokio::test]
#[cfg_attr(windows, ignore = "requires symlink privilege")]
async fn download_refuses_symlink_destination_directory() {
let dir = DownloadDir::new();
let outside = dir.0.join("outside");
let link = dir.0.join("file.txt");
std::fs::create_dir_all(&outside).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_dir(&outside, &link).unwrap();
let mut job = dir.job_with_files(vec![FileEntry {
name: "child.txt".into(),
..Default::default()
}]);
assert!(job.write(block()).await.is_err());
job.modify_time();
assert!(!outside.join("child.txt").exists());
assert!(!outside.join("child.txt.download").exists());
}
#[tokio::test]
#[cfg_attr(windows, ignore = "requires symlink privilege")]
async fn download_refuses_linked_target_and_staging_files() {
for suffix in ["", ".download", ".digest"] {
let dir = DownloadDir::new();
let outside = dir.0.join("outside.txt");
let link = dir.0.join(format!("file.txt{suffix}"));
std::fs::write(&outside, b"original").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_file(&outside, &link).unwrap();
let mut job = dir.job();
assert!(job.write(block()).await.is_err());
job.modify_time();
job.remove_download_file();
assert_eq!(std::fs::read(&outside).unwrap(), b"original");
assert!(std::fs::symlink_metadata(link)
.unwrap()
.file_type()
.is_symlink());
}
}
-56
View File
@@ -515,48 +515,6 @@ pub fn get_home_dir_trusted() -> Option<PathBuf> {
mod tests {
use super::*;
#[test]
fn test_transform_degrees_maps_all_eight_variants() {
use sctk::reexports::client::protocol::wl_output::Transform;
// Flipped variants report their rotation: the frame still needs that turn to read
// upright, and the mirror half has no producer among desktop compositors to test.
for (t, deg) in [
(Transform::Normal, 0),
(Transform::_90, 90),
(Transform::_180, 180),
(Transform::_270, 270),
(Transform::Flipped, 0),
(Transform::Flipped90, 90),
(Transform::Flipped180, 180),
(Transform::Flipped270, 270),
] {
assert_eq!(transform_degrees(t), deg, "{t:?}");
}
}
#[test]
fn test_display_info_without_transform_defaults_to_zero() {
// A snapshot serialized by an older probe child carries no transform field; it must
// deserialize with 0 rather than fail, or a greeter-side child update becomes a
// lockstep upgrade.
let old = r#"{"name":"HDMI-1","x":0,"y":0,"width":1920,"height":1080,"logical_size":null,"refresh_rate":60}"#;
let info: WaylandDisplayInfo = serde_json::from_str(old).unwrap();
assert_eq!(info.transform, 0);
let roundtrip: WaylandDisplayInfo =
serde_json::from_str(&serde_json::to_string(&info).unwrap()).unwrap();
assert_eq!(roundtrip.transform, 0);
}
#[test]
fn test_run_cmds_trim_newline() {
assert_eq!(run_cmds_trim_newline("echo -n 123").unwrap(), "123");
assert_eq!(run_cmds_trim_newline("echo 123").unwrap(), "123");
assert_eq!(
run_cmds_trim_newline("whoami").unwrap() + "\n",
run_cmds("whoami").unwrap()
);
}
/// Test get_home_dir_trusted: returns valid path and ignores HOME env var
#[test]
fn test_get_home_dir_trusted() {
@@ -584,20 +542,6 @@ mod tests {
}
}
/// Test shell_quote with normal strings
#[test]
fn test_shell_quote_normal() {
assert_eq!(shell_quote("hello"), "'hello'");
assert_eq!(shell_quote("/home/user"), "'/home/user'");
}
/// Test shell_quote with spaces
#[test]
fn test_shell_quote_spaces() {
assert_eq!(shell_quote("/home/my user/file"), "'/home/my user/file'");
assert_eq!(shell_quote("path with spaces"), "'path with spaces'");
}
/// Test shell_quote with single quotes (the tricky case)
#[test]
fn test_shell_quote_single_quotes() {
-8
View File
@@ -288,11 +288,3 @@ fn send_data_to_all(data: ClipboardFile) {
allow_err!(msg_channel.sender.send(data.clone()));
}
}
#[cfg(test)]
mod tests {
// #[test]
// fn test_cliprdr_run() {
// super::cliprdr_run();
// }
}
@@ -244,8 +244,6 @@ mod tests {
const ATTRIBUTES_OFFSET: usize = PDU_HEADER_SIZE + 36;
const LAST_WRITE_TIME_OFFSET: usize = PDU_HEADER_SIZE + 56;
const NAME_OFFSET: usize = PDU_HEADER_SIZE + 72;
const FILE_NAME_CODE_UNITS: usize = 260;
const INVALID_UTF16_UNIT: u16 = 0xdc00;
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
fn descriptor_pdu(name: &str) -> Vec<u8> {
@@ -291,18 +289,6 @@ mod tests {
assert_eq!(files[0].name, PathBuf::from("folder/nested/file.txt"));
}
#[test]
fn ignores_data_after_null_terminator() {
let name = "file.txt";
let mut pdu = descriptor_pdu(name);
let padding_offset = NAME_OFFSET + (name.encode_utf16().count() + 1) * size_of::<u16>();
pdu[padding_offset..padding_offset + size_of::<u16>()]
.copy_from_slice(&INVALID_UTF16_UNIT.to_le_bytes());
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
assert_eq!(files[0].name, PathBuf::from("file.txt"));
}
#[test]
fn file_list_id_is_fnv1a() {
// Reference vectors; the Windows side computes the same id in C.
@@ -319,15 +305,6 @@ mod tests {
assert_eq!(files[0].clip_data_id, id);
}
#[test]
fn rejects_non_terminated_file_name() {
let name = "a".repeat(FILE_NAME_CODE_UNITS);
assert!(matches!(
parse_name(&name),
Err(CliprdrError::InvalidRequest { .. })
));
}
fn parse_perm(attributes: u32) -> u16 {
let mut pdu = descriptor_pdu("folder");
pdu[ATTRIBUTES_OFFSET..ATTRIBUTES_OFFSET + size_of::<u32>()]
@@ -966,35 +966,6 @@ mod fuse_test {
}
}
fn build_single_file(prefix: &str) {
let raw_name = "simple_test_file.txt";
let f_name = if prefix == "" {
raw_name.to_string()
} else {
prefix.to_string() + "/" + raw_name
};
let desc = desc_gen(&f_name, FileType::File);
let tree = FuseNode::build_tree(vec![desc]).unwrap();
assert_eq!(tree.len(), 2);
assert_eq!(tree[0].name, "/");
assert_eq!(tree[0].children, vec![2]);
assert_eq!(tree[1].name, raw_name);
assert_eq!(tree[1].index, 0);
assert_eq!(tree[1].attributes.kind, FileType::File);
}
#[test]
fn test_parse_single() {
build_single_file("");
build_single_file("/");
build_single_file("test");
build_single_file("/test");
build_single_file("🗂");
build_single_file("/🗂");
}
#[test]
fn test_parse_tree() {
build_tree("");
+1 -41
View File
@@ -322,7 +322,7 @@ pub(super) fn construct_file_list(paths: &[PathBuf]) -> Result<Vec<LocalFile>, C
mod file_list_test {
use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
sync::atomic::AtomicU64,
time::{Duration, SystemTime},
};
@@ -466,32 +466,6 @@ mod file_list_test {
Ok(())
}
#[test]
fn read_exact_at_reopens_after_read_failure() -> Result<(), Box<dyn std::error::Error>> {
let file_path = std::env::temp_dir().join(format!(
"rustdesk-clipboard-local-file-{}",
std::process::id()
));
std::fs::write(&file_path, b"")?;
let mut file = LocalFile::try_open(&std::env::temp_dir(), &file_path)?;
file.size = 1;
let mut buf = [0u8; 1];
assert!(file.read_exact_at(&mut buf, 0).is_err());
assert!(file.handle.is_none());
assert_eq!(file.offset.load(Ordering::Relaxed), 0);
std::fs::write(&file_path, [42u8])?;
file.read_exact_at(&mut buf, 0)?;
assert_eq!(buf, [42u8]);
assert!(file.handle.is_none());
std::fs::remove_file(file_path)?;
Ok(())
}
const LAST_WRITE_TIME_OFFSET: usize = 56;
fn file_with_last_write_time(last_write_time: SystemTime) -> LocalFile {
@@ -519,18 +493,4 @@ mod file_list_test {
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(())
}
}
@@ -809,18 +809,6 @@ mod tests {
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();
@@ -866,18 +854,4 @@ mod tests {
assert!(!download_path.exists());
assert!(!outside.join("file.txt").exists());
}
#[test]
fn rejects_symlink_component_when_creating_directory() {
let (_temp, target, outside) = test_directories();
symlink(&outside, target.join("link")).unwrap();
let directory = file_description("link/escaped", FileType::Directory, 0);
let mut task = paste_task_handle(target, vec![directory]);
assert!(matches!(
task.update_next(0),
Err(CliprdrError::InvalidRequest { .. })
));
assert!(!outside.join("escaped").exists());
}
}
@@ -430,31 +430,3 @@ pub fn create_pasteboard_context() -> ResultType<Box<PasteboardContext>> {
context.init();
Ok(context)
}
#[cfg(test)]
mod tests {
#[test]
fn test_temp_files_count() {
let mut c = super::PasteboardContext::temp_files_count();
let mut created_files = vec![];
for _ in 0..10 {
let path = format!(
"/tmp/{}{}",
super::TEMP_FILE_PREFIX,
uuid::Uuid::new_v4().to_string()
);
if std::fs::File::create(&path).is_ok() {
created_files.push(path);
c += 1;
}
}
assert_eq!(c, super::PasteboardContext::temp_files_count());
// Clean up the created files.
for file in created_files {
std::fs::remove_file(&file).ok();
}
}
}
@@ -523,48 +523,6 @@ mod sig_test {
}
}
#[test]
fn fingerprint_missing_path_is_default() {
let tmp = TmpDir::new("missing");
let missing = path_str(&tmp.join("does_not_exist.bin"));
let sigs = fingerprint(&[missing]);
assert_eq!(sigs.len(), 1);
// A path that can't be stat'd -> default sig, which forces a rebuild.
assert_eq!(sigs[0], FileSig::default());
assert_eq!(sigs[0].mtime, None);
}
#[test]
fn fingerprint_detects_inplace_edit() {
let tmp = TmpDir::new("edit");
let file = tmp.join("a.bin");
fs::write(&file, b"small").unwrap();
let p = path_str(&file);
let before = fingerprint(&[p.clone()]);
// Same content, same path: fingerprint must be stable.
let again = fingerprint(&[p.clone()]);
assert_eq!(before, again);
assert_eq!(before[0].size, 5);
assert!(!before[0].is_dir);
// Edit in place so the file grows.
fs::write(&file, b"much larger contents than before").unwrap();
let after = fingerprint(&[p]);
assert_ne!(before, after);
assert!(after[0].size > before[0].size);
}
#[test]
fn fingerprint_flags_directory() {
let tmp = TmpDir::new("dir");
let sub = tmp.join("subdir");
fs::create_dir_all(&sub).unwrap();
let sigs = fingerprint(&[path_str(&sub)]);
assert_eq!(sigs.len(), 1);
assert!(sigs[0].is_dir);
}
#[test]
fn recopy_after_edit_refreshes_cached_size() {
let tmp = TmpDir::new("recopy");
@@ -597,37 +555,6 @@ 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");
@@ -756,172 +683,6 @@ mod sig_test {
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();
@@ -975,23 +736,6 @@ mod sig_test {
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");
-36
View File
@@ -146,39 +146,3 @@ fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
Ok(tokens)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn success() {
assert_eq!(
tokenize("{{Hello World!}} {+CTRL}hi{-CTRL}"),
Ok(vec![
Token::Sequence("{Hello World!} ".into()),
Token::KeyDown(Key::Control),
Token::Sequence("hi".into()),
Token::KeyUp(Key::Control)
])
);
}
#[test]
fn unexpected_open() {
assert_eq!(tokenize("{hello{}world}"), Err(ParseError::UnexpectedOpen));
}
#[test]
fn unmatched_open() {
assert_eq!(
tokenize("{this is going to fail"),
Err(ParseError::UnmatchedOpen)
);
}
#[test]
fn unmatched_close() {
assert_eq!(
tokenize("{+CTRL}{{this}} is going to fail}"),
Err(ParseError::UnmatchedClose)
);
}
}
-25
View File
@@ -525,28 +525,3 @@ impl fmt::Debug for Enigo {
write!(f, "Enigo")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_key_state() {
let mut enigo = Enigo::new();
let keys = [Key::CapsLock, Key::NumLock];
for k in keys.iter() {
enigo.key_click(k.clone());
let a = enigo.get_key_state(k.clone());
enigo.key_click(k.clone());
let b = enigo.get_key_state(k.clone());
assert!(a != b);
}
let keys = [Key::Control, Key::Alt, Key::Shift];
for k in keys.iter() {
enigo.key_down(k.clone()).ok();
let a = enigo.get_key_state(k.clone());
enigo.key_up(k.clone());
let b = enigo.get_key_state(k.clone());
assert!(a != b);
}
}
}
-7
View File
@@ -391,13 +391,6 @@ fn convert_to_tfc_key(key: Key) -> Option<TFC_Key> {
Some(key)
}
#[test]
fn test_key_seq() {
// Get 6^ in French.
let mut en = Enigo::new();
en.key_sequence("^^");
}
/// Both directions: the failure is silent, so a one-directional test passes against the bug.
#[test]
fn test_custom_mouse_dispatch_follows_is_x11() {
+55
View File
@@ -36,6 +36,7 @@ const kUCKeyActionDisplay: u16 = 3;
#[allow(non_upper_case_globals)]
const kUCKeyTranslateDeadKeysBit: OptionBits = 1 << 31;
const BUF_LEN: usize = 4;
const KEYBOARD_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
const MOUSE_EVENT_BUTTON_NUMBER_BACK: i64 = 3;
const MOUSE_EVENT_BUTTON_NUMBER_FORWARD: i64 = 4;
@@ -428,7 +429,19 @@ impl KeyboardControllable for Enigo {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), 0, true) {
event.set_string(cluster);
self.post(event, None);
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-sequence: event source is not initialized"
);
}
}
}
@@ -436,17 +449,40 @@ impl KeyboardControllable for Enigo {
fn key_click(&mut self, key: Key) {
let keycode = self.key_to_keycode(key);
if keycode == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: keycode mapping is unavailable"
);
return;
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, true) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-down in key-click: could not create keyboard event"
);
}
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), keycode, false) {
self.post(event, Some(keycode));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up in key-click: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-click: event source is not initialized"
);
}
}
@@ -465,10 +501,29 @@ impl KeyboardControllable for Enigo {
fn key_up(&mut self, key: Key) {
let code = self.key_to_keycode(key);
if code == u16::MAX {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Cannot map macOS Enigo key-up to a keycode"
);
}
if let Some(src) = self.event_source.as_ref() {
if let Ok(event) = CGEvent::new_keyboard_event(src.clone(), code, false) {
self.post(event, Some(code));
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: could not create keyboard event"
);
}
} else {
hbb_common::throttled_log!(
KEYBOARD_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS Enigo key-up: event source is not initialized"
);
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rustdesk-portable-packer"
version = "1.5.0"
version = "1.5.1"
edition = "2021"
description = "RustDesk Remote Desktop"
@@ -20,6 +20,7 @@ windows = { version = "0.61", features = [
"Wdk_System",
"Wdk_System_SystemServices",
"Win32",
"Win32_Storage_FileSystem",
"Win32_System",
"Win32_System_SystemInformation",
] }
@@ -36,4 +37,3 @@ FileDescription = "RustDesk Remote Desktop"
winres = "0.1"
winapi = { version = "0.3", features = [ "winnt", "pdh", "synchapi" ] }
-50
View File
@@ -279,26 +279,6 @@ mod tests {
.find(|file| normalize_path(&file.path) == normalize_path(path))
}
#[test]
fn parses_the_generate_py_layout() {
let (files, exe) = parse(blob(
&[("./rustdesk.exe", b"app"), ("./custom.txt", b"cfg")],
"./rustdesk.exe",
))
.unwrap();
assert_eq!(exe, "./rustdesk.exe");
assert_eq!(files.len(), 2);
assert_eq!(entry(&files, "./custom.txt").unwrap().raw, b"cfg");
}
#[test]
fn rejects_malformed_blobs() {
assert!(parse(b"".as_slice()).is_none());
assert!(parse(b"notrustd".as_slice()).is_none());
// Truncated mid-record rather than panicking on a slice out of range.
assert!(parse(b"rustdesk\x00\x00\x00\x40partial".as_slice()).is_none());
}
#[test]
fn distinguishes_an_absent_package_from_a_malformed_one() {
assert!(parse_package_blob(None).unwrap().0.is_empty());
@@ -372,34 +352,4 @@ mod tests {
);
assert_eq!(entry(&files, "./librustdesk.dll").unwrap().raw, b"core");
}
#[test]
fn package_paths_are_recorded_for_the_dropped_file_sweep() {
let package = parse(blob(
&[("./custom.txt", b"cfg"), ("./data/logo.png", b"img")],
"./acme.exe",
))
.unwrap();
let mut paths: Vec<String> = package.0.iter().map(|f| f.path.clone()).collect();
paths.sort();
assert_eq!(paths, vec!["./custom.txt", "./data/logo.png"]);
// Merging must not disturb them: the generic payload contributes none.
let embedded = parse(blob(&[("./librustdesk.dll", b"core")], "./rustdesk.exe")).unwrap();
let (files, _) = merge(embedded, package);
assert!(entry(&files, "./data/logo.png").is_some());
}
#[test]
fn matches_paths_across_separator_styles() {
// generate.py emits backslashes when it runs on Windows.
let embedded = parse(blob(&[(".\\rustdesk.exe", b"app")], ".\\rustdesk.exe")).unwrap();
let package = parse(blob(&[("./custom.txt", b"cfg")], "./acme.exe")).unwrap();
let (files, exe) = merge(embedded, package);
assert_eq!(exe, "./acme.exe");
assert!(entry(&files, "./acme.exe").is_some());
assert!(entry(&files, ".\\rustdesk.exe").is_none());
}
}
+36
View File
@@ -19,6 +19,8 @@ const APP_METADATA_CONFIG: &str = "meta.toml";
const META_LINE_PREFIX_TIMESTAMP: &str = "timestamp = ";
const META_LINE_PREFIX_FILE: &str = "file = ";
const APP_PREFIX: &str = "rustdesk";
#[cfg(windows)]
const VERIFIED_UPDATE_FILE_PREFIX: &str = "rustdesk-verified-";
const APPNAME_RUNTIME_ENV_KEY: &str = "RUSTDESK_APPNAME";
#[cfg(windows)]
const SET_FOREGROUND_WINDOW_ENV_KEY: &str = "SET_FOREGROUND_WINDOW";
@@ -287,6 +289,13 @@ fn main() -> Result<(), String> {
#[cfg(not(windows))]
let quick_support = false;
#[cfg(windows)]
if args.first().is_some_and(|arg| arg == "--update") {
if let Err(err) = win::schedule_verified_update_cleanup() {
eprintln!("Failed to schedule verified update file cleanup: {}", err);
}
}
let mut ui = false;
let reader = BinaryReader::new()?;
if let Some(exe) = setup(
@@ -314,6 +323,33 @@ mod win {
pub const RUNTIME_BROKER_EXE: &'static str = "C:\\Windows\\System32\\RuntimeBroker.exe";
pub const WIN_TOPMOST_INJECTED_PROCESS_EXE: &'static str = "RuntimeBroker_rustdesk.exe";
pub(super) fn schedule_verified_update_cleanup() -> std::io::Result<()> {
use windows::{
core::{HSTRING, PCWSTR},
Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT},
};
let current_exe = std::env::current_exe()?;
let is_verified_update = current_exe
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name.starts_with(super::VERIFIED_UPDATE_FILE_PREFIX) && name.ends_with(".exe")
});
if !is_verified_update {
return Ok(());
}
unsafe {
MoveFileExW(
&HSTRING::from(current_exe.as_path()),
PCWSTR::null(),
MOVEFILE_DELAY_UNTIL_REBOOT,
)
}
.map_err(std::io::Error::other)
}
pub(super) fn copy_runtime_broker(dir: &Path) {
let src = RUNTIME_BROKER_EXE;
let tgt = WIN_TOPMOST_INJECTED_PROCESS_EXE;
+44 -15
View File
@@ -5,7 +5,7 @@ use winapi::{
shared::{
minwindef::{BOOL, DWORD, FALSE, LPBYTE, LPDWORD},
ntdef::HANDLE,
winerror::ERROR_INVALID_PRINTER_NAME,
winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_INVALID_PRINTER_NAME},
},
um::winspool::{
AddPrinterW, ClosePrinter, DeletePrinter, EnumPrintersW, OpenPrinterW, SetPrinterW,
@@ -42,20 +42,49 @@ fn enum_local_printer(
#[inline]
pub fn is_printer_added(name: &PCWSTR) -> ResultType<bool> {
let r = common_enum(
"EnumPrintersW",
enum_local_printer,
1,
|info: &PRINTER_INFO_1W| {
if is_name_equal(name, info.pName) {
Some(true)
} else {
None
}
},
|| None,
)?;
Ok(r.unwrap_or(false))
const PRINTER_INFO_LEVEL: DWORD = 1;
let mut needed = 0;
let mut returned = 0;
if enum_local_printer(
PRINTER_INFO_LEVEL,
null_mut(),
0,
&mut needed,
&mut returned,
) == FALSE
{
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) || needed == 0 {
bail!("Failed to query EnumPrintersW buffer size: {error}");
}
}
if needed == 0 {
return Ok(false);
}
let mut buffer = vec![0u8; needed as usize];
if enum_local_printer(
PRINTER_INFO_LEVEL,
buffer.as_mut_ptr(),
needed,
&mut needed,
&mut returned,
) == FALSE
{
bail!(
"Failed to call EnumPrintersW, error: {}",
io::Error::last_os_error()
);
}
let printers = buffer.as_ptr() as *const PRINTER_INFO_1W;
for index in 0..returned {
let printer = unsafe { &*printers.add(index as usize) };
if is_name_equal(name, printer.pName) {
return Ok(true);
}
}
Ok(false)
}
// Only return the first matched printer
+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.12). We deliberately do
# NOT depend on the `libdrmtap-sys` crate: its build.rs statically compiles the whole libdrmtap C tree
# and a CAP_SYS_ADMIN helper and emits `-ldrm -lseccomp -lcap`, which would defeat the dlopen model.
# Depends on `wayland`: the three drm modules live inside the `#[cfg(feature = "wayland")]` arm of
-17
View File
@@ -199,23 +199,6 @@ mod webrtc {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::raw::c_uint;
#[test]
fn tile_log2_uses_c_uint_and_rounds_up() {
let one_thread: c_uint = tile_log2(1);
let three_threads: c_uint = tile_log2(3);
let max_threads: c_uint = tile_log2(64);
assert_eq!(one_thread, 0);
assert_eq!(three_threads, 2);
assert_eq!(max_threads, 6);
}
}
}
impl EncoderApi for AomEncoder {
+66 -172
View File
@@ -309,6 +309,8 @@ pub struct DisplaySnapshot {
pub y: i32,
pub width: u32,
pub height: u32,
/// The kernel's whole-hertz vrefresh: 59.94 reads 60. `DrmReader::crtc_refresh` is exact.
pub refresh_hz: u32,
pub active: bool,
}
@@ -545,6 +547,17 @@ impl DrmReader {
self.last_plane_rotation
}
/// The refresh of the captured CRTC in hertz as the reduced fraction `(num, den)` of its
/// current mode, read now. `None` when the library predates the call (0.5.9) or the CRTC has
/// no mode.
pub fn crtc_refresh(&mut self) -> Option<(u64, u64)> {
let f = self.lib.crtc_refresh?;
let (mut num, mut den) = (0u64, 0u64);
// SAFETY: self.ctx is a live context and both outputs outlive the call.
let rc = unsafe { f(self.ctx, &mut num, &mut den) };
(rc == 0 && num != 0 && den != 0).then_some((num, den))
}
fn read_plane_rotation(&mut self) -> Option<u32> {
let f = self.lib.plane_rotation?;
let mut rotation: u32 = 0;
@@ -553,6 +566,12 @@ impl DrmReader {
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.
@@ -755,6 +774,7 @@ impl DrmReader {
y: raw[i].y as i32,
width: raw[i].width,
height: raw[i].height,
refresh_hz: raw[i].refresh_hz,
active: raw[i].active != 0,
}
})
@@ -775,47 +795,7 @@ impl Drop for DrmReader {
#[cfg(test)]
mod hotspot_provenance_tests {
use super::{cursor_id, hot_measured_from, provenance_code, provenance_is_news};
/// The log this makes observable is one line per CHANGE, not one per cursor read. A cursor is
/// read far more often than its provenance changes, and a per-sample line here would be the
/// same defect libdrmtap already had once.
#[test]
fn provenance_is_logged_once_and_then_only_on_a_change() {
let (none, guessed, measured) = (
provenance_code(None),
provenance_code(Some(false)),
provenance_code(Some(true)),
);
assert_ne!(none, guessed);
assert_ne!(guessed, measured);
assert_ne!(none, measured);
// First sample of a run: -1 is the unset sentinel, so anything is news.
assert!(provenance_is_news(-1, measured));
// The same state again is not.
assert!(!provenance_is_news(measured, measured));
assert!(!provenance_is_news(guessed, guessed));
// A real transition is.
assert!(provenance_is_news(guessed, measured));
assert!(provenance_is_news(measured, none));
}
/// The dedup key has to move when the provenance does, or the consumer is never told that the
/// same picture now means something different. This is the transition that produces it: the
/// properties become readable, the driver's answer is the corner, and the bitmap is unchanged.
#[test]
fn provenance_changes_the_cursor_identity() {
let guessed = cursor_id(0xabc, 24, 24, 0, 0, false);
let measured = cursor_id(0xabc, 24, 24, 0, 0, true);
assert_ne!(
guessed, measured,
"same pixels, same (0, 0), different meaning: the producer must not dedupe this away"
);
// And the pre-existing parts still count, so this did not trade one blind spot for another.
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 32, 24, 0, 0, true));
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xabc, 24, 24, 1, 0, true));
assert_ne!(cursor_id(0xabc, 24, 24, 0, 0, true), cursor_id(0xdef, 24, 24, 0, 0, true));
}
use super::hot_measured_from;
/// The case the whole entry point exists for, and the one the old heuristic got backwards: a
/// para-virtualized driver that really publishes the hotspot at the image's top-left corner.
@@ -825,25 +805,6 @@ mod hotspot_provenance_tests {
fn a_measured_zero_hotspot_is_measured() {
assert!(hot_measured_from(Some(true), 0, 0));
}
/// And the mirror: when the library says it was NOT measured, that is the answer even if the
/// coordinates happen to be non-zero. The old test would have trusted them.
#[test]
fn the_librarys_no_beats_the_coordinates() {
assert!(!hot_measured_from(Some(false), 12, 11));
assert!(!hot_measured_from(Some(false), 0, 0));
}
/// No answer available: either the symbol is absent (a library older than 0.5.6) or nothing
/// recorded one for this sample (a cursor read through an older privileged helper). Neither
/// is "it was a guess", so the pre-existing behaviour is kept rather than resolved either way
/// -- an older deployed .so must keep behaving as it used to.
#[test]
fn without_an_answer_the_old_heuristic_stands() {
assert!(!hot_measured_from(None, 0, 0));
assert!(hot_measured_from(None, 12, 11));
assert!(hot_measured_from(None, 0, 5));
}
}
#[cfg(test)]
@@ -904,45 +865,6 @@ mod hotspot_guess_tests {
assert_eq!(infer_hotspot(&px, w, h), (4, 4));
}
/// Each axis is decided by its OWN mirror. This shape is symmetric left-to-right and not
/// top-to-bottom, which is the single-direction resize family: the click point is centred
/// across the axis that mirrors and stays at the edge on the axis that does not.
#[test]
fn one_symmetric_axis_centres_that_axis_only() {
let (px, w, h) = sprite(&[
"....#....",
"...###...",
"..#####..",
".#######.",
"....#....",
"....#....",
"....#....",
"....#....",
"....#....",
]);
assert_eq!(infer_hotspot(&px, w, h), (4, 0));
}
/// A two-headed DIAGONAL arrow mirrors onto the other diagonal about either axis alone, so
/// neither axis reads as symmetric - and it is still a shape with no tip. The half turn is
/// what catches it.
#[test]
fn a_diagonal_two_headed_arrow_is_held_by_its_middle_too() {
let (px, w, h) = sprite(&[
"###......",
"##.......",
"#.#......",
"...#.....",
"....#....",
".....#...",
"......#.#",
".......##",
"......###",
]);
let (hx, hy) = infer_hotspot(&px, w, h);
assert_eq!((hx, hy), (4, 4), "a half turn maps this shape onto itself");
}
/// A single-direction resize cursor is an arrow plus the bar of the edge it resizes, and the
/// theme puts the click point on the BAR. The bar is the heavy end, and it is the only thing
/// that separates `e-resize` from `w-resize`: they are the same picture reflected, so a rule
@@ -972,25 +894,6 @@ mod hotspot_guess_tests {
assert_eq!(infer_hotspot(&px, w, h), (0, 3));
}
/// A corner resize cursor is a bracket hugging one corner, and it mirrors onto itself about a
/// DIAGONAL rather than about either axis, so neither per-axis test sees it. The click point
/// is the inner corner of the bracket, which is the heavy end on both axes.
///
/// A real one's box is usually not square, and a diagonal reflection only lines up inside a
/// square, so which corner of that square the box is placed against decides the answer:
/// `ne-resize` scores 0.62 anchored one way and 0.98 the other, and `nw-resize` is the
/// reverse. Both anchorings are therefore tried. That case cannot be built as a small
/// picture - a non-square box can never be exactly diagonal-symmetric - so it is covered by
/// the theme corpus instead, where dropping the second anchoring sends `ne-resize` back past
/// master.
#[test]
fn a_corner_bracket_is_held_by_its_inner_corner() {
let (px, w, h) = sprite(&[
".....##", ".....##", ".....##", ".....##", ".....##", "#######", "#######",
]);
assert_eq!(infer_hotspot(&px, w, h), (6, 6));
}
/// The elongation rule stays ahead of the mirror test, so a bar that is NOT symmetric still
/// keeps its centre. Nothing in the installed theme is shaped like this - its two I-beams are
/// both symmetric - but a custom cursor can be, and this is the rustdesk#16242 round-one fix.
@@ -999,14 +902,6 @@ mod hotspot_guess_tests {
let (px, w, h) = sprite(&["##########.", "#####......", "##########."]);
assert_eq!(infer_hotspot(&px, w, h), (4, 1));
}
/// Nothing opaque is not a shape, and must not read as a box at the origin with a hotspot in
/// the middle of it.
#[test]
fn a_blank_sprite_has_no_hotspot_to_guess() {
let (px, w, h) = sprite(&["...", "...", "..."]);
assert_eq!(infer_hotspot(&px, w, h), (0, 0));
}
}
/// DRM_MODE_ROTATE_0: the `rotation` bitmask of a plane that turned nothing.
@@ -1030,8 +925,6 @@ fn plane_rotation_answer(rc: c_int, rotation: u32) -> Option<u32> {
#[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() {
@@ -1042,63 +935,64 @@ mod plane_rotation_tests {
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];
#[cfg(test)]
mod crtc_refresh_tests {
use super::*;
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, rotation: *mut u32) -> c_int {
*rotation = PLANE.load(Ordering::SeqCst);
0
static RC: AtomicI32 = AtomicI32::new(0);
static NUM: AtomicU64 = AtomicU64::new(0);
static DEN: AtomicU64 = AtomicU64::new(0);
unsafe extern "C" fn crtc_refresh(_: *mut drmtap_ctx, num: *mut u64, den: *mut u64) -> c_int {
*num = NUM.load(Ordering::SeqCst);
*den = DEN.load(Ordering::SeqCst);
RC.load(Ordering::SeqCst)
}
unsafe extern "C" fn 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_mapped(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) -> c_int {
-1
}
unsafe extern "C" fn frame_release(_: *mut drmtap_ctx, _: *mut drmtap_frame_info) {}
unsafe extern "C" fn grab_desc(
_: *mut drmtap_ctx,
d: *mut drmtap_dmabuf_desc,
_: *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
-1
}
unsafe extern "C" fn plane_rotation(_: *mut drmtap_ctx, _: *mut u32) -> c_int {
-1
}
#[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,
fn reader(with_call: bool) -> DrmReader {
let mut lib = DrmtapLib::fake(grab_mapped, frame_release, grab_desc, plane_rotation);
if with_call {
lib.crtc_refresh = Some(crtc_refresh);
}
DrmReader {
lib: Box::leak(Box::new(lib)),
ctx: std::ptr::null_mut(),
buf: Vec::new(),
last_provenance: -1,
last_plane_rotation: None,
};
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");
}
}
/// rustdesk#16175: the exact refresh paces the producer; an older library has no answer.
#[test]
fn the_crtc_refresh_is_a_fraction_or_nothing() {
assert_eq!(reader(false).crtc_refresh(), None, "a library before 0.5.9");
let mut r = reader(true);
RC.store(0, Ordering::SeqCst);
NUM.store(148352, Ordering::SeqCst);
DEN.store(2475, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), Some((148352, 2475)));
RC.store(-hbb_common::libc::ENODATA, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), None, "a CRTC with no mode");
RC.store(0, Ordering::SeqCst);
DEN.store(0, Ordering::SeqCst);
assert_eq!(r.crtc_refresh(), None, "a zero denominator is no answer");
}
}
+19 -41
View File
@@ -146,6 +146,10 @@ type FnRenderNode = unsafe extern "C" fn(*mut drmtap_ctx) -> *const c_char;
/// means the compositor can only have rotated in software; `-ENOENT` with no plane bound;
/// `-EINVAL` on a null argument.
type FnPlaneRotation = unsafe extern "C" fn(*mut drmtap_ctx, *mut u32) -> c_int;
/// `drmtap_crtc_refresh`, added in libdrmtap 0.5.9: the refresh of the captured CRTC in hertz as
/// the reduced fraction `*num / *den` of its current mode. 0 on success; `-ENODATA` for a CRTC
/// with no mode; `-ENOENT` with none to pick; `-EINVAL` on a null argument.
type FnCrtcRefresh = unsafe extern "C" fn(*mut drmtap_ctx, *mut u64, *mut u64) -> c_int;
type FnConvertDmabuf =
unsafe extern "C" fn(*mut drmtap_ctx, *const drmtap_dmabuf_desc, *mut drmtap_frame_info) -> c_int;
@@ -171,6 +175,9 @@ pub struct DrmtapLib {
/// Optional: it only exists from libdrmtap 0.5.8. Absent means the library cannot say whether
/// the plane rotated the scanout, and the consumer keeps the pre-0.5.8 rule for that case.
pub plane_rotation: Option<FnPlaneRotation>,
/// Optional: it only exists from libdrmtap 0.5.9. Absent means the producer takes the
/// whole-hertz refresh of the enumeration as its pacing floor.
pub crtc_refresh: Option<FnCrtcRefresh>,
pub version: (c_int, c_int, c_int),
}
@@ -221,6 +228,7 @@ impl DrmtapLib {
convert_dmabuf,
render_node: None,
plane_rotation: Some(plane_rotation),
crtc_refresh: None,
version: (0, 5, 8),
}
}
@@ -353,6 +361,8 @@ impl DrmtapLib {
lib.get(b"drmtap_cursor_hotspot_valid").ok().map(|s| *s);
let plane_rotation: Option<FnPlaneRotation> =
lib.get(b"drmtap_plane_rotation").ok().map(|s| *s);
let crtc_refresh: Option<FnCrtcRefresh> =
lib.get(b"drmtap_crtc_refresh").ok().map(|s| *s);
// Log the load only now that every required symbol resolved: this fn still returns None on a missing one.
let loaded_from = real
.as_ref()
@@ -404,6 +414,14 @@ impl DrmtapLib {
software will be captured upside down."
);
}
if (minor, patch) >= (5, 9) && crtc_refresh.is_none() {
log::warn!(
"libdrmtap at {loaded_from} reports v{major}.{minor}.{patch} but is missing \
drmtap_crtc_refresh: it is a stale or pre-release build. Check what the \
soname symlink points at. Capture paces to the whole-hertz refresh, so a \
59.94 Hz panel is sampled as if it were 60."
);
}
Some(DrmtapLib {
_lib: lib,
open,
@@ -420,6 +438,7 @@ impl DrmtapLib {
convert_dmabuf,
render_node,
plane_rotation,
crtc_refresh,
version: (major, minor, patch),
})
}
@@ -445,41 +464,6 @@ pub fn get() -> Option<&'static DrmtapLib> {
mod tests {
use super::{abi_accepted, DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, DRMTAP_MIN_MINOR_PATCH};
#[test]
fn abi_gate_rejects_a_library_from_before_the_split() {
// These are refused because their MINOR differs from the verified one, which is the only
// reason the gate needs. Naming the pre-split releases keeps the intent readable, but do
// not read this as the floor doing the work: see the test below.
for (minor, patch) in [(3, 3), (4, 0), (4, 8), (4, 9)] {
assert!(
!abi_accepted(DRMTAP_ABI_MAJOR, minor, patch),
"v0.{minor}.{patch} is not the verified minor and must be refused"
);
}
}
#[test]
fn the_patch_floor_is_currently_vacuous_and_that_is_deliberate() {
// With MIN_MINOR_PATCH.0 == DRMTAP_ABI_MINOR the floor can never reject anything: the
// minor equality already forces `(minor, patch) >= (minor, 0)`. It is kept because it is
// the mechanism that WOULD do the work the next time a floor lands mid-minor, as (4, 10)
// did for the split API. This test exists so nobody reads the pre-split test above as
// evidence that the floor is live -- if that ever matters, this assert is the tripwire.
let (floor_minor, floor_patch) = DRMTAP_MIN_MINOR_PATCH;
assert_eq!(
floor_minor, DRMTAP_ABI_MINOR,
"the floor is inside the verified minor; a floor in a DIFFERENT minor is unreachable"
);
if floor_patch == 0 {
assert!(
abi_accepted(DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, 0),
"patch 0 of the verified minor must be accepted while the floor is 0"
);
} else {
assert!(!abi_accepted(DRMTAP_ABI_MAJOR, DRMTAP_ABI_MINOR, floor_patch - 1));
}
}
#[test]
fn abi_gate_accepts_the_floor_and_later_patches_of_the_same_minor() {
let (min_minor, min_patch) = DRMTAP_MIN_MINOR_PATCH;
@@ -509,10 +493,4 @@ mod tests {
);
}
}
#[test]
fn abi_gate_rejects_another_major_in_both_directions() {
assert!(!abi_accepted(DRMTAP_ABI_MAJOR + 1, 0, 0));
assert!(!abi_accepted(DRMTAP_ABI_MAJOR + 1, 99, 99));
}
}
+4 -1
View File
@@ -25,6 +25,9 @@ use hwcodec::{
},
};
#[cfg(all(test, windows, feature = "vram"))]
mod tests;
const DEFAULT_PIXFMT: AVPixelFormat = AVPixelFormat::AV_PIX_FMT_NV12;
pub const DEFAULT_FPS: i32 = 30;
const DEFAULT_GOP: i32 = i32::MAX;
@@ -236,7 +239,7 @@ impl HwRamEncoder {
data.append(v);
Ok(data)
}
Err(_) => Ok(Vec::<EncodeFrame>::new()),
Err(code) => Err(anyhow!("RAM encode failed: {}", code)),
}
}
+130
View File
@@ -0,0 +1,130 @@
use super::{CodecInfo, HwCodecConfig, CONFIG, CONFIG_SET_BY_IPC};
use crate::{
codec::enable_vram_option,
vram::{VRamDecoder, VRamEncoder},
AdapterDevice, CodecFormat,
};
use base::config::keys::{OPTION_ALLOW_D3D_RENDER, OPTION_ENABLE_HWCODEC};
use hbb_common::config::{OVERWRITE_LOCAL_SETTINGS, OVERWRITE_SETTINGS};
use hwcodec::{
common::{DataFormat, Driver},
vram::{DecodeContext, FeatureContext},
};
use std::{collections::HashMap, mem};
struct RestoreConfig {
config: Option<HwCodecConfig>,
set_by_ipc: bool,
options: HashMap<String, String>,
local_options: HashMap<String, String>,
}
impl Drop for RestoreConfig {
fn drop(&mut self) {
*CONFIG.lock().unwrap() = self.config.take();
*CONFIG_SET_BY_IPC.lock().unwrap() = self.set_by_ipc;
*OVERWRITE_SETTINGS.write().unwrap() = mem::take(&mut self.options);
*OVERWRITE_LOCAL_SETTINGS.write().unwrap() = mem::take(&mut self.local_options);
}
}
fn add_backend(config: &mut HwCodecConfig, driver: Driver, vendor: Driver, format: DataFormat) {
let luid = match vendor {
Driver::NV => 1,
Driver::MFX => 2,
Driver::AMF => 3,
_ => unreachable!(),
};
config.vram_encode.push(FeatureContext {
driver: driver.clone(),
vendor: vendor.clone(),
luid,
data_format: format,
});
config.vram_decode.push(DecodeContext {
device: None,
driver,
vendor,
luid,
data_format: format,
});
}
#[test]
fn cached_sdk_entries_are_ignored_before_check_completes() {
let _restore = RestoreConfig {
config: CONFIG.lock().unwrap().take(),
set_by_ipc: mem::replace(&mut *CONFIG_SET_BY_IPC.lock().unwrap(), false),
options: mem::take(&mut *OVERWRITE_SETTINGS.write().unwrap()),
local_options: mem::take(&mut *OVERWRITE_LOCAL_SETTINGS.write().unwrap()),
};
OVERWRITE_SETTINGS
.write()
.unwrap()
.insert(OPTION_ENABLE_HWCODEC.into(), "Y".into());
OVERWRITE_LOCAL_SETTINGS
.write()
.unwrap()
.insert(OPTION_ALLOW_D3D_RENDER.into(), "Y".into());
assert!(enable_vram_option(false));
let formats = [
(CodecFormat::H264, DataFormat::H264),
(CodecFormat::H265, DataFormat::H265),
];
let mut cached = HwCodecConfig::default();
for (_, format) in formats {
// A RAM fallback keeps this selection test independent of attached displays.
cached.ram_encode.push(CodecInfo {
format,
..Default::default()
});
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
add_backend(&mut cached, vendor.clone(), vendor, format);
}
}
*CONFIG.lock().unwrap() = Some(cached.clone());
assert!(!HwCodecConfig::already_set());
for (format, _) in formats {
assert!(VRamEncoder::available(format).is_empty());
for luid in 1..=3 {
assert!(VRamDecoder::try_get(format, Some(luid)).is_none());
}
}
assert_eq!(
VRamDecoder::possible_available_without_check(),
(false, false)
);
for (index, &(format, data_format)) in formats.iter().enumerate() {
for vendor in [Driver::NV, Driver::MFX, Driver::AMF] {
add_backend(&mut cached, Driver::FFMPEG, vendor, data_format);
}
*CONFIG.lock().unwrap() = Some(cached.clone());
let encoders = VRamEncoder::available(format);
assert_eq!(encoders.len(), 3);
for encoder in encoders {
assert_eq!(encoder.driver, Driver::FFMPEG);
let device = AdapterDevice {
luid: encoder.luid,
..Default::default()
};
assert_eq!(VRamEncoder::try_get(&device, format), Some(encoder.clone()));
let decoder = VRamDecoder::try_get(format, Some(encoder.luid)).unwrap();
assert_eq!(decoder.driver, Driver::FFMPEG);
assert_eq!(decoder.vendor, encoder.vendor);
assert_eq!(decoder.data_format, data_format);
}
assert!(VRamDecoder::available(format, Some(99)).is_empty());
assert!(VRamDecoder::available(format, None).is_empty());
assert_eq!(
VRamDecoder::possible_available_without_check(),
(true, index == 1)
);
}
assert!(!HwCodecConfig::already_set());
assert_eq!(
HwCodecConfig::get().vram_encode.len(),
cached.vram_encode.len()
);
}
+2
View File
@@ -209,6 +209,8 @@ impl Frame<'_> {
pub enum EncodeInput<'a> {
YUV(&'a [u8]),
Texture((*mut c_void, usize)),
#[cfg(all(windows, feature = "vram"))]
Repeat,
}
impl<'a> EncodeInput<'a> {
+12 -1
View File
@@ -20,6 +20,17 @@ use std::{ptr, slice};
generate_call_macro!(call_vpx, false);
generate_call_ptr_macro!(call_vpx_ptr);
#[derive(Debug)]
pub struct VpxNoOutput;
impl std::fmt::Display for VpxNoOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("no valid frame")
}
}
impl std::error::Error for VpxNoOutput {}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum VpxVideoCodecId {
VP8,
@@ -187,7 +198,7 @@ impl EncoderApi for VpxEncoder {
if frames.len() > 0 {
Ok(VpxEncoder::create_video_frame(self.id, frames))
} else {
Err(anyhow!("no valid frame"))
Err(VpxNoOutput.into())
}
}
+43 -41
View File
@@ -15,8 +15,9 @@ use hbb_common::{
bytes::Bytes,
log, ResultType,
};
pub use hwcodec::common::Driver;
use hwcodec::{
common::{DataFormat, Driver, MAX_GOP},
common::{DataFormat, MAX_GOP},
vram::{
decode::{self, DecodeFrame, Decoder},
encode::{self, EncodeFrame, Encoder},
@@ -24,6 +25,9 @@ use hwcodec::{
},
};
#[cfg(test)]
mod repeat_tests;
// https://www.reddit.com/r/buildapc/comments/d2m4ny/two_graphics_cards_two_monitors/
// https://www.reddit.com/r/techsupport/comments/t2v9u6/dual_monitor_setup_with_dual_gpu/
// https://cybersided.com/two-monitors-two-gpus/
@@ -48,8 +52,6 @@ pub struct VRamEncoder {
pub format: DataFormat,
ctx: EncodeContext,
bitrate: u32,
last_frame_len: usize,
same_bad_len_counter: usize,
}
impl EncoderApi for VRamEncoder {
@@ -83,8 +85,6 @@ impl EncoderApi for VRamEncoder {
ctx,
format: config.feature.data_format,
bitrate,
last_frame_len: 0,
same_bad_len_counter: 0,
}),
Err(_) => Err(anyhow!(format!("Failed to create encoder"))),
}
@@ -98,7 +98,15 @@ impl EncoderApi for VRamEncoder {
frame: EncodeInput,
ms: i64,
) -> ResultType<base::message_proto::VideoFrame> {
let (texture, rotation) = frame.texture()?;
#[cfg(all(windows, feature = "vram"))]
let repeated = matches!(&frame, EncodeInput::Repeat);
#[cfg(not(all(windows, feature = "vram")))]
let repeated = false;
let (texture, rotation) = if repeated {
(std::ptr::null_mut(), 0)
} else {
frame.texture()?
};
if rotation != 0 {
// to-do: support rotation
// Both the encoder and display(w,h) information need to be changed.
@@ -106,10 +114,12 @@ impl EncoderApi for VRamEncoder {
}
let mut vf = VideoFrame::new();
let mut frames = Vec::new();
for frame in self
.encode(texture, ms)
.with_context(|| "Failed to encode")?
{
let result = if repeated {
self.encode_repeat(ms)
} else {
self.encode(texture, ms)
};
for frame in result.with_context(|| "Failed to encode")? {
frames.push(EncodedVideoFrame {
data: Bytes::from(frame.data),
pts: frame.pts,
@@ -117,29 +127,10 @@ impl EncoderApi for VRamEncoder {
..Default::default()
});
}
if repeated && frames.is_empty() {
return Ok(vf);
}
if frames.len() > 0 {
// This kind of problem is occurred after a period of time when using the AMD SDK,
// the encoding length is fixed at about 40, and the picture is still
const MIN_BAD_LEN: usize = 100;
const MAX_BAD_COUNTER: usize = 30;
let this_frame_len = frames[0].data.len();
if self.ctx.f.driver == Driver::AMF
&& this_frame_len < MIN_BAD_LEN
&& this_frame_len == self.last_frame_len
{
self.same_bad_len_counter += 1;
if self.same_bad_len_counter >= MAX_BAD_COUNTER {
log::info!(
"{} times encoding len is {}, switch",
self.same_bad_len_counter,
self.last_frame_len
);
bail!(crate::codec::ENCODE_NEED_SWITCH);
}
} else {
self.same_bad_len_counter = 0;
}
self.last_frame_len = this_frame_len;
let frames = EncodedVideoFrames {
frames: frames.into(),
..Default::default()
@@ -244,6 +235,7 @@ impl VRamEncoder {
let v: Vec<_> = crate::hwcodec::HwCodecConfig::get()
.vram_encode
.drain(..)
.filter(|c| c.driver == Driver::FFMPEG)
.filter(|c| c.data_format == data_format)
.collect();
if crate::hwcodec::HwRamEncoder::try_get(format).is_some() {
@@ -274,14 +266,21 @@ impl VRamEncoder {
}
}
pub fn encode(&mut self, texture: *mut c_void, ms: i64) -> ResultType<Vec<EncodeFrame>> {
pub fn encode(
&mut self,
texture: *mut c_void,
ms: i64,
) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
match self.encoder.encode(texture, ms) {
Ok(v) => {
let mut data = Vec::<EncodeFrame>::new();
data.append(v);
Ok(data)
}
Err(_) => Ok(Vec::<EncodeFrame>::new()),
Ok(frames) => Ok(frames.drain(..)),
Err(code) => Err(anyhow!("VRAM encode failed: {}", code)),
}
}
fn encode_repeat(&mut self, ms: i64) -> ResultType<std::vec::Drain<'_, EncodeFrame>> {
match self.encoder.encode_repeat(ms) {
Ok(frames) => Ok(frames.drain(..)),
Err(code) => Err(anyhow!("VRAM repeat encode failed: {}", code)),
}
}
@@ -340,6 +339,7 @@ impl VRamDecoder {
crate::hwcodec::HwCodecConfig::get()
.vram_decode
.drain(..)
.filter(|c| c.driver == Driver::FFMPEG)
.filter(|c| c.data_format == data_format && c.luid == luid && luid != 0)
.collect()
}
@@ -350,8 +350,10 @@ impl VRamDecoder {
}
let v = crate::hwcodec::HwCodecConfig::get().vram_decode;
(
v.iter().any(|d| d.data_format == DataFormat::H264),
v.iter().any(|d| d.data_format == DataFormat::H265),
v.iter()
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H264),
v.iter()
.any(|d| d.driver == Driver::FFMPEG && d.data_format == DataFormat::H265),
)
}
+244
View File
@@ -0,0 +1,244 @@
use super::VRamEncoder;
use crate::{codec::EncoderApi, EncodeInput};
use base::message_proto::{video_frame, VideoFrame};
use hwcodec::{
common::{DataFormat, Driver, MAX_GOP},
ffmpeg::AVHWDeviceType,
ffmpeg_ram::decode::{DecodeContext, Decoder},
vram::{encode::Encoder, DynamicContext, EncodeContext, FeatureContext},
};
use std::{mem, ptr};
use winapi::{
shared::{
dxgi::{CreateDXGIFactory1, IDXGIFactory1},
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
dxgitype::DXGI_SAMPLE_DESC,
winerror::DXGI_ERROR_NOT_FOUND,
},
um::{d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown},
Interface,
};
struct Com<T>(*mut T);
impl<T> Drop for Com<T> {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { (*(self.0 as *mut IUnknown)).Release() };
}
}
}
unsafe fn texture(
device: *mut ID3D11Device,
width: u32,
height: u32,
shade: u8,
) -> Com<ID3D11Texture2D> {
let pixels = pixels(width, height, shade);
let desc = D3D11_TEXTURE2D_DESC {
Width: width,
Height: height,
MipLevels: 1,
ArraySize: 1,
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
CPUAccessFlags: 0,
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
};
let data = D3D11_SUBRESOURCE_DATA {
pSysMem: pixels.as_ptr() as _,
SysMemPitch: width * 4,
SysMemSlicePitch: 0,
};
let mut raw = ptr::null_mut();
assert_eq!((*device).CreateTexture2D(&desc, &data, &mut raw), 0);
Com(raw)
}
fn pixels(width: u32, height: u32, shade: u8) -> Vec<u8> {
[shade, shade, shade, 255].repeat((width * height) as usize)
}
fn check_picture(
decoder: &mut Decoder,
frame: VideoFrame,
width: u32,
height: u32,
bright: bool,
pts: i64,
) {
let frames = match frame.union.unwrap() {
video_frame::Union::H264s(frames) | video_frame::Union::H265s(frames) => frames,
_ => panic!("unexpected codec"),
};
let mut decoded = 0;
for packet in frames.frames {
assert_eq!(packet.pts, pts);
for picture in decoder.decode(&packet.data).unwrap() {
assert_eq!((picture.width, picture.height), (width as _, height as _));
let center = (height as usize / 2) * picture.linesize[0] as usize + width as usize / 2;
let y = picture.data[0][center];
assert!(
if bright { y > 160 } else { y < 90 },
"stale or overwritten pixels: expected bright={}, got Y={}",
bright,
y
);
decoded += 1;
}
}
assert!(decoded > 0, "encoder output did not decode to a picture");
}
#[test]
#[ignore = "requires hardware H.264/H.265 encoders; run explicitly on GPU hosts"]
fn hardware_repeats_own_pixels_and_reset_on_recreation() {
unsafe {
let mut raw_factory = ptr::null_mut();
assert_eq!(
CreateDXGIFactory1(&IDXGIFactory1::uuidof(), &mut raw_factory),
0
);
let factory = Com(raw_factory as *mut IDXGIFactory1);
let mut tested = 0;
for index in 0.. {
let mut raw_adapter = ptr::null_mut();
let result = (*factory.0).EnumAdapters1(index, &mut raw_adapter);
if result == DXGI_ERROR_NOT_FOUND {
break;
}
assert_eq!(result, 0);
let adapter = Com(raw_adapter);
let mut desc = mem::zeroed();
assert_eq!((*adapter.0).GetDesc1(&mut desc), 0);
let vendor = match desc.VendorId {
0x10de => Driver::NV,
0x1002 => Driver::AMF,
0x8086 => Driver::MFX,
_ => continue,
};
let luid = ((desc.AdapterLuid.HighPart as i64) << 32) | desc.AdapterLuid.LowPart as i64;
let mut raw_device = ptr::null_mut();
let mut raw_context = ptr::null_mut();
assert_eq!(
D3D11CreateDevice(
adapter.0 as _,
D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(),
D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
ptr::null(),
0,
D3D11_SDK_VERSION,
&mut raw_device,
ptr::null_mut(),
&mut raw_context,
),
0
);
let device = Com(raw_device);
let context = Com(raw_context);
for driver in [Driver::FFMPEG, vendor.clone()] {
for format in [DataFormat::H264, DataFormat::H265] {
for (width, height) in [(320, 240), (640, 360)] {
let ctx = EncodeContext {
f: FeatureContext {
driver: driver.clone(),
vendor: vendor.clone(),
luid,
data_format: format,
},
d: DynamicContext {
device: Some(device.0 as _),
width: width as _,
height: height as _,
kbitrate: 1000,
framerate: 30,
gop: MAX_GOP as _,
},
};
let native = match Encoder::new(ctx.clone()) {
Ok(encoder) => encoder,
Err(()) => {
eprintln!(
"SKIP unavailable {:?} {:?} {:?} adapter={luid:#x}",
vendor, driver, format
);
continue;
}
};
let mut encoder = VRamEncoder {
encoder: native,
format,
ctx,
bitrate: 1000,
};
assert!(encoder.encode_to_message(EncodeInput::Repeat, 0).is_err());
assert!(encoder
.encode_to_message(EncodeInput::Texture((ptr::null_mut(), 0)), 0)
.is_err());
let mut decoder = Decoder::new(DecodeContext {
name: if format == DataFormat::H264 {
"h264"
} else {
"hevc"
}
.into(),
device_type: AVHWDeviceType::AV_HWDEVICE_TYPE_NONE,
thread_count: 1,
})
.unwrap();
let source = texture(device.0, width, height, 32);
let frame = encoder
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 0)
.unwrap();
check_picture(&mut decoder, frame, width, height, false, 0);
// Overwrite and release the capture resource before any repeats.
let overwritten = pixels(width, height, 224);
(*context.0).UpdateSubresource(
source.0 as _,
0,
ptr::null(),
overwritten.as_ptr() as _,
width * 4,
0,
);
(*context.0).Flush();
drop(source);
for count in 1..=100 {
let pts = count * 100;
let frame =
encoder.encode_to_message(EncodeInput::Repeat, pts).unwrap();
check_picture(&mut decoder, frame, width, height, false, pts);
}
let source = texture(device.0, width, height, 224);
let frame = encoder
.encode_to_message(EncodeInput::Texture((source.0 as _, 0)), 10100)
.unwrap();
check_picture(&mut decoder, frame, width, height, true, 10100);
drop(source);
encoder.encoder.set_bitrate(1500).unwrap();
let frame = encoder
.encode_to_message(EncodeInput::Repeat, 10200)
.unwrap();
check_picture(&mut decoder, frame, width, height, true, 10200);
eprintln!(
"PASS {:?} {:?} {:?} {width}x{height} adapter={luid:#x}",
vendor, driver, format
);
tested += 1;
}
}
}
}
assert!(tested > 0, "no hardware encoders were tested");
eprintln!("Validated {tested} encoder/codec/resolution combinations");
}
}
-35
View File
@@ -176,38 +176,3 @@ impl Drop for CapturerGDI {
}
}
}
#[cfg(test)]
mod tests {
use super::super::*;
use super::*;
#[test]
fn test() {
match Displays::new().unwrap().next() {
Some(d) => {
let w = d.width();
let h = d.height();
let c = CapturerGDI::new(d.name(), w, h).unwrap();
let mut data = Vec::new();
c.frame(&mut data).unwrap();
let mut bitflipped = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
let i = (w * 4 * y + 4 * x) as usize;
bitflipped.extend_from_slice(&[data[i + 2], data[i + 1], data[i], 255]);
}
}
repng::encode(
std::fs::File::create("gdi_screen.png").unwrap(),
d.width() as u32,
d.height() as u32,
&bitflipped,
)
.unwrap();
}
_ => {
assert!(false);
}
}
}
}
-14
View File
@@ -692,17 +692,3 @@ impl CapturerMag {
TRUE
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let mut capture_mag = CapturerMag::new((0, 0), 1920, 1080).unwrap();
capture_mag.exclude("", "RustDeskPrivacyWindow").unwrap();
std::thread::sleep(std::time::Duration::from_millis(1000 * 10));
let mut data = Vec::new();
capture_mag.frame(&mut data).unwrap();
println!("capture data len: {}", data.len());
}
}
+5 -152
View File
@@ -21,10 +21,10 @@ const COMMAND_TIMEOUT: Duration = Duration::from_millis(1000);
// drm builds only: an unnamed-endpoint failure there forks the probe child, and the pollers
// turn every few hundred milliseconds. Every other failure is one cheap in-process error.
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
const FAILED_LOOKUP_BACKOFF: Duration = Duration::from_secs(5);
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
static LAST_FAILED_LOOKUP: Mutex<Option<Instant>> = Mutex::new(None);
#[cfg(feature = "drm")]
@@ -183,8 +183,7 @@ fn get_primary_monitor() -> Option<String> {
.or_else(try_gdbus_primary)
}
// Pure, so the backoff policy is testable without a compositor.
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
fn lookup_allowed(failed_at: Option<Instant>, now: Instant) -> bool {
failed_at.map_or(true, |at| {
now.saturating_duration_since(at) >= FAILED_LOOKUP_BACKOFF
@@ -302,6 +301,7 @@ pub fn clear_wayland_displays_cache() {
// every OTHER live capturer on a multi-display session. A capturer records this at build and
// treats a later bump as "the layout changed under me, rebuild" — the only trigger a rotation
// has, since it changes neither the CRTC mode nor the framebuffer size (rustdesk#15886).
#[cfg(feature = "drm")]
static SNAPSHOT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Whether no snapshot has been cached: the signature of an enumeration that failed at session
@@ -311,7 +311,7 @@ pub fn wayland_snapshot_missing() -> bool {
DISPLAYS.lock().unwrap().is_none()
}
#[cfg(any(test, feature = "drm"))]
#[cfg(feature = "drm")]
pub fn bump_layout_generation() {
SNAPSHOT_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Release);
}
@@ -516,40 +516,6 @@ fn map_axis(v: i32, base_origin: i32, base_extent: i32, live_origin: i32, live_e
mod tests {
use super::*;
#[test]
fn test_lookup_backoff_boundaries() {
// Future `now`s sidestep Instant subtraction, which can panic near boot.
let failed_at = Instant::now();
assert!(lookup_allowed(None, failed_at));
assert!(!lookup_allowed(
Some(failed_at),
failed_at + FAILED_LOOKUP_BACKOFF / 2
));
assert!(lookup_allowed(
Some(failed_at),
failed_at + FAILED_LOOKUP_BACKOFF
));
}
#[test]
fn test_lookup_stamp_from_the_future_only_waits() {
// saturating_duration_since answers zero rather than underflowing.
let now = Instant::now();
assert!(!lookup_allowed(Some(now + FAILED_LOOKUP_BACKOFF), now));
}
#[test]
fn test_clear_keeps_the_failure_stamp() {
// The stamp describes the seat, not the cache: the ~1/s capturer rebuild loop clears,
// and dropping the stamp with it would defeat the backoff. The generation test also
// calls clear now; both only assert monotonic/unchanged state, so they can interleave.
*LAST_FAILED_LOOKUP.lock().unwrap() = Some(Instant::now());
clear_wayland_displays_cache();
let stamp = *LAST_FAILED_LOOKUP.lock().unwrap();
assert!(stamp.is_some());
*LAST_FAILED_LOOKUP.lock().unwrap() = None;
}
fn display(
x: i32,
y: i32,
@@ -569,11 +535,6 @@ mod tests {
}
}
#[test]
fn test_desktop_rect_empty() {
assert_eq!(desktop_rect_of(&[]), None);
}
#[test]
fn test_desktop_rect_single_display_uses_physical_size() {
let displays = [display(0, 0, 2880, 1800, Some((1859, 1162)))];
@@ -591,15 +552,6 @@ mod tests {
assert_eq!(desktop_rect_of(&displays), Some((0, 3779, 0, 2160)));
}
#[test]
fn test_desktop_rect_missing_logical_size_falls_back_to_physical() {
let displays = [
display(0, 0, 2560, 1440, None),
display(2560, 0, 2560, 1440, Some((2560, 1440))),
];
assert_eq!(desktop_rect_of(&displays), Some((0, 5120, 0, 1440)));
}
#[test]
fn a_single_rotated_display_swaps_the_uinput_rect() {
// Review finding 1 on rustdesk#15889: the single-display branch served the unrotated
@@ -611,31 +563,6 @@ mod tests {
assert_eq!((rects[0].w, rects[0].h), (1080, 1920));
}
#[test]
fn a_transform_flip_is_visible_to_the_drift_comparison() {
// Review finding 5: 0<->180 and 90<->270 leave every rect identical; the transform
// field is what lets `baseline != live` fire on them.
let mut a = display(0, 0, 1920, 1080, Some((1920, 1080)));
let mut b = a.clone();
a.transform = 90;
b.transform = 270;
assert_ne!(logical_rects_of(&[a.clone(), a.clone()]), logical_rects_of(&[b.clone(), b]));
}
#[test]
fn only_the_explicit_bump_moves_the_generation() {
// A cache clear must NOT bump: session inits clear too, and a bump there rebuilds
// every other live capturer (adversarial finding on the first version of this).
let before = SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire);
clear_wayland_displays_cache();
assert_eq!(
SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire),
before
);
bump_layout_generation();
assert!(SNAPSHOT_GENERATION.load(std::sync::atomic::Ordering::Acquire) > before);
}
fn rect(name: &str, x: i32, y: i32, w: i32, h: i32) -> DisplayRect {
DisplayRect {
name: name.to_owned(),
@@ -671,16 +598,6 @@ mod tests {
);
}
// A point on the rescaled display itself is squeezed to its new logical width.
#[test]
fn test_remap_scales_within_resized_display() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2048, 1440), rect("DP-2", 2048, 0, 2560, 1440)];
// x=1280 across the 2560-wide baseline DP-1 -> proportionally across the 2048-wide
// live DP-1 (endpoint-preserving scale, so ~1px off the naive midpoint).
assert_eq!(remap_to_live_layout(1280, 500, &baseline, &live), (1023, 500));
}
// The far edge of the followed display stays reachable when it is enlarged, so hot
// corners keep working. Baseline DP-1 is 2048 wide, live DP-1 is 2560 wide; the
// client's last column (2047) must map to the live last column (2559), not 2558.
@@ -692,57 +609,6 @@ mod tests {
assert_eq!(remap_to_live_layout(0, 0, &baseline, &live), (0, 0));
}
// No drift: identical layouts map every point to itself.
#[test]
fn test_remap_identity_when_unchanged() {
let layout = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
assert_eq!(remap_to_live_layout(3000, 700, &layout, &layout), (3000, 700));
}
// Point outside every baseline display is left untouched.
#[test]
fn test_remap_point_outside_all_displays_unchanged() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2048, 1440)];
assert_eq!(remap_to_live_layout(9000, 9000, &baseline, &live), (9000, 9000));
}
// Matched display gone from the live layout (e.g. unplugged): leave the point be
// rather than mapping it somewhere wrong.
#[test]
fn test_remap_display_removed_unchanged() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2560, 1440)];
assert_eq!(remap_to_live_layout(2600, 100, &baseline, &live), (2600, 100));
}
// Nameless compositor: fall back to index matching while the count is unchanged.
#[test]
fn test_remap_nameless_index_fallback() {
let baseline = [rect("", 0, 0, 2560, 1440), rect("", 2560, 0, 2560, 1440)];
let live = [rect("", 0, 0, 2048, 1440), rect("", 2048, 0, 2560, 1440)];
assert_eq!(remap_to_live_layout(2560, 0, &baseline, &live), (2048, 0));
}
// Nameless compositor with a changed count: cannot index-match safely, so no-op.
#[test]
fn test_remap_nameless_count_changed_unchanged() {
let baseline = [rect("", 0, 0, 2560, 1440), rect("", 2560, 0, 2560, 1440)];
let live = [rect("", 0, 0, 2048, 1440)];
assert_eq!(remap_to_live_layout(2560, 0, &baseline, &live), (2560, 0));
}
// A named display absent from the live layout, but the count is unchanged (e.g. a
// monitor was swapped for a different one at the same index): the index fallback is
// for nameless layouts only, so a named miss stays unchanged rather than mapping to
// whatever now occupies that index.
#[test]
fn test_remap_named_miss_equal_count_unchanged() {
let baseline = [rect("DP-1", 0, 0, 2560, 1440), rect("DP-2", 2560, 0, 2560, 1440)];
let live = [rect("DP-1", 0, 0, 2048, 1440), rect("HDMI-1", 2048, 0, 1920, 1080)];
assert_eq!(remap_to_live_layout(2600, 100, &baseline, &live), (2600, 100));
}
// A single display uses physical size in both baseline and live (scale reported as
// 1.0), so it never drifts and the remap is a no-op even across a rescale.
#[test]
@@ -753,17 +619,4 @@ mod tests {
vec![rect("", 0, 0, 2560, 1440)]
);
}
// Multiple displays use logical size, falling back to physical when absent.
#[test]
fn test_logical_rects_multi_display_uses_logical() {
let displays = [
display(0, 0, 2560, 1440, Some((2048, 1152))),
display(2048, 0, 1920, 1080, None),
];
assert_eq!(
logical_rects_of(&displays),
vec![rect("", 0, 0, 2048, 1152), rect("", 2048, 0, 1920, 1080)]
);
}
}
+134 -18
View File
@@ -23,7 +23,7 @@ use gstreamer_app::AppSink;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use base::platform::linux::CMD_SH;
use base::platform::linux::{WaylandDisplayInfo, CMD_SH};
use hbb_common::{anyhow::anyhow, bail, config, serde_json, tokio, ResultType};
use super::capturable::PixelProvider;
@@ -77,7 +77,9 @@ pub fn close_session() {
#[inline]
pub fn is_rdp_session_hold() -> bool {
RDP_SESSION_INFO.lock().unwrap().is_some()
// try_lock: a request waiting for the user holds the slot (no session yet), and so do the short
// looks while a session is set up. Busy answers no session rather than wait.
matches!(RDP_SESSION_INFO.try_lock(), Ok(info) if info.is_some())
}
pub fn try_close_session() {
@@ -157,6 +159,9 @@ 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 {
@@ -168,7 +173,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 physical_size = get_res(Self {
let measured = get_res(Self {
dbus_conn: conn.clone(),
fd: fd.clone(),
path: stream.path,
@@ -177,8 +182,10 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size: (0, 0),
})
.unwrap_or(stream.size);
physical_size_measured: false,
});
let physical_size_measured = measured.is_ok();
let physical_size = measured.unwrap_or(stream.size);
*resolution.lock().unwrap() = Some(physical_size);
Self {
dbus_conn: conn,
@@ -189,6 +196,7 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size,
physical_size_measured,
}
}
}
@@ -1291,6 +1299,26 @@ 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);
}
@@ -1303,6 +1331,50 @@ 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)>,
@@ -1605,6 +1677,7 @@ 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>) =
@@ -1731,26 +1804,69 @@ fn sort_streams(
#[cfg(test)]
mod tests {
use super::stage_err;
use super::{corrected_origin, 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 stage_err_keeps_the_detail_safe_for_a_placeholder() {
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!(
stage_err("start", "declined", ""),
"wl-stage:start:declined:"
corrected_origin((0, 0), (2880, 1800), &pair),
Some((1920, 0))
);
// Braces of its own would break the placeholder lookup on the peer.
// 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!(
stage_err("create-session", "dbus", "org.freedesktop.{Error}"),
"wl-stage:create-session:dbus:org.freedesktop.Error"
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!(
stage_err("select-sources", "internal", "one\ntwo"),
"wl-stage:select-sources:internal:one two"
);
assert_eq!(
stage_err("start", "internal", &"x".repeat(300)),
format!("wl-stage:start:internal:{}", "x".repeat(200))
corrected_origin((0, 0), (1920, 1080), &turned_right),
Some((2560, 0))
);
}
}
+28 -5
View File
@@ -12,7 +12,12 @@ use super::{Display, Rect, Server};
pub struct DisplayIter {
outer: xcb_screen_iterator_t,
inner: Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)>,
// The monitor iterator points into the reply, so the reply is freed only when moving on.
inner: Option<(
xcb_randr_monitor_info_iterator_t,
xcb_window_t,
*mut xcb_randr_get_monitors_reply_t,
)>,
server: Rc<Server>,
}
@@ -30,7 +35,11 @@ impl DisplayIter {
fn next_screen(
outer: &mut xcb_screen_iterator_t,
server: &Server,
) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> {
) -> Option<(
xcb_randr_monitor_info_iterator_t,
xcb_window_t,
*mut xcb_randr_get_monitors_reply_t,
)> {
if outer.rem == 0 {
return None;
}
@@ -48,10 +57,17 @@ impl DisplayIter {
let inner = xcb_randr_get_monitors_monitors_iterator(response);
libc::free(response as *mut _);
xcb_screen_next(outer);
Some((inner, root))
Some((inner, root, response))
}
}
fn free_reply(&mut self) {
if let Some((_, _, response)) = self.inner.take() {
unsafe {
libc::free(response as *mut _);
}
}
}
}
@@ -61,7 +77,7 @@ impl Iterator for DisplayIter {
fn next(&mut self) -> Option<Display> {
loop {
if let Some((ref mut inner, root)) = self.inner {
if let Some((ref mut inner, root, _)) = self.inner {
// If there is something in the current screen, return that.
if inner.rem != 0 {
unsafe {
@@ -92,11 +108,18 @@ impl Iterator for DisplayIter {
}
// The current screen was empty, so try the next screen.
self.free_reply();
self.inner = Self::next_screen(&mut self.outer, &self.server);
}
}
}
impl Drop for DisplayIter {
fn drop(&mut self) {
self.free_reply();
}
}
fn get_atom_name(conn: *mut xcb_connection_t, atom: xcb_atom_t) -> String {
let empty = "".to_owned();
if atom == 0 {
+1 -1
View File
@@ -1,5 +1,5 @@
pkgname=rustdesk
pkgver=1.5.0
pkgver=1.5.1
pkgrel=0
epoch=
pkgdesc=""
+1
View File
@@ -14,3 +14,4 @@ EXPORTS
RemoveAmyuniIdd
InstallPrinter
UninstallPrinter
SetPrinterInstallDefault
+66
View File
@@ -3,6 +3,7 @@
#include <Windows.h>
#include <winspool.h>
#include <setupapi.h>
#include <strutil.h>
#include <memory>
#include <string>
#include <functional>
@@ -356,6 +357,42 @@ 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)
@@ -528,3 +565,32 @@ 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,13 +74,22 @@
<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="RestoreSavedPrinterValue" Sequence="first" Condition="INSTALLPRINTER = 1 OR INSTALLPRINTER = &quot;Y&quot; OR INSTALLPRINTER = &quot;y&quot;" />
<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="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>
+1 -1
View File
@@ -1,5 +1,5 @@
Name: rustdesk
Version: 1.5.0
Version: 1.5.1
Release: 0
Summary: RPM package
License: GPL-3.0
+1 -1
View File
@@ -1,5 +1,5 @@
Name: rustdesk
Version: 1.5.0
Version: 1.5.1
Release: 0
Summary: RPM package
License: GPL-3.0
+1 -1
View File
@@ -1,5 +1,5 @@
Name: rustdesk
Version: 1.5.0
Version: 1.5.1
Release: 0
Summary: RPM package
License: GPL-3.0
+297
View File
@@ -0,0 +1,297 @@
#!/usr/bin/env python3
import argparse
import base64
import binascii
import hashlib
import json
import os
import re
from pathlib import Path
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
from update_metadata_policy import (
release_artifact_url,
validate_artifact_file_name,
validate_package_id,
validate_published_at,
validate_release,
validate_release_base_url,
)
APP_NAME = "rustdesk"
SCHEMA_VERSION = 1
SIGNATURE_ALGORITHM = "ed25519"
SIGNATURE_CONTEXT = b"RustDesk update metadata v1\n"
KEY_ID = "2026-ed25519-main"
SEED_ENV = "RUSTDESK_UPDATE_ED25519_SEED"
PUBLIC_KEY_ENV = "RUSTDESK_UPDATE_ED25519_PUBLIC_KEY"
def fail(message):
raise SystemExit(message)
def stable_json(value):
return json.dumps(value, separators=(",", ":"), sort_keys=True).encode("utf-8")
def write_bytes(path, data):
output = Path(path)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(data)
def sha256_hex(path):
hasher = hashlib.sha256()
with Path(path).open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
hasher.update(chunk)
return hasher.hexdigest()
def decode_env(name, expected_size):
encoded = os.environ.get(name)
if not encoded:
fail(f"missing environment variable: {name}")
try:
value = base64.b64decode(encoded, validate=True)
except (ValueError, binascii.Error) as error:
fail(f"invalid base64 in {name}: {error}")
if len(value) != expected_size:
fail(f"{name} must decode to {expected_size} bytes")
if base64.b64encode(value).decode("ascii") != encoded:
fail(f"{name} must use canonical base64")
return value
def validate_or_fail(function, *args):
try:
return function(*args)
except ValueError as error:
fail(str(error))
def artifact_metadata(spec, release_id, release_base_url):
platform, arch, file_format, raw_path = spec
if not all(value.strip() for value in (platform, arch, file_format)):
fail("artifact selector fields must not be empty")
path = Path(raw_path)
file_name = path.name
validate_or_fail(validate_artifact_file_name, file_name)
size = path.stat().st_size
if size == 0:
fail(f"artifact must not be empty: {file_name}")
return {
"platform": platform,
"arch": arch,
"format": file_format,
"url": release_artifact_url(release_base_url, release_id, file_name),
"file_name": file_name,
"size": size,
"sha256": sha256_hex(path),
}
def command_sign(args):
metadata_out = Path(args.metadata_out).resolve()
signature_out = Path(args.signature_out).resolve()
if metadata_out == signature_out:
fail("metadata and signature outputs must be different files")
validate_or_fail(validate_release, args.release_id, args.version)
validate_or_fail(validate_published_at, args.published_at)
package_id = validate_or_fail(validate_package_id, args.package_id)
release_base_url = validate_or_fail(
validate_release_base_url, args.release_base_url
)
artifacts = [
artifact_metadata(spec, args.release_id, release_base_url)
for spec in args.artifact
]
selectors = [(item["platform"], item["arch"], item["format"]) for item in artifacts]
names = [item["file_name"] for item in artifacts]
if len(set(selectors)) != len(selectors):
fail("duplicate artifact selector")
if len(set(names)) != len(names):
fail("duplicate artifact file name")
artifacts.sort(key=lambda item: (item["platform"], item["arch"], item["format"]))
metadata = {
"schema_version": SCHEMA_VERSION,
"app": APP_NAME,
"package_id": package_id,
"version": args.version,
"release_id": args.release_id,
"published_at": args.published_at,
"signature_key_id": KEY_ID,
"artifacts": artifacts,
}
private_key = ed25519.Ed25519PrivateKey.from_private_bytes(decode_env(SEED_ENV, 32))
metadata_bytes = stable_json(metadata)
signature = {
"schema_version": SCHEMA_VERSION,
"algorithm": SIGNATURE_ALGORITHM,
"key_id": KEY_ID,
"signature": base64.b64encode(
private_key.sign(SIGNATURE_CONTEXT + metadata_bytes)
).decode("ascii"),
}
write_bytes(metadata_out, metadata_bytes)
write_bytes(signature_out, stable_json(signature))
def verify_metadata_signature(metadata_bytes, signature):
if (
signature.get("schema_version") != SCHEMA_VERSION
or signature.get("algorithm") != SIGNATURE_ALGORITHM
or signature.get("key_id") != KEY_ID
):
fail("invalid signature metadata")
public_key = ed25519.Ed25519PublicKey.from_public_bytes(decode_env(PUBLIC_KEY_ENV, 32))
try:
public_key.verify(
base64.b64decode(signature["signature"], validate=True),
SIGNATURE_CONTEXT + metadata_bytes,
)
except (InvalidSignature, ValueError, binascii.Error):
fail("invalid metadata signature")
def validated_artifacts(metadata, local_artifacts):
artifacts = metadata.get("artifacts")
if not isinstance(artifacts, list) or not artifacts:
fail("metadata must contain artifacts")
selector_fields = ("platform", "arch", "format")
required_fields = selector_fields + ("file_name", "url", "size", "sha256")
if any(
not isinstance(artifact, dict)
or any(field not in artifact for field in required_fields)
for artifact in artifacts
):
fail("artifact metadata is missing required fields")
names = [artifact.get("file_name") for artifact in artifacts]
for file_name in names:
validate_or_fail(validate_artifact_file_name, file_name)
selectors = [
tuple(artifact[field] for field in selector_fields)
for artifact in artifacts
]
if any(
not all(isinstance(value, str) and value.strip() for value in selector)
for selector in selectors
):
fail("artifact selector fields must be non-empty strings")
if len(set(names)) != len(names) or set(names) != set(local_artifacts):
fail("artifact file set mismatch")
if len(set(selectors)) != len(selectors):
fail("duplicate artifact selector")
return artifacts
def command_verify(args):
metadata_bytes = Path(args.metadata).read_bytes()
metadata = json.loads(metadata_bytes)
signature = json.loads(Path(args.signature).read_bytes())
verify_metadata_signature(metadata_bytes, signature)
package_id = validate_or_fail(validate_package_id, args.package_id)
release_base_url = validate_or_fail(
validate_release_base_url, args.release_base_url
)
expected_fields = {
"schema_version": SCHEMA_VERSION,
"app": APP_NAME,
"package_id": package_id,
"version": args.version,
"release_id": args.release_id,
"signature_key_id": KEY_ID,
}
if any(metadata.get(key) != value for key, value in expected_fields.items()):
fail("metadata does not match the release")
validate_or_fail(validate_release, args.release_id, args.version)
validate_or_fail(validate_published_at, metadata.get("published_at", ""))
local_paths = [Path(path) for path in args.artifact]
local_artifacts = {path.name: path for path in local_paths}
if len(local_artifacts) != len(local_paths):
fail("duplicate local artifact file name")
artifacts = validated_artifacts(metadata, local_artifacts)
for artifact in artifacts:
file_name = artifact["file_name"]
expected_url = release_artifact_url(
release_base_url, args.release_id, file_name
)
if artifact["url"] != expected_url:
fail(f"artifact URL mismatch for {file_name}")
path = local_artifacts[file_name]
if path.stat().st_size != artifact["size"]:
fail(f"artifact size mismatch for {file_name}")
if sha256_hex(path) != artifact["sha256"]:
fail(f"artifact sha256 mismatch for {file_name}")
def command_check_key(args):
seed = decode_env(SEED_ENV, 32)
configured_key = decode_env(PUBLIC_KEY_ENV, 32)
derived_key = ed25519.Ed25519PrivateKey.from_private_bytes(seed).public_key()
derived_key_bytes = derived_key.public_bytes(
serialization.Encoding.Raw,
serialization.PublicFormat.Raw,
)
if derived_key_bytes != configured_key:
fail(f"{SEED_ENV} does not match {PUBLIC_KEY_ENV}")
source = Path(args.rust_source).read_text(encoding="utf-8")
match = re.search(
rf'TrustedUpdateKey\s*\{{[^{{}}]*key_id:\s*"{KEY_ID}"[^{{}}]*public_key:\s*\[([^\]]+)\]',
source,
re.S,
)
if not match:
fail("failed to find embedded update public key")
try:
embedded_key = bytes(
int(part) for part in match.group(1).split(",") if part.strip()
)
except ValueError as error:
fail(f"invalid embedded update public key: {error}")
if embedded_key != configured_key:
fail(f"embedded update public key does not match {PUBLIC_KEY_ENV}")
def build_parser():
parser = argparse.ArgumentParser()
commands = parser.add_subparsers(dest="command", required=True)
sign = commands.add_parser("sign")
sign.add_argument("--artifact", action="append", nargs=4, required=True)
sign.add_argument("--version", required=True)
sign.add_argument("--release-id", required=True)
sign.add_argument("--package-id", required=True)
sign.add_argument("--release-base-url", required=True)
sign.add_argument("--published-at", required=True)
sign.add_argument("--metadata-out", required=True)
sign.add_argument("--signature-out", required=True)
sign.set_defaults(func=command_sign)
verify = commands.add_parser("verify")
verify.add_argument("--metadata", required=True)
verify.add_argument("--signature", required=True)
verify.add_argument("--artifact", action="append", required=True)
verify.add_argument("--version", required=True)
verify.add_argument("--release-id", required=True)
verify.add_argument("--package-id", required=True)
verify.add_argument("--release-base-url", required=True)
verify.set_defaults(func=command_verify)
check_key = commands.add_parser("check-key")
check_key.add_argument(
"--rust-source", default="src/update_metadata.rs"
)
check_key.set_defaults(func=command_check_key)
return parser
def main():
args = build_parser().parse_args()
args.func(args)
if __name__ == "__main__":
main()
+300
View File
@@ -0,0 +1,300 @@
import base64
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
SCRIPT = Path(__file__).with_name("generate_update_metadata.py")
OFFICIAL_RELEASE_BASE_URL = "https://github.com/rustdesk/rustdesk/releases/download"
class GenerateUpdateMetadataTest(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.root = Path(self.temp_dir.name)
private_key = ed25519.Ed25519PrivateKey.generate()
seed = private_key.private_bytes(
serialization.Encoding.Raw,
serialization.PrivateFormat.Raw,
serialization.NoEncryption(),
)
public_key = private_key.public_key().public_bytes(
serialization.Encoding.Raw,
serialization.PublicFormat.Raw,
)
self.seed = base64.b64encode(seed).decode("ascii")
self.public_key = base64.b64encode(public_key).decode("ascii")
def tearDown(self):
self.temp_dir.cleanup()
def run_script(self, *args, seed=None, public_key=None):
env = os.environ.copy()
env.pop("RUSTDESK_UPDATE_ED25519_SEED", None)
env.pop("RUSTDESK_UPDATE_ED25519_PUBLIC_KEY", None)
if seed is not None:
env["RUSTDESK_UPDATE_ED25519_SEED"] = seed
if public_key is not None:
env["RUSTDESK_UPDATE_ED25519_PUBLIC_KEY"] = public_key
return subprocess.run(
[sys.executable, str(SCRIPT), *args],
cwd=SCRIPT.parents[2],
env=env,
text=True,
capture_output=True,
)
def artifact(self, name="rustdesk-1.4.6-x86_64.exe", data=b"rustdesk"):
path = self.root / name
path.write_bytes(data)
return path
def sign(
self,
artifacts,
*,
version="1.4.6",
release_id="v1.4.6",
package_id="rustdesk",
release_base_url=OFFICIAL_RELEASE_BASE_URL,
seed=None,
):
metadata = self.root / "rustdesk-update.json"
signature = self.root / "rustdesk-update.json.sig"
args = ["sign"]
for platform, arch, file_format, path in artifacts:
args.extend(["--artifact", platform, arch, file_format, str(path)])
args.extend(
[
"--version",
version,
"--release-id",
release_id,
"--package-id",
package_id,
"--release-base-url",
release_base_url,
"--published-at",
"2026-05-14T00:00:00Z",
"--metadata-out",
str(metadata),
"--signature-out",
str(signature),
]
)
result = self.run_script(*args, seed=self.seed if seed is None else seed)
return metadata, signature, result
def verify(
self,
metadata,
signature,
artifacts,
*,
public_key=None,
package_id="rustdesk",
release_base_url=OFFICIAL_RELEASE_BASE_URL,
):
args = [
"verify",
"--metadata",
str(metadata),
"--signature",
str(signature),
"--version",
"1.4.6",
"--release-id",
"v1.4.6",
"--package-id",
package_id,
"--release-base-url",
release_base_url,
]
for artifact in artifacts:
args.extend(["--artifact", str(artifact)])
return self.run_script(
*args,
public_key=public_key or self.public_key,
)
def rust_source(self, public_key=None):
key_bytes = base64.b64decode(public_key or self.public_key)
source = self.root / "update_metadata.rs"
source.write_text(
'TrustedUpdateKey { key_id: "2026-ed25519-main", public_key: ['
+ ",".join(str(byte) for byte in key_bytes)
+ "] }",
encoding="utf-8",
)
return source
def test_signs_and_verifies_release_artifacts(self):
exe = self.artifact()
dmg = self.artifact("rustdesk-1.4.6-aarch64.dmg", b"dmg")
specs = [("windows", "x86_64", "exe", exe), ("macos", "aarch64", "dmg", dmg)]
metadata, signature, signed = self.sign(specs)
verified = self.verify(metadata, signature, [exe, dmg])
self.assertEqual(signed.returncode, 0, signed.stderr)
self.assertEqual(verified.returncode, 0, verified.stderr)
data = json.loads(metadata.read_text(encoding="utf-8"))
self.assertEqual(data["release_id"], "v1.4.6")
self.assertEqual({item["file_name"] for item in data["artifacts"]}, {exe.name, dmg.name})
def test_verification_rejects_tampering(self):
artifact = self.artifact()
metadata, signature, _ = self.sign([("windows", "x86_64", "exe", artifact)])
artifact.write_bytes(b"tampered")
self.assertNotEqual(self.verify(metadata, signature, [artifact]).returncode, 0)
artifact.write_bytes(b"rustdesk")
data = json.loads(metadata.read_text(encoding="utf-8"))
data["published_at"] = "2026-05-15T00:00:00Z"
metadata.write_text(json.dumps(data), encoding="utf-8")
self.assertNotEqual(self.verify(metadata, signature, [artifact]).returncode, 0)
def test_verification_rejects_wrong_public_key(self):
artifact = self.artifact()
metadata, signature, _ = self.sign([("windows", "x86_64", "exe", artifact)])
wrong_key = base64.b64encode(b"x" * 32).decode("ascii")
self.assertNotEqual(
self.verify(
metadata,
signature,
[artifact],
public_key=wrong_key,
).returncode,
0,
)
def test_sign_rejects_invalid_release_inputs(self):
artifact = self.artifact()
spec = [("windows", "x86_64", "exe", artifact)]
self.assertNotEqual(self.sign(spec, version="1.4.7")[2].returncode, 0)
for release_id in ("bad/tag", "bad\tid", "bad%zz"):
self.assertNotEqual(self.sign(spec, release_id=release_id)[2].returncode, 0)
self.assertNotEqual(self.sign(spec, seed="invalid")[2].returncode, 0)
duplicate = spec + [("windows", "x86_64", "exe", artifact)]
self.assertNotEqual(self.sign(duplicate)[2].returncode, 0)
def test_signs_and_verifies_custom_release_identity(self):
package_id = "com.example.rustdesk-custom"
release_base_url = "https://updates.example.com/releases/download"
artifact = self.artifact("rustdesk-custom-1.4.6-aarch64.dmg", b"dmg")
metadata, signature, signed = self.sign(
[("macos", "aarch64", "dmg", artifact)],
package_id=package_id,
release_base_url=release_base_url,
)
verified = self.verify(
metadata,
signature,
[artifact],
package_id=package_id,
release_base_url=release_base_url,
)
self.assertEqual(signed.returncode, 0, signed.stderr)
self.assertEqual(verified.returncode, 0, verified.stderr)
data = json.loads(metadata.read_text(encoding="utf-8"))
self.assertEqual(data["package_id"], package_id)
self.assertEqual(
data["artifacts"][0]["url"],
f"{release_base_url}/v1.4.6/{artifact.name}",
)
def test_rejects_unsafe_custom_release_policy(self):
artifact = self.artifact("rustdesk-custom-1.4.6-aarch64.dmg", b"dmg")
spec = [("macos", "aarch64", "dmg", artifact)]
for package_id in ("", "com.example/custom", "com.example custom"):
with self.subTest(package_id=package_id):
self.assertNotEqual(
self.sign(spec, package_id=package_id)[2].returncode,
0,
)
for release_base_url in (
"http://updates.example.com/releases",
"https://user@updates.example.com/releases",
"https://updates.example.com/releases/",
"https://updates.example.com/releases?channel=stable",
"https://updates.example.com/relea\nses",
):
with self.subTest(release_base_url=release_base_url):
self.assertNotEqual(
self.sign(spec, release_base_url=release_base_url)[2].returncode,
0,
)
def test_checks_embedded_public_key(self):
source = self.rust_source()
result = self.run_script(
"check-key",
"--rust-source",
str(source),
seed=self.seed,
public_key=self.public_key,
)
self.assertEqual(result.returncode, 0, result.stderr)
def test_check_key_rejects_invalid_or_mismatched_seed(self):
source = self.rust_source()
invalid_seeds = [
None,
"invalid",
base64.b64encode(b"x" * 31).decode("ascii"),
base64.b64encode(b"x" * 32).decode("ascii"),
]
for seed in invalid_seeds:
with self.subTest(seed=seed):
result = self.run_script(
"check-key",
"--rust-source",
str(source),
seed=seed,
public_key=self.public_key,
)
self.assertNotEqual(result.returncode, 0)
def test_check_key_rejects_invalid_public_key(self):
source = self.rust_source()
invalid_keys = [
None,
"invalid",
base64.b64encode(b"x" * 31).decode("ascii"),
]
for public_key in invalid_keys:
with self.subTest(public_key=public_key):
result = self.run_script(
"check-key",
"--rust-source",
str(source),
seed=self.seed,
public_key=public_key,
)
self.assertNotEqual(result.returncode, 0)
def test_check_key_rejects_mismatched_embedded_key(self):
embedded_key = base64.b64encode(b"x" * 32).decode("ascii")
result = self.run_script(
"check-key",
"--rust-source",
str(self.rust_source(embedded_key)),
seed=self.seed,
public_key=self.public_key,
)
self.assertNotEqual(result.returncode, 0)
if __name__ == "__main__":
unittest.main()
+104
View File
@@ -0,0 +1,104 @@
import plistlib
import socket
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
MACOS_SOURCE = (REPOSITORY_ROOT / "src/platform/macos.rs").read_text(
encoding="utf-8"
)
DAEMON_SCRIPT = (
REPOSITORY_ROOT / "src/platform/privileges_scripts/update.scpt"
).read_text(encoding="utf-8")
MANUAL_SCRIPT = MACOS_SOURCE.split(
'const PRIVILEGED_UPDATE_BODY: &str = r#"', 1
)[1].split('"#;', 1)[0]
def write_bundle_id(app, bundle_id):
if bundle_id is None:
return
info = app / "Contents/Info.plist"
info.parent.mkdir(parents=True)
info.write_bytes(plistlib.dumps({"CFBundleIdentifier": bundle_id}))
class MacosUpdateScriptTests(unittest.TestCase):
@unittest.skipUnless(sys.platform == "darwin", "requires macOS AppleScript")
def test_daemon_update_rejects_stale_ipc_sockets(self):
with tempfile.TemporaryDirectory(dir="/tmp") as directory:
for check in ("check_service", "check_agent"):
with self.subTest(check=check), socket.socket(
socket.AF_UNIX, socket.SOCK_STREAM
) as listener:
path = str(Path(directory) / check)
listener.bind(path)
listener.listen(1)
script = DAEMON_SCRIPT.split(" set sh to", 1)[0]
script += f" return {check}\nend run\n"
script = script.replace("/tmp/RustDesk-service/ipc_service", path)
script = script.replace("/tmp/RustDesk-$uid/ipc", path)
command = subprocess.check_output(
["osascript", "-e", script, "test", "0", "", ""],
text=True,
timeout=10,
)
command = "launchctl() { echo 'state = running'; }; " + command
args = ["/bin/sh", "-c", command]
self.assertEqual(subprocess.call(args, timeout=10), 0)
listener.setblocking(False)
with self.assertRaises(BlockingIOError):
connection, _ = listener.accept()
connection.close()
listener.close()
self.assertNotEqual(subprocess.call(args, timeout=10), 0)
@unittest.skipUnless(sys.platform == "darwin", "requires macOS AppleScript")
def test_manual_update_requires_matching_bundle_identity(self):
validation = next(
line for line in MANUAL_SCRIPT.splitlines()
if "set validate_verified_app" in line
)
script = "\n".join([
"on run {app_bundle, expected_bundle_id}",
"set app_bundle_q to quoted form of app_bundle",
'set installed_info_q to quoted form of (app_bundle & "/Contents/Info.plist")',
"set expected_bundle_id_q to quoted form of expected_bundle_id",
validation,
"return validate_verified_app",
"end run",
])
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
root = Path(directory.name)
bundle_id = "com.carriez.rustdesk"
cases = (
("new", None, bundle_id, 0),
("installed", bundle_id, bundle_id, 0),
("wrong_candidate", None, "example.other", 1),
("wrong_destination", "example.other", bundle_id, 1),
)
for name, installed_id, candidate_id, exit_code in cases:
with self.subTest(case=name):
installed = root / name / "installed.app"
candidate = root / name / "candidate.app"
write_bundle_id(installed, installed_id)
write_bundle_id(candidate, candidate_id)
command = subprocess.check_output(
["osascript", "-e", script, str(installed), bundle_id],
text=True, timeout=10,
)
result = subprocess.run(
["/bin/sh", "-c", 'set -e; verified_app="$1"; ' + command,
"update-test", str(candidate)],
text=True, capture_output=True, timeout=10,
)
self.assertEqual(result.returncode, exit_code, result.stderr)
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPT = Path(__file__).with_name("generate_update_metadata.py")
class UpdateMetadataCliTests(unittest.TestCase):
def test_sign_and_verify_require_update_identity_policy(self):
commands = (
[
"sign",
"--artifact", "macos", "aarch64", "dmg", "missing.dmg",
"--version", "1.4.6",
"--release-id", "v1.4.6",
"--published-at", "invalid",
"--metadata-out", "metadata.json",
"--signature-out", "signature.json",
],
[
"verify",
"--metadata", "missing.json",
"--signature", "missing.sig",
"--artifact", "missing.dmg",
"--version", "1.4.6",
"--release-id", "v1.4.6",
],
)
for command in commands:
with self.subTest(command=command[0]):
result = subprocess.run(
[sys.executable, str(SCRIPT), *command],
text=True,
capture_output=True,
)
self.assertIn("the following arguments are required", result.stderr)
self.assertIn("--package-id", result.stderr)
self.assertIn("--release-base-url", result.stderr)
def test_sign_rejects_empty_artifact(self):
with tempfile.TemporaryDirectory() as directory:
artifact = Path(directory) / "rustdesk-1.4.6-aarch64.dmg"
artifact.touch()
result = subprocess.run(
[
sys.executable,
str(SCRIPT),
"sign",
"--artifact", "macos", "aarch64", "dmg", str(artifact),
"--version", "1.4.6",
"--release-id", "v1.4.6",
"--package-id", "rustdesk",
"--release-base-url",
"https://github.com/rustdesk/rustdesk/releases/download",
"--published-at", "2026-05-14T00:00:00Z",
"--metadata-out", str(Path(directory) / "metadata.json"),
"--signature-out", str(Path(directory) / "metadata.json.sig"),
],
env=os.environ.copy(),
text=True,
capture_output=True,
)
self.assertNotEqual(0, result.returncode)
self.assertIn("artifact must not be empty", result.stderr)
if __name__ == "__main__":
unittest.main()
+100
View File
@@ -0,0 +1,100 @@
import re
from datetime import datetime
from string import ascii_letters, digits
from urllib.parse import urlsplit
PACKAGE_ID_CHARACTERS = frozenset(ascii_letters + digits + ".-")
RFC3339_TIMESTAMP = re.compile(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt][0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?(?:[Zz]|[+-][0-9]{2}:[0-9]{2})"
)
ARTIFACT_FILE_NAME_PATTERN = re.compile(r"[A-Za-z0-9._-]+")
def validate_release(release_id, version):
if (
not release_id
or not release_id.isascii()
or release_id in {".", ".."}
or any(
char.isspace() or not char.isprintable() or char in "/\\?%#"
for char in release_id
)
):
raise ValueError(f"invalid release id: {release_id}")
match = re.fullmatch(r"v?([0-9]+)\.([0-9]+)\.([0-9]+)", release_id)
if not match:
return
segments = [int(part) for part in match.groups()]
if any(part > 65535 for part in segments) or not any(segments):
raise ValueError(f"invalid release version: {release_id}")
display_version = ".".join(match.groups())
if display_version != version:
raise ValueError(
f"release id {release_id} maps to {display_version}, not {version}"
)
def validate_published_at(value):
if not RFC3339_TIMESTAMP.fullmatch(value):
raise ValueError("published_at must be an RFC 3339 timestamp")
normalized = value[:-1] + "+00:00" if value[-1] in "Zz" else value
try:
datetime.fromisoformat(normalized)
except ValueError as error:
raise ValueError(
"published_at must be an RFC 3339 timestamp"
) from error
def validate_artifact_file_name(file_name):
if (
not isinstance(file_name, str)
or file_name in {".", ".."}
or not ARTIFACT_FILE_NAME_PATTERN.fullmatch(file_name)
):
raise ValueError(f"invalid artifact file name: {file_name}")
def validate_package_id(value):
if (
not isinstance(value, str)
or not value
or not value.isascii()
or any(char not in PACKAGE_ID_CHARACTERS for char in value)
or not any(char.isalnum() for char in value)
):
raise ValueError(f"invalid package id: {value}")
return value
def validate_release_base_url(value):
if (
not isinstance(value, str)
or not value
or not value.isascii()
or any(char.isspace() or not char.isprintable() for char in value)
or value.endswith("/")
or "\\" in value
or "?" in value
or "#" in value
):
raise ValueError(f"invalid release base URL: {value}")
try:
parsed = urlsplit(value)
parsed.port
except ValueError as error:
raise ValueError(f"invalid release base URL: {value}") from error
if (
parsed.scheme != "https"
or parsed.hostname is None
or parsed.username is not None
or parsed.password is not None
):
raise ValueError(
"release base URL must be HTTPS and must not contain credentials"
)
return value
def release_artifact_url(release_base_url, release_id, file_name):
return f"{release_base_url}/{release_id}/{file_name}"

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