Flutter iOS Embedder
FlutterTextInputPlugin.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
7 
8 #import <Foundation/Foundation.h>
9 #import <UIKit/UIKit.h>
10 
11 #include "unicode/uchar.h"
12 
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"
17 
19 
20 static const char kTextAffinityDownstream[] = "TextAffinity.downstream";
21 static const char kTextAffinityUpstream[] = "TextAffinity.upstream";
22 // A delay before enabling the accessibility of FlutterTextInputView after
23 // it is activated.
24 static constexpr double kUITextInputAccessibilityEnablingDelaySeconds = 0.5;
25 
26 // A delay before reenabling the UIView areAnimationsEnabled to YES
27 // in order for becomeFirstResponder to receive the proper value.
28 static const NSTimeInterval kKeyboardAnimationDelaySeconds = 0.1;
29 
30 // A time set for the screenshot to animate back to the assigned position.
31 static const NSTimeInterval kKeyboardAnimationTimeToCompleteion = 0.3;
32 
33 // The "canonical" invalid CGRect, similar to CGRectNull, used to
34 // indicate a CGRect involved in firstRectForRange calculation is
35 // invalid. The specific value is chosen so that if firstRectForRange
36 // returns kInvalidFirstRect, iOS will not show the IME candidates view.
37 const CGRect kInvalidFirstRect = {{-1, -1}, {9999, 9999}};
38 
39 #pragma mark - TextInput channel method names.
40 // See https://api.flutter-io.cn/flutter/services/SystemChannels/textInput-constant.html
41 static NSString* const kShowMethod = @"TextInput.show";
42 static NSString* const kHideMethod = @"TextInput.hide";
43 static NSString* const kSetClientMethod = @"TextInput.setClient";
44 static NSString* const kSetPlatformViewClientMethod = @"TextInput.setPlatformViewClient";
45 static NSString* const kSetEditingStateMethod = @"TextInput.setEditingState";
46 static NSString* const kClearClientMethod = @"TextInput.clearClient";
47 static NSString* const kSetEditableSizeAndTransformMethod =
48  @"TextInput.setEditableSizeAndTransform";
49 static NSString* const kSetMarkedTextRectMethod = @"TextInput.setMarkedTextRect";
50 static NSString* const kFinishAutofillContextMethod = @"TextInput.finishAutofillContext";
51 // TODO(justinmc): Remove the TextInput method constant when the framework has
52 // finished transitioning to using the Scribble channel.
53 // https://github.com/flutter/flutter/pull/104128
54 static NSString* const kDeprecatedSetSelectionRectsMethod = @"TextInput.setSelectionRects";
55 static NSString* const kSetSelectionRectsMethod = @"Scribble.setSelectionRects";
56 static NSString* const kStartLiveTextInputMethod = @"TextInput.startLiveTextInput";
57 static NSString* const kUpdateConfigMethod = @"TextInput.updateConfig";
59  @"TextInput.onPointerMoveForInteractiveKeyboard";
60 static NSString* const kOnInteractiveKeyboardPointerUpMethod =
61  @"TextInput.onPointerUpForInteractiveKeyboard";
62 
63 #pragma mark - TextInputConfiguration Field Names
64 static NSString* const kSecureTextEntry = @"obscureText";
65 static NSString* const kKeyboardType = @"inputType";
66 static NSString* const kKeyboardAppearance = @"keyboardAppearance";
67 static NSString* const kInputAction = @"inputAction";
68 static NSString* const kEnableDeltaModel = @"enableDeltaModel";
69 static NSString* const kEnableInteractiveSelection = @"enableInteractiveSelection";
70 
71 static NSString* const kSmartDashesType = @"smartDashesType";
72 static NSString* const kSmartQuotesType = @"smartQuotesType";
73 
74 static NSString* const kAssociatedAutofillFields = @"fields";
75 
76 // TextInputConfiguration.autofill and sub-field names
77 static NSString* const kAutofillProperties = @"autofill";
78 static NSString* const kAutofillId = @"uniqueIdentifier";
79 static NSString* const kAutofillEditingValue = @"editingValue";
80 static NSString* const kAutofillHints = @"hints";
81 
82 static NSString* const kAutocorrectionType = @"autocorrect";
83 static NSString* const kEnableInlinePrediction = @"enableInlinePrediction";
84 
85 #pragma mark - Static Functions
86 
87 // Determine if the character at `range` of `text` is an emoji.
88 static BOOL IsEmoji(NSString* text, NSRange charRange) {
89  UChar32 codePoint;
90  BOOL gotCodePoint = [text getBytes:&codePoint
91  maxLength:sizeof(codePoint)
92  usedLength:NULL
93  encoding:NSUTF32StringEncoding
94  options:kNilOptions
95  range:charRange
96  remainingRange:NULL];
97  return gotCodePoint && u_hasBinaryProperty(codePoint, UCHAR_EMOJI);
98 }
99 
100 // "TextInputType.none" is a made-up input type that's typically
101 // used when there's an in-app virtual keyboard. If
102 // "TextInputType.none" is specified, disable the system
103 // keyboard.
104 static BOOL ShouldShowSystemKeyboard(NSDictionary* type) {
105  NSString* inputType = type[@"name"];
106  return ![inputType isEqualToString:@"TextInputType.none"];
107 }
108 static UIKeyboardType ToUIKeyboardType(NSDictionary* type) {
109  NSString* inputType = type[@"name"];
110  if ([inputType isEqualToString:@"TextInputType.address"]) {
111  return UIKeyboardTypeDefault;
112  }
113  if ([inputType isEqualToString:@"TextInputType.datetime"]) {
114  return UIKeyboardTypeNumbersAndPunctuation;
115  }
116  if ([inputType isEqualToString:@"TextInputType.emailAddress"]) {
117  return UIKeyboardTypeEmailAddress;
118  }
119  if ([inputType isEqualToString:@"TextInputType.multiline"]) {
120  return UIKeyboardTypeDefault;
121  }
122  if ([inputType isEqualToString:@"TextInputType.name"]) {
123  return UIKeyboardTypeNamePhonePad;
124  }
125  if ([inputType isEqualToString:@"TextInputType.number"]) {
126  if ([type[@"signed"] boolValue]) {
127  return UIKeyboardTypeNumbersAndPunctuation;
128  }
129  if ([type[@"decimal"] boolValue]) {
130  return UIKeyboardTypeDecimalPad;
131  }
132  return UIKeyboardTypeNumberPad;
133  }
134  if ([inputType isEqualToString:@"TextInputType.phone"]) {
135  return UIKeyboardTypePhonePad;
136  }
137  if ([inputType isEqualToString:@"TextInputType.text"]) {
138  return UIKeyboardTypeDefault;
139  }
140  if ([inputType isEqualToString:@"TextInputType.url"]) {
141  return UIKeyboardTypeURL;
142  }
143  if ([inputType isEqualToString:@"TextInputType.visiblePassword"]) {
144  return UIKeyboardTypeASCIICapable;
145  }
146  if ([inputType isEqualToString:@"TextInputType.webSearch"]) {
147  return UIKeyboardTypeWebSearch;
148  }
149  if ([inputType isEqualToString:@"TextInputType.twitter"]) {
150  return UIKeyboardTypeTwitter;
151  }
152  return UIKeyboardTypeDefault;
153 }
154 
155 static UITextAutocapitalizationType ToUITextAutoCapitalizationType(NSDictionary* type) {
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;
163  }
164  return UITextAutocapitalizationTypeNone;
165 }
166 
167 static UIReturnKeyType ToUIReturnKeyType(NSString* inputType) {
168  // Where did the term "unspecified" come from? iOS has a "default" and Android
169  // has "unspecified." These 2 terms seem to mean the same thing but we need
170  // to pick just one. "unspecified" was chosen because "default" is often a
171  // reserved word in languages with switch statements (dart, java, etc).
172  if ([inputType isEqualToString:@"TextInputAction.unspecified"]) {
173  return UIReturnKeyDefault;
174  }
175 
176  if ([inputType isEqualToString:@"TextInputAction.done"]) {
177  return UIReturnKeyDone;
178  }
179 
180  if ([inputType isEqualToString:@"TextInputAction.go"]) {
181  return UIReturnKeyGo;
182  }
183 
184  if ([inputType isEqualToString:@"TextInputAction.send"]) {
185  return UIReturnKeySend;
186  }
187 
188  if ([inputType isEqualToString:@"TextInputAction.search"]) {
189  return UIReturnKeySearch;
190  }
191 
192  if ([inputType isEqualToString:@"TextInputAction.next"]) {
193  return UIReturnKeyNext;
194  }
195 
196  if ([inputType isEqualToString:@"TextInputAction.continueAction"]) {
197  return UIReturnKeyContinue;
198  }
199 
200  if ([inputType isEqualToString:@"TextInputAction.join"]) {
201  return UIReturnKeyJoin;
202  }
203 
204  if ([inputType isEqualToString:@"TextInputAction.route"]) {
205  return UIReturnKeyRoute;
206  }
207 
208  if ([inputType isEqualToString:@"TextInputAction.emergencyCall"]) {
209  return UIReturnKeyEmergencyCall;
210  }
211 
212  if ([inputType isEqualToString:@"TextInputAction.newline"]) {
213  return UIReturnKeyDefault;
214  }
215 
216  // Present default key if bad input type is given.
217  return UIReturnKeyDefault;
218 }
219 
220 static UITextContentType ToUITextContentType(NSArray<NSString*>* hints) {
221  if (!hints || hints.count == 0) {
222  // If no hints are specified, use the default content type nil.
223  return nil;
224  }
225 
226  NSString* hint = hints[0];
227  if ([hint isEqualToString:@"addressCityAndState"]) {
228  return UITextContentTypeAddressCityAndState;
229  }
230 
231  if ([hint isEqualToString:@"addressState"]) {
232  return UITextContentTypeAddressState;
233  }
234 
235  if ([hint isEqualToString:@"addressCity"]) {
236  return UITextContentTypeAddressCity;
237  }
238 
239  if ([hint isEqualToString:@"sublocality"]) {
240  return UITextContentTypeSublocality;
241  }
242 
243  if ([hint isEqualToString:@"streetAddressLine1"]) {
244  return UITextContentTypeStreetAddressLine1;
245  }
246 
247  if ([hint isEqualToString:@"streetAddressLine2"]) {
248  return UITextContentTypeStreetAddressLine2;
249  }
250 
251  if ([hint isEqualToString:@"countryName"]) {
252  return UITextContentTypeCountryName;
253  }
254 
255  if ([hint isEqualToString:@"fullStreetAddress"]) {
256  return UITextContentTypeFullStreetAddress;
257  }
258 
259  if ([hint isEqualToString:@"postalCode"]) {
260  return UITextContentTypePostalCode;
261  }
262 
263  if ([hint isEqualToString:@"location"]) {
264  return UITextContentTypeLocation;
265  }
266 
267  if ([hint isEqualToString:@"creditCardNumber"]) {
268  return UITextContentTypeCreditCardNumber;
269  }
270 
271  if ([hint isEqualToString:@"email"]) {
272  return UITextContentTypeEmailAddress;
273  }
274 
275  if ([hint isEqualToString:@"jobTitle"]) {
276  return UITextContentTypeJobTitle;
277  }
278 
279  if ([hint isEqualToString:@"givenName"]) {
280  return UITextContentTypeGivenName;
281  }
282 
283  if ([hint isEqualToString:@"middleName"]) {
284  return UITextContentTypeMiddleName;
285  }
286 
287  if ([hint isEqualToString:@"familyName"]) {
288  return UITextContentTypeFamilyName;
289  }
290 
291  if ([hint isEqualToString:@"name"]) {
292  return UITextContentTypeName;
293  }
294 
295  if ([hint isEqualToString:@"namePrefix"]) {
296  return UITextContentTypeNamePrefix;
297  }
298 
299  if ([hint isEqualToString:@"nameSuffix"]) {
300  return UITextContentTypeNameSuffix;
301  }
302 
303  if ([hint isEqualToString:@"nickname"]) {
304  return UITextContentTypeNickname;
305  }
306 
307  if ([hint isEqualToString:@"organizationName"]) {
308  return UITextContentTypeOrganizationName;
309  }
310 
311  if ([hint isEqualToString:@"telephoneNumber"]) {
312  return UITextContentTypeTelephoneNumber;
313  }
314 
315  if ([hint isEqualToString:@"password"]) {
316  return UITextContentTypePassword;
317  }
318 
319  if ([hint isEqualToString:@"oneTimeCode"]) {
320  return UITextContentTypeOneTimeCode;
321  }
322 
323  if ([hint isEqualToString:@"newPassword"]) {
324  return UITextContentTypeNewPassword;
325  }
326 
327  return hints[0];
328 }
329 
330 // Retrieves the autofillId from an input field's configuration. Returns
331 // nil if the field is nil and the input field is not a password field.
332 static NSString* AutofillIdFromDictionary(NSDictionary* dictionary) {
333  NSDictionary* autofill = dictionary[kAutofillProperties];
334  if (autofill) {
335  return autofill[kAutofillId];
336  }
337 
338  // When autofill is nil, the field may still need an autofill id
339  // if the field is for password.
340  return [dictionary[kSecureTextEntry] boolValue] ? @"password" : nil;
341 }
342 
343 // # Autofill Implementation Notes:
344 //
345 // Currently there're 2 types of autofills on iOS:
346 // - Regular autofill, including contact information and one-time-code,
347 // takes place in the form of predictive text in the quick type bar.
348 // This type of autofill does not save user input, and the keyboard
349 // currently only populates the focused field when a predictive text entry
350 // is selected by the user.
351 //
352 // - Password autofill, includes automatic strong password and regular
353 // password autofill. The former happens automatically when a
354 // "new password" field is detected and focused, and only that password
355 // field will be populated. The latter appears in the quick type bar when
356 // an eligible input field (which either has a UITextContentTypePassword
357 // contentType, or is a secure text entry) becomes the first responder, and may
358 // fill both the username and the password fields. iOS will attempt
359 // to save user input for both kinds of password fields. It's relatively
360 // tricky to deal with password autofill since it can autofill more than one
361 // field at a time and may employ heuristics based on what other text fields
362 // are in the same view controller.
363 //
364 // When a flutter text field is focused, and autofill is not explicitly disabled
365 // for it ("autofillable"), the framework collects its attributes and checks if
366 // it's in an AutofillGroup, and collects the attributes of other autofillable
367 // text fields in the same AutofillGroup if so. The attributes are sent to the
368 // text input plugin via a "TextInput.setClient" platform channel message. If
369 // autofill is disabled for a text field, its "autofill" field will be nil in
370 // the configuration json.
371 //
372 // The text input plugin then tries to determine which kind of autofill the text
373 // field needs. If the AutofillGroup the text field belongs to contains an
374 // autofillable text field that's password related, this text 's autofill type
375 // will be kFlutterAutofillTypePassword. If autofill is disabled for a text field,
376 // then its type will be kFlutterAutofillTypeNone. Otherwise the text field will
377 // have an autofill type of kFlutterAutofillTypeRegular.
378 //
379 // The text input plugin creates a new UIView for every kFlutterAutofillTypeNone
380 // text field. The UIView instance is never reused for other flutter text fields
381 // since the software keyboard often uses the identity of a UIView to distinguish
382 // different views and provides the same predictive text suggestions or restore
383 // the composing region if a UIView is reused for a different flutter text field.
384 //
385 // The text input plugin creates a new "autofill context" if the text field has
386 // the type of kFlutterAutofillTypePassword, to represent the AutofillGroup of
387 // the text field, and creates one FlutterTextInputView for every text field in
388 // the AutofillGroup.
389 //
390 // The text input plugin will try to reuse a UIView if a flutter text field's
391 // type is kFlutterAutofillTypeRegular, and has the same autofill id.
392 typedef NS_ENUM(NSInteger, FlutterAutofillType) {
393  // The field does not have autofillable content. Additionally if
394  // the field is currently in the autofill context, it will be
395  // removed from the context without triggering autofill save.
396  kFlutterAutofillTypeNone,
397  kFlutterAutofillTypeRegular,
398  kFlutterAutofillTypePassword,
399 };
400 
401 static BOOL IsFieldPasswordRelated(NSDictionary* configuration) {
402  // Autofill is explicitly disabled if the id isn't present.
403  if (!AutofillIdFromDictionary(configuration)) {
404  return NO;
405  }
406 
407  BOOL isSecureTextEntry = [configuration[kSecureTextEntry] boolValue];
408  if (isSecureTextEntry) {
409  return YES;
410  }
411 
412  NSDictionary* autofill = configuration[kAutofillProperties];
413  UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]);
414 
415  if ([contentType isEqualToString:UITextContentTypePassword] ||
416  [contentType isEqualToString:UITextContentTypeUsername]) {
417  return YES;
418  }
419 
420  if ([contentType isEqualToString:UITextContentTypeNewPassword]) {
421  return YES;
422  }
423 
424  return NO;
425 }
426 
427 static FlutterAutofillType AutofillTypeOf(NSDictionary* configuration) {
428  for (NSDictionary* field in configuration[kAssociatedAutofillFields]) {
429  if (IsFieldPasswordRelated(field)) {
430  return kFlutterAutofillTypePassword;
431  }
432  }
433 
434  if (IsFieldPasswordRelated(configuration)) {
435  return kFlutterAutofillTypePassword;
436  }
437 
438  NSDictionary* autofill = configuration[kAutofillProperties];
439  UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]);
440  return !autofill || [contentType isEqualToString:@""] ? kFlutterAutofillTypeNone
441  : kFlutterAutofillTypeRegular;
442 }
443 
444 static BOOL IsApproximatelyEqual(float x, float y, float delta) {
445  return fabsf(x - y) <= delta;
446 }
447 
448 // This is a helper function for floating cursor selection logic to determine which text
449 // position is closer to a point.
450 // Checks whether point should be considered closer to selectionRect compared to
451 // otherSelectionRect.
452 //
453 // If `useTrailingBoundaryOfSelectionRect` is not set, it uses the leading-center point
454 // on selectionRect and otherSelectionRect to compare.
455 // For left-to-right text, this means the left-center point, and for right-to-left text,
456 // this means the right-center point.
457 //
458 // If useTrailingBoundaryOfSelectionRect is set, the trailing-center point on selectionRect
459 // will be used instead of the leading-center point, while leading-center point is still used
460 // for otherSelectionRect.
461 //
462 // This uses special (empirically determined using a 1st gen iPad pro, 9.7" model running
463 // iOS 14.7.1) logic for determining the closer rect, rather than a simple distance calculation.
464 // - First, the rect with closer y distance wins.
465 // - Otherwise (same y distance):
466 // - If the point is above bottom of the rect, the rect boundary with closer x distance wins.
467 // - Otherwise (point is below bottom of the rect), the rect boundary with farthest x wins.
468 // This is because when the point is below the bottom line of text, we want to select the
469 // whole line of text, so we mark the farthest rect as closest.
470 static BOOL IsSelectionRectBoundaryCloserToPoint(CGPoint point,
471  CGRect selectionRect,
472  BOOL selectionRectIsRTL,
473  BOOL useTrailingBoundaryOfSelectionRect,
474  CGRect otherSelectionRect,
475  BOOL otherSelectionRectIsRTL,
476  CGFloat verticalPrecision) {
477  // The point is inside the selectionRect's corresponding half-rect area.
478  if (CGRectContainsPoint(
479  CGRectMake(
480  selectionRect.origin.x + ((useTrailingBoundaryOfSelectionRect ^ selectionRectIsRTL)
481  ? 0.5 * selectionRect.size.width
482  : 0),
483  selectionRect.origin.y, 0.5 * selectionRect.size.width, selectionRect.size.height),
484  point)) {
485  return YES;
486  }
487  // pointForSelectionRect is either leading-center or trailing-center point of selectionRect.
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);
494 
495  // pointForOtherSelectionRect is the leading-center point of otherSelectionRect.
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);
501 
502  // This serves a similar purpose to IsApproximatelyEqual, allowing a little buffer before
503  // declaring something closer vertically to account for the small variations in size and position
504  // of SelectionRects, especially when dealing with emoji.
505  BOOL isCloserVertically = yDist < yDistOther - verticalPrecision;
506  BOOL isEqualVertically = IsApproximatelyEqual(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;
510  // Is "farther away", or is closer to the end of the text line.
511  BOOL isFarther;
512  if (selectionRectIsRTL) {
513  isFarther = selectionRect.origin.x < otherSelectionRect.origin.x;
514  } else {
515  isFarther = selectionRect.origin.x +
516  (useTrailingBoundaryOfSelectionRect ? selectionRect.size.width : 0) >
517  otherSelectionRect.origin.x;
518  }
519  return (isCloserVertically ||
520  (isEqualVertically &&
521  ((isAboveBottomOfLine && isCloserHorizontally) || (isBelowBottomOfLine && isFarther))));
522 }
523 
524 #pragma mark - FlutterTextPosition
525 
526 @implementation FlutterTextPosition
527 
528 + (instancetype)positionWithIndex:(NSUInteger)index {
529  return [[FlutterTextPosition alloc] initWithIndex:index affinity:UITextStorageDirectionForward];
530 }
531 
532 + (instancetype)positionWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity {
533  return [[FlutterTextPosition alloc] initWithIndex:index affinity:affinity];
534 }
535 
536 - (instancetype)initWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity {
537  self = [super init];
538  if (self) {
539  _index = index;
540  _affinity = affinity;
541  }
542  return self;
543 }
544 
545 @end
546 
547 #pragma mark - FlutterTextRange
548 
549 @implementation FlutterTextRange
550 
551 + (instancetype)rangeWithNSRange:(NSRange)range {
552  return [[FlutterTextRange alloc] initWithNSRange:range];
553 }
554 
555 - (instancetype)initWithNSRange:(NSRange)range {
556  self = [super init];
557  if (self) {
558  _range = range;
559  }
560  return self;
561 }
562 
563 - (UITextPosition*)start {
564  return [FlutterTextPosition positionWithIndex:self.range.location
565  affinity:UITextStorageDirectionForward];
566 }
567 
568 - (UITextPosition*)end {
569  return [FlutterTextPosition positionWithIndex:self.range.location + self.range.length
570  affinity:UITextStorageDirectionBackward];
571 }
572 
573 - (BOOL)isEmpty {
574  return self.range.length == 0;
575 }
576 
577 - (id)copyWithZone:(NSZone*)zone {
578  return [[FlutterTextRange allocWithZone:zone] initWithNSRange:self.range];
579 }
580 
581 - (BOOL)isEqualTo:(FlutterTextRange*)other {
582  return NSEqualRanges(self.range, other.range);
583 }
584 @end
585 
586 #pragma mark - FlutterTokenizer
587 
588 @interface FlutterTokenizer ()
589 
590 @property(nonatomic, weak) FlutterTextInputView* textInputView;
591 
592 @end
593 
594 @implementation FlutterTokenizer
595 
596 - (instancetype)initWithTextInput:(UIResponder<UITextInput>*)textInput {
597  NSAssert([textInput isKindOfClass:[FlutterTextInputView class]],
598  @"The FlutterTokenizer can only be used in a FlutterTextInputView");
599  self = [super initWithTextInput:textInput];
600  if (self) {
601  _textInputView = (FlutterTextInputView*)textInput;
602  }
603  return self;
604 }
605 
606 - (UITextRange*)rangeEnclosingPosition:(UITextPosition*)position
607  withGranularity:(UITextGranularity)granularity
608  inDirection:(UITextDirection)direction {
609  UITextRange* result;
610  switch (granularity) {
611  case UITextGranularityLine:
612  // The default UITextInputStringTokenizer does not handle line granularity
613  // correctly. We need to implement our own line tokenizer.
614  result = [self lineEnclosingPosition:position inDirection:direction];
615  break;
616  case UITextGranularityCharacter:
617  case UITextGranularityWord:
618  case UITextGranularitySentence:
619  case UITextGranularityParagraph:
620  case UITextGranularityDocument:
621  // The UITextInputStringTokenizer can handle all these cases correctly.
622  result = [super rangeEnclosingPosition:position
623  withGranularity:granularity
624  inDirection:direction];
625  break;
626  }
627  return result;
628 }
629 
630 - (UITextRange*)lineEnclosingPosition:(UITextPosition*)position
631  inDirection:(UITextDirection)direction {
632  // TODO(hellohuanlin): remove iOS 17 check. The same logic should apply to older iOS version.
633  if (@available(iOS 17.0, *)) {
634  // According to the API doc if the text position is at a text-unit boundary, it is considered
635  // enclosed only if the next position in the given direction is entirely enclosed. Link:
636  // https://developer.apple.com/documentation/uikit/uitextinputtokenizer/1614464-rangeenclosingposition?language=objc
637  FlutterTextPosition* flutterPosition = (FlutterTextPosition*)position;
638  if (flutterPosition.index > _textInputView.text.length ||
639  (flutterPosition.index == _textInputView.text.length &&
640  direction == UITextStorageDirectionForward)) {
641  return nil;
642  }
643  }
644 
645  // Gets the first line break position after the input position.
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];
653  // Gets the first line break position before the input position.
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];
661 
662  return [_textInputView textRangeFromPosition:lineBreakBefore toPosition:lineBreakAfter];
663 }
664 
665 @end
666 
667 #pragma mark - FlutterTextSelectionRect
668 
669 @implementation FlutterTextSelectionRect
670 
671 // Synthesize properties declared readonly in UITextSelectionRect.
672 @synthesize rect = _rect;
673 @synthesize writingDirection = _writingDirection;
674 @synthesize containsStart = _containsStart;
675 @synthesize containsEnd = _containsEnd;
676 @synthesize isVertical = _isVertical;
677 
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 {
684  return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect
685  position:position
686  writingDirection:writingDirection
687  containsStart:containsStart
688  containsEnd:containsEnd
689  isVertical:isVertical];
690 }
691 
692 + (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position {
693  return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect
694  position:position
695  writingDirection:NSWritingDirectionNatural
696  containsStart:NO
697  containsEnd:NO
698  isVertical:NO];
699 }
700 
701 + (instancetype)selectionRectWithRect:(CGRect)rect
702  position:(NSUInteger)position
703  writingDirection:(NSWritingDirection)writingDirection {
704  return [[FlutterTextSelectionRect alloc] initWithRectAndInfo:rect
705  position:position
706  writingDirection:writingDirection
707  containsStart:NO
708  containsEnd:NO
709  isVertical:NO];
710 }
711 
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 {
718  self = [super init];
719  if (self) {
720  self.rect = rect;
721  self.position = position;
722  self.writingDirection = writingDirection;
723  self.containsStart = containsStart;
724  self.containsEnd = containsEnd;
725  self.isVertical = isVertical;
726  }
727  return self;
728 }
729 
730 - (BOOL)isRTL {
731  return _writingDirection == NSWritingDirectionRightToLeft;
732 }
733 
734 @end
735 
736 #pragma mark - FlutterTextPlaceholder
737 
738 @implementation FlutterTextPlaceholder
739 
740 - (NSArray<UITextSelectionRect*>*)rects {
741  // Returning anything other than an empty array here seems to cause PencilKit to enter an
742  // infinite loop of allocating placeholders until the app crashes
743  return @[];
744 }
745 
746 @end
747 
748 // A FlutterTextInputView that masquerades as a UITextField, and forwards
749 // selectors it can't respond to a shared UITextField instance.
750 //
751 // Relevant API docs claim that password autofill supports any custom view
752 // that adopts the UITextInput protocol, automatic strong password seems to
753 // currently only support UITextFields, and password saving only supports
754 // UITextFields and UITextViews, as of iOS 13.5.
756 @property(nonatomic, retain, readonly) UITextField* textField;
757 @end
758 
759 @implementation FlutterSecureTextInputView {
760  UITextField* _textField;
761 }
762 
763 - (UITextField*)textField {
764  if (!_textField) {
765  _textField = [[UITextField alloc] init];
766  }
767  return _textField;
768 }
769 
770 - (BOOL)isKindOfClass:(Class)aClass {
771  return [super isKindOfClass:aClass] || (aClass == [UITextField class]);
772 }
773 
774 - (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector {
775  NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];
776  if (!signature) {
777  signature = [self.textField methodSignatureForSelector:aSelector];
778  }
779  return signature;
780 }
781 
782 - (void)forwardInvocation:(NSInvocation*)anInvocation {
783  [anInvocation invokeWithTarget:self.textField];
784 }
785 
786 @end
787 
789 @property(nonatomic, readonly, weak) id<FlutterTextInputDelegate> textInputDelegate;
790 @property(nonatomic, readonly) UIView* hostView;
791 @end
792 
793 @interface FlutterTextInputView ()
794 @property(nonatomic, readonly, weak) FlutterTextInputPlugin* textInputPlugin;
795 @property(nonatomic, copy) NSString* autofillId;
796 @property(nonatomic, readonly) CATransform3D editableTransform;
797 @property(nonatomic, assign) CGRect markedRect;
798 // Disables the cursor from dismissing when firstResponder is resigned
799 @property(nonatomic, assign) BOOL preventCursorDismissWhenResignFirstResponder;
800 @property(nonatomic) BOOL isVisibleToAutofill;
801 @property(nonatomic, assign) BOOL accessibilityEnabled;
802 @property(nonatomic, assign) int textInputClient;
803 // The composed character that is temporarily removed by the keyboard API.
804 // This is cleared at the start of each keyboard interaction. (Enter a character, delete a character
805 // etc)
806 @property(nonatomic, copy) NSString* temporarilyDeletedComposedCharacter;
807 @property(nonatomic, assign) CGRect editMenuTargetRect;
808 @property(nonatomic, strong) NSArray<NSDictionary*>* editMenuItems;
809 
810 - (void)setEditableTransform:(NSArray*)matrix;
811 - (BOOL)becomeFirstResponderFromFramework;
812 - (BOOL)resignFirstResponderFromFramework;
813 @end
814 
815 @implementation FlutterTextInputView {
816  int _textInputClient;
817  const char* _selectionAffinity;
819  UIInputViewController* _inputViewController;
821  FlutterScribbleInteractionStatus _scribbleInteractionStatus;
823  // Whether to show the system keyboard when this view
824  // becomes the first responder. Typically set to false
825  // when the app shows its own in-flutter keyboard.
831  // A non-framework resign arms a one-shot notification for this exact view. The responder API
832  // does not reveal which object, if any, takes focus next, so a handoff to a native input can arm
833  // it too. Framework responder calls and client updates cancel it before UIKit can restore stale
834  // input state.
836  UITextInteraction* _textInteraction API_AVAILABLE(ios(13.0));
837 }
838 
839 @synthesize tokenizer = _tokenizer;
840 
841 - (instancetype)initWithOwner:(FlutterTextInputPlugin*)textInputPlugin {
842  self = [super initWithFrame:CGRectZero];
843  if (self) {
844  _textInputPlugin = textInputPlugin;
845  _textInputClient = 0;
847  _preventCursorDismissWhenResignFirstResponder = NO;
848 
849  // UITextInput
850  _text = [[NSMutableString alloc] init];
851  _selectedTextRange = [[FlutterTextRange alloc] initWithNSRange:NSMakeRange(0, 0)];
852  _markedRect = kInvalidFirstRect;
854  _scribbleInteractionStatus = FlutterScribbleInteractionStatusNone;
855  _pendingDeltas = [[NSMutableArray alloc] init];
856  // Initialize with the zero matrix which is not
857  // an affine transform.
858  _editableTransform = CATransform3D();
859 
860  // UITextInputTraits
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;
877  }
878 
879  if (@available(iOS 14.0, *)) {
880  UIScribbleInteraction* interaction = [[UIScribbleInteraction alloc] initWithDelegate:self];
881  [self addInteraction:interaction];
882  }
883  }
884 
885  if (@available(iOS 16.0, *)) {
886  _editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
887  [self addInteraction:_editMenuInteraction];
888  }
889 
890  return self;
891 }
892 
893 - (void)handleSearchWebAction {
894  [self.textInputDelegate flutterTextInputView:self
895  searchWebWithSelectedText:[self textInRange:_selectedTextRange]];
896 }
897 
898 - (void)handleLookUpAction {
899  [self.textInputDelegate flutterTextInputView:self
900  lookUpSelectedText:[self textInRange:_selectedTextRange]];
901 }
902 
903 - (void)handleShareAction {
904  [self.textInputDelegate flutterTextInputView:self
905  shareSelectedText:[self textInRange:_selectedTextRange]];
906 }
907 
908 - (void)handleTranslateAction {
909  [self.textInputDelegate flutterTextInputView:self
910  translateSelectedText:[self textInRange:_selectedTextRange]];
911 }
912 
913 // DFS algorithm to search a UICommand from the menu tree.
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];
923  if (result) {
924  return result;
925  }
926  }
927  return nil;
928  } else {
929  return nil;
930  }
931 }
932 
933 - (void)addBasicEditingCommandToItems:(NSMutableArray*)items
934  type:(NSString*)type
935  selector:(SEL)selector
936  suggestedMenu:(UIMenu*)suggestedMenu {
937  UICommand* command = [self searchCommandWithSelector:selector element:suggestedMenu];
938  if (command) {
939  [items addObject:command];
940  } else {
941  NSString* errorMessage =
942  [NSString stringWithFormat:@"Cannot find context menu item of type \"%@\".", type];
943  [FlutterLogger logError:errorMessage];
944  }
945 }
946 
947 - (void)addAdditionalBasicCommandToItems:(NSMutableArray*)items
948  type:(NSString*)type
949  selector:(SEL)selector
950  encodedItem:(NSDictionary<NSString*, id>*)encodedItem {
951  NSString* title = encodedItem[@"title"];
952  if (title) {
953  UICommand* command = [UICommand commandWithTitle:title
954  image:nil
955  action:selector
956  propertyList:nil];
957  [items addObject:command];
958  } else {
959  NSString* errorMessage =
960  [NSString stringWithFormat:@"Missing title for context menu item of type \"%@\".", type];
961  [FlutterLogger logError:errorMessage];
962  }
963 }
964 
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;
971  }
972 
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
978  type:type
979  selector:@selector(copy:)
980  suggestedMenu:suggestedMenu];
981  } else if ([type isEqualToString:@"paste"]) {
982  [self addBasicEditingCommandToItems:items
983  type:type
984  selector:@selector(paste:)
985  suggestedMenu:suggestedMenu];
986  } else if ([type isEqualToString:@"cut"]) {
987  [self addBasicEditingCommandToItems:items
988  type:type
989  selector:@selector(cut:)
990  suggestedMenu:suggestedMenu];
991  } else if ([type isEqualToString:@"delete"]) {
992  [self addBasicEditingCommandToItems:items
993  type:type
994  selector:@selector(delete:)
995  suggestedMenu:suggestedMenu];
996  } else if ([type isEqualToString:@"selectAll"]) {
997  [self addBasicEditingCommandToItems:items
998  type:type
999  selector:@selector(selectAll:)
1000  suggestedMenu:suggestedMenu];
1001  } else if ([type isEqualToString:@"searchWeb"]) {
1002  [self addAdditionalBasicCommandToItems:items
1003  type:type
1004  selector:@selector(handleSearchWebAction)
1005  encodedItem:encodedItem];
1006  } else if ([type isEqualToString:@"share"]) {
1007  [self addAdditionalBasicCommandToItems:items
1008  type:type
1009  selector:@selector(handleShareAction)
1010  encodedItem:encodedItem];
1011  } else if ([type isEqualToString:@"lookUp"]) {
1012  [self addAdditionalBasicCommandToItems:items
1013  type:type
1014  selector:@selector(handleLookUpAction)
1015  encodedItem:encodedItem];
1016  } else if ([type isEqualToString:@"captureTextFromCamera"]) {
1017  if (@available(iOS 15.0, *)) {
1018  [self addBasicEditingCommandToItems:items
1019  type:type
1020  selector:@selector(captureTextFromCamera:)
1021  suggestedMenu:suggestedMenu];
1022  }
1023  } else if ([type isEqualToString:@"translate"]) {
1024  if (@available(iOS 17.4, *)) {
1025  [self addAdditionalBasicCommandToItems:items
1026  type:type
1027  selector:@selector(handleTranslateAction)
1028  encodedItem:encodedItem];
1029  }
1030  } else if ([type isEqualToString:@"custom"]) {
1031  NSString* callbackId = encodedItem[@"id"];
1032  NSString* title = encodedItem[@"title"];
1033  if (callbackId && title) {
1034  __weak FlutterTextInputView* weakSelf = self;
1035  UIAction* action = [UIAction
1036  actionWithTitle:title
1037  image:nil
1038  identifier:nil
1039  handler:^(__kindof UIAction* _Nonnull action) {
1040  FlutterTextInputView* strongSelf = weakSelf;
1041  if (strongSelf) {
1042  [strongSelf.textInputDelegate flutterTextInputView:strongSelf
1043  performContextMenuCustomActionWithActionID:callbackId
1044  textInputClient:strongSelf->
1045  _textInputClient];
1046  }
1047  }];
1048  [items addObject:action];
1049  }
1050  }
1051  }
1052  return [UIMenu menuWithChildren:items];
1053 }
1054 
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];
1061 }
1062 
1063 - (CGRect)editMenuInteraction:(UIEditMenuInteraction*)interaction
1064  targetRectForConfiguration:(UIEditMenuConfiguration*)configuration API_AVAILABLE(ios(16.0)) {
1065  return _editMenuTargetRect;
1066 }
1067 
1068 - (void)showEditMenuWithTargetRect:(CGRect)targetRect
1069  items:(NSArray<NSDictionary*>*)items API_AVAILABLE(ios(16.0)) {
1070  _editMenuTargetRect = targetRect;
1071  _editMenuItems = items;
1072 
1073  UIEditMenuConfiguration* config =
1074  [UIEditMenuConfiguration configurationWithIdentifier:nil sourcePoint:CGPointZero];
1075  [self.editMenuInteraction presentEditMenuWithConfiguration:config];
1076 }
1077 
1078 - (void)hideEditMenu API_AVAILABLE(ios(16.0)) {
1079  [self.editMenuInteraction dismissMenu];
1080 }
1081 
1082 - (void)configureWithDictionary:(NSDictionary*)configuration {
1083  NSDictionary* inputType = configuration[kKeyboardType];
1084  NSString* keyboardAppearance = configuration[kKeyboardAppearance];
1085  NSDictionary* autofill = configuration[kAutofillProperties];
1086 
1087  self.secureTextEntry = [configuration[kSecureTextEntry] boolValue];
1088  self.enableDeltaModel = [configuration[kEnableDeltaModel] boolValue];
1089 
1091  self.keyboardType = ToUIKeyboardType(inputType);
1092  self.returnKeyType = ToUIReturnKeyType(configuration[kInputAction]);
1093  self.autocapitalizationType = ToUITextAutoCapitalizationType(configuration);
1094  _enableInteractiveSelection = [configuration[kEnableInteractiveSelection] boolValue];
1095  NSString* smartDashesType = configuration[kSmartDashesType];
1096  // This index comes from the SmartDashesType enum in the framework.
1097  bool smartDashesIsDisabled = smartDashesType && [smartDashesType isEqualToString:@"0"];
1098  self.smartDashesType = smartDashesIsDisabled ? UITextSmartDashesTypeNo : UITextSmartDashesTypeYes;
1099  NSString* smartQuotesType = configuration[kSmartQuotesType];
1100  // This index comes from the SmartQuotesType enum in the framework.
1101  bool smartQuotesIsDisabled = smartQuotesType && [smartQuotesType isEqualToString:@"0"];
1102  self.smartQuotesType = smartQuotesIsDisabled ? UITextSmartQuotesTypeNo : UITextSmartQuotesTypeYes;
1103  if ([keyboardAppearance isEqualToString:@"Brightness.dark"]) {
1104  self.keyboardAppearance = UIKeyboardAppearanceDark;
1105  } else if ([keyboardAppearance isEqualToString:@"Brightness.light"]) {
1106  self.keyboardAppearance = UIKeyboardAppearanceLight;
1107  } else {
1108  self.keyboardAppearance = UIKeyboardAppearanceDefault;
1109  }
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;
1116  self.autofillId = AutofillIdFromDictionary(configuration);
1117  if (autofill == nil) {
1118  self.textContentType = @"";
1119  } else {
1120  self.textContentType = ToUITextContentType(autofill[kAutofillHints]);
1121  [self setTextInputState:autofill[kAutofillEditingValue]];
1122  NSAssert(_autofillId, @"The autofill configuration must contain an autofill id");
1123  }
1124  // The input field needs to be visible for the system autofill
1125  // to find it.
1126  self.isVisibleToAutofill = autofill || _secureTextEntry;
1127 
1128  if (@available(iOS 17.0, *)) {
1129  // iOS 17+ inline prediction. Only enabled when explicitly set to true;
1130  // all other values (nil, NSNull, false) disable it.
1131  id enableInlinePrediction = configuration[kEnableInlinePrediction];
1132  BOOL enabled = enableInlinePrediction != nil && enableInlinePrediction != [NSNull null] &&
1133  [enableInlinePrediction boolValue];
1134  self.inlinePredictionType =
1135  enabled ? UITextInlinePredictionTypeYes : UITextInlinePredictionTypeNo;
1136  }
1137 }
1138 
1139 - (UITextContentType)textContentType {
1140  return _textContentType;
1141 }
1142 
1143 // Prevent UIKit from showing selection handles or highlights. This is needed
1144 // because Scribble interactions require the view to have it's actual frame on
1145 // the screen. They're not needed on iOS 17 with the new
1146 // UITextSelectionDisplayInteraction API.
1147 //
1148 // These are undocumented methods. On iOS 17, the insertion point color is also
1149 // used as the highlighted background of the selected IME candidate:
1150 // https://github.com/flutter/flutter/issues/132548
1151 // So the respondsToSelector method is overridden to return NO for this method
1152 // on iOS 17+.
1153 - (UIColor*)insertionPointColor {
1154  return [UIColor clearColor];
1155 }
1156 
1157 - (UIColor*)selectionBarColor {
1158  return [UIColor clearColor];
1159 }
1160 
1161 - (UIColor*)selectionHighlightColor {
1162  return [UIColor clearColor];
1163 }
1164 
1165 - (UIInputViewController*)inputViewController {
1167  return nil;
1168  }
1169 
1170  if (!_inputViewController) {
1171  _inputViewController = [[UIInputViewController alloc] init];
1172  }
1173  return _inputViewController;
1174 }
1175 
1176 - (id<FlutterTextInputDelegate>)textInputDelegate {
1177  return _textInputPlugin.textInputDelegate;
1178 }
1179 
1180 - (BOOL)respondsToSelector:(SEL)selector {
1181  if (@available(iOS 17.0, *)) {
1182  // See the comment on this method.
1183  if (selector == @selector(insertionPointColor)) {
1184  return NO;
1185  }
1186  }
1187  return [super respondsToSelector:selector];
1188 }
1189 
1190 - (void)setTextInputClient:(int)client {
1192  _textInputClient = client;
1193  _hasPlaceholder = NO;
1194 }
1195 
1196 - (UITextInteraction*)textInteraction API_AVAILABLE(ios(13.0)) {
1197  if (!_textInteraction) {
1198  _textInteraction = [UITextInteraction textInteractionForMode:UITextInteractionModeEditable];
1199  _textInteraction.textInput = self;
1200  }
1201  return _textInteraction;
1202 }
1203 
1204 - (void)setTextInputState:(NSDictionary*)state {
1205  // [UITextInteraction willMoveToView:] sometimes sets the textInput's inputDelegate
1206  // to nil. This is likely a bug in UIKit. In order to inform the keyboard of text
1207  // and selection changes when that happens, add a dummy UITextInteraction to this
1208  // view so it sets a valid inputDelegate that we can call textWillChange et al. on.
1209  // See https://github.com/flutter/engine/pull/32881.
1210  if (!self.inputDelegate && self.isFirstResponder) {
1211  [self addInteraction:self.textInteraction];
1212  }
1213 
1214  NSString* newText = state[@"text"];
1215  BOOL textChanged = ![self.text isEqualToString:newText];
1216  if (textChanged) {
1217  [self.inputDelegate textWillChange:self];
1218  [self.text setString:newText];
1219  }
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))
1224  forText:self.text];
1225 
1226  self.markedTextRange =
1227  composingRange.length > 0 ? [FlutterTextRange rangeWithNSRange:composingRange] : nil;
1228 
1229  NSRange selectedRange = [self clampSelectionFromBase:[state[@"selectionBase"] intValue]
1230  extent:[state[@"selectionExtent"] intValue]
1231  forText:self.text];
1232 
1233  NSRange oldSelectedRange = [(FlutterTextRange*)self.selectedTextRange range];
1234  if (!NSEqualRanges(selectedRange, oldSelectedRange)) {
1235  [self.inputDelegate selectionWillChange:self];
1236 
1237  [self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:selectedRange]];
1238 
1240  if ([state[@"selectionAffinity"] isEqualToString:@(kTextAffinityUpstream)]) {
1242  }
1243  [self.inputDelegate selectionDidChange:self];
1244  }
1245 
1246  if (textChanged) {
1247  [self.inputDelegate textDidChange:self];
1248  }
1249 
1250  if (_textInteraction) {
1251  [self removeInteraction:_textInteraction];
1252  }
1253 }
1254 
1255 // Forward touches to the viewResponder to allow tapping inside the UITextField as normal.
1256 - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
1257  _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
1258  [self resetScribbleInteractionStatusIfEnding];
1259  [self.viewResponder touchesBegan:touches withEvent:event];
1260 }
1261 
1262 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
1263  [self.viewResponder touchesMoved:touches withEvent:event];
1264 }
1265 
1266 - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
1267  [self.viewResponder touchesEnded:touches withEvent:event];
1268 }
1269 
1270 - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
1271  [self.viewResponder touchesCancelled:touches withEvent:event];
1272 }
1273 
1274 - (void)touchesEstimatedPropertiesUpdated:(NSSet*)touches {
1275  [self.viewResponder touchesEstimatedPropertiesUpdated:touches];
1276 }
1277 
1278 // Extracts the selection information from the editing state dictionary.
1279 //
1280 // The state may contain an invalid selection, such as when no selection was
1281 // explicitly set in the framework. This is handled here by setting the
1282 // selection to (0,0). In contrast, Android handles this situation by
1283 // clearing the selection, but the result in both cases is that the cursor
1284 // is placed at the beginning of the field.
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];
1292 }
1293 
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);
1298 }
1299 
1300 - (BOOL)isVisibleToAutofill {
1301  return self.frame.size.width > 0 && self.frame.size.height > 0;
1302 }
1303 
1304 // An input view is generally ignored by password autofill attempts, if it's
1305 // not the first responder and is zero-sized. For input fields that are in the
1306 // autofill context but do not belong to the current autofill group, setting
1307 // their frames to CGRectZero prevents ios autofill from taking them into
1308 // account.
1309 - (void)setIsVisibleToAutofill:(BOOL)isVisibleToAutofill {
1310  // This probably needs to change (think it is getting overwritten by the updateSizeAndTransform
1311  // stuff for now).
1312  self.frame = isVisibleToAutofill ? CGRectMake(0, 0, 1, 1) : CGRectZero;
1313 }
1314 
1315 #pragma mark UIScribbleInteractionDelegate
1316 
1317 // Checks whether Scribble features are possibly available – meaning this is an iPad running iOS
1318 // 14 or higher.
1319 - (BOOL)isScribbleAvailable {
1320  if (@available(iOS 14.0, *)) {
1321  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
1322  return YES;
1323  }
1324  }
1325  return NO;
1326 }
1327 
1328 - (void)scribbleInteractionWillBeginWriting:(UIScribbleInteraction*)interaction
1329  API_AVAILABLE(ios(14.0)) {
1330  _scribbleInteractionStatus = FlutterScribbleInteractionStatusStarted;
1331  [self.textInputDelegate flutterTextInputViewScribbleInteractionBegan:self];
1332 }
1333 
1334 - (void)scribbleInteractionDidFinishWriting:(UIScribbleInteraction*)interaction
1335  API_AVAILABLE(ios(14.0)) {
1336  _scribbleInteractionStatus = FlutterScribbleInteractionStatusEnding;
1337  [self.textInputDelegate flutterTextInputViewScribbleInteractionFinished:self];
1338 }
1339 
1340 - (BOOL)scribbleInteraction:(UIScribbleInteraction*)interaction
1341  shouldBeginAtLocation:(CGPoint)location API_AVAILABLE(ios(14.0)) {
1342  return YES;
1343 }
1344 
1345 - (BOOL)scribbleInteractionShouldDelayFocus:(UIScribbleInteraction*)interaction
1346  API_AVAILABLE(ios(14.0)) {
1347  return NO;
1348 }
1349 
1350 #pragma mark - UIResponder Overrides
1351 
1352 - (BOOL)canBecomeFirstResponder {
1353  // Only the currently focused input field can
1354  // become the first responder. This prevents iOS
1355  // from changing focus by itself (the framework
1356  // focus will be out of sync if that happens).
1357  return _textInputClient != 0;
1358 }
1359 
1360 - (BOOL)becomeFirstResponder {
1361  BOOL wasFirstResponder = self.isFirstResponder;
1362  BOOL success = [super becomeFirstResponder];
1363  if (success && !wasFirstResponder && self.isFirstResponder &&
1366  int client = _textInputClient;
1367  __weak FlutterTextInputView* weakSelf = self;
1368  FlutterResult handleResult = ^(id result) {
1369  [weakSelf handleFirstResponderRestoreResult:result client:client];
1370  };
1371  // Existing framework client and FocusNode guards decide whether to accept the restored focus.
1372  [self.textInputDelegate flutterTextInputView:self
1373  didRestoreFirstResponderWithTextInputClient:client
1374  result:handleResult];
1375  }
1376  return success;
1377 }
1378 
1379 - (void)handleFirstResponderRestoreResult:(id)result client:(int)client {
1380  if ([result isKindOfClass:[NSNumber class]] && [result boolValue]) {
1381  return;
1382  }
1383  // The framework declined the restored focus or failed to answer. Don't leave the keyboard up
1384  // without a framework client behind it, unless the view has been given another client since the
1385  // restore was reported.
1386  if (client == _textInputClient && self.isFirstResponder) {
1387  [self resignFirstResponderFromFramework];
1388  }
1389 }
1390 
1391 - (BOOL)resignFirstResponder {
1392  BOOL wasFirstResponder = self.isFirstResponder;
1393  BOOL success = [super resignFirstResponder];
1394  if (success && !_preventCursorDismissWhenResignFirstResponder) {
1395  if (wasFirstResponder) {
1397  !_isResigningFirstResponderFromFramework && _textInputClient != 0;
1398  }
1399  [self.textInputDelegate flutterTextInputView:self
1400  didResignFirstResponderWithTextInputClient:_textInputClient];
1401  }
1402  return success;
1403 }
1404 
1405 - (BOOL)becomeFirstResponderFromFramework {
1407  return [self becomeFirstResponder];
1408 }
1409 
1410 - (BOOL)resignFirstResponderFromFramework {
1413  BOOL success = [self resignFirstResponder];
1415  return success;
1416 }
1417 
1418 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
1419  if (action == @selector(paste:)) {
1420  // Forbid pasting images, memojis, or other non-string content.
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, *)) {
1429  return YES;
1430  }
1431  return NO;
1432  }
1433  return [super canPerformAction:action withSender:sender];
1434 }
1435 
1436 #pragma mark - UIResponderStandardEditActions Overrides
1437 
1438 - (void)cut:(id)sender {
1439  [UIPasteboard generalPasteboard].string = [self textInRange:_selectedTextRange];
1440  [self replaceRange:_selectedTextRange withText:@""];
1441 }
1442 
1443 - (void)copy:(id)sender {
1444  [UIPasteboard generalPasteboard].string = [self textInRange:_selectedTextRange];
1445 }
1446 
1447 - (void)paste:(id)sender {
1448  NSString* pasteboardString = [UIPasteboard generalPasteboard].string;
1449  if (pasteboardString != nil) {
1450  [self insertText:pasteboardString];
1451  }
1452 }
1453 
1454 - (void)delete:(id)sender {
1455  [self replaceRange:_selectedTextRange withText:@""];
1456 }
1457 
1458 - (void)selectAll:(id)sender {
1459  [self setSelectedTextRange:[self textRangeFromPosition:[self beginningOfDocument]
1460  toPosition:[self endOfDocument]]];
1461 }
1462 
1463 #pragma mark - UITextInput Overrides
1464 
1465 - (id<UITextInputTokenizer>)tokenizer {
1466  if (_tokenizer == nil) {
1467  _tokenizer = [[FlutterTokenizer alloc] initWithTextInput:self];
1468  }
1469  return _tokenizer;
1470 }
1471 
1472 - (UITextRange*)selectedTextRange {
1473  return [_selectedTextRange copy];
1474 }
1475 
1476 // Change the range of selected text, without notifying the framework.
1477 - (void)setSelectedTextRangeLocal:(UITextRange*)selectedTextRange {
1479  if (self.hasText) {
1480  FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange;
1482  rangeWithNSRange:fml::RangeForCharactersInRange(self.text, flutterTextRange.range)] copy];
1483  } else {
1484  _selectedTextRange = [selectedTextRange copy];
1485  }
1486  }
1487 }
1488 
1489 - (void)setSelectedTextRange:(UITextRange*)selectedTextRange {
1491  return;
1492  }
1493 
1494  [self setSelectedTextRangeLocal:selectedTextRange];
1495 
1496  if (_enableDeltaModel) {
1497  [self updateEditingStateWithDelta:flutter::TextEditingDelta([self.text UTF8String])];
1498  } else {
1499  [self updateEditingState];
1500  }
1501 
1502  if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone ||
1503  _scribbleFocusStatus == FlutterScribbleFocusStatusFocused) {
1504  NSAssert([selectedTextRange isKindOfClass:[FlutterTextRange class]],
1505  @"Expected a FlutterTextRange for range (got %@).", [selectedTextRange class]);
1506  FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange;
1507  if (flutterTextRange.range.length > 0) {
1508  [self.textInputDelegate flutterTextInputView:self showToolbar:_textInputClient];
1509  }
1510  }
1511 
1512  [self resetScribbleInteractionStatusIfEnding];
1513 }
1514 
1515 - (id)insertDictationResultPlaceholder {
1516  return @"";
1517 }
1518 
1519 - (void)removeDictationResultPlaceholder:(id)placeholder willInsertResult:(BOOL)willInsertResult {
1520 }
1521 
1522 - (NSString*)textInRange:(UITextRange*)range {
1523  if (!range) {
1524  return nil;
1525  }
1526  NSAssert([range isKindOfClass:[FlutterTextRange class]],
1527  @"Expected a FlutterTextRange for range (got %@).", [range class]);
1528  NSRange textRange = ((FlutterTextRange*)range).range;
1529  if (textRange.location == NSNotFound) {
1530  // Avoids [crashes](https://github.com/flutter/flutter/issues/138464) from an assertion
1531  // against NSNotFound.
1532  // TODO(hellohuanlin): This is a temp workaround, but we should look into why
1533  // framework is providing NSNotFound to the engine.
1534  // https://github.com/flutter/flutter/issues/160100
1535  return nil;
1536  }
1537  // Sanitize the range to prevent going out of bounds.
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];
1542 }
1543 
1544 // Replace the text within the specified range with the given text,
1545 // without notifying the framework.
1546 - (void)replaceRangeLocal:(NSRange)range withText:(NSString*)text {
1547  [self.text replaceCharactersInRange:[self clampSelection:range forText:self.text]
1548  withString:text];
1549 
1550  // Adjust the selected range and the marked text range. There's no
1551  // documentation but UITextField always sets markedTextRange to nil,
1552  // and collapses the selection to the end of the new replacement text.
1553  const NSRange newSelectionRange =
1554  [self clampSelection:NSMakeRange(range.location + text.length, 0) forText:self.text];
1555 
1556  [self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:newSelectionRange]];
1557  self.markedTextRange = nil;
1558 }
1559 
1560 - (void)replaceRange:(UITextRange*)range withText:(NSString*)text {
1561  NSString* textBeforeChange = [self.text copy];
1562  NSRange replaceRange = ((FlutterTextRange*)range).range;
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],
1568  flutter::TextRange(
1569  nextReplaceRange.location,
1570  nextReplaceRange.location + nextReplaceRange.length),
1571  [text UTF8String])];
1572  } else {
1573  [self updateEditingState];
1574  }
1575 }
1576 
1577 - (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text {
1578  // `temporarilyDeletedComposedCharacter` should only be used during a single text change session.
1579  // So it needs to be cleared at the start of each text editing session.
1580  self.temporarilyDeletedComposedCharacter = nil;
1581 
1582  if (self.returnKeyType == UIReturnKeyDefault && [text isEqualToString:@"\n"]) {
1583  [self.textInputDelegate flutterTextInputView:self
1584  performAction:FlutterTextInputActionNewline
1585  withClient:_textInputClient];
1586  return YES;
1587  }
1588 
1589  if ([text isEqualToString:@"\n"]) {
1590  FlutterTextInputAction action;
1591  switch (self.returnKeyType) {
1592  case UIReturnKeyDefault:
1593  action = FlutterTextInputActionUnspecified;
1594  break;
1595  case UIReturnKeyDone:
1596  action = FlutterTextInputActionDone;
1597  break;
1598  case UIReturnKeyGo:
1599  action = FlutterTextInputActionGo;
1600  break;
1601  case UIReturnKeySend:
1602  action = FlutterTextInputActionSend;
1603  break;
1604  case UIReturnKeySearch:
1605  case UIReturnKeyGoogle:
1606  case UIReturnKeyYahoo:
1607  action = FlutterTextInputActionSearch;
1608  break;
1609  case UIReturnKeyNext:
1610  action = FlutterTextInputActionNext;
1611  break;
1612  case UIReturnKeyContinue:
1613  action = FlutterTextInputActionContinue;
1614  break;
1615  case UIReturnKeyJoin:
1616  action = FlutterTextInputActionJoin;
1617  break;
1618  case UIReturnKeyRoute:
1619  action = FlutterTextInputActionRoute;
1620  break;
1621  case UIReturnKeyEmergencyCall:
1622  action = FlutterTextInputActionEmergencyCall;
1623  break;
1624  }
1625 
1626  [self.textInputDelegate flutterTextInputView:self
1627  performAction:action
1628  withClient:_textInputClient];
1629  return NO;
1630  }
1631 
1632  return YES;
1633 }
1634 
1635 // Either replaces the existing marked text or, if none is present, inserts it in
1636 // place of the current selection.
1637 - (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange {
1638  NSString* textBeforeChange = [self.text copy];
1639 
1640  if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone ||
1641  _scribbleFocusStatus != FlutterScribbleFocusStatusUnfocused) {
1642  return;
1643  }
1644 
1645  if (markedText == nil) {
1646  markedText = @"";
1647  }
1648 
1649  const FlutterTextRange* currentMarkedTextRange = (FlutterTextRange*)self.markedTextRange;
1650  const NSRange& actualReplacedRange = currentMarkedTextRange && !currentMarkedTextRange.isEmpty
1651  ? currentMarkedTextRange.range
1653  // No need to call replaceRangeLocal as this method always adjusts the
1654  // selected/marked text ranges anyways.
1655  [self.text replaceCharactersInRange:actualReplacedRange withString:markedText];
1656 
1657  const NSRange newMarkedRange = NSMakeRange(actualReplacedRange.location, markedText.length);
1658  self.markedTextRange =
1659  newMarkedRange.length > 0 ? [FlutterTextRange rangeWithNSRange:newMarkedRange] : nil;
1660 
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],
1671  flutter::TextRange(
1672  nextReplaceRange.location,
1673  nextReplaceRange.location + nextReplaceRange.length),
1674  [markedText UTF8String])];
1675  } else {
1676  [self updateEditingState];
1677  }
1678 }
1679 
1680 // iOS 17+ inline predictive text uses setAttributedMarkedText:selectedRange:.
1681 // Forward to the existing setMarkedText implementation by extracting the plain string.
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];
1686 }
1687 
1688 - (void)unmarkText {
1689  if (!self.markedTextRange) {
1690  return;
1691  }
1692  self.markedTextRange = nil;
1693  if (_enableDeltaModel) {
1694  [self updateEditingStateWithDelta:flutter::TextEditingDelta([self.text UTF8String])];
1695  } else {
1696  [self updateEditingState];
1697  }
1698 }
1699 
1700 - (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition
1701  toPosition:(UITextPosition*)toPosition {
1702  NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index;
1703  NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index;
1704  if (toIndex >= fromIndex) {
1705  return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)];
1706  } else {
1707  // toIndex can be smaller than fromIndex, because
1708  // UITextInputStringTokenizer does not handle CJK characters
1709  // well in some cases. See:
1710  // https://github.com/flutter/flutter/issues/58750#issuecomment-644469521
1711  // Swap fromPosition and toPosition to match the behavior of native
1712  // UITextViews.
1713  return [FlutterTextRange rangeWithNSRange:NSMakeRange(toIndex, fromIndex - toIndex)];
1714  }
1715 }
1716 
1717 - (NSUInteger)decrementOffsetPosition:(NSUInteger)position {
1718  return fml::RangeForCharacterAtIndex(self.text, MAX(0, position - 1)).location;
1719 }
1720 
1721 - (NSUInteger)incrementOffsetPosition:(NSUInteger)position {
1722  NSRange charRange = fml::RangeForCharacterAtIndex(self.text, position);
1723  return MIN(position + charRange.length, self.text.length);
1724 }
1725 
1726 - (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset {
1727  NSUInteger offsetPosition = ((FlutterTextPosition*)position).index;
1728 
1729  NSInteger newLocation = (NSInteger)offsetPosition + offset;
1730  if (newLocation < 0 || newLocation > (NSInteger)self.text.length) {
1731  return nil;
1732  }
1733 
1734  if (_scribbleInteractionStatus != FlutterScribbleInteractionStatusNone) {
1735  return [FlutterTextPosition positionWithIndex:newLocation];
1736  }
1737 
1738  if (offset >= 0) {
1739  for (NSInteger i = 0; i < offset && offsetPosition < self.text.length; ++i) {
1740  offsetPosition = [self incrementOffsetPosition:offsetPosition];
1741  }
1742  } else {
1743  for (NSInteger i = 0; i < ABS(offset) && offsetPosition > 0; ++i) {
1744  offsetPosition = [self decrementOffsetPosition:offsetPosition];
1745  }
1746  }
1747  return [FlutterTextPosition positionWithIndex:offsetPosition];
1748 }
1749 
1750 - (UITextPosition*)positionFromPosition:(UITextPosition*)position
1751  inDirection:(UITextLayoutDirection)direction
1752  offset:(NSInteger)offset {
1753  // TODO(cbracken) Add RTL handling.
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];
1761  }
1762 }
1763 
1764 - (UITextPosition*)beginningOfDocument {
1765  return [FlutterTextPosition positionWithIndex:0 affinity:UITextStorageDirectionForward];
1766 }
1767 
1768 - (UITextPosition*)endOfDocument {
1769  return [FlutterTextPosition positionWithIndex:self.text.length
1770  affinity:UITextStorageDirectionBackward];
1771 }
1772 
1773 - (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other {
1774  NSUInteger positionIndex = ((FlutterTextPosition*)position).index;
1775  NSUInteger otherIndex = ((FlutterTextPosition*)other).index;
1776  if (positionIndex < otherIndex) {
1777  return NSOrderedAscending;
1778  }
1779  if (positionIndex > otherIndex) {
1780  return NSOrderedDescending;
1781  }
1782  UITextStorageDirection positionAffinity = ((FlutterTextPosition*)position).affinity;
1783  UITextStorageDirection otherAffinity = ((FlutterTextPosition*)other).affinity;
1784  if (positionAffinity == otherAffinity) {
1785  return NSOrderedSame;
1786  }
1787  if (positionAffinity == UITextStorageDirectionBackward) {
1788  // positionAffinity points backwards, otherAffinity points forwards
1789  return NSOrderedAscending;
1790  }
1791  // positionAffinity points forwards, otherAffinity points backwards
1792  return NSOrderedDescending;
1793 }
1794 
1795 - (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition {
1796  return ((FlutterTextPosition*)toPosition).index - ((FlutterTextPosition*)from).index;
1797 }
1798 
1799 - (UITextPosition*)positionWithinRange:(UITextRange*)range
1800  farthestInDirection:(UITextLayoutDirection)direction {
1801  NSUInteger index;
1802  UITextStorageDirection affinity;
1803  switch (direction) {
1804  case UITextLayoutDirectionLeft:
1805  case UITextLayoutDirectionUp:
1806  index = ((FlutterTextPosition*)range.start).index;
1807  affinity = UITextStorageDirectionForward;
1808  break;
1809  case UITextLayoutDirectionRight:
1810  case UITextLayoutDirectionDown:
1811  index = ((FlutterTextPosition*)range.end).index;
1812  affinity = UITextStorageDirectionBackward;
1813  break;
1814  }
1815  return [FlutterTextPosition positionWithIndex:index affinity:affinity];
1816 }
1817 
1818 - (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position
1819  inDirection:(UITextLayoutDirection)direction {
1820  NSUInteger positionIndex = ((FlutterTextPosition*)position).index;
1821  NSUInteger startIndex;
1822  NSUInteger endIndex;
1823  switch (direction) {
1824  case UITextLayoutDirectionLeft:
1825  case UITextLayoutDirectionUp:
1826  startIndex = [self decrementOffsetPosition:positionIndex];
1827  endIndex = positionIndex;
1828  break;
1829  case UITextLayoutDirectionRight:
1830  case UITextLayoutDirectionDown:
1831  startIndex = positionIndex;
1832  endIndex = [self incrementOffsetPosition:positionIndex];
1833  break;
1834  }
1835  return [FlutterTextRange rangeWithNSRange:NSMakeRange(startIndex, endIndex - startIndex)];
1836 }
1837 
1838 #pragma mark - UITextInput text direction handling
1839 
1840 - (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position
1841  inDirection:(UITextStorageDirection)direction {
1842  // TODO(cbracken) Add RTL handling.
1843  return UITextWritingDirectionNatural;
1844 }
1845 
1846 - (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection
1847  forRange:(UITextRange*)range {
1848  // TODO(cbracken) Add RTL handling.
1849 }
1850 
1851 #pragma mark - UITextInput cursor, selection rect handling
1852 
1853 - (void)setMarkedRect:(CGRect)markedRect {
1854  _markedRect = markedRect;
1855  // Invalidate the cache.
1857 }
1858 
1859 // This method expects a 4x4 perspective matrix
1860 // stored in a NSArray in column-major order.
1861 - (void)setEditableTransform:(NSArray*)matrix {
1862  CATransform3D* transform = &_editableTransform;
1863 
1864  transform->m11 = [matrix[0] doubleValue];
1865  transform->m12 = [matrix[1] doubleValue];
1866  transform->m13 = [matrix[2] doubleValue];
1867  transform->m14 = [matrix[3] doubleValue];
1868 
1869  transform->m21 = [matrix[4] doubleValue];
1870  transform->m22 = [matrix[5] doubleValue];
1871  transform->m23 = [matrix[6] doubleValue];
1872  transform->m24 = [matrix[7] doubleValue];
1873 
1874  transform->m31 = [matrix[8] doubleValue];
1875  transform->m32 = [matrix[9] doubleValue];
1876  transform->m33 = [matrix[10] doubleValue];
1877  transform->m34 = [matrix[11] doubleValue];
1878 
1879  transform->m41 = [matrix[12] doubleValue];
1880  transform->m42 = [matrix[13] doubleValue];
1881  transform->m43 = [matrix[14] doubleValue];
1882  transform->m44 = [matrix[15] doubleValue];
1883 
1884  // Invalidate the cache.
1886 }
1887 
1888 // Returns the bounding CGRect of the transformed incomingRect, in the view's
1889 // coordinates.
1890 - (CGRect)localRectFromFrameworkTransform:(CGRect)incomingRect {
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)};
1897 
1898  CGPoint origin = CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX);
1899  CGPoint farthest = CGPointMake(-CGFLOAT_MAX, -CGFLOAT_MAX);
1900 
1901  for (int i = 0; i < 4; i++) {
1902  const CGPoint point = points[i];
1903 
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;
1908 
1909  const CGFloat w = _editableTransform.m14 * point.x + _editableTransform.m24 * point.y +
1910  _editableTransform.m44;
1911 
1912  if (w == 0.0) {
1913  return kInvalidFirstRect;
1914  } else if (w != 1.0) {
1915  x /= w;
1916  y /= w;
1917  }
1918 
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);
1923  }
1924  return CGRectMake(origin.x, origin.y, farthest.x - origin.x, farthest.y - origin.y);
1925 }
1926 
1927 // The following methods are required to support force-touch cursor positioning
1928 // and to position the
1929 // candidates view for multi-stage input methods (e.g., Japanese) when using a
1930 // physical keyboard.
1931 // Returns the rect for the queried range, or a subrange through the end of line, if
1932 // the range encompasses multiple lines.
1933 - (CGRect)firstRectForRange:(UITextRange*)range {
1934  NSAssert([range.start isKindOfClass:[FlutterTextPosition class]],
1935  @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]);
1936  NSAssert([range.end isKindOfClass:[FlutterTextPosition class]],
1937  @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]);
1938  NSUInteger start = ((FlutterTextPosition*)range.start).index;
1939  NSUInteger end = ((FlutterTextPosition*)range.end).index;
1940  if (_markedTextRange != nil) {
1941  // The candidates view can't be shown if the framework has not sent the
1942  // first caret rect.
1943  if (CGRectEqualToRect(kInvalidFirstRect, _markedRect)) {
1944  return kInvalidFirstRect;
1945  }
1946 
1947  if (CGRectEqualToRect(_cachedFirstRect, kInvalidFirstRect)) {
1948  // If the width returned is too small, that means the framework sent us
1949  // the caret rect instead of the marked text rect. Expand it to 0.2 so
1950  // the IME candidates view would show up.
1951  CGRect rect = _markedRect;
1952  if (CGRectIsEmpty(rect)) {
1953  rect = CGRectInset(rect, -0.1, 0);
1954  }
1955  _cachedFirstRect = [self localRectFromFrameworkTransform:rect];
1956  }
1957 
1958  UIView* hostView = _textInputPlugin.hostView;
1959  NSAssert(hostView == nil || [self isDescendantOfView:hostView], @"%@ is not a descendant of %@",
1960  self, hostView);
1961  return hostView ? [hostView convertRect:_cachedFirstRect toView:self] : _cachedFirstRect;
1962  }
1963 
1964  if (_scribbleInteractionStatus == FlutterScribbleInteractionStatusNone &&
1965  _scribbleFocusStatus == FlutterScribbleFocusStatusUnfocused) {
1966  if (@available(iOS 17.0, *)) {
1967  // Disable auto-correction highlight feature for iOS 17+.
1968  // In iOS 17+, whenever a character is inserted or deleted, the system will always query
1969  // the rect for every single character of the current word.
1970  // GitHub Issue: https://github.com/flutter/flutter/issues/128406
1971  } else {
1972  // This tells the framework to show the highlight for incorrectly spelled word that is
1973  // about to be auto-corrected.
1974  // There is no other UITextInput API that informs about the auto-correction highlight.
1975  // So we simply add the call here as a workaround.
1976  [self.textInputDelegate flutterTextInputView:self
1977  showAutocorrectionPromptRectForStart:start
1978  end:end
1979  withClient:_textInputClient];
1980  }
1981  }
1982 
1983  // The iOS 16 system highlight does not repect the height returned by `firstRectForRange`
1984  // API (unlike iOS 17). So we return CGRectZero to hide it (unless if scribble is enabled).
1985  // To support scribble's advanced gestures (e.g. insert a space with a vertical bar),
1986  // at least 1 character's width is required.
1987  if (@available(iOS 17, *)) {
1988  // No-op
1989  } else if (![self isScribbleAvailable]) {
1990  return CGRectZero;
1991  }
1992 
1993  NSUInteger first = start;
1994  if (end < start) {
1995  first = end;
1996  }
1997 
1998  CGRect startSelectionRect = CGRectNull;
1999  CGRect endSelectionRect = CGRectNull;
2000  // Selection rects from different langauges may have different minY/maxY.
2001  // So we need to iterate through each rects to update minY/maxY.
2002  CGFloat minY = CGFLOAT_MAX;
2003  CGFloat maxY = CGFLOAT_MIN;
2004 
2005  FlutterTextRange* textRange = [FlutterTextRange
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)) {
2015  // TODO(hellohaunlin): Remove iOS 17 check. The logic should also work for older versions.
2016  if (@available(iOS 17, *)) {
2017  startSelectionRect = _selectionRects[i].rect;
2018  } else {
2019  return _selectionRects[i].rect;
2020  }
2021  }
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; // end is exclusive
2026  BOOL nextSelectionRectIsOnNextLine =
2027  !isLastSelectionRect &&
2028  // Selection rects from different langauges in 2 lines may overlap with each other.
2029  // A good approximation is to check if the center of next rect is below the bottom of
2030  // current rect.
2031  // TODO(hellohuanlin): Consider passing the line break info from framework.
2032  CGRectGetMidY(_selectionRects[i + 1].rect) > CGRectGetMaxY(_selectionRects[i].rect);
2033  if (endsOnOrAfterEndOfRange || isLastSelectionRect || nextSelectionRectIsOnNextLine) {
2034  endSelectionRect = _selectionRects[i].rect;
2035  break;
2036  }
2037  }
2038  }
2039  if (CGRectIsNull(startSelectionRect) || CGRectIsNull(endSelectionRect)) {
2040  return CGRectZero;
2041  } else {
2042  // fmin/fmax to support both LTR and RTL languages.
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);
2046  }
2047 }
2048 
2049 - (CGRect)caretRectForPosition:(UITextPosition*)position {
2050  NSInteger index = ((FlutterTextPosition*)position).index;
2051  UITextStorageDirection affinity = ((FlutterTextPosition*)position).affinity;
2052  // Get the selectionRect of the characters before and after the requested caret position.
2053  NSArray<UITextSelectionRect*>* rects = [self
2054  selectionRectsForRange:[FlutterTextRange
2055  rangeWithNSRange:fml::RangeForCharactersInRange(
2056  self.text,
2057  NSMakeRange(
2058  MAX(0, index - 1),
2059  (index >= (NSInteger)self.text.length)
2060  ? 1
2061  : 2))]];
2062  if (rects.count == 0) {
2063  return CGRectZero;
2064  }
2065  if (index == 0) {
2066  // There is no character before the caret, so this will be the bounds of the character after the
2067  // caret position.
2068  CGRect characterAfterCaret = rects[0].rect;
2069  // Return a zero-width rectangle along the upstream edge of the character after the caret
2070  // position.
2071  if ([rects[0] isKindOfClass:[FlutterTextSelectionRect class]] &&
2072  ((FlutterTextSelectionRect*)rects[0]).isRTL) {
2073  return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width,
2074  characterAfterCaret.origin.y, 0, characterAfterCaret.size.height);
2075  } else {
2076  return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0,
2077  characterAfterCaret.size.height);
2078  }
2079  } else if (rects.count == 2 && affinity == UITextStorageDirectionForward) {
2080  // There are characters before and after the caret, with forward direction affinity.
2081  // It's better to use the character after the caret.
2082  CGRect characterAfterCaret = rects[1].rect;
2083  // Return a zero-width rectangle along the upstream edge of the character after the caret
2084  // position.
2085  if ([rects[1] isKindOfClass:[FlutterTextSelectionRect class]] &&
2086  ((FlutterTextSelectionRect*)rects[1]).isRTL) {
2087  return CGRectMake(characterAfterCaret.origin.x + characterAfterCaret.size.width,
2088  characterAfterCaret.origin.y, 0, characterAfterCaret.size.height);
2089  } else {
2090  return CGRectMake(characterAfterCaret.origin.x, characterAfterCaret.origin.y, 0,
2091  characterAfterCaret.size.height);
2092  }
2093  }
2094 
2095  // Covers 2 remaining cases:
2096  // 1. there are characters before and after the caret, with backward direction affinity.
2097  // 2. there is only 1 character before the caret (caret is at the end of text).
2098  // For both cases, return a zero-width rectangle along the downstream edge of the character
2099  // before the caret position.
2100  CGRect characterBeforeCaret = rects[0].rect;
2101  if ([rects[0] isKindOfClass:[FlutterTextSelectionRect class]] &&
2102  ((FlutterTextSelectionRect*)rects[0]).isRTL) {
2103  return CGRectMake(characterBeforeCaret.origin.x, characterBeforeCaret.origin.y, 0,
2104  characterBeforeCaret.size.height);
2105  } else {
2106  return CGRectMake(characterBeforeCaret.origin.x + characterBeforeCaret.size.width,
2107  characterBeforeCaret.origin.y, 0, characterBeforeCaret.size.height);
2108  }
2109 }
2110 
2111 - (UITextPosition*)closestPositionToPoint:(CGPoint)point {
2112  if ([_selectionRects count] == 0) {
2113  NSAssert([_selectedTextRange.start isKindOfClass:[FlutterTextPosition class]],
2114  @"Expected a FlutterTextPosition for position (got %@).",
2115  [_selectedTextRange.start class]);
2116  NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index;
2117  UITextStorageDirection currentAffinity =
2118  ((FlutterTextPosition*)_selectedTextRange.start).affinity;
2119  return [FlutterTextPosition positionWithIndex:currentIndex affinity:currentAffinity];
2120  }
2121 
2123  rangeWithNSRange:fml::RangeForCharactersInRange(self.text, NSMakeRange(0, self.text.length))];
2124  return [self closestPositionToPoint:point withinRange:range];
2125 }
2126 
2127 - (NSArray*)selectionRectsForRange:(UITextRange*)range {
2128  // At least in the simulator, swapping to the Japanese keyboard crashes the app as this method
2129  // is called immediately with a UITextRange with a UITextPosition rather than FlutterTextPosition
2130  // for the start and end.
2131  if (![range.start isKindOfClass:[FlutterTextPosition class]]) {
2132  return @[];
2133  }
2134  NSAssert([range.start isKindOfClass:[FlutterTextPosition class]],
2135  @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]);
2136  NSAssert([range.end isKindOfClass:[FlutterTextPosition class]],
2137  @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]);
2138  NSUInteger start = ((FlutterTextPosition*)range.start).index;
2139  NSUInteger end = ((FlutterTextPosition*)range.end).index;
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;
2146  if (start == end) {
2147  width = 0;
2148  }
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
2154  writingDirection:NSWritingDirectionNatural
2155  containsStart:(i == 0)
2156  containsEnd:(i == fml::RangeForCharactersInRange(
2157  self.text, NSMakeRange(0, self.text.length))
2158  .length)
2159  isVertical:NO];
2160  [rects addObject:selectionRect];
2161  }
2162  }
2163  return rects;
2164 }
2165 
2166 - (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range {
2167  NSAssert([range.start isKindOfClass:[FlutterTextPosition class]],
2168  @"Expected a FlutterTextPosition for range.start (got %@).", [range.start class]);
2169  NSAssert([range.end isKindOfClass:[FlutterTextPosition class]],
2170  @"Expected a FlutterTextPosition for range.end (got %@).", [range.end class]);
2171  NSUInteger start = ((FlutterTextPosition*)range.start).index;
2172  NSUInteger end = ((FlutterTextPosition*)range.end).index;
2173 
2174  // Selecting text using the floating cursor is not as precise as the pencil.
2175  // Allow further vertical deviation and base more of the decision on horizontal comparison.
2176  CGFloat verticalPrecision = _isFloatingCursorActive ? 10 : 1;
2177 
2178  // Find the selectionRect with a leading-center point that is closest to a given point.
2179  BOOL isFirst = YES;
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) {
2184  if (isFirst ||
2186  point, _selectionRects[i].rect, _selectionRects[i].isRTL,
2187  /*useTrailingBoundaryOfSelectionRect=*/NO, _selectionRects[_closestRectIndex].rect,
2188  _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) {
2189  isFirst = NO;
2190  _closestRectIndex = i;
2191  }
2192  }
2193  }
2194 
2195  FlutterTextPosition* closestPosition =
2196  [FlutterTextPosition positionWithIndex:_selectionRects[_closestRectIndex].position
2197  affinity:UITextStorageDirectionForward];
2198 
2199  // Check if the far side of the closest rect is a better fit (e.g. tapping end of line)
2200  // Cannot simply check the _closestRectIndex result from the previous for loop due to RTL
2201  // writing direction and the gaps between selectionRects. So we also need to consider
2202  // the adjacent selectionRects to refine _closestRectIndex.
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  /*useTrailingBoundaryOfSelectionRect=*/YES, _selectionRects[_closestRectIndex].rect,
2210  _selectionRects[_closestRectIndex].isRTL, verticalPrecision)) {
2211  // This is an upstream position
2212  closestPosition = [FlutterTextPosition positionWithIndex:position
2213  affinity:UITextStorageDirectionBackward];
2214  }
2215  }
2216  }
2217 
2218  return closestPosition;
2219 }
2220 
2221 - (UITextRange*)characterRangeAtPoint:(CGPoint)point {
2222  // TODO(cbracken) Implement.
2223  NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index;
2224  return [FlutterTextRange rangeWithNSRange:fml::RangeForCharacterAtIndex(self.text, currentIndex)];
2225 }
2226 
2227 // Overall logic for floating cursor's "move" gesture and "selection" gesture:
2228 //
2229 // Floating cursor's "move" gesture takes 1 finger to force press the space bar, and then move the
2230 // cursor. The process starts with `beginFloatingCursorAtPoint`. When the finger is moved,
2231 // `updateFloatingCursorAtPoint` will be called. When the finger is released, `endFloatingCursor`
2232 // will be called. In all cases, we send the point (relative to the initial point registered in
2233 // beginFloatingCursorAtPoint) to the framework, so that framework can animate the floating cursor.
2234 //
2235 // During the move gesture, the framework only animate the cursor visually. It's only
2236 // after the gesture is complete, will the framework update the selection to the cursor's
2237 // new position (with zero selection length). This means during the animation, the visual effect
2238 // of the cursor is temporarily out of sync with the selection state in both framework and engine.
2239 // But it will be in sync again after the animation is complete.
2240 //
2241 // Floating cursor's "selection" gesture also starts with 1 finger to force press the space bar,
2242 // so exactly the same functions as the "move gesture" discussed above will be called. When the
2243 // second finger is pressed, `setSelectedText` will be called. This mechanism requires
2244 // `closestPositionFromPoint` to be implemented, to allow UIKit to translate the finger touch
2245 // location displacement to the text range to select. When the selection is completed
2246 // (i.e. when both of the 2 fingers are released), similar to "move" gesture,
2247 // the `endFloatingCursor` will be called.
2248 //
2249 // When the 2nd finger is pressed, it does not trigger another startFloatingCursor call. So
2250 // floating cursor move/selection logic has to be implemented in iOS embedder rather than
2251 // just the framework side.
2252 //
2253 // Whenever a selection is updated, the engine sends the new selection to the framework. So unlike
2254 // the move gesture, the selections in the framework and the engine are always kept in sync.
2255 - (void)beginFloatingCursorAtPoint:(CGPoint)point {
2256  // For "beginFloatingCursorAtPoint" and "updateFloatingCursorAtPoint", "point" is roughly:
2257  //
2258  // CGPoint(
2259  // width >= 0 ? point.x.clamp(boundingBox.left, boundingBox.right) : point.x,
2260  // height >= 0 ? point.y.clamp(boundingBox.top, boundingBox.bottom) : point.y,
2261  // )
2262  // where
2263  // point = keyboardPanGestureRecognizer.translationInView(textInputView) + caretRectForPosition
2264  // boundingBox = self.convertRect(bounds, fromView:textInputView)
2265  // bounds = self._selectionClipRect ?? self.bounds
2266  //
2267  // It seems impossible to use a negative "width" or "height", as the "convertRect"
2268  // call always turns a CGRect's negative dimensions into non-negative values, e.g.,
2269  // (1, 2, -3, -4) would become (-2, -2, 3, 4).
2271  _floatingCursorOffset = point;
2272  [self.textInputDelegate flutterTextInputView:self
2273  updateFloatingCursor:FlutterFloatingCursorDragStateStart
2274  withClient:_textInputClient
2275  withPosition:@{@"X" : @0, @"Y" : @0}];
2276 }
2277 
2278 - (void)updateFloatingCursorAtPoint:(CGPoint)point {
2279  [self.textInputDelegate flutterTextInputView:self
2280  updateFloatingCursor:FlutterFloatingCursorDragStateUpdate
2281  withClient:_textInputClient
2282  withPosition:@{
2283  @"X" : @(point.x - _floatingCursorOffset.x),
2284  @"Y" : @(point.y - _floatingCursorOffset.y)
2285  }];
2286 }
2287 
2288 - (void)endFloatingCursor {
2290  [self.textInputDelegate flutterTextInputView:self
2291  updateFloatingCursor:FlutterFloatingCursorDragStateEnd
2292  withClient:_textInputClient
2293  withPosition:@{@"X" : @0, @"Y" : @0}];
2294 }
2295 
2296 #pragma mark - UIKeyInput Overrides
2297 
2298 - (void)updateEditingState {
2299  NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index;
2300  NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index;
2301 
2302  // Empty compositing range is represented by the framework's TextRange.empty.
2303  NSInteger composingBase = -1;
2304  NSInteger composingExtent = -1;
2305  if (self.markedTextRange != nil) {
2306  composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index;
2307  composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index;
2308  }
2309  NSDictionary* state = @{
2310  @"selectionBase" : @(selectionBase),
2311  @"selectionExtent" : @(selectionExtent),
2312  @"selectionAffinity" : @(_selectionAffinity),
2313  @"selectionIsDirectional" : @(false),
2314  @"composingBase" : @(composingBase),
2315  @"composingExtent" : @(composingExtent),
2316  @"text" : [NSString stringWithString:self.text],
2317  };
2318 
2319  if (_textInputClient == 0 && _autofillId != nil) {
2320  [self.textInputDelegate flutterTextInputView:self
2321  updateEditingClient:_textInputClient
2322  withState:state
2323  withTag:_autofillId];
2324  } else {
2325  [self.textInputDelegate flutterTextInputView:self
2326  updateEditingClient:_textInputClient
2327  withState:state];
2328  }
2329 }
2330 
2331 - (void)updateEditingStateWithDelta:(flutter::TextEditingDelta)delta {
2332  NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index;
2333  NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index;
2334 
2335  // Empty compositing range is represented by the framework's TextRange.empty.
2336  NSInteger composingBase = -1;
2337  NSInteger composingExtent = -1;
2338  if (self.markedTextRange != nil) {
2339  composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index;
2340  composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index;
2341  }
2342 
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),
2350  @"selectionAffinity" : @(_selectionAffinity),
2351  @"selectionIsDirectional" : @(false),
2352  @"composingBase" : @(composingBase),
2353  @"composingExtent" : @(composingExtent),
2354  };
2355 
2356  [_pendingDeltas addObject:deltaToFramework];
2357 
2358  if (_pendingDeltas.count == 1) {
2359  __weak FlutterTextInputView* weakSelf = self;
2360  dispatch_async(dispatch_get_main_queue(), ^{
2361  __strong FlutterTextInputView* strongSelf = weakSelf;
2362  if (strongSelf && strongSelf.pendingDeltas.count > 0) {
2363  NSDictionary* deltas = @{
2364  @"deltas" : strongSelf.pendingDeltas,
2365  };
2366 
2367  [strongSelf.textInputDelegate flutterTextInputView:strongSelf
2368  updateEditingClient:strongSelf->_textInputClient
2369  withDelta:deltas];
2370  [strongSelf.pendingDeltas removeAllObjects];
2371  }
2372  });
2373  }
2374 }
2375 
2376 - (BOOL)hasText {
2377  return self.text.length > 0;
2378 }
2379 
2380 - (void)insertText:(NSString*)text {
2381  if (self.temporarilyDeletedComposedCharacter.length > 0 && text.length == 1 && !text.UTF8String &&
2382  [text characterAtIndex:0] == [self.temporarilyDeletedComposedCharacter characterAtIndex:0]) {
2383  // Workaround for https://github.com/flutter/flutter/issues/111494
2384  // TODO(cyanglaz): revert this workaround if when flutter supports a minimum iOS version which
2385  // this bug is fixed by Apple.
2386  text = self.temporarilyDeletedComposedCharacter;
2387  self.temporarilyDeletedComposedCharacter = nil;
2388  }
2389 
2390  // insertText finalizes composing text and should replace the whole marked
2391  // range, not just the last reported selection within it. See
2392  // https://github.com/flutter/flutter/issues/59541#issuecomment-4617810595.
2393  UITextRange* replacedRange = self.markedTextRange ?: _selectedTextRange;
2394 
2395  NSMutableArray<FlutterTextSelectionRect*>* copiedRects =
2396  [[NSMutableArray alloc] initWithCapacity:[_selectionRects count]];
2397  NSAssert([replacedRange.start isKindOfClass:[FlutterTextPosition class]],
2398  @"Expected a FlutterTextPosition for position (got %@).", [replacedRange.start class]);
2399  NSUInteger insertPosition = ((FlutterTextPosition*)replacedRange.start).index;
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++) {
2404  [copiedRects addObject:[FlutterTextSelectionRect
2405  selectionRectWithRect:_selectionRects[i].rect
2406  position:rectPosition + j
2407  writingDirection:_selectionRects[i].writingDirection]];
2408  }
2409  } else {
2410  if (rectPosition > insertPosition) {
2411  rectPosition = rectPosition + text.length;
2412  }
2413  [copiedRects addObject:[FlutterTextSelectionRect
2414  selectionRectWithRect:_selectionRects[i].rect
2415  position:rectPosition
2416  writingDirection:_selectionRects[i].writingDirection]];
2417  }
2418  }
2419 
2420  _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
2421  [self resetScribbleInteractionStatusIfEnding];
2422  self.selectionRects = copiedRects;
2424  [self replaceRange:replacedRange withText:text];
2425 }
2426 
2427 - (UITextPlaceholder*)insertTextPlaceholderWithSize:(CGSize)size API_AVAILABLE(ios(13.0)) {
2428  [self.textInputDelegate flutterTextInputView:self
2429  insertTextPlaceholderWithSize:size
2430  withClient:_textInputClient];
2431  _hasPlaceholder = YES;
2432  return [[FlutterTextPlaceholder alloc] init];
2433 }
2434 
2435 - (void)removeTextPlaceholder:(UITextPlaceholder*)textPlaceholder API_AVAILABLE(ios(13.0)) {
2436  _hasPlaceholder = NO;
2437  [self.textInputDelegate flutterTextInputView:self removeTextPlaceholder:_textInputClient];
2438 }
2439 
2440 - (void)deleteBackward {
2442  _scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
2443  [self resetScribbleInteractionStatusIfEnding];
2444 
2445  // When deleting Thai vowel, _selectedTextRange has location
2446  // but does not have length, so we have to manually set it.
2447  // In addition, we needed to delete only a part of grapheme cluster
2448  // because it is the expected behavior of Thai input.
2449  // https://github.com/flutter/flutter/issues/24203
2450  // https://github.com/flutter/flutter/issues/21745
2451  // https://github.com/flutter/flutter/issues/39399
2452  //
2453  // This is needed for correct handling of the deletion of Thai vowel input.
2454  // TODO(cbracken): Get a good understanding of expected behavior of Thai
2455  // input and ensure that this is the correct solution.
2456  // https://github.com/flutter/flutter/issues/28962
2457  if (_selectedTextRange.isEmpty && [self hasText]) {
2458  UITextRange* oldSelectedRange = _selectedTextRange;
2459  NSRange oldRange = ((FlutterTextRange*)oldSelectedRange).range;
2460  if (oldRange.location > 0) {
2461  NSRange newRange = NSMakeRange(oldRange.location - 1, 1);
2462 
2463  // We should check if the last character is a part of emoji.
2464  // If so, we must delete the entire emoji to prevent the text from being malformed.
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);
2468  }
2469 
2471  }
2472  }
2473 
2474  if (!_selectedTextRange.isEmpty) {
2475  // Cache the last deleted emoji to use for an iOS bug where the next
2476  // insertion corrupts the emoji characters.
2477  // See: https://github.com/flutter/flutter/issues/111494#issuecomment-1248441346
2478  if (IsEmoji(self.text, _selectedTextRange.range)) {
2479  NSString* deletedText = [self.text substringWithRange:_selectedTextRange.range];
2480  NSRange deleteFirstCharacterRange = fml::RangeForCharacterAtIndex(deletedText, 0);
2481  self.temporarilyDeletedComposedCharacter =
2482  [deletedText substringWithRange:deleteFirstCharacterRange];
2483  }
2484  [self replaceRange:_selectedTextRange withText:@""];
2485  }
2486 }
2487 
2488 - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target {
2489  UIAccessibilityPostNotification(notification, target);
2490 }
2491 
2492 - (void)accessibilityElementDidBecomeFocused {
2493  if ([self accessibilityElementIsFocused]) {
2494  // For most of the cases, this flutter text input view should never
2495  // receive the focus. If we do receive the focus, we make the best effort
2496  // to send the focus back to the real text field.
2497  FML_DCHECK(_backingTextInputAccessibilityObject);
2498  [self postAccessibilityNotification:UIAccessibilityScreenChangedNotification
2499  target:_backingTextInputAccessibilityObject];
2500  }
2501 }
2502 
2503 - (BOOL)accessibilityElementsHidden {
2504  return !_accessibilityEnabled;
2505 }
2506 
2508  if (_scribbleInteractionStatus == FlutterScribbleInteractionStatusEnding) {
2509  _scribbleInteractionStatus = FlutterScribbleInteractionStatusNone;
2510  }
2511 }
2512 
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];
2517 }
2518 
2519 - (void)pressesChanged:(NSSet<UIPress*>*)presses
2520  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2521  [_textInputPlugin.viewController pressesChanged:presses withEvent:event];
2522 }
2523 
2524 - (void)pressesEnded:(NSSet<UIPress*>*)presses
2525  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2526  [_textInputPlugin.viewController pressesEnded:presses withEvent:event];
2527 }
2528 
2529 - (void)pressesCancelled:(NSSet<UIPress*>*)presses
2530  withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
2531  [_textInputPlugin.viewController pressesCancelled:presses withEvent:event];
2532 }
2533 
2534 @end
2535 
2536 /**
2537  * Hides `FlutterTextInputView` from iOS accessibility system so it
2538  * does not show up twice, once where it is in the `UIView` hierarchy,
2539  * and a second time as part of the `SemanticsObject` hierarchy.
2540  *
2541  * This prevents the `FlutterTextInputView` from receiving the focus
2542  * due to swiping gesture.
2543  *
2544  * There are other cases the `FlutterTextInputView` may receive
2545  * focus. One example is during screen changes, the accessibility
2546  * tree will undergo a dramatic structural update. The Voiceover may
2547  * decide to focus the `FlutterTextInputView` that is not involved
2548  * in the structural update instead. If that happens, the
2549  * `FlutterTextInputView` will make a best effort to direct the
2550  * focus back to the `SemanticsObject`.
2551  */
2553 }
2554 
2555 @end
2556 
2558 }
2559 
2560 - (BOOL)accessibilityElementsHidden {
2561  return YES;
2562 }
2563 
2564 @end
2565 
2566 @interface FlutterTextInputPlugin ()
2567 - (void)enableActiveViewAccessibility;
2568 @end
2569 
2570 @interface FlutterTimerProxy : NSObject
2571 @property(nonatomic, weak) FlutterTextInputPlugin* target;
2572 @end
2573 
2574 @implementation FlutterTimerProxy
2575 
2576 + (instancetype)proxyWithTarget:(FlutterTextInputPlugin*)target {
2577  FlutterTimerProxy* proxy = [[self alloc] init];
2578  if (proxy) {
2579  proxy.target = target;
2580  }
2581  return proxy;
2582 }
2583 
2584 - (void)enableActiveViewAccessibility {
2585  [self.target enableActiveViewAccessibility];
2586 }
2587 
2588 @end
2589 
2590 @interface FlutterTextInputPlugin ()
2591 // The current password-autofillable input fields that have yet to be saved.
2592 @property(nonatomic, readonly)
2593  NSMutableDictionary<NSString*, FlutterTextInputView*>* autofillContext;
2594 // Whether the client disconnected while an autofill context was active.
2595 // The removeFromSuperview call is delayed until triggerAutofillSave
2596 // to avoid prematurely ending the autofill session.
2597 @property(nonatomic, readonly) BOOL pendingAutofillRemoval;
2598 // Whether the client disconnected without sending a hideText message.
2599 // This can indicate that the focus is being switched to a different
2600 // text field and to prevent flickering the removeFromSuperview
2601 // call should be delayed until hideTextInput.
2602 @property(nonatomic, readonly) BOOL pendingInputViewRemoval;
2603 @property(nonatomic, retain) FlutterTextInputView* activeView;
2604 @property(nonatomic, retain) FlutterTextInputViewAccessibilityHider* inputHider;
2605 @property(nonatomic, readonly, weak) id<FlutterViewResponder> viewResponder;
2606 
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;
2613 @end
2614 
2615 @implementation FlutterTextInputPlugin {
2616  NSTimer* _enableFlutterTextInputViewAccessibilityTimer;
2619 }
2620 
2621 - (instancetype)initWithDelegate:(id<FlutterTextInputDelegate>)textInputDelegate {
2622  self = [super init];
2623  if (self) {
2624  // `_textInputDelegate` is a weak reference because it should retain FlutterTextInputPlugin.
2625  _textInputDelegate = textInputDelegate;
2626  _autofillContext = [[NSMutableDictionary alloc] init];
2627  _inputHider = [[FlutterTextInputViewAccessibilityHider alloc] init];
2628  _scribbleElements = [[NSMutableDictionary alloc] init];
2629  _keyboardViewContainer = [[UIView alloc] init];
2630 
2631  [[NSNotificationCenter defaultCenter] addObserver:self
2632  selector:@selector(handleKeyboardWillShow:)
2633  name:UIKeyboardWillShowNotification
2634  object:nil];
2635  }
2636 
2637  return self;
2638 }
2639 
2640 - (void)handleKeyboardWillShow:(NSNotification*)notification {
2641  NSDictionary* keyboardInfo = [notification userInfo];
2642  NSValue* keyboardFrameEnd = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
2643  _keyboardRect = [keyboardFrameEnd CGRectValue];
2644 }
2645 
2646 - (void)dealloc {
2647  [self reset];
2648 }
2649 
2650 - (void)removeEnableFlutterTextInputViewAccessibilityTimer {
2651  if (_enableFlutterTextInputViewAccessibilityTimer) {
2652  [_enableFlutterTextInputViewAccessibilityTimer invalidate];
2653  _enableFlutterTextInputViewAccessibilityTimer = nil;
2654  }
2655 }
2656 
2657 - (UIView<UITextInput>*)textInputView {
2658  return _activeView;
2659 }
2660 
2661 - (void)reset {
2662  [_autofillContext removeAllObjects];
2663  [self clearTextInputClient];
2664  [self hideTextInput];
2665 }
2666 
2667 - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
2668  NSString* method = call.method;
2669  id args = call.arguments;
2670  if ([method isEqualToString:kShowMethod]) {
2671  [self showTextInput];
2672  result(nil);
2673  } else if ([method isEqualToString:kHideMethod]) {
2674  [self hideTextInput];
2675  result(nil);
2676  } else if ([method isEqualToString:kSetClientMethod]) {
2677  [self setTextInputClient:[args[0] intValue] withConfiguration:args[1]];
2678  result(nil);
2679  } else if ([method isEqualToString:kSetPlatformViewClientMethod]) {
2680  // This method call has a `platformViewId` argument, but we do not need it for iOS for now.
2681  [self setPlatformViewTextInputClient];
2682  result(nil);
2683  } else if ([method isEqualToString:kSetEditingStateMethod]) {
2684  [self setTextInputEditingState:args];
2685  result(nil);
2686  } else if ([method isEqualToString:kClearClientMethod]) {
2687  [self clearTextInputClient];
2688  result(nil);
2689  } else if ([method isEqualToString:kSetEditableSizeAndTransformMethod]) {
2690  [self setEditableSizeAndTransform:args];
2691  result(nil);
2692  } else if ([method isEqualToString:kSetMarkedTextRectMethod]) {
2693  [self updateMarkedRect:args];
2694  result(nil);
2695  } else if ([method isEqualToString:kFinishAutofillContextMethod]) {
2696  [self triggerAutofillSave:[args boolValue]];
2697  result(nil);
2698  // TODO(justinmc): Remove the TextInput method constant when the framework has
2699  // finished transitioning to using the Scribble channel.
2700  // https://github.com/flutter/flutter/pull/104128
2701  } else if ([method isEqualToString:kDeprecatedSetSelectionRectsMethod]) {
2702  [self setSelectionRects:args];
2703  result(nil);
2704  } else if ([method isEqualToString:kSetSelectionRectsMethod]) {
2705  [self setSelectionRects:args];
2706  result(nil);
2707  } else if ([method isEqualToString:kStartLiveTextInputMethod]) {
2708  [self startLiveTextInput];
2709  result(nil);
2710  } else if ([method isEqualToString:kUpdateConfigMethod]) {
2711  [self updateConfig:args];
2712  result(nil);
2713  } else if ([method isEqualToString:kOnInteractiveKeyboardPointerMoveMethod]) {
2714  CGFloat pointerY = (CGFloat)[args[@"pointerY"] doubleValue];
2715  [self handlePointerMove:pointerY];
2716  result(nil);
2717  } else if ([method isEqualToString:kOnInteractiveKeyboardPointerUpMethod]) {
2718  CGFloat pointerY = (CGFloat)[args[@"pointerY"] doubleValue];
2719  [self handlePointerUp:pointerY];
2720  result(nil);
2721  } else {
2723  }
2724 }
2725 
2726 - (void)handlePointerUp:(CGFloat)pointerY {
2727  if (_keyboardView.superview != nil) {
2728  // Done to avoid the issue of a pointer up done without a screenshot
2729  // View must be loaded at this point.
2730  UIScreen* screen = _viewController.flutterScreenIfViewLoaded;
2731  CGFloat screenHeight = screen.bounds.size.height;
2732  CGFloat keyboardHeight = _keyboardRect.size.height;
2733  // Negative velocity indicates a downward movement
2734  BOOL shouldDismissKeyboardBasedOnVelocity = _pointerYVelocity < 0;
2735  [UIView animateWithDuration:kKeyboardAnimationTimeToCompleteion
2736  animations:^{
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);
2742  }
2743  completion:^(BOOL finished) {
2744  if (shouldDismissKeyboardBasedOnVelocity) {
2745  [self.textInputDelegate flutterTextInputView:self.activeView
2746  didResignFirstResponderWithTextInputClient:self.activeView.textInputClient];
2747  [self dismissKeyboardScreenshot];
2748  } else {
2749  [self showKeyboardAndRemoveScreenshot];
2750  }
2751  }];
2752  }
2753 }
2754 
2755 - (void)dismissKeyboardScreenshot {
2756  for (UIView* subView in _keyboardViewContainer.subviews) {
2757  [subView removeFromSuperview];
2758  }
2759 }
2760 
2761 - (void)showKeyboardAndRemoveScreenshot {
2762  [UIView setAnimationsEnabled:NO];
2763  [_cachedFirstResponder becomeFirstResponder];
2764  // UIKit does not immediately access the areAnimationsEnabled Boolean so a delay is needed before
2765  // returned
2766  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kKeyboardAnimationDelaySeconds * NSEC_PER_SEC),
2767  dispatch_get_main_queue(), ^{
2768  [UIView setAnimationsEnabled:YES];
2769  [self dismissKeyboardScreenshot];
2770  });
2771 }
2772 
2773 - (void)handlePointerMove:(CGFloat)pointerY {
2774  // View must be loaded at this point.
2775  UIScreen* screen = _viewController.flutterScreenIfViewLoaded;
2776  CGFloat screenHeight = screen.bounds.size.height;
2777  CGFloat keyboardHeight = _keyboardRect.size.height;
2778  if (screenHeight - keyboardHeight <= pointerY) {
2779  // If the pointer is within the bounds of the keyboard.
2780  if (_keyboardView.superview == nil) {
2781  // If no screenshot has been taken.
2782  [self takeKeyboardScreenshotAndDisplay];
2783  [self hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate];
2784  } else {
2785  [self setKeyboardContainerHeight:pointerY];
2786  _pointerYVelocity = _previousPointerYPosition - pointerY;
2787  }
2788  } else {
2789  if (_keyboardView.superview != nil) {
2790  // Keeps keyboard at proper height.
2791  _keyboardViewContainer.frame = _keyboardRect;
2792  _pointerYVelocity = _previousPointerYPosition - pointerY;
2793  }
2794  }
2795  _previousPointerYPosition = pointerY;
2796 }
2797 
2798 - (void)setKeyboardContainerHeight:(CGFloat)pointerY {
2799  CGRect frameRect = _keyboardRect;
2800  frameRect.origin.y = pointerY;
2801  _keyboardViewContainer.frame = frameRect;
2802 }
2803 
2804 - (void)hideKeyboardWithoutAnimationAndAvoidCursorDismissUpdate {
2805  [UIView setAnimationsEnabled:NO];
2806  UIApplication* flutterApplication = FlutterSharedApplication.application;
2807  _cachedFirstResponder =
2808  flutterApplication
2809  ? flutterApplication.keyWindow.flutterFirstResponder
2810  : self.viewController.flutterWindowSceneIfViewLoaded.keyWindow.flutterFirstResponder;
2811 
2812  _activeView.preventCursorDismissWhenResignFirstResponder = YES;
2813  [_cachedFirstResponder resignFirstResponder];
2814  _activeView.preventCursorDismissWhenResignFirstResponder = NO;
2815  [UIView setAnimationsEnabled:YES];
2816 }
2817 
2818 - (void)takeKeyboardScreenshotAndDisplay {
2819  // View must be loaded at this point
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) {
2828  UIApplication* flutterApplication = FlutterSharedApplication.application;
2829  UIView* rootView = flutterApplication
2830  ? flutterApplication.delegate.window.rootViewController.view
2831  : self.viewController.viewIfLoaded.window.rootViewController.view;
2832  [rootView addSubview:_keyboardViewContainer];
2833  }
2834  _keyboardViewContainer.layer.zPosition = NSIntegerMax;
2835  _keyboardViewContainer.frame = _keyboardRect;
2836 }
2837 
2838 - (BOOL)showEditMenu:(NSDictionary*)args API_AVAILABLE(ios(16.0)) {
2839  if (!self.activeView.isFirstResponder) {
2840  return NO;
2841  }
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"]];
2848  return YES;
2849 }
2850 
2851 - (void)hideEditMenu {
2852  [self.activeView hideEditMenu];
2853 }
2854 
2855 - (void)setEditableSizeAndTransform:(NSDictionary*)dictionary {
2856  NSArray* transform = dictionary[@"transform"];
2857  [_activeView setEditableTransform:transform];
2858  const int leftIndex = 12;
2859  const int topIndex = 13;
2860  if ([_activeView isScribbleAvailable]) {
2861  // This is necessary to set up where the scribble interactable element will be.
2862  _inputHider.frame =
2863  CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue],
2864  [dictionary[@"width"] intValue], [dictionary[@"height"] intValue]);
2865  _activeView.frame =
2866  CGRectMake(0, 0, [dictionary[@"width"] intValue], [dictionary[@"height"] intValue]);
2867  _activeView.tintColor = [UIColor clearColor];
2868  } else {
2869  // TODO(hellohuanlin): Also need to handle iOS 16 case, where the auto-correction highlight does
2870  // not match the size of text.
2871  // See https://github.com/flutter/flutter/issues/131695
2872  if (@available(iOS 17, *)) {
2873  // Move auto-correction highlight to overlap with the actual text.
2874  // This is to fix an issue where the system auto-correction highlight is displayed at
2875  // the top left corner of the screen on iOS 17+.
2876  // This problem also happens on iOS 16, but the size of highlight does not match the text.
2877  // See https://github.com/flutter/flutter/issues/131695
2878  // TODO(hellohuanlin): Investigate if we can use non-zero size.
2879  _inputHider.frame =
2880  CGRectMake([transform[leftIndex] intValue], [transform[topIndex] intValue], 0, 0);
2881  }
2882  }
2883 }
2884 
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;
2892 }
2893 
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];
2899  [rectsAsRect addObject:[FlutterTextSelectionRect
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]];
2908  }
2909 
2910  // TODO(hellohuanlin): Investigate why notifying the text input system about text changes (via
2911  // textWillChange and textDidChange APIs) causes a bug where we cannot enter text with IME
2912  // keyboards. Issue: https://github.com/flutter/flutter/issues/133908
2913  _activeView.selectionRects = rectsAsRect;
2914 }
2915 
2916 - (void)startLiveTextInput {
2917  if (@available(iOS 15.0, *)) {
2918  if (_activeView == nil || !_activeView.isFirstResponder) {
2919  return;
2920  }
2921  [_activeView captureTextFromCamera:nil];
2922  }
2923 }
2924 
2925 - (void)showTextInput {
2926  _activeView.viewResponder = _viewResponder;
2927  [self addToInputParentViewIfNeeded:_activeView];
2928  [_activeView becomeFirstResponderFromFramework];
2929 }
2930 
2931 - (void)enableActiveViewAccessibility {
2932  if (_activeView.isFirstResponder) {
2933  _activeView.accessibilityEnabled = YES;
2934  }
2935  [self removeEnableFlutterTextInputViewAccessibilityTimer];
2936 }
2937 
2938 - (void)hideTextInput {
2939  [_activeView resignFirstResponderFromFramework];
2940 
2941  // Remove the input view from the view hierarchy after resigning first responder.
2942  // This flag is set by clearTextInputClient when autofillContext is empty.
2943  // Removing after resignFirstResponder (not during clearTextInputClient) prevents
2944  // keyboard flicker when switching between text fields.
2946  [_activeView removeFromSuperview];
2947  [_inputHider removeFromSuperview];
2949  }
2950 }
2951 
2952 - (void)triggerAutofillSave:(BOOL)saveEntries {
2953  [_activeView resignFirstResponderFromFramework];
2954 
2955  if (saveEntries) {
2956  // Make all the input fields in the autofill context visible,
2957  // then remove them to trigger autofill save.
2958  [self cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO];
2959  [_autofillContext removeAllObjects];
2960  [self changeInputViewsAutofillVisibility:YES];
2961  } else {
2962  [_autofillContext removeAllObjects];
2963  }
2964 
2965  [self cleanUpViewHierarchy:YES clearText:!saveEntries delayRemoval:NO];
2966 
2967  // Trigger removal of input hider if needed.
2969  [_activeView removeFromSuperview];
2970  [_inputHider removeFromSuperview];
2973  }
2974 
2975  [self addToInputParentViewIfNeeded:_activeView];
2976 }
2977 
2978 - (void)setPlatformViewTextInputClient {
2979  // No need to track the platformViewID (unlike in Android). When a platform view
2980  // becomes the first responder, simply hide this dummy text input view (`_activeView`)
2981  // for the previously focused widget.
2982  [self removeEnableFlutterTextInputViewAccessibilityTimer];
2983  _activeView.accessibilityEnabled = NO;
2984  [_activeView removeFromSuperview];
2985  [_inputHider removeFromSuperview];
2986 }
2987 
2988 - (void)setTextInputClient:(int)client withConfiguration:(NSDictionary*)configuration {
2989  [self resetAllClientIds];
2990 
2991  // Reset pending removal flags set by the previous clearTextInputClient call.
2994 
2995  // Hide all input views from autofill, only make those in the new configuration visible
2996  // to autofill.
2997  [self changeInputViewsAutofillVisibility:NO];
2998 
2999  // Update the current active view.
3000  switch (AutofillTypeOf(configuration)) {
3001  case kFlutterAutofillTypeNone:
3002  self.activeView = [self createInputViewWith:configuration];
3003  break;
3004  case kFlutterAutofillTypeRegular:
3005  // If the group does not involve password autofill, only install the
3006  // input view that's being focused.
3007  self.activeView = [self updateAndShowAutofillViews:nil
3008  focusedField:configuration
3009  isPasswordRelated:NO];
3010  break;
3011  case kFlutterAutofillTypePassword:
3012  self.activeView = [self updateAndShowAutofillViews:configuration[kAssociatedAutofillFields]
3013  focusedField:configuration
3014  isPasswordRelated:YES];
3015  break;
3016  }
3017  [_activeView setTextInputClient:client];
3018  [_activeView reloadInputViews];
3019 
3020  // Clean up views that no longer need to be in the view hierarchy, according to
3021  // the current autofill context. The "garbage" input views are already made
3022  // invisible to autofill and they can't `becomeFirstResponder`, we only remove
3023  // them to free up resources and reduce the number of input views in the view
3024  // hierarchy.
3025  //
3026  // The garbage views are decommissioned immediately, but the removeFromSuperview
3027  // call is scheduled on the runloop and delayed by 0.1s so we don't remove the
3028  // text fields immediately (which seems to make the keyboard flicker).
3029  // See: https://github.com/flutter/flutter/issues/64628.
3030  [self cleanUpViewHierarchy:NO clearText:YES delayRemoval:YES];
3031 
3032  // Adds a delay to prevent the text view from receiving accessibility
3033  // focus in case it is activated during semantics updates.
3034  //
3035  // One common case is when the app navigates to a page with an auto
3036  // focused text field. The text field will activate the FlutterTextInputView
3037  // with a semantics update sent to the engine. The voiceover will focus
3038  // the newly attached active view while performing accessibility update.
3039  // This results in accessibility focus stuck at the FlutterTextInputView.
3040  if (!_enableFlutterTextInputViewAccessibilityTimer) {
3041  _enableFlutterTextInputViewAccessibilityTimer =
3042  [NSTimer scheduledTimerWithTimeInterval:kUITextInputAccessibilityEnablingDelaySeconds
3043  target:[FlutterTimerProxy proxyWithTarget:self]
3044  selector:@selector(enableActiveViewAccessibility)
3045  userInfo:nil
3046  repeats:NO];
3047  }
3048 }
3049 
3050 // Creates and shows an input field that is not password related and has no autofill
3051 // info. This method returns a new FlutterTextInputView instance when called, since
3052 // UIKit uses the identity of `UITextInput` instances (or the identity of the input
3053 // views) to decide whether the IME's internal states should be reset. See:
3054 // https://github.com/flutter/flutter/issues/79031 .
3055 - (FlutterTextInputView*)createInputViewWith:(NSDictionary*)configuration {
3056  NSString* autofillId = AutofillIdFromDictionary(configuration);
3057  if (autofillId) {
3058  [_autofillContext removeObjectForKey:autofillId];
3059  }
3060  FlutterTextInputView* newView = [[FlutterTextInputView alloc] initWithOwner:self];
3061  [newView configureWithDictionary:configuration];
3062  [self addToInputParentViewIfNeeded:newView];
3063 
3064  for (NSDictionary* field in configuration[kAssociatedAutofillFields]) {
3065  NSString* autofillId = AutofillIdFromDictionary(field);
3066  if (autofillId && AutofillTypeOf(field) == kFlutterAutofillTypeNone) {
3067  [_autofillContext removeObjectForKey:autofillId];
3068  }
3069  }
3070  return newView;
3071 }
3072 
3073 - (FlutterTextInputView*)updateAndShowAutofillViews:(NSArray*)fields
3074  focusedField:(NSDictionary*)focusedField
3075  isPasswordRelated:(BOOL)isPassword {
3076  FlutterTextInputView* focused = nil;
3077  NSString* focusedId = AutofillIdFromDictionary(focusedField);
3078  NSAssert(focusedId, @"autofillId must not be null for the focused field: %@", focusedField);
3079 
3080  if (!fields) {
3081  // DO NOT push the current autofillable input fields to the context even
3082  // if it's password-related, because it is not in an autofill group.
3083  focused = [self getOrCreateAutofillableView:focusedField isPasswordAutofill:isPassword];
3084  [_autofillContext removeObjectForKey:focusedId];
3085  }
3086 
3087  for (NSDictionary* field in fields) {
3088  NSString* autofillId = AutofillIdFromDictionary(field);
3089  NSAssert(autofillId, @"autofillId must not be null for field: %@", field);
3090 
3091  BOOL hasHints = AutofillTypeOf(field) != kFlutterAutofillTypeNone;
3092  BOOL isFocused = [focusedId isEqualToString:autofillId];
3093 
3094  if (isFocused) {
3095  focused = [self getOrCreateAutofillableView:field isPasswordAutofill:isPassword];
3096  }
3097 
3098  if (hasHints) {
3099  // Push the current input field to the context if it has hints.
3100  _autofillContext[autofillId] = isFocused ? focused
3101  : [self getOrCreateAutofillableView:field
3102  isPasswordAutofill:isPassword];
3103  } else {
3104  // Mark for deletion.
3105  [_autofillContext removeObjectForKey:autofillId];
3106  }
3107  }
3108 
3109  NSAssert(focused, @"The current focused input view must not be nil.");
3110  return focused;
3111 }
3112 
3113 // Returns a new non-reusable input view (and put it into the view hierarchy), or get the
3114 // view from the current autofill context, if an input view with the same autofill id
3115 // already exists in the context.
3116 // This is generally used for input fields that are autofillable (UIKit tracks these veiws
3117 // for autofill purposes so they should not be reused for a different type of views).
3118 - (FlutterTextInputView*)getOrCreateAutofillableView:(NSDictionary*)field
3119  isPasswordAutofill:(BOOL)needsPasswordAutofill {
3120  NSString* autofillId = AutofillIdFromDictionary(field);
3121  FlutterTextInputView* inputView = _autofillContext[autofillId];
3122  if (!inputView) {
3123  inputView =
3124  needsPasswordAutofill ? [FlutterSecureTextInputView alloc] : [FlutterTextInputView alloc];
3125  inputView = [inputView initWithOwner:self];
3126  [self addToInputParentViewIfNeeded:inputView];
3127  }
3128 
3129  [inputView configureWithDictionary:field];
3130  return inputView;
3131 }
3132 
3133 // The UIView to add FlutterTextInputViews to.
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 %@",
3139  _viewController);
3140  return host;
3141 }
3142 
3143 // The UIView to add FlutterTextInputViews to.
3144 - (NSArray<UIView*>*)textInputViews {
3145  return _inputHider.subviews;
3146 }
3147 
3148 // Removes every installed input field, unless it's in the current autofill context.
3149 //
3150 // The active view will be removed from its superview too, if includeActiveView is YES.
3151 // When clearText is YES, the text on the input fields will be set to empty before
3152 // they are removed from the view hierarchy, to avoid triggering autofill save.
3153 // If delayRemoval is true, removeFromSuperview will be scheduled on the runloop and
3154 // will be delayed by 0.1s so we don't remove the text fields immediately (which seems
3155 // to make the keyboard flicker).
3156 // See: https://github.com/flutter/flutter/issues/64628.
3157 
3158 - (void)cleanUpViewHierarchy:(BOOL)includeActiveView
3159  clearText:(BOOL)clearText
3160  delayRemoval:(BOOL)delayRemoval {
3161  for (UIView* view in self.textInputViews) {
3162  if ([view isKindOfClass:[FlutterTextInputView class]] &&
3163  (includeActiveView || view != _activeView)) {
3164  FlutterTextInputView* inputView = (FlutterTextInputView*)view;
3165  if (_autofillContext[inputView.autofillId] != view) {
3166  if (clearText) {
3167  [inputView replaceRangeLocal:NSMakeRange(0, inputView.text.length) withText:@""];
3168  }
3169  if (delayRemoval) {
3170  [inputView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:0.1];
3171  } else {
3172  [inputView removeFromSuperview];
3173  }
3174  }
3175  }
3176  }
3177 }
3178 
3179 // Changes the visibility of every FlutterTextInputView currently in the
3180 // view hierarchy.
3181 - (void)changeInputViewsAutofillVisibility:(BOOL)newVisibility {
3182  for (UIView* view in self.textInputViews) {
3183  if ([view isKindOfClass:[FlutterTextInputView class]]) {
3184  FlutterTextInputView* inputView = (FlutterTextInputView*)view;
3185  inputView.isVisibleToAutofill = newVisibility;
3186  }
3187  }
3188 }
3189 
3190 // Resets the client id of every FlutterTextInputView in the view hierarchy
3191 // to 0.
3192 // Called before establishing a new text input connection.
3193 // For views in the current autofill context, they need to
3194 // stay in the view hierachy but should not be allowed to
3195 // send messages (other than autofill related ones) to the
3196 // framework.
3197 - (void)resetAllClientIds {
3198  for (UIView* view in self.textInputViews) {
3199  if ([view isKindOfClass:[FlutterTextInputView class]]) {
3200  FlutterTextInputView* inputView = (FlutterTextInputView*)view;
3201  [inputView setTextInputClient:0];
3202  }
3203  }
3204 }
3205 
3206 - (void)addToInputParentViewIfNeeded:(FlutterTextInputView*)inputView {
3207  if (![inputView isDescendantOfView:_inputHider]) {
3208  [_inputHider addSubview:inputView];
3209  }
3210 
3211  if (_viewController.view == nil) {
3212  // If view controller's view has detached from flutter engine, we don't add _inputHider
3213  // in parent view to fallback and avoid crash.
3214  // https://github.com/flutter/flutter/issues/106404.
3215  return;
3216  }
3217  UIView* parentView = self.hostView;
3218  if (_inputHider.superview != parentView) {
3219  [parentView addSubview:_inputHider];
3220  }
3221 }
3222 
3223 - (void)setTextInputEditingState:(NSDictionary*)state {
3224  [_activeView setTextInputState:state];
3225 }
3226 
3227 - (void)clearTextInputClient {
3228  [_activeView setTextInputClient:0];
3229  _activeView.frame = CGRectZero;
3230 
3231  [self removeEnableFlutterTextInputViewAccessibilityTimer];
3232  _activeView.accessibilityEnabled = NO;
3233 
3234  // Schedule the removal of the input view and input hider.
3235  // The removal is deferred to avoid keyboard flicker when switching between
3236  // text fields, where clearTextInputClient is called before the next
3237  // setTextInputClient.
3238  // See: https://github.com/flutter/flutter/issues/180842
3239  if (_autofillContext.count == 0) {
3241  if (_activeView.isFirstResponder) {
3242  // Still first responder: defer removal to hideTextInput,
3243  // right after resignFirstResponder dismisses the keyboard.
3245  } else {
3246  // Already resigned (hideTextInput was called first):
3247  // safe to remove immediately since the keyboard is already dismissed.
3248  [_activeView removeFromSuperview];
3249  [_inputHider removeFromSuperview];
3251  }
3252  } else {
3253  // Autofill context exists: removal will be performed in triggerAutofillSave,
3254  // which is called by finishAutofillContext to save autofill entries.
3257  }
3258 }
3259 
3260 - (void)updateConfig:(NSDictionary*)dictionary {
3261  BOOL isSecureTextEntry = [dictionary[kSecureTextEntry] boolValue];
3262  for (UIView* view in self.textInputViews) {
3263  if ([view isKindOfClass:[FlutterTextInputView class]]) {
3264  FlutterTextInputView* inputView = (FlutterTextInputView*)view;
3265  // The feature of holding and draging spacebar to move cursor is affected by
3266  // secureTextEntry, so when obscureText is updated, we need to update secureTextEntry
3267  // and call reloadInputViews.
3268  // https://github.com/flutter/flutter/issues/122139
3269  if (inputView.isSecureTextEntry != isSecureTextEntry) {
3270  inputView.secureTextEntry = isSecureTextEntry;
3271  [inputView reloadInputViews];
3272  }
3273  }
3274  }
3275 }
3276 
3277 #pragma mark UIIndirectScribbleInteractionDelegate
3278 
3279 - (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3280  isElementFocused:(UIScribbleElementIdentifier)elementIdentifier
3281  API_AVAILABLE(ios(14.0)) {
3282  return _activeView.scribbleFocusStatus == FlutterScribbleFocusStatusFocused;
3283 }
3284 
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);
3298  }];
3299 }
3300 
3301 - (BOOL)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3302  shouldDelayFocusForElement:(UIScribbleElementIdentifier)elementIdentifier
3303  API_AVAILABLE(ios(14.0)) {
3304  return NO;
3305 }
3306 
3307 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3308  willBeginWritingInElement:(UIScribbleElementIdentifier)elementIdentifier
3309  API_AVAILABLE(ios(14.0)) {
3310 }
3311 
3312 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3313  didFinishWritingInElement:(UIScribbleElementIdentifier)elementIdentifier
3314  API_AVAILABLE(ios(14.0)) {
3315 }
3316 
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) {
3322  return CGRectZero;
3323  }
3324  return [elementValue CGRectValue];
3325 }
3326 
3327 - (void)indirectScribbleInteraction:(UIIndirectScribbleInteraction*)interaction
3328  requestElementsInRect:(CGRect)rect
3329  completion:
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]];
3341  [_scribbleElements
3342  setObject:[NSValue
3343  valueWithCGRect:CGRectMake(
3344  [elementArray[1] floatValue],
3345  [elementArray[2] floatValue],
3346  [elementArray[3] floatValue],
3347  [elementArray[4] floatValue])]
3348  forKey:elementArray[0]];
3349  }
3350  }
3351  completion(elements);
3352  }];
3353 }
3354 
3355 #pragma mark - Methods related to Scribble support
3356 
3357 - (void)setUpIndirectScribbleInteraction:(id<FlutterViewResponder>)viewResponder {
3358  if (_viewResponder != viewResponder) {
3359  if (@available(iOS 14.0, *)) {
3360  UIView* parentView = viewResponder.view;
3361  if (parentView != nil) {
3362  UIIndirectScribbleInteraction* scribbleInteraction = [[UIIndirectScribbleInteraction alloc]
3363  initWithDelegate:(id<UIIndirectScribbleInteractionDelegate>)self];
3364  [parentView addInteraction:scribbleInteraction];
3365  }
3366  }
3367  }
3368  _viewResponder = viewResponder;
3369 }
3370 
3371 - (void)resetViewResponder {
3372  _viewResponder = nil;
3373 }
3374 
3375 #pragma mark -
3376 #pragma mark FlutterKeySecondaryResponder
3377 
3378 /**
3379  * Handles key down events received from the view controller, responding YES if
3380  * the event was handled.
3381  */
3382 - (BOOL)handlePress:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) {
3383  return NO;
3384 }
3385 @end
3386 
3387 /**
3388  * Recursively searches the UIView's subviews to locate the First Responder
3389  */
3390 @implementation UIView (FindFirstResponder)
3391 - (id)flutterFirstResponder {
3392  if (self.isFirstResponder) {
3393  return self;
3394  }
3395  for (UIView* subView in self.subviews) {
3396  UIView* firstResponder = subView.flutterFirstResponder;
3397  if (firstResponder) {
3398  return firstResponder;
3399  }
3400  }
3401  return nil;
3402 }
3403 @end
void(^ FlutterResult)(id _Nullable result)
FLUTTER_DARWIN_EXPORT NSObject const * FlutterMethodNotImplemented
NSRange _range
BOOL isScribbleAvailable
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
CGRect _cachedFirstRect
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
BOOL _hasPlaceholder
const char * _selectionAffinity
FlutterTextInputPlugin * textInputPlugin
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