fix(shortcuts): preserve input state and refresh action availability
This commit is contained in:
@@ -16,6 +16,14 @@ List<Map<String, dynamic>> shortcutBindingMapsFrom(dynamic rawBindings) {
|
||||
final bindings = <Map<String, dynamic>>[];
|
||||
for (final raw in rawBindings) {
|
||||
if (raw is! Map) continue;
|
||||
final mods = raw['mods'];
|
||||
if (raw['action'] is! String ||
|
||||
raw['key'] is! String ||
|
||||
mods is! List ||
|
||||
mods.any((mod) =>
|
||||
!const {'primary', 'ctrl', 'alt', 'shift'}.contains(mod))) {
|
||||
continue;
|
||||
}
|
||||
final binding = <String, dynamic>{};
|
||||
for (final entry in raw.entries) {
|
||||
final key = entry.key;
|
||||
|
||||
@@ -1424,6 +1424,31 @@ List<TToggleMenu> toolbarKeyboardToggles(FFI ffi) {
|
||||
/// `toolbarDisplayToggle`'s `isMobile` branch — calling it explicitly there
|
||||
/// would double-register.
|
||||
void registerToolbarShortcuts(BuildContext context, String id, FFI ffi) {
|
||||
// Rebuild only the triggered action's menu, so permission/capability changes
|
||||
// and temporary disabled states take effect without opening the toolbar.
|
||||
void register(List<String> actions, FutureOr<Object> Function() refresh) {
|
||||
ffi.shortcutModel.registerRefresher(actions, () async {
|
||||
if (!context.mounted || ffi.closed) {
|
||||
ffi.shortcutModel.clear();
|
||||
return;
|
||||
}
|
||||
await refresh();
|
||||
});
|
||||
}
|
||||
|
||||
register([
|
||||
..._kToolbarOwnedActionIds,
|
||||
if (!(isDesktop || isWeb)) kShortcutActionToggleRecording,
|
||||
], () => toolbarControls(context, id, ffi));
|
||||
register(_kToolbarKeyboardToggleActionIds, () => toolbarKeyboardToggles(ffi));
|
||||
register(_kToolbarCursorActionIds, () => toolbarCursor(context, id, ffi));
|
||||
register(_kToolbarDisplayToggleActionIds,
|
||||
() => toolbarDisplayToggle(context, id, ffi));
|
||||
register(_kToolbarViewStyleActionIds, () => toolbarViewStyle(context, id, ffi));
|
||||
register(_kToolbarImageQualityActionIds,
|
||||
() => toolbarImageQuality(context, id, ffi));
|
||||
register(_kToolbarCodecActionIds, () => toolbarCodec(context, id, ffi));
|
||||
|
||||
if (isDesktop) toolbarKeyboardToggles(ffi);
|
||||
unawaited(toolbarCursor(context, id, ffi));
|
||||
unawaited(toolbarDisplayToggle(context, id, ffi));
|
||||
|
||||
@@ -19,6 +19,7 @@ import '../../models/shortcut_model.dart';
|
||||
import '../../models/state_model.dart';
|
||||
import '../common/widgets/keyboard_shortcuts/shortcut_utils.dart';
|
||||
import 'input_modifier_utils.dart';
|
||||
import 'local_flutter_shortcuts.dart';
|
||||
import 'relative_mouse_model.dart';
|
||||
import '../common.dart';
|
||||
import '../consts.dart';
|
||||
@@ -418,6 +419,14 @@ class InputModel {
|
||||
|
||||
final ToReleaseRawKeys toReleaseRawKeys = ToReleaseRawKeys();
|
||||
final ToReleaseKeys toReleaseKeys = ToReleaseKeys();
|
||||
late final _localFlutterShortcuts = LocalFlutterShortcutDispatcher(
|
||||
onTriggered: (action) {
|
||||
final ffi = parent.target;
|
||||
if (ffi != null && !ffi.closed) {
|
||||
ffi.shortcutModel.onTriggered(action);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// trackpad
|
||||
var _trackpadLastDelta = Offset.zero;
|
||||
@@ -738,7 +747,11 @@ class InputModel {
|
||||
}
|
||||
|
||||
KeyEventResult handleRawKeyEvent(RawKeyEvent e) {
|
||||
if (isViewOnly) return KeyEventResult.handled;
|
||||
if (_localFlutterShortcuts.tryDispatchRaw(e)) return KeyEventResult.handled;
|
||||
if (isViewOnly) {
|
||||
_tryDispatchRawFlutterShortcut(e, releaseModifiers: false);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (isViewCamera) return KeyEventResult.handled;
|
||||
if (!isInputSourceFlutter) {
|
||||
if (isDesktop) {
|
||||
@@ -747,6 +760,7 @@ class InputModel {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
}
|
||||
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey, raw: true);
|
||||
|
||||
if (_relativeMouse.handleRawKeyEvent(e)) {
|
||||
return KeyEventResult.handled;
|
||||
@@ -814,8 +828,11 @@ class InputModel {
|
||||
|
||||
// * Currently mobile does not enable map mode
|
||||
if ((isDesktop || isWebDesktop) && keyboardMode == kKeyMapMode) {
|
||||
_restoreRawFlutterShortcutModifiers(e);
|
||||
mapKeyboardModeRaw(e, iosCapsLock);
|
||||
} else {
|
||||
if (_tryDispatchRawFlutterShortcut(e)) return KeyEventResult.handled;
|
||||
_restoreRawFlutterShortcutModifiers(e, mapMode: false);
|
||||
legacyKeyboardModeRaw(e);
|
||||
}
|
||||
|
||||
@@ -823,7 +840,11 @@ class InputModel {
|
||||
}
|
||||
|
||||
KeyEventResult handleKeyEvent(KeyEvent e) {
|
||||
if (isViewOnly) return KeyEventResult.handled;
|
||||
if (_localFlutterShortcuts.tryDispatch(e)) return KeyEventResult.handled;
|
||||
if (isViewOnly) {
|
||||
_tryDispatchFlutterShortcut(e, releaseModifiers: false);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (isViewCamera) return KeyEventResult.handled;
|
||||
if (!isInputSourceFlutter) {
|
||||
if (isDesktop) {
|
||||
@@ -832,7 +853,8 @@ class InputModel {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
}
|
||||
if (_tryDispatchWebFlutterShortcut(e)) {
|
||||
_syncFlutterShortcutModifiersAfterViewOnly(e.physicalKey);
|
||||
if (isWeb && _tryDispatchFlutterShortcut(e)) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (isWindows || isLinux) {
|
||||
@@ -915,6 +937,7 @@ class InputModel {
|
||||
final isDesktopAndMapMode =
|
||||
isDesktop || (isWebDesktop && keyboardMode == kKeyMapMode);
|
||||
if (isMobileAndMapMode || isDesktopAndMapMode) {
|
||||
_restoreFlutterShortcutModifiers(e);
|
||||
// FIXME: e.character is wrong for dead keys, eg: ^ in de
|
||||
newKeyboardMode(
|
||||
e.character ?? '',
|
||||
@@ -923,44 +946,144 @@ class InputModel {
|
||||
e is KeyDownEvent || e is KeyRepeatEvent,
|
||||
iosCapsLock);
|
||||
} else {
|
||||
if (!isWeb && _tryDispatchFlutterShortcut(e)) return KeyEventResult.handled;
|
||||
_restoreFlutterShortcutModifiers(e, mapMode: false);
|
||||
legacyKeyboardMode(e);
|
||||
}
|
||||
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
bool _tryDispatchWebFlutterShortcut(KeyEvent e) {
|
||||
if (!isWeb || !isInputSourceFlutter) return false;
|
||||
if (e is! KeyDownEvent && e is! KeyRepeatEvent) return false;
|
||||
if (!ShortcutModel.isEnabled() || ShortcutModel.isPassThrough()) {
|
||||
return false;
|
||||
}
|
||||
final keyName = shortcutKeyNameForEvent(e);
|
||||
if (keyName == null) return false;
|
||||
final mods = canonicalShortcutModsForSave(_webFlutterShortcutMods());
|
||||
final action = _matchWebFlutterShortcut(keyName, mods);
|
||||
if (action == null) return false;
|
||||
if (e is KeyDownEvent) {
|
||||
parent.target?.shortcutModel.onTriggered(action);
|
||||
}
|
||||
return true;
|
||||
bool _tryDispatchFlutterShortcut(KeyEvent e, {bool releaseModifiers = true}) {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
return _localFlutterShortcuts.tryDispatch(
|
||||
e,
|
||||
viewOnly: isViewOnly,
|
||||
match: () => _matchFlutterShortcut(e.physicalKey,
|
||||
ctrlPressed: keyboard.isControlPressed,
|
||||
altPressed: keyboard.isAltPressed,
|
||||
shiftPressed: keyboard.isShiftPressed,
|
||||
commandPressed: keyboard.isMetaPressed),
|
||||
releaseModifiers:
|
||||
releaseModifiers ? _releaseFlutterShortcutModifiers : null,
|
||||
);
|
||||
}
|
||||
|
||||
Set<String> _webFlutterShortcutMods() {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
final mods = <String>{};
|
||||
bool _tryDispatchRawFlutterShortcut(RawKeyEvent e,
|
||||
{bool releaseModifiers = true}) {
|
||||
return _localFlutterShortcuts.tryDispatchRaw(
|
||||
e,
|
||||
viewOnly: isViewOnly,
|
||||
match: () => _matchFlutterShortcut(e.physicalKey,
|
||||
ctrlPressed: e.isControlPressed,
|
||||
altPressed: e.isAltPressed,
|
||||
shiftPressed: e.isShiftPressed,
|
||||
commandPressed: e.isMetaPressed),
|
||||
releaseModifiers: releaseModifiers
|
||||
? () => _releaseFlutterShortcutModifiers(raw: true)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _releaseFlutterShortcutModifiers({bool raw = false}) async {
|
||||
final releases = <Future<void>>[];
|
||||
// Release only on the remote: the modifiers are still physically held.
|
||||
final pressed = raw
|
||||
? RawKeyboard.instance.keysPressed
|
||||
: HardwareKeyboard.instance.logicalKeysPressed;
|
||||
for (final entry in {
|
||||
LogicalKeyboardKey.controlLeft: PhysicalKeyboardKey.controlLeft,
|
||||
LogicalKeyboardKey.controlRight: PhysicalKeyboardKey.controlRight,
|
||||
LogicalKeyboardKey.altLeft: PhysicalKeyboardKey.altLeft,
|
||||
LogicalKeyboardKey.altRight: PhysicalKeyboardKey.altRight,
|
||||
LogicalKeyboardKey.shiftLeft: PhysicalKeyboardKey.shiftLeft,
|
||||
LogicalKeyboardKey.shiftRight: PhysicalKeyboardKey.shiftRight,
|
||||
LogicalKeyboardKey.metaLeft: PhysicalKeyboardKey.metaLeft,
|
||||
LogicalKeyboardKey.metaRight: PhysicalKeyboardKey.metaRight,
|
||||
}.entries) {
|
||||
if (!pressed.contains(entry.key)) continue;
|
||||
if (isWebDesktop && keyboardMode == kKeyMapMode) {
|
||||
_localFlutterShortcuts.recordReleasedModifiers([entry.value]);
|
||||
releases.add(bind.sessionHandleFlutterKeyEvent(
|
||||
sessionId: sessionId,
|
||||
character: '',
|
||||
usbHid: entry.value.usbHidUsage & 0xFFFF,
|
||||
lockModes: _buildLockModes(false),
|
||||
downOrUp: false,
|
||||
));
|
||||
} else {
|
||||
final label = physicalKeyMap[entry.value.usbHidUsage] ?? entry.key.keyLabel;
|
||||
releases.add(bind.sessionInputKey(
|
||||
sessionId: sessionId,
|
||||
name: label,
|
||||
down: false,
|
||||
press: false,
|
||||
alt: false,
|
||||
ctrl: false,
|
||||
shift: false,
|
||||
command: false,
|
||||
));
|
||||
}
|
||||
}
|
||||
await Future.wait(releases);
|
||||
}
|
||||
|
||||
void _syncFlutterShortcutModifiersAfterViewOnly(PhysicalKeyboardKey incoming,
|
||||
{bool raw = false}) {
|
||||
if (!isInputSourceFlutter) return;
|
||||
final pressed = raw
|
||||
? RawKeyboard.instance.physicalKeysPressed
|
||||
: HardwareKeyboard.instance.physicalKeysPressed;
|
||||
if (!_localFlutterShortcuts.resumeModifiersAfterViewOnly(incoming, pressed)) {
|
||||
return;
|
||||
}
|
||||
ctrl = pressed.contains(PhysicalKeyboardKey.controlLeft) ||
|
||||
pressed.contains(PhysicalKeyboardKey.controlRight);
|
||||
alt = pressed.contains(PhysicalKeyboardKey.altLeft) ||
|
||||
pressed.contains(PhysicalKeyboardKey.altRight);
|
||||
shift = pressed.contains(PhysicalKeyboardKey.shiftLeft) ||
|
||||
pressed.contains(PhysicalKeyboardKey.shiftRight);
|
||||
command = pressed.contains(PhysicalKeyboardKey.metaLeft) ||
|
||||
pressed.contains(PhysicalKeyboardKey.metaRight);
|
||||
}
|
||||
|
||||
void _restoreFlutterShortcutModifiers(KeyEvent e, {bool mapMode = true}) {
|
||||
final keys = _localFlutterShortcuts.takeModifiersToRestore(
|
||||
e, HardwareKeyboard.instance.physicalKeysPressed);
|
||||
if (!mapMode) return;
|
||||
for (final key in keys) {
|
||||
newKeyboardMode('', key.usbHidUsage & 0xFFFF, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
void _restoreRawFlutterShortcutModifiers(RawKeyEvent e, {bool mapMode = true}) {
|
||||
final keys = _localFlutterShortcuts.takeRawModifiersToRestore(
|
||||
e, RawKeyboard.instance.physicalKeysPressed);
|
||||
if (!mapMode) return;
|
||||
for (final key in keys) {
|
||||
newKeyboardMode('', key.usbHidUsage & 0xFFFF, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
String? _matchFlutterShortcut(PhysicalKeyboardKey key,
|
||||
{required bool ctrlPressed,
|
||||
required bool altPressed,
|
||||
required bool shiftPressed,
|
||||
required bool commandPressed}) {
|
||||
if (isViewCamera ||
|
||||
!ShortcutModel.isEnabled() ||
|
||||
ShortcutModel.isPassThrough()) return null;
|
||||
final keyName = physicalKeyName(key);
|
||||
if (keyName == null) return null;
|
||||
final mods = <String>[];
|
||||
if (isMacOS || isIOS || isWebOnMacOs) {
|
||||
if (keyboard.isMetaPressed) mods.add('primary');
|
||||
if (keyboard.isControlPressed) mods.add('ctrl');
|
||||
} else if (keyboard.isControlPressed) {
|
||||
if (commandPressed) mods.add('primary');
|
||||
if (ctrlPressed) mods.add('ctrl');
|
||||
} else if (ctrlPressed) {
|
||||
mods.add('primary');
|
||||
}
|
||||
if (keyboard.isAltPressed) mods.add('alt');
|
||||
if (keyboard.isShiftPressed) mods.add('shift');
|
||||
return mods;
|
||||
}
|
||||
|
||||
String? _matchWebFlutterShortcut(String keyName, List<String> mods) {
|
||||
if (altPressed) mods.add('alt');
|
||||
if (shiftPressed) mods.add('shift');
|
||||
for (final binding in ShortcutModel.readBindings()) {
|
||||
final action = binding['action'];
|
||||
final key = binding['key'];
|
||||
@@ -1160,6 +1283,7 @@ class InputModel {
|
||||
/// Reset key modifiers to false, including [shift], [ctrl], [alt] and [command].
|
||||
void resetModifiers() {
|
||||
shift = ctrl = alt = command = false;
|
||||
if (parent.target?.closed == true) _localFlutterShortcuts.clear();
|
||||
}
|
||||
|
||||
/// Modify the given modifier map [evt] based on current modifier key status.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class LocalFlutterShortcutDispatcher {
|
||||
final void Function(String) onTriggered;
|
||||
// A shortcut can switch focus before its physical key is released.
|
||||
static final _firedKeys =
|
||||
<PhysicalKeyboardKey, LocalFlutterShortcutDispatcher>{};
|
||||
final _releasedModifiers = <PhysicalKeyboardKey>{};
|
||||
bool _viewOnlyShortcutPending = false;
|
||||
int _generation = 0;
|
||||
|
||||
LocalFlutterShortcutDispatcher({required this.onTriggered});
|
||||
|
||||
void clear() {
|
||||
_firedKeys.removeWhere((_, owner) => identical(owner, this));
|
||||
_releasedModifiers.clear();
|
||||
_viewOnlyShortcutPending = false;
|
||||
_generation++;
|
||||
}
|
||||
|
||||
void recordReleasedModifiers(Iterable<PhysicalKeyboardKey> keys) {
|
||||
_releasedModifiers.addAll(keys);
|
||||
}
|
||||
|
||||
bool resumeModifiersAfterViewOnly(
|
||||
PhysicalKeyboardKey incoming, Set<PhysicalKeyboardKey> pressed) {
|
||||
if (!_viewOnlyShortcutPending) return false;
|
||||
_viewOnlyShortcutPending = false;
|
||||
_releasedModifiers
|
||||
.addAll(pressed.where((key) => key != incoming && _isModifier(key)));
|
||||
return true;
|
||||
}
|
||||
|
||||
List<PhysicalKeyboardKey> takeModifiersToRestore(
|
||||
KeyEvent event, Set<PhysicalKeyboardKey> pressed) =>
|
||||
_takeModifiersToRestore(event.physicalKey,
|
||||
event is KeyDownEvent || event is KeyRepeatEvent, pressed);
|
||||
|
||||
List<PhysicalKeyboardKey> takeRawModifiersToRestore(
|
||||
RawKeyEvent event, Set<PhysicalKeyboardKey> pressed) =>
|
||||
_takeModifiersToRestore(
|
||||
event.physicalKey, event is RawKeyDownEvent, pressed);
|
||||
|
||||
List<PhysicalKeyboardKey> _takeModifiersToRestore(
|
||||
PhysicalKeyboardKey incoming,
|
||||
bool down,
|
||||
Set<PhysicalKeyboardKey> pressed) {
|
||||
_releasedModifiers.removeWhere((key) => !pressed.contains(key));
|
||||
if (!down || _isModifier(incoming)) return [];
|
||||
final keys = _releasedModifiers.toList();
|
||||
_releasedModifiers.clear();
|
||||
return keys;
|
||||
}
|
||||
|
||||
bool _isModifier(PhysicalKeyboardKey key) {
|
||||
// HID keyboard modifier usages are contiguous.
|
||||
return key.usbHidUsage >= PhysicalKeyboardKey.controlLeft.usbHidUsage &&
|
||||
key.usbHidUsage <= PhysicalKeyboardKey.metaRight.usbHidUsage;
|
||||
}
|
||||
|
||||
bool tryDispatch(
|
||||
KeyEvent event, {
|
||||
bool viewOnly = false,
|
||||
String? Function()? match,
|
||||
Future<void> Function()? releaseModifiers,
|
||||
}) =>
|
||||
_tryDispatch(
|
||||
event.physicalKey,
|
||||
down: event is KeyDownEvent,
|
||||
up: event is KeyUpEvent,
|
||||
viewOnly: viewOnly,
|
||||
match: match,
|
||||
releaseModifiers: releaseModifiers,
|
||||
);
|
||||
|
||||
bool tryDispatchRaw(
|
||||
RawKeyEvent event, {
|
||||
bool viewOnly = false,
|
||||
String? Function()? match,
|
||||
Future<void> Function()? releaseModifiers,
|
||||
}) =>
|
||||
_tryDispatch(
|
||||
event.physicalKey,
|
||||
down: event is RawKeyDownEvent && !event.repeat,
|
||||
up: event is RawKeyUpEvent,
|
||||
viewOnly: viewOnly,
|
||||
match: match,
|
||||
releaseModifiers: releaseModifiers,
|
||||
);
|
||||
|
||||
bool _tryDispatch(
|
||||
PhysicalKeyboardKey key, {
|
||||
required bool down,
|
||||
required bool up,
|
||||
required bool viewOnly,
|
||||
String? Function()? match,
|
||||
Future<void> Function()? releaseModifiers,
|
||||
}) {
|
||||
if (up) return _firedKeys.remove(key) != null;
|
||||
if (_firedKeys.containsKey(key)) return true;
|
||||
if (!down) return false;
|
||||
final action = match?.call();
|
||||
if (action == null) return false;
|
||||
_firedKeys[key] = this;
|
||||
if (viewOnly) _viewOnlyShortcutPending = true;
|
||||
unawaited(_trigger(action, releaseModifiers));
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _trigger(
|
||||
String action, Future<void> Function()? releaseModifiers) async {
|
||||
final generation = _generation;
|
||||
try {
|
||||
if (releaseModifiers != null) await releaseModifiers();
|
||||
if (generation == _generation) onTriggered(action);
|
||||
} catch (e, st) {
|
||||
debugPrint('Local shortcut failed for $action: $e\n$st');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import '../common/shared_state.dart' show PrivacyModeState;
|
||||
import '../common/widgets/dialog.dart'
|
||||
show desktopTryShowTabAuditDialogCloseCancelled;
|
||||
import '../common/widgets/keyboard_shortcuts/shortcut_utils.dart';
|
||||
import '../common/widgets/toolbar.dart'
|
||||
show allowDisplaySwitchInPrivacyMode, showVirtualDisplayMenu;
|
||||
import '../consts.dart';
|
||||
import '../desktop/widgets/remote_toolbar.dart' show ToolbarState;
|
||||
import 'chat_model.dart' show VoiceCallStatus;
|
||||
@@ -30,12 +32,14 @@ class ShortcutModel {
|
||||
|
||||
final WeakReference<FFI> parent;
|
||||
final Map<String, ShortcutCallback> _callbacks = {};
|
||||
final Map<String, ShortcutCallback> _refreshers = {};
|
||||
|
||||
ShortcutModel(this.parent);
|
||||
|
||||
/// Called by toolbar / menu builders to register what to do when the
|
||||
/// matched shortcut fires.
|
||||
void register(String actionId, ShortcutCallback callback) {
|
||||
if (parent.target?.closed != false) return;
|
||||
_callbacks[actionId] = callback;
|
||||
_activeWebModel = WeakReference(this);
|
||||
}
|
||||
@@ -44,8 +48,16 @@ class ShortcutModel {
|
||||
_callbacks.remove(actionId);
|
||||
}
|
||||
|
||||
void registerRefresher(List<String> actionIds, ShortcutCallback refresh) {
|
||||
if (parent.target?.closed != false) return;
|
||||
for (final actionId in actionIds) {
|
||||
_refreshers[actionId] = refresh;
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_callbacks.clear();
|
||||
_refreshers.clear();
|
||||
if (identical(_activeWebModel?.target, this)) {
|
||||
_activeWebModel = null;
|
||||
}
|
||||
@@ -68,15 +80,23 @@ class ShortcutModel {
|
||||
/// support), and the chord is a deliberate no-op: a bound chord always
|
||||
/// belongs to RustDesk and is never forwarded to the remote.
|
||||
void onTriggered(String actionId) {
|
||||
final cb = _callbacks[actionId];
|
||||
if (cb != null) {
|
||||
unawaited(Future.sync(cb).catchError((e, st) {
|
||||
debugPrint(
|
||||
'shortcut_triggered: handler failed for $actionId: $e\n$st');
|
||||
}));
|
||||
} else {
|
||||
debugPrint('shortcut_triggered: no handler for $actionId');
|
||||
}
|
||||
if (parent.target?.closed != false) return;
|
||||
unawaited(Future.sync(() async {
|
||||
final refresh = _refreshers[actionId];
|
||||
if (refresh != null) {
|
||||
await refresh();
|
||||
if (!identical(_refreshers[actionId], refresh)) return;
|
||||
}
|
||||
if (parent.target?.closed != false) return;
|
||||
final cb = _callbacks[actionId];
|
||||
if (cb != null) {
|
||||
await cb();
|
||||
} else {
|
||||
debugPrint('shortcut_triggered: no handler for $actionId');
|
||||
}
|
||||
}).catchError((e, st) {
|
||||
debugPrint('shortcut_triggered: handler failed for $actionId: $e\n$st');
|
||||
}));
|
||||
}
|
||||
|
||||
/// Read the bindings JSON from LocalConfig.
|
||||
@@ -272,6 +292,11 @@ void registerSessionShortcutActions(
|
||||
// view via these shortcuts.
|
||||
void switchDisplayBy(int delta) {
|
||||
final pi = ffi.ffiModel.pi;
|
||||
final privacyMode = PrivacyModeState.find(ffi.id).value;
|
||||
if (privacyMode.isNotEmpty &&
|
||||
!allowDisplaySwitchInPrivacyMode(pi, privacyMode)) {
|
||||
return;
|
||||
}
|
||||
final count = pi.displays.length;
|
||||
if (count <= 1) return;
|
||||
final current = pi.currentDisplay;
|
||||
@@ -315,6 +340,11 @@ void registerSessionShortcutActions(
|
||||
// view never engages.
|
||||
ffi.shortcutModel.register(kShortcutActionSwitchDisplayAll, () {
|
||||
final pi = ffi.ffiModel.pi;
|
||||
final privacyMode = PrivacyModeState.find(ffi.id).value;
|
||||
if (privacyMode.isNotEmpty &&
|
||||
!allowDisplaySwitchInPrivacyMode(pi, privacyMode)) {
|
||||
return;
|
||||
}
|
||||
if (pi.displays.length <= 1) return;
|
||||
if (pi.currentDisplay == kAllDisplayValue) return;
|
||||
openMonitorInTheSameTab(kAllDisplayValue, ffi, pi);
|
||||
@@ -432,6 +462,20 @@ void registerSessionShortcutActions(
|
||||
// `_KeyboardMenu.keyboardMode()` (built as RdoMenuButton, not TRadioMenu).
|
||||
void registerKeyboardMode(String actionId, String mode) {
|
||||
ffi.shortcutModel.register(actionId, () async {
|
||||
if (!ffi.ffiModel.keyboard ||
|
||||
ffi.ffiModel.viewOnly ||
|
||||
!bind.sessionIsKeyboardModeSupported(
|
||||
sessionId: sessionId, mode: mode) ||
|
||||
(ffi.ffiModel.pi.isWayland && mode != kKeyMapMode)) {
|
||||
return;
|
||||
}
|
||||
if (isInputSourceFlutter && isDesktop) {
|
||||
final modeOnly = bind.sessionIsKeyboardModeSupported(
|
||||
sessionId: sessionId, mode: kKeyMapMode)
|
||||
? kKeyMapMode
|
||||
: kKeyLegacyMode;
|
||||
if (mode != modeOnly) return;
|
||||
}
|
||||
await bind.sessionSetKeyboardMode(sessionId: sessionId, value: mode);
|
||||
await ffi.inputModel.updateKeyboardMode();
|
||||
});
|
||||
@@ -445,6 +489,13 @@ void registerSessionShortcutActions(
|
||||
// "Plug out all" button — present in both IDD modes (RustDesk + Amyuni),
|
||||
// built as a MenuButton inside `getVirtualDisplayMenuChildren`.
|
||||
ffi.shortcutModel.register(kShortcutActionPlugOutAllVirtualDisplays, () {
|
||||
if (ffi.connType != ConnType.defaultConn ||
|
||||
!showVirtualDisplayMenu(ffi) ||
|
||||
PrivacyModeState.find(ffi.id).value.isNotEmpty ||
|
||||
(ffi.ffiModel.pi.isAmyuniIdd &&
|
||||
ffi.ffiModel.pi.amyuniVirtualDisplayCount == 0)) {
|
||||
return;
|
||||
}
|
||||
bind.sessionToggleVirtualDisplay(
|
||||
sessionId: sessionId,
|
||||
index: kAllVirtualDisplay,
|
||||
@@ -471,6 +522,28 @@ void registerSessionShortcutActions(
|
||||
return null;
|
||||
}
|
||||
|
||||
bool checkPrivacyModeAllowed(String implKey) {
|
||||
final ffiModel = ffi.ffiModel;
|
||||
final pi = ffiModel.pi;
|
||||
final privacyMode = PrivacyModeState.find(ffi.id).value;
|
||||
if (ffi.connType != ConnType.defaultConn ||
|
||||
ffiModel.viewOnly ||
|
||||
(privacyMode.isEmpty &&
|
||||
(!pi.features.privacyMode || !ffiModel.keyboard))) {
|
||||
return false;
|
||||
}
|
||||
if (privacyMode == implKey) return true;
|
||||
if (ffiModel.permissions['privacy_mode'] == false) return false;
|
||||
if (allowDisplaySwitchInPrivacyMode(pi, implKey) ||
|
||||
(pi.currentDisplay == 0 &&
|
||||
!bind.sessionIsMultiUiSession(sessionId: sessionId))) {
|
||||
return true;
|
||||
}
|
||||
msgBox(sessionId, 'custom-nook-nocancel-hasclose', 'info',
|
||||
'Please switch to Display 1 first', '', ffi.dialogManager);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match the multi-impl branch of `toolbarPrivacyMode`: turn this impl on iff
|
||||
// the active impl isn't already this one. Comparing `.value == implKey`
|
||||
// (rather than `.value.isEmpty`) means pressing the mode-1 shortcut while
|
||||
@@ -479,6 +552,7 @@ void registerSessionShortcutActions(
|
||||
ffi.shortcutModel.register(kShortcutActionPrivacyMode1, () {
|
||||
final implKey = findPrivacyImpl('privacy_mode_impl_mag_tip');
|
||||
if (implKey == null) return;
|
||||
if (!checkPrivacyModeAllowed(implKey)) return;
|
||||
bind.sessionTogglePrivacyMode(
|
||||
sessionId: sessionId,
|
||||
implKey: implKey,
|
||||
@@ -488,6 +562,7 @@ void registerSessionShortcutActions(
|
||||
ffi.shortcutModel.register(kShortcutActionPrivacyMode2, () {
|
||||
final implKey = findPrivacyImpl('privacy_mode_impl_virtual_display_tip');
|
||||
if (implKey == null) return;
|
||||
if (!checkPrivacyModeAllowed(implKey)) return;
|
||||
bind.sessionTogglePrivacyMode(
|
||||
sessionId: sessionId,
|
||||
implKey: implKey,
|
||||
@@ -515,6 +590,7 @@ void registerSessionShortcutActions(
|
||||
// Toggle Reverse mouse wheel — read current 'Y'/'N' (falling back to user
|
||||
// default), flip, write back.
|
||||
ffi.shortcutModel.register(kShortcutActionToggleReverseMouseWheel, () async {
|
||||
if (!ffi.ffiModel.keyboard || ffi.ffiModel.viewOnly) return;
|
||||
var cur = bind.sessionGetReverseMouseWheelSync(sessionId: sessionId) ?? '';
|
||||
if (cur == '') {
|
||||
cur = bind.mainGetUserDefaultOption(key: kKeyReverseMouseWheel);
|
||||
|
||||
@@ -83,6 +83,65 @@ void main() {
|
||||
]);
|
||||
});
|
||||
|
||||
test('shortcutBindingMapsFrom ignores malformed binding fields', () {
|
||||
final valid = {
|
||||
'action': kShortcutActionScreenshot,
|
||||
'mods': ['primary', 'ctrl', 'alt', 'shift'],
|
||||
'key': 'p',
|
||||
};
|
||||
final malformed = [
|
||||
for (final field in ['action', 'mods', 'key'])
|
||||
{...valid}..remove(field),
|
||||
for (final fields in [
|
||||
{'action': 1},
|
||||
{'action': null},
|
||||
{'key': 1},
|
||||
{'key': null},
|
||||
{'mods': null},
|
||||
{'mods': 'primary'},
|
||||
{'mods': ['primary', 1]},
|
||||
{'mods': ['primary', null]},
|
||||
{'mods': ['primary', 'unknown']},
|
||||
])
|
||||
{...valid, ...fields},
|
||||
];
|
||||
|
||||
for (final binding in malformed) {
|
||||
expect(shortcutBindingMapsFrom([binding, valid]), [valid],
|
||||
reason: 'malformed binding should be ignored: $binding');
|
||||
}
|
||||
});
|
||||
|
||||
test('shortcutBindingMapsFrom preserves unbound and unknown bindings', () {
|
||||
expect(
|
||||
shortcutBindingMapsFrom([
|
||||
{'action': kShortcutActionScreenshot, 'mods': [], 'key': ''},
|
||||
{'action': 'future_action', 'mods': ['ctrl'], 'key': 'future_key'},
|
||||
]),
|
||||
[
|
||||
{'action': kShortcutActionScreenshot, 'mods': [], 'key': ''},
|
||||
{'action': 'future_action', 'mods': ['ctrl'], 'key': 'future_key'},
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('platform filtering ignores malformed binding fields', () {
|
||||
final filtered = filterDefaultBindingsForPlatform([
|
||||
{'action': 1, 'mods': ['primary'], 'key': 'p'},
|
||||
{'action': kShortcutActionScreenshot, 'mods': ['primary'], 'key': 1},
|
||||
{'action': kShortcutActionToggleMute, 'mods': ['alt'], 'key': 's'},
|
||||
{
|
||||
'action': kShortcutActionToggleFullscreen,
|
||||
'mods': ['primary'],
|
||||
'key': 'enter',
|
||||
},
|
||||
], capabilities(includeFullscreenShortcut: false));
|
||||
|
||||
expect(filtered, [
|
||||
{'action': kShortcutActionToggleMute, 'mods': ['alt'], 'key': 's'},
|
||||
]);
|
||||
});
|
||||
|
||||
test('shortcutModSetFrom ignores malformed modifiers', () {
|
||||
expect(shortcutModSetFrom('not a list'), isEmpty);
|
||||
expect(shortcutModSetFrom(['primary', 1, 'alt', null, 'primary']), {
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_hbb/models/local_flutter_shortcuts.dart';
|
||||
|
||||
LocalFlutterShortcutDispatcher dispatcherFor(
|
||||
void Function(String) onTriggered) {
|
||||
final dispatcher = LocalFlutterShortcutDispatcher(onTriggered: onTriggered);
|
||||
addTearDown(dispatcher.clear);
|
||||
return dispatcher;
|
||||
}
|
||||
|
||||
class _ShortcutHarness {
|
||||
final String? Function(KeyEvent) match;
|
||||
final Future<void> Function() releaseModifiers;
|
||||
final LocalFlutterShortcutDispatcher dispatcher;
|
||||
|
||||
_ShortcutHarness({
|
||||
required this.match,
|
||||
required this.releaseModifiers,
|
||||
required void Function(String) onTriggered,
|
||||
}) : dispatcher = dispatcherFor(onTriggered);
|
||||
|
||||
bool tryDispatch(KeyEvent event) => dispatcher.tryDispatch(
|
||||
event,
|
||||
match: () => match(event),
|
||||
releaseModifiers: releaseModifiers,
|
||||
);
|
||||
|
||||
void clear() => dispatcher.clear();
|
||||
}
|
||||
|
||||
KeyEvent down(PhysicalKeyboardKey key,
|
||||
{LogicalKeyboardKey logicalKey = LogicalKeyboardKey.keyP}) =>
|
||||
KeyDownEvent(
|
||||
physicalKey: key,
|
||||
logicalKey: logicalKey,
|
||||
timeStamp: Duration.zero,
|
||||
);
|
||||
|
||||
KeyEvent repeat(PhysicalKeyboardKey key) => KeyRepeatEvent(
|
||||
physicalKey: key,
|
||||
logicalKey: LogicalKeyboardKey.keyP,
|
||||
timeStamp: Duration.zero,
|
||||
);
|
||||
|
||||
KeyEvent up(PhysicalKeyboardKey key,
|
||||
{LogicalKeyboardKey logicalKey = LogicalKeyboardKey.keyP}) =>
|
||||
KeyUpEvent(
|
||||
physicalKey: key,
|
||||
logicalKey: logicalKey,
|
||||
timeStamp: Duration.zero,
|
||||
);
|
||||
|
||||
RawKeyEvent rawP({required bool down, bool repeat = false, bool ctrl = false}) {
|
||||
final data = RawKeyEventDataLinux(
|
||||
keyHelper: GtkKeyHelper(),
|
||||
scanCode: 33,
|
||||
keyCode: 112,
|
||||
unicodeScalarValues: 112,
|
||||
modifiers: ctrl ? GtkKeyHelper.modifierControl : 0,
|
||||
isDown: down,
|
||||
);
|
||||
return down
|
||||
? RawKeyDownEvent(data: data, repeat: repeat)
|
||||
: RawKeyUpEvent(data: data);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('owns repeats and release after the chord modifiers are released',
|
||||
() async {
|
||||
var modifiersPressed = true;
|
||||
final actions = <String>[];
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (_) => modifiersPressed ? 'screenshot' : null,
|
||||
releaseModifiers: () async {},
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
modifiersPressed = false;
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot']);
|
||||
});
|
||||
|
||||
test('owns each overlapping shortcut key until its own release', () async {
|
||||
var modifiersPressed = true;
|
||||
final actions = <String>[];
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (event) => modifiersPressed
|
||||
? event.physicalKey == PhysicalKeyboardKey.keyP
|
||||
? 'screenshot'
|
||||
: 'chat'
|
||||
: null,
|
||||
releaseModifiers: () async {},
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyC)), isTrue);
|
||||
modifiersPressed = false;
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyC)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue);
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot', 'chat']);
|
||||
});
|
||||
|
||||
test('binding changes do not forward a previously consumed key', () async {
|
||||
var enabled = true;
|
||||
final actions = <String>[];
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (_) => enabled ? 'screenshot' : null,
|
||||
releaseModifiers: () async {},
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
enabled = false;
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot']);
|
||||
});
|
||||
|
||||
test('unmatched key stays forwarded when modifiers change during repeat',
|
||||
() async {
|
||||
var modifiersPressed = false;
|
||||
final actions = <String>[];
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (_) => modifiersPressed ? 'screenshot' : null,
|
||||
releaseModifiers: () async {},
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
modifiersPressed = true;
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
await Future<void>.value();
|
||||
expect(actions, isEmpty);
|
||||
});
|
||||
|
||||
test('auto-repeat cannot trigger an action again', () async {
|
||||
final actions = <String>[];
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (_) => 'screenshot',
|
||||
releaseModifiers: () async {},
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot', 'screenshot']);
|
||||
});
|
||||
|
||||
test('releases remote modifiers before running the action', () async {
|
||||
final released = Completer<void>();
|
||||
final actions = <String>[];
|
||||
var releases = 0;
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (_) => 'screenshot',
|
||||
releaseModifiers: () {
|
||||
releases++;
|
||||
return released.future;
|
||||
},
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(releases, 1);
|
||||
expect(actions, isEmpty);
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(releases, 1);
|
||||
released.complete();
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot']);
|
||||
});
|
||||
|
||||
test('closing the session clears owned keys and pending actions', () async {
|
||||
final released = Completer<void>();
|
||||
final actions = <String>[];
|
||||
var enabled = true;
|
||||
final dispatcher = _ShortcutHarness(
|
||||
match: (_) => enabled ? 'screenshot' : null,
|
||||
releaseModifiers: () => released.future,
|
||||
onTriggered: actions.add,
|
||||
);
|
||||
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
dispatcher.clear();
|
||||
enabled = false;
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
released.complete();
|
||||
await Future<void>.value();
|
||||
expect(actions, isEmpty);
|
||||
|
||||
enabled = true;
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot']);
|
||||
});
|
||||
|
||||
test('raw legacy shortcuts own repeats and release after modifiers change',
|
||||
() async {
|
||||
addTearDown(RawKeyboard.instance.clearKeysPressed);
|
||||
final actions = <String>[];
|
||||
final dispatcher = dispatcherFor(actions.add);
|
||||
bool dispatch(RawKeyEvent event) {
|
||||
RawKeyboard.instance.handleRawKeyEvent(event);
|
||||
return dispatcher.tryDispatchRaw(
|
||||
event,
|
||||
match: () => event.isControlPressed ? 'screenshot' : null,
|
||||
releaseModifiers: () async {},
|
||||
);
|
||||
}
|
||||
|
||||
expect(dispatch(rawP(down: true, ctrl: true)), isTrue);
|
||||
expect(dispatch(rawP(down: true, repeat: true)), isTrue);
|
||||
expect(dispatch(rawP(down: false)), isTrue);
|
||||
expect(dispatch(rawP(down: true)), isFalse);
|
||||
expect(dispatch(rawP(down: true, repeat: true, ctrl: true)), isFalse);
|
||||
expect(dispatch(rawP(down: false, ctrl: true)), isFalse);
|
||||
await Future<void>.value();
|
||||
expect(actions, ['screenshot']);
|
||||
});
|
||||
|
||||
test('read-only shortcut release is consumed after local matching stops', () {
|
||||
var viewOnly = true;
|
||||
final actions = <String>[];
|
||||
final dispatcher = dispatcherFor((action) {
|
||||
actions.add(action);
|
||||
viewOnly = false;
|
||||
});
|
||||
|
||||
expect(
|
||||
dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
||||
match: () => viewOnly ? 'toggle_view_only' : null),
|
||||
isTrue,
|
||||
);
|
||||
expect(viewOnly, isFalse);
|
||||
expect(dispatcher.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
expect(actions, ['toggle_view_only']);
|
||||
});
|
||||
|
||||
test('raw read-only shortcut keeps ownership when input routing changes', () {
|
||||
final actions = <String>[];
|
||||
final dispatcher = dispatcherFor(actions.add);
|
||||
|
||||
expect(
|
||||
dispatcher.tryDispatchRaw(rawP(down: true, ctrl: true),
|
||||
match: () => 'toggle_view_only'),
|
||||
isTrue,
|
||||
);
|
||||
expect(dispatcher.tryDispatchRaw(rawP(down: true, repeat: true)), isTrue);
|
||||
expect(dispatcher.tryDispatchRaw(rawP(down: false)), isTrue);
|
||||
expect(dispatcher.tryDispatchRaw(rawP(down: true)), isFalse);
|
||||
expect(actions, ['toggle_view_only']);
|
||||
});
|
||||
|
||||
test('shortcut key ownership follows focus to another session', () {
|
||||
final actions = <String>[];
|
||||
final first = dispatcherFor(actions.add);
|
||||
final second = dispatcherFor(actions.add);
|
||||
|
||||
expect(
|
||||
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
||||
match: () => 'next_tab'),
|
||||
isTrue,
|
||||
);
|
||||
expect(second.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(second.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(
|
||||
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
||||
match: () => 'next_tab'),
|
||||
isTrue,
|
||||
);
|
||||
expect(actions, ['next_tab', 'next_tab']);
|
||||
});
|
||||
|
||||
test('closing another session preserves the original session owned key', () {
|
||||
final first = dispatcherFor((_) {});
|
||||
final second = dispatcherFor((_) {});
|
||||
first.tryDispatch(down(PhysicalKeyboardKey.keyP),
|
||||
match: () => 'screenshot');
|
||||
second.tryDispatch(down(PhysicalKeyboardKey.keyC), match: () => 'chat');
|
||||
|
||||
second.clear();
|
||||
expect(second.tryDispatch(repeat(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(first.tryDispatch(repeat(PhysicalKeyboardKey.keyC)), isFalse);
|
||||
expect(second.tryDispatch(up(PhysicalKeyboardKey.keyP)), isTrue);
|
||||
expect(first.tryDispatch(up(PhysicalKeyboardKey.keyP)), isFalse);
|
||||
});
|
||||
|
||||
test('restores released modifiers before the next ordinary map key', () {
|
||||
final dispatcher = dispatcherFor((_) {});
|
||||
dispatcher.recordReleasedModifiers([
|
||||
PhysicalKeyboardKey.controlLeft,
|
||||
PhysicalKeyboardKey.altRight,
|
||||
]);
|
||||
final pressed = {PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.keyC};
|
||||
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(
|
||||
down(PhysicalKeyboardKey.keyC), pressed),
|
||||
[PhysicalKeyboardKey.controlLeft],
|
||||
);
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(
|
||||
repeat(PhysicalKeyboardKey.keyC), pressed),
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('modifier events do not replay previously released modifiers', () {
|
||||
final dispatcher = dispatcherFor((_) {});
|
||||
dispatcher.recordReleasedModifiers([PhysicalKeyboardKey.controlLeft]);
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.shiftLeft),
|
||||
{PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.shiftLeft}),
|
||||
isEmpty,
|
||||
);
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(
|
||||
up(PhysicalKeyboardKey.controlLeft), {PhysicalKeyboardKey.shiftLeft}),
|
||||
isEmpty,
|
||||
);
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.keyC),
|
||||
{PhysicalKeyboardKey.shiftLeft, PhysicalKeyboardKey.keyC}),
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('session closure drops pending modifier replay', () {
|
||||
final dispatcher = dispatcherFor((_) {});
|
||||
dispatcher.recordReleasedModifiers([PhysicalKeyboardKey.controlLeft]);
|
||||
dispatcher.clear();
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(down(PhysicalKeyboardKey.keyC),
|
||||
{PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.keyC}),
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
for (final releaseControl in [false, true]) {
|
||||
test(
|
||||
'view-only resume restores only still-held modifiers '
|
||||
'(releaseControl=$releaseControl)', () {
|
||||
final keyboard = HardwareKeyboard();
|
||||
var viewOnly = true;
|
||||
final dispatcher = dispatcherFor((_) => viewOnly = false);
|
||||
final controlDown = down(PhysicalKeyboardKey.controlLeft,
|
||||
logicalKey: LogicalKeyboardKey.controlLeft);
|
||||
keyboard.handleKeyEvent(controlDown);
|
||||
expect(dispatcher.tryDispatch(controlDown, viewOnly: true), isFalse);
|
||||
|
||||
final shortcutDown = down(PhysicalKeyboardKey.keyP);
|
||||
keyboard.handleKeyEvent(shortcutDown);
|
||||
expect(
|
||||
dispatcher.tryDispatch(shortcutDown,
|
||||
viewOnly: true, match: () => 'toggle_view_only'),
|
||||
isTrue,
|
||||
);
|
||||
expect(viewOnly, isFalse);
|
||||
final shortcutUp = up(PhysicalKeyboardKey.keyP);
|
||||
keyboard.handleKeyEvent(shortcutUp);
|
||||
expect(dispatcher.tryDispatch(shortcutUp), isTrue);
|
||||
if (releaseControl) {
|
||||
final controlUp = up(PhysicalKeyboardKey.controlLeft,
|
||||
logicalKey: LogicalKeyboardKey.controlLeft);
|
||||
keyboard.handleKeyEvent(controlUp);
|
||||
}
|
||||
|
||||
final copyDown =
|
||||
down(PhysicalKeyboardKey.keyC, logicalKey: LogicalKeyboardKey.keyC);
|
||||
keyboard.handleKeyEvent(copyDown);
|
||||
expect(dispatcher.tryDispatch(copyDown), isFalse);
|
||||
expect(
|
||||
dispatcher.resumeModifiersAfterViewOnly(
|
||||
copyDown.physicalKey, keyboard.physicalKeysPressed),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
dispatcher.takeModifiersToRestore(
|
||||
copyDown, keyboard.physicalKeysPressed),
|
||||
releaseControl ? isEmpty : [PhysicalKeyboardKey.controlLeft],
|
||||
);
|
||||
expect(keyboard.isControlPressed, !releaseControl);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/models/shortcut_model.dart';
|
||||
|
||||
class _Session extends Fake implements FFI {
|
||||
@override
|
||||
bool closed = false;
|
||||
}
|
||||
|
||||
void main() {
|
||||
late _Session session;
|
||||
late ShortcutModel model;
|
||||
|
||||
setUp(() {
|
||||
session = _Session();
|
||||
model = ShortcutModel(WeakReference(session));
|
||||
});
|
||||
|
||||
tearDown(() => model.clear());
|
||||
|
||||
test('a removed menu action cannot run its cached callback', () async {
|
||||
var calls = 0;
|
||||
model.register('mute', () => calls++);
|
||||
model.registerRefresher(['mute'], () => model.unregister('mute'));
|
||||
|
||||
model.onTriggered('mute');
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(calls, 0);
|
||||
});
|
||||
|
||||
test('an action becomes available without reopening its menu', () async {
|
||||
var calls = 0;
|
||||
model.registerRefresher(['screenshot'], () {
|
||||
model.register('screenshot', () => calls++);
|
||||
});
|
||||
|
||||
model.onTriggered('screenshot');
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(calls, 1);
|
||||
});
|
||||
|
||||
test('refresh finishes before invoking the current callback', () async {
|
||||
final ready = Completer<void>();
|
||||
final calls = <String>[];
|
||||
model.register('cursor', () => calls.add('stale'));
|
||||
model.registerRefresher(['cursor'], () async {
|
||||
await ready.future;
|
||||
model.register('cursor', () => calls.add('current'));
|
||||
});
|
||||
|
||||
model.onTriggered('cursor');
|
||||
expect(calls, isEmpty);
|
||||
ready.complete();
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(calls, ['current']);
|
||||
});
|
||||
|
||||
test('closing during a refresh prevents late registration and dispatch',
|
||||
() async {
|
||||
final ready = Completer<void>();
|
||||
var calls = 0;
|
||||
model.registerRefresher(['mute'], () async {
|
||||
await ready.future;
|
||||
model.register('mute', () => calls++);
|
||||
});
|
||||
|
||||
model.onTriggered('mute');
|
||||
session.closed = true;
|
||||
model.clear();
|
||||
ready.complete();
|
||||
await pumpEventQueue();
|
||||
model.onTriggered('mute');
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(calls, 0);
|
||||
});
|
||||
}
|
||||
+4
-2
@@ -1651,8 +1651,10 @@ pub fn get_cur_peer_id() -> String {
|
||||
}
|
||||
|
||||
pub fn set_cur_session_id(session_id: SessionID) {
|
||||
if get_cur_session_id() != session_id {
|
||||
*CUR_SESSION_ID.write().unwrap() = session_id;
|
||||
let mut current = CUR_SESSION_ID.write().unwrap();
|
||||
if *current != session_id {
|
||||
crate::keyboard::shortcuts::transfer_fired_keys(¤t, &session_id);
|
||||
*current = session_id;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -263,7 +263,7 @@ pub fn will_session_close_close_session(session_id: SessionID) -> SyncReturn<boo
|
||||
|
||||
pub fn session_close(session_id: SessionID) {
|
||||
if let Some(session) = sessions::remove_session_by_session_id(&session_id) {
|
||||
crate::keyboard::shortcuts::clear_fired_keys(&session_id);
|
||||
crate::keyboard::shortcuts::clear_session_state(&session_id);
|
||||
// `release_remote_keys` is not required for mobile platforms in common cases.
|
||||
// But we still call it to make the code more stable.
|
||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||
@@ -325,6 +325,9 @@ pub fn session_toggle_option(session_id: SessionID, value: String) {
|
||||
if let Some(session) = sessions::get_session_by_session_id(&session_id) {
|
||||
log::warn!("toggle option {}", &value);
|
||||
session.toggle_option(value.clone());
|
||||
if value == "view-only" && session.get_toggle_option(value.clone()) {
|
||||
crate::keyboard::shortcuts::enter_view_only(&session_id);
|
||||
}
|
||||
try_sync_peer_option(&session, &session_id, &value, None);
|
||||
}
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
|
||||
+327
-17
@@ -253,6 +253,10 @@ pub fn event_to_key_name(event: &rdev::Event) -> Option<String> {
|
||||
/// written.
|
||||
pub fn reload_from_config() {
|
||||
let raw = hbb_common::config::LocalConfig::get_option(LOCAL_CONFIG_KEY);
|
||||
reload_from_raw(&raw);
|
||||
}
|
||||
|
||||
fn reload_from_raw(raw: &str) {
|
||||
let parsed = if raw.is_empty() {
|
||||
Bindings::default()
|
||||
} else {
|
||||
@@ -319,6 +323,9 @@ lazy_static::lazy_static! {
|
||||
static ref FIRED_KEYS: std::sync::Mutex<
|
||||
std::collections::HashMap<hbb_common::SessionID, std::collections::HashSet<rdev::Key>>,
|
||||
> = Default::default();
|
||||
static ref RELEASED_MODIFIERS: std::sync::Mutex<
|
||||
std::collections::HashMap<hbb_common::SessionID, std::collections::HashMap<rdev::Key, rdev::Event>>,
|
||||
> = Default::default();
|
||||
}
|
||||
|
||||
/// Forget the fired keys of a session that is going away.
|
||||
@@ -330,6 +337,50 @@ pub fn clear_fired_keys(session_id: &hbb_common::SessionID) {
|
||||
FIRED_KEYS.lock().unwrap().remove(session_id);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
pub fn clear_session_state(session_id: &hbb_common::SessionID) {
|
||||
clear_fired_keys(session_id);
|
||||
let held = RELEASED_MODIFIERS.lock().unwrap().remove(session_id);
|
||||
if let Some(held) = held {
|
||||
{
|
||||
let mut state = super::MODIFIERS_STATE.lock().unwrap();
|
||||
for key in held.keys() {
|
||||
state.insert(*key, false);
|
||||
}
|
||||
}
|
||||
let mut to_release = super::TO_RELEASE.lock().unwrap();
|
||||
for key in held.keys() {
|
||||
to_release.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
pub fn enter_view_only(session_id: &hbb_common::SessionID) {
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
if super::IS_RDEV_ENABLED.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
clear_session_state(session_id);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
pub fn transfer_fired_keys(from: &hbb_common::SessionID, to: &hbb_common::SessionID) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let mut all = FIRED_KEYS.lock().unwrap();
|
||||
if let Some(fired) = all.remove(from) {
|
||||
// A held shortcut key's repeats and release follow the newly focused tab.
|
||||
all.entry(*to).or_default().extend(fired);
|
||||
}
|
||||
drop(all);
|
||||
let mut released = RELEASED_MODIFIERS.lock().unwrap();
|
||||
if let Some(held) = released.remove(from) {
|
||||
released.entry(*to).or_default().extend(held);
|
||||
}
|
||||
}
|
||||
|
||||
/// Match `event` against the cached bindings; if it matched, push a
|
||||
/// `shortcut_triggered` Flutter session event and return `true` so the caller
|
||||
/// can `return` early. Returns `false` when no shortcut fired (caller should
|
||||
@@ -361,6 +412,15 @@ pub fn try_dispatch(
|
||||
&resolved
|
||||
}
|
||||
};
|
||||
if let EventType::KeyRelease(key) = event.event_type {
|
||||
let mut released = RELEASED_MODIFIERS.lock().unwrap();
|
||||
if let Some(held) = released.get_mut(sid) {
|
||||
held.remove(&key);
|
||||
if held.is_empty() {
|
||||
released.remove(sid);
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut all = FIRED_KEYS.lock().unwrap();
|
||||
if let Some(fired) = all.get_mut(sid) {
|
||||
@@ -377,9 +437,10 @@ pub fn try_dispatch(
|
||||
}
|
||||
}
|
||||
let Some(action_id) = match_event(event) else {
|
||||
restore_remote_modifiers(sid, event, keyboard_mode, peer, &send);
|
||||
return false;
|
||||
};
|
||||
release_remote_keys(keyboard_mode, &peer(), &send);
|
||||
release_remote_keys(sid, keyboard_mode, &peer(), &send);
|
||||
if let EventType::KeyPress(k) = event.event_type {
|
||||
FIRED_KEYS.lock().unwrap().entry(*sid).or_default().insert(k);
|
||||
}
|
||||
@@ -387,6 +448,38 @@ pub fn try_dispatch(
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
fn restore_remote_modifiers(
|
||||
session_id: &hbb_common::SessionID,
|
||||
event: &rdev::Event,
|
||||
keyboard_mode: &str,
|
||||
peer: impl FnOnce() -> String,
|
||||
send: &impl Fn(&base::message_proto::KeyEvent),
|
||||
) {
|
||||
use super::{event_to_key_events, get_keyboard_mode_enum, is_modifier, MODIFIERS_STATE};
|
||||
|
||||
let rdev::EventType::KeyPress(key) = event.event_type else { return };
|
||||
if is_modifier(&key) {
|
||||
return;
|
||||
}
|
||||
let held = RELEASED_MODIFIERS.lock().unwrap().remove(session_id);
|
||||
let Some(mut held) = held else { return };
|
||||
{
|
||||
let state = MODIFIERS_STATE.lock().unwrap();
|
||||
held.retain(|key, _| state.get(key).copied().unwrap_or(false));
|
||||
}
|
||||
if held.is_empty() {
|
||||
return;
|
||||
}
|
||||
let peer = peer();
|
||||
let mode = get_keyboard_mode_enum(keyboard_mode);
|
||||
for event in held.into_values() {
|
||||
for key_event in event_to_key_events(peer.clone(), &event, mode, None) {
|
||||
send(&key_event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Release on the remote every key it still holds, the chord's modifiers
|
||||
/// included, so the action does not run with them held down there.
|
||||
///
|
||||
@@ -396,21 +489,22 @@ pub fn try_dispatch(
|
||||
/// `send` instead of the globally current session.
|
||||
#[cfg(feature = "flutter")]
|
||||
fn release_remote_keys(
|
||||
session_id: &hbb_common::SessionID,
|
||||
keyboard_mode: &str,
|
||||
peer: &str,
|
||||
send: &impl Fn(&base::message_proto::KeyEvent),
|
||||
) {
|
||||
use super::{event_to_key_events, get_keyboard_mode_enum, take_remote_keys, MODIFIERS_STATE};
|
||||
use super::{event_to_key_events, get_keyboard_mode_enum, take_remote_keys, MODIFIERS_STATE, TO_RELEASE};
|
||||
use rdev::{EventType, Key};
|
||||
|
||||
let mode = get_keyboard_mode_enum(keyboard_mode);
|
||||
let to_release = take_remote_keys();
|
||||
let held: Vec<Key> = {
|
||||
let held: Vec<(Key, rdev::Event)> = {
|
||||
let state = MODIFIERS_STATE.lock().unwrap();
|
||||
to_release
|
||||
.keys()
|
||||
.filter(|k| state.get(k).copied().unwrap_or(false))
|
||||
.copied()
|
||||
.iter()
|
||||
.filter(|(k, _)| state.get(k).copied().unwrap_or(false))
|
||||
.map(|(key, event)| (*key, event.clone()))
|
||||
.collect()
|
||||
};
|
||||
for (key, mut event) in to_release {
|
||||
@@ -428,10 +522,17 @@ fn release_remote_keys(
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut state = MODIFIERS_STATE.lock().unwrap();
|
||||
for key in held {
|
||||
state.insert(key, true);
|
||||
{
|
||||
let mut state = MODIFIERS_STATE.lock().unwrap();
|
||||
for (key, _) in &held {
|
||||
state.insert(*key, true);
|
||||
}
|
||||
}
|
||||
RELEASED_MODIFIERS.lock().unwrap().insert(
|
||||
*session_id, held.iter().cloned().collect()
|
||||
);
|
||||
// Focus-loss cleanup must still reset modifiers released outside the grab.
|
||||
TO_RELEASE.lock().unwrap().extend(held);
|
||||
}
|
||||
|
||||
fn mods_bits(m: &[Modifier]) -> u8 {
|
||||
@@ -461,7 +562,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn make_press(k: rdev::Key) -> rdev::Event {
|
||||
rdev::Event {
|
||||
let mut event = rdev::Event {
|
||||
time: std::time::SystemTime::now(),
|
||||
unicode: None,
|
||||
platform_code: 0,
|
||||
@@ -470,7 +571,27 @@ mod tests {
|
||||
usb_hid: 0,
|
||||
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||
extra_data: 0,
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
event.platform_code = rdev::win_code_from_key(k).unwrap_or_default();
|
||||
event.position_code = rdev::win_scancode_from_key(k).unwrap_or_default();
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
event.platform_code = rdev::macos_keycode_from_key(k).unwrap_or_default() as _;
|
||||
event.position_code = event.platform_code;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
event.position_code = rdev::linux_keycode_from_key(k).unwrap_or_default();
|
||||
event.platform_code = event.position_code;
|
||||
}
|
||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||
{
|
||||
event.usb_hid = rdev::usb_hid_keycode_from_key(k).unwrap_or_default();
|
||||
}
|
||||
event
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -791,15 +912,13 @@ mod tests {
|
||||
fn reload_handles_missing_and_invalid_json() {
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// empty (no value set) → defaults
|
||||
hbb_common::config::LocalConfig::set_option(LOCAL_CONFIG_KEY.into(), String::new());
|
||||
reload_from_config();
|
||||
reload_from_raw("");
|
||||
let b = current();
|
||||
assert!(!b.enabled);
|
||||
assert!(b.bindings.is_empty());
|
||||
|
||||
// invalid JSON → defaults (no panic)
|
||||
hbb_common::config::LocalConfig::set_option(LOCAL_CONFIG_KEY.into(), "not json".into());
|
||||
reload_from_config();
|
||||
reload_from_raw("not json");
|
||||
let b = current();
|
||||
assert!(!b.enabled);
|
||||
}
|
||||
@@ -838,7 +957,6 @@ mod tests {
|
||||
};
|
||||
|
||||
assert!(dispatch(&make_press(Key::KeyP)));
|
||||
assert!(super::super::TO_RELEASE.lock().unwrap().is_empty());
|
||||
{
|
||||
let state = super::super::MODIFIERS_STATE.lock().unwrap();
|
||||
for k in chord {
|
||||
@@ -909,6 +1027,198 @@ mod tests {
|
||||
assert!(!dispatch(&SID_A, &make_release(Key::KeyP)), "closing A drops its keys");
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[test]
|
||||
fn dispatch_consumes_fired_key_after_session_switch() {
|
||||
use rdev::Key;
|
||||
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let chord = enable_defaults_and_hold_chord();
|
||||
let previous_session = crate::flutter::get_cur_session_id();
|
||||
crate::flutter::set_cur_session_id(SID_A);
|
||||
let dispatch = |e: &rdev::Event| {
|
||||
try_dispatch(None, e, "map", || "windows".into(), |_| {})
|
||||
};
|
||||
|
||||
assert!(dispatch(&make_press(Key::KeyP)));
|
||||
crate::flutter::set_cur_session_id(SID_B);
|
||||
release_chord(chord);
|
||||
assert!(dispatch(&make_press(Key::KeyP)), "repeat stays consumed in the new tab");
|
||||
clear_fired_keys(&SID_A);
|
||||
crate::flutter::set_cur_session_id(SID_A);
|
||||
assert!(dispatch(&make_press(Key::KeyP)), "repeat stays consumed after switching back");
|
||||
crate::flutter::set_cur_session_id(SID_B);
|
||||
assert!(dispatch(&make_release(Key::KeyP)), "release stays consumed in the new tab");
|
||||
crate::flutter::set_cur_session_id(SID_A);
|
||||
assert!(!dispatch(&make_press(Key::KeyP)), "new press is not a stale repeat");
|
||||
crate::flutter::set_cur_session_id(previous_session);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[test]
|
||||
fn dispatch_preserves_modifier_cleanup_on_leave() {
|
||||
use rdev::Key;
|
||||
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let chord = enable_defaults_and_hold_chord();
|
||||
assert!(try_dispatch(
|
||||
Some(&SID_A), &make_press(Key::KeyP), "map", || "windows".into(), |_| {}
|
||||
));
|
||||
super::super::release_remote_keys("map");
|
||||
assert_eq!(
|
||||
super::super::client::get_modifiers_state(false, false, false, false),
|
||||
(false, false, false, false),
|
||||
"leaving the remote image must clear modifiers even after a shortcut"
|
||||
);
|
||||
release_chord(chord);
|
||||
clear_fired_keys(&SID_A);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[test]
|
||||
fn repeated_shortcuts_leave_remote_modifiers_released() {
|
||||
use rdev::Key;
|
||||
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let chord = enable_defaults_and_hold_chord();
|
||||
let remote_held = std::cell::RefCell::new(
|
||||
chord.into_iter().collect::<std::collections::HashSet<_>>()
|
||||
);
|
||||
for key in [Key::KeyP, Key::KeyC] {
|
||||
assert!(try_dispatch(
|
||||
Some(&SID_A),
|
||||
&make_press(key),
|
||||
"map",
|
||||
|| "windows".into(),
|
||||
|event| {
|
||||
let key = rdev::win_key_from_scancode(event.chr());
|
||||
assert!(chord.contains(&key), "only held modifiers are released");
|
||||
if event.down {
|
||||
remote_held.borrow_mut().insert(key);
|
||||
} else {
|
||||
remote_held.borrow_mut().remove(&key);
|
||||
}
|
||||
},
|
||||
));
|
||||
assert!(remote_held.borrow().is_empty());
|
||||
}
|
||||
release_chord(chord);
|
||||
clear_fired_keys(&SID_A);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
fn shortcut_followed_by_c(release_primary: bool) -> (rdev::Key, Vec<(rdev::Key, bool)>) {
|
||||
use base::message_proto::KeyboardMode;
|
||||
use rdev::Key;
|
||||
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
clear_fired_keys(&SID_A);
|
||||
*CACHE.write().unwrap() = Arc::new(Bindings {
|
||||
enabled: true,
|
||||
pass_through: false,
|
||||
bindings: vec![Binding {
|
||||
action: action_id::SCREENSHOT.into(),
|
||||
mods: vec![Modifier::Primary],
|
||||
key: "p".into(),
|
||||
}],
|
||||
});
|
||||
let primary = if cfg!(any(target_os = "macos", target_os = "ios")) {
|
||||
Key::MetaLeft
|
||||
} else {
|
||||
Key::ControlLeft
|
||||
};
|
||||
let sent = std::cell::RefCell::new(Vec::new());
|
||||
let send = |event: &base::message_proto::KeyEvent| {
|
||||
sent.borrow_mut().push((rdev::win_key_from_scancode(event.chr()), event.down));
|
||||
};
|
||||
let handle = |event: &rdev::Event| {
|
||||
if !try_dispatch(Some(&SID_A), event, "map", || "windows".into(), &send) {
|
||||
for key_event in super::super::event_to_key_events(
|
||||
"windows".into(), event, KeyboardMode::Map, Some(0)
|
||||
) {
|
||||
send(&key_event);
|
||||
}
|
||||
}
|
||||
};
|
||||
handle(&make_press(primary));
|
||||
handle(&make_press(Key::KeyP));
|
||||
handle(&make_release(Key::KeyP));
|
||||
if release_primary {
|
||||
handle(&make_release(primary));
|
||||
}
|
||||
sent.borrow_mut().clear();
|
||||
handle(&make_press(Key::KeyC));
|
||||
let result = sent.borrow().clone();
|
||||
handle(&make_release(Key::KeyC));
|
||||
handle(&make_release(primary));
|
||||
clear_fired_keys(&SID_A);
|
||||
(primary, result)
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[test]
|
||||
fn unbound_key_restores_modifiers_held_after_shortcut() {
|
||||
let (primary, sent) = shortcut_followed_by_c(false);
|
||||
assert_eq!(sent, vec![(primary, true), (rdev::Key::KeyC, true)]);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
#[test]
|
||||
fn unbound_key_does_not_restore_released_modifiers() {
|
||||
let (_, sent) = shortcut_followed_by_c(true);
|
||||
assert_eq!(sent, vec![(rdev::Key::KeyC, true)]);
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "flutter", not(any(target_os = "android", target_os = "ios"))))]
|
||||
#[test]
|
||||
fn view_only_preserves_rdev_shortcut_keys() {
|
||||
use rdev::Key;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let previous = super::super::IS_RDEV_ENABLED.swap(true, Ordering::SeqCst);
|
||||
let chord = enable_defaults_and_hold_chord();
|
||||
assert!(try_dispatch(
|
||||
Some(&SID_A), &make_press(Key::KeyP), "map", || "windows".into(), |_| {}
|
||||
));
|
||||
enter_view_only(&SID_A);
|
||||
let action = match_event(&make_press(Key::KeyC));
|
||||
let fired = fired_keys_of(&SID_A).contains(&Key::KeyP);
|
||||
super::super::IS_RDEV_ENABLED.store(previous, Ordering::SeqCst);
|
||||
release_chord(chord);
|
||||
clear_session_state(&SID_A);
|
||||
assert_eq!(action.as_deref(), Some(action_id::TOGGLE_CHAT));
|
||||
assert!(fired, "rdev still receives the held shortcut key's release");
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "flutter", not(any(target_os = "android", target_os = "ios"))))]
|
||||
#[test]
|
||||
fn view_only_clears_flutter_shortcut_keys_and_modifiers() {
|
||||
use rdev::Key;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let previous = super::super::IS_RDEV_ENABLED.swap(false, Ordering::SeqCst);
|
||||
let chord = enable_defaults_and_hold_chord();
|
||||
assert!(try_dispatch(
|
||||
Some(&SID_A), &make_press(Key::KeyP), "map", || "windows".into(), |_| {}
|
||||
));
|
||||
clear_session_state(&SID_B);
|
||||
assert_eq!(match_event(&make_press(Key::KeyC)).as_deref(), Some(action_id::TOGGLE_CHAT));
|
||||
enter_view_only(&SID_A);
|
||||
super::super::IS_RDEV_ENABLED.store(previous, Ordering::SeqCst);
|
||||
assert!(fired_keys_of(&SID_A).is_empty());
|
||||
assert_eq!(
|
||||
super::super::client::get_modifiers_state(false, false, false, false),
|
||||
(false, false, false, false)
|
||||
);
|
||||
assert!(!try_dispatch(
|
||||
Some(&SID_A), &make_press(Key::KeyP), "map", || "windows".into(),
|
||||
|_| panic!("view-only reset must not replay old modifiers")
|
||||
));
|
||||
release_chord(chord);
|
||||
}
|
||||
|
||||
#[cfg(feature = "flutter")]
|
||||
const SID_A: hbb_common::SessionID = hbb_common::SessionID::from_u128(0xA);
|
||||
#[cfg(feature = "flutter")]
|
||||
@@ -929,8 +1239,8 @@ mod tests {
|
||||
pass_through: false,
|
||||
bindings: default_bindings(),
|
||||
});
|
||||
clear_fired_keys(&SID_A);
|
||||
clear_fired_keys(&SID_B);
|
||||
clear_session_state(&SID_A);
|
||||
clear_session_state(&SID_B);
|
||||
let primary = if cfg!(any(target_os = "macos", target_os = "ios")) {
|
||||
Key::MetaLeft
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user