Compare commits

...
Author SHA1 Message Date
rustdeskandClaude Opus 5.5 372c255293 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
2026-10-12 18:54:41 +08:00
rustdeskandClaude Opus 5.5 353045e786 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
2026-10-12 15:50:54 +08:00
rustdeskandClaude Opus 5.5 2461514476 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
2026-10-11 14:04:38 +08:00
rustdeskandClaude Opus 5.5 a3c513056a 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
2026-10-10 22:29:08 +08:00
rustdeskandClaude Opus 5.5 47544054a2 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
2026-10-10 17:40:43 +08:00
rustdeskandClaude Opus 5.5 7cd70b3d18 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
2026-10-10 16:43:00 +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
32 changed files with 2111 additions and 100 deletions
Generated
+13 -18
View File
@@ -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",
@@ -7187,6 +7175,7 @@ dependencies = [
"uuid",
"virtual_display",
"wallpaper",
"wayland-client",
"winapi 0.3.9",
"windows 0.61.1",
"windows-service",
@@ -7196,6 +7185,7 @@ dependencies = [
"wol-rs",
"x11-clipboard 0.8.1",
"x11rb 0.12.0",
"xkbcommon-dl",
"xxhash-rust",
"zstd",
]
@@ -8744,20 +8734,25 @@ dependencies = [
[[package]]
name = "tower-http"
version = "0.6.6"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"async-compression",
"bitflags 2.9.1",
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"iri-string",
"http-body-util",
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower-layer",
"tower-service",
"url",
]
[[package]]
+2
View File
@@ -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"] }
+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';
@@ -335,6 +335,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) {
+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;
}
}
+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"
);
}
}
+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
+6
View File
@@ -553,6 +553,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.
+158 -5
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;
@@ -157,6 +157,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 +171,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 +180,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 +194,7 @@ impl PipeWireCapturable {
position: stream.position,
logical_size: stream.size,
physical_size,
physical_size_measured,
}
}
}
@@ -1291,6 +1297,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 +1329,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 +1675,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,7 +1802,89 @@ fn sort_streams(
#[cfg(test)]
mod tests {
use super::stage_err;
use super::{corrected_origin, reconciled_origin, stage_err, WaylandDisplayInfo};
fn output(x: i32, y: i32, mode: (i32, i32)) -> WaylandDisplayInfo {
WaylandDisplayInfo {
name: String::new(),
x,
y,
width: mode.0,
height: mode.1,
logical_size: None,
refresh_rate: 60,
transform: 0,
}
}
#[test]
fn a_portal_position_naming_no_output_of_its_size_moves_to_the_only_one() {
// 1920x1080 at the origin, 2880x1800 to its right: xdph puts the right one at (0, 0).
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
assert_eq!(
corrected_origin((0, 0), (2880, 1800), &pair),
Some((1920, 0))
);
// A real origin is kept.
assert_eq!(corrected_origin((1920, 0), (2880, 1800), &pair), None);
// Nothing starts at the origin (the hyprland layout in #15731).
let three = [
output(0, 120, (1920, 1200)),
output(1920, 0, (3440, 1440)),
output(5360, 180, (1920, 1080)),
];
assert_eq!(
corrected_origin((0, 0), (3440, 1440), &three),
Some((1920, 0))
);
// Two outputs of that size cannot be told apart: the position is kept.
let twins = [
output(0, 0, (2560, 1600)),
output(2560, 0, (1920, 1080)),
output(4480, 0, (1920, 1080)),
];
assert_eq!(corrected_origin((0, 0), (1920, 1080), &twins), None);
// A portrait panel turned to landscape keeps its position next to a 1920x1080 output.
let turned = [
WaylandDisplayInfo {
transform: 90,
..output(0, 0, (1080, 1920))
},
output(1920, 0, (1920, 1080)),
];
assert_eq!(corrected_origin((0, 0), (1920, 1080), &turned), None);
// A rotated output that try_fill_positions could not match by its mode is found in its
// delivered orientation.
let turned_right = [
output(0, 0, (2560, 1440)),
WaylandDisplayInfo {
transform: 90,
..output(2560, 0, (1080, 1920))
},
];
assert_eq!(
corrected_origin((0, 0), (1920, 1080), &turned_right),
Some((2560, 0))
);
}
#[test]
fn a_cached_position_is_not_overridden_by_an_unmeasured_size() {
let outputs = [output(0, 0, (1440, 900)), output(1920, 0, (2880, 1800))];
// Restored from the cache, or sent by the portal: get_res() failed, so the size is the
// portal size, here the mode of the other output, and it moves nothing.
assert_eq!(
reconciled_origin((1920, 0), (1440, 900), false, &outputs),
None
);
// A measured size still moves a position that names no output of that size: xdph sends
// (0, 0) for every stream.
let pair = [output(0, 0, (1920, 1080)), output(1920, 0, (2880, 1800))];
assert_eq!(
reconciled_origin((0, 0), (2880, 1800), true, &pair),
Some((1920, 0))
);
}
#[test]
fn stage_err_keeps_the_detail_safe_for_a_placeholder() {
+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>
+26
View File
@@ -4467,6 +4467,32 @@ fn _input_os_password(p: String, activate: bool, interface: impl Interface) {
interface.send(Data::Message(msg_out));
}
/// Auto Login. A peer that can check for its logon or lock screen gets the password and types it
/// itself, only if it is there right then. Keys typed from here land in whatever has focus if the
/// screen is not locked by the time they arrive.
pub fn auto_login(p: String, pi: &PeerInfo, interface: impl Interface) {
if !is_peer_handling_os_login(pi) {
input_os_password(p, true, interface);
return;
}
std::thread::spawn(move || {
activate_os(&interface, true);
std::thread::sleep(Duration::from_millis(1200));
let mut msg_out = Message::new();
msg_out.set_os_login(OSLogin {
password: p,
..Default::default()
});
interface.send(Data::Message(msg_out));
});
}
/// Windows and macOS peers from the 1.5.1 release handle `os_login`.
fn is_peer_handling_os_login(pi: &PeerInfo) -> bool {
(pi.platform == crate::common::PLATFORM_WINDOWS || pi.platform == crate::common::PLATFORM_MACOS)
&& hbb_common::get_version_number(&pi.version) >= hbb_common::get_version_number("1.5.1")
}
#[derive(Copy, Clone)]
struct LoginErrorMsgBox {
msgtype: &'static str,
+2
View File
@@ -267,6 +267,8 @@ pub enum DataKeyboard {
#[serde(tag = "t", content = "c")]
pub enum DataKeyboardResponse {
GetKeyState(bool),
#[cfg(target_os = "linux")]
GetKeyStateError(String),
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
+33
View File
@@ -23,6 +23,10 @@ pub struct DrmDisplayInfo {
/// alone is ambiguous across cards. Empty = the single auto-detected device.
#[serde(default)]
pub device: String,
/// The primary plane rotates its framebuffer by 90/270 in hardware, so every frame is this
/// mode TRANSPOSED whatever the compositor reports (gamescope's wl_output has no transform).
#[serde(default)]
pub plane_transposed: bool,
}
/// Mirrors `scrap::drm_reader::drmtap_dmabuf_desc` except `dma_buf_fd` (never serializes — it rides
@@ -280,6 +284,7 @@ fn drm_displays_from_reader(
true
})
.map(|d| DrmDisplayInfo {
plane_transposed: plane_transposed(device, d.crtc_id),
name: d.name,
crtc_id: d.crtc_id,
x: d.x,
@@ -294,6 +299,33 @@ fn drm_displays_from_reader(
(displays, undriven)
}
const DRM_MODE_ROTATE_90: u32 = 0x2;
const DRM_MODE_ROTATE_270: u32 = 0x8;
/// Through a reader bound to `crtc_id`: the enumerating reader is bound to whichever crtc
/// auto-select picked.
fn plane_transposed(device: &str, crtc_id: u32) -> bool {
let dev = (!device.is_empty()).then_some(device);
let Some(mut r) = scrap::drm_reader::DrmReader::open(dev, crtc_id) else {
return false;
};
let transposed = match r.query_plane_rotation() {
Some(m) => m & (DRM_MODE_ROTATE_90 | DRM_MODE_ROTATE_270) != 0,
None => {
hbb_common::throttled_log!(
std::time::Duration::from_secs(600),
debug,
"drm: crtc {crtc_id} ({device:?}): plane rotation unreadable; sized as unrotated"
);
false
}
};
if transposed {
log::trace!("drm: crtc {crtc_id} ({device:?}) is rotated 90/270 by its plane");
}
transposed
}
/// Active displays of every DRM device + the connected-but-undriven identities, from ONE look.
fn drm_enumerate_all_displays() -> (Vec<DrmDisplayInfo>, Vec<String>) {
if let Some(devices) = scrap::drm_reader::list_devices() {
@@ -1673,6 +1705,7 @@ mod drm_conn_tests {
active: true,
render_node: "/dev/dri/renderD129".to_owned(),
device: "/dev/dri/card2".to_owned(),
plane_transposed: false,
};
let wire = serde_json::to_vec(&current).unwrap();
let back: DrmDisplayInfo = serde_json::from_slice(&wire).unwrap();
+24 -24
View File
@@ -7,11 +7,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Password", "Wachtwoord"),
("Ready", "Gereed"),
("Established", "Opgezet"),
("connecting_status", "Verbinding maken met het RustDesk-netwerk..."),
("connecting_status", "Verbinding maken met het RustDesk-netwerk…"),
("Enable service", "Service inschakelen"),
("Start service", "Service starten"),
("Service is running", "De service loopt."),
("Service is not running", "De service loopt niet"),
("Service is running", "Service loopt."),
("Service is not running", "Service loopt niet"),
("not_ready_status", "Niet verbonden met de server, controleer de netwerkverbinding"),
("Control Remote Desktop", "Extern Bureaublad beheren"),
("Transfer file", "Bestand overzetten"),
@@ -76,12 +76,12 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Connection Error", "Fout bij verbinding"),
("Error", "Fout"),
("Reset by the peer", "Door de peer gereset"),
("Connecting...", "Verbinding maken..."),
("Connecting...", "Verbinding maken…"),
("Connection in progress. Please wait.", "Verbinding wordt gemaakt. Even geduld."),
("Please try 1 minute later", "Probeer opnieuw over 1 minuut"),
("Login Error", "Loginfout"),
("Successful", "Geslaagd"),
("Connected, waiting for image...", "Verbonden, wachten op beeld..."),
("Connected, waiting for image...", "Verbonden, wachten op beeld…"),
("Name", "Naam"),
("Type", "Type"),
("Modified", "Gewijzigd"),
@@ -94,7 +94,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Remote", "Op afstand"),
("Remote Computer", "Externe computer"),
("Local Computer", "Lokale computer"),
("Confirm Delete", "Verwijderen bevestigen"),
("Confirm Delete", "Verwijdering bevestigen"),
("Delete", "Verwijderen"),
("Properties", "Eigenschappen"),
("Multi Select", "Meervoudige selectie"),
@@ -127,7 +127,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Optimize reaction time", "Responstijd optimaliseren"),
("Custom", "Aangepast"),
("Show remote cursor", "Cursor van extern bureaublad weergeven"),
("Show quality monitor", "Kwaliteitsmonitor tonen"),
("Show quality monitor", "Kwaliteitsmonitor weergeven"),
("Disable clipboard", "Klembord uitschakelen"),
("Lock after session end", "Vergrendelen na einde sessie"),
("Insert Ctrl + Alt + Del", "Ctrl + Alt + Del invoeren"),
@@ -150,7 +150,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Configure", "Configureren"),
("config_acc", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Toegankelijkheid."),
("config_screen", "Om uw apparaat op afstand te kunnen bedienen, moet u RustDesk toestemming geven voor Schermopname."),
("Installing ...", "Installeren ..."),
("Installing ...", "Installeren…"),
("Install", "Installeren"),
("Installation", "Installatie"),
("Installation Path", "Locatie"),
@@ -159,10 +159,10 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("agreement_tip", "Het starten van de installatie betekent het accepteren van de licentieovereenkomst."),
("Accept and Install", "Accepteren en installeren"),
("End-user license agreement", "Eindgebruikerslicentieovereenkomst"),
("Generating ...", "Genereren ..."),
("Generating ...", "Genereren…"),
("Your installation is lower version.", "Uw installatie is een lagere versie."),
("not_close_tcp_tip", "Sluit dit venster niet zolang u de tunnel gebruikt"),
("Listening ...", "Luisteren ..."),
("Listening ...", "Luisteren…"),
("Remote Host", "Externe host"),
("Remote Port", "Externe poort"),
("Action", "Actie"),
@@ -185,7 +185,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Relayed and unencrypted connection", "Doorgeschakelde en niet-versleutelde verbinding"),
("Enter Remote ID", "Extern ID invoeren"),
("Enter your password", "Wachtwoord invoeren"),
("Logging in...", "Aanmelden..."),
("Logging in...", "Aanmelden…"),
("Enable RDP session sharing", "Delen van RDP-sessie inschakelen"),
("Auto Login", "Automatisch aanmelden"),
("Enable direct IP access", "Directe IP-toegang inschakelen"),
@@ -368,11 +368,11 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Deny LAN discovery", "LAN-detectie weigeren"),
("Write a message", "Schrijf een bericht"),
("Prompt", "Melding"),
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging..."),
("Please wait for confirmation of UAC...", "Wacht op UAC-bevestiging…"),
("elevated_foreground_window_tip", "Het momenteel geopende venster van de op afstand bediende computer vereist hogere rechten. Daarom is het momenteel niet mogelijk de muis en het toetsenbord te gebruiken. Vraag de gebruiker wiens computer u op afstand bedient om het venster te minimaliseren of de rechten te verhogen. Om dit probleem in de toekomst te voorkomen, wordt aanbevolen de software te installeren op de op afstand bediende computer."),
("Disconnected", "Afgesloten"),
("Other", "Andere"),
("Confirm before closing multiple tabs", "Bevestig voordat u meerdere tabbladen sluit"),
("Confirm before closing multiple tabs", "Bevestiging geven bij sluiten van meerdere tabbladen"),
("Keyboard Settings", "Toetsenbordinstellingen"),
("Full Access", "Volledige toegang"),
("Screen Share", "Scherm delen"),
@@ -381,7 +381,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("xdp-portal-unavailable", "Wayland schermopname is mislukt. De XDG Desktop Portal kan gecrashed zijn of is onbeschikbaar. Probeer het opnieuw te starten met `systemctl --user restart xdg-desktop-portal`."),
("JumpLink", "JumpLink"),
("Please Select the screen to be shared(Operate on the peer side).", "Selecteer het scherm dat moet worden gedeeld (Bediening aan de kant van de peer)."),
("Show RustDesk", "Toon RustDesk"),
("Show RustDesk", "RustDesk weergeven"),
("This PC", "Deze PC"),
("or", "of"),
("Elevate", "Verhogen"),
@@ -389,7 +389,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Accept sessions via password", "Sessies accepteren via wachtwoord"),
("Accept sessions via click", "Sessies accepteren via klik"),
("Accept sessions via both", "Accepteer sessies via klik of wachtwoord"),
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert..."),
("Please wait for the remote side to accept your session request...", "Wacht tot de andere kant uw sessieverzoek accepteert…"),
("One-time Password", "Eenmalig wachtwoord"),
("Use one-time password", "Eenmalig wachtwoord gebruiken"),
("One-time password length", "Lengte eenmalig wachtwoord"),
@@ -428,7 +428,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Medium", "Middelmatig"),
("Strong", "Sterk"),
("Switch Sides", "Van kant wisselen"),
("Please confirm if you want to share your desktop?", "Bevestig dat u uw bureaublad wilt delen?"),
("Please confirm if you want to share your desktop?", "Weet u zeker dat u uw bureaublad wilt delen?"),
("Display", "Weergave"),
("Default View Style", "Standaard Weergavestijl"),
("Default Scroll Style", "Standaard Scrollstijl"),
@@ -649,13 +649,13 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("use-the-default-printer-tip", "Standaard printer gebruiken"),
("use-the-selected-printer-tip", "Geselecteerde printer gebruiken"),
("auto-print-tip", "Automatisch afdrukken op de geselecteerde printer."),
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet ik deze lokaal afdrukken?"),
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is verboden"),
("print-incoming-job-confirm-tip", "Er werd een afdruktaak ontvangen van een extern apparaat. Moet deze lokaal worden afgedrukt?"),
("remote-printing-disallowed-tile-tip", "Afdruk op afstand is niet toegestaan"),
("remote-printing-disallowed-text-tip", "Machtigingsinstellingen aan beheerde zijde verhinderen afdrukken op afstand."),
("save-settings-tip", "Instellingen opslaan"),
("dont-show-again-tip", "Dit bericht wordt niet meer weergegeven"),
("Take screenshot", "Schermopname maken"),
("Taking screenshot", "Schermopname maken..."),
("Taking screenshot", "Schermopname maken…"),
("screenshot-merged-screen-not-supported-tip", "Schermopnames van meerdere schermen samenvoegen wordt momenteel niet ondersteund. Schakel over naar een enkel scherm en herhaal de actie."),
("screenshot-action-tip", "Kies wat je met de gemaakte schermopname wilt doen."),
("Save as", "Opslaan als"),
@@ -693,7 +693,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Failed to check if the user is an administrator.", "Fout bij het controleren of de gebruiker een beheerder is."),
("Supported only in the installed version.", "Alleen ondersteund in de geïnstalleerde versie."),
("elevation_username_tip", "Voer je gebruikersnaam of domeinnaam in"),
("Preparing for installation ...", "Installatie voorbereiden ..."),
("Preparing for installation ...", "Installatie voorbereiden…"),
("Show my cursor", "Mijn cursor weergeven"),
("Scale custom", "Aangepaste schaal"),
("Custom scale slider", "Aangepaste schuifregelaar voor schaal"),
@@ -713,8 +713,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("disable-udp-tip", "Controleert of alleen TCP moet worden gebruikt. Als deze optie is ingeschakeld, gebruikt RustDesk niet langer UDP 21116, maar TCP 21116."),
("server-oss-not-support-tip", "Opmerking: Deze functie is niet beschikbaar in de open-sourceversie van de RustDesk-server."),
("input note here", "voeg hier een opmerking toe"),
("note-at-conn-end-tip", "Vraag om een opmerking aan het einde van de verbinding"),
("Show terminal extra keys", "Toon extra toetsen voor terminal"),
("note-at-conn-end-tip", "Om een opmerking vragen aan het einde van de verbinding"),
("Show terminal extra keys", "Extra toetsen voor terminal weergeven"),
("Relative mouse mode", "Relatieve muismodus"),
("rel-mouse-not-supported-peer-tip", "De relatieve muismodus wordt niet ondersteund door het externe apparaat."),
("rel-mouse-not-ready-tip", "De relatieve muismodus was nog niet klaar, probeer het later opnieuw."),
@@ -763,8 +763,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("Lock canvas", "Canvas vergrendelen"),
("Sync clipboard between sessions", "Klembord synchroniseren tussen sessies"),
("sync-clipboard-between-sessions-tip", "Tekst of afbeeldingen die in één externe sessie worden gekopieerd, worden ook naar het klembord van uw andere verbonden sessies gestuurd."),
("terminal-clipboard-write-tip", ""),
("Allow terminal apps to copy to clipboard", ""),
("terminal-clipboard-write-tip", "Een app in de terminal wil tekst naar het klembord van dit apparaat kopiëren. Indien verleend, is deze toestemming van toepassing op terminal-apps in alle verbindingen totdat u deze uitschakelt in Instellingen. Handmatig kopiëren en plakken wordt niet beïnvloed."),
("Allow terminal apps to copy to clipboard", "Terminal-apps toestaan om naar klembord te kopiëren"),
("Enable", "Inschakelen"),
("Reuse one connection for port forwarding", "Eén verbinding hergebruiken voor poortdoorschakeling"),
("port-forward-mux-tip", "Alle verbindingen van een poortdoorschakeling via één enkele verbinding met de andere computer laten lopen, in plaats van voor elke verbinding opnieuw verbinding te maken en in te loggen."),
+4
View File
@@ -767,6 +767,10 @@ pub fn is_locked() -> bool {
}
}
pub fn is_logon_screen() -> bool {
is_prelogin() || is_locked()
}
pub fn is_root() -> bool {
crate::username() == "root"
}
+7 -5
View File
@@ -604,14 +604,16 @@ extern "C"
return rdp_or_console;
}
BOOL is_session_locked(DWORD session_id)
// WTSInfoExLevel1.SessionFlags, or WTS_SESSIONSTATE_UNKNOWN when it cannot be read.
DWORD get_session_flags(DWORD session_id)
{
DWORD flags = WTS_SESSIONSTATE_UNKNOWN;
// WTS_CURRENT_SESSION, which would query the caller's session instead.
if (session_id == 0xFFFFFFFF) {
return FALSE;
return flags;
}
PWTSINFOEXW pInfo = NULL;
DWORD bytes = 0;
BOOL locked = FALSE;
if (WTSQuerySessionInformationW(
WTS_CURRENT_SERVER_HANDLE,
session_id,
@@ -619,13 +621,13 @@ extern "C"
(LPWSTR *)&pInfo,
&bytes)) {
if (pInfo && pInfo->Level == 1) {
locked = (pInfo->Data.WTSInfoExLevel1.SessionFlags == WTS_SESSIONSTATE_LOCK);
flags = (DWORD)pInfo->Data.WTSInfoExLevel1.SessionFlags;
}
if (pInfo) {
WTSFreeMemory(pInfo);
}
}
return locked;
return flags;
}
uint32_t get_active_user(PWSTR bufin, uint32_t nin, BOOL rdp)
+77 -6
View File
@@ -565,7 +565,6 @@ const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
extern "C" {
fn get_current_session(rdp: BOOL) -> DWORD;
fn is_session_locked(session_id: DWORD) -> BOOL;
fn LaunchProcessWin(
cmd: *const u16,
session_id: DWORD,
@@ -1269,7 +1268,7 @@ pub fn is_locked() -> bool {
let Some(session_id) = get_current_process_session_id() else {
return false;
};
unsafe { is_session_locked(session_id) == TRUE }
is_session_locked_flag(session_id) == Some(true)
}
#[inline]
@@ -1283,6 +1282,47 @@ pub fn is_logon_ui() -> ResultType<bool> {
.any(|pid| get_session_id_of_process(pid) == Some(current_sid)))
}
// Auto-login types the OS password on this, so a state that cannot be read counts as unlocked.
// `is_prelogin()` reads a failed query as no user signed in, and `is_logon_ui()` is left out
// because a LogonUI.exe can outlive the unlock.
pub fn is_logon_screen() -> bool {
let Some(session_id) = get_current_process_session_id() else {
return false;
};
is_session_prelogin(session_id) == Some(true)
|| is_session_locked_flag(session_id) == Some(true)
}
fn is_session_prelogin(session_id: u32) -> Option<bool> {
extern "C" {
fn get_session_user_info(path: *mut u16, n: u32, session_id: u32) -> u32;
}
let mut buff = [0u16; 256];
// The bytes copied include the terminating null, so 0 means the query failed.
let n = unsafe { get_session_user_info(buff.as_mut_ptr(), buff.len() as _, session_id) };
if n == 0 {
return None;
}
let username = String::from_utf16_lossy(&buff);
let username = username.trim_end_matches('\0');
Some(username.is_empty() || username == "SYSTEM")
}
// Windows 7 and Server 2008 R2 report LOCK and UNLOCK the other way round (see WTSINFOEX_LEVEL1).
fn is_session_locked_flag(session_id: u32) -> Option<bool> {
extern "C" {
fn get_session_flags(session_id: DWORD) -> DWORD;
}
const WTS_SESSIONSTATE_LOCK: DWORD = 0;
const WTS_SESSIONSTATE_UNLOCK: DWORD = 1;
let reversed = !base::platform::windows::is_windows_version_or_greater(6, 2, 0, 0, 0);
match unsafe { get_session_flags(session_id) } {
WTS_SESSIONSTATE_LOCK => Some(!reversed),
WTS_SESSIONSTATE_UNLOCK => Some(reversed),
_ => None,
}
}
pub fn is_root() -> bool {
// https://stackoverflow.com/questions/4023586/correct-way-to-find-out-if-a-service-is-running-as-the-system-user
unsafe { is_local_system() == TRUE }
@@ -1354,6 +1394,10 @@ pub fn get_install_options() -> String {
}
pub fn get_silent_install_options(printer_override: Option<bool>) -> &'static str {
if !is_win_10_or_greater() {
return "desktopicon startmenu";
}
let install_printer = match printer_override {
Some(override_value) => override_value,
None => {
@@ -1361,9 +1405,13 @@ pub fn get_silent_install_options(printer_override: Option<bool>) -> &'static st
let subkey = format!(".{}", app_name.to_lowercase());
let printer = get_reg_of_hkcr(&subkey, REG_NAME_INSTALL_PRINTER);
printer.as_deref() == Some("1")
&& remote_printer::is_rd_printer_installed(&app_name).unwrap_or_else(|err| {
log::warn!("Failed to check printer installation status: {err}; skipping printer installation");
false
})
}
};
if install_printer && is_win_10_or_greater() {
if install_printer {
"desktopicon startmenu printer"
} else {
"desktopicon startmenu"
@@ -3911,8 +3959,22 @@ pub fn update_to(file: &str) -> ResultType<()> {
// We need also to handle the command line parsing to find the tray processes.
pub fn update_me_msi(msi: &str, quiet: bool) -> ResultType<()> {
let quiet_args = if quiet { " /qn LAUNCH_TRAY_APP=N" } else { "" };
let cmds =
format!("chcp 65001 && msiexec /i \"{msi}\"{quiet_args} REBOOT=ReallySuppress /norestart");
let app_name = crate::get_app_name();
let subkey = format!(".{}", app_name.to_lowercase());
let printer_installed = get_reg_of_hkcr(&subkey, REG_NAME_INSTALL_PRINTER).as_deref()
!= Some("0")
&& remote_printer::is_rd_printer_installed(&app_name).unwrap_or_else(|err| {
log::warn!(
"Failed to check printer installation status: {err}; skipping printer installation"
);
false
});
let printer_args = if printer_installed {
""
} else {
" INSTALLPRINTER=0"
};
let cmds = format!("chcp 65001 && msiexec /i \"{msi}\"{quiet_args}{printer_args} REBOOT=ReallySuppress /norestart");
run_cmds(cmds, false, "update-msi")?;
Ok(())
}
@@ -4846,7 +4908,16 @@ mod tests {
#[test]
fn install_app_names_enforce_ascii_command_safety() {
assert!(validate_install_app_name("RustDesk-Admin1").is_ok());
for app_name in ["", "RustDesk_Admin", "RustDesk&whoami", "RustDesk应用"] {
for app_name in [
"",
"RustDesk_Admin",
"RustDesk&whoami",
"RustDesk应用",
"RustDesk앱",
"RustDeskBüro",
"RustDeskFrançais",
"RustDeskアプリ",
] {
assert!(
validate_install_app_name(app_name).is_err(),
"unsafe application name was accepted: {app_name}"
+28
View File
@@ -75,6 +75,11 @@ pub trait PrivacyMode: Sync + Send {
Ok(false)
}
/// `INVALID_PRIVACY_MODE_CONN_ID` deliberately bypasses the ownership check, meaning
/// "turn it off whoever owns it": shutdown (`ipc::Data::Close`), `reset_all`, and
/// `TurnOnGuard`, which undoes a half-finished turn-on however far it got. A caller
/// acting for one connection must pass that connection's own id, or it can turn off
/// privacy mode belonging to another.
#[inline]
fn check_off_conn_id(&self, conn_id: i32) -> ResultType<()> {
let pre_conn_id = self.pre_conn_id();
@@ -289,6 +294,29 @@ fn turn_on_privacy_sync(impl_key: &str, conn_id: i32) -> Option<ResultType<bool>
Some(privacy_mode_lock.as_mut()?.turn_on_privacy(conn_id))
}
#[cfg(not(target_os = "ios"))]
pub(crate) fn close_other_remote_connections_for_privacy(owner_id: i32) {
use crate::server::{AuthConnType, AUTHED_CONNS};
let privacy_mode_lock = PRIVACY_MODE.lock().unwrap();
// Ownership can change while the caller validates the capturer.
if privacy_mode_lock.as_ref().map(|mode| mode.pre_conn_id()) != Some(owner_id) {
return;
}
for connection in AUTHED_CONNS.lock().unwrap().iter() {
if connection.conn_type != AuthConnType::Remote || connection.conn_id == owner_id {
continue;
}
if let Err(err) = connection.sender.send(crate::ipc::Data::Close) {
hbb_common::log::debug!(
"Failed to close connection {} for privacy mode: {}",
connection.conn_id,
err
);
}
}
}
#[inline]
pub fn turn_off_privacy(conn_id: i32, state: Option<PrivacyModeState>) -> Option<ResultType<()>> {
Some(
+56 -4
View File
@@ -1145,6 +1145,14 @@ impl Connection {
},
Some(data) = rx_from_authed.recv() => {
match data {
ipc::Data::Close => {
conn.send(crate::common::make_privacy_mode_msg(
back_notification::PrivacyModeState::PrvOnByOther,
String::new(),
)).await;
conn.on_close("privacy mode", false).await;
break;
}
#[cfg(all(target_os = "windows", feature = "flutter"))]
ipc::Data::PrinterData(data) => {
if Self::permission(keys::OPTION_ENABLE_REMOTE_PRINTER, &conn.control_permissions) {
@@ -2455,6 +2463,41 @@ impl Connection {
self.tx_input.send(MessageInput::Key((msg, press))).ok();
}
// Auto Login: the password and Return the client would otherwise type itself, typed only if a
// check right before finds the logon or lock screen.
#[cfg(any(target_os = "windows", target_os = "macos"))]
async fn type_auto_login_password(&self, password: String) {
// A peer can send this at any rate, hence the throttled logs.
let at_logon_screen = tokio::task::spawn_blocking(crate::platform::is_logon_screen)
.await
.unwrap_or_else(|e| {
hbb_common::throttled_log!(
Duration::from_secs(60),
error,
"Failed to check the logon screen: {}",
e
);
false
});
if !at_logon_screen {
hbb_common::throttled_log!(
Duration::from_secs(60),
info,
"Auto login dropped, not at the logon or lock screen"
);
return;
}
let mut key_event = KeyEvent::new();
key_event.mode = KeyboardMode::Legacy.into();
key_event.press = true;
key_event.set_seq(password);
self.input_key(key_event.clone(), false);
key_event.set_control_key(ControlKey::Return);
CLICK_TIME.store(get_time(), Ordering::SeqCst);
MOUSE_MOVE_TIME.store(get_time(), Ordering::SeqCst);
self.input_key(key_event, true);
}
fn verify_h1(&self, h1: &[u8]) -> bool {
let mut hasher2 = Sha256::new();
hasher2.update(h1);
@@ -3347,6 +3390,13 @@ impl Connection {
}
self.update_auto_disconnect_timer();
}
#[cfg(any(target_os = "windows", target_os = "macos"))]
Some(message::Union::OsLogin(login)) => {
if self.peer_keyboard_enabled() {
self.type_auto_login_password(login.password).await;
}
self.update_auto_disconnect_timer();
}
Some(message::Union::Clipboard(cb)) => {
if self.should_handle_text_clipboard_message() && self.clipboard_enabled() {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
@@ -5142,6 +5192,7 @@ impl Connection {
5_000,
);
if err_msg.is_empty() {
privacy_mode::close_other_remote_connections_for_privacy(self.inner.id);
crate::common::make_privacy_mode_msg(
back_notification::PrivacyModeState::PrvOnSucceeded,
impl_key,
@@ -5168,10 +5219,10 @@ impl Connection {
Some(Err(e)) => {
log::error!("Failed to turn on privacy mode. {}", e);
if privacy_mode::is_in_privacy_mode() {
let _ = Self::turn_off_privacy_to_msg(
privacy_mode::INVALID_PRIVACY_MODE_CONN_ID,
String::new(),
);
// Use this connection's ID so a failed request cannot disable another
// connection's privacy mode: INVALID_PRIVACY_MODE_CONN_ID would bypass
// the ownership check (see `check_off_conn_id`).
let _ = Self::turn_off_privacy_to_msg(self.inner.id, String::new());
}
crate::common::make_privacy_mode_msg_with_details(
back_notification::PrivacyModeState::PrvOnFailed,
@@ -6105,6 +6156,7 @@ impl Connection {
Some(message::Union::TerminalAction(_)) => "terminal_action",
Some(message::Union::TerminalResponse(_)) => "terminal_response",
Some(message::Union::PortForwardChannel(_)) => "port_forward_channel",
Some(message::Union::OsLogin(_)) => "os_login",
Some(message::Union::Misc(misc)) => Self::misc_message_family(misc),
Some(_) => "message.other",
None => "empty",
+79 -8
View File
@@ -110,6 +110,17 @@ fn connector_key(d: &DrmDisplayInfo) -> String {
format!("{}:{}", d.device, d.name)
}
/// The transform whose dimensions the delivered frames have: a plane rotated 90/270 in hardware
/// already hands over the transposed scanout (and `frame_transform` then turns nothing), whatever
/// the output transform says; otherwise the output transform is undone in software.
fn delivered_transform(d: &DrmDisplayInfo, wl_transform: i32) -> i32 {
if d.plane_transposed {
90
} else {
wl_transform
}
}
/// Frame dimensions after undoing `transform` degrees of output rotation.
fn rotated_dims(transform: i32, w: usize, h: usize) -> (usize, usize) {
if transform == 90 || transform == 270 {
@@ -416,9 +427,13 @@ impl IpcDrmCapturer {
stop,
display,
connector: displays.get(wire_idx).map(connector_key),
session_size: displays
.get(wire_idx)
.map(|d| rotated_dims(wl_transform, d.width as usize, d.height as usize)),
session_size: displays.get(wire_idx).map(|d| {
rotated_dims(
delivered_transform(d, wl_transform),
d.width as usize,
d.height as usize,
)
}),
transform: wl_transform,
snapshot_gen,
cur: Vec::new(),
@@ -2122,7 +2137,8 @@ fn augment_with_wayland_geometry_from(
// Identity matches ONLY, the same rule the capturer's transform follows: swapping on a
// layout-order guess advertises dimensions the capturer will not deliver.
let is_identity = identity[i].is_some() && identity[i] == matched[i];
if is_identity && (w.transform == 90 || w.transform == 270) {
// A plane-transposed display was already swapped by `display_info_from_drm`.
if is_identity && !drm[i].plane_transposed && (w.transform == 90 || w.transform == 270) {
std::mem::swap(&mut info.width, &mut info.height);
info.original_resolution = super::display_service::get_original_resolution(
&drm[i].name,
@@ -2259,13 +2275,18 @@ fn swap_available_displays(list: Vec<DrmDisplayInfo>) {
}
fn display_info_from_drm(d: &DrmDisplayInfo) -> DisplayInfo {
let (width, height) = rotated_dims(
delivered_transform(d, 0),
d.width as usize,
d.height as usize,
);
let original_resolution =
super::display_service::get_original_resolution(&d.name, d.width as usize, d.height as usize);
super::display_service::get_original_resolution(&d.name, width, height);
DisplayInfo {
x: d.x,
y: d.y,
width: d.width as i32,
height: d.height as i32,
width: width as i32,
height: height as i32,
name: d.name.clone(),
online: d.active,
cursor_embedded: false,
@@ -2330,7 +2351,11 @@ pub(super) fn get_capturer_info(
// Origin and transform come from the ONE snapshot new() resolved, so both reflect the
// same output assignment; dimensions stay PHYSICAL, rotated to frame orientation.
let origin = origin.unwrap_or((d.x, d.y));
let (cap_w, cap_h) = rotated_dims(capturer.transform, d.width as usize, d.height as usize);
let (cap_w, cap_h) = rotated_dims(
delivered_transform(&d, capturer.transform),
d.width as usize,
d.height as usize,
);
Ok(super::video_service::CapturerInfo {
origin,
width: cap_w,
@@ -3792,6 +3817,7 @@ mod drm_capturer_tests {
active: true,
render_node: String::new(),
device: String::new(),
plane_transposed: false,
}
}
@@ -3814,6 +3840,51 @@ mod drm_capturer_tests {
}
}
fn plane_transposed_display(name: &str, w: u32, h: u32) -> DrmDisplayInfo {
DrmDisplayInfo {
plane_transposed: true,
..drm_display(name, w, h)
}
}
#[test]
fn a_plane_transposed_display_advertises_its_scanout() {
// Steam Deck under gamescope: 800x1280 panel mode, 1280x800 framebuffer on a rotate-270
// plane, and no wayland output that matches the connector.
let drm = [plane_transposed_display("eDP-1", 800, 1280)];
let wl = scrap::wayland::display::Displays {
primary: 0,
displays: vec![],
};
let assignment = assign_wayland_outputs(&drm, &wl.displays);
let infos = augment_with_wayland_geometry_from(&drm, &wl, &assignment);
assert_eq!((infos[0].width, infos[0].height), (1280, 800));
}
#[test]
fn a_plane_transposed_scanout_is_delivered_at_the_advertised_size() {
let d = plane_transposed_display("eDP-1", 800, 1280);
let session = rotated_dims(delivered_transform(&d, 0), d.width as usize, d.height as usize);
let mut c = capturer_named(Some(session), Some("test:plane-transposed-session"));
put_frame_rot(&c, 1280, 800, Some(0x8));
assert!(matches!(c.frame(Duration::from_millis(50)), Ok(_)));
}
#[test]
fn a_rotated_output_over_a_rotated_plane_is_swapped_once() {
// mutter rotates the output and programs the plane from it: one quarter turn, as before.
let drm = [plane_transposed_display("HDMI-A-1", 1920, 1080)];
let mut out = wl_display("HDMI-1", 0, 0, 1920, 1080);
out.transform = 90;
let wl = scrap::wayland::display::Displays {
primary: 0,
displays: vec![out],
};
let assignment = assign_wayland_outputs(&drm, &wl.displays);
let infos = augment_with_wayland_geometry_from(&drm, &wl, &assignment);
assert_eq!((infos[0].width, infos[0].height), (1080, 1920));
}
#[test]
fn a_lone_rotated_output_advertises_delivered_dimensions() {
// Fix for the origin-only cut: one connector, one rotated output. The capturer will
+11
View File
@@ -710,6 +710,8 @@ struct VirtualInputState {
#[cfg(target_os = "macos")]
impl VirtualInputState {
const KEY_UP_ERROR_LOG_INTERVAL: Duration = Duration::from_secs(5);
fn new() -> Option<Self> {
VirtualInput::new(
CGEventSourceStateID::CombinedSessionState,
@@ -1657,6 +1659,12 @@ fn simulate_(event_type: &EventType) {
let _lock = VIRTUAL_INPUT_MTX.lock();
if let Some(input) = VIRTUAL_INPUT_STATE.as_ref() {
let _ = input.simulate(&event_type);
} else if matches!(event_type, EventType::KeyRelease(_)) {
hbb_common::throttled_log!(
VirtualInputState::KEY_UP_ERROR_LOG_INTERVAL,
error,
"Failed to inject macOS key-up: virtual input is not initialized"
);
}
}
}
@@ -2481,6 +2489,9 @@ pub fn handle_key_(evt: &KeyEvent) {
return;
}
#[cfg(target_os = "linux")]
super::uinput::prepare_layout(evt);
#[cfg(not(any(target_os = "android", target_os = "ios")))]
let mut _lock_mode_handler = None;
#[cfg(not(any(target_os = "android", target_os = "ios")))]
+213 -10
View File
@@ -10,6 +10,12 @@ use hbb_common::{
ResultType,
};
mod layout;
pub(super) fn prepare_layout(event: &base::message_proto::KeyEvent) {
layout::prepare_layout(event);
}
static IPC_CONN_TIMEOUT: u64 = 1000;
static IPC_REQUEST_TIMEOUT: u64 = 1000;
static IPC_POSTFIX_KEYBOARD: &str = "_uinput_keyboard";
@@ -17,24 +23,182 @@ static IPC_POSTFIX_MOUSE: &str = "_uinput_mouse";
static IPC_POSTFIX_CONTROL: &str = "_uinput_control";
pub mod client {
use super::*;
use super::{layout::LayoutKey, *};
use std::{collections::HashMap, time::Duration};
const LAYOUT_ERROR_LOG_INTERVAL: Duration = Duration::from_secs(5);
struct LayoutContext {
locks: (bool, bool),
// None for ordinary input; otherwise whether the shortcut holds Shift.
shortcut_shift: Option<bool>,
}
impl LayoutContext {
fn resolve(&self, chr: char) -> ResultType<LayoutKey> {
layout::resolve(chr, self.locks, self.shortcut_shift)
}
}
pub struct UInputKeyboard {
conn: Connection,
rt: Runtime,
// Ownership is per character. The Linux connection turns character
// downs into clicks; overlapping direct-backend holds can release a
// generated modifier still needed by another character.
layout_keys: HashMap<char, LayoutKey>,
}
impl UInputKeyboard {
pub async fn new() -> ResultType<Self> {
let conn = ipc::connect(IPC_CONN_TIMEOUT, IPC_POSTFIX_KEYBOARD).await?;
let rt = Runtime::new()?;
Ok(Self { conn, rt })
layout::prewarm_layout();
Ok(Self {
conn,
rt,
layout_keys: HashMap::new(),
})
}
fn send(&mut self, data: Data) -> ResultType<()> {
self.rt.block_on(self.conn.send(&data))
}
fn send_raw_key(&mut self, keycode: u16, down: bool) -> ResultType<()> {
let key = Key::Raw(keycode);
let event = if down {
DataKeyboard::KeyDown(key)
} else {
DataKeyboard::KeyUp(key)
};
self.send(Data::Keyboard(event))
}
fn press_layout_key(&mut self, chr: char, mapping: LayoutKey) -> ResultType<()> {
if let Some(pressed) = self.layout_keys.get(&chr).cloned() {
return self.send_layout_key_down(&pressed);
}
let mut pressed = LayoutKey {
key: mapping.key,
modifiers: Vec::new(),
};
for keycode in mapping.modifiers {
let query = Data::Keyboard(DataKeyboard::GetKeyState(Key::Raw(keycode)));
if !self.send_get_key_state(query)? {
pressed.modifiers.push(keycode);
}
}
let result = self.send_layout_key_down(&pressed);
if let Err(error) = result {
if let Err(release_error) = self.release_layout_key(&pressed) {
bail!(
"{}; failed to release uinput modifiers: {}",
error,
release_error
);
}
return Err(error);
}
self.layout_keys.insert(chr, pressed);
Ok(())
}
fn send_layout_key_down(&mut self, pressed: &LayoutKey) -> ResultType<()> {
// Character dispatch can release Shift before a repeated key-down.
for keycode in &pressed.modifiers {
self.send_raw_key(*keycode, true)?;
}
self.send(Data::Keyboard(DataKeyboard::KeyDown(pressed.key)))
}
fn release_layout_key(&mut self, pressed: &LayoutKey) -> ResultType<()> {
let mut result = self.send(Data::Keyboard(DataKeyboard::KeyUp(pressed.key)));
for keycode in pressed.modifiers.iter().rev() {
// Attempt every release even if an earlier send failed.
result = result.and(self.send_raw_key(*keycode, false));
}
result
}
fn layout_key_down(&mut self, chr: char) -> ResultType<()> {
if let Some(pressed) = self.layout_keys.get(&chr).cloned() {
return self.send_layout_key_down(&pressed);
}
let mapping = if layout::is_available() {
self.layout_context()?.resolve(chr)?
} else {
// Discovery may finish before key-up; retain the legacy key for release.
LayoutKey {
key: Key::Layout(chr),
modifiers: Vec::new(),
}
};
self.press_layout_key(chr, mapping)
}
fn layout_key_up(&mut self, chr: char) -> ResultType<()> {
if let Some(pressed) = self.layout_keys.remove(&chr) {
self.release_layout_key(&pressed)?;
}
Ok(())
}
fn layout_key_sequence(&mut self, sequence: &str) -> ResultType<()> {
if sequence.is_empty() {
return Ok(());
}
let context = self.layout_context()?;
// Keep supported text after a mapping failure and report the first error.
// Modifier and IPC failures must still stop the sequence immediately.
let mut result = Ok(());
for chr in sequence.chars() {
let mapping = match context.resolve(chr) {
Ok(mapping) => mapping,
Err(error) => {
result = result.and(Err(error));
continue;
}
};
self.press_layout_key(chr, mapping)?;
self.layout_key_up(chr)?;
}
result
}
fn layout_context(&mut self) -> ResultType<LayoutContext> {
let caps_lock =
self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::CapsLock)))?;
let num_lock =
self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::NumLock)))?;
let shortcut = self
.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Control)))?
|| self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Alt)))?
|| self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Meta)))?;
let shortcut_shift = if shortcut {
Some(
self.send_get_key_state(Data::Keyboard(DataKeyboard::GetKeyState(Key::Shift)))?,
)
} else {
None
};
Ok(LayoutContext {
locks: (caps_lock, num_lock),
shortcut_shift,
})
}
fn log_layout_error(result: &ResultType<()>) {
if let Err(error) = result {
hbb_common::throttled_log!(
LAYOUT_ERROR_LOG_INTERVAL,
error,
"Uinput layout-aware keyboard input failed: {}",
error
);
}
}
fn send_get_key_state(&mut self, data: Data) -> ResultType<bool> {
self.rt.block_on(self.conn.send(&data))?;
@@ -45,6 +209,9 @@ pub mod client {
Ok(Some(Data::KeyboardResponse(ipc::DataKeyboardResponse::GetKeyState(state)))) => {
Ok(state)
}
Ok(Some(Data::KeyboardResponse(ipc::DataKeyboardResponse::GetKeyStateError(
error,
)))) => bail!("Failed to query uinput key state: {}", error),
Ok(Some(resp)) => {
// FATAL error!!!
bail!(
@@ -90,25 +257,39 @@ pub mod client {
}
fn key_sequence(&mut self, sequence: &str) {
// Sequence events are normally handled in the --server process before reaching here.
// Forward via IPC as a fallback — input_text_wayland can still handle ASCII chars
// via keysym/uinput, though non-ASCII will be skipped (no clipboard in --service).
log::debug!(
"UInputKeyboard::key_sequence called (len={})",
sequence.len()
);
allow_err!(self.send(Data::Keyboard(DataKeyboard::Sequence(sequence.to_string()))));
if !layout::is_available() {
Self::log_layout_error(
&self.send(Data::Keyboard(DataKeyboard::Sequence(sequence.to_string()))),
);
return;
}
Self::log_layout_error(&self.layout_key_sequence(sequence));
}
// TODO: handle error???
fn key_down(&mut self, key: Key) -> enigo::ResultType {
if let Key::Layout(chr) = key {
let result = self.layout_key_down(chr);
Self::log_layout_error(&result);
return result.map_err(Into::into);
}
allow_err!(self.send(Data::Keyboard(DataKeyboard::KeyDown(key))));
Ok(())
}
fn key_up(&mut self, key: Key) {
if let Key::Layout(chr) = key {
Self::log_layout_error(&self.layout_key_up(chr));
return;
}
allow_err!(self.send(Data::Keyboard(DataKeyboard::KeyUp(key))));
}
fn key_click(&mut self, key: Key) {
if let Key::Layout(chr) = key {
if layout::is_available() {
Self::log_layout_error(&self.layout_key_sequence(&chr.to_string()));
return;
}
}
allow_err!(self.send(Data::Keyboard(DataKeyboard::KeyClick(key))));
}
}
@@ -203,6 +384,8 @@ pub mod service {
use std::os::unix::io::AsRawFd;
use std::{collections::HashMap, sync::Mutex};
const RAW_KEY_STATE_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
lazy_static::lazy_static! {
static ref KEY_MAP: HashMap<enigo::Key, evdev::Key> = HashMap::from(
[
@@ -686,6 +869,9 @@ pub mod service {
} else {
match keyboard.get_key_state() {
Ok(keys) => match key {
enigo::Key::Raw(code) if *code >= layout::XKB_KEYCODE_OFFSET => {
keys.contains(evdev::Key::new(*code - layout::XKB_KEYCODE_OFFSET))
}
enigo::Key::Shift => {
keys.contains(evdev::Key::KEY_LEFTSHIFT)
|| keys.contains(evdev::Key::KEY_RIGHTSHIFT)
@@ -704,6 +890,23 @@ pub mod service {
}
_ => false,
},
Err(error) if matches!(key, enigo::Key::Raw(_)) => {
hbb_common::throttled_log!(
RAW_KEY_STATE_ERROR_LOG_INTERVAL,
error,
"Failed to query uinput layout modifier state: {}",
error
);
// Unknown modifier state must not be treated as released.
ipc_send_data(
stream,
&Data::KeyboardResponse(
ipc::DataKeyboardResponse::GetKeyStateError(error.to_string()),
),
)
.await;
return;
}
Err(_e) => {
// log::debug!("Failed to get key state: {}", &_e);
false
+298
View File
@@ -0,0 +1,298 @@
use hbb_common::{anyhow::anyhow, bail, ResultType};
use std::{collections::HashMap, ops::RangeInclusive, ptr::NonNull};
use xkbcommon_dl::{self as xkb, keysyms};
mod cache;
mod source;
mod wayland;
mod xwayland;
pub(super) use cache::{is_available, prepare_layout, prewarm_layout, resolve};
pub(super) const XKB_KEYCODE_OFFSET: u16 = 8;
const CAPS_LOCK_BIT: usize = 1;
const NUM_LOCK_BIT: usize = 2;
const SHIFT_BIT: usize = 4;
const LAYOUT_STATE_COUNT: usize = 8;
const DEFAULT_GROUP: u32 = 0;
#[derive(Clone)]
pub(super) struct LayoutKey {
pub key: enigo::Key,
pub modifiers: Vec<u16>,
}
struct Keymap {
maps: [HashMap<char, LayoutKey>; LAYOUT_STATE_COUNT],
}
impl Keymap {
fn load(source: &source::Source) -> ResultType<Self> {
let keymap = XkbKeymap::open(source)?;
let mut state = State::new(&keymap)?;
let caps = state.locked_mask(keysyms::Caps_Lock);
let num = state.locked_mask(keysyms::Num_Lock);
let shift = state.modifier(&[keysyms::Shift_L, keysyms::Shift_R]);
let level3 = state.modifier(&[keysyms::ISO_Level3_Shift]);
let modifiers = [shift, level3];
let maps = std::array::from_fn(|index| {
let locked = if index & CAPS_LOCK_BIT != 0 { caps } else { 0 }
| if index & NUM_LOCK_BIT != 0 { num } else { 0 };
let held_shift = if index & SHIFT_BIT != 0 { shift } else { None };
let modifiers = if held_shift.is_some() {
std::slice::from_ref(&level3)
} else {
&modifiers
};
state.mappings(locked, modifiers, held_shift)
});
Ok(Self { maps })
}
}
struct XkbKeymap {
api: &'static xkb::XkbCommon,
map: NonNull<xkb::xkb_keymap>,
group: u32,
}
impl XkbKeymap {
fn open(source: &source::Source) -> ResultType<Self> {
let api = xkb::xkbcommon_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon"))?;
let mut keymap = Self {
api,
map: compile(api, source)?,
group: DEFAULT_GROUP,
};
let groups = unsafe { (api.xkb_keymap_num_layouts)(keymap.map.as_ptr()) };
if let source::Source::Wayland { group, .. } | source::Source::Xwayland { group, .. } =
source
{
if groups > 1 {
keymap.group =
group.ok_or_else(|| anyhow!("Cannot determine the active XKB group"))?;
}
}
if keymap.group >= groups {
bail!("The detected keyboard layout group is absent from the keymap");
}
Ok(keymap)
}
fn keycodes(&self) -> RangeInclusive<u32> {
unsafe {
(self.api.xkb_keymap_min_keycode)(self.map.as_ptr())
..=(self.api.xkb_keymap_max_keycode)(self.map.as_ptr())
}
}
}
impl Drop for XkbKeymap {
fn drop(&mut self) {
unsafe { (self.api.xkb_keymap_unref)(self.map.as_ptr()) };
}
}
fn compile(api: &xkb::XkbCommon, source: &source::Source) -> ResultType<NonNull<xkb::xkb_keymap>> {
let context =
unsafe { (api.xkb_context_new)(xkb::xkb_context_flags::XKB_CONTEXT_NO_ENVIRONMENT_NAMES) };
let context = NonNull::new(context).ok_or_else(|| anyhow!("Cannot create XKB context"))?;
let flags = xkb::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS;
let map = unsafe {
match source {
source::Source::Gnome(names) => {
let names = xkb::xkb_rule_names {
rules: std::ptr::null(),
model: names.model.as_ptr(),
layout: names.layout.as_ptr(),
variant: names.variant.as_ptr(),
options: names.options.as_ptr(),
};
(api.xkb_keymap_new_from_names)(context.as_ptr(), &names, flags)
}
source::Source::Wayland { keymap: bytes, .. }
| source::Source::Xwayland { keymap: bytes, .. } => (api.xkb_keymap_new_from_string)(
context.as_ptr(),
bytes.as_ptr().cast(),
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
flags,
),
}
};
unsafe { (api.xkb_context_unref)(context.as_ptr()) };
NonNull::new(map).ok_or_else(|| anyhow!("Cannot compile the detected XKB keyboard map"))
}
#[derive(Clone, Copy)]
struct Modifier {
keycode: u16,
mask: u32,
}
struct State<'a> {
keymap: &'a XkbKeymap,
state: NonNull<xkb::xkb_state>,
}
impl<'a> State<'a> {
fn new(keymap: &'a XkbKeymap) -> ResultType<Self> {
let state = unsafe { (keymap.api.xkb_state_new)(keymap.map.as_ptr()) };
let state = NonNull::new(state).ok_or_else(|| anyhow!("Cannot create XKB state"))?;
let mut state = Self { keymap, state };
state.set_modifiers(0, 0);
Ok(state)
}
fn set_modifiers(&mut self, depressed: u32, locked: u32) {
unsafe {
(self.keymap.api.xkb_state_update_mask)(
self.state.as_ptr(),
depressed,
0,
locked,
0,
0,
self.keymap.group,
);
}
}
fn symbol(&self, keycode: u16) -> u32 {
unsafe {
(self.keymap.api.xkb_state_key_get_one_sym)(self.state.as_ptr(), u32::from(keycode))
}
}
fn update_key(&mut self, keycode: u16, direction: xkb::xkb_key_direction) {
unsafe {
(self.keymap.api.xkb_state_update_key)(
self.state.as_ptr(),
u32::from(keycode),
direction,
)
};
}
fn locked_mask(&mut self, symbol: u32) -> u32 {
let keycode = self
.keymap
.keycodes()
.filter_map(supported_keycode)
.find(|keycode| self.symbol(*keycode) == symbol);
let Some(keycode) = keycode else { return 0 };
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_DOWN);
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_UP);
let mask = unsafe {
(self.keymap.api.xkb_state_serialize_mods)(
self.state.as_ptr(),
xkb::xkb_state_component::XKB_STATE_MODS_LOCKED,
)
};
self.set_modifiers(0, 0);
mask
}
fn modifier(&mut self, symbols: &[u32]) -> Option<Modifier> {
// Prefer physical modifier keys to XKB's synthetic <LVL3> keycode.
let preferred = [
evdev::Key::KEY_LEFTSHIFT,
evdev::Key::KEY_RIGHTSHIFT,
evdev::Key::KEY_RIGHTALT,
];
let preferred = preferred
.iter()
.map(|key| u32::from(key.code() + XKB_KEYCODE_OFFSET));
for keycode in preferred
.chain(self.keymap.keycodes())
.filter_map(supported_keycode)
{
if !symbols.contains(&self.symbol(keycode)) {
continue;
}
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_DOWN);
let mask = unsafe {
(self.keymap.api.xkb_state_serialize_mods)(
self.state.as_ptr(),
xkb::xkb_state_component::XKB_STATE_MODS_DEPRESSED,
)
};
self.update_key(keycode, xkb::xkb_key_direction::XKB_KEY_UP);
self.set_modifiers(0, 0);
if mask != 0 {
return Some(Modifier { keycode, mask });
}
}
None
}
fn mappings(
&mut self,
locked: u32,
modifiers: &[Option<Modifier>],
held_shift: Option<Modifier>,
) -> HashMap<char, LayoutKey> {
let mut mappings = HashMap::new();
let mut keypad_mappings = HashMap::new();
for combination in 0..(1usize << modifiers.len()) {
let selected: Vec<_> = modifiers
.iter()
.enumerate()
.filter(|(index, _)| combination & (1 << *index) != 0)
.filter_map(|(_, modifier)| *modifier)
.collect();
// Held Shift affects the symbol, but belongs to the caller.
let mask = selected.iter().fold(
held_shift.map_or(0, |modifier| modifier.mask),
|mask, modifier| mask | modifier.mask,
);
self.set_modifiers(mask, locked);
for keycode in self.keymap.keycodes().filter_map(supported_keycode) {
let symbol = self.symbol(keycode);
// Keypad aliases can produce the same text but different shortcuts.
let candidates = if (keysyms::KP_Space..=keysyms::KP_Equal).contains(&symbol) {
&mut keypad_mappings
} else {
&mut mappings
};
let codepoint = unsafe { (self.keymap.api.xkb_keysym_to_utf32)(symbol) };
if let Some(character) =
char::from_u32(codepoint).filter(|character| *character != '\0')
{
candidates.entry(character).or_insert_with(|| LayoutKey {
key: enigo::Key::Raw(keycode),
// Press Level3 first to avoid Shift+RightAlt activating Compose.
// Candidate preference still follows the original modifier order.
modifiers: selected
.iter()
.rev()
.map(|modifier| modifier.keycode)
.collect(),
});
}
}
}
// Shift must not redirect an ordinary shortcut to a keypad alias.
if held_shift.is_none() {
for (character, mapping) in keypad_mappings {
mappings.entry(character).or_insert(mapping);
}
}
mappings
}
}
impl Drop for State<'_> {
fn drop(&mut self) {
unsafe { (self.keymap.api.xkb_state_unref)(self.state.as_ptr()) };
}
}
fn supported_keycode(keycode: u32) -> Option<u16> {
let keycode = u16::try_from(keycode).ok()?;
let code = keycode.checked_sub(XKB_KEYCODE_OFFSET)?;
// Match the keys enabled by create_uinput_keyboard().
let supported = (evdev::Key::KEY_ESC.code()..=evdev::Key::BTN_TRIGGER_HAPPY40.code())
.contains(&code)
&& !format!("{:?}", evdev::Key::new(code)).contains("unknown");
supported.then_some(keycode)
}
+259
View File
@@ -0,0 +1,259 @@
use super::{source::Source, Keymap, LayoutKey, CAPS_LOCK_BIT, NUM_LOCK_BIT, SHIFT_BIT};
use crate::server::input_service::is_ascii_printable;
use base::message_proto::{key_event, KeyEvent, KeyboardMode};
use hbb_common::{bail, lazy_static, ResultType};
use std::{
sync::{mpsc, Mutex, RwLock, TryLockError},
thread,
time::{Duration, Instant},
};
const LAYOUT_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
// GNOME 46/Plasma 6.6 probes (200-400 initial samples): preparation p99 7-16 ms;
// repeated refresh medians were 2-6 ms. KDE query outliers exceeded 100 ms,
// so this limits input waiting while the background query continues.
const LAYOUT_INPUT_WAIT: Duration = Duration::from_millis(25);
const LAYOUT_WARNING_INTERVAL: Duration = Duration::from_secs(5);
lazy_static::lazy_static! {
static ref REFRESH: Mutex<Refresh> = Mutex::new(Refresh::default());
// Only the first relevant input takes the startup query's completion receiver.
static ref PREWARM_RECEIVER: Mutex<Option<mpsc::Receiver<()>>> = Mutex::new(None);
static ref CURRENT: RwLock<Result<Keymap, String>> =
RwLock::new(Err("Uinput keyboard layout has not been detected".to_owned()));
}
#[derive(Default)]
struct Refresh {
checked: Option<Instant>,
source: Option<Source>,
// Cover scheduling until the worker acquires REFRESH.
running: bool,
}
pub(in crate::server::uinput) fn prepare_layout(event: &KeyEvent) {
if !crate::server::input_service::wayland_use_uinput() || !needs_layout(event) {
return;
}
let deadline = Instant::now() + LAYOUT_INPUT_WAIT;
let receiver = {
let mut prewarm = PREWARM_RECEIVER.lock().unwrap();
// Prefer a due refresh over an old, already-completed startup query.
start_refresh().or(prewarm.take())
};
if let Some(receiver) = receiver {
wait_for_refresh(receiver, deadline);
}
}
pub(in crate::server::uinput) fn prewarm_layout() {
// Use server startup time for discovery before the first remote character.
// This reduces cold-start fallback; a still-pending query cannot guarantee readiness.
let mut prewarm = PREWARM_RECEIVER.lock().unwrap();
if let Some(receiver) = start_refresh() {
*prewarm = Some(receiver);
}
}
fn start_refresh() -> Option<mpsc::Receiver<()>> {
// A stalled desktop query must not block later input or spawn more workers.
let mut refresh = match REFRESH.try_lock() {
Ok(refresh) => refresh,
Err(TryLockError::WouldBlock) => return None,
Err(TryLockError::Poisoned(error)) => {
hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
error,
"Uinput layout refresh lock is poisoned: {}",
error
);
return None;
}
};
if refresh.running
|| refresh
.checked
.is_some_and(|checked| checked.elapsed() < LAYOUT_REFRESH_INTERVAL)
{
return None;
}
let (completed, receiver) = mpsc::channel();
refresh.running = true;
if let Err(error) = thread::Builder::new()
.name("uinput-layout".to_owned())
.spawn(move || refresh_layout(completed))
{
refresh.running = false;
refresh.checked = Some(Instant::now());
hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
error,
"Cannot start uinput layout refresh: {}",
error
);
return None;
}
drop(refresh);
Some(receiver)
}
fn refresh_layout(completed: mpsc::Sender<()>) {
let mut refresh = REFRESH.lock().unwrap();
if let Err(error) = refresh.update() {
let retained = {
let mut current = CURRENT.write().unwrap();
if current.is_err() {
*current = Err(error.to_string());
}
current.is_ok()
};
hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
warn,
"Uinput layout refresh failed (previous mapping retained: {}): {}",
retained,
error
);
}
refresh.checked = Some(Instant::now());
refresh.running = false;
drop(refresh);
// An input timeout drops its receiver but leaves this worker running.
if completed.send(()).is_err() {
hbb_common::log::trace!("Uinput layout refresh finished without an input waiter");
}
}
fn wait_for_refresh(receiver: mpsc::Receiver<()>, deadline: Instant) {
match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
Ok(()) => {}
Err(mpsc::RecvTimeoutError::Timeout) => hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
warn,
"Uinput layout refresh exceeded the {} ms input wait; query continues in the background",
LAYOUT_INPUT_WAIT.as_millis()
),
Err(mpsc::RecvTimeoutError::Disconnected) => hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
error,
"Uinput layout refresh worker stopped before completion"
),
}
}
impl Refresh {
fn update(&mut self) -> ResultType<()> {
let source = Source::read().map_err(|error| {
if error.is::<super::source::UnreliableSource>() {
// Unlike a transient query failure, this invalidates the old map.
self.source = None;
*CURRENT.write().unwrap() = Err(error.to_string());
}
error
})?;
if self.source.as_ref() == Some(&source) {
return Ok(());
}
let keymap = match Keymap::load(&source) {
Ok(keymap) => keymap,
Err(error) => {
// A newly observed layout cannot use the previous layout's map.
self.source = None;
*CURRENT.write().unwrap() = Err(error.to_string());
return Err(error);
}
};
*CURRENT.write().unwrap() = Ok(keymap);
self.source = Some(source);
Ok(())
}
}
fn needs_layout(event: &KeyEvent) -> bool {
let mode = event.mode.enum_value_or(KeyboardMode::Legacy);
if mode == KeyboardMode::Map {
return false;
}
match &event.union {
Some(key_event::Union::Seq(sequence)) => {
// Translate shortcuts use Key::Layout even for non-ASCII text.
!sequence.is_empty()
&& (mode == KeyboardMode::Translate || sequence.chars().all(is_ascii_printable))
}
Some(key_event::Union::Chr(_)) => mode == KeyboardMode::Legacy && event.down,
Some(key_event::Union::Unicode(character)) => {
mode == KeyboardMode::Legacy
&& char::from_u32(*character).is_some_and(is_ascii_printable)
}
_ => false,
}
}
pub(in crate::server::uinput) fn is_available() -> bool {
let current = CURRENT.read().unwrap();
if let Err(error) = current.as_ref() {
hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
warn,
"Uinput layout unavailable: {}; using legacy character mapping (may differ from the host layout)",
error
);
}
current.is_ok()
}
pub(in crate::server::uinput) fn resolve(
character: char,
locks: (bool, bool),
shortcut_shift: Option<bool>,
) -> ResultType<LayoutKey> {
let current = CURRENT.read().unwrap();
let keymap = match current.as_ref() {
Ok(keymap) => keymap,
Err(error) => {
hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
warn,
"Uinput layout unavailable: {}; using legacy character mapping (may differ from the host layout)",
error
);
return Ok(LayoutKey {
key: enigo::Key::Layout(character),
modifiers: Vec::new(),
});
}
};
let index = usize::from(locks.0) * CAPS_LOCK_BIT + usize::from(locks.1) * NUM_LOCK_BIT;
// Letter shortcuts keep their physical key even when Shift changes case.
// Other shortcuts prefer a symbol compatible with the caller's held Shift.
let shifted = (shortcut_shift == Some(true) && !character.is_alphabetic())
.then(|| keymap.maps[index | SHIFT_BIT].get(&character))
.flatten();
if let Some(mapping) = shifted.or_else(|| keymap.maps[index].get(&character)) {
return Ok(mapping.clone());
}
if shortcut_shift.is_some() && character.is_ascii_graphic() {
return legacy_shortcut(character);
}
bail!("Character cannot be generated in the detected XKB layout")
}
fn legacy_shortcut(character: char) -> ResultType<LayoutKey> {
// Uppercase letters must not synthesize Shift for a shortcut, but shifted
// punctuation still needs the legacy table's modifier.
let (key, shift) =
super::super::service::map_key(&enigo::Key::Layout(character.to_ascii_lowercase()))?;
hbb_common::throttled_log!(
LAYOUT_WARNING_INTERVAL,
warn,
"Uinput layout lacks an ASCII shortcut character; using its legacy physical mapping"
);
Ok(LayoutKey {
key: enigo::Key::Raw(key.code() + super::XKB_KEYCODE_OFFSET),
modifiers: if shift {
vec![evdev::Key::KEY_LEFTSHIFT.code() + super::XKB_KEYCODE_OFFSET]
} else {
Vec::new()
},
})
}
+179
View File
@@ -0,0 +1,179 @@
use dbus::blocking::Connection;
use gtk::{
gio::{self, prelude::SettingsExt},
glib::variant::FromVariant,
};
use hbb_common::{anyhow::anyhow, bail, ResultType};
use std::{error::Error, ffi::CString, fmt, time::Duration};
mod ibus;
pub(super) const DBUS_TIMEOUT: Duration = Duration::from_millis(250);
const GNOME_INPUT_SCHEMA: &str = "org.gnome.desktop.input-sources";
const GNOME_DEFAULT_LAYOUT: &str = "us";
#[derive(Debug)]
pub(super) struct UnreliableSource(pub &'static str);
impl fmt::Display for UnreliableSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.0)
}
}
impl Error for UnreliableSource {}
#[derive(PartialEq, Eq)]
pub(super) enum Source {
Gnome(Names),
Wayland { keymap: Vec<u8>, group: Option<u32> },
Xwayland { keymap: Vec<u8>, group: Option<u32> },
}
#[derive(PartialEq, Eq)]
pub(super) struct Names {
pub model: CString,
pub layout: CString,
pub variant: CString,
pub options: CString,
}
impl Source {
pub fn read() -> ResultType<Self> {
let connection = Connection::new_session()?;
if name_has_owner(&connection, "org.gnome.Shell")? {
if let Some(names) = gnome_layout()? {
return Ok(Self::Gnome(names));
}
return Ok(Self::Wayland {
keymap: super::wayland::read_keymap()?,
group: None,
});
}
let kde_layouts = name_has_owner(&connection, "org.kde.keyboard")?;
// KWin 5 does not publish the layout service for a single-layout map.
if kde_layouts || name_has_owner(&connection, "org.kde.KWin")? {
return Ok(Self::Wayland {
keymap: super::wayland::read_keymap()?,
group: if kde_layouts {
Some(kde_layout_group(&connection)?)
} else {
None
},
});
}
// Other compositors need the effective keymap and active group of our
// uinput device, including per-device options and custom keymap overrides.
// wl_keyboard exposes a seat map that may belong to a physical keyboard.
// Equal layout names/group indices do not prove map identity: Caps can
// act as AltGr in one map and toggle CapsLock in the other.
//
// Sway GET_INPUTS/GET_SEATS expose names and an index, not the device map.
// GET_CONFIG returns saved config text, not effective runtime input
// settings; parsing it cannot reliably account for runtime overrides.
// Hyprland's devices reply reports RMLVO (rules/model/layout/variant/options),
// but kb_file can override it. Those fields alone cannot reconstruct the
// loaded map. This does not rule out additional compositor-specific APIs.
//
// Reliable native discovery needs a compositor query associating the
// device's actual map (or verified effective configuration) with its group.
// uinput supplies keycodes; it cannot report the compositor's XKB policy.
// Xwayland remains best effort; see xwayland::read for its freshness limits.
// zwp_virtual_keyboard_manager_v1 needs a separate injection backend and
// is not universally supported; it does not query an existing uinput map.
super::xwayland::read()
}
}
fn name_has_owner(connection: &Connection, name: &str) -> ResultType<bool> {
let proxy = connection.with_proxy(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
DBUS_TIMEOUT,
);
let (owned,): (bool,) = proxy.method_call("org.freedesktop.DBus", "NameHasOwner", (name,))?;
Ok(owned)
}
fn kde_layout_group(connection: &Connection) -> ResultType<u32> {
let proxy = connection.with_proxy("org.kde.keyboard", "/Layouts", DBUS_TIMEOUT);
let (group,): (u32,) = proxy.method_call("org.kde.KeyboardLayouts", "getLayout", ())?;
Ok(group)
}
fn gnome_layout() -> ResultType<Option<Names>> {
let schemas = gio::SettingsSchemaSource::default()
.ok_or_else(|| anyhow!("GSettings schemas are unavailable"))?;
let schema = schemas
.lookup(GNOME_INPUT_SCHEMA, true)
.ok_or_else(|| anyhow!("GNOME input source schema is unavailable"))?;
let settings = gio::Settings::new_full(&schema, gio::SettingsBackend::NONE, None);
let sources: Vec<(String, String)> = required_setting(&settings, "sources")?;
// Focus changes restore a window's source without persisting MRU. Mark it
// unreliable so refresh also discards a previously accepted MRU mapping.
if sources.len() > 1 && required_setting::<bool>(&settings, "per-window")? {
return Err(UnreliableSource(
"GNOME per-window input sources cannot be determined from persisted MRU",
)
.into());
}
let recent: Vec<(String, String)> = required_setting(&settings, "mru-sources")?;
// GNOME initially selects the first configured source when MRU is empty.
// The IBus reader verifies the active engine before accepting persisted MRU.
let selected = recent
.iter()
.find(|source| sources.contains(source))
.or(sources.first());
let Some((layout, variant)) = gnome_source_layout(selected)? else {
// IBus engines without an XKB override use the compositor's keymap.
return Ok(None);
};
if layout.is_empty() {
bail!("GNOME input source has an empty layout");
}
// Match GNOME Shell's session-wide options; it does not merge IBus
// engine layout-option metadata into the compositor keymap.
let options: Vec<String> = required_setting(&settings, "xkb-options")?;
// Older GNOME releases use the default model and have no xkb-model setting.
let model: String = if schema.has_key("xkb-model") {
required_setting(&settings, "xkb-model")?
} else {
String::new()
};
Ok(Some(Names {
model: CString::new(model)?,
layout: CString::new(layout)?,
variant: CString::new(variant)?,
options: CString::new(options.join(","))?,
}))
}
fn gnome_source_layout(
selected: Option<&(String, String)>,
) -> ResultType<Option<(String, String)>> {
let Some((kind, id)) = selected else {
// GNOME Shell selects this layout when no input source is configured.
return Ok(Some((GNOME_DEFAULT_LAYOUT.to_owned(), String::new())));
};
match kind.as_str() {
"xkb" => {
let (layout, variant) = id.split_once('+').unwrap_or((id.as_str(), ""));
Ok(Some((layout.to_owned(), variant.to_owned())))
}
"ibus" => ibus::layout(id),
_ => bail!("Unsupported GNOME input source type: {}", kind),
}
}
fn required_setting<T: FromVariant>(settings: &gio::Settings, key: &str) -> ResultType<T> {
if !settings
.settings_schema()
.is_some_and(|schema| schema.has_key(key))
{
bail!("Missing GNOME setting {}", key);
}
settings
.value(key)
.get()
.ok_or_else(|| anyhow!("Invalid GNOME setting {}", key))
}
+86
View File
@@ -0,0 +1,86 @@
use dbus::{
arg::{RefArg, Variant},
blocking::{stdintf::org_freedesktop_dbus::Properties, Connection},
channel::Channel,
};
use hbb_common::{anyhow::anyhow, bail, ResultType};
use std::{env, fs, io::ErrorKind, path::PathBuf};
const IBUS_SERVICE: &str = "org.freedesktop.IBus";
const IBUS_PATH: &str = "/org/freedesktop/IBus";
// IBusEngineDesc serialization preserves these field positions for its clients.
const ENGINE_TYPE_FIELD: usize = 0;
const ENGINE_NAME_FIELD: usize = 2;
const ENGINE_LAYOUT_FIELD: usize = 9;
const ENGINE_VARIANT_FIELD: usize = 14;
pub(super) fn layout(id: &str) -> ResultType<Option<(String, String)>> {
let connection = Connection::from(Channel::open_private(&address()?)?);
let bus = connection.with_proxy(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
super::DBUS_TIMEOUT,
);
let _: (String,) = bus.method_call("org.freedesktop.DBus", "Hello", ())?;
let proxy = connection.with_proxy(IBUS_SERVICE, IBUS_PATH, super::DBUS_TIMEOUT);
let engine: Variant<Box<dyn RefArg>> = proxy.get(IBUS_SERVICE, "GlobalEngine")?;
let fields: Vec<_> = engine
.0
.as_iter()
.ok_or_else(|| anyhow!("Invalid IBus engine description"))?
.collect();
if field(&fields, ENGINE_TYPE_FIELD)? != "IBusEngineDesc" {
bail!("IBus returned an unexpected engine description");
}
// GNOME may suppress IBus for password entry without updating persisted MRU.
// Its xkb:us::eng echo engine does not identify the compositor's layout.
if field(&fields, ENGINE_NAME_FIELD)? != id {
return Err(
super::UnreliableSource("MRU-selected IBus engine is not currently active").into(),
);
}
let layout = field(&fields, ENGINE_LAYOUT_FIELD)?;
if layout.is_empty() || layout == "default" {
return Ok(None);
}
let variant = field(&fields, ENGINE_VARIANT_FIELD)?;
let variant = if variant == "default" { "" } else { variant };
Ok(Some((layout.to_owned(), variant.to_owned())))
}
fn field<'a>(fields: &[&'a dyn RefArg], index: usize) -> ResultType<&'a str> {
fields
.get(index)
.and_then(|value| (*value).as_str())
.ok_or_else(|| anyhow!("Invalid IBus engine field {}", index))
}
fn address() -> ResultType<String> {
if let Some(address) = env::var_os("IBUS_ADDRESS") {
return address
.into_string()
.map_err(|_| anyhow!("Invalid IBus address"));
}
let settings = fs::read_to_string(address_file()?)?;
settings
.lines()
.find_map(|line| line.strip_prefix("IBUS_ADDRESS="))
.map(str::to_owned)
.ok_or_else(|| anyhow!("IBus address file contains no address"))
}
fn address_file() -> ResultType<PathBuf> {
if let Some(path) = env::var_os("IBUS_ADDRESS_FILE") {
return Ok(path.into());
}
let machine = match fs::read_to_string("/var/lib/dbus/machine-id") {
Err(error) if error.kind() == ErrorKind::NotFound => fs::read_to_string("/etc/machine-id")?,
result => result?,
};
let display = env::var("WAYLAND_DISPLAY")?;
Ok(gtk::glib::user_config_dir().join("ibus/bus").join(format!(
"{}-unix-{}",
machine.trim(),
display
)))
}
+151
View File
@@ -0,0 +1,151 @@
use hbb_common::{anyhow::anyhow, bail, libc, ResultType};
use std::{
ffi::CStr,
fs::File,
io,
os::{
fd::{AsRawFd, OwnedFd, RawFd},
unix::fs::FileExt,
},
time::{Duration, Instant},
};
use wayland_client::{
protocol::{wl_keyboard, wl_registry, wl_seat},
Connection, Dispatch, QueueHandle, WEnum,
};
const KEYMAP_TIMEOUT: Duration = Duration::from_secs(1);
const SEAT_VERSION: u32 = 7;
#[derive(Default)]
struct KeyboardState {
seat_bound: bool,
keymap: Option<ResultType<Vec<u8>>>,
}
pub(super) fn read_keymap() -> ResultType<Vec<u8>> {
let connection = Connection::connect_to_env()?;
let mut queue = connection.new_event_queue();
connection.display().get_registry(&queue.handle(), ());
let mut state = KeyboardState::default();
let deadline = Instant::now() + KEYMAP_TIMEOUT;
loop {
queue.dispatch_pending(&mut state)?;
if let Some(keymap) = state.keymap.take() {
return keymap;
}
if Instant::now() >= deadline {
bail!("Timed out reading the Wayland keyboard map");
}
queue.flush()?;
if let Some(reader) = queue.prepare_read() {
wait_for_read(reader.connection_fd().as_raw_fd(), deadline)?;
reader.read()?;
}
}
}
fn wait_for_read(fd: RawFd, deadline: Instant) -> ResultType<()> {
let mut descriptor = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
let timeout = i32::try_from(remaining.as_millis())?;
let ready = unsafe { libc::poll(&mut descriptor, 1, timeout) };
if ready < 0 {
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted {
continue;
}
return Err(error.into());
}
if ready == 0 {
bail!("Timed out reading the Wayland keyboard map");
}
if descriptor.revents & libc::POLLIN == 0 {
bail!("Wayland keyboard connection closed: {}", descriptor.revents);
}
return Ok(());
}
}
fn read_keymap_file(fd: OwnedFd, size: u32) -> ResultType<Vec<u8>> {
let file = File::from(fd);
if file.metadata()?.len() < u64::from(size) {
bail!("Wayland keyboard map is shorter than its advertised size");
}
let mut bytes = vec![0; usize::try_from(size)?];
// Compositors can share this file description with other clients.
file.read_exact_at(&mut bytes, 0)?;
CStr::from_bytes_with_nul(&bytes)?;
Ok(bytes)
}
impl Dispatch<wl_registry::WlRegistry, ()> for KeyboardState {
fn event(
state: &mut Self,
registry: &wl_registry::WlRegistry,
event: wl_registry::Event,
_: &(),
_: &Connection,
handle: &QueueHandle<Self>,
) {
if let wl_registry::Event::Global {
name,
interface,
version,
} = event
{
// Multi-seat sessions are unsupported: neither registry order nor
// keyboard capability identifies the seat receiving our uinput events.
// The first seat may have no keyboard or expose an unrelated keymap.
if interface == "wl_seat" && !state.seat_bound {
registry.bind::<wl_seat::WlSeat, _, _>(name, version.min(SEAT_VERSION), handle, ());
state.seat_bound = true;
}
}
}
}
impl Dispatch<wl_seat::WlSeat, ()> for KeyboardState {
fn event(
_: &mut Self,
seat: &wl_seat::WlSeat,
event: wl_seat::Event,
_: &(),
_: &Connection,
handle: &QueueHandle<Self>,
) {
if let wl_seat::Event::Capabilities {
capabilities: WEnum::Value(capabilities),
} = event
{
if capabilities.contains(wl_seat::Capability::Keyboard) {
seat.get_keyboard(handle, ());
}
}
}
}
impl Dispatch<wl_keyboard::WlKeyboard, ()> for KeyboardState {
fn event(
state: &mut Self,
_: &wl_keyboard::WlKeyboard,
event: wl_keyboard::Event,
_: &(),
_: &Connection,
_: &QueueHandle<Self>,
) {
if let wl_keyboard::Event::Keymap { format, fd, size } = event {
state.keymap = Some(match format {
WEnum::Value(wl_keyboard::KeymapFormat::XkbV1) => read_keymap_file(fd, size),
_ => Err(anyhow!(
"Wayland compositor did not provide an XKB keyboard map"
)),
});
}
}
}
+150
View File
@@ -0,0 +1,150 @@
use super::{source::Source, XkbKeymap, DEFAULT_GROUP};
use hbb_common::{anyhow::anyhow, bail, libc, libloading::Library, ResultType};
use std::{
ffi::{c_void, CStr, CString},
ptr::NonNull,
};
use xkbcommon_dl::{self as xkb, x11};
struct Connection {
pointer: NonNull<c_void>,
disconnect: unsafe extern "C" fn(*mut c_void),
_library: Library,
}
impl Connection {
fn open() -> ResultType<Self> {
let display = CString::new(std::env::var("DISPLAY")?)?;
if display.as_bytes().is_empty() {
bail!("Xwayland DISPLAY is empty");
}
if !display.as_bytes().starts_with(b":")
&& !display.as_bytes().starts_with(b"unix:")
&& !display.as_bytes().starts_with(b"unix/:")
{
bail!("Xwayland layout detection requires a local DISPLAY");
}
unsafe {
let library = Library::new("libxcb.so.1")?;
let connect = *library
.get::<unsafe extern "C" fn(*const libc::c_char, *mut libc::c_int) -> *mut c_void>(
b"xcb_connect\0",
)?;
let disconnect =
*library.get::<unsafe extern "C" fn(*mut c_void)>(b"xcb_disconnect\0")?;
let has_error = *library.get::<unsafe extern "C" fn(*mut c_void) -> libc::c_int>(
b"xcb_connection_has_error\0",
)?;
let pointer = NonNull::new(connect(display.as_ptr(), std::ptr::null_mut()))
.ok_or_else(|| anyhow!("Cannot create Xwayland connection"))?;
let connection = Self {
pointer,
disconnect,
_library: library,
};
let error = has_error(connection.pointer.as_ptr());
if error != 0 {
bail!("Cannot connect to Xwayland (XCB error {})", error);
}
Ok(connection)
}
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe { (self.disconnect)(self.pointer.as_ptr()) };
}
}
pub(super) fn read() -> ResultType<Source> {
// Xwayland receives the group through focus-scoped wl_keyboard.modifiers.
// With a native window focused, both core and slave X11 keyboards can
// retain the last X11-focused group (verified on GNOME and KWin).
// Reopening XCB or waiting cannot request the missing compositor update.
// Prefer native GNOME/KDE sources; do not steal focus to refresh Xwayland.
let api = xkb::xkbcommon_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon"))?;
let x11 = x11::xkbcommon_x11_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon-x11"))?;
let connection = Connection::open()?;
let device = keyboard_device(x11, &connection)?;
let keymap = read_keymap(x11, &connection, device)?;
let state = unsafe {
(x11.xkb_x11_state_new_from_device)(
keymap.map.as_ptr(),
connection.pointer.as_ptr(),
device,
)
};
let state =
NonNull::new(state).ok_or_else(|| anyhow!("Cannot read Xwayland keyboard state"))?;
let group = unsafe {
(api.xkb_state_serialize_layout)(
state.as_ptr(),
xkb::xkb_state_component::XKB_STATE_LAYOUT_EFFECTIVE,
)
};
unsafe { (api.xkb_state_unref)(state.as_ptr()) };
let text = unsafe {
(api.xkb_keymap_get_as_string)(
keymap.map.as_ptr(),
xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
)
};
let text = NonNull::new(text.cast_mut())
.ok_or_else(|| anyhow!("Cannot serialize Xwayland keyboard map"))?;
let bytes = unsafe { CStr::from_ptr(text.as_ptr()).to_bytes_with_nul().to_vec() };
unsafe { libc::free(text.as_ptr().cast()) };
Ok(Source::Xwayland {
keymap: bytes,
group: Some(group),
})
}
fn read_keymap(
x11: &x11::XkbCommonX11,
connection: &Connection,
device: i32,
) -> ResultType<XkbKeymap> {
let api = xkb::xkbcommon_option().ok_or_else(|| anyhow!("Cannot load libxkbcommon"))?;
let context =
unsafe { (api.xkb_context_new)(xkb::xkb_context_flags::XKB_CONTEXT_NO_ENVIRONMENT_NAMES) };
let context = NonNull::new(context).ok_or_else(|| anyhow!("Cannot create XKB context"))?;
let map = unsafe {
(x11.xkb_x11_keymap_new_from_device)(
context.as_ptr(),
connection.pointer.as_ptr(),
device,
xkb::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
)
};
unsafe { (api.xkb_context_unref)(context.as_ptr()) };
let map = NonNull::new(map).ok_or_else(|| anyhow!("Cannot read Xwayland keyboard map"))?;
Ok(XkbKeymap {
api,
map,
group: DEFAULT_GROUP,
})
}
fn keyboard_device(api: &x11::XkbCommonX11, connection: &Connection) -> ResultType<i32> {
let supported = unsafe {
(api.xkb_x11_setup_xkb_extension)(
connection.pointer.as_ptr(),
x11::XKB_X11_MIN_MAJOR_XKB_VERSION,
x11::XKB_X11_MIN_MINOR_XKB_VERSION,
x11::xkb_x11_setup_xkb_extension_flags::XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if supported == 0 {
bail!("Xwayland does not support the required XKB extension");
}
let device = unsafe { (api.xkb_x11_get_core_keyboard_device_id)(connection.pointer.as_ptr()) };
if device < 0 {
bail!("Xwayland has no core keyboard device");
}
Ok(device)
}
+36 -1
View File
@@ -727,6 +727,8 @@ fn run(vs: VideoService) -> ResultType<()> {
let repeat_encode_max = 10;
let mut encode_fail_counter = 0;
let mut first_frame = true;
// Set once the encoder emits its first packet; until then it may legitimately return nothing.
let mut encoder_warmed_up = false;
let capture_width = c.width;
let capture_height = c.height;
let (mut second_instant, mut send_counter) = (Instant::now(), 0);
@@ -743,7 +745,12 @@ fn run(vs: VideoService) -> ResultType<()> {
&mut second_instant,
&sp.name(),
)?;
if sp.is_option_true(OPTION_REFRESH) {
// On macOS, a refresh here would destroy a hardware encoder that has been fed a frame but
// not yet produced its first packet, restarting the warm-up forever. Defer until it has;
// one that never does is still switched away from by max_fail_times in handle_one_frame.
if sp.is_option_true(OPTION_REFRESH)
&& refresh_allowed(first_frame, encoder_warmed_up, encoder.latency_free())
{
if vs.source.is_monitor() {
let _ = try_broadcast_display_changed(&sp, display_idx, &c, true);
}
@@ -857,6 +864,7 @@ fn run(vs: VideoService) -> ResultType<()> {
recorder.clone(),
&mut encode_fail_counter,
&mut first_frame,
&mut encoder_warmed_up,
capture_width,
capture_height,
)?;
@@ -921,6 +929,7 @@ fn run(vs: VideoService) -> ResultType<()> {
recorder.clone(),
&mut encode_fail_counter,
&mut first_frame,
&mut encoder_warmed_up,
capture_width,
capture_height,
)?;
@@ -1233,6 +1242,12 @@ fn check_privacy_mode_changed(
Ok(())
}
#[inline]
fn refresh_allowed(unfed: bool, warmed_up: bool, latency_free: bool) -> bool {
// Only VideoToolbox has been seen to need this; other platforms keep refreshing as before.
!cfg!(target_os = "macos") || unfed || warmed_up || latency_free
}
#[inline]
fn handle_one_frame(
display: usize,
@@ -1243,6 +1258,7 @@ fn handle_one_frame(
recorder: Arc<Mutex<Option<Recorder>>>,
encode_fail_counter: &mut usize,
first_frame: &mut bool,
encoder_warmed_up: &mut bool,
width: usize,
height: usize,
) -> ResultType<HashSet<i32>> {
@@ -1261,6 +1277,7 @@ fn handle_one_frame(
match encoder.encode_to_message(frame, ms) {
Ok(mut vf) => {
*encode_fail_counter = 0;
*encoder_warmed_up = true;
vf.display = display as _;
let mut msg = Message::new();
msg.set_video_frame(vf);
@@ -1525,3 +1542,21 @@ fn handle_screenshot(screenshot: Screenshot, msg: String, w: usize, h: usize, da
log::error!("Failed to send screenshot, {}", e);
}
}
#[cfg(test)]
mod tests {
use super::refresh_allowed;
#[test]
fn refresh_waits_for_hw_encoder_warmup() {
// Deferred on macOS only; everywhere else a refresh is always allowed.
assert_eq!(
refresh_allowed(false, false, false),
!cfg!(target_os = "macos")
);
assert!(refresh_allowed(false, true, false));
assert!(refresh_allowed(false, false, true));
// Nothing fed yet: no warm-up to lose, and a refresh can restart a stalled capturer.
assert!(refresh_allowed(true, false, false));
}
}
+1 -1
View File
@@ -1832,7 +1832,7 @@ impl<T: InvokeUiSession> Interface for Session<T> {
self.try_change_init_resolution(pi.current_display);
let p = self.lc.read().unwrap().should_auto_login();
if !p.is_empty() {
input_os_password(p, true, self.clone());
crate::client::auto_login(p, &pi, self.clone());
}
}
let current = &pi.displays[pi.current_display as usize];