From 43e0762d68ae197e701f28381b38c658d10dd078 Mon Sep 17 00:00:00 2001 From: Tong Mu Date: Mon, 24 Jan 2022 12:18:07 -0800 Subject: [PATCH] [Keyboard] Key guard only on Mac (flutter/engine#30981) This PR limits the "key guarding" mechanism of the web embedding to macOS only. --- .../web_ui/lib/src/engine/initialization.dart | 3 +- .../lib/web_ui/lib/src/engine/keyboard.dart | 46 +++++++----- .../lib/src/engine/keyboard_binding.dart | 45 +++++------ .../web_ui/test/keyboard_converter_test.dart | 36 +++++++-- .../lib/web_ui/test/keyboard_test.dart | 75 +++++++++++++++++-- 5 files changed, 150 insertions(+), 55 deletions(-) diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart index 8018f14e01..7fd03c9bba 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/initialization.dart @@ -6,6 +6,7 @@ import 'dart:developer' as developer; import 'dart:html' as html; import 'dart:typed_data'; +import 'package:ui/src/engine/browser_detection.dart'; import 'package:ui/src/engine/embedder.dart'; import 'package:ui/src/engine/keyboard.dart'; import 'package:ui/src/engine/mouse_cursor.dart'; @@ -143,7 +144,7 @@ void initializeEngine() { } }; - Keyboard.initialize(); + Keyboard.initialize(onMacOs: operatingSystem == OperatingSystem.macOs); MouseCursor.initialize(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart index 0b55c8463a..316101a21a 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard.dart @@ -10,20 +10,13 @@ import '../engine.dart' show registerHotRestartListener; import 'platform_dispatcher.dart'; import 'services.dart'; -/// After a keydown is received, this is the duration we wait for a repeat event -/// before we decide to synthesize a keyup event. -/// -/// On Linux and Windows, the typical ranges for keyboard repeat delay go up to -/// 1000ms. On Mac, the range goes up to 2000ms. -const Duration _keydownCancelDuration = Duration(milliseconds: 1000); - /// Provides keyboard bindings, such as the `flutter/keyevent` channel. class Keyboard { /// Initializes the [Keyboard] singleton. /// /// Use the [instance] getter to get the singleton after calling this method. - static void initialize() { - _instance ??= Keyboard._(); + static void initialize({bool onMacOs = false}) { + _instance ??= Keyboard._(onMacOs); } /// The [Keyboard] singleton. @@ -39,7 +32,7 @@ class Keyboard { html.EventListener? _keydownListener; html.EventListener? _keyupListener; - Keyboard._() { + Keyboard._(this._onMacOs) { _keydownListener = (html.Event event) { _handleHtmlEvent(event); }; @@ -79,6 +72,20 @@ class Keyboard { /// Initializing with `0x0` which means no meta keys are pressed. int _lastMetaState = 0x0; + bool _onMacOs; + + // When the user enters a browser/system shortcut (e.g. `cmd+alt+i`) on macOS, + // the browser doesn't send a keyup for it. This puts the framework in a + // corrupt state because it thinks the key was never released. + // + // To avoid this, we rely on the fact that browsers send repeat events + // while the key is held down by the user. If we don't receive a repeat + // event within a specific duration ([_kKeydownCancelDurationMac]) we assume + // the user has released the key and we synthesize a keyup event. + bool _shouldDoKeyGuard() { + return _onMacOs; + } + void _handleHtmlEvent(html.Event event) { if (event is! html.KeyboardEvent) { return; @@ -88,21 +95,13 @@ class Keyboard { final String timerKey = keyboardEvent.code!; // Don't handle synthesizing a keyup event for modifier keys - if (!_isModifierKey(event)) { - // When the user enters a browser/system shortcut (e.g. `cmd+alt+i`) the - // browser doesn't send a keyup for it. This puts the framework in a - // corrupt state because it thinks the key was never released. - // - // To avoid this, we rely on the fact that browsers send repeat events - // while the key is held down by the user. If we don't receive a repeat - // event within a specific duration ([_keydownCancelDuration]) we assume - // the user has released the key and we synthesize a keyup event. + if (!_isModifierKey(event) && _shouldDoKeyGuard()) { _keydownTimers[timerKey]?.cancel(); // Only keys affected by modifiers, require synthesizing // because the browser always sends a keyup event otherwise if (event.type == 'keydown' && _isAffectedByModifiers(event)) { - _keydownTimers[timerKey] = Timer(_keydownCancelDuration, () { + _keydownTimers[timerKey] = Timer(_kKeydownCancelDurationMac, () { _keydownTimers.remove(timerKey); _synthesizeKeyup(event); }); @@ -161,6 +160,13 @@ class Keyboard { EnginePlatformDispatcher.instance.invokeOnPlatformMessage('flutter/keyevent', _messageCodec.encodeMessage(eventData), _noopCallback); } + + /// After a keydown is received, this is the duration we wait for a repeat event + /// before we decide to synthesize a keyup event. + /// + /// This value is only for macOS, where the keyboard repeat delay goes up to + /// 2000ms. + static const Duration _kKeydownCancelDurationMac = Duration(milliseconds: 2000); } const int _modifierNone = 0x00; diff --git a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart index 63e94eb819..7efd102023 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/engine/keyboard_binding.dart @@ -43,14 +43,6 @@ final Map _kLogicalKeyToModifierGetter = event.metaKey, }; -// After a keydown is received, this is the duration we wait for a repeat event -// before we decide to synthesize a keyup event. -// -// On Linux and Windows, the typical ranges for keyboard repeat delay go up to -// 1000ms. On Mac, the range goes up to 2000ms. -const Duration _kKeydownCancelDurationNormal = Duration(milliseconds: 1000); -const Duration _kKeydownCancelDurationMacOs = Duration(milliseconds: 2000); - // ASCII for a, z, A, and Z const int _kCharLowerA = 0x61; const int _kCharLowerZ = 0x7a; @@ -230,7 +222,26 @@ class KeyboardConverter { return onMacOs; } - Duration get _keydownCancelDuration => onMacOs ? _kKeydownCancelDurationMacOs : _kKeydownCancelDurationNormal; + // ## About Key guards + // + // When the user enters a browser/system shortcut (e.g. `Cmd+Alt+i`) the + // browser doesn't send a keyup for it. This puts the framework in a corrupt + // state because it thinks the key was never released. + // + // To avoid this, we rely on the fact that browsers send repeat events + // while the key is held down by the user. If we don't receive a repeat + // event within a specific duration ([_keydownCancelDurationMac]) we assume + // the user has released the key and we synthesize a keyup event. + bool _shouldDoKeyGuard() { + return onMacOs; + } + + /// After a keydown is received, this is the duration we wait for a repeat event + /// before we decide to synthesize a keyup event. + /// + /// This value is only for macOS, where the keyboard repeat delay goes up to + /// 2000ms. + static const Duration _kKeydownCancelDurationMac = Duration(milliseconds: 2000); static int _getPhysicalCode(String code) { return kWebToPhysicalKey[code] ?? (code.hashCode + _kWebKeyIdPlane); @@ -309,23 +320,15 @@ class KeyboardConverter { return () { canceled = true; }; } - // ## About Key guards - // - // When the user enters a browser/system shortcut (e.g. `cmd+alt+i`) the - // browser doesn't send a keyup for it. This puts the framework in a corrupt - // state because it thinks the key was never released. - // - // To avoid this, we rely on the fact that browsers send repeat events - // while the key is held down by the user. If we don't receive a repeat - // event within a specific duration ([_keydownCancelDuration]) we assume - // the user has released the key and we synthesize a keyup event. final Map _keyGuards = {}; // Call this method on the down or repeated event of a non-modifier key. void _startGuardingKey(int physicalKey, int logicalKey, Duration currentTimeStamp) { + if (!_shouldDoKeyGuard()) + return; final _VoidCallback cancelingCallback = _scheduleAsyncEvent( - _keydownCancelDuration, + _kKeydownCancelDurationMac, () => ui.KeyData( - timeStamp: currentTimeStamp + _keydownCancelDuration, + timeStamp: currentTimeStamp + _kKeydownCancelDurationMac, type: ui.KeyEventType.up, physical: physicalKey, logical: logicalKey, diff --git a/engine/src/flutter/lib/web_ui/test/keyboard_converter_test.dart b/engine/src/flutter/lib/web_ui/test/keyboard_converter_test.dart index 0e9aae79ff..aafcbabcfe 100644 --- a/engine/src/flutter/lib/web_ui/test/keyboard_converter_test.dart +++ b/engine/src/flutter/lib/web_ui/test/keyboard_converter_test.dart @@ -615,12 +615,12 @@ void testMain() { ); }); - testFakeAsync('Key guards: key down events are guarded', (FakeAsync async) { + testFakeAsync('Key guards: key down events are guarded on macOS', (FakeAsync async) { final List keyDataList = []; final KeyboardConverter converter = KeyboardConverter((ui.KeyData key) { keyDataList.add(key); return true; - }); + }, onMacOs: true); converter.handleEvent(keyDownEvent('MetaLeft', 'Meta', kMeta, kLocationLeft)..timeStamp = 100); async.elapse(const Duration(milliseconds: 100)); @@ -639,7 +639,7 @@ void testMain() { async.elapse(const Duration(milliseconds: 2500)); expectKeyData(keyDataList.last, - timeStamp: const Duration(milliseconds: 1200), + timeStamp: const Duration(milliseconds: 2200), type: ui.KeyEventType.up, physical: kPhysicalKeyA, logical: kLogicalKeyA, @@ -684,7 +684,7 @@ void testMain() { final KeyboardConverter converter = KeyboardConverter((ui.KeyData key) { keyDataList.add(key); return true; - }); + }, onMacOs: true); converter.handleEvent(keyDownEvent('MetaLeft', 'Meta', kMeta, kLocationLeft)..timeStamp = 100); async.elapse(const Duration(milliseconds: 100)); @@ -700,9 +700,9 @@ void testMain() { // Keyup of KeyA is omitted due to being a shortcut. - async.elapse(const Duration(milliseconds: 2500)); + async.elapse(const Duration(milliseconds: 2000)); expectKeyData(keyDataList.last, - timeStamp: const Duration(milliseconds: 1700), + timeStamp: const Duration(milliseconds: 2700), type: ui.KeyEventType.up, physical: kPhysicalKeyA, logical: kLogicalKeyA, @@ -799,6 +799,30 @@ void testMain() { ); }); + testFakeAsync('Key guards: key down events are not guarded on non-macOS', (FakeAsync async) { + final List keyDataList = []; + final KeyboardConverter converter = KeyboardConverter((ui.KeyData key) { + keyDataList.add(key); + return true; + }, onMacOs: false); + + converter.handleEvent(keyDownEvent('MetaLeft', 'Meta', kMeta, kLocationLeft)..timeStamp = 100); + async.elapse(const Duration(milliseconds: 100)); + + converter.handleEvent(keyDownEvent('KeyA', 'a', kMeta)..timeStamp = 200); + expectKeyData(keyDataList.last, + timeStamp: const Duration(milliseconds: 200), + type: ui.KeyEventType.down, + physical: kPhysicalKeyA, + logical: kLogicalKeyA, + character: 'a', + ); + keyDataList.clear(); + + async.elapse(const Duration(milliseconds: 2500)); + expect(keyDataList, isEmpty); + }); + testFakeAsync('Lock flags of other keys', (FakeAsync async) { final List keyDataList = []; final KeyboardConverter converter = KeyboardConverter((ui.KeyData key) { diff --git a/engine/src/flutter/lib/web_ui/test/keyboard_test.dart b/engine/src/flutter/lib/web_ui/test/keyboard_test.dart index 0d23bb9a87..8541f499fc 100644 --- a/engine/src/flutter/lib/web_ui/test/keyboard_test.dart +++ b/engine/src/flutter/lib/web_ui/test/keyboard_test.dart @@ -335,7 +335,7 @@ void testMain() { }); testFakeAsync( - 'synthesize keyup when shortcut is handled by the system', + 'On macOS, synthesize keyup when shortcut is handled by the system', (FakeAsync async) { // This can happen when the user clicks `cmd+alt+i` to open devtools. Here // is the sequence we receive from the browser in such case: @@ -344,7 +344,7 @@ void testMain() { // // There's no `keyup(i)`. The web engine is expected to synthesize a // `keyup(i)` event. - Keyboard.initialize(); + Keyboard.initialize(onMacOs: true); final List> messages = >[]; ui.window.onPlatformMessage = (String channel, ByteData? data, @@ -465,9 +465,9 @@ void testMain() { ); testFakeAsync( - 'do not synthesize keyup when we receive repeat events', + 'On macOS, do not synthesize keyup when we receive repeat events', (FakeAsync async) { - Keyboard.initialize(); + Keyboard.initialize(onMacOs: true); final List> messages = >[]; ui.window.onPlatformMessage = (String channel, ByteData? data, @@ -547,7 +547,7 @@ void testMain() { ); testFakeAsync( - 'do not synthesize keyup when keys are not affected by meta modifiers', + 'On macOS, do not synthesize keyup when keys are not affected by meta modifiers', (FakeAsync async) { Keyboard.initialize(); @@ -578,8 +578,8 @@ void testMain() { }, ); - testFakeAsync('do not synthesize keyup for meta keys', (FakeAsync async) { - Keyboard.initialize(); + testFakeAsync('On macOS, do not synthesize keyup for meta keys', (FakeAsync async) { + Keyboard.initialize(onMacOs: true); final List> messages = >[]; ui.window.onPlatformMessage = (String channel, ByteData? data, @@ -639,6 +639,67 @@ void testMain() { Keyboard.instance!.dispose(); }); + + testFakeAsync( + 'On non-macOS, do not synthesize keyup for shortcuts', + (FakeAsync async) { + Keyboard.initialize(onMacOs: false); + + final List> messages = >[]; + ui.window.onPlatformMessage = (String channel, ByteData? data, + ui.PlatformMessageResponseCallback? callback) { + messages.add(const JSONMessageCodec().decodeMessage(data) as Map); + }; + + dispatchKeyboardEvent( + 'keydown', + key: 'Meta', + code: 'MetaLeft', + location: 1, + isMetaPressed: true, + ); + dispatchKeyboardEvent( + 'keydown', + key: 'Alt', + code: 'AltLeft', + location: 1, + isMetaPressed: true, + isAltPressed: true, + ); + dispatchKeyboardEvent( + 'keydown', + key: 'i', + code: 'KeyI', + isMetaPressed: true, + isAltPressed: true, + ); + async.elapse(const Duration(milliseconds: 10)); + dispatchKeyboardEvent( + 'keyup', + key: 'Meta', + code: 'MetaLeft', + location: 1, + isAltPressed: true, + ); + dispatchKeyboardEvent( + 'keyup', + key: 'Alt', + code: 'AltLeft', + location: 1, + ); + // Notice no `keyup` for "i". + + expect(messages, hasLength(5)); + messages.clear(); + + // Never synthesize keyup events. + async.elapse(const Duration(seconds: 3)); + expect(messages, isEmpty); + + Keyboard.instance!.dispose(); + }, + ); + }); }