mirror of
https://github.com/rustdesk/rustdesk.git
synced 2026-11-04 00:33:12 +00:00
* fix web break introduced in 38f130071 fix(linux): enable mouse side buttons in remote sessions (#14848)
* feat(shortcuts): user-configurable keyboard shortcuts for session actions
Adds a keyboard shortcut feature (Rust matcher + Dart UI + cross-language
parity tests) that lets users bind combinations like Ctrl+Alt+Shift+P to
session actions. Bindings are stored in LocalConfig under
`keyboard-shortcuts`; the matcher gates dispatch on `enabled` and
`pass_through` flags so flipping the master switch off is a hard stop.
Wire-up summary:
- src/keyboard/shortcuts.rs: matcher, default bindings, parity test against
flutter/test/fixtures/default_keyboard_shortcuts.json
- src/keyboard.rs: shortcut intercept in process_event{,_with_session},
feature-gated to `flutter`; runs before key swapping so users bind to
physical keys
- src/flutter_ffi.rs: main_reload_keyboard_shortcuts +
main_get_default_keyboard_shortcuts; reload_from_config seeded in main_init
- flutter/lib/common/widgets/keyboard_shortcuts/: shared config page body,
recording dialog, shortcut display formatter, action group registry
- flutter/lib/desktop/pages/desktop_keyboard_shortcuts_page.dart and
flutter/lib/mobile/pages/mobile_keyboard_shortcuts_page.dart: platform
shells around the shared body
- flutter/lib/models/shortcut_model.dart: per-session ShortcutModel +
registerSessionShortcutActions for actions with no toolbar TToggleMenu /
TRadioMenu (fullscreen, switch display/tab, close tab, voice call, etc.)
- flutter/lib/common/widgets/toolbar.dart: optional `actionId` field on
TToggleMenu / TRadioMenu, plus per-helper auto-register pass that wires
tagged entries' existing onChanged into the ShortcutModel
- flutter/test/keyboard_shortcuts_test.dart + fixtures: cross-language
parity (default bindings, supported key vocabulary)
Design principles applied during review:
1. Additions are fine; modifications to original logic must be deliberate.
Tagging an existing TToggleMenu entry with `actionId:` is an addition.
Rewriting its onChanged to satisfy a new contract is a modification —
and was reverted for every case where the original click behavior was
working. Four closures were touched and then reverted (mobile View
Mode, Privacy mode multi-impl, Relative mouse mode, Reverse mouse
wheel); their shortcuts are wired via standalone closures in
shortcut_model.dart instead.
2. Toolbar auto-register is reserved for entries whose onChanged is
inherently self-flipping — typically `sessionToggleOption(name)` where
the named option is flipped in place and the input bool is unused. The
register pass passes `!menu.value` from registration time, which is
harmless under self-flipping but wrong for closures that consume the
input bool directly. Tagging a non-self-flipping entry forces a closure
rewrite; choose non-toolbar registration in that case.
3. When shortcuts are disabled, toolbar behavior must be bit-for-bit
unchanged. The matcher's `enabled`-gate already guarantees no
dispatch; the auto-register pass is left unconditional (its only effect
is HashMap operations on a separate ShortcutModel) so mid-session
enable works without a reconnect. The trade-off is intentional and
documented at the top of toolbarControls.
4. Comments stay terse. Rationale lives in one place — the doc comment of
the helper or registration site, not duplicated at every call site.
5. Where an existing helper needs a new optional behavior (e.g.
`_OptionCheckBox` gaining a tooltip slot), the new branch must reduce
to byte-identical output for existing callers (`trailing == null`
case → original `Expanded(Text)` layout). Verified.
6. Action IDs and labels stay consistent. Renamed `reset_cursor` →
`reset_canvas` so the action ID matches its user-facing label
("Reset canvas") and capability flag.
Out-of-scope but included:
- AGENTS.md: documents flutter_rust_bridge no-codegen workflow and the
Web target's hand-written TS client, since both are load-bearing for
any new FFI work.
- remote_toolbar.dart: i18n fix for the per-monitor tooltip ("All
monitors" / "Monitor #N"), unrelated to shortcuts but kept here.
* langs
* fix(keyboard): shortcuts, harden config and callback lifecycle
Signed-off-by: fufesou <linlong1266@gmail.com>
* feat(keyboard): shortcuts, color of "Reset to defaults"
Signed-off-by: fufesou <linlong1266@gmail.com>
* feat(keyboard): shortcuts, release keys before shortcut callback
Signed-off-by: fufesou <linlong1266@gmail.com>
* feat(keyboard): shortcuts, debug web
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(keyboard): iPad, icon
Signed-off-by: fufesou <linlong1266@gmail.com>
* langs: add shortcut keys to az, gl, ur
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, keep local modifiers and release keys on the right session
When a chord fired, the shortcut path reused release_remote_keys(), which
replays synthetic releases through process_event(). That cleared the local
MODIFIERS_STATE while the user still held the modifiers, so the next key of
a held chord no longer matched and leaked to the remote, and it sent the
releases to the globally current session instead of the one that typed the
chord.
The shortcut path now releases the remote keys itself: it sends through the
caller's session, and restores the modifiers it released on the remote as
still held locally. The press that fired is remembered until its release,
so its auto repeats and its release are consumed instead of reaching the
remote.
Also state the contract for unavailable actions: a bound chord always
belongs to RustDesk and is a no-op when the session has no handler.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, record the physical key
The recording dialog and the Web Flutter matcher named keys by
LogicalKeyboardKey, while the native matcher sees the physical key through
its USB HID usage and the Web JS matcher through KeyboardEvent.code. On
AZERTY, QWERTZ, Dvorak and similar layouts a recorded binding then did not
fire, or fired from another key.
Name keys by their physical position everywhere: physicalKeyName maps the
USB HID usage to the stored name. A new fixture pins every name to its USB
HID usage, checked on the Dart side and against rdev::usb_hid_key_from_code
on the Rust side, and a test covers AZERTY and QWERTZ events.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, keep an empty binding list on re-enable
setEnabled seeded the defaults whenever the binding list was empty, so a
user who cleared every binding got all defaults back after disable and
enable. Seed only when the config has never held a bindings list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, track every fired key until its release
FIRED_KEY held a single key, so overlapping shortcut keys broke it: with the
chord held, P then C overwrote P, P's release reached the remote, and a P
repeat could fire the screenshot again. A repeat after the modifiers were
released was also treated as a new press and leaked to the remote.
Keep a set of fired keys instead. Once a press fires, every event of that
key belongs to RustDesk until its release: repeats are consumed without
dispatching, whatever the modifiers do, and the release removes the key.
Entries whose release never arrives are dropped when a session view is
entered or a session is closed, not by guessing from the modifiers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, keep fired keys per session
FIRED_KEYS was process-global while dispatch is per session. Closing or
entering any session cleared the fired keys of all of them, so a key still
held in another session leaked its release to that remote, and a key fired
in one session made the same key in another session look like a repeat.
Key the fired set by session: try_dispatch resolves the session first and
only looks at that session's keys, and session_close clears only the
closing session. Entering a session view no longer clears anything: it is
a pointer enter, and a fired key may still be physically held across it.
A key whose release is missed otherwise heals itself: its next press is
consumed as a repeat and that release removes it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(shortcuts): preserve input state and refresh action availability
* fix(keyboard): shortcuts, keep a fired key owned across session close
Close tab is itself a shortcut, so the session that consumed the key press
is gone before the key is released. Both matchers dropped the key with the
session: the Flutter dispatcher removed its own entries in clear(), and the
Rust set was keyed by session and cleared in session_close. The release,
and the repeats while the key stayed held, then reached the next session's
remote as ordinary input.
Ownership of a fired key is physical, so it is now one set shared by every
session on each side, and closing a session no longer touches it: clear()
only drops the pending action and modifier replay, and the Rust session
state only tracks released modifiers. A key whose release is missed heals
itself on its next press. Entering view-only with the Flutter input source
still clears the Rust set, since that source stops routing key events to it.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, drop the Toggle Input Source action
The action switches the key capture backend between key down and key up.
Fired-key ownership lives in whichever matcher saw the press, the Flutter
dispatcher or the Rust set, and there is no handoff between them: after the
switch the repeats and the release of the held key reach the other backend,
which forwards them to the remote and, while the chord is held, matches the
action again and toggles the source back. Remove the shortcut instead of
building a handoff for one action. The toolbar radio menu is unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* perf(keyboard): shortcuts, parse the config once per stored value
The Flutter matcher read the local config three times and parsed its JSON
three times on every key press in legacy mode, on Web and in view-only.
Keep one parsed snapshot keyed by the raw stored string, so a key press
costs one config read and no parsing while the config is unchanged. The
existing readers are thin views of the same snapshot.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix(keyboard): shortcuts, run focus-changing actions on key release
Close tab and tab switching move keyboard focus to another session before
the key that fired them is released. On Linux the Flutter input source
routes map-mode sessions through the Rust matcher and legacy-mode sessions
through the Dart matcher, and neither knows the other's fired keys, so
after such an action the repeats and the release of the held key reached
the next session's remote, and the key stayed recorded as fired in the
matcher that saw the press.
Routing Linux legacy mode through the Rust FFI path instead is not a drop-in
change: the raw key handler builds its event with no unicode, so Rust's
legacy mode would fall back to US key names and lose the layout-aware
characters the Dart path sends today, and it would take modifiers from the
X11 key state instead of Flutter's.
Run these three actions when the fired key is released. The matcher that
consumed the press then also sees the repeats and the release, the remote
modifiers are still released on the press, and a session that closes drops
the action it owed. Both matchers keep the same list of actions.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* test(keyboard): shortcuts, pin the key-up action list on both sides
kShortcutActionsRunOnKeyUp and runs_on_release are two hand-kept lists of
the actions that run on key release. Add a shared fixture and check each
side against it, the way the key vocabulary and the default bindings are
already checked, so adding a focus-changing action on one side breaks a
test until the other side follows. The Dart test also checks that every
listed id is a configurable action.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ra4my61t8q1FN5n59wB16D
* fix: prevent lost input after remote session shortcuts
Avoid synthetic Alt presses that activate the Windows system menu
and swallow the next character.
Trigger restart, switch-sides, and chat actions on key release so
focus changes cannot leave subsequent shortcut presses ignored.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(mobile): correct Chat keyboard and input helper behavior
- Keep soft keyboard and helper hidden when Chat opens via shortcut
- Restore soft input on touch and remote focus after Chat closes
- Handle modifier releases while Chat owns focus
- Clear hidden virtual modifiers while preserving held keys and Pin behavior
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): prevent recording non-simultaneous key combinations
Build new captures from currently held keys instead of reusing released
letters. Preserve the last valid chord after release so it can be saved.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): isolate window actions and prevent duplicate Alt presses
- Dispatch shortcut actions only to the originating session window.
- Clear local modifier state on focus loss without resending modifiers
already released to Windows peers, preventing lost following input.
- Strengthen the regression assertion against extra Alt keydown events
Signed-off-by: fufesou <linlong1266@gmail.com>
* refact(shortcuts): empty default shortcuts for Cmd+Option+Shift+Del on macOS and iOS
Because Del may be ambiguous for new macOS users.
Cmd+Option+Shift+Backspace is "Empty Trash without confirmation" shortcut on macOS.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: use session peer platform for Ctrl+Alt+Del events
Fix Android-to-Linux Ctrl+Alt+Del delivery by using the session's peer
platform instead of the desktop global session, which defaults to Windows
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: hide relative mouse mode shortcuts on Wayland
Separate relative mouse mode availability from screenshot support.
Filter unsupported actions and defaults while preserving saved bindings
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: align shortcut availability with platform support
- Hide unsupported mobile and web shortcut actions
- Enable mobile scaling and Android voice call shortcuts
- Use openMonitorInTheSameTab() for display switching
- Preserve cursor position when switching displays on desktop and web
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: prevent held-key shortcut recording bypass
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: preserve keyboard input after shortcut dialogs
Run native clipboard shortcuts on key release and wait for remote modifier releases before dispatching.
Release remote modifiers when mobile local UI takes focus, and document the tested iPad Bluetooth Mute shortcut limitation.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: preserve remote key state during local shortcuts
Keep unrelated held keys pressed for session actions that retain input. Preserve key release when focus or input handling changes, and avoid synthetic Alt taps during shortcut dispatch.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: suspend saved relative mouse shortcuts on Wayland
Filter the native active binding cache without changing stored configuration, so the binding becomes available again under X11.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: exclude unsupported Wayland shortcuts from Flutter matching
Keep saved bindings intact while filtering the active config used by the Flutter matcher. Cover stored bindings and enable/pass-through flags in the existing shortcut tests.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: retain forwarded key ownership across shortcut repeats
Ignore repeat presses for keys already forwarded to the peer, and release ordinary held keys before Show My Cursor enables view-only. Cover both paths with converter-level regressions.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: release Flutter-held keys before view-only shortcuts
Track ordinary keys forwarded by the Dart matcher paths and await their releases before View Only or Show My Cursor disables input. Keep Mute key ownership and existing empty-cleanup timing unchanged.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: filter active Flutter shortcuts by platform capabilities
Reuse the Settings action filter for saved bindings while preserving storage, default-seeding behavior and configurable Apple Ctrl+Alt+Del bindings.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: filter native shortcut caches for mobile controllers
Suspend saved desktop-only actions on Android and iOS and hide unavailable iOS actions without changing persisted bindings. Keep native cache filtering aligned with Flutter platform capabilities.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: share filtered shortcut bindings with the Web matcher
Pass the active platform config to JavaScript at startup and after settings changes, preserving unsupported saved bindings in local storage.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: release Flutter-held keys before focus-changing shortcuts
Drain ordinary keys owned by the original session before run-on-key-up
actions and native clipboard callbacks. Preserve Mute holds, pending-action
cancellation and Web clipboard key-down activation.
Document the required Web matcher counterpart in the bridge:
rustdesk/rustdesk-web-js@94abe431d6
Validation: 61 native Flutter tests, 32 Chrome/HTML tests, targeted analysis
and Windows debug build.
Signed-off-by: fufesou <linlong1266@gmail.com>
* refact: remove the useless comments
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: prevent Windows menu activation from Alt-only shortcuts
Neutralize the forwarded Alt with a balanced temporary Ctrl press when a consumed local shortcut releases its only modifier in Windows Map mode. Keep physical modifier tracking and normal Alt pass-through unchanged.
Add a regression covering both Alt keys, trigger repeats and the eventual physical release. Verified with 36 native shortcut tests and real Windows menu/input checks.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: prevent Alt menu activation in all keyboard modes
Extend Windows Alt-only shortcut neutralization to Translate and Legacy. Keep the temporary Ctrl packets in Map mode so Legacy modifier synchronization cannot release Alt before Ctrl.
Extend the existing regression across keyboard modes and decode scan, virtual and control-key events. Verify 36 native tests and 34 Windows menu replay cases.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: initialize outgoing chat before shortcut dispatch
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: guard Windows Alt release in Flutter legacy shortcuts
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: coordinate Web shortcut dispatch and Alt modifier cleanup
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: distinguish AltGraph from ordinary Alt shortcuts
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: dispatch macOS Web shortcuts without waiting for keyup
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: support legacy peers in privacy mode shortcut
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: exclude AltGraph from Flutter shortcut matching
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix: exclude GTK AltGr input from raw shortcut matching
Signed-off-by: fufesou <linlong1266@gmail.com>
* test: trim redundant keyboard shortcut coverage
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(keyboard): prevent Cmd shortcuts from opening remote Start
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): guard Windows menu keys after Ctrl/Cmd swapping
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): align recording and display routing
Reject non-Apple AltGraph captures to match runtime filtering. Honor individual-display windows for next, previous, and all-display shortcuts.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): reject GTK AltGr chords in recorder
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(android): restore keyboard focus for modifier-first input
Focus the existing FlutterView when a modifier is pressed without native view focus. This restores shortcut-first input after returning to RustDesk while preserving focused inputs and normal key dispatch.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): release held keys before keyboard mode changes
Drain Flutter-forwarded keys before keyboard-mode shortcut actions so releases use the original encoding. This prevents held keys from remaining down after a Web Input source 2 mode change.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(i18n): use sentence case for shortcut labels
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(mobile): preserve touch modifiers in the input helper
Keep touch-selected modifiers visible after hiding the keyboard. Clear physical modifier releases locally in view-only mode so they do not reopen the helper.
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(web): preserve modifiers across Legacy-to-Map shortcuts
Signed-off-by: fufesou <linlong1266@gmail.com>
* fix(shortcuts): check support before registering all displays view
Signed-off-by: fufesou <linlong1266@gmail.com>
---------
Signed-off-by: fufesou <linlong1266@gmail.com>
Co-authored-by: fufesou <linlong1266@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1514 lines
53 KiB
Dart
1514 lines
53 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:desktop_multi_window/desktop_multi_window.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter/scheduler.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:provider/provider.dart';
|
|
import 'package:flutter_hbb/models/state_model.dart';
|
|
|
|
import '../../consts.dart';
|
|
import '../../common/widgets/overlay.dart';
|
|
import '../../common/widgets/remote_input.dart';
|
|
import '../../common.dart';
|
|
import '../../common/widgets/dialog.dart';
|
|
import '../../common/widgets/toolbar.dart';
|
|
import '../../models/model.dart';
|
|
import '../../models/input_model.dart';
|
|
import '../../models/platform_model.dart';
|
|
import '../../models/shortcut_model.dart';
|
|
import '../../common/shared_state.dart';
|
|
import '../../utils/image.dart';
|
|
import '../widgets/remote_toolbar.dart';
|
|
import '../widgets/kb_layout_type_chooser.dart';
|
|
import '../widgets/tabbar_widget.dart';
|
|
import 'macos_full_screen_focus_recovery.dart';
|
|
|
|
import 'package:flutter_hbb/native/custom_cursor.dart'
|
|
if (dart.library.html) 'package:flutter_hbb/web/custom_cursor.dart';
|
|
|
|
final SimpleWrapper<bool> _firstEnterImage = SimpleWrapper(false);
|
|
|
|
// Used to skip session close if "move to new window" is clicked.
|
|
final Map<String, bool> closeSessionOnDispose = {};
|
|
|
|
class RemotePage extends StatefulWidget {
|
|
RemotePage({
|
|
Key? key,
|
|
required this.id,
|
|
required this.toolbarState,
|
|
this.sessionId,
|
|
this.tabWindowId,
|
|
this.password,
|
|
this.display,
|
|
this.displays,
|
|
this.tabController,
|
|
this.switchUuid,
|
|
this.forceRelay,
|
|
this.isSharedPassword,
|
|
}) : super(key: key) {
|
|
initSharedStates(id);
|
|
}
|
|
|
|
final String id;
|
|
final SessionID? sessionId;
|
|
final int? tabWindowId;
|
|
final int? display;
|
|
final List<int>? displays;
|
|
final String? password;
|
|
final ToolbarState toolbarState;
|
|
final String? switchUuid;
|
|
final bool? forceRelay;
|
|
final bool? isSharedPassword;
|
|
final SimpleWrapper<State<RemotePage>?> _lastState = SimpleWrapper(null);
|
|
final DesktopTabController? tabController;
|
|
|
|
FFI get ffi => (_lastState.value! as _RemotePageState)._ffi;
|
|
|
|
void releaseMacOSInputForTabTransfer() {
|
|
if (!isMacOS) return;
|
|
// Release before removing the source tab. Its delayed disposal must not
|
|
// disable a native keyboard hook already acquired by the destination page.
|
|
(_lastState.value! as _RemotePageState)._releaseMacOSRemoteInput();
|
|
}
|
|
|
|
@override
|
|
State<RemotePage> createState() {
|
|
final state = _RemotePageState(id);
|
|
_lastState.value = state;
|
|
return state;
|
|
}
|
|
}
|
|
|
|
class _RemotePageState extends State<RemotePage>
|
|
with
|
|
AutomaticKeepAliveClientMixin,
|
|
MultiWindowListener,
|
|
WidgetsBindingObserver,
|
|
TickerProviderStateMixin {
|
|
Timer? _timer;
|
|
String keyboardMode = "legacy";
|
|
bool _isWindowBlur = false;
|
|
// Known macOS remote-input trade-offs (kept simple intentionally):
|
|
// 1. Dialogs rely on FocusNode loss plus middleBlocked, not mirrored dialog
|
|
// state. Reproduce: activate remote input, open a dialog, then type.
|
|
// 2. Delayed fullscreen recovery can race a local-control focus change; no
|
|
// owner state is added. Reproduce: focus the toolbar during a Space switch.
|
|
// 3. Input-source switching releases native input without updating this
|
|
// page's cache. Reproduce: switch sources, then type before and after
|
|
// clicking the remote image; the click reasserts input.
|
|
// These latches compensate for out-of-order macOS focus events. Treat them
|
|
// as coupled when changing a transition or _syncMacOSKeyboardGrab().
|
|
AppLifecycleState? _macOSLifecycleState;
|
|
bool _macOSLocalFocusLost = false;
|
|
bool _macOSInputActive = false;
|
|
bool _macOSInputSuppressed = false;
|
|
final _macOSFullScreenFocusRecovery = MacOSFullScreenFocusRecovery();
|
|
bool _macOSExplicitFocusRequestPending = false;
|
|
StreamSubscription<DesktopTabState>? _tabStateSubscription;
|
|
final _cursorOverImage = false.obs;
|
|
late RxBool _showRemoteCursor;
|
|
late RxBool _zoomCursor;
|
|
late RxBool _remoteCursorMoved;
|
|
late RxBool _keyboardEnabled;
|
|
final _uniqueKey = UniqueKey();
|
|
|
|
var _blockableOverlayState = BlockableOverlayState();
|
|
|
|
final FocusNode _rawKeyFocusNode = FocusNode(debugLabel: "rawkeyFocusNode");
|
|
|
|
// Debounce timer for pointer lock center updates during window events.
|
|
// Uses kDefaultPointerLockCenterThrottleMs from consts.dart for the duration.
|
|
Timer? _pointerLockCenterDebounceTimer;
|
|
|
|
// We need `_instanceIdOnEnterOrLeaveImage4Toolbar` together with `_onEnterOrLeaveImage4Toolbar`
|
|
// to identify the toolbar instance and its callback function.
|
|
int? _instanceIdOnEnterOrLeaveImage4Toolbar;
|
|
Function(bool)? _onEnterOrLeaveImage4Toolbar;
|
|
|
|
late FFI _ffi;
|
|
Worker? _waylandKeyboardModeWorker;
|
|
bool _waylandKeyboardModeNormalized = false;
|
|
bool _waylandKeyboardModeNormalizing = false;
|
|
|
|
SessionID get sessionId => _ffi.sessionId;
|
|
|
|
_RemotePageState(String id) {
|
|
_initStates(id);
|
|
}
|
|
|
|
void _initStates(String id) {
|
|
_zoomCursor = PeerBoolOption.find(id, kOptionZoomCursor);
|
|
_showRemoteCursor = ShowRemoteCursorState.find(id);
|
|
_keyboardEnabled = KeyboardEnabledState.find(id);
|
|
_remoteCursorMoved = RemoteCursorMovedState.find(id);
|
|
}
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_ffi = FFI(widget.sessionId);
|
|
if (isMacOS) {
|
|
// SchedulerBinding.instance.lifecycleState is null in the first connection in a new window.
|
|
_macOSLifecycleState = SchedulerBinding.instance.lifecycleState;
|
|
WidgetsBinding.instance.addObserver(this);
|
|
_tabStateSubscription =
|
|
widget.tabController?.state.listen(_onMacOSTabStateChanged);
|
|
}
|
|
Get.put<FFI>(_ffi, tag: widget.id);
|
|
_ffi.imageModel.addCallbackOnFirstImage((String peerId) {
|
|
_ffi.canvasModel.activateLocalCursor();
|
|
showKBLayoutTypeChooserIfNeeded(
|
|
_ffi.ffiModel.pi.platform, _ffi.dialogManager);
|
|
_ffi.recordingModel
|
|
.updateStatus(bind.sessionGetIsRecording(sessionId: _ffi.sessionId));
|
|
// Seed shortcut action callbacks once the session is ready, so that
|
|
// global keyboard shortcuts work even if the user never opens the
|
|
// toolbar menu. The returned list is intentionally discarded — the
|
|
// side effect of registering callbacks (inside toolbarControls) is
|
|
// what we want here.
|
|
if (mounted) {
|
|
toolbarControls(context, widget.id, _ffi);
|
|
registerSessionShortcutActions(_ffi,
|
|
tabController: widget.tabController,
|
|
toolbarState: widget.toolbarState);
|
|
registerToolbarShortcuts(context, widget.id, _ffi);
|
|
}
|
|
});
|
|
_ffi.canvasModel.initializeEdgeScrollFallback(this);
|
|
_ffi.start(
|
|
widget.id,
|
|
password: widget.password,
|
|
isSharedPassword: widget.isSharedPassword,
|
|
switchUuid: widget.switchUuid,
|
|
forceRelay: widget.forceRelay,
|
|
tabWindowId: widget.tabWindowId,
|
|
display: widget.display,
|
|
displays: widget.displays,
|
|
);
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
|
|
_ffi.dialogManager
|
|
.showLoading(translate('Connecting...'), onCancel: closeConnection);
|
|
});
|
|
WakelockManager.enable(_uniqueKey);
|
|
|
|
_ffi.ffiModel.updateEventListener(sessionId, widget.id);
|
|
_ffi.qualityMonitorModel.checkShowQualityMonitor(sessionId);
|
|
_ffi.dialogManager.loadMobileActionsOverlayVisible();
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
// Session option should be set after models.dart/FFI.start
|
|
_showRemoteCursor.value = bind.sessionGetToggleOptionSync(
|
|
sessionId: sessionId, arg: 'show-remote-cursor');
|
|
_zoomCursor.value = bind.sessionGetToggleOptionSync(
|
|
sessionId: sessionId, arg: kOptionZoomCursor);
|
|
});
|
|
DesktopMultiWindow.addListener(this);
|
|
// if (!_isCustomCursorInited) {
|
|
// customCursorController.registerNeedUpdateCursorCallback(
|
|
// (String? lastKey, String? currentKey) async {
|
|
// if (_firstEnterImage.value) {
|
|
// _firstEnterImage.value = false;
|
|
// return true;
|
|
// }
|
|
// return lastKey == null || lastKey != currentKey;
|
|
// });
|
|
// _isCustomCursorInited = true;
|
|
// }
|
|
|
|
_blockableOverlayState.applyFfi(_ffi);
|
|
// Call onSelected in post frame callback, since we cannot guarantee that the callback will not call setState.
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
widget.tabController?.onSelected?.call(widget.id);
|
|
});
|
|
|
|
// Register callback to cancel debounce timer when relative mouse mode is disabled
|
|
_ffi.inputModel.onRelativeMouseModeDisabled =
|
|
_cancelPointerLockCenterDebounceTimer;
|
|
|
|
_waylandKeyboardModeWorker = ever(_ffi.ffiModel.pi.isSet, (bool isSet) {
|
|
if (isSet) {
|
|
unawaited(_normalizeWaylandKeyboardModeIfNeeded());
|
|
}
|
|
});
|
|
if (_ffi.ffiModel.pi.isSet.value) {
|
|
unawaited(_normalizeWaylandKeyboardModeIfNeeded());
|
|
}
|
|
}
|
|
|
|
Future<void> _normalizeWaylandKeyboardModeIfNeeded() async {
|
|
if (!mounted ||
|
|
_waylandKeyboardModeNormalized ||
|
|
_waylandKeyboardModeNormalizing) {
|
|
return;
|
|
}
|
|
_waylandKeyboardModeNormalizing = true;
|
|
try {
|
|
final pi = _ffi.ffiModel.pi;
|
|
if (pi.platform != kPeerPlatformLinux || !pi.isWayland) return;
|
|
final mapSupported = bind.sessionIsKeyboardModeSupported(
|
|
sessionId: sessionId, mode: kKeyMapMode);
|
|
if (!mapSupported) return;
|
|
final current = await bind.sessionGetKeyboardMode(sessionId: sessionId);
|
|
if (!mounted) return;
|
|
if (current == kKeyMapMode) {
|
|
_waylandKeyboardModeNormalized = true;
|
|
return;
|
|
}
|
|
await bind.sessionSetKeyboardMode(
|
|
sessionId: sessionId, value: kKeyMapMode);
|
|
if (!mounted) return;
|
|
await _ffi.inputModel.updateKeyboardMode();
|
|
if (!mounted) return;
|
|
_waylandKeyboardModeNormalized = true;
|
|
} catch (e, st) {
|
|
debugPrint('Failed to normalize Wayland keyboard mode: $e');
|
|
debugPrintStack(stackTrace: st);
|
|
} finally {
|
|
_waylandKeyboardModeNormalizing = false;
|
|
}
|
|
}
|
|
|
|
/// Cancel the pointer lock center debounce timer
|
|
void _cancelPointerLockCenterDebounceTimer() {
|
|
_pointerLockCenterDebounceTimer?.cancel();
|
|
_pointerLockCenterDebounceTimer = null;
|
|
}
|
|
|
|
bool get _isSelectedTab {
|
|
final controller = widget.tabController;
|
|
if (controller == null) return true;
|
|
final tabState = controller.state.value;
|
|
final selected = tabState.selected;
|
|
return selected >= 0 &&
|
|
selected < tabState.tabs.length &&
|
|
tabState.tabs[selected].key == widget.id;
|
|
}
|
|
|
|
// Every Windows requestFocus() must pass this, or a blocking dialog or an
|
|
// inactive tab could hand remote input to this page.
|
|
bool get _windowsCanFocusRemoteInput =>
|
|
_isSelectedTab && _blockableOverlayState.middleBlocked.isFalse;
|
|
|
|
bool get _isMacOSKeyboardContextActive {
|
|
return stateGlobal.isFocused.value && !_isWindowBlur && _isSelectedTab;
|
|
}
|
|
|
|
void _onMacOSTabStateChanged(DesktopTabState _) {
|
|
if (!_isSelectedTab) {
|
|
_macOSFullScreenFocusRecovery.cancel();
|
|
_syncMacOSKeyboardGrab();
|
|
return;
|
|
}
|
|
// Tab listeners run synchronously. Defer the selected page so the previous
|
|
// page releases first; a late leave from it can disable the new session.
|
|
scheduleMicrotask(() {
|
|
if (mounted) {
|
|
_syncMacOSKeyboardGrab(reassert: true);
|
|
}
|
|
});
|
|
}
|
|
|
|
void _releaseMacOSRemoteInput() {
|
|
_macOSFullScreenFocusRecovery.cancel();
|
|
_macOSExplicitFocusRequestPending = false;
|
|
_macOSInputSuppressed = true;
|
|
_macOSLocalFocusLost = true;
|
|
_ffi.inputModel.enterOrLeave(false);
|
|
_macOSInputActive = false;
|
|
_rawKeyFocusNode.unfocus();
|
|
}
|
|
|
|
void _onMacOSFocusChange() {
|
|
// requestFocus() notifies later; only a recorded explicit request may clear
|
|
// the local-focus-loss latch.
|
|
if (_rawKeyFocusNode.hasPrimaryFocus) {
|
|
final explicitRequest = _macOSExplicitFocusRequestPending;
|
|
_macOSExplicitFocusRequestPending = false;
|
|
if (explicitRequest && _isMacOSKeyboardContextActive) {
|
|
_macOSLocalFocusLost = false;
|
|
}
|
|
_syncMacOSKeyboardGrab(allowInactiveLifecycle: explicitRequest);
|
|
} else {
|
|
if (_macOSInputActive) {
|
|
_ffi.inputModel.enterOrLeave(false);
|
|
_macOSInputActive = false;
|
|
}
|
|
if (_isMacOSKeyboardContextActive) {
|
|
_macOSLocalFocusLost = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 1. Sync the keyboard grab state with the current context.
|
|
// 2. Call enterOrLeave() to update the input state in the FFI layer.
|
|
// 3. Request or unfocus the raw key focus node based on the current context.
|
|
// Flutter focus and native input are separate; native input activates only
|
|
// after the FocusNode has primary focus.
|
|
void _syncMacOSKeyboardGrab({
|
|
bool reassert = false,
|
|
bool allowInactiveLifecycle = false,
|
|
}) {
|
|
if (!isMacOS) return;
|
|
// A secondary engine may stay hidden while its window is visible, so
|
|
// explicit pointer/fullscreen recovery must bypass the global lifecycle.
|
|
final lifecycleAllowsInput = allowInactiveLifecycle ||
|
|
_macOSLifecycleState == null ||
|
|
_macOSLifecycleState == AppLifecycleState.resumed;
|
|
// Input stays pointer-gated except for focused fullscreen recovery, which
|
|
// compensates when macOS omits PointerEnter during a Space switch.
|
|
final shouldFocus = lifecycleAllowsInput &&
|
|
_isMacOSKeyboardContextActive &&
|
|
!_macOSInputSuppressed &&
|
|
_blockableOverlayState.middleBlocked.isFalse &&
|
|
_cursorOverImage.value &&
|
|
!_macOSLocalFocusLost;
|
|
final hasFocus = _rawKeyFocusNode.hasPrimaryFocus;
|
|
final shouldActivateInput = shouldFocus && hasFocus;
|
|
|
|
if (shouldActivateInput != _macOSInputActive ||
|
|
(shouldActivateInput && reassert)) {
|
|
_ffi.inputModel.enterOrLeave(shouldActivateInput);
|
|
}
|
|
_macOSInputActive = shouldActivateInput;
|
|
|
|
if (!shouldFocus) {
|
|
_macOSExplicitFocusRequestPending = false;
|
|
if (hasFocus) _rawKeyFocusNode.unfocus();
|
|
} else if (!hasFocus) {
|
|
_macOSExplicitFocusRequestPending = allowInactiveLifecycle;
|
|
_rawKeyFocusNode.requestFocus();
|
|
} else {
|
|
_macOSExplicitFocusRequestPending = false;
|
|
}
|
|
}
|
|
|
|
void _restoreMacOSKeyboardAfterFullScreen({
|
|
required int generation,
|
|
bool allowHiddenLifecycle = false,
|
|
}) {
|
|
// Fullscreen callbacks preserve recovery while hidden. Native window focus
|
|
// may bypass a stale hidden lifecycle for the newly visible Space.
|
|
if (!_macOSFullScreenFocusRecovery.isCurrent(generation) ||
|
|
(!allowHiddenLifecycle &&
|
|
_macOSLifecycleState == AppLifecycleState.hidden)) {
|
|
return;
|
|
}
|
|
final contextActive =
|
|
stateGlobal.isFocused.value && !_isWindowBlur && _isSelectedTab;
|
|
// macOS can focus a fullscreen Space without sending PointerEnter. Native
|
|
// window focus is authoritative here; a later blur cancels this generation
|
|
// before an off-screen window can restore input.
|
|
final shouldInferPointerInside = !_cursorOverImage.value &&
|
|
allowHiddenLifecycle &&
|
|
stateGlobal.fullscreen.isTrue &&
|
|
contextActive;
|
|
final canRestore = contextActive &&
|
|
_blockableOverlayState.middleBlocked.isFalse &&
|
|
(_cursorOverImage.value || shouldInferPointerInside);
|
|
if (!_macOSFullScreenFocusRecovery.consume(generation)) return;
|
|
if (!canRestore) {
|
|
// Consuming recovery here requires a later pointer/window/tab event.
|
|
return;
|
|
}
|
|
if (shouldInferPointerInside) {
|
|
_cursorOverImage.value = true;
|
|
}
|
|
_macOSLocalFocusLost = false;
|
|
stateGlobal.getInputSource(force: true);
|
|
_syncMacOSKeyboardGrab(reassert: true, allowInactiveLifecycle: true);
|
|
}
|
|
|
|
void _scheduleMacOSKeyboardAfterFullScreen({
|
|
required int generation,
|
|
bool allowHiddenLifecycle = false,
|
|
}) {
|
|
// Fullscreen can deliver FocusNode loss after its callback; wait for frame
|
|
// completion and then advance one event-loop turn before restoring.
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
Timer.run(() {
|
|
if (mounted) {
|
|
_restoreMacOSKeyboardAfterFullScreen(
|
|
generation: generation,
|
|
allowHiddenLifecycle: allowHiddenLifecycle,
|
|
);
|
|
}
|
|
});
|
|
});
|
|
WidgetsBinding.instance.ensureVisualUpdate();
|
|
}
|
|
|
|
void _queueMacOSKeyboardAfterFullScreen({
|
|
bool allowHiddenLifecycle = false,
|
|
}) {
|
|
final generation = _macOSFullScreenFocusRecovery.queue();
|
|
if (_macOSLifecycleState == AppLifecycleState.paused ||
|
|
_macOSLifecycleState == AppLifecycleState.detached) {
|
|
_macOSFullScreenFocusRecovery.cancel();
|
|
return;
|
|
}
|
|
_scheduleMacOSKeyboardAfterFullScreen(
|
|
generation: generation,
|
|
allowHiddenLifecycle: allowHiddenLifecycle,
|
|
);
|
|
}
|
|
|
|
@override
|
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
|
super.didChangeAppLifecycleState(state);
|
|
if (!isMacOS || _macOSLifecycleState == state) return;
|
|
_macOSLifecycleState = state;
|
|
if (state == AppLifecycleState.resumed) {
|
|
_syncMacOSKeyboardGrab(reassert: true);
|
|
} else if (_macOSInputActive) {
|
|
_ffi.inputModel.enterOrLeave(false);
|
|
_macOSInputActive = false;
|
|
}
|
|
|
|
final generation = _macOSFullScreenFocusRecovery.pendingGeneration;
|
|
if (generation == null) return;
|
|
if (state == AppLifecycleState.inactive ||
|
|
state == AppLifecycleState.resumed) {
|
|
_scheduleMacOSKeyboardAfterFullScreen(generation: generation);
|
|
} else if (state == AppLifecycleState.paused ||
|
|
state == AppLifecycleState.detached) {
|
|
_macOSFullScreenFocusRecovery.cancel();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void onWindowBlur() {
|
|
super.onWindowBlur();
|
|
// On windows, we use `focus` way to handle keyboard better.
|
|
// Now on Linux, there's some rdev issues which will break the input.
|
|
// We disable the `focus` way for Linux temporarily.
|
|
if (isWindows || isMacOS) {
|
|
_isWindowBlur = true;
|
|
}
|
|
if (isMacOS) {
|
|
_macOSFullScreenFocusRecovery.cancel();
|
|
// A blur or Space switch may not emit PointerExit, so cursor state alone
|
|
// cannot prevent the old remote surface from reclaiming the keyboard.
|
|
_macOSLocalFocusLost = true;
|
|
}
|
|
if (isWindows) {
|
|
// unfocus the primary-focus when the whole window is lost focus,
|
|
// and let OS to handle events instead.
|
|
_rawKeyFocusNode.unfocus();
|
|
}
|
|
stateGlobal.isFocused.value = false;
|
|
_syncMacOSKeyboardGrab();
|
|
|
|
// When window loses focus, temporarily release relative mouse mode constraints
|
|
// to allow user to interact with other applications normally.
|
|
// The cursor will be re-hidden and re-centered when window regains focus.
|
|
if (_ffi.inputModel.relativeMouseMode.value) {
|
|
_ffi.inputModel.onWindowBlur();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void onWindowFocus() {
|
|
super.onWindowFocus();
|
|
// See [onWindowBlur].
|
|
if (isWindows || isMacOS) {
|
|
_isWindowBlur = false;
|
|
}
|
|
if (isMacOS) stateGlobal.getInputSource(force: true);
|
|
stateGlobal.isFocused.value = true;
|
|
|
|
// Normal macOS windows wait for PointerEnter or PointerDown. A focused
|
|
// fullscreen Space queues delayed recovery; if this window blurs again, the
|
|
// pending recovery is cancelled before native input can reactivate.
|
|
// Regression: switch directly between fullscreen remote Spaces without
|
|
// moving or clicking; only the newly focused session may receive input.
|
|
if (isMacOS &&
|
|
stateGlobal.fullscreen.isTrue &&
|
|
!_ffi.inputModel.relativeMouseMode.value) {
|
|
// Native window focus is authoritative when a secondary engine retains a
|
|
// stale hidden lifecycle state after its fullscreen Space becomes visible.
|
|
_queueMacOSKeyboardAfterFullScreen(allowHiddenLifecycle: true);
|
|
}
|
|
|
|
// Refocus without PointerEnter: the cursor already hovers the image when
|
|
// focus returns (Alt+Tab, taskbar), so enterView() never fires again.
|
|
if (isWindows &&
|
|
_cursorOverImage.value &&
|
|
_windowsCanFocusRemoteInput &&
|
|
!_rawKeyFocusNode.hasFocus) {
|
|
_rawKeyFocusNode.requestFocus();
|
|
}
|
|
|
|
// Restore relative mouse mode constraints when window regains focus.
|
|
if (_ffi.inputModel.relativeMouseMode.value) {
|
|
if (isMacOS) {
|
|
// Native relative mode retains pointer capture and does not emit
|
|
// PointerEnter after window focus returns. Restore both latches unless
|
|
// a local overlay still owns input.
|
|
if (_blockableOverlayState.middleBlocked.isFalse) {
|
|
_cursorOverImage.value = true;
|
|
_macOSLocalFocusLost = false;
|
|
}
|
|
} else if (!isWindows || _windowsCanFocusRemoteInput) {
|
|
_rawKeyFocusNode.requestFocus();
|
|
}
|
|
_ffi.inputModel.onWindowFocus();
|
|
}
|
|
_syncMacOSKeyboardGrab(reassert: true, allowInactiveLifecycle: true);
|
|
}
|
|
|
|
@override
|
|
void onWindowRestore() {
|
|
super.onWindowRestore();
|
|
// On windows, we use `onWindowRestore` way to handle window restore from
|
|
// a minimized state.
|
|
if (isWindows) {
|
|
_isWindowBlur = false;
|
|
}
|
|
WakelockManager.enable(_uniqueKey);
|
|
// Update pointer lock center when window is restored
|
|
_updatePointerLockCenterIfNeeded();
|
|
}
|
|
|
|
// When the window is unminimized, onWindowMaximize or onWindowRestore can be called when the old state was maximized or not.
|
|
@override
|
|
void onWindowMaximize() {
|
|
super.onWindowMaximize();
|
|
WakelockManager.enable(_uniqueKey);
|
|
// Update pointer lock center when window is maximized
|
|
_updatePointerLockCenterIfNeeded();
|
|
}
|
|
|
|
@override
|
|
void onWindowResize() {
|
|
super.onWindowResize();
|
|
// Update pointer lock center when window is resized
|
|
_updatePointerLockCenterIfNeeded();
|
|
}
|
|
|
|
@override
|
|
void onWindowMove() {
|
|
super.onWindowMove();
|
|
// Update pointer lock center when window is moved
|
|
_updatePointerLockCenterIfNeeded();
|
|
}
|
|
|
|
/// Update pointer lock center with debouncing to avoid excessive updates
|
|
/// during rapid window move/resize events.
|
|
void _updatePointerLockCenterIfNeeded() {
|
|
if (!_ffi.inputModel.relativeMouseMode.value) return;
|
|
|
|
// Cancel any pending update and schedule a new one (debounce pattern)
|
|
_pointerLockCenterDebounceTimer?.cancel();
|
|
_pointerLockCenterDebounceTimer = Timer(
|
|
const Duration(milliseconds: kDefaultPointerLockCenterThrottleMs),
|
|
() {
|
|
if (!mounted) return;
|
|
if (_ffi.inputModel.relativeMouseMode.value) {
|
|
_ffi.inputModel.updatePointerLockCenter();
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
@override
|
|
void onWindowMinimize() {
|
|
super.onWindowMinimize();
|
|
WakelockManager.disable(_uniqueKey);
|
|
if (isMacOS) {
|
|
_macOSFullScreenFocusRecovery.cancel();
|
|
_isWindowBlur = true;
|
|
_cursorOverImage.value = false;
|
|
stateGlobal.isFocused.value = false;
|
|
_syncMacOSKeyboardGrab();
|
|
}
|
|
// Release cursor constraints when minimized
|
|
if (_ffi.inputModel.relativeMouseMode.value) {
|
|
_ffi.inputModel.onWindowBlur();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void onWindowEnterFullScreen() {
|
|
super.onWindowEnterFullScreen();
|
|
if (isMacOS) {
|
|
stateGlobal.setFullscreen(true);
|
|
_queueMacOSKeyboardAfterFullScreen();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void onWindowLeaveFullScreen() {
|
|
super.onWindowLeaveFullScreen();
|
|
if (isMacOS) {
|
|
stateGlobal.setFullscreen(false);
|
|
_queueMacOSKeyboardAfterFullScreen();
|
|
}
|
|
}
|
|
|
|
@override
|
|
Future<void> dispose() async {
|
|
final closeSession = closeSessionOnDispose.remove(widget.id) ?? true;
|
|
|
|
// https://github.com/flutter/flutter/issues/64935
|
|
if (isMacOS) {
|
|
// Tab moves release before transfer to avoid a late retained-session leave.
|
|
if (closeSession) {
|
|
_releaseMacOSRemoteInput();
|
|
}
|
|
_tabStateSubscription?.cancel();
|
|
WidgetsBinding.instance.removeObserver(this);
|
|
}
|
|
super.dispose();
|
|
debugPrint("REMOTE PAGE dispose session $sessionId ${widget.id}");
|
|
|
|
// Defensive cleanup: ensure host system-key propagation is reset even if
|
|
// MouseRegion.onExit never fired (e.g., tab closed while cursor inside).
|
|
if (!isWeb) bind.hostStopSystemKeyPropagate(stopped: true);
|
|
|
|
_pointerLockCenterDebounceTimer?.cancel();
|
|
_pointerLockCenterDebounceTimer = null;
|
|
_waylandKeyboardModeWorker?.dispose();
|
|
// Clear callback reference to prevent memory leaks and stale references
|
|
_ffi.inputModel.onRelativeMouseModeDisabled = null;
|
|
// Relative mouse mode cleanup is centralized in FFI.close(closeSession: ...).
|
|
_ffi.textureModel.onRemotePageDispose(closeSession);
|
|
if (closeSession && !isMacOS) {
|
|
// ensure we leave this session, this is a double check
|
|
// enterOrLeave() is already called previously in _releaseMacOSRemoteInput() for macOS.
|
|
_ffi.inputModel.enterOrLeave(false);
|
|
}
|
|
DesktopMultiWindow.removeListener(this);
|
|
_ffi.dialogManager.hideMobileActionsOverlay();
|
|
_ffi.imageModel.disposeImage();
|
|
_ffi.cursorModel.disposeImages();
|
|
_rawKeyFocusNode.dispose();
|
|
if (closeSession) {
|
|
clearWaylandKeyboardPromptSuppressedForConnection(sessionId.toString());
|
|
}
|
|
await _ffi.close(closeSession: closeSession);
|
|
_timer?.cancel();
|
|
_ffi.dialogManager.dismissAll();
|
|
if (closeSession) {
|
|
await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
|
|
overlays: SystemUiOverlay.values);
|
|
}
|
|
WakelockManager.disable(_uniqueKey);
|
|
await Get.delete<FFI>(tag: widget.id);
|
|
removeSharedStates(widget.id);
|
|
}
|
|
|
|
Widget emptyOverlay() => BlockableOverlay(
|
|
/// the Overlay key will be set with _blockableOverlayState in BlockableOverlay
|
|
/// see override build() in [BlockableOverlay]
|
|
state: _blockableOverlayState,
|
|
underlying: Container(
|
|
color: Colors.transparent,
|
|
),
|
|
);
|
|
|
|
Widget buildBody(BuildContext context) {
|
|
remoteToolbar(BuildContext context) => RemoteToolbar(
|
|
id: widget.id,
|
|
ffi: _ffi,
|
|
state: widget.toolbarState,
|
|
onEnterOrLeaveImageSetter: (id, func) {
|
|
_instanceIdOnEnterOrLeaveImage4Toolbar = id;
|
|
_onEnterOrLeaveImage4Toolbar = func;
|
|
},
|
|
onEnterOrLeaveImageCleaner: (id) {
|
|
// If _instanceIdOnEnterOrLeaveImage4Toolbar != id
|
|
// it means `_onEnterOrLeaveImage4Toolbar` is not set or it has been changed to another toolbar.
|
|
if (_instanceIdOnEnterOrLeaveImage4Toolbar == id) {
|
|
_instanceIdOnEnterOrLeaveImage4Toolbar = null;
|
|
_onEnterOrLeaveImage4Toolbar = null;
|
|
}
|
|
},
|
|
setRemoteState: setState,
|
|
);
|
|
|
|
bodyWidget() {
|
|
return Stack(
|
|
children: [
|
|
Container(
|
|
color: kColorCanvas,
|
|
child: RawKeyFocusScope(
|
|
focusNode: _rawKeyFocusNode,
|
|
onFocusChange: (bool imageFocused) {
|
|
debugPrint(
|
|
"onFocusChange(window active:${!_isWindowBlur}) $imageFocused");
|
|
// See [onWindowBlur].
|
|
if (isWindows) {
|
|
if (_isWindowBlur) {
|
|
imageFocused = false;
|
|
Future.delayed(Duration.zero, () {
|
|
_rawKeyFocusNode.unfocus();
|
|
});
|
|
}
|
|
if (imageFocused) {
|
|
_ffi.inputModel.enterOrLeave(true);
|
|
} else {
|
|
_ffi.inputModel.enterOrLeave(false);
|
|
}
|
|
} else if (isMacOS) {
|
|
_onMacOSFocusChange();
|
|
}
|
|
},
|
|
inputModel: _ffi.inputModel,
|
|
child: getBodyForDesktop(context))),
|
|
Stack(
|
|
children: [
|
|
_ffi.ffiModel.pi.isSet.isTrue &&
|
|
_ffi.ffiModel.waitForFirstImage.isTrue
|
|
? emptyOverlay()
|
|
: () {
|
|
if (!_ffi.ffiModel.isPeerAndroid) {
|
|
return Offstage();
|
|
} else {
|
|
return Obx(() => Offstage(
|
|
offstage: _ffi.dialogManager
|
|
.mobileActionsOverlayVisible.isFalse,
|
|
child: Overlay(initialEntries: [
|
|
makeMobileActionsOverlayEntry(
|
|
() => _ffi.dialogManager
|
|
.setMobileActionsOverlayVisible(false),
|
|
ffi: _ffi,
|
|
)
|
|
]),
|
|
));
|
|
}
|
|
}(),
|
|
// Use Overlay to enable rebuild every time on menu button click.
|
|
// Hide toolbar when relative mouse mode is active to prevent
|
|
// cursor from escaping to toolbar area.
|
|
Obx(() => _ffi.inputModel.relativeMouseMode.value
|
|
? const Offstage()
|
|
: _ffi.ffiModel.pi.isSet.isTrue
|
|
? Overlay(initialEntries: [
|
|
OverlayEntry(builder: remoteToolbar)
|
|
])
|
|
: remoteToolbar(context)),
|
|
_ffi.ffiModel.pi.isSet.isFalse ? emptyOverlay() : Offstage(),
|
|
],
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
return Scaffold(
|
|
backgroundColor: Theme.of(context).colorScheme.background,
|
|
body: Obx(() {
|
|
final imageReady = _ffi.ffiModel.pi.isSet.isTrue &&
|
|
_ffi.ffiModel.waitForFirstImage.isFalse;
|
|
if (imageReady) {
|
|
// If the privacy mode(disable physical displays) is switched,
|
|
// we should not dismiss the dialog immediately.
|
|
if (DateTime.now().difference(togglePrivacyModeTime) >
|
|
const Duration(milliseconds: 3000)) {
|
|
// `dismissAll()` is to ensure that the state is clean.
|
|
// It's ok to call dismissAll() here.
|
|
_ffi.dialogManager.dismissAll();
|
|
// Recreate the block state to refresh the state.
|
|
_blockableOverlayState = BlockableOverlayState();
|
|
_blockableOverlayState.applyFfi(_ffi);
|
|
}
|
|
// Block the whole `bodyWidget()` when dialog shows.
|
|
return BlockableOverlay(
|
|
underlying: bodyWidget(),
|
|
state: _blockableOverlayState,
|
|
);
|
|
} else {
|
|
// `_blockableOverlayState` is not recreated here.
|
|
// The toolbar's block state won't work properly when reconnecting, but that's okay.
|
|
return bodyWidget();
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
super.build(context);
|
|
return WillPopScope(
|
|
onWillPop: () async {
|
|
clientClose(sessionId, _ffi);
|
|
return false;
|
|
},
|
|
child: MultiProvider(providers: [
|
|
ChangeNotifierProvider.value(value: _ffi.ffiModel),
|
|
ChangeNotifierProvider.value(value: _ffi.imageModel),
|
|
ChangeNotifierProvider.value(value: _ffi.cursorModel),
|
|
ChangeNotifierProvider.value(value: _ffi.canvasModel),
|
|
ChangeNotifierProvider.value(value: _ffi.recordingModel),
|
|
], child: buildBody(context)));
|
|
}
|
|
|
|
void enterView(PointerEnterEvent evt) {
|
|
_ffi.canvasModel.rearmEdgeScroll();
|
|
|
|
_cursorOverImage.value = true;
|
|
_firstEnterImage.value = true;
|
|
if (_onEnterOrLeaveImage4Toolbar != null) {
|
|
try {
|
|
_onEnterOrLeaveImage4Toolbar!(true);
|
|
} catch (e) {
|
|
//
|
|
}
|
|
}
|
|
|
|
// See [onWindowBlur].
|
|
if (isMacOS) {
|
|
_macOSLocalFocusLost = false;
|
|
stateGlobal.getInputSource(force: true);
|
|
_syncMacOSKeyboardGrab(reassert: true, allowInactiveLifecycle: true);
|
|
} else if (isWindows) {
|
|
// Blur unfocuses this node and nothing restores it, so the keyboard stayed
|
|
// dead until a click. Focus only while the window is really active, or a
|
|
// background window would grab system keys. onFocusChange does enterOrLeave.
|
|
if (!_isWindowBlur &&
|
|
_windowsCanFocusRemoteInput &&
|
|
!_rawKeyFocusNode.hasFocus) {
|
|
_rawKeyFocusNode.requestFocus();
|
|
}
|
|
} else {
|
|
if (!_rawKeyFocusNode.hasFocus) {
|
|
_rawKeyFocusNode.requestFocus();
|
|
}
|
|
_ffi.inputModel.enterOrLeave(true);
|
|
}
|
|
}
|
|
|
|
void leaveView(PointerExitEvent evt) {
|
|
_ffi.canvasModel.disableEdgeScroll();
|
|
|
|
if (_ffi.ffiModel.keyboard) {
|
|
_ffi.inputModel.tryMoveEdgeOnExit(evt.position);
|
|
}
|
|
|
|
_cursorOverImage.value = false;
|
|
_firstEnterImage.value = false;
|
|
if (_onEnterOrLeaveImage4Toolbar != null) {
|
|
try {
|
|
_onEnterOrLeaveImage4Toolbar!(false);
|
|
} catch (e) {
|
|
//
|
|
}
|
|
}
|
|
|
|
// See [onWindowBlur].
|
|
if (isMacOS) {
|
|
_syncMacOSKeyboardGrab();
|
|
} else if (!isWindows) {
|
|
_ffi.inputModel.enterOrLeave(false);
|
|
}
|
|
}
|
|
|
|
Widget _buildRawTouchAndPointerRegion(
|
|
Widget child,
|
|
PointerEnterEventListener? onEnter,
|
|
PointerExitEventListener? onExit,
|
|
) {
|
|
return RawTouchGestureDetectorRegion(
|
|
child: _buildRawPointerMouseRegion(child, onEnter, onExit),
|
|
ffi: _ffi,
|
|
);
|
|
}
|
|
|
|
Widget _buildRawPointerMouseRegion(
|
|
Widget child,
|
|
PointerEnterEventListener? onEnter,
|
|
PointerExitEventListener? onExit,
|
|
) {
|
|
return RawPointerMouseRegion(
|
|
onEnter: onEnter,
|
|
onExit: onExit,
|
|
onPointerDown: (event) {
|
|
// A double check for blur status on Windows and macOS.
|
|
// Note: If there's an `onPointerDown` event is triggered, `_isWindowBlur` is expected being false.
|
|
// Sometimes the system does not send the necessary focus event to flutter. We should manually
|
|
// handle this inconsistent status by setting `_isWindowBlur` to false. So we can
|
|
// ensure the grab-key thread is running when our users are clicking the remote canvas.
|
|
if ((isWindows || isMacOS) && _isWindowBlur) {
|
|
debugPrint(
|
|
"Unexpected status: onPointerDown is triggered while the remote window is in blur status");
|
|
_isWindowBlur = false;
|
|
}
|
|
if (isMacOS) {
|
|
// Regions without matching enter/exit callbacks cannot safely own
|
|
// keyboard state.
|
|
if (onEnter == null || onExit == null) return;
|
|
if (!stateGlobal.isFocused.value) {
|
|
stateGlobal.isFocused.value = true;
|
|
}
|
|
_cursorOverImage.value = true;
|
|
_macOSLocalFocusLost = false;
|
|
stateGlobal.getInputSource(force: true);
|
|
_syncMacOSKeyboardGrab(
|
|
reassert: !isInputSourceFlutter, allowInactiveLifecycle: true);
|
|
} else if (!_rawKeyFocusNode.hasFocus) {
|
|
_rawKeyFocusNode.requestFocus();
|
|
}
|
|
},
|
|
inputModel: _ffi.inputModel,
|
|
child: child,
|
|
);
|
|
}
|
|
|
|
Widget getBodyForDesktop(BuildContext context) {
|
|
var paints = <Widget>[
|
|
MouseRegion(
|
|
onEnter: (evt) {
|
|
if (!isWeb) bind.hostStopSystemKeyPropagate(stopped: false);
|
|
},
|
|
onExit: (evt) {
|
|
if (!isWeb) bind.hostStopSystemKeyPropagate(stopped: true);
|
|
},
|
|
child: _ViewStyleUpdater(
|
|
canvasModel: _ffi.canvasModel,
|
|
inputModel: _ffi.inputModel,
|
|
child: Builder(builder: (context) {
|
|
final peerDisplay = CurrentDisplayState.find(widget.id);
|
|
return Obx(
|
|
() => _ffi.ffiModel.pi.isSet.isFalse
|
|
? Container(color: Colors.transparent)
|
|
: Obx(() {
|
|
_ffi.textureModel.updateCurrentDisplay(peerDisplay.value);
|
|
return ImagePaint(
|
|
id: widget.id,
|
|
zoomCursor: _zoomCursor,
|
|
cursorOverImage: _cursorOverImage,
|
|
keyboardEnabled: _keyboardEnabled,
|
|
remoteCursorMoved: _remoteCursorMoved,
|
|
listenerBuilder: (child) =>
|
|
_buildRawTouchAndPointerRegion(
|
|
child, enterView, leaveView),
|
|
ffi: _ffi,
|
|
);
|
|
}),
|
|
);
|
|
}),
|
|
),
|
|
)
|
|
];
|
|
|
|
if (!_ffi.canvasModel.cursorEmbedded) {
|
|
paints
|
|
.add(Obx(() => _showRemoteCursor.isFalse || _remoteCursorMoved.isFalse
|
|
? Offstage()
|
|
: CursorPaint(
|
|
id: widget.id,
|
|
zoomCursor: _zoomCursor,
|
|
)));
|
|
}
|
|
paints.add(
|
|
Positioned(
|
|
top: 10,
|
|
right: 10,
|
|
child: _buildRawTouchAndPointerRegion(
|
|
QualityMonitor(_ffi.qualityMonitorModel), null, null),
|
|
),
|
|
);
|
|
return Stack(
|
|
children: paints,
|
|
);
|
|
}
|
|
|
|
@override
|
|
bool get wantKeepAlive => true;
|
|
}
|
|
|
|
/// Tracks view size and DPR to update CanvasModel.updateViewStyle()
|
|
/// and InputModel.updateImageWidgetSize() only when either changes.
|
|
/// This avoids scheduling post-frame callbacks on every LayoutBuilder rebuild.
|
|
class _ViewStyleUpdater extends StatefulWidget {
|
|
final CanvasModel canvasModel;
|
|
final InputModel inputModel;
|
|
final Widget child;
|
|
|
|
const _ViewStyleUpdater({
|
|
Key? key,
|
|
required this.canvasModel,
|
|
required this.inputModel,
|
|
required this.child,
|
|
}) : super(key: key);
|
|
|
|
@override
|
|
State<_ViewStyleUpdater> createState() => _ViewStyleUpdaterState();
|
|
}
|
|
|
|
class _ViewStyleUpdaterState extends State<_ViewStyleUpdater> {
|
|
Size? _lastSize;
|
|
double? _lastDevicePixelRatio;
|
|
bool _callbackScheduled = false;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
|
|
return LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
final maxWidth = constraints.maxWidth;
|
|
final maxHeight = constraints.maxHeight;
|
|
// Guard against infinite constraints (e.g., unconstrained ancestor).
|
|
if (!maxWidth.isFinite || !maxHeight.isFinite) {
|
|
return widget.child;
|
|
}
|
|
final newSize = Size(maxWidth, maxHeight);
|
|
if (_lastSize != newSize || _lastDevicePixelRatio != devicePixelRatio) {
|
|
_lastSize = newSize;
|
|
_lastDevicePixelRatio = devicePixelRatio;
|
|
// Schedule the update for after the current frame to avoid setState during build.
|
|
// Use _callbackScheduled flag to prevent accumulating multiple callbacks
|
|
// when size changes rapidly before any callback executes.
|
|
if (!_callbackScheduled) {
|
|
_callbackScheduled = true;
|
|
SchedulerBinding.instance.addPostFrameCallback((_) {
|
|
_callbackScheduled = false;
|
|
final currentSize = _lastSize;
|
|
if (mounted && currentSize != null) {
|
|
widget.canvasModel.updateViewStyle();
|
|
widget.inputModel.updateImageWidgetSize(currentSize);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
return widget.child;
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
class ImagePaint extends StatefulWidget {
|
|
final FFI ffi;
|
|
final String id;
|
|
final RxBool zoomCursor;
|
|
final RxBool cursorOverImage;
|
|
final RxBool keyboardEnabled;
|
|
final RxBool remoteCursorMoved;
|
|
final Widget Function(Widget)? listenerBuilder;
|
|
|
|
ImagePaint(
|
|
{Key? key,
|
|
required this.ffi,
|
|
required this.id,
|
|
required this.zoomCursor,
|
|
required this.cursorOverImage,
|
|
required this.keyboardEnabled,
|
|
required this.remoteCursorMoved,
|
|
this.listenerBuilder})
|
|
: super(key: key);
|
|
|
|
@override
|
|
State<StatefulWidget> createState() => _ImagePaintState();
|
|
}
|
|
|
|
class _ImagePaintState extends State<ImagePaint> {
|
|
bool _lastRemoteCursorMoved = false;
|
|
final _cursorDisplayScale = 1.0.obs;
|
|
|
|
String get id => widget.id;
|
|
RxBool get zoomCursor => widget.zoomCursor;
|
|
RxBool get cursorOverImage => widget.cursorOverImage;
|
|
RxBool get keyboardEnabled => widget.keyboardEnabled;
|
|
RxBool get remoteCursorMoved => widget.remoteCursorMoved;
|
|
Widget Function(Widget)? get listenerBuilder => widget.listenerBuilder;
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final m = Provider.of<ImageModel>(context);
|
|
var c = Provider.of<CanvasModel>(context);
|
|
final s = c.scale;
|
|
// Read the live DPR while the canvas's post-frame update is pending.
|
|
final dpr = MediaQuery.devicePixelRatioOf(context);
|
|
|
|
bool isViewOriginal() => c.viewStyle.style == kRemoteViewStyleOriginal;
|
|
|
|
mouseRegion({child}) => Obx(() {
|
|
double getCursorScale() {
|
|
var c = Provider.of<CanvasModel>(context);
|
|
if (isDesktop) {
|
|
return _getDesktopCursorScale(c, dpr);
|
|
} else {
|
|
return zoomCursor.value || isViewOriginal() ? s : 1.0;
|
|
}
|
|
}
|
|
|
|
return MouseRegion(
|
|
cursor: cursorOverImage.isTrue
|
|
? c.cursorEmbedded
|
|
? SystemMouseCursors.none
|
|
// Hide cursor when relative mouse mode is active
|
|
: widget.ffi.inputModel.relativeMouseMode.value
|
|
? SystemMouseCursors.none
|
|
: keyboardEnabled.isTrue
|
|
? (() {
|
|
if (remoteCursorMoved.isTrue) {
|
|
_lastRemoteCursorMoved = true;
|
|
return SystemMouseCursors.none;
|
|
} else {
|
|
if (_lastRemoteCursorMoved) {
|
|
_lastRemoteCursorMoved = false;
|
|
_firstEnterImage.value = true;
|
|
}
|
|
return _buildCustomCursor(
|
|
context, getCursorScale());
|
|
}
|
|
}())
|
|
: _buildDisabledCursor(context, getCursorScale())
|
|
: MouseCursor.defer,
|
|
onHover: (evt) {},
|
|
child: child);
|
|
});
|
|
if (c.imageOverflow.isTrue && c.scrollStyle != ScrollStyle.scrollauto) {
|
|
final paintWidth = c.getDisplayWidth() * s;
|
|
final paintHeight = c.getDisplayHeight() * s;
|
|
final paintSize = Size(paintWidth, paintHeight);
|
|
final paintWidget =
|
|
m.useTextureRender || widget.ffi.ffiModel.pi.forceTextureRender
|
|
? _BuildPaintTextureRender(
|
|
c, s, Offset.zero, paintSize, isViewOriginal())
|
|
: _buildScrollbarNonTextureRender(m, paintSize, s);
|
|
return NotificationListener<ScrollNotification>(
|
|
onNotification: (notification) {
|
|
c.updateScrollPercent();
|
|
return false;
|
|
},
|
|
child: mouseRegion(
|
|
child: Obx(() => _buildCrossScrollbarFromLayout(
|
|
context,
|
|
_buildListener(paintWidget),
|
|
c.size,
|
|
paintSize,
|
|
c.scrollHorizontal,
|
|
c.scrollVertical,
|
|
)),
|
|
));
|
|
} else {
|
|
if (c.size.width > 0 && c.size.height > 0) {
|
|
final paintWidget =
|
|
m.useTextureRender || widget.ffi.ffiModel.pi.forceTextureRender
|
|
? _BuildPaintTextureRender(
|
|
c,
|
|
s,
|
|
Offset(
|
|
isLinux ? c.x.toInt().toDouble() : c.x,
|
|
isLinux ? c.y.toInt().toDouble() : c.y,
|
|
),
|
|
c.size,
|
|
isViewOriginal())
|
|
: _buildScrollAutoNonTextureRender(m, c, s);
|
|
return mouseRegion(child: _buildListener(paintWidget));
|
|
} else {
|
|
return Container();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Matches desktop cursors to the rendered image and native pixel units.
|
|
///
|
|
/// Windows cursor pixels are physical; NSCursor/GdkCursor use logical pixels.
|
|
/// Unzoomed Adaptive/Custom views preserve macOS cursors' point dimensions.
|
|
double _getDesktopCursorScale(CanvasModel c, double dpr) {
|
|
final peer = widget.ffi.ffiModel;
|
|
if (!zoomCursor.value &&
|
|
peer.pi.platform == kPeerPlatformMacOS &&
|
|
(c.viewStyle.style == kRemoteViewStyleAdaptive ||
|
|
c.viewStyle.style == kRemoteViewStyleCustom)) {
|
|
return isWindows ? dpr : 1.0;
|
|
}
|
|
if (peer.isPeerLinux && peer.pi.currentDisplay == kAllDisplayValue) {
|
|
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
|
|
// Remove the host output's density without applying canvas zoom.
|
|
final scale = 1.0 / _cursorDisplayScale.value;
|
|
return isWindows ? scale : scale / dpr;
|
|
}
|
|
final scale = c.scale / _cursorDisplayScale.value;
|
|
return isWindows ? scale * dpr : scale;
|
|
}
|
|
if (!zoomCursor.value || c.viewStyle.style == kRemoteViewStyleOriginal) {
|
|
// Original and unzoomed views do not apply canvas zoom.
|
|
final scale = _getCursorScaleForDisplay(1.0);
|
|
return isWindows ? scale : scale / dpr;
|
|
}
|
|
final scale = _getCursorScaleForDisplay(c.scale);
|
|
return isWindows ? scale * dpr : scale;
|
|
}
|
|
|
|
double _getCursorScaleForDisplay(double scale) {
|
|
final peer = widget.ffi.ffiModel;
|
|
// All Displays can mix densities; no single display scale applies.
|
|
if (peer.pi.currentDisplay == kAllDisplayValue) return scale;
|
|
final displays = peer.pi.getCurDisplays();
|
|
if (displays.isEmpty) return scale;
|
|
if (peer.pi.platform == kPeerPlatformMacOS) {
|
|
// macOS sends NSImage.size in points (src/platform/macos.rs:640,682),
|
|
// while HiDPI screen frames use backing pixels (libs/scrap/src/quartz/display.rs:37).
|
|
return scale * displays.first.scale;
|
|
}
|
|
if (!peer.isPeerLinux) return scale;
|
|
// Match rendering when a Wayland host
|
|
// with multiple outputs reports a display scale > 1.
|
|
// A single-output host keeps scale at 1.0 to preserve physical uinput
|
|
// coordinates, even with OS scaling enabled. This counts host outputs,
|
|
// not the selected displays.length.
|
|
// See src/server/display_service.rs:650 (update_sync_displays) and
|
|
// src/server/drm_capturer.rs:1523 (DRM's matching convention).
|
|
return scale / displays.first.scale;
|
|
}
|
|
|
|
Widget _buildScrollbarNonTextureRender(
|
|
ImageModel m, Size imageSize, double s) {
|
|
double sizeScale = s;
|
|
if (widget.ffi.ffiModel.isPeerLinux) {
|
|
final displays = widget.ffi.ffiModel.pi.getCurDisplays();
|
|
if (displays.isNotEmpty) {
|
|
sizeScale = s / displays[0].scale;
|
|
}
|
|
}
|
|
return CustomPaint(
|
|
size: imageSize,
|
|
painter: ImagePainter(image: m.image, x: 0, y: 0, scale: sizeScale),
|
|
);
|
|
}
|
|
|
|
Widget _buildScrollAutoNonTextureRender(
|
|
ImageModel m, CanvasModel c, double s) {
|
|
double sizeScale = s;
|
|
if (widget.ffi.ffiModel.isPeerLinux) {
|
|
final displays = widget.ffi.ffiModel.pi.getCurDisplays();
|
|
if (displays.isNotEmpty) {
|
|
sizeScale = s / displays[0].scale;
|
|
}
|
|
}
|
|
return CustomPaint(
|
|
size: Size(c.size.width, c.size.height),
|
|
painter: ImagePainter(
|
|
image: m.image,
|
|
x: c.x / sizeScale,
|
|
y: c.y / sizeScale,
|
|
scale: sizeScale),
|
|
);
|
|
}
|
|
|
|
Widget _BuildPaintTextureRender(
|
|
CanvasModel c, double s, Offset offset, Size size, bool isViewOriginal) {
|
|
final ffiModel = c.parent.target!.ffiModel;
|
|
final displays = ffiModel.pi.getCurDisplays();
|
|
final children = <Widget>[];
|
|
final rect = ffiModel.rect;
|
|
if (rect == null) {
|
|
return Container();
|
|
}
|
|
final isPeerLinux = ffiModel.isPeerLinux;
|
|
final curDisplay = ffiModel.pi.currentDisplay;
|
|
for (var i = 0; i < displays.length; i++) {
|
|
final textureId = widget.ffi.textureModel
|
|
.getTextureId(curDisplay == kAllDisplayValue ? i : curDisplay);
|
|
if (true) {
|
|
// both "textureId.value != -1" and "true" seems ok
|
|
final sizeScale = isPeerLinux ? s / displays[i].scale : s;
|
|
children.add(Positioned(
|
|
left: (displays[i].x - rect.left) * s + offset.dx,
|
|
top: (displays[i].y - rect.top) * s + offset.dy,
|
|
width: displays[i].width * sizeScale,
|
|
height: displays[i].height * sizeScale,
|
|
child: _trackCursorDisplay(
|
|
Obx(() => Texture(
|
|
textureId: textureId.value,
|
|
filterQuality:
|
|
isViewOriginal ? FilterQuality.none : FilterQuality.low,
|
|
)),
|
|
displays[i],
|
|
),
|
|
));
|
|
}
|
|
}
|
|
return SizedBox(
|
|
width: size.width,
|
|
height: size.height,
|
|
child: Stack(children: children),
|
|
);
|
|
}
|
|
|
|
Widget _trackCursorDisplay(Widget child, Display display) {
|
|
final peer = widget.ffi.ffiModel;
|
|
if (!isDesktop ||
|
|
!peer.isPeerLinux ||
|
|
peer.pi.currentDisplay != kAllDisplayValue) {
|
|
return child;
|
|
}
|
|
return MouseRegion(
|
|
onEnter: (_) => _cursorDisplayScale.value = display.scale,
|
|
onHover: (_) => _cursorDisplayScale.value = display.scale,
|
|
child: child,
|
|
);
|
|
}
|
|
|
|
MouseCursor _buildCustomCursor(BuildContext context, double scale) {
|
|
final cursor = Provider.of<CursorModel>(context);
|
|
final cache = cursor.cache ?? preDefaultCursor.cache;
|
|
return buildCursorOfCache(cursor, scale, cache);
|
|
}
|
|
|
|
MouseCursor _buildDisabledCursor(BuildContext context, double scale) {
|
|
final cursor = Provider.of<CursorModel>(context);
|
|
final cache = preForbiddenCursor.cache;
|
|
return buildCursorOfCache(cursor, scale, cache);
|
|
}
|
|
|
|
Widget _buildCrossScrollbarFromLayout(
|
|
BuildContext context,
|
|
Widget child,
|
|
Size layoutSize,
|
|
Size size,
|
|
ScrollController horizontal,
|
|
ScrollController vertical,
|
|
) {
|
|
var widget = child;
|
|
if (layoutSize.width < size.width) {
|
|
widget = ScrollConfiguration(
|
|
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
|
|
child: SingleChildScrollView(
|
|
controller: horizontal,
|
|
scrollDirection: Axis.horizontal,
|
|
physics: cursorOverImage.isTrue
|
|
? const NeverScrollableScrollPhysics()
|
|
: null,
|
|
child: widget,
|
|
),
|
|
);
|
|
} else {
|
|
widget = Row(
|
|
children: [
|
|
Container(
|
|
width: ((layoutSize.width - size.width) ~/ 2).toDouble(),
|
|
),
|
|
widget,
|
|
],
|
|
);
|
|
}
|
|
if (layoutSize.height < size.height) {
|
|
widget = ScrollConfiguration(
|
|
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
|
|
child: SingleChildScrollView(
|
|
controller: vertical,
|
|
physics: cursorOverImage.isTrue
|
|
? const NeverScrollableScrollPhysics()
|
|
: null,
|
|
child: widget,
|
|
),
|
|
);
|
|
} else {
|
|
widget = Column(
|
|
children: [
|
|
Container(
|
|
height: ((layoutSize.height - size.height) ~/ 2).toDouble(),
|
|
),
|
|
widget,
|
|
],
|
|
);
|
|
}
|
|
if (layoutSize.width < size.width) {
|
|
widget = RawScrollbar(
|
|
thickness: kScrollbarThickness,
|
|
thumbColor: Colors.grey,
|
|
controller: horizontal,
|
|
thumbVisibility: false,
|
|
trackVisibility: false,
|
|
notificationPredicate: layoutSize.height < size.height
|
|
? (notification) => notification.depth == 1
|
|
: defaultScrollNotificationPredicate,
|
|
child: widget,
|
|
);
|
|
}
|
|
if (layoutSize.height < size.height) {
|
|
widget = RawScrollbar(
|
|
thickness: kScrollbarThickness,
|
|
thumbColor: Colors.grey,
|
|
controller: vertical,
|
|
thumbVisibility: false,
|
|
trackVisibility: false,
|
|
child: widget,
|
|
);
|
|
}
|
|
|
|
return Container(
|
|
child: widget,
|
|
width: layoutSize.width,
|
|
height: layoutSize.height,
|
|
);
|
|
}
|
|
|
|
Widget _buildListener(Widget child) {
|
|
if (listenerBuilder != null) {
|
|
return listenerBuilder!(child);
|
|
} else {
|
|
return child;
|
|
}
|
|
}
|
|
}
|
|
|
|
class CursorPaint extends StatelessWidget {
|
|
final String id;
|
|
final RxBool zoomCursor;
|
|
|
|
const CursorPaint({
|
|
Key? key,
|
|
required this.id,
|
|
required this.zoomCursor,
|
|
}) : super(key: key);
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final m = Provider.of<CursorModel>(context);
|
|
final c = Provider.of<CanvasModel>(context);
|
|
double hotx = m.hotx;
|
|
double hoty = m.hoty;
|
|
if (m.image == null) {
|
|
if (preDefaultCursor.image != null) {
|
|
hotx = preDefaultCursor.image!.width / 2;
|
|
hoty = preDefaultCursor.image!.height / 2;
|
|
}
|
|
}
|
|
|
|
double cx = c.x;
|
|
double cy = c.y;
|
|
if (c.viewStyle.style == kRemoteViewStyleOriginal &&
|
|
c.scrollStyle == ScrollStyle.scrollbar) {
|
|
final rect = c.parent.target!.ffiModel.rect;
|
|
if (rect == null) {
|
|
// unreachable!
|
|
debugPrint('unreachable! The displays rect is null.');
|
|
return Container();
|
|
}
|
|
if (cx < 0) {
|
|
final imageWidth = rect.width * c.scale;
|
|
cx = -imageWidth * c.scrollX;
|
|
}
|
|
if (cy < 0) {
|
|
final imageHeight = rect.height * c.scale;
|
|
cy = -imageHeight * c.scrollY;
|
|
}
|
|
}
|
|
|
|
double x = (m.x - hotx) * c.scale + cx;
|
|
double y = (m.y - hoty) * c.scale + cy;
|
|
double scale = 1.0;
|
|
final isViewOriginal = c.viewStyle.style == kRemoteViewStyleOriginal;
|
|
if (zoomCursor.value || isViewOriginal) {
|
|
x = m.x - hotx + cx / c.scale;
|
|
y = m.y - hoty + cy / c.scale;
|
|
scale = c.scale;
|
|
}
|
|
|
|
return CustomPaint(
|
|
painter: ImagePainter(
|
|
image: m.image ?? preDefaultCursor.image,
|
|
x: x,
|
|
y: y,
|
|
scale: scale,
|
|
),
|
|
);
|
|
}
|
|
}
|