diff --git a/engine/src/flutter/ci/licenses_golden/licenses_flutter b/engine/src/flutter/ci/licenses_golden/licenses_flutter index 92d90d728a..025e84d5de 100755 --- a/engine/src/flutter/ci/licenses_golden/licenses_flutter +++ b/engine/src/flutter/ci/licenses_golden/licenses_flutter @@ -1046,9 +1046,15 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryM FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryMessengerRelayTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterCallbackCache_Internal.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProjectTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroup.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineGroupTest.mm @@ -1057,7 +1063,14 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineT FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngineTest_mrc.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Test.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterHeadlessDartRunner.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterObservatoryPublisher.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterObservatoryPublisher.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h @@ -1070,7 +1083,7 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatfor FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate.mm -FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.m +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.mm @@ -1078,7 +1091,9 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterRestora FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm -FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterUmbrellaImport.m FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterView.mm @@ -1087,6 +1102,8 @@ FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewCon FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/FlutterViewTest.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/IOKit.h +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.mm +FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.mm FILE: ../../../flutter/shell/platform/darwin/ios/framework/Source/SemanticsObjectTest.mm @@ -1228,7 +1245,7 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterViewC FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.mm FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.mm -FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_internal.h +FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/MacOSGLContextSwitch.h FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/MacOSGLContextSwitch.mm FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/fixtures/flutter_desktop_test.dart diff --git a/engine/src/flutter/lib/ui/key.dart b/engine/src/flutter/lib/ui/key.dart index a6e3c6bdd4..50e07703fb 100644 --- a/engine/src/flutter/lib/ui/key.dart +++ b/engine/src/flutter/lib/ui/key.dart @@ -80,9 +80,78 @@ class KeyData { /// [KeyRepeatEvent] is never synthesized. final bool synthesized; + // Returns the bits that are not included in [valueMask], shifted to the + // right. + // + // For example, if the input is 0x12abcdabcd, then the result is 0x12. + // + // This is mostly equivalent to a right shift, resolving the problem that + // JavaScript only support 32-bit bitwise operations and needs to use division + // instead. + static int _nonValueBits(int n) { + const int valueMask = 0x000FFFFFFFF; + // `n >> valueMaskWidth` is equivalent to `n / divisorForValueMask`. + const int divisorForValueMask = valueMask + 1; + const int valueMaskWidth = 32; + + // Equivalent to assert(divisorForValueMask == (1 << valueMaskWidth)). + const int _firstDivisorWidth = 28; + assert(divisorForValueMask == + (1 << _firstDivisorWidth) * (1 << (valueMaskWidth - _firstDivisorWidth))); + + // JS only supports up to 2^53 - 1, therefore non-value bits can only + // contain (maxSafeIntegerWidth - valueMaskWidth) bits. + const int maxSafeIntegerWidth = 52; + const int nonValueMask = (1 << (maxSafeIntegerWidth - valueMaskWidth)) - 1; + + if (identical(0, 0.0)) { // Detects if we are on the web. + return (n / divisorForValueMask).floor() & nonValueMask; + } else { + return (n >> valueMaskWidth) & nonValueMask; + } + } + + String _logicalToString() { + String result = '0x${logical.toRadixString(16)}'; + final int nonValueBits = _nonValueBits(logical); + if (nonValueBits & 0x0FF == 0x000) { + result += '(Unicode)'; + } + if (nonValueBits & 0x0FF == 0x001) { + result += '(HID)'; + } + if (nonValueBits & 0x100 != 0x000) { + result += '(auto)'; + } + if (nonValueBits & 0x200 != 0x000) { + result += '(synonym)'; + } + return result; + } + + String? _escapeCharacter() { + if (character == null) { + return character ?? ''; + } + switch (character!) { + case '\n': + return r'"\n"'; + case '\t': + return r'"\t"'; + case '\r': + return r'"\r"'; + case '\b': + return r'"\b"'; + case '\f': + return r'"\f"'; + default: + return '"$character"'; + } + } + @override - String toString() => 'KeyData(type: ${_typeToString(type)}, physical: 0x${physical.toRadixString(16)}, ' - 'logical: 0x${logical.toRadixString(16)}, character: $character)'; + String toString() => 'KeyData(key ${_typeToString(type)}, physical: 0x${physical.toRadixString(16)}, ' + 'logical: ${_logicalToString()}, character: ${_escapeCharacter()})'; /// Returns a complete textual description of the information in this object. String toStringFull() { @@ -91,7 +160,7 @@ class KeyData { 'timeStamp: $timeStamp, ' 'physical: 0x${physical.toRadixString(16)}, ' 'logical: 0x${logical.toRadixString(16)}, ' - 'character: $character, ' + 'character: ${_escapeCharacter()}, ' 'synthesized: $synthesized' ')'; } diff --git a/engine/src/flutter/lib/ui/platform_dispatcher.dart b/engine/src/flutter/lib/ui/platform_dispatcher.dart index 40814c93a2..4f2ce29116 100644 --- a/engine/src/flutter/lib/ui/platform_dispatcher.dart +++ b/engine/src/flutter/lib/ui/platform_dispatcher.dart @@ -32,6 +32,9 @@ typedef PointerDataPacketCallback = void Function(PointerDataPacket packet); typedef _KeyDataResponseCallback = void Function(int responseId, bool handled); /// Signature for [PlatformDispatcher.onKeyData]. +/// +/// The callback should return true if the key event has been handled by the +/// framework and should not be propagated further. typedef KeyDataCallback = bool Function(KeyData data); /// Signature for [PlatformDispatcher.onSemanticsAction]. @@ -346,6 +349,9 @@ class PlatformDispatcher { /// /// The framework invokes this callback in the same zone in which the callback /// was set. + /// + /// The callback should return true if the key event has been handled by the + /// framework and should not be propagated further. KeyDataCallback? get onKeyData => _onKeyData; KeyDataCallback? _onKeyData; Zone _onKeyDataZone = Zone.root; diff --git a/engine/src/flutter/lib/ui/window/platform_configuration.cc b/engine/src/flutter/lib/ui/window/platform_configuration.cc index ecd0415e3e..8a5a047c3b 100644 --- a/engine/src/flutter/lib/ui/window/platform_configuration.cc +++ b/engine/src/flutter/lib/ui/window/platform_configuration.cc @@ -455,7 +455,13 @@ void PlatformConfiguration::CompleteKeyDataResponse(uint64_t response_id, } KeyDataResponse callback = std::move(it->second); pending_key_responses_.erase(it); - callback(handled); + // The key result callback must be called on the platform thread. This is + // mainly because iOS needs to block the platform message loop with a nested + // loop to respond to key events synchronously, and if the callback is called + // from another thread, it won't stop the nested message loop, causing a + // deadlock. + UIDartState::Current()->GetTaskRunners().GetPlatformTaskRunner()->PostTask( + [handled, callback]() { callback(handled); }); } Dart_Handle ComputePlatformResolvedLocale(Dart_Handle supportedLocalesHandle) { diff --git a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn index 7ae1e975d3..da5cf62edd 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn +++ b/engine/src/flutter/shell/platform/darwin/ios/BUILD.gn @@ -50,12 +50,20 @@ source_set("flutter_framework_source") { "framework/Source/FlutterBinaryMessengerRelay.mm", "framework/Source/FlutterCallbackCache.mm", "framework/Source/FlutterCallbackCache_Internal.h", + "framework/Source/FlutterChannelKeyResponder.h", + "framework/Source/FlutterChannelKeyResponder.mm", "framework/Source/FlutterDartProject.mm", "framework/Source/FlutterDartProject_Internal.h", + "framework/Source/FlutterEmbedderKeyResponder.h", + "framework/Source/FlutterEmbedderKeyResponder.mm", "framework/Source/FlutterEngine.mm", "framework/Source/FlutterEngineGroup.mm", "framework/Source/FlutterEngine_Internal.h", "framework/Source/FlutterHeadlessDartRunner.mm", + "framework/Source/FlutterKeyPrimaryResponder.h", + "framework/Source/FlutterKeySecondaryResponder.h", + "framework/Source/FlutterKeyboardManager.h", + "framework/Source/FlutterKeyboardManager.mm", "framework/Source/FlutterObservatoryPublisher.h", "framework/Source/FlutterObservatoryPublisher.mm", "framework/Source/FlutterOverlayView.h", @@ -71,10 +79,14 @@ source_set("flutter_framework_source") { "framework/Source/FlutterTextInputDelegate.h", "framework/Source/FlutterTextInputPlugin.h", "framework/Source/FlutterTextInputPlugin.mm", + "framework/Source/FlutterUIPressProxy.h", + "framework/Source/FlutterUIPressProxy.mm", "framework/Source/FlutterView.h", "framework/Source/FlutterView.mm", "framework/Source/FlutterViewController.mm", "framework/Source/FlutterViewController_Internal.h", + "framework/Source/KeyCodeMap.mm", + "framework/Source/KeyCodeMap_Internal.h", "framework/Source/SemanticsObject.h", "framework/Source/SemanticsObject.mm", "framework/Source/accessibility_bridge.h", @@ -146,6 +158,7 @@ source_set("flutter_framework_source") { "//flutter/shell/common", "//flutter/shell/platform/darwin/common", "//flutter/shell/platform/darwin/common:framework_shared", + "//flutter/shell/platform/embedder:embedder_as_internal_library", "//flutter/shell/profiling:profiling", "//third_party/skia", ] @@ -192,6 +205,7 @@ source_set("ios_test_flutter_mrc") { deps = [ ":flutter_framework_source", "//flutter/shell/platform/darwin/common:framework_shared", + "//flutter/shell/platform/embedder:embedder_as_internal_library", "//flutter/third_party/tonic", "//flutter/third_party/txt", "//third_party/ocmock:ocmock_shared", @@ -201,6 +215,7 @@ source_set("ios_test_flutter_mrc") { } shared_library("ios_test_flutter") { + testonly = true visibility = [ ":*" ] cflags = [ "-fvisibility=default", @@ -220,12 +235,17 @@ shared_library("ios_test_flutter") { sources = [ "framework/Source/FlutterAppDelegateTest.mm", "framework/Source/FlutterBinaryMessengerRelayTest.mm", + "framework/Source/FlutterChannelKeyResponderTest.mm", "framework/Source/FlutterDartProjectTest.mm", + "framework/Source/FlutterEmbedderKeyResponderTest.mm", "framework/Source/FlutterEngineGroupTest.mm", "framework/Source/FlutterEngineTest.mm", - "framework/Source/FlutterPluginAppLifeCycleDelegateTest.m", + "framework/Source/FlutterFakeKeyEvents.h", + "framework/Source/FlutterFakeKeyEvents.mm", + "framework/Source/FlutterKeyboardManagerTest.mm", + "framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm", "framework/Source/FlutterRestorationPluginTest.mm", - "framework/Source/FlutterTextInputPluginTest.m", + "framework/Source/FlutterTextInputPluginTest.mm", "framework/Source/FlutterViewControllerTest.mm", "framework/Source/SemanticsObjectTest.mm", "framework/Source/connection_collection_test.mm", @@ -236,6 +256,7 @@ shared_library("ios_test_flutter") { ":ios_test_flutter_mrc", "//flutter/common:common", "//flutter/shell/platform/darwin/common:framework_shared", + "//flutter/shell/platform/embedder:embedder_as_internal_library", "//flutter/third_party/tonic", "//flutter/third_party/txt", "//third_party/ocmock:ocmock_shared", diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h new file mode 100644 index 0000000000..674b523785 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_CHANNEL_KEY_RESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_CHANNEL_KEY_RESPONDER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" + +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" + +/** + * A primary responder of |FlutterKeyboardManager| that handles events by + * sending the raw information through a method channel. + * + * This class corresponds to the RawKeyboard API in the framework. + */ +@interface FlutterChannelKeyResponder : NSObject + +/** + * Create an instance by specifying the method channel to use. + */ +- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_CHANNEL_KEY_RESPONDER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm new file mode 100644 index 0000000000..e1579024a7 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.mm @@ -0,0 +1,245 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h" + +#import +#include +#include "fml/memory/weak_ptr.h" + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" + +namespace { +// An enumeration of the modifier values that the framework expects. These are +// largely the same values as the OS (UIKeyModifierShift, etc.), but because the +// framework code expects certain values, and has additional values (like the +// sided modifier values below), we translate the iOS values to the framework +// values, and add a mask for all the possible values. +typedef NS_OPTIONS(NSInteger, KeyboardModifier) { + KeyboardModifierAlphaShift = 0x10000, + KeyboardModifierShift = 0x20000, + KeyboardModifierLeftShift = 0x02, + KeyboardModifierRightShift = 0x04, + KeyboardModifierControl = 0x40000, + KeyboardModifierLeftControl = 0x01, + KeyboardModifierRightControl = 0x2000, + KeyboardModifierOption = 0x80000, + KeyboardModifierLeftOption = 0x20, + KeyboardModifierRightOption = 0x40, + KeyboardModifierCommand = 0x100000, + KeyboardModifierLeftCommand = 0x08, + KeyboardModifierRightCommand = 0x10, + KeyboardModifierNumericPad = 0x200000, + KeyboardModifierMask = KeyboardModifierAlphaShift | KeyboardModifierShift | + KeyboardModifierLeftShift | KeyboardModifierRightShift | + KeyboardModifierControl | KeyboardModifierLeftControl | + KeyboardModifierRightControl | KeyboardModifierOption | + KeyboardModifierLeftOption | KeyboardModifierRightOption | + KeyboardModifierCommand | KeyboardModifierLeftCommand | + KeyboardModifierRightCommand | KeyboardModifierNumericPad, +}; + +/** + * Filters out some special cases in the characters field on UIKey. + */ +static NSString* getEventCharacters(NSString* characters, UIKeyboardHIDUsage keyCode) + API_AVAILABLE(ios(13.4)) { + if (characters == nil) { + return nil; + } + if ([characters length] == 0) { + return nil; + } + if (@available(iOS 13.4, *)) { + // On iOS, function keys return the UTF8 string "\^P" (with a literal '/', + // '^' and a 'P', not escaped ctrl-P) as their "characters" field. This + // isn't a valid (single) UTF8 character. Looking at the only UTF16 + // character for a function key yields a value of "16", which is a Unicode + // "SHIFT IN" character, which is just odd. UTF8 conversion of that string + // is what generates the three characters "\^P". + // + // Anyhow, we strip them all out and replace them with empty strings, since + // function keys shouldn't be printable. + if (functionKeyCodes.find(keyCode) != functionKeyCodes.end()) { + return nil; + } + } + return characters; +} + +} // namespace +@interface FlutterChannelKeyResponder () + +/** + * The channel used to communicate with Flutter. + */ +@property(nonatomic) FlutterBasicMessageChannel* channel; + +- (NSInteger)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); +- (void)updatePressedModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); + +@property(nonatomic) KeyboardModifier pressedModifiers; +@end + +@implementation FlutterChannelKeyResponder + +- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel { + self = [super init]; + if (self != nil) { + _channel = channel; + _pressedModifiers = 0; + } + return self; +} + +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return; + } + NSString* type; + switch (press.phase) { + case UIPressPhaseBegan: + type = @"keydown"; + break; + case UIPressPhaseCancelled: + // This event doesn't appear to happen on iOS, at least when switching + // apps. Maybe on tvOS? In any case, it's probably best to send a keyup if + // we do receive one, since if the event was canceled, it's likely that a + // keyup will never be received otherwise. + case UIPressPhaseEnded: + type = @"keyup"; + break; + case UIPressPhaseChanged: + // This only happens for analog devices like joysticks. + return; + case UIPressPhaseStationary: + // The entire volume of documentation of this phase on the Apple site, and + // indeed the Internet, is: + // "A button was pressed but hasn’t moved since the previous event." + // It's unclear what this is actually used for, and we've yet to see it in + // the wild. + return; + } + + NSString* characters = getEventCharacters(press.key.characters, press.key.keyCode); + NSString* charactersIgnoringModifiers = + getEventCharacters(press.key.charactersIgnoringModifiers, press.key.keyCode); + NSMutableDictionary* keyMessage = [@{ + @"keymap" : @"ios", + @"type" : type, + @"keyCode" : @(press.key.keyCode), + @"modifiers" : @([self adjustModifiers:press]), + @"characters" : characters == nil ? @"" : characters, + @"charactersIgnoringModifiers" : charactersIgnoringModifiers == nil + ? @"" + : charactersIgnoringModifiers, + } mutableCopy]; + [self.channel sendMessage:keyMessage + reply:^(id reply) { + bool handled = reply ? [[reply valueForKey:@"handled"] boolValue] : true; + callback(handled); + }]; +} + +#pragma mark - Private + +- (void)updatePressedModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return; + } + + bool isKeyDown = false; + switch (press.phase) { + case UIPressPhaseStationary: + case UIPressPhaseChanged: + // These kinds of events shouldn't get this far. + NSAssert(false, @"Unexpected key event type received in updatePressedModifiers."); + return; + case UIPressPhaseBegan: + isKeyDown = true; + break; + case UIPressPhaseCancelled: + case UIPressPhaseEnded: + isKeyDown = false; + break; + } + + void (^update)(KeyboardModifier, bool) = ^(KeyboardModifier mod, bool isOn) { + if (isOn) { + _pressedModifiers |= mod; + } else { + _pressedModifiers &= ~mod; + } + }; + switch (press.key.keyCode) { + case UIKeyboardHIDUsageKeyboardCapsLock: + update(KeyboardModifierAlphaShift, isKeyDown); + break; + case UIKeyboardHIDUsageKeypadNumLock: + update(KeyboardModifierNumericPad, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftShift: + update(KeyboardModifierLeftShift, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightShift: + update(KeyboardModifierRightShift, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftControl: + update(KeyboardModifierLeftControl, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightControl: + update(KeyboardModifierRightControl, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftAlt: + update(KeyboardModifierLeftOption, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightAlt: + update(KeyboardModifierRightOption, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardLeftGUI: + update(KeyboardModifierLeftCommand, isKeyDown); + break; + case UIKeyboardHIDUsageKeyboardRightGUI: + update(KeyboardModifierRightCommand, isKeyDown); + break; + default: + // If we didn't update any of the modifiers above, we're done. + return; + } + // Update the non-sided modifier flags to match the content of the sided ones. + update(KeyboardModifierShift, + _pressedModifiers & (KeyboardModifierRightShift | KeyboardModifierLeftShift)); + update(KeyboardModifierControl, + _pressedModifiers & (KeyboardModifierRightControl | KeyboardModifierLeftControl)); + update(KeyboardModifierOption, + _pressedModifiers & (KeyboardModifierRightOption | KeyboardModifierLeftOption)); + update(KeyboardModifierCommand, + _pressedModifiers & (KeyboardModifierRightCommand | KeyboardModifierLeftCommand)); +} + +// Because iOS differs from macOS in that the modifier flags still contain the +// flag for the key that is being released on the keyup event, we adjust the +// modifiers when the key being released is the matching modifier key itself. +- (NSInteger)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return press.key.modifierFlags; + } + + [self updatePressedModifiers:press]; + // Replace the supplied modifier flags with our computed ones. + return _pressedModifiers | (press.key.modifierFlags & ~KeyboardModifierMask); +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm new file mode 100644 index 0000000000..64999711bc --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponderTest.mm @@ -0,0 +1,141 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import +#import +#import + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" + +FLUTTER_ASSERT_ARC; + +#define XCTAssertStrEqual(value, expected) \ + XCTAssertTrue([value isEqualToString:expected], \ + @"String \"%@\" not equal to the expected value of \"%@\"", value, expected) + +namespace { +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage keyACode = (UIKeyboardHIDUsage)0x4; // KeyA iOS scan code. +} // namespace + +API_AVAILABLE(ios(13.4)) +@interface FlutterChannelKeyResponderTest : XCTestCase +@property(copy, nonatomic) FlutterUIPressProxy* testKeyDownEvent API_AVAILABLE(ios(13.4)); +@property(copy, nonatomic) FlutterUIPressProxy* testKeyUpEvent API_AVAILABLE(ios(13.4)); +@end + +@implementation FlutterChannelKeyResponderTest + +- (void)setUp API_AVAILABLE(ios(13.4)) { + _testKeyDownEvent = keyDownEvent(keyACode, 0x0, 0.0f, "a", "a"); + _testKeyUpEvent = keyUpEvent(keyACode, 0x0, 0.0f); +} + +- (void)tearDown API_AVAILABLE(ios(13.4)) { + _testKeyDownEvent = nil; + _testKeyUpEvent = nil; +} + +- (void)testBasicKeyEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* messages = [[NSMutableArray alloc] init]; + __block BOOL next_response = TRUE; + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + + id mockKeyEventChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockKeyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + [invocation retainArguments]; + NSDictionary* message; + [invocation getArgument:&message atIndex:2]; + [messages addObject:message]; + + FlutterReply callback; + [invocation getArgument:&callback atIndex:3]; + NSDictionary* keyMessage = @{ + @"handled" : @(next_response), + }; + callback(keyMessage); + })); + + // Key down + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel]; + [responder handlePress:_testKeyDownEvent + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + XCTAssertEqual([messages count], 1u); + XCTAssertEqual([messages lastObject][@"keymap"], @"ios"); + XCTAssertEqual([messages lastObject][@"type"], @"keydown"); + XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], keyACode); + XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0); + XCTAssertStrEqual([messages lastObject][@"characters"], @"a"); + XCTAssertStrEqual([messages lastObject][@"charactersIgnoringModifiers"], @"a"); + + XCTAssertEqual([responses count], 1u); + XCTAssertEqual([[responses lastObject] boolValue], TRUE); + + [messages removeAllObjects]; + [responses removeAllObjects]; + + // Key up + next_response = FALSE; + [responder handlePress:_testKeyUpEvent + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + XCTAssertEqual([messages count], 1u); + XCTAssertEqual([messages lastObject][@"keymap"], @"ios"); + XCTAssertEqual([messages lastObject][@"type"], @"keyup"); + XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], keyACode); + XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0); + + XCTAssertEqual([responses count], 1u); + XCTAssertEqual([[responses lastObject] boolValue], FALSE); + + [messages removeAllObjects]; + [responses removeAllObjects]; +} + +- (void)testEmptyResponseIsTakenAsHandled API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* messages = [[NSMutableArray alloc] init]; + __block NSMutableArray* responses = [[NSMutableArray alloc] init]; + + id mockKeyEventChannel = OCMStrictClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockKeyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + [invocation retainArguments]; + NSDictionary* message; + [invocation getArgument:&message atIndex:2]; + [messages addObject:message]; + + FlutterReply callback; + [invocation getArgument:&callback atIndex:3]; + callback(nullptr); + })); + + FlutterChannelKeyResponder* responder = + [[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel]; + [responder handlePress:_testKeyDownEvent + callback:^(BOOL handled) { + [responses addObject:@(handled)]; + }]; + + XCTAssertEqual([messages count], 1u); + XCTAssertEqual([messages lastObject][@"keymap"], @"ios"); + XCTAssertEqual([messages lastObject][@"type"], @"keydown"); + XCTAssertEqual([[messages lastObject][@"keyCode"] intValue], keyACode); + XCTAssertEqual([[messages lastObject][@"modifiers"] intValue], 0x0); + XCTAssertStrEqual([messages lastObject][@"characters"], @"a"); + XCTAssertStrEqual([messages lastObject][@"charactersIgnoringModifiers"], @"a"); + + XCTAssertEqual([responses count], 1u); + XCTAssertEqual([[responses lastObject] boolValue], TRUE); +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h new file mode 100644 index 0000000000..43bed3b656 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_EMBEDDER_KEY_RESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_EMBEDDER_KEY_RESPONDER_H_ + +#import +#import +#include "fml/memory/weak_ptr.h" + +#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/embedder/embedder.h" + +namespace { +typedef void* _VoidPtr; +} + +typedef void (^FlutterSendKeyEvent)(const FlutterKeyEvent& /* event */, + _Nullable FlutterKeyEventCallback /* callback */, + _Nullable _VoidPtr /* user_data */); + +/** + * A primary responder of |FlutterKeyboardManager| that handles events by + * sending the converted events through a Dart hook to the framework. + * + * This class interfaces with the HardwareKeyboard API in the framework. + */ +@interface FlutterEmbedderKeyResponder : NSObject + +/** + * Create an instance by specifying the function to send converted events to. + * + * The |sendEvent| is typically |FlutterEngine|'s |sendKeyEvent|. + */ +- (nonnull instancetype)initWithSendEvent:(nonnull FlutterSendKeyEvent)sendEvent; + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_EMBEDDER_KEY_RESPONDER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm new file mode 100644 index 0000000000..6c8fbf85c6 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm @@ -0,0 +1,857 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" +#include + +#import +#include +#include "fml/memory/weak_ptr.h" + +#import "KeyCodeMap_Internal.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" + +namespace { + +/** + * Isolate the least significant 1-bit. + * + * For example, + * + * * lowestSetBit(0x1010) returns 0x10. + * * lowestSetBit(0) returns 0. + */ +static NSUInteger lowestSetBit(NSUInteger bitmask) { + // This utilizes property of two's complement (negation), which propagates a + // carry bit from LSB to the lowest set bit. + return bitmask & -bitmask; +} + +/** + * Whether a string represents a control character. + */ +static bool IsControlCharacter(NSUInteger length, NSString* label) { + if (length > 1) { + return false; + } + unichar codeUnit = [label characterAtIndex:0]; + return (codeUnit <= 0x1f && codeUnit >= 0x00) || (codeUnit >= 0x7f && codeUnit <= 0x9f); +} + +/** + * Whether a string represents an unprintable key. + */ +static bool IsUnprintableKey(NSUInteger length, NSString* label) { + if (length > 1) { + return false; + } + unichar codeUnit = [label characterAtIndex:0]; + return codeUnit >= 0xF700 && codeUnit <= 0xF8FF; +} + +/** + * Returns a key code composed with a base key and a plane. + * + * Examples of unprintable keys are "NSUpArrowFunctionKey = 0xF700" or + * "NSHomeFunctionKey = 0xF729". + * + * See + * https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc + * for more information. + */ +static uint64_t KeyOfPlane(uint64_t baseKey, uint64_t plane) { + return plane | (baseKey & kValueMask); +} + +/** + * Returns the physical key for a key code. + */ +static uint64_t GetPhysicalKeyForKeyCode(UInt32 keyCode) { + auto physicalKey = keyCodeToPhysicalKey.find(keyCode); + if (physicalKey == keyCodeToPhysicalKey.end()) { + return 0; + } + return physicalKey->second; +} + +/** + * Returns the logical key for a modifier physical key. + */ +static uint64_t GetLogicalKeyForModifier(UInt32 keyCode, uint64_t hidCode) { + auto fromKeyCode = keyCodeToLogicalKey.find(keyCode); + if (fromKeyCode != keyCodeToLogicalKey.end()) { + return fromKeyCode->second; + } + return KeyOfPlane(hidCode, kHidPlane); +} + +/** + * Converts upper letters to lower letters in ASCII and extended ASCII, and + * returns as-is otherwise. + * + * Independent of locale. + */ +static uint64_t toLower(uint64_t n) { + constexpr uint64_t lower_a = 0x61; + constexpr uint64_t upper_a = 0x41; + constexpr uint64_t upper_z = 0x5a; + + constexpr uint64_t lower_a_grave = 0xe0; + constexpr uint64_t upper_a_grave = 0xc0; + constexpr uint64_t upper_thorn = 0xde; + constexpr uint64_t division = 0xf7; + + // ASCII range. + if (n >= upper_a && n <= upper_z) { + return n - upper_a + lower_a; + } + + // EASCII range. + if (n >= upper_a_grave && n <= upper_thorn && n != division) { + return n - upper_a_grave + lower_a_grave; + } + + return n; +} + +/** + * Filters out some special cases in the characters field on UIKey. + */ +static const char* getEventCharacters(NSString* characters, UIKeyboardHIDUsage keyCode) + API_AVAILABLE(ios(13.4)) { + if (characters == nil) { + return nullptr; + } + if ([characters length] == 0) { + return nullptr; + } + if (@available(iOS 13.4, *)) { + // On iOS, function keys return the UTF8 string "\^P" (with a literal '/', + // '^' and a 'P', not escaped ctrl-P) as their "characters" field. This + // isn't a valid (single) UTF8 character. Looking at the only UTF16 + // character for a function key yields a value of "16", which is a Unicode + // "SHIFT IN" character, which is just odd. UTF8 conversion of that string + // is what generates the three characters "\^P". + // + // Anyhow, we strip them all out and replace them with empty strings, since + // function keys shouldn't be printable. + if (functionKeyCodes.find(keyCode) != functionKeyCodes.end()) { + return nullptr; + } + } + return [characters UTF8String]; +} + +/** + * Returns the logical key of a KeyUp or KeyDown event. + * + * For modifier keys, use GetLogicalKeyForModifier. + */ +static uint64_t GetLogicalKeyForEvent(FlutterUIPressProxy* press, uint64_t physicalKey) + API_AVAILABLE(ios(13.4)) { + // Look to see if the keyCode can be mapped from keycode. + auto fromKeyCode = keyCodeToLogicalKey.find(press.key.keyCode); + if (fromKeyCode != keyCodeToLogicalKey.end()) { + return fromKeyCode->second; + } + const char* characters = + getEventCharacters(press.key.charactersIgnoringModifiers, press.key.keyCode); + NSString* keyLabel = + characters == nullptr ? nil : [[NSString alloc] initWithUTF8String:characters]; + NSUInteger keyLabelLength = [keyLabel length]; + // If this key is printable, generate the logical key from its Unicode + // value. Control keys such as ESC, CTRL, and SHIFT are not printable. HOME, + // DEL, arrow keys, and function keys are considered modifier function keys, + // which generate invalid Unicode scalar values. + if (keyLabelLength != 0 && !IsControlCharacter(keyLabelLength, keyLabel) && + !IsUnprintableKey(keyLabelLength, keyLabel)) { + // Given that charactersIgnoringModifiers can contain a string of arbitrary + // length, limit to a maximum of two Unicode scalar values. It is unlikely + // that a keyboard would produce a code point bigger than 32 bits, but it is + // still worth defending against this case. + NSCAssert((keyLabelLength < 2), @"Unexpected long key label: |%@|.", keyLabel); + + uint64_t codeUnit = (uint64_t)[keyLabel characterAtIndex:0]; + if (keyLabelLength == 2) { + uint64_t secondCode = (uint64_t)[keyLabel characterAtIndex:1]; + codeUnit = (codeUnit << 16) | secondCode; + } + return KeyOfPlane(toLower(codeUnit), kUnicodePlane); + } + + // Control keys like "backspace" and movement keys like arrow keys don't have + // a printable representation, but are present on the physical keyboard. Since + // there is no logical keycode map for iOS (iOS uses the keycode to + // reference physical keys), a LogicalKeyboardKey is created with the physical + // key's HID usage and debugName. This avoids duplicating the physical key + // map. + if (physicalKey != 0) { + return KeyOfPlane(physicalKey, kHidPlane); + } + + // This is a non-printable key that is unrecognized, so a new code is minted + // with the autogenerated bit set. + return KeyOfPlane(press.key.keyCode, kIOSPlane | kAutogeneratedMask); +} + +/** + * Converts NSEvent.timestamp to the timestamp for Flutter. + */ +static double GetFlutterTimestampFrom(NSTimeInterval timestamp) { + // Timestamp in microseconds. The event.timestamp is in seconds with sub-ms precision. + return timestamp * 1000000.0; +} + +/** + * Compute |modifierFlagOfInterestMask| out of |keyCodeToModifierFlag|. + * + * This is equal to the bitwise-or of all values of |keyCodeToModifierFlag|. + */ +static NSUInteger computeModifierFlagOfInterestMask() { + NSUInteger modifierFlagOfInterestMask = kModifierFlagCapsLock | kModifierFlagShiftAny | + kModifierFlagControlAny | kModifierFlagAltAny | + kModifierFlagMetaAny; + for (std::pair entry : keyCodeToModifierFlag) { + modifierFlagOfInterestMask = modifierFlagOfInterestMask | entry.second; + } + return modifierFlagOfInterestMask; +} + +static bool isKeyDown(FlutterUIPressProxy* press) API_AVAILABLE(ios(13.4)) { + switch (press.phase) { + case UIPressPhaseStationary: + case UIPressPhaseChanged: + // Not sure if this is the right thing to do for these two, but true seems + // more correct than false. + return true; + case UIPressPhaseBegan: + return true; + case UIPressPhaseCancelled: + case UIPressPhaseEnded: + return false; + } + return false; +} + +/** + * The C-function sent to the engine's |sendKeyEvent|, wrapping + * |FlutterEmbedderKeyResponder.handleResponse|. + * + * For the reason of this wrap, see |FlutterKeyPendingResponse|. + */ +void HandleResponse(bool handled, void* user_data); +} // namespace + +/** + * The invocation context for |HandleResponse|, wrapping + * |FlutterEmbedderKeyResponder.handleResponse|. + * + * The key responder's functions only accept C-functions as callbacks, as well + * as arbitrary user_data. In order to send an instance method of + * |FlutterEmbedderKeyResponder.handleResponse| to the engine's |SendKeyEvent|, + * we wrap the invocation into a C-function |HandleResponse| and invocation + * context |FlutterKeyPendingResponse|. + */ +@interface FlutterKeyPendingResponse : NSObject + +@property(readonly) FlutterEmbedderKeyResponder* responder; + +@property(nonatomic) uint64_t responseId; + +- (nonnull instancetype)initWithHandler:(nonnull FlutterEmbedderKeyResponder*)responder + responseId:(uint64_t)responseId; + +@end + +@implementation FlutterKeyPendingResponse +- (instancetype)initWithHandler:(FlutterEmbedderKeyResponder*)responder + responseId:(uint64_t)responseId { + self = [super init]; + if (self != nil) { + _responder = responder; + _responseId = responseId; + } + return self; +} +@end + +/** + * Guards a |FlutterAsyncKeyCallback| to make sure it's handled exactly once + * throughout the process of handling an event in |FlutterEmbedderKeyResponder|. + * + * A callback can either be handled with |pendTo:withId:|, or with |resolveTo:|. + * Either way, the callback cannot be handled again, or an assertion will be + * thrown. + */ +@interface FlutterKeyCallbackGuard : NSObject +- (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback; + +/** + * Handle the callback by storing it to pending responses. + */ +- (void)pendTo:(nonnull NSMutableDictionary*)pendingResponses + withId:(uint64_t)responseId; + +/** + * Handle the callback by calling it with a result. + */ +- (void)resolveTo:(BOOL)handled; + +@property(nonatomic) BOOL handled; +/** + * A string indicating how the callback is handled. + * + * Only set in debug mode. Nil in release mode, or if the callback has not been + * handled. + */ +@property(readonly) NSString* debugHandleSource; +@end + +@implementation FlutterKeyCallbackGuard { + // The callback is declared in the implementation block to avoid being + // accessed directly. + FlutterAsyncKeyCallback _callback; +} +- (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback { + self = [super init]; + if (self != nil) { + _callback = [callback copy]; + _handled = FALSE; + } + return self; +} + +- (void)dealloc { + [_callback release]; + [super dealloc]; +} + +- (void)pendTo:(nonnull NSMutableDictionary*)pendingResponses + withId:(uint64_t)responseId { + NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); + if (_handled) { + return; + } + pendingResponses[@(responseId)] = _callback; + _handled = TRUE; + NSAssert( + ((_debugHandleSource = [NSString stringWithFormat:@"pending event %llu", responseId]), TRUE), + @""); +} + +- (void)resolveTo:(BOOL)handled { + NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); + if (_handled) { + return; + } + _callback(handled); + _handled = TRUE; + NSAssert(((_debugHandleSource = [NSString stringWithFormat:@"resolved with %d", _handled]), TRUE), + @""); +} +@end + +@interface FlutterEmbedderKeyResponder () + +/** + * The function to send converted events to. + * + * Set by the initializer. + */ +@property(nonatomic) FlutterSendKeyEvent sendEvent; + +/** + * A map of pressed keys. + * + * The keys of the dictionary are physical keys, while the values are the logical keys + * of the key down event. + */ +@property(nonatomic) NSMutableDictionary* pressingRecords; + +/** + * A constant mask for NSEvent.modifierFlags that Flutter synchronizes with. + * + * Flutter keeps track of the last |modifierFlags| and compares it with the + * incoming one. Any bit within |modifierFlagOfInterestMask| that is different + * (except for the one that corresponds to the event key) indicates that an + * event for this modifier was missed, and Flutter synthesizes an event to make + * up for the state difference. + * + * It is computed by computeModifierFlagOfInterestMask. + */ +@property(nonatomic) NSUInteger modifierFlagOfInterestMask; + +/** + * The modifier flags of the last received key event, excluding uninterested + * bits. + * + * This should be kept synchronized with the last |NSEvent.modifierFlags| + * after masking with |modifierFlagOfInterestMask|. This should also be kept + * synchronized with the corresponding keys of |pressingRecords|. + * + * This is used by |synchronizeModifiers| to quickly find out modifier keys that + * are desynchronized. + */ +@property(nonatomic) NSUInteger lastModifierFlagsOfInterest; + +/** + * A self-incrementing ID used to label key events sent to the framework. + */ +@property(nonatomic) uint64_t responseId; + +/** + * A map of unresponded key events sent to the framework. + * + * Its values are |responseId|s, and keys are the callback that was received + * along with the event. + */ +@property(nonatomic) NSMutableDictionary* pendingResponses; + +/** + * Compare the last modifier flags and the current, and dispatch synthesized + * key events for each different modifier flag bit. + * + * The flags compared are all flags after masking with + * |modifierFlagOfInterestMask| and excluding |ignoringFlags|. + */ +- (void)synchronizeModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); + +/** + * Update the pressing state. + * + * If `logicalKey` is not 0, `physicalKey` is pressed as `logicalKey`. + * Otherwise, `physicalKey` is released. + */ +- (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey; + +/** + * Synthesize a CapsLock down event, then a CapsLock up event. + */ +- (void)synthesizeCapsLockTapWithTimestamp:(NSTimeInterval)timestamp; + +/** + * Send an event to the framework, expecting its response. + */ +- (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event + callback:(nonnull FlutterKeyCallbackGuard*)callback; + +/** + * Send a key event for a modifier key. + */ +- (void)synthesizeModifierEventOfType:(BOOL)isDownEvent + timestamp:(NSTimeInterval)timestamp + keyCode:(UInt32)keyCode; + +/** + * Processes a down event from the system. + */ +- (void)handlePressBegin:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)); + +/** + * Processes an up event from the system. + */ +- (void)handlePressEnd:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)); + +/** + * Processes the response from the framework. + */ +- (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId; + +/** + * Fix up the modifiers for a particular type of modifier key. + */ +- (UInt32)fixSidedFlags:(ModifierFlag)anyFlag + withLeftFlag:(ModifierFlag)leftSide + withRightFlag:(ModifierFlag)rightSide + withLeftKey:(UInt16)leftKeyCode + withRightKey:(UInt16)rightKeyCode + withKeyCode:(UInt16)keyCode + keyDown:(BOOL)isKeyDown + forFlags:(UInt32)modifiersPressed API_AVAILABLE(ios(13.4)); + +/** + * Because iOS differs from other platforms in that the modifier flags still + * contain the flag for the key that is being released on the keyup event, we + * adjust the modifiers when the released key is a matching modifier key. + */ +- (UInt32)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); +@end + +@implementation FlutterEmbedderKeyResponder + +- (nonnull instancetype)initWithSendEvent:(FlutterSendKeyEvent)sendEvent { + self = [super init]; + if (self != nil) { + _sendEvent = [sendEvent copy]; + _pressingRecords = [[NSMutableDictionary alloc] init]; + _pendingResponses = [[NSMutableDictionary alloc] init]; + _responseId = 1; + _lastModifierFlagsOfInterest = 0; + _modifierFlagOfInterestMask = computeModifierFlagOfInterestMask(); + } + return self; +} + +- (void)dealloc { + [_sendEvent release]; + [_pressingRecords release]; + [_pendingResponses release]; + [super dealloc]; +} + +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + callback:(FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + // The conversion algorithm relies on a non-nil callback to properly compute + // `synthesized`. + NSAssert(callback != nil, @"The callback must not be nil."); + + FlutterKeyCallbackGuard* guardedCallback = nil; + switch (press.phase) { + case UIPressPhaseBegan: + guardedCallback = [[FlutterKeyCallbackGuard alloc] initWithCallback:callback]; + [self handlePressBegin:press callback:guardedCallback]; + break; + case UIPressPhaseEnded: + guardedCallback = [[FlutterKeyCallbackGuard alloc] initWithCallback:callback]; + [self handlePressEnd:press callback:guardedCallback]; + break; + case UIPressPhaseChanged: + case UIPressPhaseCancelled: + // TODO(gspencergoog): Handle cancelled events as synthesized up events. + case UIPressPhaseStationary: + NSAssert(false, @"Unexpected press phase receieved in handlePress"); + return; + } + NSAssert(guardedCallback.handled, @"The callback returned without being handled."); + NSAssert( + (_lastModifierFlagsOfInterest & ~kModifierFlagCapsLock) == + ([self adjustModifiers:press] & (_modifierFlagOfInterestMask & ~kModifierFlagCapsLock)), + @"The modifier flags are not properly updated: recorded 0x%lx, event with mask 0x%lx", + static_cast(_lastModifierFlagsOfInterest & ~kModifierFlagCapsLock), + static_cast([self adjustModifiers:press] & + (_modifierFlagOfInterestMask & ~kModifierFlagCapsLock))); +} + +#pragma mark - Private + +- (void)synchronizeModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + + const UInt32 lastFlagsOfInterest = _lastModifierFlagsOfInterest & _modifierFlagOfInterestMask; + const UInt32 pressedModifiers = [self adjustModifiers:press]; + const UInt32 currentFlagsOfInterest = pressedModifiers & _modifierFlagOfInterestMask; + UInt32 flagDifference = currentFlagsOfInterest ^ lastFlagsOfInterest; + if (flagDifference & kModifierFlagCapsLock) { + // If the caps lock changed, and we didn't expect that, then send a + // synthesized down and an up to simulate a toggle of the state. + if (press.key.keyCode != UIKeyboardHIDUsageKeyboardCapsLock) { + [self synthesizeCapsLockTapWithTimestamp:press.timestamp]; + } + flagDifference &= ~kModifierFlagCapsLock; + } + while (true) { + const UInt32 currentFlag = lowestSetBit(flagDifference); + if (currentFlag == 0) { + break; + } + flagDifference &= ~currentFlag; + if (currentFlag & kModifierFlagAnyMask) { + // Skip synthesizing keys for the "any" flags, since their synthesis will + // be handled when we do the sided flags. We still want them in the flags + // of interest, though, so we can keep their state. + continue; + } + auto keyCode = modifierFlagToKeyCode.find(static_cast(currentFlag)); + NSAssert(keyCode != modifierFlagToKeyCode.end(), @"Invalid modifier flag of interest 0x%lx", + static_cast(currentFlag)); + if (keyCode == modifierFlagToKeyCode.end()) { + continue; + } + // If this press matches the modifier key in question, then don't synthesize + // it, because it's already a "real" keypress. + if (keyCode->second == static_cast(press.key.keyCode)) { + continue; + } + BOOL isDownEvent = currentFlagsOfInterest & currentFlag; + [self synthesizeModifierEventOfType:isDownEvent + timestamp:press.timestamp + keyCode:keyCode->second]; + } + _lastModifierFlagsOfInterest = + (_lastModifierFlagsOfInterest & ~_modifierFlagOfInterestMask) | currentFlagsOfInterest; +} + +- (void)synthesizeCapsLockTapWithTimestamp:(NSTimeInterval)timestamp { + // The assumption when the app starts is that caps lock is off, but if that + // turns out to be untrue (according to the modifier flags), then this is used + // to simulate a key down and a key up of the caps lock key, to simulate + // toggling of that state in the framework. + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(timestamp), + .type = kFlutterKeyEventTypeDown, + .physical = kCapsLockPhysicalKey, + .logical = kCapsLockLogicalKey, + .character = nil, + .synthesized = true, + }; + _sendEvent(flutterEvent, nullptr, nullptr); + + flutterEvent.type = kFlutterKeyEventTypeUp; + _sendEvent(flutterEvent, nullptr, nullptr); +} + +- (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey { + if (logicalKey == 0) { + [_pressingRecords removeObjectForKey:@(physicalKey)]; + } else { + _pressingRecords[@(physicalKey)] = @(logicalKey); + } +} + +- (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyCallbackGuard*)callback { + _responseId += 1; + uint64_t responseId = _responseId; + FlutterKeyPendingResponse* pending = + [[FlutterKeyPendingResponse alloc] initWithHandler:self responseId:responseId]; + [callback pendTo:_pendingResponses withId:responseId]; + _sendEvent(event, HandleResponse, pending); +} + +- (void)synthesizeModifierEventOfType:(BOOL)isDownEvent + timestamp:(NSTimeInterval)timestamp + keyCode:(UInt32)keyCode { + uint64_t physicalKey = GetPhysicalKeyForKeyCode(keyCode); + uint64_t logicalKey = GetLogicalKeyForModifier(keyCode, physicalKey); + if (physicalKey == 0 || logicalKey == 0) { + return; + } + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(timestamp), + .type = isDownEvent ? kFlutterKeyEventTypeDown : kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = logicalKey, + .character = nil, + .synthesized = true, + }; + [self updateKey:physicalKey asPressed:isDownEvent ? logicalKey : 0]; + _sendEvent(flutterEvent, nullptr, nullptr); +} + +- (void)handlePressBegin:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + uint64_t physicalKey = GetPhysicalKeyForKeyCode(press.key.keyCode); + uint64_t logicalKey = GetLogicalKeyForEvent(press, physicalKey); + [self synchronizeModifiers:press]; + + NSNumber* pressedLogicalKey = nil; + if ([_pressingRecords count] > 0) { + pressedLogicalKey = _pressingRecords[@(physicalKey)]; + if (pressedLogicalKey != nil) { + // Normally the key up events won't be missed since iOS always sends the + // key up event to the view where the corresponding key down occurred. + // However this might happen in add-to-app scenarios if the focus is changed + // from the native view to the Flutter view amid the key tap. + [callback resolveTo:TRUE]; + return; + } + } + + if (pressedLogicalKey == nil) { + [self updateKey:physicalKey asPressed:logicalKey]; + } + + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(press.timestamp), + .type = kFlutterKeyEventTypeDown, + .physical = physicalKey, + .logical = pressedLogicalKey == nil ? logicalKey : [pressedLogicalKey unsignedLongLongValue], + .character = getEventCharacters(press.key.characters, press.key.keyCode), + .synthesized = false, + }; + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; +} + +- (void)handlePressEnd:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + [self synchronizeModifiers:press]; + + uint64_t physicalKey = GetPhysicalKeyForKeyCode(press.key.keyCode); + NSNumber* pressedLogicalKey = _pressingRecords[@(physicalKey)]; + if (pressedLogicalKey == nil) { + // Normally the key up events won't be missed since iOS always sends the + // key up event to the view where the corresponding key down occurred. + // However this might happen in add-to-app scenarios if the focus is changed + // from the native view to the Flutter view amid the key tap. + [callback resolveTo:TRUE]; + return; + } + [self updateKey:physicalKey asPressed:0]; + + FlutterKeyEvent flutterEvent = { + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = GetFlutterTimestampFrom(press.timestamp), + .type = kFlutterKeyEventTypeUp, + .physical = physicalKey, + .logical = [pressedLogicalKey unsignedLongLongValue], + .character = nil, + .synthesized = false, + }; + [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; +} + +- (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId { + FlutterAsyncKeyCallback callback = _pendingResponses[@(responseId)]; + callback(handled); + [_pendingResponses removeObjectForKey:@(responseId)]; +} + +- (UInt32)fixSidedFlags:(ModifierFlag)anyFlag + withLeftFlag:(ModifierFlag)leftSide + withRightFlag:(ModifierFlag)rightSide + withLeftKey:(UInt16)leftKeyCode + withRightKey:(UInt16)rightKeyCode + withKeyCode:(UInt16)keyCode + keyDown:(BOOL)isKeyDown + forFlags:(UInt32)modifiersPressed API_AVAILABLE(ios(13.4)) { + UInt32 newModifiers = modifiersPressed; + if (isKeyDown) { + // Add in the modifier flags that correspond to this key code, if any. + if (keyCode == leftKeyCode) { + newModifiers |= leftSide | anyFlag; + } else if (keyCode == rightKeyCode) { + newModifiers |= rightSide | anyFlag; + } + } else { + // If this is a key up, then remove any modifier that matches the keycode in + // the event from the flags, and the anyFlag if the other side isn't also + // pressed. + if (keyCode == leftKeyCode) { + newModifiers &= ~leftSide; + if (!(newModifiers & rightSide)) { + newModifiers &= ~anyFlag; + } + } else if (keyCode == rightKeyCode) { + newModifiers &= ~rightSide; + if (!(newModifiers & leftSide)) { + newModifiers &= ~anyFlag; + } + } + } + + if (!(newModifiers & anyFlag)) { + // Turn off any sided flags, since the "any" flag is gone. + newModifiers &= ~(leftSide | rightSide); + } + + return newModifiers; +} + +// This fixes a few cases where iOS provides modifier flags differently from how +// the framework would like to receive them. +// +// 1) iOS turns off the flag associated with a modifier key AFTER the modifier +// key up event, so when the key up event arrives, the flags must be modified +// before synchronizing so they do not include the modifier that arrived in +// the key up event. +// 2) Modifier flags can be set even when that modifier is not being pressed. +// One example of this is when a special character is produced with the Alt +// (Option) key, and the Alt key is released before the letter key: the +// letter key's key up event still contains the Alt key flag. +// 3) iOS doesn't provide information about which side modifier was pressed, +// except through the keycode of the pressed key, so we look at the pressed +// key code to decide which side to indicate in the flags. If we can't know +// (in the case of a non-modifier key event having an "any" modifier set, but +// we don't know already that the modifier is down), then we just pick the +// left one arbitrarily. +- (UInt32)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return press.key.modifierFlags; + } + + bool keyDown = isKeyDown(press); + + // Start with the current modifier flags, along with any sided flags that we + // already know are down. + UInt32 pressedModifiers = + press.key.modifierFlags | (_lastModifierFlagsOfInterest & kModifierFlagSidedMask); + + pressedModifiers = [self fixSidedFlags:kModifierFlagShiftAny + withLeftFlag:kModifierFlagShiftLeft + withRightFlag:kModifierFlagShiftRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftShift + withRightKey:UIKeyboardHIDUsageKeyboardRightShift + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + pressedModifiers = [self fixSidedFlags:kModifierFlagControlAny + withLeftFlag:kModifierFlagControlLeft + withRightFlag:kModifierFlagControlRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftControl + withRightKey:UIKeyboardHIDUsageKeyboardRightControl + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + pressedModifiers = [self fixSidedFlags:kModifierFlagAltAny + withLeftFlag:kModifierFlagAltLeft + withRightFlag:kModifierFlagAltRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftAlt + withRightKey:UIKeyboardHIDUsageKeyboardRightAlt + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + pressedModifiers = [self fixSidedFlags:kModifierFlagMetaAny + withLeftFlag:kModifierFlagMetaLeft + withRightFlag:kModifierFlagMetaRight + withLeftKey:UIKeyboardHIDUsageKeyboardLeftGUI + withRightKey:UIKeyboardHIDUsageKeyboardRightGUI + withKeyCode:press.key.keyCode + keyDown:keyDown + forFlags:pressedModifiers]; + + if (press.key.keyCode == UIKeyboardHIDUsageKeyboardCapsLock) { + // The caps lock modifier needs to be unset only if it was already on + // and this is a key up. This is because it indicates the lock state, and + // not the key press state. The caps lock state should be on between the + // first down, and the second up (i.e. while the lock in in effect), and + // this code turns it off at the second up event. The OS leaves it on still + // because of iOS's weird late processing of modifier states. Synthesis of + // the appropriate synthesized key events happens in synchronizeModifiers. + if (!keyDown && _lastModifierFlagsOfInterest & kModifierFlagCapsLock) { + pressedModifiers &= ~kModifierFlagCapsLock; + } + } + return pressedModifiers; +} + +@end + +namespace { +void HandleResponse(bool handled, void* user_data) { + FlutterKeyPendingResponse* pending = reinterpret_cast(user_data); + [pending.responder handleResponse:handled forId:pending.responseId]; +} +} // namespace diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm new file mode 100644 index 0000000000..825744bd4f --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponderTest.mm @@ -0,0 +1,875 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import +#import +#import +#include <_types/_uint64_t.h> + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" +#include "flutter/shell/platform/embedder/embedder.h" + +FLUTTER_ASSERT_ARC; + +#define XCTAssertStrEqual(value, expected) \ + XCTAssertTrue(strcmp(value, expected) == 0, \ + @"String \"%s\" not equal to the expected value of \"%s\"", value, expected) + +// A wrap to convert FlutterKeyEvent to a ObjC class. +@interface TestKeyEvent : NSObject +@property(nonatomic) FlutterKeyEvent* data; +@property(nonatomic) FlutterKeyEventCallback callback; +@property(nonatomic) _VoidPtr userData; +- (nonnull instancetype)initWithEvent:(const FlutterKeyEvent*)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable _VoidPtr)userData; +- (BOOL)hasCallback; +- (void)respond:(BOOL)handled; +@end + +@implementation TestKeyEvent +- (instancetype)initWithEvent:(const FlutterKeyEvent*)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable _VoidPtr)userData { + self = [super init]; + _data = new FlutterKeyEvent(*event); + if (event->character != nullptr) { + size_t len = strlen(event->character); + char* character = new char[len + 1]; + strcpy(character, event->character); + _data->character = character; + } + _callback = callback; + _userData = userData; + return self; +} + +- (BOOL)hasCallback { + return _callback != nil; +} + +- (void)respond:(BOOL)handled { + NSAssert( + _callback != nil, + @"Improper call to `respond` that does not have a callback."); // Caller's responsibility + _callback(handled, _userData); +} + +- (void)dealloc { + if (_data->character != nullptr) + delete[] _data->character; + delete _data; +} +@end + +namespace { +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeUndefined = (UIKeyboardHIDUsage)0x03; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeKeyA = (UIKeyboardHIDUsage)0x04; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeKeyW = (UIKeyboardHIDUsage)0x1a; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeShiftLeft = (UIKeyboardHIDUsage)0xe1; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeShiftRight = (UIKeyboardHIDUsage)0xe5; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeNumpad1 = (UIKeyboardHIDUsage)0x59; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeCapsLock = (UIKeyboardHIDUsage)0x39; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeF1 = (UIKeyboardHIDUsage)0x3a; +API_AVAILABLE(ios(13.4)) +constexpr UIKeyboardHIDUsage kKeyCodeAltRight = (UIKeyboardHIDUsage)0xe6; + +constexpr uint64_t kPhysicalKeyUndefined = 0x00070003; +constexpr uint64_t kPhysicalKeyA = 0x00070004; +constexpr uint64_t kPhysicalKeyW = 0x0007001a; +constexpr uint64_t kPhysicalShiftLeft = 0x000700e1; +constexpr uint64_t kPhysicalShiftRight = 0x000700e5; +constexpr uint64_t kPhysicalCapsLock = 0x00070039; +constexpr uint64_t kPhysicalNumpad1 = 0x00070059; +constexpr uint64_t kPhysicalF1 = 0x0007003a; +constexpr uint64_t kPhysicalAltRight = 0x000700e6; + +constexpr uint64_t kLogicalKeyUndefined = 0x0100070003; +constexpr uint64_t kLogicalKeyA = 0x0000000061; +constexpr uint64_t kLogicalKeyW = 0x0000000077; +constexpr uint64_t kLogicalShiftLeft = 0x3000000010d; +constexpr uint64_t kLogicalShiftRight = 0x4000000010d; +constexpr uint64_t kLogicalCapsLock = 0x01000000104; +constexpr uint64_t kLogicalNumpad1 = 0x50000000031; +constexpr uint64_t kLogicalF1 = 0x01000000801; +constexpr uint64_t kLogicalAltRight = 0x40000000102; + +constexpr uint64_t kModifierFlagNone = 0x0; + +typedef void (^ResponseCallback)(bool handled); +} // namespace + +@interface FlutterEmbedderKeyResponderTest : XCTestCase +@end + +@implementation FlutterEmbedderKeyResponderTest + +- (void)setUp { +} + +- (void)tearDown { +} + +// Test the most basic key events. +// +// Press, hold, and release key A on an US keyboard. +- (void)testBasicKeyEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->timestamp, 123000000.0f); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + + XCTAssertEqual(last_handled, FALSE); + XCTAssert([[events lastObject] hasCallback]); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = TRUE; + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->timestamp, 123000000.0f); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + XCTAssertEqual(last_handled, TRUE); + XCTAssert([[events lastObject] hasCallback]); + [[events lastObject] respond:FALSE]; // Check if responding FALSE works + XCTAssertEqual(last_handled, FALSE); + + [events removeAllObjects]; +} + +- (void)testOutOfOrderModifiers API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // This tests that we synthesize the correct modifier keys when we release the + // modifier key that created the letter before we release the letter. + [responder handlePress:keyDownEvent(kKeyCodeAltRight, kModifierFlagAltAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalAltRight); + XCTAssertEqual(event->logical, kLogicalAltRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Test non-ASCII characters being produced. + [responder handlePress:keyDownEvent(kKeyCodeKeyW, kModifierFlagAltAny, 123.0f, "∑", "w") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyW); + XCTAssertEqual(event->logical, kLogicalKeyW); + XCTAssertStrEqual(event->character, "∑"); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Releasing the modifier key before the letter should send the key up to the + // framework. + [responder handlePress:keyUpEvent(kKeyCodeAltRight, kModifierFlagAltAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalAltRight); + XCTAssertEqual(event->logical, kLogicalAltRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Yes, iOS sends a modifier flag for the Alt key being down on this event, + // even though the Alt (Option) key has already been released. This means that + // for the framework to be in the correct state, we must synthesize a key down + // event for the modifier key here, and another key up before the next key + // event. + [responder handlePress:keyUpEvent(kKeyCodeKeyW, kModifierFlagAltAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalKeyW); + XCTAssertEqual(event->logical, kLogicalKeyW); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Here we should simulate a key up for the Alt key, since it is no longer + // shown as down in the modifier flags. + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "å", "a") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "å"); + XCTAssertEqual(event->synthesized, false); +} + +- (void)testIgnoreDuplicateDownEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 0u); + XCTAssertEqual(last_handled, TRUE); + + last_handled = FALSE; + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; +} + +- (void)testIgnoreAbruptUpEvent API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled) { + last_handled = handled; + }]; + + XCTAssertEqual([events count], 0u); + XCTAssertEqual(last_handled, TRUE); +} + +// Press R-Shift, A, then release R-Shift then A, on a US keyboard. +// +// This is special because the characters for the A key will change in this +// process. +- (void)testToggleModifiersDuringKeyTap API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder handlePress:keyDownEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->timestamp, 123000000.0f); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagShiftAny, 123.0f, "A", "A") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "A"); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeShiftRight, kModifierFlagNone, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +// Special modifier flags. +// +// Some keys in modifierFlags are not to indicate modifier state, but to mark +// the key area that the key belongs to, such as numpad keys or function keys. +// Ensure these flags do not obstruct other keys. +- (void)testSpecialModiferFlags API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + // Keydown: Numpad1, Fn (undefined), F1, KeyA, ShiftLeft + // Then KeyUp: Numpad1, Fn (undefined), F1, KeyA, ShiftLeft + + // Numpad 1 + // OS provides: char: "1", code: 0x59, modifiers: 0x200000 + [responder handlePress:keyDownEvent(kKeyCodeNumpad1, kModifierFlagNumPadKey, 123.0, "1", "1") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalNumpad1); + XCTAssertEqual(event->logical, kLogicalNumpad1); + XCTAssertStrEqual(event->character, "1"); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // Fn Key (sends HID undefined) + // OS provides: char: nil, keycode: 0x3, modifiers: 0x0 + [responder handlePress:keyDownEvent(kKeyCodeUndefined, kModifierFlagNone, 123.0) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyUndefined); + XCTAssertEqual(event->logical, kLogicalKeyUndefined); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // F1 Down + // OS provides: char: UIKeyInputF1, code: 0x3a, modifiers: 0x0 + [responder handlePress:keyDownEvent(kKeyCodeF1, kModifierFlagNone, 123.0f, "\\^P", "\\^P") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalF1); + XCTAssertEqual(event->logical, kLogicalF1); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // KeyA Down + // OS provides: char: "q", code: 0x4, modifiers: 0x0 + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // ShiftLeft Down + // OS Provides: char: nil, code: 0xe1, modifiers: 0x20000 + [responder handlePress:keyDownEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // Numpad 1 Up + // OS provides: char: "1", code: 0x59, modifiers: 0x200000 + [responder handlePress:keyUpEvent(kKeyCodeNumpad1, kModifierFlagNumPadKey, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 2u); + + // Because the OS no longer provides the 0x20000 (kModifierFlagShiftAny), we + // have to simulate a keyup. + event = [events firstObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalNumpad1); + XCTAssertEqual(event->logical, kLogicalNumpad1); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // F1 Up + // OS provides: char: UIKeyInputF1, code: 0x3a, modifiers: 0x0 + [responder handlePress:keyUpEvent(kKeyCodeF1, kModifierFlagNone, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalF1); + XCTAssertEqual(event->logical, kLogicalF1); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // Fn Key (sends HID undefined) + // OS provides: char: nil, code: 0x3, modifiers: 0x0 + [responder handlePress:keyUpEvent(kKeyCodeUndefined, kModifierFlagNone, 123.0) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalKeyUndefined); + XCTAssertEqual(event->logical, kLogicalKeyUndefined); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // KeyA Up + // OS provides: char: "a", code: 0x4, modifiers: 0x0 + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + // ShiftLeft Up + // OS provides: char: nil, code: 0xe1, modifiers: 0x20000 + [responder handlePress:keyUpEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 0u); +} + +- (void)testIdentifyLeftAndRightModifiers API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + [responder handlePress:keyDownEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyDownEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeShiftLeft, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalShiftLeft); + XCTAssertEqual(event->logical, kLogicalShiftLeft); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; + + [responder handlePress:keyUpEvent(kKeyCodeShiftRight, kModifierFlagShiftAny, 123.0f) + callback:^(BOOL handled){ + }]; + + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalShiftRight); + XCTAssertEqual(event->logical, kLogicalShiftRight); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + [[events lastObject] respond:TRUE]; + + [events removeAllObjects]; +} + +// Press the CapsLock key when CapsLock state is desynchronized +- (void)testSynchronizeCapsLockStateOnCapsLock API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f, "A", "A") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 3u); + + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[0] hasCallback]); + + event = events[1].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[1] hasCallback]); + + event = events[2].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "A"); + XCTAssertEqual(event->synthesized, false); + XCTAssert([events[2] hasCallback]); + + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; + + // Release the "A" key. + [responder handlePress:keyUpEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f) + callback:keyEventCallback]; + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertEqual(event->synthesized, false); + + [events removeAllObjects]; + + // In: CapsLock down + // Out: CapsLock down + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeCapsLock, kModifierFlagCapsLock, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events firstObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + XCTAssert([[events firstObject] hasCallback]); + + [events removeAllObjects]; + + // In: CapsLock up + // Out: CapsLock up + // This turns off the caps lock, triggering a synthesized up/down to tell the + // framework that. + last_handled = FALSE; + [responder handlePress:keyUpEvent(kKeyCodeCapsLock, kModifierFlagCapsLock, 123.0f) + callback:keyEventCallback]; + + XCTAssertEqual([events count], 1u); + event = [events firstObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, false); + XCTAssert([[events firstObject] hasCallback]); + + [events removeAllObjects]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagNone, 123.0f, "a", "a") + callback:keyEventCallback]; + + // Just to make sure that we aren't simulating events now, since the state is + // consistent, and should be off. + XCTAssertEqual([events count], 1u); + event = [events lastObject].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "a"); + XCTAssertEqual(event->synthesized, false); + XCTAssert([[events firstObject] hasCallback]); +} + +// Press the CapsLock key when CapsLock state is desynchronized +- (void)testSynchronizeCapsLockStateOnNormalKey API_AVAILABLE(ios(13.4)) { + __block NSMutableArray* events = [[NSMutableArray alloc] init]; + __block BOOL last_handled = TRUE; + id keyEventCallback = ^(BOOL handled) { + last_handled = handled; + }; + FlutterKeyEvent* event; + + FlutterEmbedderKeyResponder* responder = [[FlutterEmbedderKeyResponder alloc] + initWithSendEvent:^(const FlutterKeyEvent& event, _Nullable FlutterKeyEventCallback callback, + _Nullable _VoidPtr user_data) { + [events addObject:[[TestKeyEvent alloc] initWithEvent:&event + callback:callback + userData:user_data]]; + }]; + + last_handled = FALSE; + [responder handlePress:keyDownEvent(kKeyCodeKeyA, kModifierFlagCapsLock, 123.0f, "A", "a") + callback:keyEventCallback]; + + XCTAssertEqual([events count], 3u); + + event = events[0].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[0] hasCallback]); + + event = events[1].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeUp); + XCTAssertEqual(event->physical, kPhysicalCapsLock); + XCTAssertEqual(event->logical, kLogicalCapsLock); + XCTAssertEqual(event->character, nullptr); + XCTAssertEqual(event->synthesized, true); + XCTAssertFalse([events[1] hasCallback]); + + event = events[2].data; + XCTAssertEqual(event->type, kFlutterKeyEventTypeDown); + XCTAssertEqual(event->physical, kPhysicalKeyA); + XCTAssertEqual(event->logical, kLogicalKeyA); + XCTAssertStrEqual(event->character, "A"); + XCTAssertEqual(event->synthesized, false); + XCTAssert([events[2] hasCallback]); + + XCTAssertEqual(last_handled, FALSE); + [[events lastObject] respond:TRUE]; + XCTAssertEqual(last_handled, TRUE); + + [events removeAllObjects]; +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm index 8155fd2de1..8230002058 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm @@ -126,10 +126,11 @@ static constexpr int kNumProfilerSamplesPerSec = 5; _weakFactory = std::make_unique>(self); - if (project == nil) + if (project == nil) { _dartProject.reset([[FlutterDartProject alloc] init]); - else + } else { _dartProject.reset([project retain]); + } if (!EnableTracingIfNecessary([_dartProject.get() settings])) { NSLog( @@ -141,7 +142,7 @@ static constexpr int kNumProfilerSamplesPerSec = 5; return nil; } - _pluginPublications = [NSMutableDictionary new]; + _pluginPublications = [[NSMutableDictionary alloc] init]; _registrars = [[NSMutableDictionary alloc] init]; [self recreatePlatformViewController]; @@ -261,6 +262,46 @@ static constexpr int kNumProfilerSamplesPerSec = 5; return _shell->GetTaskRunners().GetRasterTaskRunner(); } +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyEventCallback)callback + userData:(void*)userData API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + } else { + return; + } + if (!self.platformView) { + return; + } + const char* character = event.character; + + flutter::KeyData key_data; + key_data.Clear(); + key_data.timestamp = (uint64_t)event.timestamp; + switch (event.type) { + case kFlutterKeyEventTypeUp: + key_data.type = flutter::KeyEventType::kUp; + break; + case kFlutterKeyEventTypeDown: + key_data.type = flutter::KeyEventType::kDown; + break; + case kFlutterKeyEventTypeRepeat: + key_data.type = flutter::KeyEventType::kRepeat; + break; + } + key_data.physical = event.physical; + key_data.logical = event.logical; + key_data.synthesized = event.synthesized; + + auto packet = std::make_unique(key_data, character); + + auto response = [callback, userData](bool handled) { + if (callback != nullptr) { + callback(handled, userData); + } + }; + self.platformView->DispatchKeyDataPacket(std::move(packet), std::move(response)); +} + - (void)ensureSemanticsEnabled { self.iosPlatformView->SetSemanticsEnabled(true); } @@ -677,6 +718,13 @@ static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSS #pragma mark - Text input delegate +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())next API_AVAILABLE(ios(13.4)) { + if (_viewController.get() != nullptr) { + [_viewController.get() handlePressEvent:press nextAction:next]; + } +} + - (void)updateEditingClient:(int)client withState:(NSDictionary*)state { [_textInputChannel.get() invokeMethod:@"TextInputClient.updateEditingState" arguments:@[ @(client), state ]]; @@ -911,7 +959,7 @@ static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSS // [NSLocale currentLocale] provides an iOS resolved locale if the // supported locales are exposed to the iOS embedder. Here, we get // currentLocale and pass it to dart:ui - NSMutableArray* localeData = [[NSMutableArray new] autorelease]; + NSMutableArray* localeData = [[[NSMutableArray alloc] init] autorelease]; NSLocale* platformResolvedLocale = [NSLocale currentLocale]; NSString* languageCode = [platformResolvedLocale objectForKey:NSLocaleLanguageCode]; NSString* countryCode = [platformResolvedLocale objectForKey:NSLocaleCountryCode]; @@ -928,7 +976,7 @@ static void SetEntryPoint(flutter::Settings* settings, NSString* entrypoint, NSS } // Get and pass the user's preferred locale list to dart:ui - localeData = [[NSMutableArray new] autorelease]; + localeData = [[[NSMutableArray alloc] init] autorelease]; NSArray* preferredLocales = [NSLocale preferredLanguages]; for (NSString* localeID in preferredLocales) { NSLocale* locale = [[[NSLocale alloc] initWithLocaleIdentifier:localeID] autorelease]; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm index 0d339fbc72..25bfa3ac5a 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEnginePlatformViewTest.mm @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include #define FML_USED_ON_EMBEDDER #import @@ -17,7 +18,7 @@ FLUTTER_ASSERT_NOT_ARC namespace flutter { namespace { -class MockDelegate : public PlatformView::Delegate { +class FakeDelegate : public PlatformView::Delegate { void OnPlatformViewCreated(std::unique_ptr surface) override {} void OnPlatformViewDestroyed() override {} void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {} @@ -54,28 +55,36 @@ class MockDelegate : public PlatformView::Delegate { @end @implementation FlutterEnginePlatformViewTest +std::unique_ptr platform_view; +std::unique_ptr> weak_factory; +flutter::FakeDelegate fake_delegate; - (void)setUp { fml::MessageLoop::EnsureInitializedForCurrentThread(); -} - -- (void)tearDown { -} - -- (void)testCallsNotifyLowMemory { - flutter::MockDelegate mock_delegate; auto thread_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner(); flutter::TaskRunners runners(/*label=*/self.name.UTF8String, /*platform=*/thread_task_runner, /*raster=*/thread_task_runner, /*ui=*/thread_task_runner, /*io=*/thread_task_runner); - auto platform_view = std::make_unique( - /*delegate=*/mock_delegate, + platform_view = std::make_unique( + /*delegate=*/fake_delegate, /*rendering_api=*/flutter::IOSRenderingAPI::kSoftware, /*platform_views_controller=*/nil, /*task_runners=*/runners); + weak_factory = std::make_unique>(platform_view.get()); +} +- (void)tearDown { + weak_factory.reset(); + platform_view.reset(); +} + +- (fml::WeakPtr)platformViewReplacement { + return weak_factory->GetWeakPtr(); +} + +- (void)testCallsNotifyLowMemory { id project = OCMClassMock([FlutterDartProject class]); FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"tester" project:project]; XCTAssertNotNil(engine); @@ -104,7 +113,6 @@ class MockDelegate : public PlatformView::Delegate { [self waitForExpectations:@[ backgroundExpectation ] timeout:5.0]; OCMVerify([mockEngine notifyLowMemory]); - [mockEngine stopMocking]; } @end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h index 698e5fdf8d..c3ae89ca83 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ -#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_ENGINE_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_ENGINE_INTERNAL_H_ #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" @@ -14,6 +14,11 @@ #include "flutter/shell/common/platform_view.h" #include "flutter/shell/common/rasterizer.h" #include "flutter/shell/common/shell.h" + +// Embedder header included as an implementation detail (See BUILD.gn), iOS +// doesn't use the embedding API, just some structures from it. +#include "flutter/shell/platform/embedder/embedder.h" + #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" @@ -23,7 +28,7 @@ #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" -extern NSString* const FlutterEngineWillDealloc; +extern NSString* _Nonnull const FlutterEngineWillDealloc; @interface FlutterEngine () @@ -40,19 +45,20 @@ extern NSString* const FlutterEngineWillDealloc; - (flutter::Rasterizer::Screenshot)screenshot:(flutter::Rasterizer::ScreenshotType)type base64Encode:(bool)base64Encode; -- (FlutterPlatformPlugin*)platformPlugin; +- (nonnull FlutterPlatformPlugin*)platformPlugin; - (std::shared_ptr&)platformViewsController; -- (FlutterTextInputPlugin*)textInputPlugin; -- (FlutterRestorationPlugin*)restorationPlugin; -- (void)launchEngine:(NSString*)entrypoint libraryURI:(NSString*)libraryOrNil; -- (BOOL)createShell:(NSString*)entrypoint - libraryURI:(NSString*)libraryOrNil - initialRoute:(NSString*)initialRoute; +- (nonnull FlutterTextInputPlugin*)textInputPlugin; +- (nonnull FlutterRestorationPlugin*)restorationPlugin; +- (void)launchEngine:(nullable NSString*)entrypoint libraryURI:(nullable NSString*)libraryOrNil; +- (BOOL)createShell:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryOrNil + initialRoute:(nullable NSString*)initialRoute; - (void)attachView; - (void)notifyLowMemory; -- (flutter::PlatformViewIOS*)iosPlatformView; +- (nonnull flutter::PlatformViewIOS*)iosPlatformView; -- (void)waitForFirstFrame:(NSTimeInterval)timeout callback:(void (^)(BOOL didTimeout))callback; +- (void)waitForFirstFrame:(NSTimeInterval)timeout + callback:(nonnull void (^)(BOOL didTimeout))callback; /** * Creates one running FlutterEngine from another, sharing components between them. @@ -60,9 +66,16 @@ extern NSString* const FlutterEngineWillDealloc; * This results in a faster creation time and a smaller memory footprint engine. * This should only be called on a FlutterEngine that is running. */ -- (FlutterEngine*)spawnWithEntrypoint:(/*nullable*/ NSString*)entrypoint - libraryURI:(/*nullable*/ NSString*)libraryURI; +- (nonnull FlutterEngine*)spawnWithEntrypoint:(nullable NSString*)entrypoint + libraryURI:(nullable NSString*)libraryURI; +/** + * Dispatches the given key event data to the framework through the engine. + * The callback is called once the response from the framework is received. + */ +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; @end -#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERENGINE_INTERNAL_H_ +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_ENGINE_INTERNAL_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h new file mode 100644 index 0000000000..ddf5facb81 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h @@ -0,0 +1,69 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_FAKE_KEY_EVENTS_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_FAKE_KEY_EVENTS_H_ + +#import +#import +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +API_AVAILABLE(ios(13.4)) +@interface FakeUIPressProxy : FlutterUIPressProxy +- (instancetype)initWithData:(UIPressPhase)phase + key:(UIKey*)key + type:(UIEventType)type + timestamp:(NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)); + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)); +- (UIKey*)key API_AVAILABLE(ios(13.4)); +- (UIEventType)type API_AVAILABLE(ios(13.4)); +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)); + +@property(nonatomic, readonly) UIPressPhase dataPhase; +@property(nonatomic, readonly) UIKey* dataKey; +@property(nonatomic, readonly) UIEventType dataType; +@property(nonatomic, readonly) NSTimeInterval dataTimestamp; +@end + +API_AVAILABLE(ios(13.4)) +@interface FakeUIKey : UIKey +- (instancetype)initWithData:(UIKeyboardHIDUsage)keyCode + modifierFlags:(UIKeyModifierFlags)modifierFlags + characters:(NSString*)characters + charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)); + +- (UIKeyboardHIDUsage)keyCode; +- (UIKeyModifierFlags)modifierFlags; +- (NSString*)characters; +- (NSString*)charactersIgnoringModifiers; + +@property(assign, nonatomic) UIKeyboardHIDUsage dataKeyCode; +@property(assign, nonatomic) UIKeyModifierFlags dataModifierFlags; +@property(readwrite, nonatomic) NSString* dataCharacters; +@property(readwrite, nonatomic) NSString* dataCharactersIgnoringModifiers; +@end + +FlutterUIPressProxy* keyDownEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags = 0x0, + NSTimeInterval timestamp = 0.0f, + const char* characters = "", + const char* charactersIgnoringModifiers = "") + API_AVAILABLE(ios(13.4)); + +FlutterUIPressProxy* keyUpEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags = 0x0, + NSTimeInterval timestamp = 0.0f) API_AVAILABLE(ios(13.4)); + +FlutterUIPressProxy* keyEventWithPhase(UIPressPhase phase, + UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags = 0x0, + NSTimeInterval timestamp = 0.0f, + const char* characters = "", + const char* charactersIgnoringModifiers = "") + API_AVAILABLE(ios(13.4)); + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_FAKE_KEY_EVENTS_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm new file mode 100644 index 0000000000..6cd75497e6 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm @@ -0,0 +1,120 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" + +FLUTTER_ASSERT_ARC; + +@implementation FakeUIPressProxy +- (instancetype)initWithData:(UIPressPhase)phase + key:(UIKey*)key + type:(UIEventType)type + timestamp:(NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { + self = [super init]; + if (self) { + _dataPhase = phase; + _dataKey = [key copy]; + _dataType = type; + _dataTimestamp = timestamp; + } + return self; +} + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)) { + return _dataPhase; +} + +- (UIKey*)key API_AVAILABLE(ios(13.4)) { + return _dataKey; +} + +- (UIEventType)type API_AVAILABLE(ios(13.4)) { + return _dataType; +} + +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { + return _dataTimestamp; +} +@end + +@implementation FakeUIKey +- (instancetype)initWithData:(UIKeyboardHIDUsage)keyCode + modifierFlags:(UIKeyModifierFlags)modifierFlags + characters:(NSString*)characters + charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)) { + self = [super init]; + if (self) { + _dataKeyCode = keyCode; + _dataModifierFlags = modifierFlags; + _dataCharacters = characters; + _dataCharactersIgnoringModifiers = charactersIgnoringModifiers; + } + return self; +} + +- (id)copyWithZone:(NSZone*)zone { + FakeUIKey* another = [super copyWithZone:zone]; + another.dataKeyCode = _dataKeyCode; + another.dataModifierFlags = _dataModifierFlags; + another.dataCharacters = [_dataCharacters copyWithZone:zone]; + another.dataCharactersIgnoringModifiers = [_dataCharactersIgnoringModifiers copyWithZone:zone]; + + return another; +} + +- (UIKeyboardHIDUsage)keyCode API_AVAILABLE(ios(13.4)) { + return _dataKeyCode; +} + +- (UIKeyModifierFlags)modifierFlags API_AVAILABLE(ios(13.4)) { + return _dataModifierFlags; +} + +- (NSString*)characters API_AVAILABLE(ios(13.4)) { + return _dataCharacters; +} + +- (NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)) { + return _dataCharactersIgnoringModifiers; +} +@end + +FlutterUIPressProxy* keyDownEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags, + NSTimeInterval timestamp, + const char* characters, + const char* charactersIgnoringModifiers) + API_AVAILABLE(ios(13.4)) { + return keyEventWithPhase(UIPressPhaseBegan, keyCode, modifierFlags, timestamp, characters, + charactersIgnoringModifiers); +} + +FlutterUIPressProxy* keyUpEvent(UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags, + NSTimeInterval timestamp) API_AVAILABLE(ios(13.4)) { + return keyEventWithPhase(UIPressPhaseEnded, keyCode, modifierFlags, timestamp); +} + +FlutterUIPressProxy* keyEventWithPhase(UIPressPhase phase, + UIKeyboardHIDUsage keyCode, + UIKeyModifierFlags modifierFlags, + NSTimeInterval timestamp, + const char* characters, + const char* charactersIgnoringModifiers) + API_AVAILABLE(ios(13.4)) { + assert(!(modifierFlags & kModifierFlagSidedMask) && + "iOS doesn't supply modifier side flags, so don't create events with them."); + UIKey* key = + [[FakeUIKey alloc] initWithData:keyCode + modifierFlags:modifierFlags + characters:[NSString stringWithUTF8String:characters] + charactersIgnoringModifiers:[NSString stringWithUTF8String:charactersIgnoringModifiers]]; + + return [[FakeUIPressProxy alloc] initWithData:phase + key:key + type:UIEventTypePresses + timestamp:timestamp]; +} diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h new file mode 100644 index 0000000000..d89f3a9d5e --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h @@ -0,0 +1,34 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEY_PRIMARY_RESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEY_PRIMARY_RESPONDER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +typedef void (^FlutterAsyncKeyCallback)(BOOL handled); + +/** + * An interface for a responder that can process a key press event and decides + * whether to handle the event asynchronously. + * + * To use this class, add it to a |FlutterKeyboardManager| with + * |addPrimaryResponder|. + */ +@protocol FlutterKeyPrimaryResponder + +/** + * Process the event. + * + * The |callback| should be called with a value that indicates whether the + * responder has handled the given press event. The |callback| must be called + * exactly once, and can be called before the return of this method, or after. + */ +@required +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + callback:(nonnull FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)); + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEY_PRIMARY_RESPONDER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h new file mode 100644 index 0000000000..7aaa0b7f31 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEY_SECONDARY_RESPONDER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEY_SECONDARY_RESPONDER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +/** + * An interface for a responder that can process a key event and synchronously + * decide whether to handle the event. + * + * To use this class, add it to a |FlutterKeyboardManager| with + * |addSecondaryResponder|. + */ +@protocol FlutterKeySecondaryResponder + +/** + * Informs the receiver that the user has interacted with a key. + * + * The return value indicates whether it has handled the given event. + * + * Default implementation returns NO. + */ +@required + +- (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEY_SECONDARY_RESPONDER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h new file mode 100644 index 0000000000..ebdcae1d2d --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEYBOARD_MANAGER_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEYBOARD_MANAGER_H_ + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" + +#import +#import + +#include "flutter/fml/memory/weak_ptr.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +typedef void (^KeyEventCompleteCallback)(bool, FlutterUIPressProxy* _Nonnull) + API_AVAILABLE(ios(13.4)); + +/** + * A hub that manages how key events are dispatched to various Flutter key + * responders, and propagates it to the superclass if the Flutter key responders + * do not handle it. + * + * This class manages one or more primary responders, as well as zero or more + * secondary responders. + * + * An event that is received by |handlePresses| is first dispatched to *all* + * primary responders. Each primary responder responds *asynchronously* with a + * boolean, indicating whether it handles the event. + * + * An event that is not handled by any primary responders is then passed to to + * the first secondary responder (in the chronological order of addition), + * which responds *synchronously* with a boolean, indicating whether it handles + * the event. If not, the event is passed to the next secondary responder, and + * so on. + * + * The event is then handed back to the |completeCallback| from the original + * call to |handlePresses| so that it can respond synchronously to the OS if the + * event was not handled by the responders. The |completeCallback| is called on + * the platform thread because the platform thread is blocked by a nested event + * loop while the response from the framework is being collected, and it needs + * to be called on the platform thread to unblock the thread by exiting the + * nested event loop. + * + * Preventing primary responders from receiving events is not supported, because + * in reality this class only supports two hardcoded responders + * (FlutterChannelKeyResponder and FlutterEmbedderKeyResponder), where the only purpose + * of supporting two is to maintain the legacy channel API during the + * deprecation window, after which the channel responder should be removed, and + * only one primary responder will exist. + */ +@interface FlutterKeyboardManager : NSObject +/** + * Add a primary responder, which asynchronously decides whether to handle an + * event. + */ +- (void)addPrimaryResponder:(nonnull id)responder; + +/** + * Add a secondary responder, which synchronously decides whether to handle an + * event in order if no earlier responders handle. + */ +- (void)addSecondaryResponder:(nonnull id)responder; + +/** + * Dispatches a key press event to all responders, gathering their responses, + * and then calls the |nextAction| if the event was not handled. + */ +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + nextAction:(nonnull void (^)())next API_AVAILABLE(ios(13.4)); +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_KEYBOARD_MANAGER_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm new file mode 100644 index 0000000000..f575307b65 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm @@ -0,0 +1,139 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" +#include "flutter/fml/memory/weak_ptr.h" + +@interface FlutterKeyboardManager () + +/** + * The primary responders added by addPrimaryResponder. + */ +@property(nonatomic) NSMutableArray>* primaryResponders; + +/** + * The secondary responders added by addSecondaryResponder. + */ +@property(nonatomic) NSMutableArray>* secondaryResponders; + +- (void)dispatchToSecondaryResponders:(nonnull FlutterUIPressProxy*)press + complete:(nonnull KeyEventCompleteCallback)callback + API_AVAILABLE(ios(13.4)); + +@end + +@implementation FlutterKeyboardManager { + std::unique_ptr> _weakFactory; +} + +- (nonnull instancetype)init { + self = [super init]; + if (self != nil) { + _primaryResponders = [[NSMutableArray alloc] init]; + _secondaryResponders = [[NSMutableArray alloc] init]; + _weakFactory = std::make_unique>(self); + } + return self; +} + +- (void)addPrimaryResponder:(nonnull id)responder { + [_primaryResponders addObject:responder]; +} + +- (void)addSecondaryResponder:(nonnull id)responder { + [_secondaryResponders addObject:responder]; +} + +- (void)dealloc { + [_primaryResponders removeAllObjects]; + [_secondaryResponders removeAllObjects]; + [_primaryResponders release]; + [_secondaryResponders release]; + _primaryResponders = nil; + _secondaryResponders = nil; + [super dealloc]; +} + +- (fml::WeakPtr)getWeakPtr { + return _weakFactory->GetWeakPtr(); +} + +- (void)handlePress:(nonnull FlutterUIPressProxy*)press + nextAction:(nonnull void (^)())next API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + return; + } + + bool __block wasHandled = false; + KeyEventCompleteCallback completeCallback = ^void(bool handled, FlutterUIPressProxy* press) { + wasHandled = handled; + CFRunLoopStop(CFRunLoopGetCurrent()); + }; + switch (press.phase) { + case UIPressPhaseBegan: + case UIPressPhaseEnded: { + // Having no primary responders requires extra logic, but Flutter hard-codes + // all primary responders, so this is a situation that Flutter will never + // encounter. + NSAssert([_primaryResponders count] >= 0, @"At least one primary responder must be added."); + + __block auto weakSelf = [self getWeakPtr]; + __block int unreplied = [_primaryResponders count]; + __block BOOL anyHandled = false; + FlutterAsyncKeyCallback replyCallback = ^(BOOL handled) { + unreplied--; + NSAssert(unreplied >= 0, @"More primary responders replied than expected."); + anyHandled = anyHandled || handled; + if (unreplied == 0) { + if (!anyHandled && weakSelf) { + [weakSelf.get() dispatchToSecondaryResponders:press complete:completeCallback]; + } else { + completeCallback(true, press); + } + } + }; + for (id responder in _primaryResponders) { + [responder handlePress:press callback:replyCallback]; + } + // Create a nested run loop while we wait for a response from the + // framework. Once the completeCallback is called, this run loop will exit + // and the main one will resume. The completeCallback MUST be called, or + // the app will get stuck in this run loop indefinitely. + CFRunLoopRun(); + break; + } + case UIPressPhaseChanged: + case UIPressPhaseCancelled: + case UIPressPhaseStationary: + break; + } + if (!wasHandled) { + next(); + } +} + +#pragma mark - Private + +- (void)dispatchToSecondaryResponders:(nonnull FlutterUIPressProxy*)press + complete:(nonnull KeyEventCompleteCallback)callback + API_AVAILABLE(ios(13.4)) { + if (@available(iOS 13.4, *)) { + // no-op + } else { + callback(false, press); + return; + } + + for (id responder in _secondaryResponders) { + if ([responder handlePress:press]) { + callback(true, press); + return; + } + } + callback(false, press); +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm new file mode 100644 index 0000000000..0eafd55b02 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManagerTest.mm @@ -0,0 +1,294 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import +#import +#import +#import +#include <_types/_uint32_t.h> + +#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" + +FLUTTER_ASSERT_ARC; + +namespace flutter { +class PointerDataPacket {}; +} + +/// Sometimes we have to use a custom mock to avoid retain cycles in ocmock. +@interface FlutterEnginePartialMock : FlutterEngine +@property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel; +@property(nonatomic, weak) FlutterViewController* viewController; +@property(nonatomic, assign) BOOL didCallNotifyLowMemory; +@end + +@interface FlutterEngine () +- (BOOL)createShell:(NSString*)entrypoint + libraryURI:(NSString*)libraryURI + initialRoute:(NSString*)initialRoute; +- (void)dispatchPointerDataPacket:(std::unique_ptr)packet; +@end + +@interface FlutterEngine (TestLowMemory) +- (void)notifyLowMemory; +@end + +extern NSNotificationName const FlutterViewControllerWillDealloc; + +/// A simple mock class for FlutterEngine. +/// +/// OCMockClass can't be used for FlutterEngine sometimes because OCMock retains arguments to +/// invocations and since the init for FlutterViewController calls a method on the +/// FlutterEngine it creates a retain cycle that stops us from testing behaviors related to +/// deleting FlutterViewControllers. +@interface MockEngine : NSObject +@end + +@interface FlutterKeyboardManagerUnittestsObjC : NSObject +- (bool)nextResponderShouldThrowOnPressesEnded; +- (bool)singlePrimaryResponder; +- (bool)doublePrimaryResponder; +- (bool)singleSecondaryResponder; +- (bool)emptyNextResponder; +@end + +namespace { + +typedef void (^KeyCallbackSetter)(FlutterAsyncKeyCallback callback); +typedef BOOL (^BoolGetter)(); + +} // namespace + +@interface FlutterKeyboardManagerTest : XCTestCase +@property(nonatomic, strong) id mockEngine; +- (FlutterViewController*)mockOwnerWithPressesBeginOnlyNext API_AVAILABLE(ios(13.4)); +@end + +@implementation FlutterKeyboardManagerTest + +- (void)setUp { + [super setUp]; + self.mockEngine = OCMClassMock([FlutterEngine class]); +} + +- (void)tearDown { + // We stop mocking here to avoid retain cycles that stop + // FlutterViewControllers from deallocing. + [self.mockEngine stopMocking]; + self.mockEngine = nil; + [super tearDown]; +} + +- (id)checkKeyDownEvent:(UIKeyboardHIDUsage)keyCode API_AVAILABLE(ios(13.4)) { + return [OCMArg checkWithBlock:^BOOL(id value) { + if (![value isKindOfClass:[FlutterUIPressProxy class]]) { + return NO; + } + FlutterUIPressProxy* press = value; + return press.key.keyCode == keyCode; + }]; +} + +- (id)mockPrimaryResponder:(KeyCallbackSetter)callbackSetter + API_AVAILABLE(ios(13.4)) { + id mock = + OCMStrictProtocolMock(@protocol(FlutterKeyPrimaryResponder)); + OCMStub([mock handlePress:[OCMArg any] callback:[OCMArg any]]) + .andDo((^(NSInvocation* invocation) { + FlutterAsyncKeyCallback callback; + [invocation getArgument:&callback atIndex:3]; + CFRunLoopPerformBlock(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, ^() { + callbackSetter(callback); + }); + })); + return mock; +} + +- (id)mockSecondaryResponder:(BoolGetter)resultGetter + API_AVAILABLE(ios(13.4)) { + id mock = + OCMStrictProtocolMock(@protocol(FlutterKeySecondaryResponder)); + OCMStub([mock handlePress:[OCMArg any]]).andDo((^(NSInvocation* invocation) { + BOOL result = resultGetter(); + [invocation setReturnValue:&result]; + })); + return mock; +} + +- (FlutterViewController*)mockOwnerWithPressesBeginOnlyNext API_AVAILABLE(ios(13.4)) { + // The nextResponder is a strict mock and hasn't stubbed pressesEnded. + // An error will be thrown on pressesEnded. + UIResponder* nextResponder = OCMStrictClassMock([UIResponder class]); + OCMStub([nextResponder pressesBegan:[OCMArg any] withEvent:[OCMArg any]]).andDo(nil); + + FlutterViewController* viewController = + [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; + FlutterViewController* owner = OCMPartialMock(viewController); + OCMStub([owner nextResponder]).andReturn(nextResponder); + return owner; +} + +// Verify that the nextResponder returned from mockOwnerWithPressesBeginOnlyNext() +// throws exception when pressesEnded is called. +- (bool)testNextResponderShouldThrowOnPressesEnded API_AVAILABLE(ios(13.4)) { + FlutterViewController* owner = [self mockOwnerWithPressesBeginOnlyNext]; + @try { + [owner.nextResponder pressesEnded:[NSSet init] withEvent:[[UIPressesEvent alloc] init]]; + return false; + } @catch (...) { + return true; + } +} + +- (void)testSinglePrimaryResponder API_AVAILABLE(ios(13.4)) { + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + __block BOOL primaryResponse = FALSE; + __block int callbackCount = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterAsyncKeyCallback callback) { + callbackCount++; + callback(primaryResponse); + }]]; + constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50; + // Case: The responder reports TRUE + __block bool completeHandled = true; + primaryResponse = TRUE; + [manager handlePress:keyDownEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertTrue(completeHandled); + completeHandled = true; + callbackCount = 0; + + // Case: The responder reports FALSE + primaryResponse = FALSE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertFalse(completeHandled); +} + +- (void)testDoublePrimaryResponder API_AVAILABLE(ios(13.4)) { + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + + __block BOOL callback1Response = FALSE; + __block int callback1Count = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterAsyncKeyCallback callback) { + callback1Count++; + callback(callback1Response); + }]]; + + __block BOOL callback2Response = FALSE; + __block int callback2Count = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterAsyncKeyCallback callback) { + callback2Count++; + callback(callback2Response); + }]]; + + // Case: Both responders report TRUE. + __block bool somethingWasHandled = true; + constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50; + callback1Response = TRUE; + callback2Response = TRUE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + somethingWasHandled = false; + }]; + XCTAssertEqual(callback1Count, 1); + XCTAssertEqual(callback2Count, 1); + XCTAssertTrue(somethingWasHandled); + + somethingWasHandled = true; + callback1Count = 0; + callback2Count = 0; + + // Case: One responder reports TRUE. + callback1Response = TRUE; + callback2Response = FALSE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + somethingWasHandled = false; + }]; + XCTAssertEqual(callback1Count, 1); + XCTAssertEqual(callback2Count, 1); + XCTAssertTrue(somethingWasHandled); + + somethingWasHandled = true; + callback1Count = 0; + callback2Count = 0; + + // Case: Both responders report FALSE. + callback1Response = FALSE; + callback2Response = FALSE; + [manager handlePress:keyDownEvent(keyId) + nextAction:^() { + somethingWasHandled = false; + }]; + XCTAssertEqual(callback1Count, 1); + XCTAssertEqual(callback2Count, 1); + XCTAssertFalse(somethingWasHandled); +} + +- (void)testSingleSecondaryResponder API_AVAILABLE(ios(13.4)) { + FlutterKeyboardManager* manager = [[FlutterKeyboardManager alloc] init]; + + __block BOOL primaryResponse = FALSE; + __block int callbackCount = 0; + [manager addPrimaryResponder:[self mockPrimaryResponder:^(FlutterAsyncKeyCallback callback) { + callbackCount++; + callback(primaryResponse); + }]]; + + __block BOOL secondaryResponse; + [manager addSecondaryResponder:[self mockSecondaryResponder:^() { + return secondaryResponse; + }]]; + + // Case: Primary responder responds TRUE. The event shouldn't be handled by + // the secondary responder. + constexpr UIKeyboardHIDUsage keyId = (UIKeyboardHIDUsage)0x50; + secondaryResponse = FALSE; + primaryResponse = TRUE; + __block bool completeHandled = true; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertTrue(completeHandled); + completeHandled = true; + callbackCount = 0; + + // Case: Primary responder responds FALSE. The secondary responder returns + // TRUE. + secondaryResponse = TRUE; + primaryResponse = FALSE; + [manager handlePress:keyUpEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertTrue(completeHandled); + completeHandled = true; + callbackCount = 0; + + // Case: Primary responder responds FALSE. The secondary responder returns FALSE. + secondaryResponse = FALSE; + primaryResponse = FALSE; + [manager handlePress:keyDownEvent(keyId) + nextAction:^() { + completeHandled = false; + }]; + XCTAssertEqual(callbackCount, 1); + XCTAssertFalse(completeHandled); +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.m b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm similarity index 100% rename from engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.m rename to engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegateTest.mm diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h index 033a196696..cb5491a9db 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h @@ -6,6 +6,7 @@ #define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTDELEGATE_H_ #import +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" typedef NS_ENUM(NSInteger, FlutterTextInputAction) { FlutterTextInputActionUnspecified, @@ -28,7 +29,8 @@ typedef NS_ENUM(NSInteger, FlutterFloatingCursorDragState) { }; @protocol FlutterTextInputDelegate - +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())next API_AVAILABLE(ios(13.4)); - (void)updateEditingClient:(int)client withState:(NSDictionary*)state; - (void)updateEditingClient:(int)client withState:(NSDictionary*)state withTag:(NSString*)tag; - (void)performAction:(FlutterTextInputAction)action withClient:(int)client; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h index 7f9f6bcb1b..579a5a7e07 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h @@ -8,9 +8,10 @@ #import #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" -@interface FlutterTextInputPlugin : NSObject +@interface FlutterTextInputPlugin : NSObject @property(nonatomic, assign) id textInputDelegate; - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm index b8f9cfd803..3ca762561b 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm @@ -34,6 +34,18 @@ const CGRect kInvalidFirstRect = {{-1, -1}, {9999, 9999}}; // See the comments in beginFloatingCursorAtPoint and caretRectForPosition. const CGRect kSpacePanBounds = {{-2500, -2500}, {5000, 5000}}; +#pragma mark - TextInput channel method names. +// See https://api.flutter.dev/flutter/services/SystemChannels/textInput-constant.html +static NSString* const kShowMethod = @"TextInput.show"; +static NSString* const kHideMethod = @"TextInput.hide"; +static NSString* const kSetClientMethod = @"TextInput.setClient"; +static NSString* const kSetEditingStateMethod = @"TextInput.setEditingState"; +static NSString* const kClearClientMethod = @"TextInput.clearClient"; +static NSString* const kSetEditableSizeAndTransformMethod = + @"TextInput.setEditableSizeAndTransform"; +static NSString* const kSetMarkedTextRectMethod = @"TextInput.setMarkedTextRect"; +static NSString* const kFinishAutofillContextMethod = @"TextInput.finishAutofillContext"; + #pragma mark - TextInputConfiguration Field Names static NSString* const kSecureTextEntry = @"obscureText"; static NSString* const kKeyboardType = @"inputType"; @@ -720,6 +732,81 @@ static FlutterAutofillType autofillTypeOf(NSDictionary* configuration) { } } +// The documentation for presses* handlers (implemented below) is entirely +// unclear about how to handle the case where some, but not all, of the presses +// are handled here. I've elected to call super separately for each of the +// presses that aren't handled, but it's not clear if this is correct. It may be +// that iOS intends for us to either handle all or none of the presses, and pass +// the original set to super. I have not yet seen multiple presses in the set in +// the wild, however, so I suspect that the API is built for a tvOS remote or +// something, and perhaps only one ever appears in the set on iOS from a +// keyboard. + +// If you substantially change these presses overrides, consider also changing +// the similar ones in FlutterViewController. They need to be overridden in both +// places to capture keys both inside and outside of a text field, but have +// slightly different implmentations. + +- (void)pressesBegan:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + for (UIPress* press in presses) { + [_textInputDelegate handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press + withEvent:event] + nextAction:^() { + [super pressesBegan:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesBegan:presses withEvent:event]; + } +} + +- (void)pressesChanged:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + for (UIPress* press in presses) { + [_textInputDelegate + handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [super pressesChanged:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesChanged:presses withEvent:event]; + } +} + +- (void)pressesEnded:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + for (UIPress* press in presses) { + [_textInputDelegate handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press + withEvent:event] + nextAction:^() { + [super pressesEnded:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesEnded:presses withEvent:event]; + } +} + +- (void)pressesCancelled:(NSSet*)presses + withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { + if (@available(iOS 13.4, *)) { + for (UIPress* press in presses) { + [_textInputDelegate + handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [super pressesCancelled:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesCancelled:presses withEvent:event]; + } +} + // Extracts the selection information from the editing state dictionary. // // The state may contain an invalid selection, such as when no selection was @@ -1329,7 +1416,7 @@ static FlutterAutofillType autofillTypeOf(NSDictionary* configuration) { * and a second time as part of the `SemanticsObject` hierarchy. * * This prevents the `FlutterTextInputView` from receiving the focus - * due to swipping gesture. + * due to swiping gesture. * * There are other cases the `FlutterTextInputView` may receive * focus. One example is during screen changes, the accessibility @@ -1435,28 +1522,28 @@ static FlutterAutofillType autofillTypeOf(NSDictionary* configuration) { - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { NSString* method = call.method; id args = call.arguments; - if ([method isEqualToString:@"TextInput.show"]) { + if ([method isEqualToString:kShowMethod]) { [self showTextInput]; result(nil); - } else if ([method isEqualToString:@"TextInput.hide"]) { + } else if ([method isEqualToString:kHideMethod]) { [self hideTextInput]; result(nil); - } else if ([method isEqualToString:@"TextInput.setClient"]) { + } else if ([method isEqualToString:kSetClientMethod]) { [self setTextInputClient:[args[0] intValue] withConfiguration:args[1]]; result(nil); - } else if ([method isEqualToString:@"TextInput.setEditingState"]) { + } else if ([method isEqualToString:kSetEditingStateMethod]) { [self setTextInputEditingState:args]; result(nil); - } else if ([method isEqualToString:@"TextInput.clearClient"]) { + } else if ([method isEqualToString:kClearClientMethod]) { [self clearTextInputClient]; result(nil); - } else if ([method isEqualToString:@"TextInput.setEditableSizeAndTransform"]) { + } else if ([method isEqualToString:kSetEditableSizeAndTransformMethod]) { [self setEditableSizeAndTransform:args]; result(nil); - } else if ([method isEqualToString:@"TextInput.setMarkedTextRect"]) { + } else if ([method isEqualToString:kSetMarkedTextRectMethod]) { [self updateMarkedRect:args]; result(nil); - } else if ([method isEqualToString:@"TextInput.finishAutofillContext"]) { + } else if ([method isEqualToString:kFinishAutofillContextMethod]) { [self triggerAutofillSave:[args boolValue]]; result(nil); } else { @@ -1751,4 +1838,14 @@ static FlutterAutofillType autofillTypeOf(NSDictionary* configuration) { [_activeView setTextInputClient:0]; } +#pragma mark - +#pragma mark FlutterKeySecondaryResponder + +/** + * Handles key down events received from the view controller, responding YES if + * the event was handled. + */ +- (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { + return NO; +} @end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm similarity index 94% rename from engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m rename to engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm index def757b915..7b93a5f582 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm @@ -14,7 +14,6 @@ FLUTTER_ASSERT_ARC @interface FlutterTextInputView () @property(nonatomic, copy) NSString* autofillId; - - (void)setEditableTransform:(NSArray*)matrix; - (void)setTextInputState:(NSDictionary*)state; - (void)setMarkedRect:(CGRect)markedRect; @@ -83,11 +82,11 @@ FLUTTER_ASSERT_ARC for (FlutterTextInputView* autofillView in textInputPlugin.autofillContext.allValues) { autofillView.textInputDelegate = nil; } + engine = nil; [textInputPlugin.autofillContext removeAllObjects]; [textInputPlugin cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO]; [[[[textInputPlugin textInputView] superview] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)]; - [engine stopMocking]; [super tearDown]; } @@ -169,7 +168,7 @@ FLUTTER_ASSERT_ARC XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeDefault); // We should have only ever created one FlutterTextInputView. - XCTAssertEqual(inputFields.count, 1); + XCTAssertEqual(inputFields.count, 1ul); // The one FlutterTextInputView we inserted into the view hierarchy should be the text input // plugin's active text input view. @@ -226,8 +225,8 @@ FLUTTER_ASSERT_ARC toPosition:toPosition]; NSRange range = flutterRange.range; - XCTAssertEqual(range.location, 0); - XCTAssertEqual(range.length, 2); + XCTAssertEqual(range.location, 0ul); + XCTAssertEqual(range.length, 2ul); } - (void)testTextInRange { @@ -241,11 +240,11 @@ FLUTTER_ASSERT_ARC UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 20)]; NSString* substring = [inputView textInRange:range]; - XCTAssertEqual(substring.length, 4); + XCTAssertEqual(substring.length, 4ul); range = [FlutterTextRange rangeWithNSRange:NSMakeRange(10, 20)]; substring = [inputView textInRange:range]; - XCTAssertEqual(substring.length, 0); + XCTAssertEqual(substring.length, 0ul); } - (void)testNoZombies { @@ -262,7 +261,7 @@ FLUTTER_ASSERT_ARC - (void)testInputViewCrash { FlutterTextInputView* activeView = nil; @autoreleasepool { - FlutterTextInputPlugin* inputPlugin = [FlutterTextInputPlugin new]; + FlutterTextInputPlugin* inputPlugin = [[FlutterTextInputPlugin alloc] init]; activeView = inputPlugin.activeView; FlutterEngine* flutterEngine = [[FlutterEngine alloc] init]; activeView.textInputDelegate = (id)flutterEngine; @@ -550,7 +549,7 @@ FLUTTER_ASSERT_ARC - (void)testInputViewsHaveUIInteractions { if (@available(iOS 13.0, *)) { FlutterTextInputView* inputView = [[FlutterTextInputView alloc] init]; - XCTAssertGreaterThan(inputView.interactions.count, 0); + XCTAssertGreaterThan(inputView.interactions.count, 0ul); } } @@ -624,12 +623,12 @@ FLUTTER_ASSERT_ARC }]; XCTAssertEqual(self.viewsVisibleToAutofill.count, - [textInputPlugin.activeView isVisibleToAutofill] ? 1 : 0); + [textInputPlugin.activeView isVisibleToAutofill] ? 1ul : 0ul); XCTAssertNotEqual(textInputPlugin.textInputView, nil); // The active view should still be installed so it doesn't get // deallocated. - XCTAssertEqual(self.installedInputViews.count, 1); - XCTAssertEqual(textInputPlugin.autofillContext.count, 0); + XCTAssertEqual(self.installedInputViews.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul); } #pragma mark - Autofill - Tests @@ -656,12 +655,12 @@ FLUTTER_ASSERT_ARC [config setValue:@[ field1, field2 ] forKey:@"fields"]; [self setClientId:123 configuration:config]; - XCTAssertEqual(self.viewsVisibleToAutofill.count, 2); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); - XCTAssertEqual(textInputPlugin.autofillContext.count, 2); + XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 2); + XCTAssertEqual(self.installedInputViews.count, 2ul); XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); [self ensureOnlyActiveViewCanBecomeFirstResponder]; @@ -680,11 +679,11 @@ FLUTTER_ASSERT_ARC [self setClientId:123 configuration:config]; - XCTAssertEqual(self.viewsVisibleToAutofill.count, 2); - XCTAssertEqual(textInputPlugin.autofillContext.count, 3); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 3); + XCTAssertEqual(self.installedInputViews.count, 3ul); XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]); [self ensureOnlyActiveViewCanBecomeFirstResponder]; @@ -700,11 +699,11 @@ FLUTTER_ASSERT_ARC [self setClientId:124 configuration:config]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; - XCTAssertEqual(self.viewsVisibleToAutofill.count, 1); - XCTAssertEqual(textInputPlugin.autofillContext.count, 3); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 4); + XCTAssertEqual(self.installedInputViews.count, 4ul); // Old autofill input fields are still installed and reused. for (NSString* key in oldContext.allKeys) { @@ -719,11 +718,11 @@ FLUTTER_ASSERT_ARC [self setClientId:200 configuration:config]; // Reuse the input view instance from the last time. - XCTAssertEqual(self.viewsVisibleToAutofill.count, 1); - XCTAssertEqual(textInputPlugin.autofillContext.count, 3); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 4); + XCTAssertEqual(self.installedInputViews.count, 4ul); // Old autofill input fields are still installed and reused. for (NSString* key in oldContext.allKeys) { @@ -762,8 +761,8 @@ FLUTTER_ASSERT_ARC [config setValue:@[ field1, field2 ] forKey:@"fields"]; [self setClientId:123 configuration:config]; - XCTAssertEqual(self.viewsVisibleToAutofill.count, 2); - XCTAssertEqual(textInputPlugin.autofillContext.count, 2); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); [self ensureOnlyActiveViewCanBecomeFirstResponder]; [self commitAutofillContextAndVerify]; @@ -773,11 +772,11 @@ FLUTTER_ASSERT_ARC [self setClientId:123 configuration:config]; // Switch to a regular autofill group. [self setClientId:124 configuration:field3]; - XCTAssertEqual(self.viewsVisibleToAutofill.count, 1); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 3); - XCTAssertEqual(textInputPlugin.autofillContext.count, 2); + XCTAssertEqual(self.installedInputViews.count, 3ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul); XCTAssertNotEqual(textInputPlugin.textInputView, nil); [self ensureOnlyActiveViewCanBecomeFirstResponder]; @@ -787,13 +786,13 @@ FLUTTER_ASSERT_ARC // Now switch to an input field that does not autofill. [self setClientId:125 configuration:self.mutableTemplateCopy]; - XCTAssertEqual(self.viewsVisibleToAutofill.count, 0); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 0ul); // The active view should still be installed so it doesn't get // deallocated. [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 1); - XCTAssertEqual(textInputPlugin.autofillContext.count, 0); + XCTAssertEqual(self.installedInputViews.count, 1ul); + XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul); [self ensureOnlyActiveViewCanBecomeFirstResponder]; [self commitAutofillContextAndVerify]; @@ -827,8 +826,8 @@ FLUTTER_ASSERT_ARC NSArray* inputFields = self.installedInputViews; // Both fields are installed and visible because it's a password group. - XCTAssertEqual(inputFields.count, 2); - XCTAssertEqual(self.viewsVisibleToAutofill.count, 2); + XCTAssertEqual(inputFields.count, 2ul); + XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul); // Find the inactive autofillable input field. FlutterTextInputView* inactiveView = inputFields[1]; @@ -874,7 +873,7 @@ FLUTTER_ASSERT_ARC [regularField addEntriesFromDictionary:editingValue]; [self setClientId:123 configuration:regularField]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; - XCTAssertEqual(self.installedInputViews.count, 1); + XCTAssertEqual(self.installedInputViews.count, 1ul); FlutterTextInputView* oldInputView = self.installedInputViews[0]; XCTAssert([oldInputView.text isEqualToString:@"REGULAR_TEXT_FIELD"]); @@ -886,10 +885,10 @@ FLUTTER_ASSERT_ARC [self setClientId:124 configuration:self.mutablePasswordTemplateCopy]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; - XCTAssertEqual(self.installedInputViews.count, 2); + XCTAssertEqual(self.installedInputViews.count, 2ul); [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO]; - XCTAssertEqual(self.installedInputViews.count, 1); + XCTAssertEqual(self.installedInputViews.count, 1ul); // Verify the old input view is properly cleaned up. XCTAssert([oldInputView.text isEqualToString:@""]); @@ -902,13 +901,13 @@ FLUTTER_ASSERT_ARC [self setClientId:123 configuration:self.mutablePasswordTemplateCopy]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; - XCTAssertEqual(self.installedInputViews.count, 1); + XCTAssertEqual(self.installedInputViews.count, 1ul); // Add an input field that doesn't autofill. This should remove the password // field, but not immediately. [self setClientId:124 configuration:self.mutableTemplateCopy]; [self ensureOnlyActiveViewCanBecomeFirstResponder]; - XCTAssertEqual(self.installedInputViews.count, 2); + XCTAssertEqual(self.installedInputViews.count, 2ul); [self commitAutofillContextAndVerify]; } @@ -1018,8 +1017,7 @@ FLUTTER_ASSERT_ARC } - (void)testFlutterTextInputPluginRetainsFlutterTextInputView { - FlutterTextInputPlugin* myInputPlugin; - myInputPlugin = [[FlutterTextInputPlugin alloc] init]; + FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] init]; myInputPlugin.textInputDelegate = engine; __weak UIView* activeView; @autoreleasepool { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h new file mode 100644 index 0000000000..b5c568670a --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h @@ -0,0 +1,28 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_UI_PRESS_PROXY_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_UI_PRESS_PROXY_H_ + +#import +#include + +/** + * A event class that is a wrapper around a UIPress and a UIEvent to allow + * overidding for testing purposes, since UIKit doesn't allow creation of + * UIEvent or UIPress directly. + */ +API_AVAILABLE(ios(13.4)) +@interface FlutterUIPressProxy : NSObject + +- (instancetype)initWithPress:(UIPress*)press withEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)); + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)); +- (UIKey*)key API_AVAILABLE(ios(13.4)); +- (UIEventType)type API_AVAILABLE(ios(13.4)); +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)); + +@end + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTER_UI_PRESS_PROXY_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm new file mode 100644 index 0000000000..8c2ad30a45 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.mm @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import + +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" + +@interface FlutterUIPressProxy () +@property(nonatomic, readonly) UIPress* press; +@property(nonatomic, readonly) UIEvent* event; +@end + +@implementation FlutterUIPressProxy + +- (instancetype)initWithPress:(UIPress*)press withEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) { + self = [super init]; + if (self) { + _press = press; + _event = event; + } + return self; +} + +- (UIPressPhase)phase API_AVAILABLE(ios(13.4)) { + return _press.phase; +} + +- (UIKey*)key API_AVAILABLE(ios(13.4)) { + return _press.key; +} + +- (UIEventType)type API_AVAILABLE(ios(13.4)) { + return _event.type; +} + +- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) { + return _event.timestamp; +} + +@end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm index bb45f92137..905fcc0dd6 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm @@ -4,7 +4,6 @@ #define FML_USED_ON_EMBEDDER -#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" #include @@ -16,13 +15,19 @@ #include "flutter/runtime/ptrace_check.h" #include "flutter/shell/common/thread_host.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterBinaryMessengerRelay.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h" #import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h" #import "flutter/shell/platform/darwin/ios/platform_view_ios.h" +#import "flutter/shell/platform/embedder/embedder.h" static constexpr int kMicrosecondsPerSecond = 1000 * 1000; static constexpr CGFloat kScrollViewContentSize = 2.0; @@ -63,6 +68,12 @@ typedef struct MouseState { @property(nonatomic, readwrite, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI; @property(nonatomic, assign) BOOL isHomeIndicatorHidden; @property(nonatomic, assign) BOOL isPresentingViewControllerAnimating; + +/** + * Creates and registers plugins used by this view controller. + */ +- (void)addInternalPlugins; +- (void)deregisterNotifications; @end // The following conditional compilation defines an API 13 concept on earlier API targets so that @@ -607,10 +618,10 @@ static void sendFakeTouchEvent(FlutterEngine* engine, [self installFirstFrameCallback]; [_engine.get() platformViewsController]->SetFlutterView(_flutterView.get()); [_engine.get() platformViewsController]->SetFlutterViewController(self); - [_engine.get() platformView]->NotifyCreated(); + [_engine.get() iosPlatformView]->NotifyCreated(); } else { self.displayingFlutterUI = NO; - [_engine.get() platformView]->NotifyDestroyed(); + [_engine.get() iosPlatformView]->NotifyDestroyed(); [_engine.get() platformViewsController]->SetFlutterView(nullptr); [_engine.get() platformViewsController]->SetFlutterViewController(nullptr); } @@ -622,6 +633,9 @@ static void sendFakeTouchEvent(FlutterEngine* engine, TRACE_EVENT0("flutter", "viewDidLoad"); if (_engine && _engineNeedsLaunch) { + // Register internal plugins before starting the engine. + [self addInternalPlugins]; + [_engine.get() launchEngine:nil libraryURI:nil]; [_engine.get() setViewController:self]; _engineNeedsLaunch = NO; @@ -643,6 +657,25 @@ static void sendFakeTouchEvent(FlutterEngine* engine, [super viewDidLoad]; } +- (void)addInternalPlugins { + [self.keyboardManager release]; + self.keyboardManager = [[FlutterKeyboardManager alloc] init]; + FlutterSendKeyEvent sendEvent = + ^(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* userData) { + [_engine.get() sendKeyEvent:event callback:callback userData:userData]; + }; + [self.keyboardManager + addPrimaryResponder:[[FlutterEmbedderKeyResponder alloc] initWithSendEvent:sendEvent]]; + [self.keyboardManager addPrimaryResponder:[[FlutterChannelKeyResponder alloc] + initWithChannel:self.engine.keyEventChannel]]; + [self.keyboardManager addSecondaryResponder:self.engine.textInputPlugin]; +} + +- (void)removeInternalPlugins { + [self.keyboardManager release]; + self.keyboardManager = nil; +} + - (void)viewWillAppear:(BOOL)animated { TRACE_EVENT0("flutter", "viewWillAppear"); @@ -724,11 +757,16 @@ static void sendFakeTouchEvent(FlutterEngine* engine, } } -- (void)dealloc { +- (void)deregisterNotifications { [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc object:self userInfo:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)dealloc { + [self removeInternalPlugins]; + [self deregisterNotifications]; [super dealloc]; } @@ -1081,62 +1119,84 @@ static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) [self updateViewportMetrics]; } -- (void)dispatchPresses:(NSSet*)presses API_AVAILABLE(ios(13.4)) { +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())next API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { - for (UIPress* press in presses) { - if (press.key == nil || press.phase == UIPressPhaseStationary || - press.phase == UIPressPhaseChanged) { - continue; - } - NSMutableDictionary* keyMessage = [[@{ - @"keymap" : @"ios", - @"type" : @"unknown", - @"keyCode" : @(press.key.keyCode), - @"modifiers" : @(press.key.modifierFlags), - @"characters" : press.key.characters, - @"charactersIgnoringModifiers" : press.key.charactersIgnoringModifiers - } mutableCopy] autorelease]; - - if (press.phase == UIPressPhaseBegan) { - keyMessage[@"type"] = @"keydown"; - } else if (press.phase == UIPressPhaseEnded || press.phase == UIPressPhaseCancelled) { - keyMessage[@"type"] = @"keyup"; - } - - [[_engine.get() keyEventChannel] sendMessage:keyMessage]; - } + } else { + next(); + return; } + [self.keyboardManager handlePress:press nextAction:next]; } +// The documentation for presses* handlers (implemented below) is entirely +// unclear about how to handle the case where some, but not all, of the presses +// are handled here. I've elected to call super separately for each of the +// presses that aren't handled, but it's not clear if this is correct. It may be +// that iOS intends for us to either handle all or none of the presses, and pass +// the original set to super. I have not yet seen multiple presses in the set in +// the wild, however, so I suspect that the API is built for a tvOS remote or +// something, and perhaps only one ever appears in the set on iOS from a +// keyboard. + +// If you substantially change these presses overrides, consider also changing +// the similar ones in FlutterTextInputPlugin. They need to be overridden in +// both places to capture keys both inside and outside of a text field, but have +// slightly different implmentations. + - (void)pressesBegan:(NSSet*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { - [super pressesBegan:presses withEvent:event]; if (@available(iOS 13.4, *)) { - [self dispatchPresses:presses]; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [super pressesBegan:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesBegan:presses withEvent:event]; } } - (void)pressesChanged:(NSSet*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { - [super pressesChanged:presses withEvent:event]; if (@available(iOS 13.4, *)) { - [self dispatchPresses:presses]; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [super pressesChanged:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesChanged:presses withEvent:event]; } } - (void)pressesEnded:(NSSet*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { - [super pressesEnded:presses withEvent:event]; if (@available(iOS 13.4, *)) { - [self dispatchPresses:presses]; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [super pressesEnded:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesEnded:presses withEvent:event]; } } - (void)pressesCancelled:(NSSet*)presses withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) { - [super pressesCancelled:presses withEvent:event]; if (@available(iOS 13.4, *)) { - [self dispatchPresses:presses]; + for (UIPress* press in presses) { + [self handlePressEvent:[[FlutterUIPressProxy alloc] initWithPress:press withEvent:event] + nextAction:^() { + [super pressesCancelled:[NSSet setWithObject:press] withEvent:event]; + }]; + } + } else { + [super pressesCancelled:presses withEvent:event]; } } diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm index 83c62f0518..5cb96fd35d 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewControllerTest.mm @@ -8,28 +8,58 @@ #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h" +#import "flutter/shell/platform/embedder/embedder.h" FLUTTER_ASSERT_ARC +@interface FlutterEngine () +- (FlutterTextInputPlugin*)textInputPlugin; +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; +@end + namespace flutter { class PointerDataPacket {}; } -/// Sometimes we have to use a custom mock to avoid retain cycles in ocmock. +/// Sometimes we have to use a custom mock to avoid retain cycles in OCMock. +/// Used for testing low memory notification. @interface FlutterEnginePartialMock : FlutterEngine @property(nonatomic, strong) FlutterBasicMessageChannel* lifecycleChannel; +@property(nonatomic, strong) FlutterBasicMessageChannel* keyEventChannel; @property(nonatomic, weak) FlutterViewController* viewController; +@property(nonatomic, strong) FlutterTextInputPlugin* textInputPlugin; @property(nonatomic, assign) BOOL didCallNotifyLowMemory; +- (FlutterTextInputPlugin*)textInputPlugin; +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(nullable FlutterKeyEventCallback)callback + userData:(nullable void*)userData; @end @implementation FlutterEnginePartialMock @synthesize viewController; @synthesize lifecycleChannel; +@synthesize keyEventChannel; +@synthesize textInputPlugin; - (void)notifyLowMemory { _didCallNotifyLowMemory = YES; } + +- (void)sendKeyEvent:(const FlutterKeyEvent&)event + callback:(FlutterKeyEventCallback)callback + userData:(void*)userData API_AVAILABLE(ios(9.0)) { + NSAssert(callback != nullptr, @"Invalid callback"); + // Response is async, so we have to post it to the run loop instead of calling + // it directly. + CFRunLoopPerformBlock(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, ^() { + callback(true, userData); + }); +} @end @interface FlutterEngine () @@ -47,10 +77,12 @@ extern NSNotificationName const FlutterViewControllerWillDealloc; /// A simple mock class for FlutterEngine. /// -/// OCMockClass can't be used for FlutterEngine sometimes because OCMock retains arguments to +/// OCMClassMock can't be used for FlutterEngine sometimes because OCMock retains arguments to /// invocations and since the init for FlutterViewController calls a method on the /// FlutterEngine it creates a retain cycle that stops us from testing behaviors related to /// deleting FlutterViewControllers. +/// +/// Used for testing deallocation. @interface MockEngine : NSObject @end @@ -63,10 +95,6 @@ extern NSNotificationName const FlutterViewControllerWillDealloc; } @end -@interface FlutterViewControllerTest : XCTestCase -@property(nonatomic, strong) id mockEngine; -@end - // The following conditional compilation defines an API 13 concept on earlier API targets so that // a compiler compiling against API 12 or below does not blow up due to non-existent members. #if __IPHONE_OS_VERSION_MAX_ALLOWED < 130000 @@ -84,14 +112,25 @@ typedef enum UIAccessibilityContrast : NSInteger { @interface FlutterViewController (Tests) - (void)surfaceUpdated:(BOOL)appeared; - (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences; -- (void)dispatchPresses:(NSSet*)presses; +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())next API_AVAILABLE(ios(13.4)); - (void)scrollEvent:(UIPanGestureRecognizer*)recognizer; @end +@interface FlutterViewControllerTest : XCTestCase +@property(nonatomic, strong) id mockEngine; +@property(nonatomic, strong) id mockTextInputPlugin; +@property(nonatomic, strong) id messageSent; +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback; +@end + @implementation FlutterViewControllerTest - (void)setUp { self.mockEngine = OCMClassMock([FlutterEngine class]); + self.mockTextInputPlugin = OCMClassMock([FlutterTextInputPlugin class]); + OCMStub([self.mockEngine textInputPlugin]).andReturn(self.mockTextInputPlugin); + self.messageSent = nil; } - (void)tearDown { @@ -99,6 +138,8 @@ typedef enum UIAccessibilityContrast : NSInteger { // FlutterViewControllers from deallocing. [self.mockEngine stopMocking]; self.mockEngine = nil; + self.mockTextInputPlugin = nil; + self.messageSent = nil; } - (void)testViewDidDisappearDoesntPauseEngineWhenNotTheViewController { @@ -535,6 +576,7 @@ typedef enum UIAccessibilityContrast : NSInteger { nibName:nil bundle:nil]; XCTAssertFalse([realVC isViewLoaded], @"shouldn't have loaded since it hasn't been shown"); + engine.viewController = nil; } - (void)testHideOverlay { @@ -548,6 +590,7 @@ typedef enum UIAccessibilityContrast : NSInteger { [[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerHideHomeIndicator object:nil]; XCTAssertTrue(realVC.prefersHomeIndicatorAutoHidden, @""); + engine.viewController = nil; } - (void)testNotifyLowMemory { @@ -560,7 +603,18 @@ typedef enum UIAccessibilityContrast : NSInteger { [viewController beginAppearanceTransition:NO animated:NO]; [viewController endAppearanceTransition]; XCTAssertTrue(mockEngine.didCallNotifyLowMemory); - [viewControllerMock stopMocking]; +} + +- (void)sendMessage:(id _Nullable)message reply:(FlutterReply _Nullable)callback { + NSMutableDictionary* replyMessage = [@{ + @"handled" : @YES, + } mutableCopy]; + // Response is async, so we have to post it to the run loop instead of calling + // it directly. + self.messageSent = message; + CFRunLoopPerformBlock(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, ^() { + callback(replyMessage); + }); } - (void)testValidKeyUpEvent API_AVAILABLE(ios(13.4)) { @@ -569,36 +623,33 @@ typedef enum UIAccessibilityContrast : NSInteger { } else { return; } + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andCall(self, @selector(sendMessage:reply:)); + OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); + mockEngine.textInputPlugin = self.mockTextInputPlugin; - id keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); - OCMStub([self.mockEngine keyEventChannel]).andReturn(keyEventChannel); - - FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine + FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine nibName:nil bundle:nil]; - id testSet = [self fakeUiPressSetForPhase:UIPressPhaseBegan - keyCode:UIKeyboardHIDUsageKeyboardA - modifierFlags:UIKeyModifierShift - characters:@"a" - charactersIgnoringModifiers:@"A"]; + // Allocate the keyboard manager in the view controller by adding the internal + // plugins. + [vc addInternalPlugins]; - // Exercise behavior under test. - [vc dispatchPresses:testSet]; + [vc handlePressEvent:keyUpEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; - // Verify behavior. - OCMVerify([keyEventChannel - sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { - return [message[@"keymap"] isEqualToString:@"ios"] && - [message[@"type"] isEqualToString:@"keydown"] && - [message[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]] && - [message[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:131072]] && - [message[@"characters"] isEqualToString:@"a"] && - [message[@"charactersIgnoringModifiers"] isEqualToString:@"A"]; - }]]); - - // Clean up mocks - [keyEventChannel stopMocking]; + XCTAssert(self.messageSent != nil); + XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]); + XCTAssert([self.messageSent[@"type"] isEqualToString:@"keyup"]); + XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]); + XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]); + XCTAssert([self.messageSent[@"characters"] isEqualToString:@""]); + XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@""]); + [vc deregisterNotifications]; } - (void)testValidKeyDownEvent API_AVAILABLE(ios(13.4)) { @@ -608,35 +659,34 @@ typedef enum UIAccessibilityContrast : NSInteger { return; } - id keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); - OCMStub([self.mockEngine keyEventChannel]).andReturn(keyEventChannel); + FlutterEnginePartialMock* mockEngine = [[FlutterEnginePartialMock alloc] init]; + mockEngine.keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([mockEngine.keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andCall(self, @selector(sendMessage:reply:)); + OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); + mockEngine.textInputPlugin = self.mockTextInputPlugin; - FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine - nibName:nil - bundle:nil]; + __strong FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:mockEngine + nibName:nil + bundle:nil]; + // Allocate the keyboard manager in the view controller by adding the internal + // plugins. + [vc addInternalPlugins]; - id testSet = [self fakeUiPressSetForPhase:UIPressPhaseEnded - keyCode:UIKeyboardHIDUsageKeyboardA - modifierFlags:UIKeyModifierShift - characters:@"a" - charactersIgnoringModifiers:@"A"]; + [vc handlePressEvent:keyDownEvent(UIKeyboardHIDUsageKeyboardA, UIKeyModifierShift, 123.0f, "A", + "a") + nextAction:^(){ + }]; - // Exercise behavior under test. - [vc dispatchPresses:testSet]; - - // Verify behavior. - OCMVerify([keyEventChannel - sendMessage:[OCMArg checkWithBlock:^BOOL(id message) { - return [message[@"keymap"] isEqualToString:@"ios"] && - [message[@"type"] isEqualToString:@"keyup"] && - [message[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]] && - [message[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:131072]] && - [message[@"characters"] isEqualToString:@"a"] && - [message[@"charactersIgnoringModifiers"] isEqualToString:@"A"]; - }]]); - - // Clean up mocks - [keyEventChannel stopMocking]; + XCTAssert(self.messageSent != nil); + XCTAssert([self.messageSent[@"keymap"] isEqualToString:@"ios"]); + XCTAssert([self.messageSent[@"type"] isEqualToString:@"keydown"]); + XCTAssert([self.messageSent[@"keyCode"] isEqualToNumber:[NSNumber numberWithInt:4]]); + XCTAssert([self.messageSent[@"modifiers"] isEqualToNumber:[NSNumber numberWithInt:0]]); + XCTAssert([self.messageSent[@"characters"] isEqualToString:@"A"]); + XCTAssert([self.messageSent[@"charactersIgnoringModifiers"] isEqualToString:@"a"]); + [vc deregisterNotifications]; + vc = nil; } - (void)testIgnoredKeyEvents API_AVAILABLE(ios(13.4)) { @@ -645,34 +695,36 @@ typedef enum UIAccessibilityContrast : NSInteger { } else { return; } - id keyEventChannel = OCMClassMock([FlutterBasicMessageChannel class]); + OCMStub([keyEventChannel sendMessage:[OCMArg any] reply:[OCMArg any]]) + .andCall(self, @selector(sendMessage:reply:)); + OCMStub([self.mockTextInputPlugin handlePress:[OCMArg any]]).andReturn(YES); OCMStub([self.mockEngine keyEventChannel]).andReturn(keyEventChannel); FlutterViewController* vc = [[FlutterViewController alloc] initWithEngine:self.mockEngine nibName:nil bundle:nil]; - id emptySet = [NSSet set]; - id ignoredSet = [self fakeUiPressSetForPhase:UIPressPhaseStationary - keyCode:UIKeyboardHIDUsageKeyboardA - modifierFlags:UIKeyModifierShift - characters:@"a" - charactersIgnoringModifiers:@"A"]; + // Allocate the keyboard manager in the view controller by adding the internal + // plugins. + [vc addInternalPlugins]; - id mockUiPress = OCMClassMock([UIPress class]); - OCMStub([mockUiPress phase]).andReturn(UIPressPhaseBegan); - id emptyKeySet = [NSSet setWithArray:@[ mockUiPress ]]; - // Exercise behavior under test. - [vc dispatchPresses:emptySet]; - [vc dispatchPresses:ignoredSet]; - [vc dispatchPresses:emptyKeySet]; + [vc handlePressEvent:keyEventWithPhase(UIPressPhaseStationary, UIKeyboardHIDUsageKeyboardA, + UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; + [vc handlePressEvent:keyEventWithPhase(UIPressPhaseCancelled, UIKeyboardHIDUsageKeyboardA, + UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; + [vc handlePressEvent:keyEventWithPhase(UIPressPhaseChanged, UIKeyboardHIDUsageKeyboardA, + UIKeyModifierShift, 123.0) + nextAction:^(){ + }]; - // Verify behavior. + XCTAssert(self.messageSent == nil); OCMVerify(never(), [keyEventChannel sendMessage:[OCMArg any]]); - - // Clean up mocks - [keyEventChannel stopMocking]; + [vc deregisterNotifications]; } - (void)testPanGestureRecognizer API_AVAILABLE(ios(13.4)) { @@ -722,29 +774,4 @@ typedef enum UIAccessibilityContrast : NSInteger { dispatchPointerDataPacket:std::make_unique()]; } -- (NSSet*)fakeUiPressSetForPhase:(UIPressPhase)phase - keyCode:(UIKeyboardHIDUsage)keyCode - modifierFlags:(UIKeyModifierFlags)modifierFlags - characters:(NSString*)characters - charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers - API_AVAILABLE(ios(13.4)) { - if (@available(iOS 13.4, *)) { - // noop - } else { - return [NSSet set]; - } - id mockUiPress = OCMClassMock([UIPress class]); - OCMStub([mockUiPress phase]).andReturn(phase); - - id mockUiKey = OCMClassMock([UIKey class]); - OCMStub([mockUiKey keyCode]).andReturn(keyCode); - OCMStub([mockUiKey modifierFlags]).andReturn(modifierFlags); - OCMStub([mockUiKey characters]).andReturn(characters); - OCMStub([mockUiKey charactersIgnoringModifiers]).andReturn(charactersIgnoringModifiers); - - OCMStub([mockUiPress key]).andReturn(mockUiKey); - - return [NSSet setWithArray:@[ mockUiPress ]]; -} - @end diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h index c3ac4bd2a6..b6b655026b 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h @@ -8,7 +8,10 @@ #include "flutter/fml/memory/weak_ptr.h" #import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h" #import "flutter/shell/platform/darwin/ios/framework/Source/FlutterRestorationPlugin.h" +#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterUIPressProxy.h" namespace flutter { class FlutterPlatformViewsController; @@ -27,6 +30,7 @@ extern NSNotificationName const FlutterViewControllerShowHomeIndicator; @property(nonatomic, readonly) BOOL isPresentingViewController; @property(nonatomic, readonly) BOOL isVoiceOverRunning; +@property(nonatomic) FlutterKeyboardManager* keyboardManager; - (fml::WeakPtr)getWeakPtr; - (std::shared_ptr&)platformViewsController; - (FlutterRestorationPlugin*)restorationPlugin; @@ -34,6 +38,12 @@ extern NSNotificationName const FlutterViewControllerShowHomeIndicator; // The `phase`s in `touches` are ignored. - (void)forceTouchesCancelled:(NSSet*)touches; +// Accepts keypress events, and then calls |nextAction| if the event was not +// handled. +- (void)handlePressEvent:(FlutterUIPressProxy*)press + nextAction:(void (^)())nextAction API_AVAILABLE(ios(13.4)); +- (void)addInternalPlugins; +- (void)deregisterNotifications; @end #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERVIEWCONTROLLER_INTERNAL_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.mm new file mode 100644 index 0000000000..cb1e4d0e6c --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap.mm @@ -0,0 +1,378 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" + +// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT +// This file is generated by +// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not +// be edited directly. +// +// Edit the template +// flutter/flutter:dev/tools/gen_keycodes/data/ios_key_code_map_cc.tmpl instead. +// +// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. + +/** + * Mask for the 32-bit value portion of the key code. + * + * This is used by platform-specific code to generate Flutter key codes. + */ +const uint64_t kValueMask = 0x000ffffffff; + +/** + * Mask for the platform prefix portion of the key code. + * + * This is used by platform-specific code to generate Flutter key codes. + */ +const uint64_t kPlatformMask = 0x0ff00000000; + +/** + * The code prefix for keys which have a Unicode representation. + * + * This is used by platform-specific code to generate Flutter key codes. + */ +const uint64_t kUnicodePlane = 0x00000000000; + +/** + * Mask for the auto-generated bit portion of the key code. + * + * This is used by platform-specific code to generate new Flutter key codes for + * keys which are not recognized. + */ +const uint64_t kAutogeneratedMask = 0x10000000000; + +/** + * Mask for the synonym pseudo-keys generated for keys which appear in more than + * one place on the keyboard. + * + * IDs in this range are used to represent keys which appear in multiple places + * on the keyboard, such as the SHIFT, ALT, CTRL, and numeric keypad keys. These + * key codes will never be generated by the key event system, but may be used in + * key maps to represent the union of all the keys of each type in order to + * match them. + * + * To look up the synonyms that are defined, look in the [synonyms] map. + */ +const uint64_t kSynonymMask = 0x20000000000; + +/** + * The code prefix for keys which do not have a Unicode representation. + * + * This is used by platform-specific code to generate Flutter key codes using + * HID Usage codes. + */ +const uint64_t kHidPlane = 0x00100000000; + +// Maps iOS-specific key code values representing PhysicalKeyboardKey. +// +// iOS doesn't provide a scan code, but a virtual keycode to represent a physical key. +const std::map keyCodeToPhysicalKey = { + {0x00000000, 0x00070000}, // usbReserved + {0x00000001, 0x00070001}, // usbErrorRollOver + {0x00000002, 0x00070002}, // usbPostFail + {0x00000003, 0x00070003}, // usbErrorUndefined + {0x00000004, 0x00070004}, // keyA + {0x00000005, 0x00070005}, // keyB + {0x00000006, 0x00070006}, // keyC + {0x00000007, 0x00070007}, // keyD + {0x00000008, 0x00070008}, // keyE + {0x00000009, 0x00070009}, // keyF + {0x0000000a, 0x0007000a}, // keyG + {0x0000000b, 0x0007000b}, // keyH + {0x0000000c, 0x0007000c}, // keyI + {0x0000000d, 0x0007000d}, // keyJ + {0x0000000e, 0x0007000e}, // keyK + {0x0000000f, 0x0007000f}, // keyL + {0x00000010, 0x00070010}, // keyM + {0x00000011, 0x00070011}, // keyN + {0x00000012, 0x00070012}, // keyO + {0x00000013, 0x00070013}, // keyP + {0x00000014, 0x00070014}, // keyQ + {0x00000015, 0x00070015}, // keyR + {0x00000016, 0x00070016}, // keyS + {0x00000017, 0x00070017}, // keyT + {0x00000018, 0x00070018}, // keyU + {0x00000019, 0x00070019}, // keyV + {0x0000001a, 0x0007001a}, // keyW + {0x0000001b, 0x0007001b}, // keyX + {0x0000001c, 0x0007001c}, // keyY + {0x0000001d, 0x0007001d}, // keyZ + {0x0000001e, 0x0007001e}, // digit1 + {0x0000001f, 0x0007001f}, // digit2 + {0x00000020, 0x00070020}, // digit3 + {0x00000021, 0x00070021}, // digit4 + {0x00000022, 0x00070022}, // digit5 + {0x00000023, 0x00070023}, // digit6 + {0x00000024, 0x00070024}, // digit7 + {0x00000025, 0x00070025}, // digit8 + {0x00000026, 0x00070026}, // digit9 + {0x00000027, 0x00070027}, // digit0 + {0x00000028, 0x00070028}, // enter + {0x00000029, 0x00070029}, // escape + {0x0000002a, 0x0007002a}, // backspace + {0x0000002b, 0x0007002b}, // tab + {0x0000002c, 0x0007002c}, // space + {0x0000002d, 0x0007002d}, // minus + {0x0000002e, 0x0007002e}, // equal + {0x0000002f, 0x0007002f}, // bracketLeft + {0x00000030, 0x00070030}, // bracketRight + {0x00000031, 0x00070031}, // backslash + {0x00000033, 0x00070033}, // semicolon + {0x00000034, 0x00070034}, // quote + {0x00000035, 0x00070035}, // backquote + {0x00000036, 0x00070036}, // comma + {0x00000037, 0x00070037}, // period + {0x00000038, 0x00070038}, // slash + {0x00000039, 0x00070039}, // capsLock + {0x0000003a, 0x0007003a}, // f1 + {0x0000003b, 0x0007003b}, // f2 + {0x0000003c, 0x0007003c}, // f3 + {0x0000003d, 0x0007003d}, // f4 + {0x0000003e, 0x0007003e}, // f5 + {0x0000003f, 0x0007003f}, // f6 + {0x00000040, 0x00070040}, // f7 + {0x00000041, 0x00070041}, // f8 + {0x00000042, 0x00070042}, // f9 + {0x00000043, 0x00070043}, // f10 + {0x00000044, 0x00070044}, // f11 + {0x00000045, 0x00070045}, // f12 + {0x00000046, 0x00070046}, // printScreen + {0x00000047, 0x00070047}, // scrollLock + {0x00000048, 0x00070048}, // pause + {0x00000049, 0x00070049}, // insert + {0x0000004a, 0x0007004a}, // home + {0x0000004b, 0x0007004b}, // pageUp + {0x0000004c, 0x0007004c}, // delete + {0x0000004d, 0x0007004d}, // end + {0x0000004e, 0x0007004e}, // pageDown + {0x0000004f, 0x0007004f}, // arrowRight + {0x00000050, 0x00070050}, // arrowLeft + {0x00000051, 0x00070051}, // arrowDown + {0x00000052, 0x00070052}, // arrowUp + {0x00000053, 0x00070053}, // numLock + {0x00000054, 0x00070054}, // numpadDivide + {0x00000055, 0x00070055}, // numpadMultiply + {0x00000056, 0x00070056}, // numpadSubtract + {0x00000057, 0x00070057}, // numpadAdd + {0x00000058, 0x00070058}, // numpadEnter + {0x00000059, 0x00070059}, // numpad1 + {0x0000005a, 0x0007005a}, // numpad2 + {0x0000005b, 0x0007005b}, // numpad3 + {0x0000005c, 0x0007005c}, // numpad4 + {0x0000005d, 0x0007005d}, // numpad5 + {0x0000005e, 0x0007005e}, // numpad6 + {0x0000005f, 0x0007005f}, // numpad7 + {0x00000060, 0x00070060}, // numpad8 + {0x00000061, 0x00070061}, // numpad9 + {0x00000062, 0x00070062}, // numpad0 + {0x00000063, 0x00070063}, // numpadDecimal + {0x00000064, 0x00070064}, // intlBackslash + {0x00000065, 0x00070065}, // contextMenu + {0x00000066, 0x00070066}, // power + {0x00000067, 0x00070067}, // numpadEqual + {0x00000068, 0x00070068}, // f13 + {0x00000069, 0x00070069}, // f14 + {0x0000006a, 0x0007006a}, // f15 + {0x0000006b, 0x0007006b}, // f16 + {0x0000006c, 0x0007006c}, // f17 + {0x0000006d, 0x0007006d}, // f18 + {0x0000006e, 0x0007006e}, // f19 + {0x0000006f, 0x0007006f}, // f20 + {0x00000070, 0x00070070}, // f21 + {0x00000071, 0x00070071}, // f22 + {0x00000072, 0x00070072}, // f23 + {0x00000073, 0x00070073}, // f24 + {0x00000074, 0x00070074}, // open + {0x00000075, 0x00070075}, // help + {0x00000077, 0x00070077}, // select + {0x00000079, 0x00070079}, // again + {0x0000007a, 0x0007007a}, // undo + {0x0000007b, 0x0007007b}, // cut + {0x0000007c, 0x0007007c}, // copy + {0x0000007d, 0x0007007d}, // paste + {0x0000007e, 0x0007007e}, // find + {0x0000007f, 0x0007007f}, // audioVolumeMute + {0x00000080, 0x00070080}, // audioVolumeUp + {0x00000081, 0x00070081}, // audioVolumeDown + {0x00000085, 0x00070085}, // numpadComma + {0x00000087, 0x00070087}, // intlRo + {0x00000088, 0x00070088}, // kanaMode + {0x00000089, 0x00070089}, // intlYen + {0x0000008a, 0x0007008a}, // convert + {0x0000008b, 0x0007008b}, // nonConvert + {0x00000090, 0x00070090}, // lang1 + {0x00000091, 0x00070091}, // lang2 + {0x00000092, 0x00070092}, // lang3 + {0x00000093, 0x00070093}, // lang4 + {0x00000094, 0x00070094}, // lang5 + {0x0000009b, 0x0007009b}, // abort + {0x000000a3, 0x000700a3}, // props + {0x000000b6, 0x000700b6}, // numpadParenLeft + {0x000000b7, 0x000700b7}, // numpadParenRight + {0x000000bb, 0x000700bb}, // numpadBackspace + {0x000000d0, 0x000700d0}, // numpadMemoryStore + {0x000000d1, 0x000700d1}, // numpadMemoryRecall + {0x000000d2, 0x000700d2}, // numpadMemoryClear + {0x000000d3, 0x000700d3}, // numpadMemoryAdd + {0x000000d4, 0x000700d4}, // numpadMemorySubtract + {0x000000d7, 0x000700d7}, // numpadSignChange + {0x000000d8, 0x000700d8}, // numpadClear + {0x000000d9, 0x000700d9}, // numpadClearEntry + {0x000000e0, 0x000700e0}, // controlLeft + {0x000000e1, 0x000700e1}, // shiftLeft + {0x000000e2, 0x000700e2}, // altLeft + {0x000000e3, 0x000700e3}, // metaLeft + {0x000000e4, 0x000700e4}, // controlRight + {0x000000e5, 0x000700e5}, // shiftRight + {0x000000e6, 0x000700e6}, // altRight + {0x000000e7, 0x000700e7}, // metaRight +}; + +// Maps iOS-specific virtual key code values to logical keys representing +// LogicalKeyboardKey +const std::map keyCodeToLogicalKey = { + {0x0000002a, 0x01000000008}, // Backspace + {0x0000002b, 0x01000000009}, // Tab + {0x00000028, 0x0100000000d}, // Enter + {0x00000029, 0x0100000001b}, // Escape + {0x0000004c, 0x0100000007f}, // Delete + {0x00000039, 0x01000000104}, // CapsLock + {0x00000053, 0x0100000010a}, // NumLock + {0x00000051, 0x01000000301}, // ArrowDown + {0x00000050, 0x01000000302}, // ArrowLeft + {0x0000004f, 0x01000000303}, // ArrowRight + {0x00000052, 0x01000000304}, // ArrowUp + {0x0000004d, 0x01000000305}, // End + {0x0000004a, 0x01000000306}, // Home + {0x0000004e, 0x01000000307}, // PageDown + {0x0000004b, 0x01000000308}, // PageUp + {0x00000049, 0x01000000407}, // Insert + {0x00000065, 0x01000000505}, // ContextMenu + {0x0000003a, 0x01000000801}, // F1 + {0x0000003b, 0x01000000802}, // F2 + {0x0000003c, 0x01000000803}, // F3 + {0x0000003d, 0x01000000804}, // F4 + {0x0000003e, 0x01000000805}, // F5 + {0x0000003f, 0x01000000806}, // F6 + {0x00000040, 0x01000000807}, // F7 + {0x00000041, 0x01000000808}, // F8 + {0x00000042, 0x01000000809}, // F9 + {0x00000043, 0x0100000080a}, // F10 + {0x00000044, 0x0100000080b}, // F11 + {0x00000045, 0x0100000080c}, // F12 + {0x00000068, 0x0100000080d}, // F13 + {0x00000069, 0x0100000080e}, // F14 + {0x0000006a, 0x0100000080f}, // F15 + {0x0000006b, 0x01000000810}, // F16 + {0x0000006c, 0x01000000811}, // F17 + {0x0000006d, 0x01000000812}, // F18 + {0x0000006e, 0x01000000813}, // F19 + {0x0000006f, 0x01000000814}, // F20 + {0x00000081, 0x01000000a0f}, // AudioVolumeDown + {0x00000080, 0x01000000a10}, // AudioVolumeUp + {0x0000007f, 0x01000000a11}, // AudioVolumeMute + {0x00000087, 0x01100070087}, // IntlRo + {0x00000089, 0x01100070089}, // IntlYen + {0x00000090, 0x01100070090}, // Lang1 + {0x00000091, 0x01100070091}, // Lang2 + {0x00000092, 0x01100070092}, // Lang3 + {0x00000093, 0x01100070093}, // Lang4 + {0x00000094, 0x01100070094}, // Lang5 + {0x000000e2, 0x30000000102}, // AltLeft + {0x000000e0, 0x30000000105}, // ControlLeft + {0x000000e3, 0x30000000109}, // MetaLeft + {0x000000e1, 0x3000000010d}, // ShiftLeft + {0x000000e6, 0x40000000102}, // AltRight + {0x000000e4, 0x40000000105}, // ControlRight + {0x000000e7, 0x40000000109}, // MetaRight + {0x000000e5, 0x4000000010d}, // ShiftRight + {0x00000058, 0x5000000000d}, // NumpadEnter + {0x00000055, 0x5000000002a}, // NumpadMultiply + {0x00000057, 0x5000000002b}, // NumpadAdd + {0x00000085, 0x5000000002c}, // NumpadComma + {0x00000056, 0x5000000002d}, // NumpadSubtract + {0x00000063, 0x5000000002e}, // NumpadDecimal + {0x00000054, 0x5000000002f}, // NumpadDivide + {0x00000062, 0x50000000030}, // Numpad0 + {0x00000059, 0x50000000031}, // Numpad1 + {0x0000005a, 0x50000000032}, // Numpad2 + {0x0000005b, 0x50000000033}, // Numpad3 + {0x0000005c, 0x50000000034}, // Numpad4 + {0x0000005d, 0x50000000035}, // Numpad5 + {0x0000005e, 0x50000000036}, // Numpad6 + {0x0000005f, 0x50000000037}, // Numpad7 + {0x00000060, 0x50000000038}, // Numpad8 + {0x00000061, 0x50000000039}, // Numpad9 + {0x00000067, 0x5000000003d}, // NumpadEqual +}; + +// Maps iOS-specific virtual key codes to an equivalent modifier flag enum +// value. +const std::map keyCodeToModifierFlag = { + {0x000000e1, kModifierFlagShiftLeft}, {0x000000e5, kModifierFlagShiftRight}, + {0x000000e0, kModifierFlagControlLeft}, {0x000000e4, kModifierFlagControlRight}, + {0x000000e2, kModifierFlagAltLeft}, {0x000000e6, kModifierFlagAltRight}, + {0x000000e3, kModifierFlagMetaLeft}, {0x000000e7, kModifierFlagMetaRight}, +}; + +// Maps modifier flag enum values to an iOS-specific virtual key code. +const std::map modifierFlagToKeyCode = { + {kModifierFlagShiftLeft, 0x000000e1}, {kModifierFlagShiftRight, 0x000000e5}, + {kModifierFlagControlLeft, 0x000000e0}, {kModifierFlagControlRight, 0x000000e4}, + {kModifierFlagAltLeft, 0x000000e2}, {kModifierFlagAltRight, 0x000000e6}, + {kModifierFlagMetaLeft, 0x000000e3}, {kModifierFlagMetaRight, 0x000000e7}, +}; + +const std::map sidedModifierToAny = { + {kModifierFlagShiftLeft, kModifierFlagShiftAny}, + {kModifierFlagShiftRight, kModifierFlagShiftAny}, + {kModifierFlagControlLeft, kModifierFlagControlAny}, + {kModifierFlagControlRight, kModifierFlagControlAny}, + {kModifierFlagAltLeft, kModifierFlagAltAny}, + {kModifierFlagAltRight, kModifierFlagAltAny}, + {kModifierFlagMetaLeft, kModifierFlagMetaAny}, + {kModifierFlagMetaRight, kModifierFlagMetaAny}, +}; + +const std::map anyModifierToLeft = { + {kModifierFlagShiftAny, kModifierFlagShiftLeft}, + {kModifierFlagControlAny, kModifierFlagControlLeft}, + {kModifierFlagAltAny, kModifierFlagAltLeft}, + {kModifierFlagMetaAny, kModifierFlagMetaLeft}, +}; + +// A set of virtual key codes mapping to function keys, so that may be +// identified as such. +const std::set functionKeyCodes = { + 0x0000003a, // f1 + 0x0000003b, // f2 + 0x0000003c, // f3 + 0x0000003d, // f4 + 0x0000003e, // f5 + 0x0000003f, // f6 + 0x00000040, // f7 + 0x00000041, // f8 + 0x00000042, // f9 + 0x00000043, // f10 + 0x00000044, // f11 + 0x00000045, // f12 + 0x00000068, // f13 + 0x00000069, // f14 + 0x0000006a, // f15 + 0x0000006b, // f16 + 0x0000006c, // f17 + 0x0000006d, // f18 + 0x0000006e, // f19 + 0x0000006f, // f20 + 0x00000070, // f21 + 0x00000071, // f22 + 0x00000072, // f23 + 0x00000073, // f24 +}; + +const uint64_t kCapsLockPhysicalKey = 0x00070039; +const uint64_t kCapsLockLogicalKey = 0x1000000104; diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h new file mode 100644 index 0000000000..d303571ae5 --- /dev/null +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h @@ -0,0 +1,122 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEY_CODE_MAP_INTERNAL_H_ +#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEY_CODE_MAP_INTERNAL_H_ + +#import +#include +#include + +/** + * Maps iOS-specific key code values representing |PhysicalKeyboardKey|. + * + * MacOS doesn't provide a scan code, but a virtual keycode to represent a + * physical key. + */ +extern const std::map keyCodeToPhysicalKey; + +/** + * A map from iOS key codes to Flutter's logical key values. + * + * This is used to derive logical keys that can't or shouldn't be derived from + * |charactersIgnoringModifiers|. + */ +extern const std::map keyCodeToLogicalKey; + +// Several mask constants. See KeyCodeMap.mm for their descriptions. + +extern const uint64_t kValueMask; +extern const uint64_t kPlatformMask; +extern const uint64_t kUnicodePlane; +extern const uint64_t kHidPlane; +extern const uint64_t kAutogeneratedMask; +extern const uint64_t kSynonymMask; + +/** + * The code prefix for keys from iOS which do not have a Unicode + * representation. + */ +static const uint64_t kIOSPlane = 0x00400000000; + +/** + * The physical key for CapsLock, which needs special handling. + */ +extern const uint64_t kCapsLockPhysicalKey; + +/** + * The logical key for CapsLock, which needs special handling. + */ +extern const uint64_t kCapsLockLogicalKey; + +/** + * Bits in |UIKey.modifierFlags| indicating whether a modifier key is pressed. + */ +typedef enum { + // These sided flags are not in any official Apple docs, they are derived from + // experiments. + kModifierFlagControlLeft = 0x1, + kModifierFlagShiftLeft = 0x2, + kModifierFlagShiftRight = 0x4, + kModifierFlagMetaLeft = 0x8, + kModifierFlagMetaRight = 0x10, + kModifierFlagAltLeft = 0x20, + kModifierFlagAltRight = 0x40, + kModifierFlagControlRight = 0x2000, + + // These are equivalent to non-sided iOS values. + kModifierFlagCapsLock = UIKeyModifierAlphaShift, // 0x010000 + kModifierFlagShiftAny = UIKeyModifierShift, // 0x020000 + kModifierFlagControlAny = UIKeyModifierControl, // 0x040000 + kModifierFlagAltAny = UIKeyModifierAlternate, // 0x080000 + kModifierFlagMetaAny = UIKeyModifierCommand, // 0x100000 + kModifierFlagNumPadKey = UIKeyModifierNumericPad // 0x200000 +} ModifierFlag; + +/** + * A mask of all the modifier flags that represent a modifier being pressed, but + * not whether it is the left or right modifier. + */ +constexpr uint32_t kModifierFlagAnyMask = + kModifierFlagShiftAny | kModifierFlagControlAny | kModifierFlagAltAny | + kModifierFlagMetaAny; + +/** + * A mask of the modifier flags that represent only left or right modifier + * keys, and not the generic "Any" mask. + */ +constexpr uint32_t kModifierFlagSidedMask = + kModifierFlagControlLeft | kModifierFlagShiftLeft | + kModifierFlagShiftRight | kModifierFlagMetaLeft | kModifierFlagMetaRight | + kModifierFlagAltLeft | kModifierFlagAltRight | kModifierFlagControlRight; + +/** + * Map |UIKey.keyCode| to the matching sided modifier in UIEventModifierFlags. + */ +extern const std::map keyCodeToModifierFlag; + +/** + * Map a bit of bitmask of sided modifiers in UIEventModifierFlags to their + * corresponding |UIKey.keyCode|. + */ +extern const std::map modifierFlagToKeyCode; + +/** + * Maps a sided modifier key to the corresponding flag matching either side of + * that type of modifier. + */ +extern const std::map sidedModifierToAny; + +/** + * Maps a non-sided modifier key to the corresponding flag matching the left key + * of that type of modifier. + */ +extern const std::map anyModifierToLeft; + +/** + * A set of keycodes corresponding to function keys. + */ +extern const std::set functionKeyCodes; + +#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_KEY_CODE_MAP_INTERNAL_H_ diff --git a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h index 3af69b7b2b..4010da254b 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h +++ b/engine/src/flutter/shell/platform/darwin/ios/platform_view_ios.h @@ -90,6 +90,9 @@ class PlatformViewIOS final : public PlatformView { // |PlatformView| PointerDataDispatcherMaker GetDispatcherMaker() override; + void DispatchKeyDataPacket(std::unique_ptr packet, + std::function callback); + // |PlatformView| void SetSemanticsEnabled(bool enabled) override; diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm index 0f59f61bfb..b6aaae1376 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.mm @@ -5,7 +5,7 @@ #import #import "FlutterChannelKeyResponder.h" -#import "KeyCodeMap_internal.h" +#import "KeyCodeMap_Internal.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/embedder/embedder.h" @@ -74,15 +74,15 @@ keyMessage[@"characters"] = event.characters; keyMessage[@"charactersIgnoringModifiers"] = event.charactersIgnoringModifiers; } - [_channel sendMessage:keyMessage - reply:^(id reply) { - if (!reply) { - return callback(true); - } - // Only propagate the event to other responders if the framework didn't handle - // it. - callback([[reply valueForKey:@"handled"] boolValue]); - }]; + [self.channel sendMessage:keyMessage + reply:^(id reply) { + if (!reply) { + return callback(true); + } + // Only propagate the event to other responders if the framework didn't + // handle it. + callback([[reply valueForKey:@"handled"] boolValue]); + }]; } #pragma mark - Private diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm index 5c9c48bd04..5d5dcd2249 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.mm @@ -5,7 +5,7 @@ #import #import "FlutterEmbedderKeyResponder.h" -#import "KeyCodeMap_internal.h" +#import "KeyCodeMap_Internal.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #import "flutter/shell/platform/embedder/embedder.h" @@ -251,7 +251,7 @@ const char* getEventString(NSString* characters) { * throughout |FlutterEmbedderKeyResponder.handleEvent|. * * A callback can either be handled with |pendTo:withId:|, or with |resolveTo:|. - * Either way, the callback can not be handled again, or an assertion will be + * Either way, the callback cannot be handled again, or an assertion will be * thrown. */ @interface FlutterKeyCallbackGuard : NSObject @@ -609,7 +609,6 @@ const char* getEventString(NSString* characters) { [callback resolveTo:TRUE]; return; } - bool isSynthesized = false; if (pressedLogicalKey == nil) { [self updateKey:physicalKey asPressed:logicalKey]; @@ -622,7 +621,7 @@ const char* getEventString(NSString* characters) { .physical = physicalKey, .logical = pressedLogicalKey == nil ? logicalKey : [pressedLogicalKey unsignedLongLongValue], .character = getEventString(event.characters), - .synthesized = isSynthesized, + .synthesized = false, }; [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; } diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h index 2ddae205e1..fc83771d2d 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h @@ -13,11 +13,11 @@ * A hub that manages how key events are dispatched to various Flutter key * responders, and whether the event is propagated to the next NSResponder. * - * This class manage one or more primary responders, as well as zero or more + * This class manages one or more primary responders, as well as zero or more * secondary responders. * * An event that is received by |handleEvent| is first dispatched to *all* - * primary responders. Each primary responder responds *ascynchronously* with a + * primary responders. Each primary responder responds *asynchronously* with a * boolean, indicating whether it handles the event. * * An event that is not handled by any primary responders is then passed to to diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm index 9faf00103f..63e6487368 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm @@ -52,9 +52,9 @@ event.type != NSEventTypeFlagsChanged) { return; } - // Having no primary responders require extra logic, but since Flutter adds - // all primary responders in hard-code, this is a situation that Flutter will - // never meet. + // Having no primary responders require extra logic, but Flutter hard-codes + // all primary responders, so this is a situation that Flutter will never + // encounter. NSAssert([_primaryResponders count] >= 0, @"At least one primary responder must be added."); __weak __typeof__(self) weakSelf = self; diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm index dcf340df50..57544a7700 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.mm @@ -371,14 +371,14 @@ static flutter::TextRange RangeFromBaseExtent(NSNumber* base, #pragma mark FlutterKeySecondaryResponder /** - * Handles key down events received from the view controller, responding TRUE if + * Handles key down events received from the view controller, responding YES if * the event was handled. * * Note, the Apple docs suggest that clients should override essentially all the * mouse and keyboard event-handling methods of NSResponder. However, experimentation * indicates that only key events are processed by the native layer; Flutter processes * mouse events. Additionally, processing both keyUp and keyDown results in duplicate - * processing of the same keys. So for now, limit processing to just handleKeyDown. + * processing of the same keys. */ - (BOOL)handleKeyEvent:(NSEvent*)event { if (event.type == NSEventTypeKeyUp || diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm index d969d556cc..ab9d8833bf 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController.mm @@ -116,7 +116,9 @@ struct MouseState { @property(nonatomic) id keyUpMonitor; /** - * TODO + * Pointer to a keyboard manager, a hub that manages how key events are + * dispatched to various Flutter key responders, and whether the event is + * propagated to the next NSResponder. */ @property(nonatomic) FlutterKeyboardManager* keyboardManager; diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.mm b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.mm index 4c8a0ac4fc..21dacd7af8 100644 --- a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.mm +++ b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap.mm @@ -4,7 +4,7 @@ #import #import -#include "./KeyCodeMap_internal.h" +#include "./KeyCodeMap_Internal.h" // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // This file is generated by flutter/flutter@dev/tools/gen_keycodes/bin/gen_keycodes.dart and diff --git a/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_internal.h b/engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h similarity index 100% rename from engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_internal.h rename to engine/src/flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h diff --git a/engine/src/flutter/shell/platform/embedder/embedder.cc b/engine/src/flutter/shell/platform/embedder/embedder.cc index 7a9ea127d5..e0ef4454ba 100644 --- a/engine/src/flutter/shell/platform/embedder/embedder.cc +++ b/engine/src/flutter/shell/platform/embedder/embedder.cc @@ -1601,7 +1601,7 @@ FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine) flutter::KeyData key_data; key_data.Clear(); - key_data.timestamp = (uint64_t)SAFE_ACCESS(event, timestamp, 0); + key_data.timestamp = static_cast(SAFE_ACCESS(event, timestamp, 0)); key_data.type = MapKeyEventType( SAFE_ACCESS(event, type, FlutterKeyEventType::kFlutterKeyEventTypeUp)); key_data.physical = SAFE_ACCESS(event, physical, 0); @@ -1611,8 +1611,9 @@ FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine) auto packet = std::make_unique(key_data, character); auto response = [callback, user_data](bool handled) { - if (callback != nullptr) + if (callback != nullptr) { callback(handled, user_data); + } }; return reinterpret_cast(engine) diff --git a/engine/src/flutter/shell/platform/embedder/embedder_surface_metal.mm b/engine/src/flutter/shell/platform/embedder/embedder_surface_metal.mm index 6f854bdbf4..805b2f25b2 100644 --- a/engine/src/flutter/shell/platform/embedder/embedder_surface_metal.mm +++ b/engine/src/flutter/shell/platform/embedder/embedder_surface_metal.mm @@ -34,7 +34,11 @@ bool EmbedderSurfaceMetal::IsValid() const { return valid_; } -std::unique_ptr EmbedderSurfaceMetal::CreateGPUSurface() { +std::unique_ptr EmbedderSurfaceMetal::CreateGPUSurface() API_AVAILABLE(ios(13.0)) { + if (@available(iOS 13.0, *)) { + } else { + return nullptr; + } if (!IsValid()) { return nullptr; } diff --git a/engine/src/flutter/shell/platform/embedder/fixtures/main.dart b/engine/src/flutter/shell/platform/embedder/fixtures/main.dart index dc602d4dee..9ec4a2c6a8 100644 --- a/engine/src/flutter/shell/platform/embedder/fixtures/main.dart +++ b/engine/src/flutter/shell/platform/embedder/fixtures/main.dart @@ -504,7 +504,7 @@ void _echoKeyEvent( // Convert `kind` in enum form to its integer form. // -// It performs a revesed mapping from `unserializeKeyEventKind` +// It performs a reversed mapping from `unserializeKeyEventKind` // in shell/platform/embedder/tests/embedder_unittests.cc. int _serializeKeyEventType(KeyEventType change) { switch(change) { diff --git a/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc b/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc index 9345769b29..9a57e1aae5 100644 --- a/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc +++ b/engine/src/flutter/shell/platform/embedder/tests/embedder_unittests.cc @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "fml/task_runner.h" #define FML_USED_ON_EMBEDDER #include @@ -1419,21 +1420,35 @@ TEST_F(EmbedderTest, KeyDataIsCorrectlySerialized) { } TEST_F(EmbedderTest, KeyDataResponseIsCorrectlyInvoked) { - auto& context = GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); - EmbedderConfigBuilder builder(context); - builder.SetSoftwareRendererConfig(); - builder.SetDartEntrypoint("key_data_echo"); + UniqueEngine engine; + fml::AutoResetWaitableEvent sync_latch; fml::AutoResetWaitableEvent ready; - context.AddNativeCallback( - "SignalNativeTest", - CREATE_NATIVE_ENTRY( - [&ready](Dart_NativeArguments args) { ready.Signal(); })); - context.AddNativeCallback( - "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); + // One of the threads that the key data callback will be posted to is the + // platform thread. So we cannot wait for assertions to complete on the + // platform thread. Create a new thread to manage the engine instance and wait + // for assertions on the test thread. + auto platform_task_runner = CreateNewThread("platform_thread"); - auto engine = builder.LaunchEngine(); - ASSERT_TRUE(engine.is_valid()); + platform_task_runner->PostTask([&]() { + auto& context = + GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); + EmbedderConfigBuilder builder(context); + builder.SetSoftwareRendererConfig(); + builder.SetDartEntrypoint("key_data_echo"); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + context.AddNativeCallback( + "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); + + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + sync_latch.Signal(); + }); + sync_latch.Wait(); ready.Wait(); // Dispatch a single event @@ -1449,18 +1464,72 @@ TEST_F(EmbedderTest, KeyDataResponseIsCorrectlyInvoked) { KeyEventUserData user_data1{ .latch = std::make_shared(), }; - // Entrypoint `key_data_echo` uses `event.synthesized` as `handled`. + // Entrypoint `key_data_echo` returns `event.synthesized` as `handled`. event.synthesized = true; - FlutterEngineSendKeyEvent( - engine.get(), &event, - [](bool handled, void* untyped_user_data) { - KeyEventUserData* user_data = - reinterpret_cast(untyped_user_data); - EXPECT_EQ(handled, true); - user_data->latch->Signal(); - }, - &user_data1); + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent( + engine.get(), &event, + [](bool handled, void* untyped_user_data) { + KeyEventUserData* user_data = + reinterpret_cast(untyped_user_data); + EXPECT_EQ(handled, true); + user_data->latch->Signal(); + }, + &user_data1); + }); user_data1.latch->Wait(); + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); +} + +TEST_F(EmbedderTest, BackToBackKeyEventResponsesCorrectlyInvoked) { + UniqueEngine engine; + fml::AutoResetWaitableEvent sync_latch; + fml::AutoResetWaitableEvent ready; + + // One of the threads that the callback will be posted to is the platform + // thread. So we cannot wait for assertions to complete on the platform + // thread. Create a new thread to manage the engine instance and wait for + // assertions on the test thread. + auto platform_task_runner = CreateNewThread("platform_thread"); + + platform_task_runner->PostTask([&]() { + auto& context = + GetEmbedderContext(EmbedderTestContextType::kSoftwareContext); + + EmbedderConfigBuilder builder(context); + builder.SetSoftwareRendererConfig(); + builder.SetDartEntrypoint("key_data_echo"); + context.AddNativeCallback( + "SignalNativeTest", + CREATE_NATIVE_ENTRY( + [&ready](Dart_NativeArguments args) { ready.Signal(); })); + + context.AddNativeCallback( + "EchoKeyEvent", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); + + engine = builder.LaunchEngine(); + ASSERT_TRUE(engine.is_valid()); + + sync_latch.Signal(); + }); + sync_latch.Wait(); + ready.Wait(); + + // Dispatch a single event + FlutterKeyEvent event{ + .struct_size = sizeof(FlutterKeyEvent), + .timestamp = 1000, + .type = kFlutterKeyEventTypeDown, + .physical = 0x00070005, + .logical = 0x00000000062, + .character = nullptr, + .synthesized = false, + }; // Dispatch two events back to back, using the same callback on different // user_data @@ -1479,14 +1548,22 @@ TEST_F(EmbedderTest, KeyDataResponseIsCorrectlyInvoked) { user_data->returned = true; user_data->latch->Signal(); }; - - event.synthesized = false; - FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data2); - FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data3); + platform_task_runner->PostTask([&]() { + FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data2); + FlutterEngineSendKeyEvent(engine.get(), &event, callback23, &user_data3); + }); user_data2.latch->Wait(); user_data3.latch->Wait(); + EXPECT_TRUE(user_data2.returned); EXPECT_TRUE(user_data3.returned); + + fml::AutoResetWaitableEvent shutdown_latch; + platform_task_runner->PostTask([&]() { + engine.reset(); + shutdown_latch.Signal(); + }); + shutdown_latch.Wait(); } } // namespace testing diff --git a/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/xcshareddata/xcschemes/IosUnitTests.xcscheme b/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/xcshareddata/xcschemes/IosUnitTests.xcscheme index f28f49f8b4..27c2be6b4b 100644 --- a/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/xcshareddata/xcschemes/IosUnitTests.xcscheme +++ b/engine/src/flutter/testing/ios/IosUnitTests/IosUnitTests.xcodeproj/xcshareddata/xcschemes/IosUnitTests.xcscheme @@ -34,6 +34,11 @@ value = "" isEnabled = "YES"> + + + skipped = "NO">