diff --git a/flutter/lib/common/widgets/keyboard_shortcuts/shortcut_constants.dart b/flutter/lib/common/widgets/keyboard_shortcuts/shortcut_constants.dart index 002644601..aa162c5d1 100644 --- a/flutter/lib/common/widgets/keyboard_shortcuts/shortcut_constants.dart +++ b/flutter/lib/common/widgets/keyboard_shortcuts/shortcut_constants.dart @@ -107,6 +107,9 @@ final List> kDefaultShortcutBindings = [ [kShortcutActionSwitchDisplayPrev, 'arrow_left'], [kShortcutActionScreenshot, 'p'], [kShortcutActionToggleShowRemoteCursor, 'm'], + // The tested iPad/Bluetooth keyboard setup did not deliver the complete + // Cmd+Option+Shift+S chord, also in Safari. Other physical keyboards are + // unverified; Mute can be rebound to a chord that reaches the app. [kShortcutActionToggleMute, 's'], [kShortcutActionToggleBlockInput, 'i'], [kShortcutActionToggleChat, 'c'], diff --git a/flutter/lib/mobile/pages/remote_page.dart b/flutter/lib/mobile/pages/remote_page.dart index fdf9fe04f..7ba163287 100644 --- a/flutter/lib/mobile/pages/remote_page.dart +++ b/flutter/lib/mobile/pages/remote_page.dart @@ -41,9 +41,9 @@ void _disableAndroidSoftKeyboard({bool? isKeyboardVisible}) { } } -bool handleMobileChatKeyEvent(KeyEvent event, - {required bool chatFocused, required InputModel inputModel}) { - if (chatFocused && +bool handleMobileLocalKeyEvent(KeyEvent event, + {required bool remoteFocused, required InputModel inputModel}) { + if (!remoteFocused && event is KeyUpEvent && const [ PhysicalKeyboardKey.controlLeft, @@ -55,7 +55,8 @@ bool handleMobileChatKeyEvent(KeyEvent event, PhysicalKeyboardKey.metaLeft, PhysicalKeyboardKey.metaRight, ].contains(event.physicalKey)) { - // Chat owns focus, but the remote input path still owns these modifiers. + // Local UI may consume key-ups while the remote input path still owns + // the modifiers pressed before focus moved. inputModel.handleKeyEvent(event); } return false; @@ -128,7 +129,7 @@ class _RemotePageState extends State with WidgetsBindingObserver { }); WakelockManager.enable(_uniqueKey); _physicalFocusNode.requestFocus(); - HardwareKeyboard.instance.addHandler(_handleChatKeyEvent); + HardwareKeyboard.instance.addHandler(_handleLocalKeyEvent); gFFI.inputModel.listenToMouse(true); gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId); keyboardSubscription = @@ -177,7 +178,7 @@ class _RemotePageState extends State with WidgetsBindingObserver { @override Future dispose() async { - HardwareKeyboard.instance.removeHandler(_handleChatKeyEvent); + HardwareKeyboard.instance.removeHandler(_handleLocalKeyEvent); WidgetsBinding.instance.removeObserver(this); // Close the session up-front. `gFFI.close()` below only calls `sessionClose` // after several awaits (canvas save, image update, the `enable_soft_keyboard` @@ -570,8 +571,8 @@ class _RemotePageState extends State with WidgetsBindingObserver { ); } - bool _handleChatKeyEvent(KeyEvent event) => handleMobileChatKeyEvent(event, - chatFocused: gFFI.chatModel.inputNode.hasFocus, inputModel: inputModel); + bool _handleLocalKeyEvent(KeyEvent event) => handleMobileLocalKeyEvent(event, + remoteFocused: _physicalFocusNode.hasPrimaryFocus, inputModel: inputModel); Widget getRawPointerAndKeyBody(Widget child) { final ffiModel = Provider.of(context); diff --git a/flutter/lib/models/local_flutter_shortcuts.dart b/flutter/lib/models/local_flutter_shortcuts.dart index 38840eb4c..3147f440a 100644 --- a/flutter/lib/models/local_flutter_shortcuts.dart +++ b/flutter/lib/models/local_flutter_shortcuts.dart @@ -17,6 +17,8 @@ class LocalFlutterShortcutDispatcher { // session that fired them. See [kShortcutActionsRunOnKeyUp]. static final _keyUpActions = {}; + static final _clipboardModifierReleases = + )>{}; final _releasedModifiers = {}; bool _viewOnlyShortcutPending = false; int _generation = 0; @@ -27,6 +29,8 @@ class LocalFlutterShortcutDispatcher { /// stay owned until their release, whichever session receives it. void clear() { _keyUpActions.removeWhere((_, pending) => identical(pending.$1, this)); + _clipboardModifierReleases + .removeWhere((_, pending) => identical(pending.$1, this)); _releasedModifiers.clear(); _viewOnlyShortcutPending = false; _generation++; @@ -36,6 +40,7 @@ class LocalFlutterShortcutDispatcher { static void resetFiredKeys() { _firedKeys.clear(); _keyUpActions.clear(); + _clipboardModifierReleases.clear(); } void recordReleasedModifiers(Iterable keys) { @@ -119,9 +124,11 @@ class LocalFlutterShortcutDispatcher { if (up) { if (!_firedKeys.remove(key)) return false; final pending = _keyUpActions.remove(key); + final release = _clipboardModifierReleases.remove(key)?.$2; if (pending != null) { final (owner, action) = pending; - unawaited(owner._trigger(action, null)); + unawaited( + owner._trigger(action, release == null ? null : () => release)); } return true; } @@ -131,13 +138,24 @@ class LocalFlutterShortcutDispatcher { if (action == null) return false; _firedKeys.add(key); if (viewOnly) _viewOnlyShortcutPending = true; - final runOnKeyUp = kShortcutActionsRunOnKeyUp.contains(action); + // Web clipboard reads need the key-down's browser user activation. + final runOnKeyUp = kShortcutActionsRunOnKeyUp.contains(action) || + (!kIsWeb && action == kShortcutActionSendClipboardKeystrokes); if (runOnKeyUp) { _keyUpActions[key] = (this, action); } else { _keyUpActions.remove(key); } - unawaited(_trigger(runOnKeyUp ? null : action, releaseModifiers)); + if (runOnKeyUp && + action == kShortcutActionSendClipboardKeystrokes && + releaseModifiers != null) { + // The release can precede completion of the asynchronous FFI calls. + final release = Future.sync(releaseModifiers); + _clipboardModifierReleases[key] = (this, release); + unawaited(_trigger(null, () => release)); + } else { + unawaited(_trigger(runOnKeyUp ? null : action, releaseModifiers)); + } return true; } diff --git a/flutter/test/local_flutter_shortcuts_test.dart b/flutter/test/local_flutter_shortcuts_test.dart index de46188bc..c218029b5 100644 --- a/flutter/test/local_flutter_shortcuts_test.dart +++ b/flutter/test/local_flutter_shortcuts_test.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_hbb/common/widgets/keyboard_shortcuts/shortcut_constants.dart'; @@ -192,6 +193,96 @@ void main() { expect(actions, ['screenshot']); }); + test('native clipboard prompt can be repeated immediately after cancelling', + () async { + var dialogOpen = false; + var prompts = 0; + final dispatcher = _ShortcutHarness( + match: (_) => kShortcutActionSendClipboardKeystrokes, + releaseModifiers: () async {}, + onTriggered: (_) { + dialogOpen = true; + prompts++; + }, + ); + bool route(KeyEvent event) => !dialogOpen && dispatcher.tryDispatch(event); + + for (var attempt = 1; attempt <= 2; attempt++) { + expect(route(down(PhysicalKeyboardKey.keyV)), isTrue); + await Future.value(); + expect(dialogOpen, isFalse, + reason: 'the local dialog must not consume the trigger release'); + expect(route(repeat(PhysicalKeyboardKey.keyV)), isTrue); + expect(route(up(PhysicalKeyboardKey.keyV)), isTrue); + await Future.value(); + expect(dialogOpen, isTrue); + expect(prompts, attempt); + dialogOpen = false; + } + }, skip: kIsWeb); + + test('native clipboard waits for outstanding remote modifier releases', + () async { + final released = Completer(); + final actions = []; + final dispatcher = _ShortcutHarness( + match: (_) => kShortcutActionSendClipboardKeystrokes, + releaseModifiers: () => released.future, + onTriggered: actions.add, + ); + expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue); + expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue); + await Future.value(); + expect(actions, isEmpty, + reason: 'clipboard input must follow the remote modifier releases'); + released.complete(); + await Future.value(); + expect(actions, [kShortcutActionSendClipboardKeystrokes]); + }, skip: kIsWeb); + + test('Web clipboard still runs on key down for browser activation', () async { + final actions = []; + final dispatcher = _ShortcutHarness( + match: (_) => kShortcutActionSendClipboardKeystrokes, + releaseModifiers: () async {}, + onTriggered: actions.add, + ); + expect(dispatcher.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue); + await Future.value(); + expect(actions, [kShortcutActionSendClipboardKeystrokes]); + expect(dispatcher.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue); + expect(actions, [kShortcutActionSendClipboardKeystrokes]); + }, skip: !kIsWeb); + + test('closing a clipboard owner preserves another session release', () async { + final closingRelease = Completer(); + final nextRelease = Completer(); + final actions = []; + final closing = _ShortcutHarness( + match: (_) => kShortcutActionSendClipboardKeystrokes, + releaseModifiers: () => closingRelease.future, + onTriggered: (_) => actions.add('closing'), + ); + final next = _ShortcutHarness( + match: (_) => kShortcutActionSendClipboardKeystrokes, + releaseModifiers: () => nextRelease.future, + onTriggered: (_) => actions.add('next'), + ); + + expect(closing.tryDispatch(down(PhysicalKeyboardKey.keyV)), isTrue); + expect(next.tryDispatch(down(PhysicalKeyboardKey.keyC)), isTrue); + closing.clear(); + expect(next.tryDispatch(up(PhysicalKeyboardKey.keyC)), isTrue); + closingRelease.complete(); + await Future.value(); + expect(actions, isEmpty, + reason: 'the live session still awaits its own modifier release'); + expect(next.tryDispatch(up(PhysicalKeyboardKey.keyV)), isTrue); + nextRelease.complete(); + await Future.value(); + expect(actions, ['next']); + }, skip: kIsWeb); + test('closing the session drops its pending action but keeps the fired key', () async { // Close tab is itself a shortcut: the session that matched the key is diff --git a/src/keyboard/shortcuts.rs b/src/keyboard/shortcuts.rs index 8847e957b..9c1048a15 100644 --- a/src/keyboard/shortcuts.rs +++ b/src/keyboard/shortcuts.rs @@ -355,7 +355,9 @@ const RELEASE_ACTION_IDS: &[&str] = &[ ]; pub fn runs_on_release(action_id: &str) -> bool { - RELEASE_ACTION_IDS.contains(&action_id) + // A clipboard consent dialog can consume the trigger release. Web keeps + // this action on key-down for browser clipboard user activation. + action_id == action_id::SEND_CLIPBOARD_KEYSTROKES || RELEASE_ACTION_IDS.contains(&action_id) } /// Forget the modifiers a session released on its remote and the actions it @@ -1337,6 +1339,39 @@ mod tests { release_chord(chord); } + #[cfg(feature = "flutter")] + #[test] + fn clipboard_prompt_waits_for_release_before_taking_focus() { + use rdev::Key; + + let _guard = CACHE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let chord = enable_defaults_and_hold_chord(); + *CACHE.write().unwrap() = Arc::new(Bindings { + enabled: true, + pass_through: false, + bindings: vec![Binding { + action: action_id::SEND_CLIPBOARD_KEYSTROKES.into(), + mods: vec![Modifier::Primary, Modifier::Alt, Modifier::Shift], + key: "v".into(), + }], + }); + let dispatch = |event: &rdev::Event| { + try_dispatch(Some(&SID_A), event, "map", || "linux".into(), |_| {}) + }; + for _ in 0..2 { + assert!(dispatch(&make_press(Key::KeyV))); + assert_eq!( + RELEASE_ACTIONS.lock().unwrap().get(&Key::KeyV).cloned(), + Some((SID_A, action_id::SEND_CLIPBOARD_KEYSTROKES.to_owned())), + "the prompt must not take focus before the trigger release" + ); + assert!(dispatch(&make_release(Key::KeyV))); + assert!(!fired_keys().contains(&Key::KeyV)); + assert!(!RELEASE_ACTIONS.lock().unwrap().contains_key(&Key::KeyV)); + } + release_chord(chord); + } + #[cfg(feature = "flutter")] const SID_A: hbb_common::SessionID = hbb_common::SessionID::from_u128(0xA); #[cfg(feature = "flutter")]