[macOS, Keyboard] Derive keyboard layout using printable information from system (flutter/engine#32152)

* Impl

Remove log

add sync; clean code

Format

* Impl

* New Impl

* Fix dead key

* Rename to goals and clues

* CFRelease source

* Move to view controller

* No global

* First-phase

* No weak in dealloc

* Tests

* One more test

* Format

* Format

* Docs

* Tests

* Docs

* Format

* Fix compile

* Compile

* Add channel test

* Format

* Fix comments

* Fix keycodes

* Fix namespaces

* Format

* strlcpy
This commit is contained in:
Tong Mu
2022-04-01 11:57:21 -07:00
committed by GitHub
parent cdd2946003
commit aa029368e5
11 changed files with 719 additions and 64 deletions

View File

@@ -152,6 +152,7 @@ source_set("flutter_framework_source") {
cflags_objcc = flutter_cflags_objcc_arc
frameworks = [
"Carbon.framework",
"Cocoa.framework",
"CoreVideo.framework",
"IOSurface.framework",

View File

@@ -29,6 +29,8 @@
@implementation FlutterChannelKeyResponder
@synthesize layoutMap;
- (nonnull instancetype)initWithChannel:(nonnull FlutterBasicMessageChannel*)channel {
self = [super init];
if (self != nil) {
@@ -79,6 +81,10 @@
keyMessage[@"characters"] = event.characters;
keyMessage[@"charactersIgnoringModifiers"] = event.charactersIgnoringModifiers;
}
NSNumber* specifiedLogicalKey = layoutMap[@(event.keyCode)];
if (specifiedLogicalKey != nil) {
keyMessage[@"specifiedLogicalKey"] = specifiedLogicalKey;
}
[self.channel sendMessage:keyMessage
reply:^(id reply) {
if (!reply) {

View File

@@ -2,16 +2,20 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <Carbon/Carbon.h>
#import <Foundation/Foundation.h>
#import <OCMock/OCMock.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.h"
#import "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
namespace flutter::testing {
namespace {
using flutter::testing::keycodes::kLogicalKeyQ;
NSEvent* keyEvent(NSEventType type,
NSEventModifierFlags modifierFlags,
NSString* characters,
@@ -80,8 +84,8 @@ TEST(FlutterChannelKeyResponderUnittests, BasicKeyEvent) {
EXPECT_STREQ([[messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[messages lastObject][@"modifiers"] intValue], 0x0);
EXPECT_EQ([[messages lastObject][@"characters"] UTF8String], "a");
EXPECT_EQ([[messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
EXPECT_STREQ([[messages lastObject][@"characters"] UTF8String], "a");
EXPECT_STREQ([[messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
EXPECT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], TRUE);
@@ -101,8 +105,8 @@ TEST(FlutterChannelKeyResponderUnittests, BasicKeyEvent) {
EXPECT_STREQ([[messages lastObject][@"type"] UTF8String], "keyup");
EXPECT_EQ([[messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[messages lastObject][@"modifiers"] intValue], 0);
EXPECT_EQ([[messages lastObject][@"characters"] UTF8String], "a");
EXPECT_EQ([[messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
EXPECT_STREQ([[messages lastObject][@"characters"] UTF8String], "a");
EXPECT_STREQ([[messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "a");
EXPECT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], FALSE);
@@ -235,4 +239,55 @@ TEST(FlutterChannelKeyResponderUnittests, EmptyResponseIsTakenAsHandled) {
EXPECT_EQ([[responses lastObject] boolValue], TRUE);
}
TEST(FlutterChannelKeyResponderUnittests, FollowsLayoutMap) {
__block NSMutableArray<id>* messages = [[NSMutableArray<id> alloc] init];
__block BOOL next_response = TRUE;
__block NSMutableArray<NSNumber*>* responses = [[NSMutableArray<NSNumber*> 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);
}));
FlutterChannelKeyResponder* responder =
[[FlutterChannelKeyResponder alloc] initWithChannel:mockKeyEventChannel];
NSMutableDictionary<NSNumber*, NSNumber*>* layoutMap =
[NSMutableDictionary<NSNumber*, NSNumber*> dictionary];
responder.layoutMap = layoutMap;
// French layout
layoutMap[@(kVK_ANSI_A)] = @(kLogicalKeyQ);
[responder handleEvent:keyEvent(NSEventTypeKeyDown, kVK_ANSI_A, @"q", @"q", FALSE, 0)
callback:^(BOOL handled) {
[responses addObject:@(handled)];
}];
EXPECT_EQ([messages count], 1u);
EXPECT_STREQ([[messages lastObject][@"keymap"] UTF8String], "macos");
EXPECT_STREQ([[messages lastObject][@"type"] UTF8String], "keydown");
EXPECT_EQ([[messages lastObject][@"keyCode"] intValue], 0);
EXPECT_EQ([[messages lastObject][@"modifiers"] intValue], 0x0);
EXPECT_STREQ([[messages lastObject][@"characters"] UTF8String], "q");
EXPECT_STREQ([[messages lastObject][@"charactersIgnoringModifiers"] UTF8String], "q");
EXPECT_EQ([messages lastObject][@"specifiedLogicalKey"], @(kLogicalKeyQ));
EXPECT_EQ([responses count], 1u);
EXPECT_EQ([[responses lastObject] boolValue], TRUE);
[messages removeAllObjects];
[responses removeAllObjects];
}
} // namespace flutter::testing

View File

@@ -52,16 +52,16 @@ static bool IsUnprintableKey(uint64_t character) {
* for more information.
*/
static uint64_t KeyOfPlane(uint64_t baseKey, uint64_t plane) {
return plane | (baseKey & kValueMask);
return plane | (baseKey & flutter::kValueMask);
}
/**
* Returns the physical key for a key code.
*/
static uint64_t GetPhysicalKeyForKeyCode(unsigned short keyCode) {
NSNumber* physicalKey = [keyCodeToPhysicalKey objectForKey:@(keyCode)];
NSNumber* physicalKey = [flutter::keyCodeToPhysicalKey objectForKey:@(keyCode)];
if (physicalKey == nil) {
return KeyOfPlane(keyCode, kMacosPlane);
return KeyOfPlane(keyCode, flutter::kMacosPlane);
}
return physicalKey.unsignedLongLongValue;
}
@@ -70,11 +70,11 @@ static uint64_t GetPhysicalKeyForKeyCode(unsigned short keyCode) {
* Returns the logical key for a modifier physical key.
*/
static uint64_t GetLogicalKeyForModifier(unsigned short keyCode, uint64_t hidCode) {
NSNumber* fromKeyCode = [keyCodeToLogicalKey objectForKey:@(keyCode)];
NSNumber* fromKeyCode = [flutter::keyCodeToLogicalKey objectForKey:@(keyCode)];
if (fromKeyCode != nil) {
return fromKeyCode.unsignedLongLongValue;
}
return KeyOfPlane(hidCode, kMacosPlane);
return KeyOfPlane(hidCode, flutter::kMacosPlane);
}
/**
@@ -147,7 +147,7 @@ static uint32_t* DecodeUtf16(NSString* target, size_t* out_length) {
*/
static uint64_t GetLogicalKeyForEvent(NSEvent* event, uint64_t physicalKey) {
// Look to see if the keyCode can be mapped from keycode.
NSNumber* fromKeyCode = [keyCodeToLogicalKey objectForKey:@(event.keyCode)];
NSNumber* fromKeyCode = [flutter::keyCodeToLogicalKey objectForKey:@(event.keyCode)];
if (fromKeyCode != nil) {
return fromKeyCode.unsignedLongLongValue;
}
@@ -175,12 +175,12 @@ static uint64_t GetLogicalKeyForEvent(NSEvent* event, uint64_t physicalKey) {
delete[] keyLabel;
}
if (character != 0) {
return KeyOfPlane(toLower(character), kUnicodePlane);
return KeyOfPlane(toLower(character), flutter::kUnicodePlane);
}
// We can't represent this key with a single printable unicode, so a new code
// is minted to the macOS plane.
return KeyOfPlane(event.keyCode, kMacosPlane);
return KeyOfPlane(event.keyCode, flutter::kMacosPlane);
}
/**
@@ -199,7 +199,7 @@ static double GetFlutterTimestampFrom(NSTimeInterval timestamp) {
*/
static NSUInteger computeModifierFlagOfInterestMask() {
__block NSUInteger modifierFlagOfInterestMask = NSEventModifierFlagCapsLock;
[keyCodeToModifierFlag
[flutter::keyCodeToModifierFlag
enumerateKeysAndObjectsUsingBlock:^(NSNumber* keyCode, NSNumber* flag, BOOL* stop) {
modifierFlagOfInterestMask = modifierFlagOfInterestMask | [flag unsignedLongValue];
}];
@@ -472,6 +472,8 @@ struct FlutterKeyPendingResponse {
@implementation FlutterEmbedderKeyResponder
@synthesize layoutMap;
- (nonnull instancetype)initWithSendEvent:(FlutterSendEmbedderKeyEvent)sendEvent {
self = [super init];
if (self != nil) {
@@ -542,7 +544,7 @@ struct FlutterKeyPendingResponse {
break;
}
flagDifference = flagDifference & ~currentFlag;
NSNumber* keyCode = [modifierFlagToKeyCode objectForKey:@(currentFlag)];
NSNumber* keyCode = [flutter::modifierFlagToKeyCode objectForKey:@(currentFlag)];
NSAssert(keyCode != nil, @"Invalid modifier flag 0x%lx", currentFlag);
if (keyCode == nil) {
continue;
@@ -595,8 +597,8 @@ struct FlutterKeyPendingResponse {
.struct_size = sizeof(FlutterKeyEvent),
.timestamp = GetFlutterTimestampFrom(timestamp),
.type = kFlutterKeyEventTypeDown,
.physical = kCapsLockPhysicalKey,
.logical = kCapsLockLogicalKey,
.physical = flutter::kCapsLockPhysicalKey,
.logical = flutter::kCapsLockLogicalKey,
.character = nil,
.synthesized = synthesizeDown,
};
@@ -642,7 +644,9 @@ struct FlutterKeyPendingResponse {
- (void)handleDownEvent:(NSEvent*)event callback:(FlutterKeyCallbackGuard*)callback {
uint64_t physicalKey = GetPhysicalKeyForKeyCode(event.keyCode);
uint64_t logicalKey = GetLogicalKeyForEvent(event, physicalKey);
NSNumber* logicalKeyFromMap = self.layoutMap[@(event.keyCode)];
uint64_t logicalKey = logicalKeyFromMap != nil ? [logicalKeyFromMap unsignedLongLongValue]
: GetLogicalKeyForEvent(event, physicalKey);
[self synchronizeModifiers:event.modifierFlags
ignoringFlags:0
timestamp:event.timestamp
@@ -733,11 +737,11 @@ struct FlutterKeyPendingResponse {
}
- (void)handleFlagEvent:(NSEvent*)event callback:(FlutterKeyCallbackGuard*)callback {
NSNumber* targetModifierFlagObj = keyCodeToModifierFlag[@(event.keyCode)];
NSNumber* targetModifierFlagObj = flutter::keyCodeToModifierFlag[@(event.keyCode)];
NSUInteger targetModifierFlag =
targetModifierFlagObj == nil ? 0 : [targetModifierFlagObj unsignedLongValue];
uint64_t targetKey = GetPhysicalKeyForKeyCode(event.keyCode);
if (targetKey == kCapsLockPhysicalKey) {
if (targetKey == flutter::kCapsLockPhysicalKey) {
return [self handleCapsLockEvent:event callback:callback];
}

View File

@@ -24,4 +24,13 @@ typedef void (^FlutterAsyncKeyCallback)(BOOL handled);
@required
- (void)handleEvent:(nonnull NSEvent*)event callback:(nonnull FlutterAsyncKeyCallback)callback;
/* A map from macOS key code to logical keyboard.
*
* The map is assigned on initialization, and updated when the user changes
* keyboard type or layout. The responder should prioritize this map when
* deriving logical keys.
*/
@required
@property(nonatomic) NSMutableDictionary<NSNumber*, NSNumber*>* _Nullable layoutMap;
@end

View File

@@ -4,19 +4,53 @@
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h"
#include <cctype>
#include <map>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterChannelKeyResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEmbedderKeyResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/KeyCodeMap_Internal.h"
// Turn on this flag to print complete layout data when switching IMEs. The data
// is used in unit tests.
// #define DEBUG_PRINT_LAYOUT
namespace {
using flutter::LayoutClue;
using flutter::LayoutGoal;
#ifdef DEBUG_PRINT_LAYOUT
// Prints layout entries that will be parsed by `MockLayoutData`.
NSString* debugFormatLayoutData(NSString* debugLayoutData,
uint16_t keyCode,
LayoutClue clue1,
LayoutClue clue2) {
return [NSString
stringWithFormat:@" %@%@0x%d%04x, 0x%d%04x,", debugLayoutData,
keyCode % 4 == 0 ? [NSString stringWithFormat:@"\n/* 0x%02x */ ", keyCode]
: @" ",
clue1.isDeadKey, clue1.character, clue2.isDeadKey, clue2.character];
}
#endif
// Someohow this pointer type must be defined as a single type for the compiler
// to compile the function pointer type (due to _Nullable).
typedef NSResponder* _NSResponderPtr;
typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
bool isEascii(const LayoutClue& clue) {
return clue.character < 256 && !clue.isDeadKey;
}
typedef void (^VoidBlock)();
// Someohow this pointer type must be defined as a single type for the compiler
// to compile the function pointer type (due to _Nullable).
typedef NSResponder* _NSResponderPtr;
typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
}
} // namespace
@interface FlutterKeyboardManager ()
@@ -30,10 +64,12 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
*/
@property(nonatomic) NSMutableArray<id<FlutterKeyPrimaryResponder>>* primaryResponders;
@property(nonatomic) NSMutableArray<NSEvent*>* pendingTextEvents;
@property(nonatomic) NSMutableArray<NSEvent*>* pendingEvents;
@property(nonatomic) BOOL processingEvent;
@property(nonatomic) NSMutableDictionary<NSNumber*, NSNumber*>* layoutMap;
/**
* Add a primary responder, which asynchronously decides whether to handle an
* event.
@@ -64,6 +100,11 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
*/
- (void)dispatchTextEvent:(nonnull NSEvent*)pendingEvent;
/**
* Clears the current layout and build a new one based on the current layout.
*/
- (void)buildLayout;
@end
@implementation FlutterKeyboardManager {
@@ -93,7 +134,17 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
getBinaryMessenger]
codec:[FlutterJSONMessageCodec
sharedInstance]]]];
_pendingTextEvents = [[NSMutableArray alloc] init];
_pendingEvents = [[NSMutableArray alloc] init];
_layoutMap = [NSMutableDictionary<NSNumber*, NSNumber*> dictionary];
[self buildLayout];
for (id<FlutterKeyPrimaryResponder> responder in _primaryResponders) {
responder.layoutMap = _layoutMap;
}
__weak __typeof__(self) weakSelf = self;
[_viewDelegate subscribeToKeyboardLayoutChange:^() {
[weakSelf buildLayout];
}];
}
return self;
}
@@ -113,7 +164,7 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
return;
}
[_pendingTextEvents addObject:event];
[_pendingEvents addObject:event];
[self processNextEvent];
}
@@ -121,14 +172,14 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
- (void)processNextEvent {
@synchronized(self) {
if (_processingEvent || [_pendingTextEvents count] == 0) {
if (_processingEvent || [_pendingEvents count] == 0) {
return;
}
_processingEvent = TRUE;
}
NSEvent* pendingEvent = [_pendingTextEvents firstObject];
[_pendingTextEvents removeObjectAtIndex:0];
NSEvent* pendingEvent = [_pendingEvents firstObject];
[_pendingEvents removeObjectAtIndex:0];
__weak __typeof__(self) weakSelf = self;
VoidBlock onFinish = ^() {
@@ -200,4 +251,67 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
}
}
- (void)buildLayout {
[_layoutMap removeAllObjects];
std::map<uint32_t, LayoutGoal> mandatoryGoalsByChar;
std::map<uint32_t, LayoutGoal> usLayoutGoalsByKeyCode;
for (const LayoutGoal& goal : flutter::layoutGoals) {
if (goal.mandatory) {
mandatoryGoalsByChar[goal.keyChar] = goal;
} else {
usLayoutGoalsByKeyCode[goal.keyCode] = goal;
}
}
// Derive key mapping for each key code based on their layout clues.
// Max key code is 127 for ADB keyboards.
// https://developer.apple.com/documentation/coreservices/1390584-uckeytranslate?language=objc#parameters
const uint16_t kMaxKeyCode = 127;
#ifdef DEBUG_PRINT_LAYOUT
NSString* debugLayoutData = @"";
#endif
for (uint16_t keyCode = 0; keyCode <= kMaxKeyCode; keyCode += 1) {
std::vector<LayoutClue> thisKeyClues = {
[_viewDelegate lookUpLayoutForKeyCode:keyCode shift:false],
[_viewDelegate lookUpLayoutForKeyCode:keyCode shift:true]};
#ifdef DEBUG_PRINT_LAYOUT
debugLayoutData =
debugFormatLayoutData(debugLayoutData, keyCode, thisKeyClues[0], thisKeyClues[1]);
#endif
// The logical key should be the first available clue from below:
//
// - Mandatory goal, if it matches any clue. This ensures that all alnum
// keys can be found somewhere.
// - US layout, if neither clue of the key is EASCII. This ensures that
// there are no non-latin logical keys.
// - Derived on the fly from keyCode & characters.
for (const LayoutClue& clue : thisKeyClues) {
uint32_t keyChar = clue.isDeadKey ? 0 : clue.character;
auto matchingGoal = mandatoryGoalsByChar.find(keyChar);
if (matchingGoal != mandatoryGoalsByChar.end()) {
// Found a key that produces a mandatory char. Use it.
NSAssert(_layoutMap[@(keyCode)] == nil, @"Attempting to assign an assigned key code.");
_layoutMap[@(keyCode)] = @(keyChar);
mandatoryGoalsByChar.erase(matchingGoal);
break;
}
}
bool hasAnyEascii = isEascii(thisKeyClues[0]) || isEascii(thisKeyClues[1]);
// See if any produced char meets the requirement as a logical key.
if (_layoutMap[@(keyCode)] == nil && !hasAnyEascii) {
_layoutMap[@(keyCode)] = @(usLayoutGoalsByKeyCode[keyCode].keyChar);
}
}
#ifdef DEBUG_PRINT_LAYOUT
NSLog(@"%@", debugLayoutData);
#endif
// Ensure all mandatory goals are assigned.
for (auto mandatoryGoalIter : mandatoryGoalsByChar) {
const LayoutGoal& goal = mandatoryGoalIter.second;
_layoutMap[@(goal.keyCode)] = @(goal.keyChar);
}
}
@end

View File

@@ -2,19 +2,32 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <Carbon/Carbon.h>
#import <Foundation/Foundation.h>
#import <OCMock/OCMock.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.h"
#import "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
namespace {
using flutter::testing::keycodes::kLogicalKeyA;
using flutter::testing::keycodes::kLogicalKeyM;
using flutter::testing::keycodes::kLogicalKeyQ;
using flutter::testing::keycodes::kLogicalKeyT;
using flutter::testing::keycodes::kLogicalDigit1;
using flutter::testing::keycodes::kLogicalBracketLeft;
using flutter::LayoutClue;
typedef BOOL (^BoolGetter)();
typedef void (^AsyncKeyCallbackHandler)(FlutterAsyncKeyCallback callback);
typedef void (^AsyncEmbedderCallbackHandler)(const FlutterKeyEvent* event,
FlutterAsyncKeyCallback callback);
typedef BOOL (^TextInputCallback)(NSEvent*);
// When the Vietnamese IME converts messages into "pure text" messages, their
@@ -23,14 +36,131 @@ typedef BOOL (^TextInputCallback)(NSEvent*);
// The 0 also happens to be the key code for key A.
constexpr uint16_t kKeyCodeEmpty = 0x00;
constexpr uint16_t kKeyCodeKeyO = 0x1f;
constexpr uint16_t kKeyCodeBackspace = 0x33;
// Constants used for `recordCallTypesTo:forTypes:`.
constexpr uint32_t kEmbedderCall = 0x1;
constexpr uint32_t kChannelCall = 0x2;
constexpr uint32_t kTextCall = 0x4;
// All key clues for a keyboard layout.
//
// The index is (keyCode * 2 + hasShift). The value is 0xMNNNN, where:
//
// - M is whether the key is a dead key (0x1 for true, 0x0 for false).
// - N is the character for this key. (It only supports UTF-16, but we don't
// need full UTF-32 support for unit tests. Moreover, Carbon's UCKeyTranslate
// only returns UniChar (UInt16) anyway.)
typedef const std::array<uint32_t, 256> MockLayoutData;
// The following layout data is generated using DEBUG_PRINT_LAYOUT.
MockLayoutData kUsLayout = {
// +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift
/* 0x00 */ 0x00061, 0x00041, 0x00073, 0x00053, 0x00064, 0x00044, 0x00066, 0x00046,
/* 0x04 */ 0x00068, 0x00048, 0x00067, 0x00047, 0x0007a, 0x0005a, 0x00078, 0x00058,
/* 0x08 */ 0x00063, 0x00043, 0x00076, 0x00056, 0x000a7, 0x000b1, 0x00062, 0x00042,
/* 0x0c */ 0x00071, 0x00051, 0x00077, 0x00057, 0x00065, 0x00045, 0x00072, 0x00052,
/* 0x10 */ 0x00079, 0x00059, 0x00074, 0x00054, 0x00031, 0x00021, 0x00032, 0x00040,
/* 0x14 */ 0x00033, 0x00023, 0x00034, 0x00024, 0x00036, 0x0005e, 0x00035, 0x00025,
/* 0x18 */ 0x0003d, 0x0002b, 0x00039, 0x00028, 0x00037, 0x00026, 0x0002d, 0x0005f,
/* 0x1c */ 0x00038, 0x0002a, 0x00030, 0x00029, 0x0005d, 0x0007d, 0x0006f, 0x0004f,
/* 0x20 */ 0x00075, 0x00055, 0x0005b, 0x0007b, 0x00069, 0x00049, 0x00070, 0x00050,
/* 0x24 */ 0x00000, 0x00000, 0x0006c, 0x0004c, 0x0006a, 0x0004a, 0x00027, 0x00022,
/* 0x28 */ 0x0006b, 0x0004b, 0x0003b, 0x0003a, 0x0005c, 0x0007c, 0x0002c, 0x0003c,
/* 0x2c */ 0x0002f, 0x0003f, 0x0006e, 0x0004e, 0x0006d, 0x0004d, 0x0002e, 0x0003e,
/* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x00060, 0x0007e, 0x00000, 0x00000,
/* 0x34 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x38 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x3c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x40 */ 0x00000, 0x00000, 0x0002e, 0x0002e, 0x00000, 0x0002a, 0x0002a, 0x0002a,
/* 0x44 */ 0x00000, 0x00000, 0x0002b, 0x0002b, 0x00000, 0x0002b, 0x00000, 0x00000,
/* 0x48 */ 0x00000, 0x0003d, 0x00000, 0x00000, 0x00000, 0x00000, 0x0002f, 0x0002f,
/* 0x4c */ 0x00000, 0x00000, 0x00000, 0x0002f, 0x0002d, 0x0002d, 0x00000, 0x00000,
/* 0x50 */ 0x00000, 0x00000, 0x0003d, 0x0003d, 0x00030, 0x00030, 0x00031, 0x00031,
/* 0x54 */ 0x00032, 0x00032, 0x00033, 0x00033, 0x00034, 0x00034, 0x00035, 0x00035,
/* 0x58 */ 0x00036, 0x00036, 0x00037, 0x00037, 0x00000, 0x00000, 0x00038, 0x00038,
/* 0x5c */ 0x00039, 0x00039, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x60 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x64 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x68 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x6c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x70 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x74 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x78 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x7c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
};
MockLayoutData kFrenchLayout = {
// +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift
/* 0x00 */ 0x00071, 0x00051, 0x00073, 0x00053, 0x00064, 0x00044, 0x00066, 0x00046,
/* 0x04 */ 0x00068, 0x00048, 0x00067, 0x00047, 0x00077, 0x00057, 0x00078, 0x00058,
/* 0x08 */ 0x00063, 0x00043, 0x00076, 0x00056, 0x00040, 0x00023, 0x00062, 0x00042,
/* 0x0c */ 0x00061, 0x00041, 0x0007a, 0x0005a, 0x00065, 0x00045, 0x00072, 0x00052,
/* 0x10 */ 0x00079, 0x00059, 0x00074, 0x00054, 0x00026, 0x00031, 0x000e9, 0x00032,
/* 0x14 */ 0x00022, 0x00033, 0x00027, 0x00034, 0x000a7, 0x00036, 0x00028, 0x00035,
/* 0x18 */ 0x0002d, 0x0005f, 0x000e7, 0x00039, 0x000e8, 0x00037, 0x00029, 0x000b0,
/* 0x1c */ 0x00021, 0x00038, 0x000e0, 0x00030, 0x00024, 0x0002a, 0x0006f, 0x0004f,
/* 0x20 */ 0x00075, 0x00055, 0x1005e, 0x100a8, 0x00069, 0x00049, 0x00070, 0x00050,
/* 0x24 */ 0x00000, 0x00000, 0x0006c, 0x0004c, 0x0006a, 0x0004a, 0x000f9, 0x00025,
/* 0x28 */ 0x0006b, 0x0004b, 0x0006d, 0x0004d, 0x10060, 0x000a3, 0x0003b, 0x0002e,
/* 0x2c */ 0x0003d, 0x0002b, 0x0006e, 0x0004e, 0x0002c, 0x0003f, 0x0003a, 0x0002f,
/* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x0003c, 0x0003e, 0x00000, 0x00000,
/* 0x34 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x38 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x3c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x40 */ 0x00000, 0x00000, 0x0002c, 0x0002e, 0x00000, 0x0002a, 0x0002a, 0x0002a,
/* 0x44 */ 0x00000, 0x00000, 0x0002b, 0x0002b, 0x00000, 0x0002b, 0x00000, 0x00000,
/* 0x48 */ 0x00000, 0x0003d, 0x00000, 0x00000, 0x00000, 0x00000, 0x0002f, 0x0002f,
/* 0x4c */ 0x00000, 0x00000, 0x00000, 0x0002f, 0x0002d, 0x0002d, 0x00000, 0x00000,
/* 0x50 */ 0x00000, 0x00000, 0x0003d, 0x0003d, 0x00030, 0x00030, 0x00031, 0x00031,
/* 0x54 */ 0x00032, 0x00032, 0x00033, 0x00033, 0x00034, 0x00034, 0x00035, 0x00035,
/* 0x58 */ 0x00036, 0x00036, 0x00037, 0x00037, 0x00000, 0x00000, 0x00038, 0x00038,
/* 0x5c */ 0x00039, 0x00039, 0x00040, 0x00023, 0x0003c, 0x0003e, 0x00000, 0x00000,
/* 0x60 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x64 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x68 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x6c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x70 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x74 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x78 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x7c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
};
MockLayoutData kRussianLayout = {
// +0x0 Shift +0x1 Shift +0x2 Shift +0x3 Shift
/* 0x00 */ 0x00444, 0x00424, 0x0044b, 0x0042b, 0x00432, 0x00412, 0x00430, 0x00410,
/* 0x04 */ 0x00440, 0x00420, 0x0043f, 0x0041f, 0x0044f, 0x0042f, 0x00447, 0x00427,
/* 0x08 */ 0x00441, 0x00421, 0x0043c, 0x0041c, 0x0003e, 0x0003c, 0x00438, 0x00418,
/* 0x0c */ 0x00439, 0x00419, 0x00446, 0x00426, 0x00443, 0x00423, 0x0043a, 0x0041a,
/* 0x10 */ 0x0043d, 0x0041d, 0x00435, 0x00415, 0x00031, 0x00021, 0x00032, 0x00022,
/* 0x14 */ 0x00033, 0x02116, 0x00034, 0x00025, 0x00036, 0x0002c, 0x00035, 0x0003a,
/* 0x18 */ 0x0003d, 0x0002b, 0x00039, 0x00028, 0x00037, 0x0002e, 0x0002d, 0x0005f,
/* 0x1c */ 0x00038, 0x0003b, 0x00030, 0x00029, 0x0044a, 0x0042a, 0x00449, 0x00429,
/* 0x20 */ 0x00433, 0x00413, 0x00445, 0x00425, 0x00448, 0x00428, 0x00437, 0x00417,
/* 0x24 */ 0x00000, 0x00000, 0x00434, 0x00414, 0x0043e, 0x0041e, 0x0044d, 0x0042d,
/* 0x28 */ 0x0043b, 0x0041b, 0x00436, 0x00416, 0x00451, 0x00401, 0x00431, 0x00411,
/* 0x2c */ 0x0002f, 0x0003f, 0x00442, 0x00422, 0x0044c, 0x0042c, 0x0044e, 0x0042e,
/* 0x30 */ 0x00000, 0x00000, 0x00020, 0x00020, 0x0005d, 0x0005b, 0x00000, 0x00000,
/* 0x34 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x38 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x3c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x40 */ 0x00000, 0x00000, 0x0002c, 0x0002e, 0x00000, 0x0002a, 0x0002a, 0x0002a,
/* 0x44 */ 0x00000, 0x00000, 0x0002b, 0x0002b, 0x00000, 0x0002b, 0x00000, 0x00000,
/* 0x48 */ 0x00000, 0x0003d, 0x00000, 0x00000, 0x00000, 0x00000, 0x0002f, 0x0002f,
/* 0x4c */ 0x00000, 0x00000, 0x00000, 0x0002f, 0x0002d, 0x0002d, 0x00000, 0x00000,
/* 0x50 */ 0x00000, 0x00000, 0x0003d, 0x0003d, 0x00030, 0x00030, 0x00031, 0x00031,
/* 0x54 */ 0x00032, 0x00032, 0x00033, 0x00033, 0x00034, 0x00034, 0x00035, 0x00035,
/* 0x58 */ 0x00036, 0x00036, 0x00037, 0x00037, 0x00000, 0x00000, 0x00038, 0x00038,
/* 0x5c */ 0x00039, 0x00039, 0x0003e, 0x0003c, 0x0005d, 0x0005b, 0x00000, 0x00000,
/* 0x60 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x64 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x68 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x6c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x70 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x74 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x78 */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
/* 0x7c */ 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,
};
NSEvent* keyDownEvent(unsigned short keyCode, NSString* chars = @"", NSString* charsUnmod = @"") {
return [NSEvent keyEventWithType:NSEventTypeKeyDown
location:NSZeroPoint
@@ -67,17 +197,22 @@ id checkKeyDownEvent(unsigned short keyCode) {
}];
}
NSResponder* mockOwnerWithDownOnlyNext() {
NSResponder* nextResponder = OCMStrictClassMock([NSResponder class]);
OCMStub([nextResponder keyDown:[OCMArg any]]).andDo(nil);
// The nextResponder is a strict mock and hasn't stubbed keyUp.
// An error will be thrown on keyUp.
NSResponder* owner = OCMStrictClassMock([NSResponder class]);
OCMStub([owner nextResponder]).andReturn(nextResponder);
return owner;
// Clear a list of `FlutterKeyEvent` whose `character` is dynamically allocated.
void clearEvents(std::vector<FlutterKeyEvent>& events) {
for (FlutterKeyEvent& event : events) {
if (event.character != nullptr) {
delete[] event.character;
}
}
events.clear();
}
#define VERIFY_DOWN(OUT_LOGICAL, OUT_CHAR) \
EXPECT_EQ(events[0].type, kFlutterKeyEventTypeDown); \
EXPECT_EQ(events[0].logical, static_cast<uint64_t>(OUT_LOGICAL)); \
EXPECT_STREQ(events[0].character, (OUT_CHAR)); \
clearEvents(events);
} // namespace
@interface KeyboardTester : NSObject
@@ -91,6 +226,9 @@ NSResponder* mockOwnerWithDownOnlyNext() {
// They are not responded to until the stored callbacks are manually called.
- (void)recordEmbedderCallsTo:(nonnull NSMutableArray<FlutterAsyncKeyCallback>*)storage;
- (void)recordEmbedderEventsTo:(nonnull std::vector<FlutterKeyEvent>*)storage
returning:(bool)handled;
// Set channel calls to respond immediately with the given response.
- (void)respondChannelCallsWith:(BOOL)response;
@@ -130,12 +268,15 @@ NSResponder* mockOwnerWithDownOnlyNext() {
@end
@implementation KeyboardTester {
AsyncKeyCallbackHandler _embedderHandler;
AsyncEmbedderCallbackHandler _embedderHandler;
AsyncKeyCallbackHandler _channelHandler;
TextInputCallback _textCallback;
NSMutableArray<NSNumber*>* _typeStorage;
uint32_t _typeStorageMask;
flutter::KeyboardLayoutNotifier _keyboardLayoutNotifier;
const MockLayoutData* _currentLayout;
}
- (nonnull instancetype)init {
@@ -150,6 +291,8 @@ NSResponder* mockOwnerWithDownOnlyNext() {
[self respondTextInputWith:FALSE];
_isComposing = NO;
_currentLayout = &kUsLayout;
id messengerMock = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub([messengerMock sendOnChannel:@"flutter/keyevent"
message:[OCMArg any]
@@ -165,23 +308,43 @@ NSResponder* mockOwnerWithDownOnlyNext() {
OCMStub([viewDelegateMock sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil])
.ignoringNonObjectArgs()
.andCall(self, @selector(handleEmbedderEvent:callback:userData:));
OCMStub([viewDelegateMock subscribeToKeyboardLayoutChange:[OCMArg any]])
.andCall(self, @selector(onSetKeyboardLayoutNotifier:));
OCMStub([viewDelegateMock lookUpLayoutForKeyCode:0 shift:false])
.ignoringNonObjectArgs()
.andCall(self, @selector(lookUpLayoutForKeyCode:shift:));
_manager = [[FlutterKeyboardManager alloc] initWithViewDelegate:viewDelegateMock];
return self;
}
- (void)respondEmbedderCallsWith:(BOOL)response {
_embedderHandler = ^(FlutterAsyncKeyCallback callback) {
_embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) {
callback(response);
};
}
- (void)recordEmbedderCallsTo:(nonnull NSMutableArray<FlutterAsyncKeyCallback>*)storage {
_embedderHandler = ^(FlutterAsyncKeyCallback callback) {
_embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) {
[storage addObject:callback];
};
}
- (void)recordEmbedderEventsTo:(nonnull std::vector<FlutterKeyEvent>*)storage
returning:(bool)handled {
_embedderHandler = ^(const FlutterKeyEvent* event, FlutterAsyncKeyCallback callback) {
FlutterKeyEvent newEvent = *event;
if (event->character != nullptr) {
size_t charLen = strlen(event->character);
char* newCharacter = new char[charLen + 1];
strlcpy(newCharacter, event->character, charLen + 1);
newEvent.character = newCharacter;
}
storage->push_back(newEvent);
callback(handled);
};
}
- (void)respondChannelCallsWith:(BOOL)response {
_channelHandler = ^(FlutterAsyncKeyCallback callback) {
callback(response);
@@ -206,6 +369,13 @@ NSResponder* mockOwnerWithDownOnlyNext() {
_typeStorageMask = typeMask;
}
- (void)setLayout:(const MockLayoutData&)layout {
_currentLayout = &layout;
if (_keyboardLayoutNotifier != nil) {
_keyboardLayoutNotifier();
}
}
#pragma mark - Private
- (void)handleEmbedderEvent:(const FlutterKeyEvent&)event
@@ -215,7 +385,7 @@ NSResponder* mockOwnerWithDownOnlyNext() {
[_typeStorage addObject:@(kEmbedderCall)];
}
if (callback != nullptr) {
_embedderHandler(^(BOOL handled) {
_embedderHandler(&event, ^(BOOL handled) {
callback(handled, userData);
});
}
@@ -243,23 +413,30 @@ NSResponder* mockOwnerWithDownOnlyNext() {
return _textCallback(event);
}
- (void)onSetKeyboardLayoutNotifier:(nullable flutter::KeyboardLayoutNotifier)callback {
_keyboardLayoutNotifier = callback;
}
- (LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift {
uint32_t cluePair = (*_currentLayout)[(keyCode * 2) + (shift ? 1 : 0)];
const uint32_t kCharMask = 0xffff;
const uint32_t kDeadKeyMask = 0x10000;
return LayoutClue{cluePair & kCharMask, (cluePair & kDeadKeyMask) != 0};
}
@end
@interface FlutterKeyboardManagerUnittestsObjC : NSObject
- (bool)nextResponderShouldThrowOnKeyUp;
- (bool)singlePrimaryResponder;
- (bool)doublePrimaryResponder;
- (bool)textInputPlugin;
- (bool)forwardKeyEventsToSystemWhenComposing;
- (bool)emptyNextResponder;
- (bool)racingConditionBetweenKeyAndText;
- (bool)correctLogicalKeyForLayouts;
@end
namespace flutter::testing {
TEST(FlutterKeyboardManagerUnittests, NextResponderShouldThrowOnKeyUp) {
ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] nextResponderShouldThrowOnKeyUp]);
}
TEST(FlutterKeyboardManagerUnittests, SinglePrimaryResponder) {
ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] singlePrimaryResponder]);
}
@@ -284,22 +461,14 @@ TEST(FlutterKeyboardManagerUnittests, RacingConditionBetweenKeyAndText) {
ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] racingConditionBetweenKeyAndText]);
}
TEST(FlutterKeyboardManagerUnittests, CorrectLogicalKeyForLayouts) {
ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] correctLogicalKeyForLayouts]);
}
} // namespace flutter::testing
@implementation FlutterKeyboardManagerUnittestsObjC
// Verify that the nextResponder returned from mockOwnerWithDownOnlyNext()
// throws exception when keyUp is called.
- (bool)nextResponderShouldThrowOnKeyUp {
NSResponder* owner = mockOwnerWithDownOnlyNext();
@try {
[owner.nextResponder keyUp:keyUpEvent(0x50)];
return false;
} @catch (...) {
return true;
}
}
- (bool)singlePrimaryResponder {
KeyboardTester* tester = [[KeyboardTester alloc] init];
NSMutableArray<FlutterAsyncKeyCallback>* embedderCallbacks =
@@ -505,8 +674,8 @@ TEST(FlutterKeyboardManagerUnittests, RacingConditionBetweenKeyAndText) {
// Tap key O, which is converted to normal KeyO events, but the responses are
// slow.
[tester.manager handleEvent:keyDownEvent(kKeyCodeKeyO, @"o", @"o")];
[tester.manager handleEvent:keyUpEvent(kKeyCodeKeyO)];
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_O, @"o", @"o")];
[tester.manager handleEvent:keyUpEvent(kVK_ANSI_O)];
EXPECT_EQ([keyCallbacks count], 1u);
EXPECT_EQ([allCalls count], 1u);
EXPECT_EQ(allCalls[0], @(kEmbedderCall));
@@ -514,8 +683,8 @@ TEST(FlutterKeyboardManagerUnittests, RacingConditionBetweenKeyAndText) {
// Tap key C, which results in two Backspace messages first - and here they
// arrive before the key O messages are responded.
[tester.manager handleEvent:keyDownEvent(kKeyCodeBackspace)];
[tester.manager handleEvent:keyUpEvent(kKeyCodeBackspace)];
[tester.manager handleEvent:keyDownEvent(kVK_Delete)];
[tester.manager handleEvent:keyUpEvent(kVK_Delete)];
EXPECT_EQ([keyCallbacks count], 1u);
EXPECT_EQ([allCalls count], 1u);
@@ -542,4 +711,86 @@ TEST(FlutterKeyboardManagerUnittests, RacingConditionBetweenKeyAndText) {
return true;
}
- (bool)correctLogicalKeyForLayouts {
KeyboardTester* tester = [[KeyboardTester alloc] init];
tester.nextResponder = nil;
std::vector<FlutterKeyEvent> events;
[tester recordEmbedderEventsTo:&events returning:true];
[tester respondChannelCallsWith:false];
[tester respondTextInputWith:false];
auto sendTap = [&](uint16_t keyCode, NSString* chars, NSString* charsUnmod) {
[tester.manager handleEvent:keyDownEvent(keyCode, chars, charsUnmod)];
[tester.manager handleEvent:keyUpEvent(keyCode)];
};
/* US keyboard layout */
sendTap(kVK_ANSI_A, @"a", @"a"); // KeyA
VERIFY_DOWN(kLogicalKeyA, "a");
sendTap(kVK_ANSI_A, @"A", @"A"); // Shift-KeyA
VERIFY_DOWN(kLogicalKeyA, "A");
sendTap(kVK_ANSI_A, @"å", @"a"); // Option-KeyA
VERIFY_DOWN(kLogicalKeyA, "å");
sendTap(kVK_ANSI_T, @"t", @"t"); // KeyT
VERIFY_DOWN(kLogicalKeyT, "t");
sendTap(kVK_ANSI_1, @"1", @"1"); // Digit1
VERIFY_DOWN(kLogicalDigit1, "1");
sendTap(kVK_ANSI_1, @"!", @"!"); // Shift-Digit1
VERIFY_DOWN(kLogicalDigit1, "!");
sendTap(kVK_ANSI_Minus, @"-", @"-"); // Minus
VERIFY_DOWN('-', "-");
sendTap(kVK_ANSI_Minus, @"=", @"="); // Shift-Minus
VERIFY_DOWN('=', "=");
/* French keyboard layout */
[tester setLayout:kFrenchLayout];
sendTap(kVK_ANSI_A, @"q", @"q"); // KeyA
VERIFY_DOWN(kLogicalKeyQ, "q");
sendTap(kVK_ANSI_A, @"Q", @"Q"); // Shift-KeyA
VERIFY_DOWN(kLogicalKeyQ, "Q");
sendTap(kVK_ANSI_Semicolon, @"m", @"m"); // ; but prints M
VERIFY_DOWN(kLogicalKeyM, "m");
sendTap(kVK_ANSI_M, @",", @","); // M but prints ,
VERIFY_DOWN(',', ",");
sendTap(kVK_ANSI_1, @"&", @"&"); // Digit1
VERIFY_DOWN(kLogicalDigit1, "&");
sendTap(kVK_ANSI_1, @"1", @"1"); // Shift-Digit1
VERIFY_DOWN(kLogicalDigit1, "1");
sendTap(kVK_ANSI_Minus, @")", @")"); // Minus
VERIFY_DOWN(')', ")");
sendTap(kVK_ANSI_Minus, @"°", @"°"); // Shift-Minus
VERIFY_DOWN(L'°', "°");
/* Russian keyboard layout */
[tester setLayout:kRussianLayout];
sendTap(kVK_ANSI_A, @"ф", @"ф"); // KeyA
VERIFY_DOWN(kLogicalKeyA, "ф");
sendTap(kVK_ANSI_1, @"1", @"1"); // Digit1
VERIFY_DOWN(kLogicalDigit1, "1");
sendTap(kVK_ANSI_LeftBracket, @"х", @"х");
VERIFY_DOWN(kLogicalBracketLeft, "х");
return TRUE;
}
@end

View File

@@ -7,6 +7,29 @@
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h"
#import "flutter/shell/platform/embedder/embedder.h"
namespace flutter {
// Signature used to notify that a keyboard layout has changed.
typedef void (^KeyboardLayoutNotifier)();
// The printable result of a key under certain modifiers, used to derive key
// mapping.
typedef struct {
// The printable character.
//
// If `isDeadKey` is true, then this is the character when pressing the same
// dead key twice.
uint32_t character;
// Whether this character is a dead key.
//
// A dead key is a key that is not counted as text per se, but holds a
// diacritics to be added to the next key.
bool isDeadKey;
} LayoutClue;
} // namespace flutter
/**
* An interface for a class that can provides |FlutterKeyboardManager| with
* platform-related features.
@@ -16,7 +39,6 @@
@protocol FlutterKeyboardViewDelegate
@required
/**
* Get the next responder to dispatch events that the keyboard system
* (including text input) do not handle.
@@ -61,4 +83,17 @@
// https://github.com/flutter/flutter/issues/85328.
- (BOOL)isComposing;
/**
* Add a listener that is called whenever the user changes keyboard layout.
*
* Only one listeners is supported. Adding new ones overwrites the current one.
* Assigning nil unsubscribes.
*/
- (void)subscribeToKeyboardLayoutChange:(nullable flutter::KeyboardLayoutNotifier)callback;
/**
* Querying the printable result of a key under the given modifier state.
*/
- (flutter::LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift;
@end

View File

@@ -5,6 +5,8 @@
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#include <Carbon/Carbon.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h"
@@ -22,6 +24,8 @@
#import "flutter/shell/platform/embedder/embedder.h"
namespace {
using flutter::LayoutClue;
using flutter::KeyboardLayoutNotifier;
/// Clipboard plain text format.
constexpr char kTextPlainFormat[] = "text/plain";
@@ -73,6 +77,27 @@ struct MouseState {
}
};
/**
* Returns the current Unicode layout data (kTISPropertyUnicodeKeyLayoutData).
*
* To use the returned data, convert it to CFDataRef first, finds its bytes
* with CFDataGetBytePtr, then reinterpret it into const UCKeyboardLayout*.
* It's returned in NSData* to enable auto reference count.
*/
NSData* currentKeyboardLayoutData() {
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
CFTypeRef layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
if (layout_data == nil) {
CFRelease(source);
// TISGetInputSourceProperty returns null with Japanese keyboard layout.
// Using TISCopyCurrentKeyboardLayoutInputSource to fix NULL return.
// https://github.com/microsoft/node-native-keymap/blob/5f0699ded00179410a14c0e1b0e089fe4df8e130/src/keyboard_mac.mm#L91
source = TISCopyCurrentKeyboardLayoutInputSource();
layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
}
return (__bridge_transfer NSData*)CFRetain(layout_data);
}
} // namespace
#pragma mark - Private interface declaration.
@@ -121,6 +146,10 @@ struct MouseState {
*/
@property(nonatomic) FlutterKeyboardManager* keyboardManager;
@property(nonatomic) KeyboardLayoutNotifier keyboardLayoutNotifier;
@property(nonatomic) NSData* keyboardLayoutData;
/**
* Starts running |engine|, including any initial setup.
*/
@@ -169,6 +198,9 @@ struct MouseState {
*/
- (void)onAccessibilityStatusChanged:(NSNotification*)notification;
// TODO
- (void)onKeyboardLayoutChanged;
/**
* Handles messages received from the Flutter engine on the _*Channel channels.
*/
@@ -199,6 +231,21 @@ struct MouseState {
@end
#pragma mark - Private dependant functions
namespace {
void OnKeyboardLayoutChanged(CFNotificationCenterRef center,
void* observer,
CFStringRef name,
const void* object,
CFDictionaryRef userInfo) {
FlutterViewController* controller = (__bridge FlutterViewController*)observer;
if (controller != nil) {
[controller onKeyboardLayoutChanged];
}
}
} // namespace
#pragma mark - FlutterViewWrapper implementation.
@implementation FlutterViewWrapper {
@@ -257,6 +304,12 @@ static void CommonInit(FlutterViewController* controller) {
selector:@selector(applicationWillTerminate:)
name:NSApplicationWillTerminateNotification
object:nil];
// macOS fires this message when changing IMEs.
CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter();
__weak FlutterViewController* weakSelf = controller;
CFNotificationCenterAddObserver(cfCenter, (__bridge void*)weakSelf, OnKeyboardLayoutChanged,
kTISNotifySelectedKeyboardInputSourceChanged, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
}
- (instancetype)initWithCoder:(NSCoder*)coder {
@@ -354,6 +407,8 @@ static void CommonInit(FlutterViewController* controller) {
- (void)dealloc {
_engine.viewController = nil;
CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter();
CFNotificationCenterRemoveEveryObserver(cfCenter, (__bridge void*)self);
}
#pragma mark - Public methods
@@ -585,6 +640,13 @@ static void CommonInit(FlutterViewController* controller) {
}];
}
- (void)onKeyboardLayoutChanged {
_keyboardLayoutData = nil;
if (_keyboardLayoutNotifier != nil) {
_keyboardLayoutNotifier();
}
}
- (void)sendInitialSettings {
// TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015.
[[NSDistributedNotificationCenter defaultCenter]
@@ -681,6 +743,42 @@ static void CommonInit(FlutterViewController* controller) {
return [_textInputPlugin handleKeyEvent:event];
}
- (void)subscribeToKeyboardLayoutChange:(nullable KeyboardLayoutNotifier)callback {
_keyboardLayoutNotifier = callback;
}
- (LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift {
if (_keyboardLayoutData == nil) {
_keyboardLayoutData = currentKeyboardLayoutData();
}
const UCKeyboardLayout* layout = reinterpret_cast<const UCKeyboardLayout*>(
CFDataGetBytePtr((__bridge CFDataRef)_keyboardLayoutData));
UInt32 deadKeyState = 0;
UniCharCount stringLength = 0;
UniChar resultChar;
UInt32 modifierState = ((shift ? shiftKey : 0) >> 8) & 0xFF;
UInt32 keyboardType = LMGetKbdLast();
bool isDeadKey = false;
OSStatus status =
UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierState, keyboardType,
kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 1, &stringLength, &resultChar);
// For dead keys, press the same key again to get the printable representation of the key.
if (status == noErr && stringLength == 0 && deadKeyState != 0) {
isDeadKey = true;
status =
UCKeyTranslate(layout, keyCode, kUCKeyActionDown, modifierState, keyboardType,
kUCKeyTranslateNoDeadKeysBit, &deadKeyState, 1, &stringLength, &resultChar);
}
if (status == noErr && stringLength == 1 && !std::iscntrl(resultChar)) {
return LayoutClue{resultChar, isDeadKey};
}
return LayoutClue{0, false};
}
#pragma mark - NSResponder
- (BOOL)acceptsFirstResponder {

View File

@@ -17,6 +17,8 @@
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
namespace flutter {
const uint64_t kValueMask = 0x000ffffffff;
const uint64_t kUnicodePlane = 0x00000000000;
const uint64_t kMacosPlane = 0x01400000000;
@@ -242,3 +244,56 @@ const NSDictionary* modifierFlagToKeyCode = @{
const uint64_t kCapsLockPhysicalKey = 0x00070039;
const uint64_t kCapsLockLogicalKey = 0x100000104;
const std::vector<LayoutGoal> layoutGoals = {
LayoutGoal{0x31, 0x20, false}, // Space
LayoutGoal{0x27, 0x22, false}, // Quote
LayoutGoal{0x2b, 0x2c, false}, // Comma
LayoutGoal{0x1b, 0x2d, false}, // Minus
LayoutGoal{0x2f, 0x2e, false}, // Period
LayoutGoal{0x2c, 0x2f, false}, // Slash
LayoutGoal{0x1d, 0x30, true}, // Digit0
LayoutGoal{0x12, 0x31, true}, // Digit1
LayoutGoal{0x13, 0x32, true}, // Digit2
LayoutGoal{0x14, 0x33, true}, // Digit3
LayoutGoal{0x15, 0x34, true}, // Digit4
LayoutGoal{0x17, 0x35, true}, // Digit5
LayoutGoal{0x16, 0x36, true}, // Digit6
LayoutGoal{0x1a, 0x37, true}, // Digit7
LayoutGoal{0x1c, 0x38, true}, // Digit8
LayoutGoal{0x19, 0x39, true}, // Digit9
LayoutGoal{0x29, 0x3b, false}, // Semicolon
LayoutGoal{0x18, 0x3d, false}, // Equal
LayoutGoal{0x21, 0x5b, false}, // BracketLeft
LayoutGoal{0x2a, 0x5c, false}, // Backslash
LayoutGoal{0x1e, 0x5d, false}, // BracketRight
LayoutGoal{0x32, 0x60, false}, // Backquote
LayoutGoal{0x00, 0x61, true}, // KeyA
LayoutGoal{0x0b, 0x62, true}, // KeyB
LayoutGoal{0x08, 0x63, true}, // KeyC
LayoutGoal{0x02, 0x64, true}, // KeyD
LayoutGoal{0x0e, 0x65, true}, // KeyE
LayoutGoal{0x03, 0x66, true}, // KeyF
LayoutGoal{0x05, 0x67, true}, // KeyG
LayoutGoal{0x04, 0x68, true}, // KeyH
LayoutGoal{0x22, 0x69, true}, // KeyI
LayoutGoal{0x26, 0x6a, true}, // KeyJ
LayoutGoal{0x28, 0x6b, true}, // KeyK
LayoutGoal{0x25, 0x6c, true}, // KeyL
LayoutGoal{0x2e, 0x6d, true}, // KeyM
LayoutGoal{0x2d, 0x6e, true}, // KeyN
LayoutGoal{0x1f, 0x6f, true}, // KeyO
LayoutGoal{0x23, 0x70, true}, // KeyP
LayoutGoal{0x0c, 0x71, true}, // KeyQ
LayoutGoal{0x0f, 0x72, true}, // KeyR
LayoutGoal{0x01, 0x73, true}, // KeyS
LayoutGoal{0x11, 0x74, true}, // KeyT
LayoutGoal{0x20, 0x75, true}, // KeyU
LayoutGoal{0x09, 0x76, true}, // KeyV
LayoutGoal{0x0d, 0x77, true}, // KeyW
LayoutGoal{0x07, 0x78, true}, // KeyX
LayoutGoal{0x10, 0x79, true}, // KeyY
LayoutGoal{0x06, 0x7a, true}, // KeyZ
};
} // namespace flutter

View File

@@ -4,6 +4,9 @@
#import <Cocoa/Cocoa.h>
#include <cinttypes>
#include <vector>
namespace flutter {
/**
* Maps macOS-specific key code values representing |PhysicalKeyboardKey|.
@@ -80,3 +83,27 @@ typedef enum {
kModifierFlagAltRight = 0x40,
kModifierFlagControlRight = 0x200,
} ModifierFlag;
/**
* A character that Flutter wants to derive layout for, and guides on how to
* derive it.
*/
typedef struct {
// The key code for a key that prints `keyChar` in the US keyboard layout.
uint16_t keyCode;
// The printable string to derive logical key for.
uint8_t keyChar;
// If the goal is mandatory, the keyboard manager will make sure to find a
// logical key for this character, falling back to the US keyboard layout.
bool mandatory;
} LayoutGoal;
/**
* All keys that Flutter wants to derive layout for, and guides on how to derive
* them.
*/
extern const std::vector<LayoutGoal> layoutGoals;
} // namespace flutter