7 #import <Foundation/Foundation.h>
8 #import <objc/message.h>
14 #include "flutter/common/constants.h"
15 #include "flutter/fml/platform/darwin/string_range_sanitization.h"
25 #pragma mark - TextInput channel method names
36 @"TextInputClient.updateEditingStateWithDeltas";
41 #pragma mark - TextInputConfiguration field names
42 static NSString*
const kViewId =
@"viewId";
77 typedef NS_ENUM(NSUInteger, FlutterTextAffinity) {
78 kFlutterTextAffinityUpstream,
79 kFlutterTextAffinityDownstream
82 #pragma mark - Static functions
90 if (base == nil || extent == nil) {
93 if (base.intValue == -1 && extent.intValue == -1) {
106 const long text_length =
static_cast<long>(length);
107 const long signed_length = std::clamp(
static_cast<long>(range.length), -text_length, text_length);
108 const long base = std::clamp(
static_cast<long>(range.location), 0L, text_length);
115 return hints.count > 0 ? hints[0] : nil;
121 API_AVAILABLE(macos(11.0)) {
126 if ([hint isEqualToString:
@"username"]) {
127 return NSTextContentTypeUsername;
129 if ([hint isEqualToString:
@"password"]) {
130 return NSTextContentTypePassword;
132 if ([hint isEqualToString:
@"oneTimeCode"]) {
133 return NSTextContentTypeOneTimeCode;
138 return NSTextContentTypePassword;
154 if (autofill == nil) {
161 if ([hint isEqualToString:
@"password"] || [hint isEqualToString:
@"username"]) {
185 #pragma mark - NSEvent (KeyEquivalentMarker) protocol
207 objc_setAssociatedObject(
self, &
markerKey, @
true, OBJC_ASSOCIATION_RETAIN);
211 return [objc_getAssociatedObject(self, &markerKey) boolValue] == YES;
216 #pragma mark - FlutterTextInputPlugin private interface
330 - (void)setEditingState:(NSDictionary*)state;
336 - (void)updateEditState;
342 - (void)updateEditStateWithDelta:(const
flutter::TextEditingDelta)delta;
351 - (void)updateTextAndSelection;
357 - (NSString*)textAffinityString;
362 @property(readwrite, nonatomic) NSString* customRunLoopMode;
363 @property(nonatomic) NSTextInputContext* textInputContext;
367 #pragma mark - FlutterTextInputPlugin
374 self = [
super initWithFrame:NSZeroRect];
375 self.clipsToBounds = YES;
377 _delegate = delegate;
388 [_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
389 [unsafeSelf handleMethodCall:call result:result];
391 _textInputContext = [[NSTextInputContext alloc] initWithClient:unsafeSelf];
392 _previouslyPressedFlags = 0;
396 _editableTransform = CATransform3D();
397 _caretRect = CGRectNull;
403 if (!_currentViewController.viewLoaded) {
406 return [_currentViewController.view.window firstResponder] ==
self;
410 [_channel setMethodCallHandler:nil];
413 #pragma mark - Private
415 - (void)resignAndRemoveFromSuperview {
416 if (
self.superview != nil) {
417 [
self.window makeFirstResponder:_currentViewController.flutterView];
418 [
self removeFromSuperview];
424 NSString* method = call.
method;
426 FML_DCHECK(_currentViewController == nil);
429 errorWithCode:
@"error"
430 message:
@"Missing arguments"
431 details:
@"Missing arguments while trying to set a text input client"]);
435 if (clientID != nil) {
436 NSDictionary* config = call.
arguments[1];
438 _clientID = clientID;
439 _inputAction = config[kTextInputAction];
440 _enableDeltaModel = [config[kEnableDeltaModel] boolValue];
441 NSDictionary* inputTypeInfo = config[kTextInputType];
442 _inputType = inputTypeInfo[kTextInputTypeName];
443 _textAffinity = kFlutterTextAffinityUpstream;
445 if (@available(macOS 11.0, *)) {
449 _activeModel = std::make_unique<flutter::TextInputModel>();
451 NSObject* requestViewId = config[kViewId];
452 if ([requestViewId isKindOfClass:[NSNumber
class]]) {
453 viewId = [(NSNumber*)requestViewId longLongValue];
455 _currentViewController = [_delegate viewControllerForIdentifier:viewId];
456 _originalViewController = _currentViewController;
457 while (!_currentViewController.view.window.canBecomeKeyWindow) {
458 NSWindow* parentWindow = [_currentViewController.view.window parentWindow];
459 if (parentWindow == nil) {
462 NSViewController* controller = parentWindow.contentViewController;
469 FML_DCHECK(_currentViewController != nil);
472 FML_DCHECK(_currentViewController != nil);
476 if (_client == nil) {
477 [_currentViewController.view addSubview:self];
479 [
self.window makeFirstResponder:self];
482 [
self resignAndRemoveFromSuperview];
485 FML_DCHECK(_currentViewController != nil);
486 [
self resignAndRemoveFromSuperview];
488 if (_activeModel && _activeModel->composing()) {
489 _activeModel->CommitComposing();
490 _activeModel->EndComposing();
492 [_textInputContext discardMarkedText];
496 _enableDeltaModel = NO;
498 _activeModel =
nullptr;
499 _currentViewController = nil;
500 _originalViewController = nil;
502 FML_DCHECK(_currentViewController != nil);
504 [
self setEditingState:state];
506 FML_DCHECK(_currentViewController != nil);
508 [
self setEditableTransform:state[kTransformKey]];
510 FML_DCHECK(_currentViewController != nil);
512 [
self updateCaretRect:rect];
519 - (void)setEditableTransform:(NSArray*)matrix {
520 CATransform3D* transform = &_editableTransform;
522 transform->m11 = [matrix[0] doubleValue];
523 transform->m12 = [matrix[1] doubleValue];
524 transform->m13 = [matrix[2] doubleValue];
525 transform->m14 = [matrix[3] doubleValue];
527 transform->m21 = [matrix[4] doubleValue];
528 transform->m22 = [matrix[5] doubleValue];
529 transform->m23 = [matrix[6] doubleValue];
530 transform->m24 = [matrix[7] doubleValue];
532 transform->m31 = [matrix[8] doubleValue];
533 transform->m32 = [matrix[9] doubleValue];
534 transform->m33 = [matrix[10] doubleValue];
535 transform->m34 = [matrix[11] doubleValue];
537 transform->m41 = [matrix[12] doubleValue];
538 transform->m42 = [matrix[13] doubleValue];
539 transform->m43 = [matrix[14] doubleValue];
540 transform->m44 = [matrix[15] doubleValue];
543 - (void)updateCaretRect:(NSDictionary*)dictionary {
544 NSAssert(dictionary[
@"x"] != nil && dictionary[
@"y"] != nil && dictionary[
@"width"] != nil &&
545 dictionary[
@"height"] != nil,
546 @"Expected a dictionary representing a CGRect, got %@", dictionary);
547 _caretRect = CGRectMake([dictionary[
@"x"] doubleValue], [dictionary[
@"y"] doubleValue],
548 [dictionary[
@"width"] doubleValue], [dictionary[
@"height"] doubleValue]);
551 - (void)setEditingState:(NSDictionary*)state {
552 if (_activeModel ==
nullptr) {
555 NSString* selectionAffinity = state[kSelectionAffinityKey];
556 if (selectionAffinity != nil) {
557 _textAffinity = [selectionAffinity isEqualToString:kTextAffinityUpstream]
558 ? kFlutterTextAffinityUpstream
559 : kFlutterTextAffinityDownstream;
562 NSString* text = state[kTextKey];
563 if (![text isKindOfClass:[NSString
class]]) {
573 size_t text_length = text.length;
576 _activeModel->selection())
580 _activeModel->composing_range())
583 const bool wasComposing = _activeModel->composing();
584 _activeModel->SetText([text UTF8String], selected_range, composing_range);
585 if (composing_range.
collapsed() && wasComposing) {
586 [_textInputContext discardMarkedText];
588 [_client startEditing];
590 [
self updateTextAndSelection];
594 if (_activeModel ==
nullptr) {
598 NSString*
const textAffinity = [
self textAffinityString];
600 int composingBase = _activeModel->composing() ? _activeModel->composing_range().base() : -1;
601 int composingExtent = _activeModel->composing() ? _activeModel->composing_range().extent() : -1;
610 kTextKey : [NSString stringWithUTF8String:_activeModel->GetText().c_str()] ?: [NSNull null],
614 - (void)updateEditState {
615 if (_activeModel ==
nullptr) {
619 NSDictionary* state = [
self editingState];
620 [_channel invokeMethod:kUpdateEditStateResponseMethod arguments:@[ _clientID, state ]];
621 [
self updateTextAndSelection];
624 - (void)updateEditStateWithDelta:(const
flutter::TextEditingDelta)delta {
625 NSUInteger selectionBase = _activeModel->selection().base();
626 NSUInteger selectionExtent = _activeModel->selection().extent();
627 int composingBase = _activeModel->composing() ? _activeModel->composing_range().base() : -1;
628 int composingExtent = _activeModel->composing() ? _activeModel->composing_range().extent() : -1;
630 NSString*
const textAffinity = [
self textAffinityString];
632 NSDictionary* deltaToFramework = @{
633 @"oldText" : @(delta.old_text().c_str()),
634 @"deltaText" : @(delta.delta_text().c_str()),
635 @"deltaStart" : @(delta.delta_start()),
636 @"deltaEnd" : @(delta.delta_end()),
637 @"selectionBase" : @(selectionBase),
638 @"selectionExtent" : @(selectionExtent),
639 @"selectionAffinity" : textAffinity,
640 @"selectionIsDirectional" : @(
false),
641 @"composingBase" : @(composingBase),
642 @"composingExtent" : @(composingExtent),
645 NSDictionary* deltas = @{
646 @"deltas" : @[ deltaToFramework ],
649 [_channel invokeMethod:kUpdateEditStateWithDeltasResponseMethod arguments:@[ _clientID, deltas ]];
650 [
self updateTextAndSelection];
653 - (void)updateTextAndSelection {
654 NSAssert(_activeModel !=
nullptr,
@"Flutter text model must not be null.");
655 NSString* text = @(_activeModel->GetText().data());
656 int start = _activeModel->selection().base();
657 int extend = _activeModel->selection().extent();
658 NSRange selection = NSMakeRange(MIN(start, extend), ABS(start - extend));
664 [_client updateString:text withSelection:selection];
667 [
self setSelectedRange:selection];
671 - (NSString*)textAffinityString {
676 - (BOOL)handleKeyEvent:(NSEvent*)event {
677 if (event.type == NSEventTypeKeyUp ||
678 (event.type == NSEventTypeFlagsChanged && event.modifierFlags < _previouslyPressedFlags)) {
681 _previouslyPressedFlags =
event.modifierFlags;
686 _eventProducedOutput = NO;
687 BOOL res = [_textInputContext handleEvent:event];
697 bool is_navigation =
event.modifierFlags & NSEventModifierFlagFunction &&
698 event.modifierFlags & NSEventModifierFlagNumericPad;
699 bool is_navigation_in_ime = is_navigation &&
self.hasMarkedText;
701 if (event.isKeyEquivalent && !is_navigation_in_ime && !_eventProducedOutput) {
708 #pragma mark NSResponder
710 - (void)keyDown:(NSEvent*)event {
711 [_currentViewController keyDown:event];
714 - (void)keyUp:(NSEvent*)event {
715 [_currentViewController keyUp:event];
718 - (BOOL)performKeyEquivalent:(NSEvent*)event {
719 if ([_currentViewController isDispatchingKeyEvent:event]) {
731 [event markAsKeyEquivalent];
732 [_currentViewController keyDown:event];
736 - (void)flagsChanged:(NSEvent*)event {
737 [_currentViewController flagsChanged:event];
740 - (void)mouseDown:(NSEvent*)event {
741 [_currentViewController mouseDown:event];
744 - (void)mouseUp:(NSEvent*)event {
745 [_currentViewController mouseUp:event];
748 - (void)mouseDragged:(NSEvent*)event {
749 [_currentViewController mouseDragged:event];
752 - (void)rightMouseDown:(NSEvent*)event {
753 [_currentViewController rightMouseDown:event];
756 - (void)rightMouseUp:(NSEvent*)event {
757 [_currentViewController rightMouseUp:event];
760 - (void)rightMouseDragged:(NSEvent*)event {
761 [_currentViewController rightMouseDragged:event];
764 - (void)otherMouseDown:(NSEvent*)event {
765 [_currentViewController otherMouseDown:event];
768 - (void)otherMouseUp:(NSEvent*)event {
769 [_currentViewController otherMouseUp:event];
772 - (void)otherMouseDragged:(NSEvent*)event {
773 [_currentViewController otherMouseDragged:event];
776 - (void)mouseMoved:(NSEvent*)event {
777 [_currentViewController mouseMoved:event];
780 - (void)scrollWheel:(NSEvent*)event {
781 [_currentViewController scrollWheel:event];
784 - (NSTextInputContext*)inputContext {
785 return _textInputContext;
789 #pragma mark NSTextInputClient
791 - (void)insertTab:(
id)sender {
796 - (void)insertText:(
id)string replacementRange:(NSRange)range {
797 if (_activeModel ==
nullptr) {
801 _eventProducedOutput |=
true;
803 if (range.location != NSNotFound) {
804 _activeModel->SetSelection(
ClampNSRange(range, _activeModel->text_range().end()));
805 }
else if (_activeModel->composing() &&
806 !(_activeModel->composing_range() == _activeModel->selection())) {
823 std::string textBeforeChange = _activeModel->GetText().c_str();
825 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
826 const NSString* rawString = isAttributedString ? [string string] : string;
827 std::string utf8String = rawString ? [rawString UTF8String] :
"";
828 _activeModel->AddText(utf8String);
829 if (_activeModel->composing()) {
830 replacedRange = composingBeforeChange;
831 _activeModel->CommitComposing();
832 _activeModel->EndComposing();
834 replacedRange = range.location == NSNotFound
836 :
flutter::TextRange(range.location, range.location + range.length);
838 if (_enableDeltaModel) {
839 [
self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange, replacedRange,
842 [
self updateEditState];
846 - (void)doCommandBySelector:(
SEL)selector {
847 _eventProducedOutput |= selector != NSSelectorFromString(
@"noop:");
848 if ([
self respondsToSelector:selector]) {
852 IMP imp = [
self methodForSelector:selector];
853 void (*func)(id, SEL, id) =
reinterpret_cast<void (*)(
id,
SEL,
id)
>(imp);
854 func(
self, selector, nil);
856 if (_clientID == nil) {
861 if (selector ==
@selector(insertNewline:)) {
868 NSString* name = NSStringFromSelector(selector);
869 if (_pendingSelectors == nil) {
870 _pendingSelectors = [NSMutableArray array];
872 [_pendingSelectors addObject:name];
874 if (_pendingSelectors.count == 1) {
875 __weak NSMutableArray* selectors = _pendingSelectors;
877 __weak NSNumber* clientID = _clientID;
879 CFStringRef runLoopMode =
self.customRunLoopMode != nil
881 : kCFRunLoopCommonModes;
883 CFRunLoopPerformBlock(CFRunLoopGetMain(), runLoopMode, ^{
884 if (selectors.count > 0) {
885 [channel invokeMethod:kPerformSelectors arguments:@[ clientID, selectors ]];
886 [selectors removeAllObjects];
892 - (void)insertNewline:(
id)sender {
893 if (_activeModel ==
nullptr) {
896 if (_activeModel->composing()) {
897 _activeModel->CommitComposing();
898 _activeModel->EndComposing();
902 [
self insertText:@"\n" replacementRange:self.selectedRange];
904 [_channel invokeMethod:kPerformAction arguments:@[ _clientID, _inputAction ]];
907 - (void)setMarkedText:(
id)string
908 selectedRange:(NSRange)selectedRange
909 replacementRange:(NSRange)replacementRange {
910 if (_activeModel ==
nullptr) {
913 std::string textBeforeChange = _activeModel->GetText().c_str();
914 if (!_activeModel->composing()) {
915 _activeModel->BeginComposing();
918 if (replacementRange.location != NSNotFound) {
927 _activeModel->SetComposingRange(
928 ClampNSRange(replacementRange, _activeModel->text_range().end()), 0);
935 BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]];
936 const NSString* rawString = isAttributedString ? [string string] : string;
940 std::u16string marked_text_utf16(rawString.length, u
'\0');
941 [rawString getCharacters:reinterpret_cast<unichar*>(marked_text_utf16.data())
942 range:NSMakeRange(0, marked_text_utf16.length())];
946 _activeModel->UpdateComposingText(marked_text_utf16,
947 ClampNSRange(selectedRange, marked_text_utf16.length()));
949 if (_enableDeltaModel) {
950 std::string marked_text = rawString ? [rawString UTF8String] :
"";
951 [
self updateEditStateWithDelta:flutter::TextEditingDelta(textBeforeChange,
952 selectionBeforeChange.collapsed()
953 ? composingBeforeChange
954 : selectionBeforeChange,
957 [
self updateEditState];
962 if (_activeModel ==
nullptr) {
965 _activeModel->CommitComposing();
966 _activeModel->EndComposing();
967 if (_enableDeltaModel) {
968 [
self updateEditStateWithDelta:flutter::TextEditingDelta(_activeModel->GetText().c_str())];
970 [
self updateEditState];
974 - (NSRange)markedRange {
975 if (_activeModel ==
nullptr) {
976 return NSMakeRange(NSNotFound, 0);
979 _activeModel->composing_range().base(),
980 _activeModel->composing_range().extent() - _activeModel->composing_range().base());
983 - (BOOL)hasMarkedText {
984 return _activeModel !=
nullptr && _activeModel->composing_range().length() > 0;
987 - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
988 actualRange:(NSRangePointer)actualRange {
989 if (_activeModel ==
nullptr) {
992 NSString* text = [NSString stringWithUTF8String:_activeModel->GetText().c_str()];
993 if (range.location >= text.length) {
996 range.length = std::min(range.length, text.length - range.location);
997 if (actualRange != nil) {
998 *actualRange = range;
1000 NSString* substring = [text substringWithRange:range];
1001 return [[NSAttributedString alloc] initWithString:substring attributes:nil];
1004 - (NSArray<NSString*>*)validAttributesForMarkedText {
1010 - (CGRect)screenRectFromFrameworkTransform:(CGRect)incomingRect {
1011 CGPoint points[] = {
1012 incomingRect.origin,
1013 CGPointMake(incomingRect.origin.x, incomingRect.origin.y + incomingRect.size.height),
1014 CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y),
1015 CGPointMake(incomingRect.origin.x + incomingRect.size.width,
1016 incomingRect.origin.y + incomingRect.size.height)};
1018 CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX);
1019 CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX);
1021 for (
int i = 0; i < 4; i++) {
1022 const CGPoint point = points[i];
1024 CGFloat x = _editableTransform.m11 * point.x + _editableTransform.m21 * point.y +
1025 _editableTransform.m41;
1026 CGFloat y = _editableTransform.m12 * point.x + _editableTransform.m22 * point.y +
1027 _editableTransform.m42;
1029 const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y +
1030 _editableTransform.m44;
1034 }
else if (w != 1.0) {
1039 origin.x = MIN(origin.x, x);
1040 origin.y = MIN(origin.y, y);
1041 farthest.x = MAX(farthest.x, x);
1042 farthest.y = MAX(farthest.y, y);
1045 const NSView* fromView = _originalViewController.flutterView;
1046 const CGRect rectInWindow = [fromView
1047 convertRect:CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y)
1049 NSWindow* window = fromView.window;
1050 return window ? [window convertRectToScreen:rectInWindow] : rectInWindow;
1053 - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange {
1056 return !_originalViewController.viewLoaded || CGRectEqualToRect(_caretRect, CGRectNull)
1058 : [
self screenRectFromFrameworkTransform:_caretRect];
1061 - (NSUInteger)characterIndexForPoint:(NSPoint)point {
void(^ FlutterResult)(id _Nullable result)
FLUTTER_DARWIN_EXPORT NSObject const * FlutterMethodNotImplemented
typedef NS_ENUM(NSUInteger, FlutterTextAffinity)
static NSString *const kViewId
static NSString *const kUpdateEditStateWithDeltasResponseMethod
static NSString *const kTextKey
static NSString *const kMultilineInputType
static NSString *const kAutofillHints
static NSString *const kAutofillEditingValue
static NSString *const kSecureTextEntry
static NSString *const kShowMethod
static NSString *const kPerformSelectors
static NSString *const kSetEditableSizeAndTransform
static NSTextContentType GetTextContentType(NSDictionary *configuration) API_AVAILABLE(macos(11.0))
static NSString *const kSelectionBaseKey
static NSString *const kSelectionAffinityKey
static NSString *const kAssociatedAutofillFields
static flutter::TextRange ClampNSRange(NSRange range, size_t length)
static NSString *const kSetEditingStateMethod
static NSString *const kComposingExtentKey
static NSString *const kAutofillId
static NSString *const kSelectionExtentKey
static NSString *const kClearClientMethod
static NSString *const kEnableDeltaModel
static NSString *const kPerformAction
static NSString * GetAutofillHint(NSDictionary *autofill)
static NSString *const kInputActionNewline
static NSString *const kTextInputChannel
static NSString *const kTextAffinityDownstream
static NSString *const kTextInputType
static NSString *const kSetClientMethod
static NSString *const kTextAffinityUpstream
static NSString *const kTransformKey
static NSString *const kAutofillProperties
static NSString *const kUpdateEditStateResponseMethod
static BOOL EnableAutocompleteForTextInputConfiguration(NSDictionary *configuration)
static BOOL EnableAutocomplete(NSDictionary *configuration)
static NSString *const kSetCaretRect
static NSString *const kTextInputAction
static flutter::TextRange RangeFromBaseExtent(NSNumber *base, NSNumber *extent, const flutter::TextRange &range)
static NSString *const kComposingBaseKey
static NSString *const kHideMethod
static NSString *const kTextInputTypeName
static NSString *const kSelectionIsDirectionalKey
int64_t FlutterViewIdentifier
uint64_t _previouslyPressedFlags
NSTextInputContext * _textInputContext
CATransform3D _editableTransform
std::unique_ptr< flutter::TextInputModel > _activeModel
NSMutableArray * _pendingSelectors
FlutterTextAffinity _textAffinity
__weak FlutterViewController * _originalViewController
__weak FlutterViewController * _currentViewController
FlutterMethodChannel * _channel
__weak id< FlutterTextInputPluginDelegate > _delegate
BOOL _eventProducedOutput
NSString * customRunLoopMode
NSDictionary * editingState()
void markAsKeyEquivalent()
TextRange ClampedTo(size_t length) const
instancetype methodChannelWithName:binaryMessenger:codec:(NSString *name,[binaryMessenger] NSObject< FlutterBinaryMessenger > *messenger,[codec] NSObject< FlutterMethodCodec > *codec)