[macOS] Prepare FlutterKeyboardManager for multi-view (#163962)

Notable changes:
- Moved keyboard layout related code from `FlutterViewController` to
`FlutterKeyboardLayout`.
- `FlutterKeyboardManager` is now owned by the engine and shared between
view controllers. The per view controller part, which is associated with
event, has been moved from `FlutterKeyboardManager` delegate to
`FlutterKeyboardManagerEventContext`.
- The `FlutterKeyboardManagerDelegate` is implemented by
`FlutterEngine`.
- Some overall clean-up and dead code removal (i.e. `_NSResponderPtr`
and `NextResponderProvider`)

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

If you need help, consider asking for advice on the #hackers-new channel
on [Discord].

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md

---------

Co-authored-by: Tong Mu <dkwingsmt@users.noreply.github.com>
This commit is contained in:
Matej Knopp
2025-02-28 23:28:25 +01:00
committed by GitHub
parent b831b269c5
commit 07503bbc82
14 changed files with 439 additions and 363 deletions

View File

@@ -43450,10 +43450,11 @@ ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterEng
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm + ../../../flutter/LICENSE
@@ -46401,10 +46402,11 @@ FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterEngin
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyPrimaryResponder.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardLayout.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManagerTest.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.mm
FILE: ../../../flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm

View File

@@ -77,9 +77,10 @@ source_set("flutter_framework_source") {
"framework/Source/FlutterExternalTexture.h",
"framework/Source/FlutterExternalTexture.mm",
"framework/Source/FlutterKeyPrimaryResponder.h",
"framework/Source/FlutterKeyboardLayout.h",
"framework/Source/FlutterKeyboardLayout.mm",
"framework/Source/FlutterKeyboardManager.h",
"framework/Source/FlutterKeyboardManager.mm",
"framework/Source/FlutterKeyboardViewDelegate.h",
"framework/Source/FlutterMenuPlugin.h",
"framework/Source/FlutterMenuPlugin.mm",
"framework/Source/FlutterMenuPlugin_Internal.h",

View File

@@ -104,9 +104,6 @@
forEventFlags:modifierFlags
keyCode:0x00000039 // kVK_CapsLock
timestamp:timestamp];
// At the end we should end up with the same modifier flags as the event.
FML_DCHECK(_previouslyPressedFlags == modifierFlags);
}
- (void)handleEvent:(NSEvent*)event callback:(FlutterAsyncKeyCallback)callback {

View File

@@ -89,7 +89,9 @@ constexpr char kTextPlainFormat[] = "text/plain";
/**
* Private interface declaration for FlutterEngine.
*/
@interface FlutterEngine () <FlutterBinaryMessenger, FlutterMouseCursorPluginDelegate>
@interface FlutterEngine () <FlutterBinaryMessenger,
FlutterMouseCursorPluginDelegate,
FlutterKeyboardManagerDelegate>
/**
* A mutable array that holds one bool value that determines if responses to platform messages are
@@ -473,6 +475,9 @@ static void OnPlatformMessage(const FlutterPlatformMessage* message, void* user_
// Weak reference to last view that received a pointer event. This is used to
// pair cursor change with a view.
__weak FlutterView* _lastViewWithPointerEvent;
// Pointer to a keyboard manager.
FlutterKeyboardManager* _keyboardManager;
}
- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project {
@@ -513,6 +518,7 @@ static void SetThreadPriority(FlutterThreadPriority priority) {
_binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self];
_isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
[_isResponseValid addObject:@YES];
_keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:self];
_embedderAPI.struct_size = sizeof(FlutterEngineProcTable);
FlutterEngineGetProcAddresses(&_embedderAPI);
@@ -1024,12 +1030,6 @@ static void SetThreadPriority(FlutterThreadPriority priority) {
_lastViewWithPointerEvent = [self viewControllerForIdentifier:kFlutterImplicitViewId].flutterView;
}
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(FlutterKeyEventCallback)callback
userData:(void*)userData {
_embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
}
- (void)setSemanticsEnabled:(BOOL)enabled {
if (_semanticsEnabled == enabled) {
return;
@@ -1127,6 +1127,7 @@ static void SetThreadPriority(FlutterThreadPriority priority) {
[nextViewController onPreEngineRestart];
}
[_platformViewController reset];
_keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:self];
}
- (void)onVSync:(uintptr_t)baton {
@@ -1564,4 +1565,15 @@ static void SetThreadPriority(FlutterThreadPriority priority) {
return _macOSCompositor.get();
}
#pragma mark - FlutterKeyboardManagerDelegate
/**
* Dispatches the given pointer event data to engine.
*/
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(FlutterKeyEventCallback)callback
userData:(void*)userData {
_embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
}
@end

View File

@@ -14,6 +14,7 @@
#include "flutter/shell/platform/common/app_lifecycle_state.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
@@ -165,13 +166,6 @@ typedef NS_ENUM(NSInteger, FlutterAppExitResponse) {
*/
- (void)sendPointerEvent:(const FlutterPointerEvent&)event;
/**
* Dispatches the given pointer event data to engine.
*/
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)userData;
/**
* Registers an external texture with the given id. Returns YES on success.
*/
@@ -218,6 +212,11 @@ typedef NS_ENUM(NSInteger, FlutterAppExitResponse) {
- (void)announceAccessibilityMessage:(NSString*)message
withPriority:(NSAccessibilityPriorityLevel)priority;
/**
* Returns keyboard manager for the engine.
*/
@property(nonatomic, readonly) FlutterKeyboardManager* keyboardManager;
/**
* Returns an array of screen objects representing all of the screens available on the system.
*/

View File

@@ -0,0 +1,61 @@
// 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_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDLAYOUT_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDLAYOUT_H_
#import <AppKit/AppKit.h>
namespace flutter {
// 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
/**
* A delegate protocol for FlutterKeyboardLayout. Implemented by FlutterKeyboardManager.
*/
@protocol FlutterKeyboardLayoutDelegate
/**
* Called when the active keyboard input source changes.
*
* Input sources may be simple keyboard layouts, or more complex input methods involving an IME,
* such as Chinese, Japanese, and Korean.
*/
- (void)keyboardLayoutDidChange;
@end
/**
* A class that allows querying the printable result of a key with a modifier state according to the
* current keyboard layout. It also provides a delegate protocol for clients interested in
* listening to keyboard layout changes.
*/
@interface FlutterKeyboardLayout : NSObject
@property(readwrite, nonatomic, weak) id<FlutterKeyboardLayoutDelegate> delegate;
/**
* Querying the printable result of a key under the given modifier state.
*/
- (flutter::LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDLAYOUT_H_

View File

@@ -0,0 +1,107 @@
// 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/macos/framework/Source/FlutterKeyboardLayout.h"
#include <Carbon/Carbon.h>
#include <cctype>
#include "flutter/fml/platform/darwin/cf_utils.h"
@implementation FlutterKeyboardLayout {
NSData* _keyboardLayoutData;
}
@synthesize delegate = _delegate;
/**
* 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.
*/
static NSData* CurrentKeyboardLayoutData() {
fml::CFRef<TISInputSourceRef> source(TISCopyCurrentKeyboardInputSource());
CFTypeRef layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
if (layout_data == nil) {
// 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.Reset(TISCopyCurrentKeyboardLayoutInputSource());
layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
}
return (__bridge NSData*)layout_data;
}
/**
* NotificationCenter callback invoked on kTISNotifySelectedKeyboardInputSourceChanged events.
*/
static void OnKeyboardLayoutChanged(CFNotificationCenterRef center,
void* observer,
CFStringRef name,
const void* object,
CFDictionaryRef userInfo) {
FlutterKeyboardLayout* controller = (__bridge FlutterKeyboardLayout*)observer;
if (controller != nil) {
[controller onKeyboardLayoutChanged];
}
}
- (instancetype)initWithDelegate:(id<FlutterKeyboardLayoutDelegate>)delegate {
self = [super init];
if (self) {
_delegate = delegate;
// macOS fires this message when changing IMEs.
CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter();
__weak FlutterKeyboardLayout* weakSelf = self;
CFNotificationCenterAddObserver(cfCenter, (__bridge void*)weakSelf, OnKeyboardLayoutChanged,
kTISNotifySelectedKeyboardInputSourceChanged, NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
}
return self;
}
- (void)dealloc {
CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter();
CFNotificationCenterRemoveEveryObserver(cfCenter, (__bridge void*)self);
}
- (void)onKeyboardLayoutChanged {
_keyboardLayoutData = nil;
[_delegate keyboardLayoutDidChange];
}
- (flutter::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 flutter::LayoutClue{resultChar, isDeadKey};
}
return flutter::LayoutClue{0, false};
}
@end

View File

@@ -7,10 +7,61 @@
#import <Cocoa/Cocoa.h>
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h"
#import "flutter/shell/platform/embedder/embedder.h"
@protocol FlutterKeyboardManagerDelegate
@required
/**
* Processes keyboard events and cooperate with |TextInputPlugin|.
* Dispatch events to the framework to be processed by |HardwareKeyboard|.
*
* This method typically forwards events to
* |FlutterEngine.sendKeyEvent:callback:userData:|.
*/
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)userData;
/**
* Get a binary messenger to send channel messages with.
*
* This method is used to create the key data channel and typically
* forwards to |FlutterEngine.binaryMessenger|.
*/
- (nonnull id<FlutterBinaryMessenger>)binaryMessenger;
@end
/**
* Provides context for a keyboard event. Implemented by FlutterViewController.
*/
@protocol FlutterKeyboardManagerEventContext
@required
/**
* Get the next responder to dispatch events that the keyboard system
* (including text input) do not handle.
*
* If the |nextResponder| is null, then those events will be discarded.
*/
@property(nonatomic, readonly, nullable) NSResponder* nextResponder;
/**
* Dispatch events that are not handled by the keyboard event handlers
* to the text input handler.
*
* This method typically forwards events to |TextInputPlugin.handleKeyEvent|.
*/
- (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event;
@end
/**
* A hub that manages how key events are dispatched to various Flutter key
* responders, and whether the event is propagated to the next NSResponder.
* Cooperates with |TextInputPlugin| to handle text
*
* A keyboard event goes through a few sections, each can choose to handled the
* event, and only unhandled events can move to the next section:
@@ -32,7 +83,7 @@
* The |viewDelegate| is a weak reference, typically implemented by
* |FlutterViewController|.
*/
- (nonnull instancetype)initWithViewDelegate:(nonnull id<FlutterKeyboardViewDelegate>)viewDelegate;
- (nonnull instancetype)initWithDelegate:(nonnull id<FlutterKeyboardManagerDelegate>)delegate;
/**
* Processes a key event.
@@ -40,7 +91,8 @@
* Unhandled events will be dispatched to the text input system, and possibly
* the next responder afterwards.
*/
- (void)handleEvent:(nonnull NSEvent*)event;
- (void)handleEvent:(nonnull NSEvent*)event
withContext:(nonnull id<FlutterKeyboardManagerEventContext>)eventContext;
/**
* Returns yes if is event currently being redispatched.
@@ -70,4 +122,11 @@
@end
@class FlutterKeyboardLayout;
@interface FlutterKeyboardManager (Testing)
- (nonnull instancetype)initWithDelegate:(nonnull id<FlutterKeyboardManagerDelegate>)delegate
keyboardLayout:(nonnull FlutterKeyboardLayout*)keyboardLayout;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDMANAGER_H_

View File

@@ -11,6 +11,7 @@
#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/FlutterKeyboardLayout.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
@@ -35,36 +36,54 @@ NSString* debugFormatLayoutData(NSString* debugLayoutData,
}
#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 ()
@interface FlutterEventWithContext : NSObject
@property(nonatomic, readonly) NSEvent* event;
@property(nonatomic, readonly) id<FlutterKeyboardManagerEventContext> context;
- (instancetype)initWithEvent:(NSEvent*)event
context:(nonnull id<FlutterKeyboardManagerEventContext>)context;
@end
@implementation FlutterEventWithContext {
NSEvent* _event;
id<FlutterKeyboardManagerEventContext> _context;
}
- (instancetype)initWithEvent:(NSEvent*)event
context:(id<FlutterKeyboardManagerEventContext>)context {
self = [super init];
if (self) {
_event = event;
_context = context;
}
return self;
}
@end
@interface FlutterKeyboardManager () <FlutterKeyboardLayoutDelegate>
/**
* The text input plugin set by initialization.
*/
@property(nonatomic, weak) id<FlutterKeyboardViewDelegate> viewDelegate;
@property(nonatomic, weak) id<FlutterKeyboardManagerDelegate> delegate;
/**
* The primary responders added by addPrimaryResponder.
*/
@property(nonatomic) NSMutableArray<id<FlutterKeyPrimaryResponder>>* primaryResponders;
@property(nonatomic) NSMutableArray<NSEvent*>* pendingEvents;
@property(nonatomic) NSMutableArray<FlutterEventWithContext*>* pendingEvents;
@property(nonatomic) BOOL processingEvent;
@@ -94,13 +113,16 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
*
* This function is called by processNextEvent.
*/
- (void)performProcessEvent:(NSEvent*)event onFinish:(nonnull VoidBlock)onFinish;
- (void)performProcessEvent:(NSEvent*)event
withContext:(nonnull id<FlutterKeyboardManagerEventContext>)context
onFinish:(nonnull VoidBlock)onFinish;
/**
* Dispatch an event that's not hadled by the responders to text input plugin,
* and potentially to the next responder.
*/
- (void)dispatchTextEvent:(nonnull NSEvent*)pendingEvent;
- (void)dispatchTextEvent:(nonnull NSEvent*)pendingEvent
withContext:(nonnull id<FlutterKeyboardManagerEventContext>)context;
/**
* Clears the current layout and build a new one based on the current layout.
@@ -110,18 +132,23 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
@end
@implementation FlutterKeyboardManager {
NextResponderProvider _getNextResponder;
FlutterKeyboardLayout* _keyboardLayout;
}
- (nonnull instancetype)initWithViewDelegate:(nonnull id<FlutterKeyboardViewDelegate>)viewDelegate {
- (nonnull instancetype)initWithDelegate:(nonnull id<FlutterKeyboardManagerDelegate>)delegate {
return [self initWithDelegate:delegate keyboardLayout:[[FlutterKeyboardLayout alloc] init]];
}
- (nonnull instancetype)initWithDelegate:(nonnull id<FlutterKeyboardManagerDelegate>)delegate
keyboardLayout:(nonnull FlutterKeyboardLayout*)keyboardLayout {
self = [super init];
if (self != nil) {
_processingEvent = FALSE;
_viewDelegate = viewDelegate;
_delegate = delegate;
FlutterMethodChannel* keyboardChannel =
[FlutterMethodChannel methodChannelWithName:@"flutter/keyboard"
binaryMessenger:[_viewDelegate getBinaryMessenger]
binaryMessenger:_delegate.binaryMessenger
codec:[FlutterStandardMethodCodec sharedInstance]];
[keyboardChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
@@ -136,30 +163,28 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
FlutterKeyEventCallback callback,
void* userData) {
__strong __typeof__(weakSelf) strongSelf = weakSelf;
[strongSelf.viewDelegate sendKeyEvent:event
callback:callback
userData:userData];
[strongSelf.delegate sendKeyEvent:event
callback:callback
userData:userData];
}]];
[self
addPrimaryResponder:[[FlutterChannelKeyResponder alloc]
initWithChannel:[FlutterBasicMessageChannel
messageChannelWithName:@"flutter/keyevent"
binaryMessenger:[_viewDelegate
getBinaryMessenger]
binaryMessenger:_delegate.binaryMessenger
codec:[FlutterJSONMessageCodec
sharedInstance]]]];
_pendingEvents = [[NSMutableArray alloc] init];
_layoutMap = [NSMutableDictionary<NSNumber*, NSNumber*> dictionary];
_keyboardLayout = keyboardLayout;
_keyboardLayout.delegate = self;
[self buildLayout];
for (id<FlutterKeyPrimaryResponder> responder in _primaryResponders) {
responder.layoutMap = _layoutMap;
}
[_viewDelegate subscribeToKeyboardLayoutChange:^() {
[weakSelf buildLayout];
}];
}
return self;
}
@@ -176,7 +201,8 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
[_primaryResponders addObject:responder];
}
- (void)handleEvent:(nonnull NSEvent*)event {
- (void)handleEvent:(nonnull NSEvent*)event
withContext:(nonnull id<FlutterKeyboardManagerEventContext>)context {
// The `handleEvent` does not process the event immediately, but instead put
// events into a queue. Events are processed one by one by `processNextEvent`.
@@ -187,7 +213,7 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
return;
}
[_pendingEvents addObject:event];
[_pendingEvents addObject:[[FlutterEventWithContext alloc] initWithEvent:event context:context]];
[self processNextEvent];
}
@@ -205,7 +231,7 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
_processingEvent = TRUE;
}
NSEvent* pendingEvent = [_pendingEvents firstObject];
FlutterEventWithContext* pendingEvent = [_pendingEvents firstObject];
[_pendingEvents removeObjectAtIndex:0];
__weak __typeof__(self) weakSelf = self;
@@ -213,10 +239,12 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
weakSelf.processingEvent = FALSE;
[weakSelf processNextEvent];
};
[self performProcessEvent:pendingEvent onFinish:onFinish];
[self performProcessEvent:pendingEvent.event withContext:pendingEvent.context onFinish:onFinish];
}
- (void)performProcessEvent:(NSEvent*)event onFinish:(VoidBlock)onFinish {
- (void)performProcessEvent:(NSEvent*)event
withContext:(id<FlutterKeyboardManagerEventContext>)context
onFinish:(VoidBlock)onFinish {
// Having no primary responders require extra logic, but Flutter hard-codes
// all primary responders, so this is a situation that Flutter will never
// encounter.
@@ -232,7 +260,7 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
anyHandled = anyHandled || handled;
if (unreplied == 0) {
if (!anyHandled) {
[weakSelf dispatchTextEvent:event];
[weakSelf dispatchTextEvent:event withContext:context];
}
onFinish();
}
@@ -243,11 +271,12 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
}
}
- (void)dispatchTextEvent:(NSEvent*)event {
if ([_viewDelegate onTextInputKeyEvent:event]) {
- (void)dispatchTextEvent:(NSEvent*)event
withContext:(id<FlutterKeyboardManagerEventContext>)context {
if ([context onTextInputKeyEvent:event]) {
return;
}
NSResponder* nextResponder = _viewDelegate.nextResponder;
NSResponder* nextResponder = context.nextResponder;
if (nextResponder == nil) {
return;
}
@@ -298,8 +327,8 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
#endif
for (uint16_t keyCode = 0; keyCode <= kMaxKeyCode; keyCode += 1) {
std::vector<LayoutClue> thisKeyClues = {
[_viewDelegate lookUpLayoutForKeyCode:keyCode shift:false],
[_viewDelegate lookUpLayoutForKeyCode:keyCode shift:true]};
[_keyboardLayout lookUpLayoutForKeyCode:keyCode shift:false],
[_keyboardLayout lookUpLayoutForKeyCode:keyCode shift:true]};
#ifdef DEBUG_PRINT_LAYOUT
debugLayoutData =
debugFormatLayoutData(debugLayoutData, keyCode, thisKeyClues[0], thisKeyClues[1]);
@@ -348,6 +377,11 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
}
}
- (void)reset {
_processingEvent = FALSE;
[_pendingEvents removeAllObjects];
}
/**
* Returns the keyboard pressed state.
*
@@ -361,4 +395,12 @@ typedef _Nullable _NSResponderPtr (^NextResponderProvider)();
return [embedderResponder getPressedState];
}
- (void)keyboardLayoutDidChange {
[self buildLayout];
}
- (void)replaceKeyboardLayout:(nonnull FlutterKeyboardLayout*)keyboardLayout {
_keyboardLayout = keyboardLayout;
}
@end

View File

@@ -8,6 +8,7 @@
#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/FlutterKeyboardLayout.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardManager.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h"
#import "flutter/testing/testing.h"
@@ -217,6 +218,7 @@ void clearEvents(std::vector<FlutterKeyEvent>& events) {
- (void)sendKeyboardChannelMessage:(NSData* _Nullable)message;
@property(readonly, nonatomic, strong) FlutterKeyboardManager* manager;
@property(readonly, nonatomic, strong) id<FlutterKeyboardManagerEventContext> eventContextMock;
@property(nonatomic, nullable, strong) NSResponder* nextResponder;
#pragma mark - Private
@@ -240,12 +242,14 @@ void clearEvents(std::vector<FlutterKeyEvent>& events) {
NSMutableArray<NSNumber*>* _typeStorage;
uint32_t _typeStorageMask;
flutter::KeyboardLayoutNotifier _keyboardLayoutNotifier;
__weak id<FlutterKeyboardLayoutDelegate> _keyboardLayoutDelegate;
const MockLayoutData* _currentLayout;
id _keyboardChannelResult;
NSObject<FlutterBinaryMessenger>* _messengerMock;
FlutterBinaryMessageHandler _keyboardHandler;
NSObject<FlutterKeyboardManagerEventContext>* _eventContextMock;
}
- (nonnull instancetype)init {
@@ -271,23 +275,28 @@ void clearEvents(std::vector<FlutterKeyEvent>& events) {
.andCall(self, @selector(setKeyboardChannelHandler:handler:));
OCMStub([_messengerMock sendOnChannel:@"flutter/keyboard" message:[OCMArg any]])
.andCall(self, @selector(handleKeyboardChannelMessage:message:));
id viewDelegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardViewDelegate));
OCMStub([viewDelegateMock nextResponder]).andReturn(_nextResponder);
OCMStub([viewDelegateMock onTextInputKeyEvent:[OCMArg any]])
.andCall(self, @selector(handleTextInputKeyEvent:));
OCMStub([viewDelegateMock getBinaryMessenger]).andReturn(_messengerMock);
OCMStub([viewDelegateMock sendKeyEvent:*(const FlutterKeyEvent*)[OCMArg anyPointer]
callback:nil
userData:nil])
id managerDelegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardManagerDelegate));
OCMStub([managerDelegateMock binaryMessenger]).andReturn(_messengerMock);
OCMStub([managerDelegateMock sendKeyEvent:*(const FlutterKeyEvent*)[OCMArg anyPointer]
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])
_eventContextMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardManagerEventContext));
OCMStub([_eventContextMock nextResponder]).andReturn(_nextResponder);
OCMStub([_eventContextMock onTextInputKeyEvent:[OCMArg any]])
.andCall(self, @selector(handleTextInputKeyEvent:));
id keyboardLayoutMock = OCMStrictClassMock([FlutterKeyboardLayout class]);
OCMStub([keyboardLayoutMock lookUpLayoutForKeyCode:0 shift:false])
.ignoringNonObjectArgs()
.andCall(self, @selector(lookUpLayoutForKeyCode:shift:));
OCMStub([keyboardLayoutMock setDelegate:[OCMArg any]])
.andCall(self, @selector(onSetKeyboardLayoutDelegate:));
_manager = [[FlutterKeyboardManager alloc] initWithViewDelegate:viewDelegateMock];
_manager = [[FlutterKeyboardManager alloc] initWithDelegate:managerDelegateMock
keyboardLayout:keyboardLayoutMock];
return self;
}
@@ -352,9 +361,7 @@ void clearEvents(std::vector<FlutterKeyEvent>& events) {
- (void)setLayout:(const MockLayoutData&)layout {
_currentLayout = &layout;
if (_keyboardLayoutNotifier != nil) {
_keyboardLayoutNotifier();
}
[_keyboardLayoutDelegate keyboardLayoutDidChange];
}
#pragma mark - Private
@@ -400,8 +407,8 @@ void clearEvents(std::vector<FlutterKeyEvent>& events) {
return _textCallback(event);
}
- (void)onSetKeyboardLayoutNotifier:(nullable flutter::KeyboardLayoutNotifier)callback {
_keyboardLayoutNotifier = callback;
- (void)onSetKeyboardLayoutDelegate:(id<FlutterKeyboardLayoutDelegate>)delegate {
_keyboardLayoutDelegate = delegate;
}
- (LayoutClue)lookUpLayoutForKeyCode:(uint16_t)keyCode shift:(BOOL)shift {
@@ -426,7 +433,7 @@ void clearEvents(std::vector<FlutterKeyEvent>& events) {
- (bool)keyboardChannelGetPressedState;
- (bool)racingConditionBetweenKeyAndText;
- (bool)correctLogicalKeyForLayouts;
- (bool)shouldNotHoldStrongReferenceToViewDelegate;
- (bool)shouldNotHoldStrongReferenceToDelegate;
@end
namespace flutter::testing {
@@ -463,9 +470,8 @@ TEST(FlutterKeyboardManagerUnittests, CorrectLogicalKeyForLayouts) {
ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] correctLogicalKeyForLayouts]);
}
TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate) {
ASSERT_TRUE(
[[FlutterKeyboardManagerUnittestsObjC alloc] shouldNotHoldStrongReferenceToViewDelegate]);
TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToDelegate) {
ASSERT_TRUE([[FlutterKeyboardManagerUnittestsObjC alloc] shouldNotHoldStrongReferenceToDelegate]);
}
} // namespace flutter::testing
@@ -479,14 +485,14 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[tester recordEmbedderCallsTo:embedderCallbacks];
// Case: The responder reports FALSE
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([embedderCallbacks count], 1u);
embedderCallbacks[0](FALSE);
OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x50)]);
[embedderCallbacks removeAllObjects];
// Case: The responder reports TRUE
[tester.manager handleEvent:keyUpEvent(0x50)];
[tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([embedderCallbacks count], 1u);
embedderCallbacks[0](TRUE);
// [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown.
@@ -500,7 +506,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Send a down event first so we can send an up event later.
[tester respondEmbedderCallsWith:false];
[tester respondChannelCallsWith:false];
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
NSMutableArray<FlutterAsyncKeyCallback>* embedderCallbacks =
[NSMutableArray<FlutterAsyncKeyCallback> array];
@@ -510,7 +516,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[tester recordChannelCallsTo:channelCallbacks];
// Case: Both responders report TRUE.
[tester.manager handleEvent:keyUpEvent(0x50)];
[tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([embedderCallbacks count], 1u);
EXPECT_EQ([channelCallbacks count], 1u);
embedderCallbacks[0](TRUE);
@@ -524,11 +530,11 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Case: One responder reports TRUE.
[tester respondEmbedderCallsWith:false];
[tester respondChannelCallsWith:false];
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
[tester recordEmbedderCallsTo:embedderCallbacks];
[tester recordChannelCallsTo:channelCallbacks];
[tester.manager handleEvent:keyUpEvent(0x50)];
[tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([embedderCallbacks count], 1u);
EXPECT_EQ([channelCallbacks count], 1u);
embedderCallbacks[0](FALSE);
@@ -540,7 +546,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[channelCallbacks removeAllObjects];
// Case: Both responders report FALSE.
[tester.manager handleEvent:keyDownEvent(0x53)];
[tester.manager handleEvent:keyDownEvent(0x53) withContext:tester.eventContextMock];
EXPECT_EQ([embedderCallbacks count], 1u);
EXPECT_EQ([channelCallbacks count], 1u);
embedderCallbacks[0](FALSE);
@@ -560,7 +566,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Send a down event first so we can send an up event later.
[tester respondEmbedderCallsWith:false];
[tester respondChannelCallsWith:false];
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
NSMutableArray<FlutterAsyncKeyCallback>* callbacks =
[NSMutableArray<FlutterAsyncKeyCallback> array];
@@ -569,7 +575,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Case: Primary responder responds TRUE. The event shouldn't be handled by
// the secondary responder.
[tester respondTextInputWith:FALSE];
[tester.manager handleEvent:keyUpEvent(0x50)];
[tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([callbacks count], 1u);
callbacks[0](TRUE);
// [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown.
@@ -577,13 +583,13 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Send a down event first so we can send an up event later.
[tester respondEmbedderCallsWith:false];
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
// Case: Primary responder responds FALSE. The secondary responder returns
// TRUE.
[tester recordEmbedderCallsTo:callbacks];
[tester respondTextInputWith:TRUE];
[tester.manager handleEvent:keyUpEvent(0x50)];
[tester.manager handleEvent:keyUpEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([callbacks count], 1u);
callbacks[0](FALSE);
// [owner.nextResponder keyUp:] should not be called, otherwise an error will be thrown.
@@ -591,7 +597,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Case: Primary responder responds FALSE. The secondary responder returns FALSE.
[tester respondTextInputWith:FALSE];
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
EXPECT_EQ([callbacks count], 1u);
callbacks[0](FALSE);
OCMVerify([tester.nextResponder keyDown:checkKeyDownEvent(0x50)]);
@@ -607,7 +613,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[tester respondEmbedderCallsWith:false];
[tester respondChannelCallsWith:false];
[tester respondTextInputWith:false];
[tester.manager handleEvent:keyDownEvent(0x50)];
[tester.manager handleEvent:keyDownEvent(0x50) withContext:tester.eventContextMock];
// Passes if no error is thrown.
return true;
@@ -619,7 +625,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[tester respondEmbedderCallsWith:false];
[tester respondChannelCallsWith:false];
[tester respondTextInputWith:false];
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_A)];
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_A) withContext:tester.eventContextMock];
NSDictionary* pressingRecords = [tester.manager getPressedState];
EXPECT_EQ([pressingRecords count], 1u);
@@ -634,7 +640,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[tester respondEmbedderCallsWith:false];
[tester respondChannelCallsWith:false];
[tester respondTextInputWith:false];
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_A)];
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_A) withContext:tester.eventContextMock];
FlutterMethodCall* getKeyboardStateMethodCall =
[FlutterMethodCall methodCallWithMethodName:@"getKeyboardState" arguments:nil];
@@ -668,7 +674,8 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Tap key U, which is converted by IME into a pure text message "ư".
[tester.manager handleEvent:keyDownEvent(kKeyCodeEmpty, @"ư", @"ư")];
[tester.manager handleEvent:keyDownEvent(kKeyCodeEmpty, @"ư", @"ư")
withContext:tester.eventContextMock];
EXPECT_EQ([keyCallbacks count], 1u);
EXPECT_EQ([allCalls count], 1u);
EXPECT_EQ(allCalls[0], @(kEmbedderCall));
@@ -679,7 +686,7 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[keyCallbacks removeAllObjects];
[allCalls removeAllObjects];
[tester.manager handleEvent:keyUpEvent(kKeyCodeEmpty)];
[tester.manager handleEvent:keyUpEvent(kKeyCodeEmpty) withContext:tester.eventContextMock];
EXPECT_EQ([keyCallbacks count], 1u);
keyCallbacks[0](false);
EXPECT_EQ([keyCallbacks count], 1u);
@@ -690,8 +697,9 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// Tap key O, which is converted to normal KeyO events, but the responses are
// slow.
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_O, @"o", @"o")];
[tester.manager handleEvent:keyUpEvent(kVK_ANSI_O)];
[tester.manager handleEvent:keyDownEvent(kVK_ANSI_O, @"o", @"o")
withContext:tester.eventContextMock];
[tester.manager handleEvent:keyUpEvent(kVK_ANSI_O) withContext:tester.eventContextMock];
EXPECT_EQ([keyCallbacks count], 1u);
EXPECT_EQ([allCalls count], 1u);
EXPECT_EQ(allCalls[0], @(kEmbedderCall));
@@ -699,8 +707,8 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
// 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(kVK_Delete)];
[tester.manager handleEvent:keyUpEvent(kVK_Delete)];
[tester.manager handleEvent:keyDownEvent(kVK_Delete) withContext:tester.eventContextMock];
[tester.manager handleEvent:keyUpEvent(kVK_Delete) withContext:tester.eventContextMock];
EXPECT_EQ([keyCallbacks count], 1u);
EXPECT_EQ([allCalls count], 1u);
@@ -737,8 +745,9 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
[tester respondTextInputWith:false];
auto sendTap = [&](uint16_t keyCode, NSString* chars, NSString* charsUnmod) {
[tester.manager handleEvent:keyDownEvent(keyCode, chars, charsUnmod)];
[tester.manager handleEvent:keyUpEvent(keyCode)];
[tester.manager handleEvent:keyDownEvent(keyCode, chars, charsUnmod)
withContext:tester.eventContextMock];
[tester.manager handleEvent:keyUpEvent(keyCode) withContext:tester.eventContextMock];
};
/* US keyboard layout */
@@ -816,30 +825,25 @@ TEST(FlutterKeyboardManagerUnittests, ShouldNotHoldStrongReferenceToViewDelegate
return TRUE;
}
- (bool)shouldNotHoldStrongReferenceToViewDelegate {
- (bool)shouldNotHoldStrongReferenceToDelegate {
__strong FlutterKeyboardManager* strongKeyboardManager;
__weak id weakViewDelegate;
__weak id weakDelegate;
@autoreleasepool {
id binaryMessengerMock = OCMStrictProtocolMock(@protocol(FlutterBinaryMessenger));
OCMStub([binaryMessengerMock setMessageHandlerOnChannel:[OCMArg any]
binaryMessageHandler:[OCMArg any]]);
id viewDelegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardViewDelegate));
OCMStub([viewDelegateMock getBinaryMessenger]).andReturn(binaryMessengerMock);
OCMStub([viewDelegateMock subscribeToKeyboardLayoutChange:[OCMArg any]]);
id delegateMock = OCMStrictProtocolMock(@protocol(FlutterKeyboardManagerDelegate));
OCMStub([delegateMock binaryMessenger]).andReturn(binaryMessengerMock);
LayoutClue layoutClue;
OCMStub([viewDelegateMock lookUpLayoutForKeyCode:0 shift:NO])
.ignoringNonObjectArgs()
.andReturn(layoutClue);
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithViewDelegate:viewDelegateMock];
[[FlutterKeyboardManager alloc] initWithDelegate:delegateMock];
strongKeyboardManager = keyboardManager;
weakViewDelegate = viewDelegateMock;
weakDelegate = delegateMock;
}
return weakViewDelegate == nil;
return weakDelegate == nil;
}
@end

View File

@@ -1,102 +0,0 @@
// 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_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDVIEWDELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDVIEWDELEGATE_H_
#import <Cocoa/Cocoa.h>
#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.
*
* This protocol is typically implemented by |FlutterViewController|.
*/
@protocol FlutterKeyboardViewDelegate
@required
/**
* Get the next responder to dispatch events that the keyboard system
* (including text input) do not handle.
*
* If the |nextResponder| is null, then those events will be discarded.
*/
@property(nonatomic, readonly, nullable) NSResponder* nextResponder;
/**
* Dispatch events to the framework to be processed by |HardwareKeyboard|.
*
* This method typically forwards events to
* |FlutterEngine.sendKeyEvent:callback:userData:|.
*/
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)userData;
/**
* Get a binary messenger to send channel messages with.
*
* This method is used to create the key data channel and typically
* forwards to |FlutterEngine.binaryMessenger|.
*/
- (nonnull id<FlutterBinaryMessenger>)getBinaryMessenger;
/**
* Dispatch events that are not handled by the keyboard event handlers
* to the text input handler.
*
* This method typically forwards events to |TextInputPlugin.handleKeyEvent|.
*/
- (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event;
/**
* 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;
/**
* Returns the keyboard pressed state.
*
* Returns the keyboard pressed state. The dictionary contains one entry per
* pressed keys, mapping from the logical key to the physical key.
*/
- (nonnull NSDictionary*)getPressedState;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERKEYBOARDVIEWDELEGATE_H_

View File

@@ -24,8 +24,6 @@
#pragma mark - Static types and data.
namespace {
using flutter::KeyboardLayoutNotifier;
using flutter::LayoutClue;
// Use different device ID for mouse and pan/zoom events, since we can't differentiate the actual
// device (mouse v.s. trackpad).
@@ -160,7 +158,7 @@ struct MouseState {
/**
* Private interface declaration for FlutterViewController.
*/
@interface FlutterViewController () <FlutterViewDelegate>
@interface FlutterViewController () <FlutterViewDelegate, FlutterKeyboardManagerEventContext>
/**
* The tracking area used to generate hover events, if enabled.
@@ -177,17 +175,6 @@ struct MouseState {
*/
@property(nonatomic) id keyUpMonitor;
/**
* 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, readonly, nonnull) FlutterKeyboardManager* keyboardManager;
@property(nonatomic) KeyboardLayoutNotifier keyboardLayoutNotifier;
@property(nonatomic) NSData* keyboardLayoutData;
/**
* Starts running |engine|, including any initial setup.
*/
@@ -199,11 +186,6 @@ struct MouseState {
*/
- (void)configureTrackingArea;
/**
* Creates and registers keyboard related components.
*/
- (void)initializeKeyboard;
/**
* Calls dispatchMouseEvent:phase: with a phase determined by self.mouseState.
*
@@ -221,32 +203,10 @@ struct MouseState {
*/
- (void)dispatchMouseEvent:(nonnull NSEvent*)event phase:(FlutterPointerPhase)phase;
/**
* Called when the active keyboard input source changes.
*
* Input sources may be simple keyboard layouts, or more complex input methods involving an IME,
* such as Chinese, Japanese, and Korean.
*/
- (void)onKeyboardLayoutChanged;
@end
#pragma mark - FlutterViewWrapper implementation.
/**
* NotificationCenter callback invoked on kTISNotifySelectedKeyboardInputSourceChanged events.
*/
static void OnKeyboardLayoutChanged(CFNotificationCenterRef center,
void* observer,
CFStringRef name,
const void* object,
CFDictionaryRef userInfo) {
FlutterViewController* controller = (__bridge FlutterViewController*)observer;
if (controller != nil) {
[controller onKeyboardLayoutChanged];
}
}
@implementation FlutterViewWrapper {
FlutterView* _flutterView;
__weak FlutterViewController* _controller;
@@ -367,14 +327,7 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
controller.engine, controller.viewIdentifier);
controller->_mouseTrackingMode = kFlutterMouseTrackingModeInKeyWindow;
controller->_textInputPlugin = [[FlutterTextInputPlugin alloc] initWithViewController:controller];
[controller initializeKeyboard];
[controller notifySemanticsEnabledChanged];
// 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 {
@@ -416,7 +369,7 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
}
- (BOOL)isDispatchingKeyEvent:(NSEvent*)event {
return [_keyboardManager isDispatchingKeyEvent:event];
return [_engine.keyboardManager isDispatchingKeyEvent:event];
}
- (void)loadView {
@@ -463,8 +416,6 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
if ([self attached]) {
[_engine removeViewController:self];
}
CFNotificationCenterRef cfCenter = CFNotificationCenterGetDistributedCenter();
CFNotificationCenterRemoveEveryObserver(cfCenter, (__bridge void*)self);
}
#pragma mark - Public methods
@@ -488,7 +439,6 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
}
- (void)onPreEngineRestart {
[self initializeKeyboard];
}
- (void)notifySemanticsEnabledChanged {
@@ -637,12 +587,6 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
}
}
- (void)initializeKeyboard {
// TODO(goderbauer): Seperate keyboard/textinput stuff into ViewController specific and Engine
// global parts. Move the global parts to FlutterEngine.
_keyboardManager = [[FlutterKeyboardManager alloc] initWithViewDelegate:self];
}
- (void)dispatchMouseEvent:(nonnull NSEvent*)event {
FlutterPointerPhase phase = _mouseState.buttons == 0
? (_mouseState.flutter_state_is_down ? kUp : kHover)
@@ -808,7 +752,7 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
}
}
[_keyboardManager syncModifiersIfNeeded:event.modifierFlags timestamp:event.timestamp];
[_engine.keyboardManager syncModifiersIfNeeded:event.modifierFlags timestamp:event.timestamp];
[_engine sendPointerEvent:flutterEvent];
// Update tracking of state as reported to Flutter.
@@ -851,13 +795,6 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
viewIdentifier:_viewIdentifier];
}
- (void)onKeyboardLayoutChanged {
_keyboardLayoutData = nil;
if (_keyboardLayoutNotifier != nil) {
_keyboardLayoutNotifier();
}
}
- (NSString*)lookupKeyForAsset:(NSString*)asset {
return [FlutterDartProject lookupKeyForAsset:asset];
}
@@ -896,80 +833,10 @@ static void CommonInit(FlutterViewController* controller, FlutterEngine* engine)
#pragma mark - FlutterKeyboardViewDelegate
/**
* 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.
*/
static NSData* CurrentKeyboardLayoutData() {
fml::CFRef<TISInputSourceRef> source(TISCopyCurrentKeyboardInputSource());
CFTypeRef layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
if (layout_data == nil) {
// 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.Reset(TISCopyCurrentKeyboardLayoutInputSource());
layout_data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
}
return (__bridge NSData*)layout_data;
}
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(nullable FlutterKeyEventCallback)callback
userData:(nullable void*)userData {
[_engine sendKeyEvent:event callback:callback userData:userData];
}
- (id<FlutterBinaryMessenger>)getBinaryMessenger {
return _engine.binaryMessenger;
}
- (BOOL)onTextInputKeyEvent:(nonnull NSEvent*)event {
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};
}
- (nonnull NSDictionary*)getPressedState {
return [_keyboardManager getPressedState];
}
#pragma mark - NSResponder
- (BOOL)acceptsFirstResponder {
@@ -977,15 +844,15 @@ static NSData* CurrentKeyboardLayoutData() {
}
- (void)keyDown:(NSEvent*)event {
[_keyboardManager handleEvent:event];
[_engine.keyboardManager handleEvent:event withContext:self];
}
- (void)keyUp:(NSEvent*)event {
[_keyboardManager handleEvent:event];
[_engine.keyboardManager handleEvent:event withContext:self];
}
- (void)flagsChanged:(NSEvent*)event {
[_keyboardManager handleEvent:event];
[_engine.keyboardManager handleEvent:event withContext:self];
}
- (void)mouseEntered:(NSEvent*)event {

View File

@@ -343,6 +343,10 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andReturn(keyboardManager);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent
callback:nil
userData:nil])
@@ -388,6 +392,10 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
called = true;
last_event = *event;
}));
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andReturn(keyboardManager);
FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock
nibName:@""
bundle:nil];
@@ -475,6 +483,9 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andReturn(keyboardManager);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent
callback:nil
userData:nil])
@@ -549,6 +560,9 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andReturn(keyboardManager);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent
callback:nil
userData:nil])
@@ -602,6 +616,9 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
OCMStub( // NOLINT(google-objc-avoid-throwing-exception)
[engineMock binaryMessenger])
.andReturn(binaryMessengerMock);
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andReturn(keyboardManager);
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent
callback:nil
userData:nil])
@@ -659,6 +676,13 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
.andReturn(binaryMessengerMock);
__block bool called = false;
__block FlutterKeyEvent last_event;
__block FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andDo(^(NSInvocation* invocation) {
[invocation setReturnValue:&keyboardManager];
});
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent
callback:nil
userData:nil])
@@ -695,7 +719,7 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown);
EXPECT_EQ(last_event.physical, kPhysicalKeyA);
[viewController onPreEngineRestart];
keyboardManager = [[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
called = false;
[viewController keyDown:keyADown];
@@ -1139,6 +1163,10 @@ static void SwizzledNoop(id self, SEL _cmd) {}
FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock];
OCMStub([engineMock renderer]).andReturn(renderer_);
FlutterKeyboardManager* keyboardManager =
[[FlutterKeyboardManager alloc] initWithDelegate:engineMock];
OCMStub([engineMock keyboardManager]).andReturn(keyboardManager);
// Capture calls to sendKeyEvent
__block NSMutableArray<KeyEventWrapper*>* events = [NSMutableArray array];
OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:kDefaultFlutterKeyEvent

View File

@@ -10,11 +10,10 @@
#include <memory>
#import "flutter/shell/platform/darwin/macos/framework/Source/AccessibilityBridgeMac.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterKeyboardViewDelegate.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
@interface FlutterViewController () <FlutterKeyboardViewDelegate>
@interface FlutterViewController ()
// The FlutterView for this view controller.
@property(nonatomic, readonly, nullable) FlutterView* flutterView;