8 #import <Foundation/Foundation.h>
9 #import <UIKit/UIKit.h>
11 #include "unicode/uchar.h"
13 #include "flutter/fml/logging.h"
14 #include "flutter/fml/platform/darwin/string_range_sanitization.h"
15 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
39 #pragma mark - TextInput channel method names.
48 @"TextInput.setEditableSizeAndTransform";
59 @"TextInput.onPointerMoveForInteractiveKeyboard";
61 @"TextInput.onPointerUpForInteractiveKeyboard";
63 #pragma mark - TextInputConfiguration Field Names
85 #pragma mark - Static Functions
88 static BOOL
IsEmoji(NSString* text, NSRange charRange) {
90 BOOL gotCodePoint = [text getBytes:&codePoint
91 maxLength:
sizeof(codePoint)
93 encoding:NSUTF32StringEncoding
97 return gotCodePoint && u_hasBinaryProperty(codePoint, UCHAR_EMOJI);
105 NSString* inputType = type[
@"name"];
106 return ![inputType isEqualToString:
@"TextInputType.none"];
109 NSString* inputType = type[
@"name"];
110 if ([inputType isEqualToString:
@"TextInputType.address"]) {
111 return UIKeyboardTypeDefault;
113 if ([inputType isEqualToString:
@"TextInputType.datetime"]) {
114 return UIKeyboardTypeNumbersAndPunctuation;
116 if ([inputType isEqualToString:
@"TextInputType.emailAddress"]) {
117 return UIKeyboardTypeEmailAddress;
119 if ([inputType isEqualToString:
@"TextInputType.multiline"]) {
120 return UIKeyboardTypeDefault;
122 if ([inputType isEqualToString:
@"TextInputType.name"]) {
123 return UIKeyboardTypeNamePhonePad;
125 if ([inputType isEqualToString:
@"TextInputType.number"]) {
126 if ([type[
@"signed"] boolValue]) {
127 return UIKeyboardTypeNumbersAndPunctuation;
129 if ([type[
@"decimal"] boolValue]) {
130 return UIKeyboardTypeDecimalPad;
132 return UIKeyboardTypeNumberPad;
134 if ([inputType isEqualToString:
@"TextInputType.phone"]) {
135 return UIKeyboardTypePhonePad;
137 if ([inputType isEqualToString:
@"TextInputType.text"]) {
138 return UIKeyboardTypeDefault;
140 if ([inputType isEqualToString:
@"TextInputType.url"]) {
141 return UIKeyboardTypeURL;
143 if ([inputType isEqualToString:
@"TextInputType.visiblePassword"]) {
144 return UIKeyboardTypeASCIICapable;
146 if ([inputType isEqualToString:
@"TextInputType.webSearch"]) {
147 return UIKeyboardTypeWebSearch;
149 if ([inputType isEqualToString:
@"TextInputType.twitter"]) {
150 return UIKeyboardTypeTwitter;
152 return UIKeyboardTypeDefault;
156 NSString* textCapitalization = type[
@"textCapitalization"];
157 if ([textCapitalization isEqualToString:
@"TextCapitalization.characters"]) {
158 return UITextAutocapitalizationTypeAllCharacters;
159 }
else if ([textCapitalization isEqualToString:
@"TextCapitalization.sentences"]) {
160 return UITextAutocapitalizationTypeSentences;
161 }
else if ([textCapitalization isEqualToString:
@"TextCapitalization.words"]) {
162 return UITextAutocapitalizationTypeWords;
164 return UITextAutocapitalizationTypeNone;
172 if ([inputType isEqualToString:
@"TextInputAction.unspecified"]) {
173 return UIReturnKeyDefault;
176 if ([inputType isEqualToString:
@"TextInputAction.done"]) {
177 return UIReturnKeyDone;
180 if ([inputType isEqualToString:
@"TextInputAction.go"]) {
181 return UIReturnKeyGo;
184 if ([inputType isEqualToString:
@"TextInputAction.send"]) {
185 return UIReturnKeySend;
188 if ([inputType isEqualToString:
@"TextInputAction.search"]) {
189 return UIReturnKeySearch;
192 if ([inputType isEqualToString:
@"TextInputAction.next"]) {
193 return UIReturnKeyNext;
196 if ([inputType isEqualToString:
@"TextInputAction.continueAction"]) {
197 return UIReturnKeyContinue;
200 if ([inputType isEqualToString:
@"TextInputAction.join"]) {
201 return UIReturnKeyJoin;
204 if ([inputType isEqualToString:
@"TextInputAction.route"]) {
205 return UIReturnKeyRoute;
208 if ([inputType isEqualToString:
@"TextInputAction.emergencyCall"]) {
209 return UIReturnKeyEmergencyCall;
212 if ([inputType isEqualToString:
@"TextInputAction.newline"]) {
213 return UIReturnKeyDefault;
217 return UIReturnKeyDefault;
221 if (!hints || hints.count == 0) {
226 NSString* hint = hints[0];
227 if ([hint isEqualToString:
@"addressCityAndState"]) {
228 return UITextContentTypeAddressCityAndState;
231 if ([hint isEqualToString:
@"addressState"]) {
232 return UITextContentTypeAddressState;
235 if ([hint isEqualToString:
@"addressCity"]) {
236 return UITextContentTypeAddressCity;
239 if ([hint isEqualToString:
@"sublocality"]) {
240 return UITextContentTypeSublocality;
243 if ([hint isEqualToString:
@"streetAddressLine1"]) {
244 return UITextContentTypeStreetAddressLine1;
247 if ([hint isEqualToString:
@"streetAddressLine2"]) {
248 return UITextContentTypeStreetAddressLine2;
251 if ([hint isEqualToString:
@"countryName"]) {
252 return UITextContentTypeCountryName;
255 if ([hint isEqualToString:
@"fullStreetAddress"]) {
256 return UITextContentTypeFullStreetAddress;
259 if ([hint isEqualToString:
@"postalCode"]) {
260 return UITextContentTypePostalCode;
263 if ([hint isEqualToString:
@"location"]) {
264 return UITextContentTypeLocation;
267 if ([hint isEqualToString:
@"creditCardNumber"]) {
268 return UITextContentTypeCreditCardNumber;
271 if ([hint isEqualToString:
@"email"]) {
272 return UITextContentTypeEmailAddress;
275 if ([hint isEqualToString:
@"jobTitle"]) {
276 return UITextContentTypeJobTitle;
279 if ([hint isEqualToString:
@"givenName"]) {
280 return UITextContentTypeGivenName;
283 if ([hint isEqualToString:
@"middleName"]) {
284 return UITextContentTypeMiddleName;
287 if ([hint isEqualToString:
@"familyName"]) {
288 return UITextContentTypeFamilyName;
291 if ([hint isEqualToString:
@"name"]) {
292 return UITextContentTypeName;
295 if ([hint isEqualToString:
@"namePrefix"]) {
296 return UITextContentTypeNamePrefix;
299 if ([hint isEqualToString:
@"nameSuffix"]) {
300 return UITextContentTypeNameSuffix;
303 if ([hint isEqualToString:
@"nickname"]) {
304 return UITextContentTypeNickname;
307 if ([hint isEqualToString:
@"organizationName"]) {
308 return UITextContentTypeOrganizationName;
311 if ([hint isEqualToString:
@"telephoneNumber"]) {
312 return UITextContentTypeTelephoneNumber;
315 if ([hint isEqualToString:
@"password"]) {
316 return UITextContentTypePassword;
319 if ([hint isEqualToString:
@"oneTimeCode"]) {
320 return UITextContentTypeOneTimeCode;
323 if ([hint isEqualToString:
@"newPassword"]) {
324 return UITextContentTypeNewPassword;
392 typedef NS_ENUM(NSInteger, FlutterAutofillType) {
396 kFlutterAutofillTypeNone,
397 kFlutterAutofillTypeRegular,
398 kFlutterAutofillTypePassword,
408 if (isSecureTextEntry) {
415 if ([contentType isEqualToString:UITextContentTypePassword] ||
416 [contentType isEqualToString:UITextContentTypeUsername]) {
420 if ([contentType isEqualToString:UITextContentTypeNewPassword]) {
430 return kFlutterAutofillTypePassword;
435 return kFlutterAutofillTypePassword;
440 return !autofill || [contentType isEqualToString:
@""] ? kFlutterAutofillTypeNone
441 : kFlutterAutofillTypeRegular;
445 return fabsf(x - y) <= delta;
471 CGRect selectionRect,
472 BOOL selectionRectIsRTL,
473 BOOL useTrailingBoundaryOfSelectionRect,
474 CGRect otherSelectionRect,
475 BOOL otherSelectionRectIsRTL,
476 CGFloat verticalPrecision) {
478 if (CGRectContainsPoint(
480 selectionRect.origin.x + ((useTrailingBoundaryOfSelectionRect ^ selectionRectIsRTL)
481 ? 0.5 * selectionRect.size.width
483 selectionRect.origin.y, 0.5 * selectionRect.size.width, selectionRect.size.height),
488 CGPoint pointForSelectionRect = CGPointMake(
489 selectionRect.origin.x +
490 (selectionRectIsRTL ^ useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0),
491 selectionRect.origin.y + selectionRect.size.height * 0.5);
492 float yDist = fabs(pointForSelectionRect.y - point.y);
493 float xDist = fabs(pointForSelectionRect.x - point.x);
496 CGPoint pointForOtherSelectionRect = CGPointMake(
497 otherSelectionRect.origin.x + (otherSelectionRectIsRTL ? otherSelectionRect.size.width : 0),
498 otherSelectionRect.origin.y + otherSelectionRect.size.height * 0.5);
499 float yDistOther = fabs(pointForOtherSelectionRect.y - point.y);
500 float xDistOther = fabs(pointForOtherSelectionRect.x - point.x);
505 BOOL isCloserVertically = yDist < yDistOther - verticalPrecision;
507 BOOL isAboveBottomOfLine = point.y <= selectionRect.origin.y + selectionRect.size.height;
508 BOOL isCloserHorizontally = xDist < xDistOther;
509 BOOL isBelowBottomOfLine = point.y > selectionRect.origin.y + selectionRect.size.height;
512 if (selectionRectIsRTL) {
513 isFarther = selectionRect.origin.x < otherSelectionRect.origin.x;
515 isFarther = selectionRect.origin.x +
516 (useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0) >
517 otherSelectionRect.origin.x;
519 return (isCloserVertically ||
520 (isEqualVertically &&
521 ((isAboveBottomOfLine && isCloserHorizontally) || (isBelowBottomOfLine && isFarther))));
524 #pragma mark - FlutterTextPosition
528 + (instancetype)positionWithIndex:(NSUInteger)index {
529 return [[
FlutterTextPosition alloc] initWithIndex:index affinity:UITextStorageDirectionForward];
532 + (instancetype)positionWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity {
536 - (instancetype)initWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity {
547 #pragma mark - FlutterTextRange
551 + (instancetype)rangeWithNSRange:(NSRange)range {
555 - (instancetype)initWithNSRange:(NSRange)range {
563 - (UITextPosition*)start {
565 affinity:UITextStorageDirectionForward];
568 - (UITextPosition*)end {
570 affinity:UITextStorageDirectionBackward];
574 return self.range.length == 0;
577 - (id)copyWithZone:(NSZone*)zone {
582 return NSEqualRanges(
self.
range, other.
range);
586 #pragma mark - FlutterTokenizer
596 - (instancetype)initWithTextInput:(UIResponder<UITextInput>*)textInput {
598 @"The FlutterTokenizer can only be used in a FlutterTextInputView");
599 self = [
super initWithTextInput:textInput];
606 - (UITextRange*)rangeEnclosingPosition:(UITextPosition*)position
607 withGranularity:(UITextGranularity)granularity
608 inDirection:(UITextDirection)direction {
610 switch (granularity) {
611 case UITextGranularityLine:
614 result = [
self lineEnclosingPosition:position inDirection:direction];
616 case UITextGranularityCharacter:
617 case UITextGranularityWord:
618 case UITextGranularitySentence:
619 case UITextGranularityParagraph:
620 case UITextGranularityDocument:
622 result = [
super rangeEnclosingPosition:position
623 withGranularity:granularity
624 inDirection:direction];
630 - (UITextRange*)lineEnclosingPosition:(UITextPosition*)position
631 inDirection:(UITextDirection)direction {
633 if (@available(iOS 17.0, *)) {
638 if (flutterPosition.
index > _textInputView.text.length ||
639 (flutterPosition.
index == _textInputView.text.length &&
640 direction == UITextStorageDirectionForward)) {
646 NSString* textAfter = [_textInputView
647 textInRange:[_textInputView textRangeFromPosition:position
648 toPosition:[_textInputView endOfDocument]]];
649 NSArray<NSString*>* linesAfter = [textAfter componentsSeparatedByString:@"\n"];
650 NSInteger offSetToLineBreak = [linesAfter firstObject].length;
651 UITextPosition* lineBreakAfter = [_textInputView positionFromPosition:position
652 offset:offSetToLineBreak];
654 NSString* textBefore = [_textInputView
655 textInRange:[_textInputView textRangeFromPosition:[_textInputView beginningOfDocument]
656 toPosition:position]];
657 NSArray<NSString*>* linesBefore = [textBefore componentsSeparatedByString:@"\n"];
658 NSInteger offSetFromLineBreak = [linesBefore lastObject].length;
659 UITextPosition* lineBreakBefore = [_textInputView positionFromPosition:position
660 offset:-offSetFromLineBreak];
662 return [_textInputView textRangeFromPosition:lineBreakBefore toPosition:lineBreakAfter];
667 #pragma mark - FlutterTextSelectionRect
672 @synthesize rect = _rect;
678 + (instancetype)selectionRectWithRectAndInfo:(CGRect)rect
679 position:(NSUInteger)position
680 writingDirection:(NSWritingDirection)writingDirection
681 containsStart:(BOOL)containsStart
682 containsEnd:(BOOL)containsEnd
683 isVertical:(BOOL)isVertical {
686 writingDirection:writingDirection
687 containsStart:containsStart
688 containsEnd:containsEnd
689 isVertical:isVertical];
692 + (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position {
695 writingDirection:NSWritingDirectionNatural
701 + (instancetype)selectionRectWithRect:(CGRect)rect
702 position:(NSUInteger)position
703 writingDirection:(NSWritingDirection)writingDirection {
706 writingDirection:writingDirection
712 - (instancetype)initWithRectAndInfo:(CGRect)rect
713 position:(NSUInteger)position
714 writingDirection:(NSWritingDirection)writingDirection
715 containsStart:(BOOL)containsStart
716 containsEnd:(BOOL)containsEnd
717 isVertical:(BOOL)isVertical {
731 return _writingDirection == NSWritingDirectionRightToLeft;
736 #pragma mark - FlutterTextPlaceholder
740 - (NSArray<UITextSelectionRect*>*)rects {
756 @property(nonatomic, retain, readonly) UITextField*
textField;
760 UITextField* _textField;
765 _textField = [[UITextField alloc] init];
770 - (BOOL)isKindOfClass:(Class)aClass {
771 return [
super isKindOfClass:aClass] || (aClass == [UITextField class]);
774 - (NSMethodSignature*)methodSignatureForSelector:(
SEL)aSelector {
775 NSMethodSignature* signature = [
super methodSignatureForSelector:aSelector];
777 signature = [
self.textField methodSignatureForSelector:aSelector];
782 - (void)forwardInvocation:(NSInvocation*)anInvocation {
783 [anInvocation invokeWithTarget:self.textField];
789 @property(nonatomic, readonly, weak) id<FlutterTextInputDelegate> textInputDelegate;
790 @property(nonatomic, readonly) UIView* hostView;
795 @property(nonatomic, copy) NSString* autofillId;
796 @property(nonatomic, readonly) CATransform3D editableTransform;
797 @property(nonatomic, assign) CGRect markedRect;
799 @property(nonatomic, assign) BOOL preventCursorDismissWhenResignFirstResponder;
800 @property(nonatomic) BOOL isVisibleToAutofill;
801 @property(nonatomic, assign) BOOL accessibilityEnabled;
802 @property(nonatomic, assign)
int textInputClient;
806 @property(nonatomic, copy) NSString* temporarilyDeletedComposedCharacter;
807 @property(nonatomic, assign) CGRect editMenuTargetRect;
808 @property(nonatomic, strong) NSArray<NSDictionary*>* editMenuItems;
810 - (void)setEditableTransform:(NSArray*)matrix;
811 - (BOOL)becomeFirstResponderFromFramework;
812 - (BOOL)resignFirstResponderFromFramework;
816 int _textInputClient;
839 @synthesize tokenizer = _tokenizer;
842 self = [
super initWithFrame:CGRectZero];
845 _textInputClient = 0;
847 _preventCursorDismissWhenResignFirstResponder = NO;
850 _text = [[NSMutableString alloc] init];
855 _pendingDeltas = [[NSMutableArray alloc] init];
858 _editableTransform = CATransform3D();
861 _autocapitalizationType = UITextAutocapitalizationTypeSentences;
862 _autocorrectionType = UITextAutocorrectionTypeDefault;
863 _spellCheckingType = UITextSpellCheckingTypeDefault;
864 _enablesReturnKeyAutomatically = NO;
865 _keyboardAppearance = UIKeyboardAppearanceDefault;
866 _keyboardType = UIKeyboardTypeDefault;
867 _returnKeyType = UIReturnKeyDone;
868 _secureTextEntry = NO;
869 _enableDeltaModel = NO;
871 _accessibilityEnabled = NO;
872 _smartQuotesType = UITextSmartQuotesTypeYes;
873 _smartDashesType = UITextSmartDashesTypeYes;
874 _selectionRects = [[NSArray alloc] init];
875 if (@available(iOS 17.0, *)) {
876 _inlinePredictionType = UITextInlinePredictionTypeNo;
879 if (@available(iOS 14.0, *)) {
880 UIScribbleInteraction* interaction = [[UIScribbleInteraction alloc] initWithDelegate:self];
881 [
self addInteraction:interaction];
885 if (@available(iOS 16.0, *)) {
886 _editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
887 [
self addInteraction:_editMenuInteraction];
893 - (void)handleSearchWebAction {
894 [
self.textInputDelegate flutterTextInputView:self
895 searchWebWithSelectedText:[
self textInRange:_selectedTextRange]];
898 - (void)handleLookUpAction {
899 [
self.textInputDelegate flutterTextInputView:self
900 lookUpSelectedText:[
self textInRange:_selectedTextRange]];
903 - (void)handleShareAction {
904 [
self.textInputDelegate flutterTextInputView:self
905 shareSelectedText:[
self textInRange:_selectedTextRange]];
908 - (void)handleTranslateAction {
909 [
self.textInputDelegate flutterTextInputView:self
910 translateSelectedText:[
self textInRange:_selectedTextRange]];
914 - (UICommand*)searchCommandWithSelector:(
SEL)selector
915 element:(UIMenuElement*)element API_AVAILABLE(ios(16.0)) {
916 if ([element isKindOfClass:UICommand.class]) {
917 UICommand* command = (UICommand*)element;
918 return command.action == selector ? command : nil;
919 }
else if ([element isKindOfClass:UIMenu.class]) {
920 NSArray<UIMenuElement*>* children = ((UIMenu*)element).children;
921 for (UIMenuElement* child in children) {
922 UICommand* result = [
self searchCommandWithSelector:selector element:child];
933 - (void)addBasicEditingCommandToItems:(NSMutableArray*)items
935 selector:(
SEL)selector
936 suggestedMenu:(UIMenu*)suggestedMenu {
937 UICommand* command = [
self searchCommandWithSelector:selector element:suggestedMenu];
939 [items addObject:command];
941 NSString* errorMessage =
942 [NSString stringWithFormat:@"Cannot find context menu item of type \"%@\".", type];
943 [FlutterLogger logError:errorMessage];
947 - (void)addAdditionalBasicCommandToItems:(NSMutableArray*)items
949 selector:(
SEL)selector
950 encodedItem:(NSDictionary<NSString*,
id>*)encodedItem {
951 NSString* title = encodedItem[@"title"];
953 UICommand* command = [UICommand commandWithTitle:title
957 [items addObject:command];
959 NSString* errorMessage =
960 [NSString stringWithFormat:@"Missing title for context menu item of type \"%@\".", type];
961 [FlutterLogger logError:errorMessage];
965 - (UIMenu*)editMenuInteraction:(UIEditMenuInteraction*)interaction
966 menuForConfiguration:(UIEditMenuConfiguration*)configuration
967 suggestedActions:(NSArray<UIMenuElement*>*)suggestedActions API_AVAILABLE(ios(16.0)) {
968 UIMenu* suggestedMenu = [UIMenu menuWithChildren:suggestedActions];
969 if (!_editMenuItems) {
970 return suggestedMenu;
973 NSMutableArray* items = [NSMutableArray array];
974 for (NSDictionary<NSString*, id>* encodedItem in _editMenuItems) {
975 NSString* type = encodedItem[@"type"];
976 if ([type isEqualToString:
@"copy"]) {
977 [
self addBasicEditingCommandToItems:items
979 selector:@selector(copy:)
980 suggestedMenu:suggestedMenu];
981 }
else if ([type isEqualToString:
@"paste"]) {
982 [
self addBasicEditingCommandToItems:items
984 selector:@selector(paste:)
985 suggestedMenu:suggestedMenu];
986 }
else if ([type isEqualToString:
@"cut"]) {
987 [
self addBasicEditingCommandToItems:items
989 selector:@selector(cut:)
990 suggestedMenu:suggestedMenu];
991 }
else if ([type isEqualToString:
@"delete"]) {
992 [
self addBasicEditingCommandToItems:items
994 selector:@selector(delete:)
995 suggestedMenu:suggestedMenu];
996 }
else if ([type isEqualToString:
@"selectAll"]) {
997 [
self addBasicEditingCommandToItems:items
999 selector:@selector(selectAll:)
1000 suggestedMenu:suggestedMenu];
1001 }
else if ([type isEqualToString:
@"searchWeb"]) {
1002 [
self addAdditionalBasicCommandToItems:items
1004 selector:@selector(handleSearchWebAction)
1005 encodedItem:encodedItem];
1006 }
else if ([type isEqualToString:
@"share"]) {
1007 [
self addAdditionalBasicCommandToItems:items
1009 selector:@selector(handleShareAction)
1010 encodedItem:encodedItem];
1011 }
else if ([type isEqualToString:
@"lookUp"]) {
1012 [
self addAdditionalBasicCommandToItems:items
1014 selector:@selector(handleLookUpAction)
1015 encodedItem:encodedItem];
1016 }
else if ([type isEqualToString:
@"captureTextFromCamera"]) {
1017 if (@available(iOS 15.0, *)) {
1018 [
self addBasicEditingCommandToItems:items
1020 selector:@selector(captureTextFromCamera:)
1021 suggestedMenu:suggestedMenu];
1023 }
else if ([type isEqualToString:
@"translate"]) {
1024 if (@available(iOS 17.4, *)) {
1025 [
self addAdditionalBasicCommandToItems:items
1027 selector:@selector(handleTranslateAction)
1028 encodedItem:encodedItem];
1030 }
else if ([type isEqualToString:
@"custom"]) {
1031 NSString* callbackId = encodedItem[@"id"];
1032 NSString* title = encodedItem[@"title"];
1033 if (callbackId && title) {
1035 UIAction* action = [UIAction
1036 actionWithTitle:title
1039 handler:^(__kindof UIAction* _Nonnull action) {
1042 [strongSelf.textInputDelegate flutterTextInputView:strongSelf
1043 performContextMenuCustomActionWithActionID:callbackId
1044 textInputClient:strongSelf->
1048 [items addObject:action];
1052 return [UIMenu menuWithChildren:items];
1055 - (void)editMenuInteraction:(UIEditMenuInteraction*)interaction
1056 willDismissMenuForConfiguration:(UIEditMenuConfiguration*)configuration
1057 animator:(
id<UIEditMenuInteractionAnimating>)animator
1058 API_AVAILABLE(ios(16.0)) {
1059 [
self.textInputDelegate flutterTextInputView:self
1060 willDismissEditMenuWithTextInputClient:_textInputClient];
1063 - (CGRect)editMenuInteraction:(UIEditMenuInteraction*)interaction
1064 targetRectForConfiguration:(UIEditMenuConfiguration*)configuration API_AVAILABLE(ios(16.0)) {
1065 return _editMenuTargetRect;
1068 - (void)showEditMenuWithTargetRect:(CGRect)targetRect
1069 items:(NSArray<NSDictionary*>*)items API_AVAILABLE(ios(16.0)) {
1070 _editMenuTargetRect = targetRect;
1071 _editMenuItems = items;
1073 UIEditMenuConfiguration* config =
1074 [UIEditMenuConfiguration configurationWithIdentifier:nil sourcePoint:CGPointZero];
1075 [
self.editMenuInteraction presentEditMenuWithConfiguration:config];
1079 [
self.editMenuInteraction dismissMenu];
1082 - (void)configureWithDictionary:(NSDictionary*)configuration {
1083 NSDictionary* inputType = configuration[kKeyboardType];
1085 NSDictionary* autofill = configuration[kAutofillProperties];
1087 self.secureTextEntry = [configuration[kSecureTextEntry] boolValue];
1088 self.enableDeltaModel = [configuration[kEnableDeltaModel] boolValue];
1095 NSString* smartDashesType = configuration[kSmartDashesType];
1097 bool smartDashesIsDisabled = smartDashesType && [smartDashesType isEqualToString:@"0"];
1098 self.smartDashesType = smartDashesIsDisabled ? UITextSmartDashesTypeNo : UITextSmartDashesTypeYes;
1099 NSString* smartQuotesType = configuration[kSmartQuotesType];
1101 bool smartQuotesIsDisabled = smartQuotesType && [smartQuotesType isEqualToString:@"0"];
1102 self.smartQuotesType = smartQuotesIsDisabled ? UITextSmartQuotesTypeNo : UITextSmartQuotesTypeYes;
1104 self.keyboardAppearance = UIKeyboardAppearanceDark;
1106 self.keyboardAppearance = UIKeyboardAppearanceLight;
1108 self.keyboardAppearance = UIKeyboardAppearanceDefault;
1110 NSString* autocorrect = configuration[kAutocorrectionType];
1111 bool autocorrectIsDisabled = autocorrect && ![autocorrect boolValue];
1112 self.autocorrectionType =
1113 autocorrectIsDisabled ? UITextAutocorrectionTypeNo : UITextAutocorrectionTypeDefault;
1114 self.spellCheckingType =
1115 autocorrectIsDisabled ? UITextSpellCheckingTypeNo : UITextSpellCheckingTypeDefault;
1117 if (autofill == nil) {
1118 self.textContentType =
@"";
1121 [
self setTextInputState:autofill[kAutofillEditingValue]];
1122 NSAssert(_autofillId,
@"The autofill configuration must contain an autofill id");
1126 self.isVisibleToAutofill = autofill || _secureTextEntry;
1128 if (@available(iOS 17.0, *)) {
1131 id enableInlinePrediction = configuration[kEnableInlinePrediction];
1132 BOOL enabled = enableInlinePrediction != nil && enableInlinePrediction != [NSNull null] &&
1133 [enableInlinePrediction boolValue];
1134 self.inlinePredictionType =
1135 enabled ? UITextInlinePredictionTypeYes : UITextInlinePredictionTypeNo;
1139 - (UITextContentType)textContentType {
1140 return _textContentType;
1153 - (UIColor*)insertionPointColor {
1154 return [UIColor clearColor];
1157 - (UIColor*)selectionBarColor {
1158 return [UIColor clearColor];
1161 - (UIColor*)selectionHighlightColor {
1162 return [UIColor clearColor];
1165 - (UIInputViewController*)inputViewController {
1177 return _textInputPlugin.textInputDelegate;
1180 - (BOOL)respondsToSelector:(
SEL)selector {
1181 if (@available(iOS 17.0, *)) {
1183 if (selector ==
@selector(insertionPointColor)) {
1187 return [
super respondsToSelector:selector];
1190 - (void)setTextInputClient:(
int)client {
1192 _textInputClient = client;
1196 - (UITextInteraction*)textInteraction
API_AVAILABLE(ios(13.0)) {
1197 if (!_textInteraction) {
1198 _textInteraction = [UITextInteraction textInteractionForMode:UITextInteractionModeEditable];
1199 _textInteraction.textInput =
self;
1201 return _textInteraction;
1204 - (void)setTextInputState:(NSDictionary*)state {
1211 [
self addInteraction:self.textInteraction];
1214 NSString* newText = state[@"text"];
1215 BOOL textChanged = ![
self.text isEqualToString:newText];
1217 [
self.inputDelegate textWillChange:self];
1218 [
self.text setString:newText];
1220 NSInteger composingBase = [state[@"composingBase"] intValue];
1221 NSInteger composingExtent = [state[@"composingExtent"] intValue];
1222 NSRange composingRange = [
self clampSelection:NSMakeRange(MIN(composingBase, composingExtent),
1223 ABS(composingBase - composingExtent))
1226 self.markedTextRange =
1229 NSRange selectedRange = [
self clampSelectionFromBase:[state[@"selectionBase"] intValue]
1230 extent:[state[@"selectionExtent"] intValue]
1233 NSRange oldSelectedRange = [(
FlutterTextRange*)
self.selectedTextRange range];
1234 if (!NSEqualRanges(selectedRange, oldSelectedRange)) {
1235 [
self.inputDelegate selectionWillChange:self];
1243 [
self.inputDelegate selectionDidChange:self];
1247 [
self.inputDelegate textDidChange:self];
1250 if (_textInteraction) {
1251 [
self removeInteraction:_textInteraction];
1256 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
1257 _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
1258 [
self resetScribbleInteractionStatusIfEnding];
1259 [
self.viewResponder touchesBegan:touches withEvent:event];
1262 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
1263 [
self.viewResponder touchesMoved:touches withEvent:event];
1266 - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
1267 [
self.viewResponder touchesEnded:touches withEvent:event];
1270 - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
1271 [
self.viewResponder touchesCancelled:touches withEvent:event];
1274 - (void)touchesEstimatedPropertiesUpdated:(NSSet*)touches {
1275 [
self.viewResponder touchesEstimatedPropertiesUpdated:touches];
1285 - (NSRange)clampSelectionFromBase:(
int)selectionBase
1286 extent:(
int)selectionExtent
1287 forText:(NSString*)text {
1288 int loc = MIN(selectionBase, selectionExtent);
1289 int len = ABS(selectionExtent - selectionBase);
1290 return loc < 0 ? NSMakeRange(0, 0)
1291 : [
self clampSelection:NSMakeRange(loc, len) forText:
self.text];
1294 - (NSRange)clampSelection:(NSRange)range forText:(NSString*)text {
1295 NSUInteger start = MIN(MAX(range.location, 0), text.length);
1296 NSUInteger length = MIN(range.length, text.length - start);
1297 return NSMakeRange(start, length);
1300 - (BOOL)isVisibleToAutofill {
1301 return self.frame.size.width > 0 &&
self.frame.size.height > 0;
1309 - (void)setIsVisibleToAutofill:(BOOL)isVisibleToAutofill {
1312 self.frame = isVisibleToAutofill ? CGRectMake(0, 0, 1, 1) : CGRectZero;
1315 #pragma mark UIScribbleInteractionDelegate
1320 if (@available(iOS 14.0, *)) {
1321 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
1328 - (void)scribbleInteractionWillBeginWriting:(UIScribbleInteraction*)interaction
1329 API_AVAILABLE(ios(14.0)) {
1331 [
self.textInputDelegate flutterTextInputViewScribbleInteractionBegan:self];
1334 - (void)scribbleInteractionDidFinishWriting:(UIScribbleInteraction*)interaction
1335 API_AVAILABLE(ios(14.0)) {
1337 [
self.textInputDelegate flutterTextInputViewScribbleInteractionFinished:self];
1340 - (BOOL)scribbleInteraction:(UIScribbleInteraction*)interaction
1341 shouldBeginAtLocation:(CGPoint)location API_AVAILABLE(ios(14.0)) {
1345 - (BOOL)scribbleInteractionShouldDelayFocus:(UIScribbleInteraction*)interaction
1346 API_AVAILABLE(ios(14.0)) {
1350 #pragma mark - UIResponder Overrides
1352 - (BOOL)canBecomeFirstResponder {
1357 return _textInputClient != 0;
1360 - (BOOL)becomeFirstResponder {
1361 BOOL wasFirstResponder =
self.isFirstResponder;
1362 BOOL success = [
super becomeFirstResponder];
1363 if (success && !wasFirstResponder &&
self.isFirstResponder &&
1366 int client = _textInputClient;
1369 [weakSelf handleFirstResponderRestoreResult:result client:client];
1372 [
self.textInputDelegate flutterTextInputView:self
1373 didRestoreFirstResponderWithTextInputClient:client
1374 result:handleResult];
1379 - (void)handleFirstResponderRestoreResult:(
id)result client:(
int)client {
1380 if ([result isKindOfClass:[NSNumber
class]] && [result boolValue]) {
1386 if (client == _textInputClient &&
self.isFirstResponder) {
1387 [
self resignFirstResponderFromFramework];
1391 - (BOOL)resignFirstResponder {
1392 BOOL wasFirstResponder =
self.isFirstResponder;
1393 BOOL success = [
super resignFirstResponder];
1394 if (success && !_preventCursorDismissWhenResignFirstResponder) {
1395 if (wasFirstResponder) {
1399 [
self.textInputDelegate flutterTextInputView:self
1400 didResignFirstResponderWithTextInputClient:_textInputClient];
1405 - (BOOL)becomeFirstResponderFromFramework {
1407 return [
self becomeFirstResponder];
1410 - (BOOL)resignFirstResponderFromFramework {
1413 BOOL success = [
self resignFirstResponder];
1418 - (BOOL)canPerformAction:(
SEL)action withSender:(
id)sender {
1419 if (action ==
@selector(paste:)) {
1421 return [UIPasteboard generalPasteboard].hasStrings;
1422 }
else if (action ==
@selector(copy:) || action ==
@selector(cut:) ||
1423 action ==
@selector(
delete:)) {
1424 return [
self textInRange:_selectedTextRange].length > 0;
1425 }
else if (action ==
@selector(selectAll:)) {
1426 return self.hasText;
1427 }
else if (action ==
@selector(captureTextFromCamera:)) {
1428 if (@available(iOS 15.0, *)) {
1433 return [
super canPerformAction:action withSender:sender];
1436 #pragma mark - UIResponderStandardEditActions Overrides
1438 - (void)cut:(
id)sender {
1439 [UIPasteboard generalPasteboard].string = [
self textInRange:_selectedTextRange];
1440 [
self replaceRange:_selectedTextRange withText:@""];
1443 - (void)copy:(
id)sender {
1444 [UIPasteboard generalPasteboard].string = [
self textInRange:_selectedTextRange];
1447 - (void)paste:(
id)sender {
1448 NSString* pasteboardString = [UIPasteboard generalPasteboard].string;
1449 if (pasteboardString != nil) {
1450 [
self insertText:pasteboardString];
1454 - (void)delete:(
id)sender {
1455 [
self replaceRange:_selectedTextRange withText:@""];
1458 - (void)selectAll:(
id)sender {
1459 [
self setSelectedTextRange:[
self textRangeFromPosition:[
self beginningOfDocument]
1460 toPosition:[
self endOfDocument]]];
1463 #pragma mark - UITextInput Overrides
1465 - (id<UITextInputTokenizer>)tokenizer {
1466 if (_tokenizer == nil) {
1473 return [_selectedTextRange copy];
1477 - (void)setSelectedTextRangeLocal:(UITextRange*)selectedTextRange {
1482 rangeWithNSRange:fml::RangeForCharactersInRange(self.text, flutterTextRange.range)] copy];
1489 - (void)setSelectedTextRange:(UITextRange*)selectedTextRange {
1494 [
self setSelectedTextRangeLocal:selectedTextRange];
1496 if (_enableDeltaModel) {
1497 [
self updateEditingStateWithDelta:flutter::TextEditingDelta([
self.text UTF8String])];
1499 [
self updateEditingState];
1503 _scribbleFocusStatus == FlutterScribbleFocusStatusFocused) {
1507 if (flutterTextRange.
range.length > 0) {
1508 [
self.textInputDelegate flutterTextInputView:self showToolbar:_textInputClient];
1512 [
self resetScribbleInteractionStatusIfEnding];
1515 - (id)insertDictationResultPlaceholder {
1519 - (void)removeDictationResultPlaceholder:(
id)placeholder willInsertResult:(BOOL)willInsertResult {
1522 - (NSString*)textInRange:(UITextRange*)range {
1527 @"Expected a FlutterTextRange for range (got %@).", [range
class]);
1529 if (textRange.location == NSNotFound) {
1538 NSUInteger location = MIN(textRange.location,
self.text.length);
1539 NSUInteger length = MIN(
self.text.length - location, textRange.length);
1540 NSRange safeRange = NSMakeRange(location, length);
1541 return [
self.text substringWithRange:safeRange];
1546 - (void)replaceRangeLocal:(NSRange)range withText:(NSString*)text {
1547 [
self.text replaceCharactersInRange:[
self clampSelection:range forText:self.text]
1553 const NSRange newSelectionRange =
1554 [
self clampSelection:NSMakeRange(range.location + text.length, 0) forText:self.text];
1557 self.markedTextRange = nil;
1560 - (void)replaceRange:(UITextRange*)range withText:(NSString*)text {
1561 NSString* textBeforeChange = [
self.text copy];
1563 [
self replaceRangeLocal:replaceRange withText:text];
1564 if (_enableDeltaModel) {
1565 NSRange nextReplaceRange = [
self clampSelection:replaceRange forText:textBeforeChange];
1566 [
self updateEditingStateWithDelta:flutter::TextEditingDelta(
1567 [textBeforeChange UTF8String],
1569 nextReplaceRange.location,
1570 nextReplaceRange.location + nextReplaceRange.length),
1571 [text UTF8String])];
1573 [
self updateEditingState];
1577 - (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text {
1580 self.temporarilyDeletedComposedCharacter = nil;
1582 if (
self.
returnKeyType == UIReturnKeyDefault && [text isEqualToString:
@"\n"]) {
1583 [
self.textInputDelegate flutterTextInputView:self
1584 performAction:FlutterTextInputActionNewline
1585 withClient:_textInputClient];
1589 if ([text isEqualToString:
@"\n"]) {
1590 FlutterTextInputAction action;
1592 case UIReturnKeyDefault:
1593 action = FlutterTextInputActionUnspecified;
1595 case UIReturnKeyDone:
1596 action = FlutterTextInputActionDone;
1599 action = FlutterTextInputActionGo;
1601 case UIReturnKeySend:
1602 action = FlutterTextInputActionSend;
1604 case UIReturnKeySearch:
1605 case UIReturnKeyGoogle:
1606 case UIReturnKeyYahoo:
1607 action = FlutterTextInputActionSearch;
1609 case UIReturnKeyNext:
1610 action = FlutterTextInputActionNext;
1612 case UIReturnKeyContinue:
1613 action = FlutterTextInputActionContinue;
1615 case UIReturnKeyJoin:
1616 action = FlutterTextInputActionJoin;
1618 case UIReturnKeyRoute:
1619 action = FlutterTextInputActionRoute;
1621 case UIReturnKeyEmergencyCall:
1622 action = FlutterTextInputActionEmergencyCall;
1626 [
self.textInputDelegate flutterTextInputView:self
1627 performAction:action
1628 withClient:_textInputClient];
1637 - (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange {
1638 NSString* textBeforeChange = [
self.text copy];
1641 _scribbleFocusStatus != FlutterScribbleFocusStatusUnfocused) {
1645 if (markedText == nil) {
1650 const NSRange& actualReplacedRange = currentMarkedTextRange && !currentMarkedTextRange.isEmpty
1651 ? currentMarkedTextRange.
range
1655 [
self.text replaceCharactersInRange:actualReplacedRange withString:markedText];
1657 const NSRange newMarkedRange = NSMakeRange(actualReplacedRange.location, markedText.length);
1658 self.markedTextRange =
1661 [
self setSelectedTextRangeLocal:
1663 rangeWithNSRange:[
self clampSelection:NSMakeRange(markedSelectedRange.location +
1664 newMarkedRange.location,
1665 markedSelectedRange.length)
1666 forText:self.text]]];
1667 if (_enableDeltaModel) {
1668 NSRange nextReplaceRange = [
self clampSelection:actualReplacedRange forText:textBeforeChange];
1669 [
self updateEditingStateWithDelta:flutter::TextEditingDelta(
1670 [textBeforeChange UTF8String],
1672 nextReplaceRange.location,
1673 nextReplaceRange.location + nextReplaceRange.length),
1674 [markedText UTF8String])];
1676 [
self updateEditingState];
1682 - (void)setAttributedMarkedText:(NSAttributedString*)attributedString
1683 selectedRange:(NSRange)selectedRange API_AVAILABLE(ios(17.0)) {
1684 NSString* markedText = attributedString ? [attributedString string] :
@"";
1685 [
self setMarkedText:markedText selectedRange:selectedRange];
1688 - (void)unmarkText {
1692 self.markedTextRange = nil;
1693 if (_enableDeltaModel) {
1694 [
self updateEditingStateWithDelta:flutter::TextEditingDelta([
self.text UTF8String])];
1696 [
self updateEditingState];
1700 - (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition
1701 toPosition:(UITextPosition*)toPosition {
1704 if (toIndex >= fromIndex) {
1717 - (NSUInteger)decrementOffsetPosition:(NSUInteger)position {
1718 return fml::RangeForCharacterAtIndex(
self.text, MAX(0, position - 1)).location;
1721 - (NSUInteger)incrementOffsetPosition:(NSUInteger)position {
1722 NSRange charRange = fml::RangeForCharacterAtIndex(
self.text, position);
1723 return MIN(position + charRange.length,
self.text.length);
1726 - (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset {
1729 NSInteger newLocation = (NSInteger)offsetPosition + offset;
1730 if (newLocation < 0 || newLocation > (NSInteger)
self.text.length) {
1739 for (NSInteger i = 0; i < offset && offsetPosition <
self.text.length; ++i) {
1740 offsetPosition = [
self incrementOffsetPosition:offsetPosition];
1743 for (NSInteger i = 0; i < ABS(offset) && offsetPosition > 0; ++i) {
1744 offsetPosition = [
self decrementOffsetPosition:offsetPosition];
1750 - (UITextPosition*)positionFromPosition:(UITextPosition*)position
1751 inDirection:(UITextLayoutDirection)direction
1752 offset:(NSInteger)offset {
1754 switch (direction) {
1755 case UITextLayoutDirectionLeft:
1756 case UITextLayoutDirectionUp:
1757 return [
self positionFromPosition:position offset:offset * -1];
1758 case UITextLayoutDirectionRight:
1759 case UITextLayoutDirectionDown:
1760 return [
self positionFromPosition:position offset:1];
1764 - (UITextPosition*)beginningOfDocument {
1768 - (UITextPosition*)endOfDocument {
1770 affinity:UITextStorageDirectionBackward];
1773 - (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other {
1776 if (positionIndex < otherIndex) {
1777 return NSOrderedAscending;
1779 if (positionIndex > otherIndex) {
1780 return NSOrderedDescending;
1784 if (positionAffinity == otherAffinity) {
1785 return NSOrderedSame;
1787 if (positionAffinity == UITextStorageDirectionBackward) {
1789 return NSOrderedAscending;
1792 return NSOrderedDescending;
1795 - (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition {
1799 - (UITextPosition*)positionWithinRange:(UITextRange*)range
1800 farthestInDirection:(UITextLayoutDirection)direction {
1802 UITextStorageDirection affinity;
1803 switch (direction) {
1804 case UITextLayoutDirectionLeft:
1805 case UITextLayoutDirectionUp:
1807 affinity = UITextStorageDirectionForward;
1809 case UITextLayoutDirectionRight:
1810 case UITextLayoutDirectionDown:
1812 affinity = UITextStorageDirectionBackward;
1818 - (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position
1819 inDirection:(UITextLayoutDirection)direction {
1821 NSUInteger startIndex;
1822 NSUInteger endIndex;
1823 switch (direction) {
1824 case UITextLayoutDirectionLeft:
1825 case UITextLayoutDirectionUp:
1826 startIndex = [
self decrementOffsetPosition:positionIndex];
1827 endIndex = positionIndex;
1829 case UITextLayoutDirectionRight:
1830 case UITextLayoutDirectionDown:
1831 startIndex = positionIndex;
1832 endIndex = [
self incrementOffsetPosition:positionIndex];
1838 #pragma mark - UITextInput text direction handling
1840 - (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position
1841 inDirection:(UITextStorageDirection)direction {
1843 return UITextWritingDirectionNatural;
1846 - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection
1847 forRange:(UITextRange*)range {
1851 #pragma mark - UITextInput cursor, selection rect handling
1853 - (void)setMarkedRect:(CGRect)markedRect {
1854 _markedRect = markedRect;
1861 - (void)setEditableTransform:(NSArray*)matrix {
1862 CATransform3D* transform = &_editableTransform;
1864 transform->m11 = [matrix[0] doubleValue];
1865 transform->m12 = [matrix[1] doubleValue];
1866 transform->m13 = [matrix[2] doubleValue];
1867 transform->m14 = [matrix[3] doubleValue];
1869 transform->m21 = [matrix[4] doubleValue];
1870 transform->m22 = [matrix[5] doubleValue];
1871 transform->m23 = [matrix[6] doubleValue];
1872 transform->m24 = [matrix[7] doubleValue];
1874 transform->m31 = [matrix[8] doubleValue];
1875 transform->m32 = [matrix[9] doubleValue];
1876 transform->m33 = [matrix[10] doubleValue];
1877 transform->m34 = [matrix[11] doubleValue];
1879 transform->m41 = [matrix[12] doubleValue];
1880 transform->m42 = [matrix[13] doubleValue];
1881 transform->m43 = [matrix[14] doubleValue];
1882 transform->m44 = [matrix[15] doubleValue];
1891 CGPoint points[] = {
1892 incomingRect.origin,
1893 CGPointMake(incomingRect.origin.x, incomingRect.origin.y + incomingRect.size.height),
1894 CGPointMake(incomingRect.origin.x + incomingRect.size.width, incomingRect.origin.y),
1895 CGPointMake(incomingRect.origin.x + incomingRect.size.width,
1896 incomingRect.origin.y + incomingRect.size.height)};
1898 CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX);
1899 CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX);
1901 for (
int i = 0; i < 4; i++) {
1902 const CGPoint point = points[i];
1904 CGFloat x = _editableTransform.m11 * point.x + _editableTransform.m21 * point.y +
1905 _editableTransform.m41;
1906 CGFloat y = _editableTransform.m12 * point.x + _editableTransform.m22 * point.y +
1907 _editableTransform.m42;
1909 const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y +
1910 _editableTransform.m44;
1914 }
else if (w != 1.0) {
1919 origin.x = MIN(origin.x, x);
1920 origin.y = MIN(origin.y, y);
1921 farthest.x = MAX(farthest.x, x);
1922 farthest.y = MAX(farthest.y, y);
1924 return CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y);
1933 - (CGRect)firstRectForRange:(UITextRange*)range {
1935 @"Expected a FlutterTextPosition for range.start (got %@).", [range.start
class]);
1937 @"Expected a FlutterTextPosition for range.end (got %@).", [range.end
class]);
1940 if (_markedTextRange != nil) {
1951 CGRect rect = _markedRect;
1952 if (CGRectIsEmpty(rect)) {
1953 rect = CGRectInset(rect, -0.1, 0);
1958 UIView* hostView = _textInputPlugin.hostView;
1959 NSAssert(hostView == nil || [
self isDescendantOfView:hostView],
@"%@ is not a descendant of %@",
1961 return hostView ? [hostView convertRect:_cachedFirstRect toView:self] :
_cachedFirstRect;
1965 _scribbleFocusStatus == FlutterScribbleFocusStatusUnfocused) {
1966 if (@available(iOS 17.0, *)) {
1976 [
self.textInputDelegate flutterTextInputView:self
1977 showAutocorrectionPromptRectForStart:start
1979 withClient:_textInputClient];
1987 if (@available(iOS 17, *)) {
1993 NSUInteger first = start;
1998 CGRect startSelectionRect = CGRectNull;
1999 CGRect endSelectionRect = CGRectNull;
2002 CGFloat minY = CGFLOAT_MAX;
2003 CGFloat maxY = CGFLOAT_MIN;
2006 rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))];
2007 for (NSUInteger i = 0; i < [_selectionRects count]; i++) {
2008 BOOL startsOnOrBeforeStartOfRange = _selectionRects[i].position <= first;
2009 BOOL isLastSelectionRect = i + 1 == [_selectionRects count];
2010 BOOL endOfTextIsAfterStartOfRange = isLastSelectionRect && textRange.
range.length > first;
2011 BOOL nextSelectionRectIsAfterStartOfRange =
2012 !isLastSelectionRect && _selectionRects[i + 1].position > first;
2013 if (startsOnOrBeforeStartOfRange &&
2014 (endOfTextIsAfterStartOfRange || nextSelectionRectIsAfterStartOfRange)) {
2016 if (@available(iOS 17, *)) {
2017 startSelectionRect = _selectionRects[i].rect;
2019 return _selectionRects[i].rect;
2022 if (!CGRectIsNull(startSelectionRect)) {
2023 minY = fmin(minY, CGRectGetMinY(_selectionRects[i].rect));
2024 maxY = fmax(maxY, CGRectGetMaxY(_selectionRects[i].rect));
2025 BOOL endsOnOrAfterEndOfRange = _selectionRects[i].position >= end - 1;
2026 BOOL nextSelectionRectIsOnNextLine =
2027 !isLastSelectionRect &&
2032 CGRectGetMidY(_selectionRects[i + 1].rect) > CGRectGetMaxY(_selectionRects[i].rect);
2033 if (endsOnOrAfterEndOfRange || isLastSelectionRect || nextSelectionRectIsOnNextLine) {
2034 endSelectionRect = _selectionRects[i].rect;
2039 if (CGRectIsNull(startSelectionRect) || CGRectIsNull(endSelectionRect)) {
2043 CGFloat minX = fmin(CGRectGetMinX(startSelectionRect), CGRectGetMinX(endSelectionRect));
2044 CGFloat maxX = fmax(CGRectGetMaxX(startSelectionRect), CGRectGetMaxX(endSelectionRect));
2045 return CGRectMake(minX, minY, maxX - minX, maxY - minY);
2053 NSArray<UITextSelectionRect*>* rects = [
self
2055 rangeWithNSRange:fml::RangeForCharactersInRange(
2059 (index >= (NSInteger)self.text.length)
2062 if (rects.count == 0) {
2068 CGRect characterAfterCaret = rects[0].rect;
2073 return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width,
2074 characterAfterCaret.origin.y, 0, characterAfterCaret.size.height);
2076 return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0,
2077 characterAfterCaret.size.height);
2079 }
else if (rects.count == 2 && affinity == UITextStorageDirectionForward) {
2082 CGRect characterAfterCaret = rects[1].rect;
2087 return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width,
2088 characterAfterCaret.origin.y, 0, characterAfterCaret.size.height);
2090 return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0,
2091 characterAfterCaret.size.height);
2100 CGRect characterBeforeCaret = rects[0].rect;
2103 return CGRectMake(characterBeforeCaret.origin.x, characterBeforeCaret.origin.y, 0,
2104 characterBeforeCaret.size.height);
2106 return CGRectMake(characterBeforeCaret.origin.x + characterBeforeCaret.size.width,
2107 characterBeforeCaret.origin.y, 0, characterBeforeCaret.size.height);
2111 - (UITextPosition*)closestPositionToPoint:(CGPoint)point {
2112 if ([_selectionRects count] == 0) {
2114 @"Expected a FlutterTextPosition for position (got %@).",
2117 UITextStorageDirection currentAffinity =
2123 rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))];
2124 return [
self closestPositionToPoint:point withinRange:range];
2127 - (NSArray*)selectionRectsForRange:(UITextRange*)range {
2135 @"Expected a FlutterTextPosition for range.start (got %@).", [range.start
class]);
2137 @"Expected a FlutterTextPosition for range.end (got %@).", [range.end
class]);
2140 NSMutableArray* rects = [[NSMutableArray alloc] init];
2141 for (NSUInteger i = 0; i < [_selectionRects count]; i++) {
2142 if (_selectionRects[i].position >= start &&
2143 (_selectionRects[i].position < end ||
2144 (start == end && _selectionRects[i].position <= end))) {
2145 float width = _selectionRects[i].rect.size.width;
2149 CGRect rect = CGRectMake(_selectionRects[i].rect.origin.x, _selectionRects[i].rect.origin.y,
2150 width, _selectionRects[i].rect.size.height);
2153 position:_selectionRects[i].position
2157 self.text, NSMakeRange(0, self.text.length))
2160 [rects addObject:selectionRect];
2166 - (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range {
2168 @"Expected a FlutterTextPosition for range.start (got %@).", [range.start
class]);
2170 @"Expected a FlutterTextPosition for range.end (got %@).", [range.end
class]);
2180 NSUInteger _closestRectIndex = 0;
2181 for (NSUInteger i = 0; i < [_selectionRects count]; i++) {
2182 NSUInteger position = _selectionRects[i].position;
2183 if (position >= start && position <= end) {
2186 point, _selectionRects[i].rect, _selectionRects[i].isRTL,
2187 NO, _selectionRects[_closestRectIndex].rect,
2188 _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) {
2190 _closestRectIndex = i;
2197 affinity:UITextStorageDirectionForward];
2203 for (NSUInteger i = MAX(0, _closestRectIndex - 1);
2204 i < MIN(_closestRectIndex + 2, [_selectionRects count]); i++) {
2205 NSUInteger position = _selectionRects[i].position + 1;
2206 if (position >= start && position <= end) {
2208 point, _selectionRects[i].rect, _selectionRects[i].isRTL,
2209 YES, _selectionRects[_closestRectIndex].rect,
2210 _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) {
2213 affinity:UITextStorageDirectionBackward];
2218 return closestPosition;
2221 - (UITextRange*)characterRangeAtPoint:(CGPoint)point {
2224 return [
FlutterTextRange rangeWithNSRange:fml::RangeForCharacterAtIndex(self.text, currentIndex)];
2255 - (void)beginFloatingCursorAtPoint:(CGPoint)point {
2272 [
self.textInputDelegate flutterTextInputView:self
2273 updateFloatingCursor:FlutterFloatingCursorDragStateStart
2274 withClient:_textInputClient
2275 withPosition:@{@"X" : @0, @"Y" : @0}];
2278 - (void)updateFloatingCursorAtPoint:(CGPoint)point {
2279 [
self.textInputDelegate flutterTextInputView:self
2280 updateFloatingCursor:FlutterFloatingCursorDragStateUpdate
2281 withClient:_textInputClient
2283 @"X" : @(point.x - _floatingCursorOffset.x),
2284 @"Y" : @(point.y - _floatingCursorOffset.y)
2288 - (void)endFloatingCursor {
2290 [
self.textInputDelegate flutterTextInputView:self
2291 updateFloatingCursor:FlutterFloatingCursorDragStateEnd
2292 withClient:_textInputClient
2293 withPosition:@{@"X" : @0, @"Y" : @0}];
2296 #pragma mark - UIKeyInput Overrides
2298 - (void)updateEditingState {
2303 NSInteger composingBase = -1;
2304 NSInteger composingExtent = -1;
2309 NSDictionary* state = @{
2310 @"selectionBase" : @(selectionBase),
2311 @"selectionExtent" : @(selectionExtent),
2313 @"selectionIsDirectional" : @(
false),
2314 @"composingBase" : @(composingBase),
2315 @"composingExtent" : @(composingExtent),
2316 @"text" : [NSString stringWithString:self.text],
2319 if (_textInputClient == 0 && _autofillId != nil) {
2320 [
self.textInputDelegate flutterTextInputView:self
2321 updateEditingClient:_textInputClient
2323 withTag:_autofillId];
2325 [
self.textInputDelegate flutterTextInputView:self
2326 updateEditingClient:_textInputClient
2331 - (void)updateEditingStateWithDelta:(
flutter::TextEditingDelta)delta {
2336 NSInteger composingBase = -1;
2337 NSInteger composingExtent = -1;
2343 NSDictionary* deltaToFramework = @{
2344 @"oldText" : @(delta.old_text().c_str()),
2345 @"deltaText" : @(delta.delta_text().c_str()),
2346 @"deltaStart" : @(delta.delta_start()),
2347 @"deltaEnd" : @(delta.delta_end()),
2348 @"selectionBase" : @(selectionBase),
2349 @"selectionExtent" : @(selectionExtent),
2351 @"selectionIsDirectional" : @(
false),
2352 @"composingBase" : @(composingBase),
2353 @"composingExtent" : @(composingExtent),
2356 [_pendingDeltas addObject:deltaToFramework];
2358 if (_pendingDeltas.count == 1) {
2360 dispatch_async(dispatch_get_main_queue(), ^{
2362 if (strongSelf && strongSelf.pendingDeltas.count > 0) {
2363 NSDictionary* deltas = @{
2364 @"deltas" : strongSelf.pendingDeltas,
2367 [strongSelf.textInputDelegate flutterTextInputView:strongSelf
2368 updateEditingClient:strongSelf->_textInputClient
2370 [strongSelf.pendingDeltas removeAllObjects];
2377 return self.text.length > 0;
2380 - (void)insertText:(NSString*)text {
2381 if (
self.temporarilyDeletedComposedCharacter.length > 0 && text.length == 1 && !text.UTF8String &&
2382 [text characterAtIndex:0] == [
self.temporarilyDeletedComposedCharacter characterAtIndex:0]) {
2386 text =
self.temporarilyDeletedComposedCharacter;
2387 self.temporarilyDeletedComposedCharacter = nil;
2395 NSMutableArray<FlutterTextSelectionRect*>* copiedRects =
2396 [[NSMutableArray alloc] initWithCapacity:[_selectionRects count]];
2398 @"Expected a FlutterTextPosition for position (got %@).", [replacedRange.start
class]);
2400 for (NSUInteger i = 0; i < [_selectionRects count]; i++) {
2401 NSUInteger rectPosition = _selectionRects[i].position;
2402 if (rectPosition == insertPosition) {
2403 for (NSUInteger j = 0; j <= text.length; j++) {
2410 if (rectPosition > insertPosition) {
2411 rectPosition = rectPosition + text.length;
2420 _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
2421 [
self resetScribbleInteractionStatusIfEnding];
2422 self.selectionRects = copiedRects;
2424 [
self replaceRange:replacedRange withText:text];
2427 - (UITextPlaceholder*)insertTextPlaceholderWithSize:(CGSize)size API_AVAILABLE(ios(13.0)) {
2428 [
self.textInputDelegate flutterTextInputView:self
2429 insertTextPlaceholderWithSize:size
2430 withClient:_textInputClient];
2435 - (void)removeTextPlaceholder:(UITextPlaceholder*)textPlaceholder API_AVAILABLE(ios(13.0)) {
2437 [
self.textInputDelegate flutterTextInputView:self removeTextPlaceholder:_textInputClient];
2440 - (void)deleteBackward {
2442 _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
2443 [
self resetScribbleInteractionStatusIfEnding];
2460 if (oldRange.location > 0) {
2461 NSRange newRange = NSMakeRange(oldRange.location - 1, 1);
2465 NSRange charRange = fml::RangeForCharacterAtIndex(
self.text, oldRange.location - 1);
2466 if (
IsEmoji(
self.text, charRange)) {
2467 newRange = NSMakeRange(charRange.location, oldRange.location - charRange.location);
2479 NSString* deletedText = [
self.text substringWithRange:_selectedTextRange.range];
2480 NSRange deleteFirstCharacterRange = fml::RangeForCharacterAtIndex(deletedText, 0);
2481 self.temporarilyDeletedComposedCharacter =
2482 [deletedText substringWithRange:deleteFirstCharacterRange];
2484 [
self replaceRange:_selectedTextRange withText:@""];
2488 - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(
id)target {
2489 UIAccessibilityPostNotification(notification, target);
2492 - (void)accessibilityElementDidBecomeFocused {
2493 if ([
self accessibilityElementIsFocused]) {
2497 FML_DCHECK(_backingTextInputAccessibilityObject);
2498 [
self postAccessibilityNotification:UIAccessibilityScreenChangedNotification
2499 target:_backingTextInputAccessibilityObject];
2503 - (BOOL)accessibilityElementsHidden {
2504 return !_accessibilityEnabled;
2513 #pragma mark - Key Events Handling
2514 - (void)pressesBegan:(NSSet<UIPress*>*)presses
2515 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2516 [_textInputPlugin.viewController pressesBegan:presses withEvent:event];
2519 - (void)pressesChanged:(NSSet<UIPress*>*)presses
2520 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2521 [_textInputPlugin.viewController pressesChanged:presses withEvent:event];
2524 - (void)pressesEnded:(NSSet<UIPress*>*)presses
2525 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2526 [_textInputPlugin.viewController pressesEnded:presses withEvent:event];
2529 - (void)pressesCancelled:(NSSet<UIPress*>*)presses
2530 withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2531 [_textInputPlugin.viewController pressesCancelled:presses withEvent:event];
2560 - (BOOL)accessibilityElementsHidden {
2567 - (void)enableActiveViewAccessibility;
2584 - (void)enableActiveViewAccessibility {
2585 [
self.target enableActiveViewAccessibility];
2592 @property(nonatomic, readonly)
2593 NSMutableDictionary<NSString*, FlutterTextInputView*>* autofillContext;
2597 @property(nonatomic, readonly) BOOL pendingAutofillRemoval;
2602 @property(nonatomic, readonly) BOOL pendingInputViewRemoval;
2607 @property(nonatomic, strong) UIView* keyboardViewContainer;
2608 @property(nonatomic, strong) UIView* keyboardView;
2609 @property(nonatomic, strong) UIView* cachedFirstResponder;
2610 @property(nonatomic, assign) CGRect keyboardRect;
2611 @property(nonatomic, assign) CGFloat previousPointerYPosition;
2612 @property(nonatomic, assign) CGFloat pointerYVelocity;
2616 NSTimer* _enableFlutterTextInputViewAccessibilityTimer;
2622 self = [
super init];
2625 _textInputDelegate = textInputDelegate;
2626 _autofillContext = [[NSMutableDictionary alloc] init];
2628 _scribbleElements = [[NSMutableDictionary alloc] init];
2629 _keyboardViewContainer = [[UIView alloc] init];
2631 [[NSNotificationCenter defaultCenter] addObserver:self
2632 selector:@selector(handleKeyboardWillShow:)
2633 name:UIKeyboardWillShowNotification
2640 - (void)handleKeyboardWillShow:(NSNotification*)notification {
2641 NSDictionary* keyboardInfo = [notification userInfo];
2642 NSValue* keyboardFrameEnd = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
2643 _keyboardRect = [keyboardFrameEnd CGRectValue];
2650 - (void)removeEnableFlutterTextInputViewAccessibilityTimer {
2651 if (_enableFlutterTextInputViewAccessibilityTimer) {
2652 [_enableFlutterTextInputViewAccessibilityTimer invalidate];
2653 _enableFlutterTextInputViewAccessibilityTimer = nil;
2657 - (UIView<UITextInput>*)textInputView {
2662 [_autofillContext removeAllObjects];
2663 [
self clearTextInputClient];
2664 [
self hideTextInput];
2668 NSString* method = call.
method;
2671 [
self showTextInput];
2673 }
else if ([method isEqualToString:
kHideMethod]) {
2674 [
self hideTextInput];
2677 [
self setTextInputClient:[args[0] intValue] withConfiguration:args[1]];
2681 [
self setPlatformViewTextInputClient];
2684 [
self setTextInputEditingState:args];
2687 [
self clearTextInputClient];
2690 [
self setEditableSizeAndTransform:args];
2693 [
self updateMarkedRect:args];
2696 [
self triggerAutofillSave:[args boolValue]];
2702 [
self setSelectionRects:args];
2705 [
self setSelectionRects:args];
2708 [
self startLiveTextInput];
2711 [
self updateConfig:args];
2714 CGFloat pointerY = (CGFloat)[args[
@"pointerY"] doubleValue];
2715 [
self handlePointerMove:pointerY];
2718 CGFloat pointerY = (CGFloat)[args[
@"pointerY"] doubleValue];
2719 [
self handlePointerUp:pointerY];
2726 - (void)handlePointerUp:(CGFloat)pointerY {
2727 if (_keyboardView.superview != nil) {
2730 UIScreen* screen = _viewController.flutterScreenIfViewLoaded;
2731 CGFloat screenHeight = screen.bounds.size.height;
2732 CGFloat keyboardHeight = _keyboardRect.size.height;
2734 BOOL shouldDismissKeyboardBasedOnVelocity = _pointerYVelocity < 0;
2735 [UIView animateWithDuration:kKeyboardAnimationTimeToCompleteion
2737 double keyboardDestination =
2738 shouldDismissKeyboardBasedOnVelocity ? screenHeight : screenHeight - keyboardHeight;
2739 _keyboardViewContainer.frame = CGRectMake(
2740 0, keyboardDestination, _viewController.flutterScreenIfViewLoaded.bounds.size.width,
2741 _keyboardViewContainer.frame.size.height);
2743 completion:^(BOOL finished) {
2744 if (shouldDismissKeyboardBasedOnVelocity) {
2745 [
self.textInputDelegate flutterTextInputView:self.activeView
2746 didResignFirstResponderWithTextInputClient:self.activeView.textInputClient];
2747 [
self dismissKeyboardScreenshot];
2749 [
self showKeyboardAndRemoveScreenshot];
2755 - (void)dismissKeyboardScreenshot {
2756 for (UIView* subView in _keyboardViewContainer.subviews) {
2757 [subView removeFromSuperview];
2761 - (void)showKeyboardAndRemoveScreenshot {
2762 [UIView setAnimationsEnabled:NO];
2763 [_cachedFirstResponder becomeFirstResponder];
2767 dispatch_get_main_queue(), ^{
2768 [UIView setAnimationsEnabled:YES];
2769 [
self dismissKeyboardScreenshot];
2773 - (void)handlePointerMove:(CGFloat)pointerY {
2775 UIScreen* screen = _viewController.flutterScreenIfViewLoaded;
2776 CGFloat screenHeight = screen.bounds.size.height;
2777 CGFloat keyboardHeight = _keyboardRect.size.height;
2778 if (screenHeight - keyboardHeight <= pointerY) {
2780 if (_keyboardView.superview == nil) {
2782 [
self takeKeyboardScreenshotAndDisplay];
2783 [
self hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate];
2785 [
self setKeyboardContainerHeight:pointerY];
2786 _pointerYVelocity = _previousPointerYPosition - pointerY;
2789 if (_keyboardView.superview != nil) {
2791 _keyboardViewContainer.frame = _keyboardRect;
2792 _pointerYVelocity = _previousPointerYPosition - pointerY;
2795 _previousPointerYPosition = pointerY;
2798 - (void)setKeyboardContainerHeight:(CGFloat)pointerY {
2799 CGRect frameRect = _keyboardRect;
2800 frameRect.origin.y = pointerY;
2801 _keyboardViewContainer.frame = frameRect;
2804 - (void)hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate {
2805 [UIView setAnimationsEnabled:NO];
2807 _cachedFirstResponder =
2809 ? flutterApplication.keyWindow.flutterFirstResponder
2810 :
self.viewController.flutterWindowSceneIfViewLoaded.keyWindow.flutterFirstResponder;
2812 _activeView.preventCursorDismissWhenResignFirstResponder = YES;
2813 [_cachedFirstResponder resignFirstResponder];
2814 _activeView.preventCursorDismissWhenResignFirstResponder = NO;
2815 [UIView setAnimationsEnabled:YES];
2818 - (void)takeKeyboardScreenshotAndDisplay {
2820 UIScreen* screen = _viewController.flutterScreenIfViewLoaded;
2821 UIView* keyboardSnap = [screen snapshotViewAfterScreenUpdates:YES];
2822 keyboardSnap = [keyboardSnap resizableSnapshotViewFromRect:_keyboardRect
2823 afterScreenUpdates:YES
2824 withCapInsets:UIEdgeInsetsZero];
2825 _keyboardView = keyboardSnap;
2826 [_keyboardViewContainer addSubview:_keyboardView];
2827 if (_keyboardViewContainer.superview == nil) {
2829 UIView* rootView = flutterApplication
2830 ? flutterApplication.delegate.window.rootViewController.view
2831 :
self.viewController.viewIfLoaded.window.rootViewController.view;
2832 [rootView addSubview:_keyboardViewContainer];
2834 _keyboardViewContainer.layer.zPosition = NSIntegerMax;
2835 _keyboardViewContainer.frame = _keyboardRect;
2838 - (BOOL)showEditMenu:(NSDictionary*)args API_AVAILABLE(ios(16.0)) {
2839 if (!
self.activeView.isFirstResponder) {
2842 NSDictionary<NSString*, NSNumber*>* encodedTargetRect = args[@"targetRect"];
2843 CGRect globalTargetRect = CGRectMake(
2844 [encodedTargetRect[
@"x"] doubleValue], [encodedTargetRect[
@"y"] doubleValue],
2845 [encodedTargetRect[
@"width"] doubleValue], [encodedTargetRect[
@"height"] doubleValue]);
2846 CGRect localTargetRect = [
self.hostView convertRect:globalTargetRect toView:self.activeView];
2847 [
self.activeView showEditMenuWithTargetRect:localTargetRect items:args[@"items"]];
2851 - (void)hideEditMenu {
2852 [
self.activeView hideEditMenu];
2855 - (void)setEditableSizeAndTransform:(NSDictionary*)dictionary {
2856 NSArray* transform = dictionary[@"transform"];
2857 [_activeView setEditableTransform:transform];
2858 const int leftIndex = 12;
2859 const int topIndex = 13;
2863 CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue],
2864 [dictionary[
@"width"] intValue], [dictionary[
@"height"] intValue]);
2866 CGRectMake(0, 0, [dictionary[
@"width"] intValue], [dictionary[
@"height"] intValue]);
2867 _activeView.tintColor = [UIColor clearColor];
2872 if (@available(iOS 17, *)) {
2880 CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue], 0, 0);
2885 - (void)updateMarkedRect:(NSDictionary*)dictionary {
2886 NSAssert(dictionary[
@"x"] != nil && dictionary[
@"y"] != nil && dictionary[
@"width"] != nil &&
2887 dictionary[
@"height"] != nil,
2888 @"Expected a dictionary representing a CGRect, got %@", dictionary);
2889 CGRect rect = CGRectMake([dictionary[
@"x"] doubleValue], [dictionary[
@"y"] doubleValue],
2890 [dictionary[
@"width"] doubleValue], [dictionary[
@"height"] doubleValue]);
2891 _activeView.markedRect = rect.size.width < 0 && rect.size.height < 0 ?
kInvalidFirstRect : rect;
2894 - (void)setSelectionRects:(NSArray*)encodedRects {
2895 NSMutableArray<FlutterTextSelectionRect*>* rectsAsRect =
2896 [[NSMutableArray alloc] initWithCapacity:[encodedRects count]];
2897 for (NSUInteger i = 0; i < [encodedRects count]; i++) {
2898 NSArray<NSNumber*>* encodedRect = encodedRects[i];
2900 selectionRectWithRect:CGRectMake([encodedRect[0] floatValue],
2901 [encodedRect[1] floatValue],
2902 [encodedRect[2] floatValue],
2903 [encodedRect[3] floatValue])
2904 position:[encodedRect[4] unsignedIntegerValue]
2905 writingDirection:[encodedRect[5] unsignedIntegerValue] == 1
2906 ? NSWritingDirectionLeftToRight
2907 : NSWritingDirectionRightToLeft]];
2913 _activeView.selectionRects = rectsAsRect;
2916 - (void)startLiveTextInput {
2917 if (@available(iOS 15.0, *)) {
2918 if (_activeView == nil || !_activeView.isFirstResponder) {
2921 [_activeView captureTextFromCamera:nil];
2925 - (void)showTextInput {
2926 _activeView.viewResponder = _viewResponder;
2927 [
self addToInputParentViewIfNeeded:_activeView];
2928 [_activeView becomeFirstResponderFromFramework];
2931 - (void)enableActiveViewAccessibility {
2932 if (_activeView.isFirstResponder) {
2933 _activeView.accessibilityEnabled = YES;
2935 [
self removeEnableFlutterTextInputViewAccessibilityTimer];
2938 - (void)hideTextInput {
2939 [_activeView resignFirstResponderFromFramework];
2946 [_activeView removeFromSuperview];
2947 [_inputHider removeFromSuperview];
2952 - (void)triggerAutofillSave:(BOOL)saveEntries {
2953 [_activeView resignFirstResponderFromFramework];
2958 [
self cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO];
2959 [_autofillContext removeAllObjects];
2960 [
self changeInputViewsAutofillVisibility:YES];
2962 [_autofillContext removeAllObjects];
2965 [
self cleanUpViewHierarchy:YES clearText:!saveEntries delayRemoval:NO];
2969 [_activeView removeFromSuperview];
2970 [_inputHider removeFromSuperview];
2975 [
self addToInputParentViewIfNeeded:_activeView];
2978 - (void)setPlatformViewTextInputClient {
2982 [
self removeEnableFlutterTextInputViewAccessibilityTimer];
2983 _activeView.accessibilityEnabled = NO;
2984 [_activeView removeFromSuperview];
2985 [_inputHider removeFromSuperview];
2988 - (void)setTextInputClient:(
int)client withConfiguration:(NSDictionary*)configuration {
2989 [
self resetAllClientIds];
2997 [
self changeInputViewsAutofillVisibility:NO];
3001 case kFlutterAutofillTypeNone:
3002 self.activeView = [
self createInputViewWith:configuration];
3004 case kFlutterAutofillTypeRegular:
3007 self.activeView = [
self updateAndShowAutofillViews:nil
3008 focusedField:configuration
3009 isPasswordRelated:NO];
3011 case kFlutterAutofillTypePassword:
3012 self.activeView = [
self updateAndShowAutofillViews:configuration[kAssociatedAutofillFields]
3013 focusedField:configuration
3014 isPasswordRelated:YES];
3017 [_activeView setTextInputClient:client];
3018 [_activeView reloadInputViews];
3030 [
self cleanUpViewHierarchy:NO clearText:YES delayRemoval:YES];
3040 if (!_enableFlutterTextInputViewAccessibilityTimer) {
3041 _enableFlutterTextInputViewAccessibilityTimer =
3042 [NSTimer scheduledTimerWithTimeInterval:kUITextInputAccessibilityEnablingDelaySeconds
3044 selector:@selector(enableActiveViewAccessibility)
3058 [_autofillContext removeObjectForKey:autofillId];
3061 [newView configureWithDictionary:configuration];
3062 [
self addToInputParentViewIfNeeded:newView];
3066 if (autofillId &&
AutofillTypeOf(field) == kFlutterAutofillTypeNone) {
3067 [_autofillContext removeObjectForKey:autofillId];
3074 focusedField:(NSDictionary*)focusedField
3075 isPasswordRelated:(BOOL)isPassword {
3078 NSAssert(focusedId,
@"autofillId must not be null for the focused field: %@", focusedField);
3083 focused = [
self getOrCreateAutofillableView:focusedField isPasswordAutofill:isPassword];
3084 [_autofillContext removeObjectForKey:focusedId];
3087 for (NSDictionary* field in fields) {
3089 NSAssert(autofillId,
@"autofillId must not be null for field: %@", field);
3091 BOOL hasHints =
AutofillTypeOf(field) != kFlutterAutofillTypeNone;
3092 BOOL isFocused = [focusedId isEqualToString:autofillId];
3095 focused = [
self getOrCreateAutofillableView:field isPasswordAutofill:isPassword];
3100 _autofillContext[autofillId] = isFocused ? focused
3101 : [
self getOrCreateAutofillableView:field
3102 isPasswordAutofill:isPassword];
3105 [_autofillContext removeObjectForKey:autofillId];
3109 NSAssert(focused,
@"The current focused input view must not be nil.");
3119 isPasswordAutofill:(BOOL)needsPasswordAutofill {
3125 inputView = [inputView initWithOwner:self];
3126 [
self addToInputParentViewIfNeeded:inputView];
3129 [inputView configureWithDictionary:field];
3134 - (UIView*)hostView {
3135 UIView* host = _viewController.view;
3136 NSAssert(host !=
nullptr,
3137 @"The application must have a host view since the keyboard client "
3138 @"must be part of the responder chain to function. The host view controller is %@",
3144 - (NSArray<UIView*>*)textInputViews {
3145 return _inputHider.subviews;
3158 - (void)cleanUpViewHierarchy:(BOOL)includeActiveView
3159 clearText:(BOOL)clearText
3160 delayRemoval:(BOOL)delayRemoval {
3161 for (UIView* view in
self.textInputViews) {
3163 (includeActiveView || view != _activeView)) {
3165 if (_autofillContext[inputView.autofillId] != view) {
3167 [inputView replaceRangeLocal:NSMakeRange(0, inputView.text.length) withText:@""];
3170 [inputView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.1];
3172 [inputView removeFromSuperview];
3181 - (void)changeInputViewsAutofillVisibility:(BOOL)newVisibility {
3182 for (UIView* view in
self.textInputViews) {
3185 inputView.isVisibleToAutofill = newVisibility;
3197 - (void)resetAllClientIds {
3198 for (UIView* view in
self.textInputViews) {
3201 [inputView setTextInputClient:0];
3207 if (![inputView isDescendantOfView:_inputHider]) {
3208 [_inputHider addSubview:inputView];
3211 if (_viewController.view == nil) {
3217 UIView* parentView =
self.hostView;
3218 if (_inputHider.superview != parentView) {
3219 [parentView addSubview:_inputHider];
3223 - (void)setTextInputEditingState:(NSDictionary*)state {
3224 [_activeView setTextInputState:state];
3227 - (void)clearTextInputClient {
3228 [_activeView setTextInputClient:0];
3229 _activeView.frame = CGRectZero;
3231 [
self removeEnableFlutterTextInputViewAccessibilityTimer];
3232 _activeView.accessibilityEnabled = NO;
3239 if (_autofillContext.count == 0) {
3241 if (_activeView.isFirstResponder) {
3248 [_activeView removeFromSuperview];
3249 [_inputHider removeFromSuperview];
3260 - (void)updateConfig:(NSDictionary*)dictionary {
3261 BOOL isSecureTextEntry = [dictionary[kSecureTextEntry] boolValue];
3262 for (UIView* view in
self.textInputViews) {
3269 if (inputView.isSecureTextEntry != isSecureTextEntry) {
3270 inputView.secureTextEntry = isSecureTextEntry;
3271 [inputView reloadInputViews];
3277 #pragma mark UIIndirectScribbleInteractionDelegate
3279 - (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3280 isElementFocused:(UIScribbleElementIdentifier)elementIdentifier
3281 API_AVAILABLE(ios(14.0)) {
3282 return _activeView.scribbleFocusStatus == FlutterScribbleFocusStatusFocused;
3285 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3286 focusElementIfNeeded:(UIScribbleElementIdentifier)elementIdentifier
3287 referencePoint:(CGPoint)focusReferencePoint
3288 completion:(
void (^)(UIResponder<UITextInput>* focusedInput))completion
3289 API_AVAILABLE(ios(14.0)) {
3290 _activeView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing;
3291 [_indirectScribbleDelegate flutterTextInputPlugin:self
3292 focusElement:elementIdentifier
3293 atPoint:focusReferencePoint
3294 result:^(id _Nullable result) {
3295 _activeView.scribbleFocusStatus =
3296 FlutterScribbleFocusStatusFocused;
3297 completion(_activeView);
3301 - (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3302 shouldDelayFocusForElement:(UIScribbleElementIdentifier)elementIdentifier
3303 API_AVAILABLE(ios(14.0)) {
3307 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3308 willBeginWritingInElement:(UIScribbleElementIdentifier)elementIdentifier
3309 API_AVAILABLE(ios(14.0)) {
3312 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3313 didFinishWritingInElement:(UIScribbleElementIdentifier)elementIdentifier
3314 API_AVAILABLE(ios(14.0)) {
3317 - (CGRect)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3318 frameForElement:(UIScribbleElementIdentifier)elementIdentifier
3319 API_AVAILABLE(ios(14.0)) {
3320 NSValue* elementValue = [_scribbleElements objectForKey:elementIdentifier];
3321 if (elementValue == nil) {
3324 return [elementValue CGRectValue];
3327 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3328 requestElementsInRect:(CGRect)rect
3330 (
void (^)(NSArray<UIScribbleElementIdentifier>* elements))completion
3331 API_AVAILABLE(ios(14.0)) {
3332 [_indirectScribbleDelegate
3333 flutterTextInputPlugin:self
3334 requestElementsInRect:rect
3335 result:^(id _Nullable result) {
3336 NSMutableArray<UIScribbleElementIdentifier>* elements =
3337 [[NSMutableArray alloc] init];
3338 if ([result isKindOfClass:[NSArray class]]) {
3339 for (NSArray* elementArray in result) {
3340 [elements addObject:elementArray[0]];
3343 valueWithCGRect:CGRectMake(
3344 [elementArray[1] floatValue],
3345 [elementArray[2] floatValue],
3346 [elementArray[3] floatValue],
3347 [elementArray[4] floatValue])]
3348 forKey:elementArray[0]];
3351 completion(elements);
3355 #pragma mark - Methods related to Scribble support
3359 if (@available(iOS 14.0, *)) {
3361 if (parentView != nil) {
3362 UIIndirectScribbleInteraction* scribbleInteraction = [[UIIndirectScribbleInteraction alloc]
3363 initWithDelegate:(id<UIIndirectScribbleInteractionDelegate>)self];
3364 [parentView addInteraction:scribbleInteraction];
3371 - (void)resetViewResponder {
3372 _viewResponder = nil;
3376 #pragma mark FlutterKeySecondaryResponder
3382 - (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) {
3391 - (id)flutterFirstResponder {
3392 if (
self.isFirstResponder) {
3395 for (UIView* subView in
self.subviews) {
3396 UIView* firstResponder = subView.flutterFirstResponder;
3397 if (firstResponder) {
3398 return firstResponder;
void(^ FlutterResult)(id _Nullable result)
FLUTTER_DARWIN_EXPORT NSObject const * FlutterMethodNotImplemented
CGRect localRectFromFrameworkTransform
void resetScribbleInteractionStatusIfEnding
UITextRange * markedTextRange
id< UITextInputDelegate > inputDelegate
API_AVAILABLE(ios(13.0)) @interface FlutterTextPlaceholder UITextRange * selectedTextRange
instancetype initWithOwner
id< FlutterViewResponder > viewResponder
UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0))
UIReturnKeyType returnKeyType
CGRect caretRectForPosition
UIKeyboardAppearance keyboardAppearance
static UITextAutocapitalizationType ToUITextAutoCapitalizationType(NSDictionary *type)
static NSString *const kSetMarkedTextRectMethod
static NSString *const kFinishAutofillContextMethod
BOOL _pendingAutofillRemoval
bool _isFloatingCursorActive
static BOOL IsEmoji(NSString *text, NSRange charRange)
static NSString *const kAutofillHints
static NSString *const kAutofillEditingValue
FlutterTextRange * _selectedTextRange
static NSString *const kSecureTextEntry
bool _enableInteractiveSelection
static BOOL ShouldShowSystemKeyboard(NSDictionary *type)
static NSString *const kEnableInlinePrediction
static NSString *const kShowMethod
static NSString *const kUpdateConfigMethod
static UIKeyboardType ToUIKeyboardType(NSDictionary *type)
CGPoint _floatingCursorOffset
static NSString *const kSmartDashesType
static FLUTTER_ASSERT_ARC const char kTextAffinityDownstream[]
static constexpr double kUITextInputAccessibilityEnablingDelaySeconds
static NSString *const kSetSelectionRectsMethod
typedef NS_ENUM(NSInteger, FlutterAutofillType)
static NSString *const kAutocorrectionType
static NSString *const kSetPlatformViewClientMethod
static NSString *const kAssociatedAutofillFields
static NSString *const kKeyboardType
static const NSTimeInterval kKeyboardAnimationDelaySeconds
static NSString *const kSetEditingStateMethod
BOOL _pendingInputViewRemoval
UIInputViewController * _inputViewController
static NSString *const kAutofillId
static NSString *const kOnInteractiveKeyboardPointerUpMethod
bool _isSystemKeyboardEnabled
static NSString *const kClearClientMethod
static NSString *const kKeyboardAppearance
const CGRect kInvalidFirstRect
BOOL _isResigningFirstResponderFromFramework
static FlutterAutofillType AutofillTypeOf(NSDictionary *configuration)
static NSString *const kSmartQuotesType
static NSString *const kEnableDeltaModel
FlutterScribbleInteractionStatus _scribbleInteractionStatus
static NSString *const kSetClientMethod
static NSString *const kEnableInteractiveSelection
static NSString *const kInputAction
static NSString *const kStartLiveTextInputMethod
static NSString *const kAutofillProperties
static BOOL IsFieldPasswordRelated(NSDictionary *configuration)
BOOL _shouldNotifyFrameworkOnFirstResponderRestore
static const NSTimeInterval kKeyboardAnimationTimeToCompleteion
static BOOL IsApproximatelyEqual(float x, float y, float delta)
static NSString *const kDeprecatedSetSelectionRectsMethod
static const char kTextAffinityUpstream[]
static NSString * AutofillIdFromDictionary(NSDictionary *dictionary)
static UIReturnKeyType ToUIReturnKeyType(NSString *inputType)
static BOOL IsSelectionRectBoundaryCloserToPoint(CGPoint point, CGRect selectionRect, BOOL selectionRectIsRTL, BOOL useTrailingBoundaryOfSelectionRect, CGRect otherSelectionRect, BOOL otherSelectionRectIsRTL, CGFloat verticalPrecision)
static NSString *const kHideMethod
static UITextContentType ToUITextContentType(NSArray< NSString * > *hints)
static NSString *const kSetEditableSizeAndTransformMethod
static NSString *const kOnInteractiveKeyboardPointerMoveMethod
const char * _selectionAffinity
FlutterTextInputPlugin * textInputPlugin
UIApplication * application
instancetype positionWithIndex:(NSUInteger index)
instancetype positionWithIndex:affinity:(NSUInteger index,[affinity] UITextStorageDirection affinity)
UITextStorageDirection affinity
instancetype rangeWithNSRange:(NSRange range)
NSWritingDirection writingDirection
instancetype selectionRectWithRect:position:writingDirection:(CGRect rect,[position] NSUInteger position,[writingDirection] NSWritingDirection writingDirection)
instancetype selectionRectWithRectAndInfo:position:writingDirection:containsStart:containsEnd:isVertical:(CGRect rect,[position] NSUInteger position,[writingDirection] NSWritingDirection writingDirection,[containsStart] BOOL containsStart,[containsEnd] BOOL containsEnd,[isVertical] BOOL isVertical)
FlutterTextInputPlugin * target