Flutter iOS Embedder
FlutterTextInputPluginTest.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 
8 
9 #import <OCMock/OCMock.h>
10 #import <XCTest/XCTest.h>
11 
16 
18 
19 @interface FlutterEngine ()
21 @end
22 
23 @interface FlutterTextInputView ()
24 @property(nonatomic, copy) NSString* autofillId;
25 @property(nonatomic, assign) BOOL preventCursorDismissWhenResignFirstResponder;
26 - (void)setEditableTransform:(NSArray*)matrix;
27 - (void)setTextInputClient:(int)client;
28 - (void)setTextInputState:(NSDictionary*)state;
29 - (void)setMarkedRect:(CGRect)markedRect;
30 - (void)updateEditingState;
31 - (BOOL)isVisibleToAutofill;
32 - (id<FlutterTextInputDelegate>)textInputDelegate;
33 - (void)configureWithDictionary:(NSDictionary*)configuration;
34 - (void)handleSearchWebAction;
35 - (void)handleLookUpAction;
36 - (void)handleShareAction;
37 - (BOOL)becomeFirstResponderFromFramework;
38 - (BOOL)resignFirstResponderFromFramework;
39 - (void)handleTranslateAction;
40 @end
41 
43 @property(nonatomic, assign) UIAccessibilityNotifications receivedNotification;
44 @property(nonatomic, assign) id receivedNotificationTarget;
45 @property(nonatomic, assign) BOOL isAccessibilityFocused;
46 
47 - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target;
48 
49 @end
50 
51 @implementation FlutterTextInputViewSpy {
52 }
53 
54 - (void)postAccessibilityNotification:(UIAccessibilityNotifications)notification target:(id)target {
55  self.receivedNotification = notification;
56  self.receivedNotificationTarget = target;
57 }
58 
59 - (BOOL)accessibilityElementIsFocused {
60  return _isAccessibilityFocused;
61 }
62 
63 @end
64 
66 @property(nonatomic, strong) UITextField* textField;
67 @end
68 
69 @interface FlutterTextInputPlugin ()
70 @property(nonatomic, assign) FlutterTextInputView* activeView;
71 @property(nonatomic, readonly) UIView* inputHider;
72 @property(nonatomic, readonly) UIView* keyboardViewContainer;
73 @property(nonatomic, readonly) UIView* keyboardView;
74 @property(nonatomic, assign) UIView* cachedFirstResponder;
75 @property(nonatomic, readonly) CGRect keyboardRect;
76 @property(nonatomic, readonly) BOOL pendingAutofillRemoval;
77 @property(nonatomic, readonly) BOOL pendingInputViewRemoval;
78 @property(nonatomic, readonly)
79  NSMutableDictionary<NSString*, FlutterTextInputView*>* autofillContext;
80 
81 - (void)cleanUpViewHierarchy:(BOOL)includeActiveView
82  clearText:(BOOL)clearText
83  delayRemoval:(BOOL)delayRemoval;
84 - (NSArray<UIView*>*)textInputViews;
85 - (UIView*)hostView;
86 - (void)addToInputParentViewIfNeeded:(FlutterTextInputView*)inputView;
87 - (void)startLiveTextInput;
88 - (void)showKeyboardAndRemoveScreenshot;
89 
90 @end
91 
92 namespace flutter {
93 namespace {
94 class MockPlatformViewDelegate : public PlatformView::Delegate {
95  public:
96  void OnPlatformViewCreated(std::unique_ptr<Surface> surface) override {}
97  void OnPlatformViewDestroyed() override {}
98  void OnPlatformViewScheduleFrame() override {}
99  void OnPlatformViewAddView(int64_t view_id,
100  const ViewportMetrics& viewport_metrics,
101  AddViewCallback callback) override {}
102  void OnPlatformViewRemoveView(int64_t view_id, RemoveViewCallback callback) override {}
103  void OnPlatformViewSendViewFocusEvent(const ViewFocusEvent& event) override {};
104  void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) override {}
105  void OnPlatformViewSetViewportMetrics(int64_t view_id, const ViewportMetrics& metrics) override {}
106  const flutter::Settings& OnPlatformViewGetSettings() const override { return settings_; }
107  void OnPlatformViewDispatchPlatformMessage(std::unique_ptr<PlatformMessage> message) override {}
108  void OnPlatformViewDispatchPointerDataPacket(std::unique_ptr<PointerDataPacket> packet) override {
109  }
110  HitTestResponse OnPlatformViewHitTest(int64_t view_id, const flutter::PointData offset) override {
111  return {.has_platform_view = false};
112  }
113  void OnPlatformViewDispatchSemanticsAction(int64_t view_id,
114  int32_t node_id,
115  SemanticsAction action,
116  fml::MallocMapping args) override {}
117  void OnPlatformViewSetSemanticsEnabled(bool enabled) override {}
118  void OnPlatformViewSetAccessibilityFeatures(int32_t flags) override {}
119  void OnPlatformViewRegisterTexture(std::shared_ptr<Texture> texture) override {}
120  void OnPlatformViewUnregisterTexture(int64_t texture_id) override {}
121  void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) override {}
122 
123  void LoadDartDeferredLibrary(intptr_t loading_unit_id,
124  std::unique_ptr<const fml::Mapping> snapshot_data,
125  std::unique_ptr<const fml::Mapping> snapshot_instructions) override {
126  }
127  void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
128  const std::string error_message,
129  bool transient) override {}
130  void UpdateAssetResolverByType(std::unique_ptr<flutter::AssetResolver> updated_asset_resolver,
131  flutter::AssetResolver::AssetResolverType type) override {}
132  std::shared_ptr<fml::BasicTaskRunner> OnPlatformViewGetShutdownSafeIOTaskRunner() const override {
133  return nullptr;
134  }
135 
136  flutter::Settings settings_;
137 };
138 
139 } // namespace
140 } // namespace flutter
141 
142 @interface FlutterTextInputPluginTest : XCTestCase
143 @end
144 
145 @implementation FlutterTextInputPluginTest {
146  NSDictionary* _template;
147  NSDictionary* _passwordTemplate;
148  id engine;
150 
152 }
153 
154 - (void)setUp {
155  [super setUp];
156  engine = OCMClassMock([FlutterEngine class]);
157 
158  textInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine];
159 
160  viewController = [[FlutterViewController alloc] init];
162 
163  // Clear pasteboard between tests.
164  UIPasteboard.generalPasteboard.items = @[];
165 }
166 
167 - (void)tearDown {
168  textInputPlugin = nil;
169  engine = nil;
170  [textInputPlugin.autofillContext removeAllObjects];
171  [textInputPlugin cleanUpViewHierarchy:YES clearText:YES delayRemoval:NO];
172  [[[[textInputPlugin textInputView] superview] subviews]
173  makeObjectsPerformSelector:@selector(removeFromSuperview)];
174  viewController = nil;
175  [super tearDown];
176 }
177 
178 - (void)setClientId:(int)clientId configuration:(NSDictionary*)config {
179  FlutterMethodCall* setClientCall =
180  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
181  arguments:@[ [NSNumber numberWithInt:clientId], config ]];
182  [textInputPlugin handleMethodCall:setClientCall
183  result:^(id _Nullable result){
184  }];
185 }
186 
187 - (void)setClientClear {
188  FlutterMethodCall* clearClientCall =
189  [FlutterMethodCall methodCallWithMethodName:@"TextInput.clearClient" arguments:@[]];
190  [textInputPlugin handleMethodCall:clearClientCall
191  result:^(id _Nullable result){
192  }];
193 }
194 
195 - (void)setTextInputShow {
196  FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.show"
197  arguments:@[]];
198  [textInputPlugin handleMethodCall:setClientCall
199  result:^(id _Nullable result){
200  }];
201 }
202 
203 - (void)setTextInputHide {
204  FlutterMethodCall* setClientCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.hide"
205  arguments:@[]];
206  [textInputPlugin handleMethodCall:setClientCall
207  result:^(id _Nullable result){
208  }];
209 }
210 
211 - (void)flushScheduledAsyncBlocks {
212  __block bool done = false;
213  XCTestExpectation* expectation =
214  [[XCTestExpectation alloc] initWithDescription:@"Testing on main queue"];
215  dispatch_async(dispatch_get_main_queue(), ^{
216  done = true;
217  });
218  dispatch_async(dispatch_get_main_queue(), ^{
219  XCTAssertTrue(done);
220  [expectation fulfill];
221  });
222  [self waitForExpectations:@[ expectation ] timeout:10];
223 }
224 
225 - (NSMutableDictionary*)mutableTemplateCopy {
226  if (!_template) {
227  _template = @{
228  @"inputType" : @{@"name" : @"TextInuptType.text"},
229  @"keyboardAppearance" : @"Brightness.light",
230  @"obscureText" : @NO,
231  @"inputAction" : @"TextInputAction.unspecified",
232  @"smartDashesType" : @"0",
233  @"smartQuotesType" : @"0",
234  @"autocorrect" : @YES,
235  @"enableInteractiveSelection" : @YES,
236  };
237  }
238 
239  return [_template mutableCopy];
240 }
241 
242 - (NSArray<FlutterTextInputView*>*)installedInputViews {
243  return (NSArray<FlutterTextInputView*>*)[textInputPlugin.textInputViews
244  filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self isKindOfClass: %@",
245  [FlutterTextInputView class]]];
246 }
247 
248 - (FlutterTextRange*)getLineRangeFromTokenizer:(id<UITextInputTokenizer>)tokenizer
249  atIndex:(NSInteger)index {
250  UITextRange* range =
251  [tokenizer rangeEnclosingPosition:[FlutterTextPosition positionWithIndex:index]
252  withGranularity:UITextGranularityLine
253  inDirection:UITextLayoutDirectionRight];
254  XCTAssertTrue([range isKindOfClass:[FlutterTextRange class]]);
255  return (FlutterTextRange*)range;
256 }
257 
258 - (void)updateConfig:(NSDictionary*)config {
259  FlutterMethodCall* updateConfigCall =
260  [FlutterMethodCall methodCallWithMethodName:@"TextInput.updateConfig" arguments:config];
261  [textInputPlugin handleMethodCall:updateConfigCall
262  result:^(id _Nullable result){
263  }];
264 }
265 
266 #pragma mark - Tests
267 
268 - (void)testWillNotCrashWhenViewControllerIsNil {
269  FlutterEngine* flutterEngine = [[FlutterEngine alloc] init];
270  FlutterTextInputPlugin* inputPlugin =
271  [[FlutterTextInputPlugin alloc] initWithDelegate:(id<FlutterTextInputDelegate>)flutterEngine];
272  XCTAssertNil(inputPlugin.viewController);
273  FlutterMethodCall* methodCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.show"
274  arguments:nil];
275  XCTestExpectation* expectation = [[XCTestExpectation alloc] initWithDescription:@"result called"];
276 
277  [inputPlugin handleMethodCall:methodCall
278  result:^(id _Nullable result) {
279  XCTAssertNil(result);
280  [expectation fulfill];
281  }];
282  XCTAssertNil(inputPlugin.activeView);
283  [self waitForExpectations:@[ expectation ] timeout:1.0];
284 }
285 
286 - (void)testInvokeStartLiveTextInput {
287  FlutterMethodCall* methodCall =
288  [FlutterMethodCall methodCallWithMethodName:@"TextInput.startLiveTextInput" arguments:nil];
289  FlutterTextInputPlugin* mockPlugin = OCMPartialMock(textInputPlugin);
290  [mockPlugin handleMethodCall:methodCall
291  result:^(id _Nullable result){
292  }];
293  OCMVerify([mockPlugin startLiveTextInput]);
294 }
295 
296 - (void)testNoDanglingEnginePointer {
297  __weak FlutterTextInputPlugin* weakFlutterTextInputPlugin;
298  FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
299  __weak FlutterEngine* weakFlutterEngine;
300 
301  FlutterTextInputView* currentView;
302 
303  // The engine instance will be deallocated after the autorelease pool is drained.
304  @autoreleasepool {
305  FlutterEngine* flutterEngine = OCMClassMock([FlutterEngine class]);
306  weakFlutterEngine = flutterEngine;
307  XCTAssertNotNil(weakFlutterEngine, @"flutter engine must not be nil");
308  FlutterTextInputPlugin* flutterTextInputPlugin = [[FlutterTextInputPlugin alloc]
309  initWithDelegate:(id<FlutterTextInputDelegate>)flutterEngine];
310  weakFlutterTextInputPlugin = flutterTextInputPlugin;
311  flutterTextInputPlugin.viewController = flutterViewController;
312 
313  // Set client so the text input plugin has an active view.
314  NSDictionary* config = self.mutableTemplateCopy;
315  FlutterMethodCall* setClientCall =
316  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
317  arguments:@[ [NSNumber numberWithInt:123], config ]];
318  [flutterTextInputPlugin handleMethodCall:setClientCall
319  result:^(id _Nullable result){
320  }];
321  currentView = flutterTextInputPlugin.activeView;
322  }
323 
324  XCTAssertNil(weakFlutterEngine, @"flutter engine must be nil");
325  XCTAssertNotNil(currentView, @"current view must not be nil");
326 
327  XCTAssertNil(weakFlutterTextInputPlugin);
328  // Verify that the view can no longer access the deallocated engine/text input plugin
329  // instance.
330  XCTAssertNil(currentView.textInputDelegate);
331 }
332 
333 - (void)testSecureInput {
334  NSDictionary* config = self.mutableTemplateCopy;
335  [config setValue:@"YES" forKey:@"obscureText"];
336  [self setClientId:123 configuration:config];
337 
338  // Find all the FlutterTextInputViews we created.
339  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
340 
341  // There are no autofill and the mock framework requested a secure entry. The first and only
342  // inserted FlutterTextInputView should be a secure text entry one.
343  FlutterTextInputView* inputView = inputFields[0];
344 
345  // Verify secureTextEntry is set to the correct value.
346  XCTAssertTrue(inputView.secureTextEntry);
347 
348  // Verify keyboardType is set to the default value.
349  XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeDefault);
350 
351  // We should have only ever created one FlutterTextInputView.
352  XCTAssertEqual(inputFields.count, 1ul);
353 
354  // The one FlutterTextInputView we inserted into the view hierarchy should be the text input
355  // plugin's active text input view.
356  XCTAssertEqual(inputView, textInputPlugin.textInputView);
357 
358  // Despite not given an id in configuration, inputView has
359  // an autofill id.
360  XCTAssert(inputView.autofillId.length > 0);
361 }
362 
363 - (void)testKeyboardType {
364  NSDictionary* config = self.mutableTemplateCopy;
365  [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"];
366  [self setClientId:123 configuration:config];
367 
368  // Find all the FlutterTextInputViews we created.
369  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
370 
371  FlutterTextInputView* inputView = inputFields[0];
372 
373  // Verify keyboardType is set to the value specified in config.
374  XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeURL);
375 }
376 
377 - (void)testKeyboardTypeWebSearch {
378  NSDictionary* config = self.mutableTemplateCopy;
379  [config setValue:@{@"name" : @"TextInputType.webSearch"} forKey:@"inputType"];
380  [self setClientId:123 configuration:config];
381 
382  // Find all the FlutterTextInputViews we created.
383  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
384 
385  FlutterTextInputView* inputView = inputFields[0];
386 
387  // Verify keyboardType is set to the value specified in config.
388  XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeWebSearch);
389 }
390 
391 - (void)testKeyboardTypeTwitter {
392  NSDictionary* config = self.mutableTemplateCopy;
393  [config setValue:@{@"name" : @"TextInputType.twitter"} forKey:@"inputType"];
394  [self setClientId:123 configuration:config];
395 
396  // Find all the FlutterTextInputViews we created.
397  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
398 
399  FlutterTextInputView* inputView = inputFields[0];
400 
401  // Verify keyboardType is set to the value specified in config.
402  XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeTwitter);
403 }
404 
405 - (void)testVisiblePasswordUseAlphanumeric {
406  NSDictionary* config = self.mutableTemplateCopy;
407  [config setValue:@{@"name" : @"TextInputType.visiblePassword"} forKey:@"inputType"];
408  [self setClientId:123 configuration:config];
409 
410  // Find all the FlutterTextInputViews we created.
411  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
412 
413  FlutterTextInputView* inputView = inputFields[0];
414 
415  // Verify keyboardType is set to the value specified in config.
416  XCTAssertEqual(inputView.keyboardType, UIKeyboardTypeASCIICapable);
417 }
418 
419 - (void)testSettingKeyboardTypeNoneDisablesSystemKeyboard {
420  NSDictionary* config = self.mutableTemplateCopy;
421  [config setValue:@{@"name" : @"TextInputType.none"} forKey:@"inputType"];
422  [self setClientId:123 configuration:config];
423 
424  // Verify the view's inputViewController is not nil;
425  XCTAssertNotNil(textInputPlugin.activeView.inputViewController);
426 
427  [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"];
428  [self setClientId:124 configuration:config];
429  XCTAssertNotNil(textInputPlugin.activeView);
430  XCTAssertNil(textInputPlugin.activeView.inputViewController);
431 }
432 
433 - (void)testAutocorrectionPromptRectAppearsBeforeIOS17AndDoesNotAppearAfterIOS17 {
434  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
435  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
436 
437  if (@available(iOS 17.0, *)) {
438  // Auto-correction prompt is disabled in iOS 17+.
439  OCMVerify(never(), [engine flutterTextInputView:inputView
440  showAutocorrectionPromptRectForStart:0
441  end:1
442  withClient:0]);
443  } else {
444  OCMVerify([engine flutterTextInputView:inputView
445  showAutocorrectionPromptRectForStart:0
446  end:1
447  withClient:0]);
448  }
449 }
450 
451 - (void)testIgnoresSelectionChangeIfSelectionIsDisabled {
452  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
453  __block int updateCount = 0;
454  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]])
455  .andDo(^(NSInvocation* invocation) {
456  updateCount++;
457  });
458 
459  [inputView.text setString:@"Some initial text"];
460  XCTAssertEqual(updateCount, 0);
461 
462  FlutterTextRange* textRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)];
463  [inputView setSelectedTextRange:textRange];
464  XCTAssertEqual(updateCount, 1);
465 
466  // Disable the interactive selection.
467  NSDictionary* config = self.mutableTemplateCopy;
468  [config setValue:@(NO) forKey:@"enableInteractiveSelection"];
469  [config setValue:@(NO) forKey:@"obscureText"];
470  [config setValue:@(NO) forKey:@"enableDeltaModel"];
471  [inputView configureWithDictionary:config];
472 
473  textRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(2, 3)];
474  [inputView setSelectedTextRange:textRange];
475  // The update count does not change.
476  XCTAssertEqual(updateCount, 1);
477 }
478 
479 - (void)testAutocorrectionPromptRectDoesNotAppearDuringScribble {
480  // Auto-correction prompt is disabled in iOS 17+.
481  if (@available(iOS 17.0, *)) {
482  return;
483  }
484 
485  if (@available(iOS 14.0, *)) {
486  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
487 
488  __block int callCount = 0;
489  OCMStub([engine flutterTextInputView:inputView
490  showAutocorrectionPromptRectForStart:0
491  end:1
492  withClient:0])
493  .andDo(^(NSInvocation* invocation) {
494  callCount++;
495  });
496 
497  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
498  // showAutocorrectionPromptRectForStart fires in response to firstRectForRange
499  XCTAssertEqual(callCount, 1);
500 
501  UIScribbleInteraction* scribbleInteraction =
502  [[UIScribbleInteraction alloc] initWithDelegate:inputView];
503 
504  [inputView scribbleInteractionWillBeginWriting:scribbleInteraction];
505  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
506  // showAutocorrectionPromptRectForStart does not fire in response to setMarkedText during a
507  // scribble interaction.firstRectForRange
508  XCTAssertEqual(callCount, 1);
509 
510  [inputView scribbleInteractionDidFinishWriting:scribbleInteraction];
511  [inputView resetScribbleInteractionStatusIfEnding];
512  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
513  // showAutocorrectionPromptRectForStart fires in response to firstRectForRange.
514  XCTAssertEqual(callCount, 2);
515 
516  inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing;
517  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
518  // showAutocorrectionPromptRectForStart does not fire in response to firstRectForRange during a
519  // scribble-initiated focus.
520  XCTAssertEqual(callCount, 2);
521 
522  inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused;
523  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
524  // showAutocorrectionPromptRectForStart does not fire in response to firstRectForRange after a
525  // scribble-initiated focus.
526  XCTAssertEqual(callCount, 2);
527 
528  inputView.scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
529  [inputView firstRectForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]];
530  // showAutocorrectionPromptRectForStart fires in response to firstRectForRange.
531  XCTAssertEqual(callCount, 3);
532  }
533 }
534 
535 - (void)testInputHiderOverlapWithTextWhenScribbleIsDisabledAfterIOS17AndDoesNotOverlapBeforeIOS17 {
536  FlutterTextInputPlugin* myInputPlugin =
537  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
538 
539  FlutterMethodCall* setClientCall =
540  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
541  arguments:@[ @(123), self.mutableTemplateCopy ]];
542  [myInputPlugin handleMethodCall:setClientCall
543  result:^(id _Nullable result){
544  }];
545 
546  FlutterTextInputView* mockInputView = OCMPartialMock(myInputPlugin.activeView);
547  OCMStub([mockInputView isScribbleAvailable]).andReturn(NO);
548 
549  // yOffset = 200.
550  NSArray* yOffsetMatrix = @[ @1, @0, @0, @0, @0, @1, @0, @0, @0, @0, @1, @0, @0, @200, @0, @1 ];
551 
552  FlutterMethodCall* setPlatformViewClientCall =
553  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setEditableSizeAndTransform"
554  arguments:@{@"transform" : yOffsetMatrix}];
555  [myInputPlugin handleMethodCall:setPlatformViewClientCall
556  result:^(id _Nullable result){
557  }];
558 
559  if (@available(iOS 17, *)) {
560  XCTAssert(CGRectEqualToRect(myInputPlugin.inputHider.frame, CGRectMake(0, 200, 0, 0)),
561  @"The input hider should overlap with the text on and after iOS 17");
562 
563  } else {
564  XCTAssert(CGRectEqualToRect(myInputPlugin.inputHider.frame, CGRectZero),
565  @"The input hider should be on the origin of screen on and before iOS 16.");
566  }
567 }
568 
569 - (void)testTextRangeFromPositionMatchesUITextViewBehavior {
570  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
573 
574  FlutterTextRange* flutterRange = (FlutterTextRange*)[inputView textRangeFromPosition:fromPosition
575  toPosition:toPosition];
576  NSRange range = flutterRange.range;
577 
578  XCTAssertEqual(range.location, 0ul);
579  XCTAssertEqual(range.length, 2ul);
580 }
581 
582 - (void)testTextInRange {
583  NSDictionary* config = self.mutableTemplateCopy;
584  [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"];
585  [self setClientId:123 configuration:config];
586  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
587  FlutterTextInputView* inputView = inputFields[0];
588 
589  [inputView insertText:@"test"];
590 
591  UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 20)];
592  NSString* substring = [inputView textInRange:range];
593  XCTAssertEqual(substring.length, 4ul);
594 
595  range = [FlutterTextRange rangeWithNSRange:NSMakeRange(10, 20)];
596  substring = [inputView textInRange:range];
597  XCTAssertEqual(substring.length, 0ul);
598 }
599 
600 - (void)testInsertTextReplacesEntireMarkedRangeForDeadKeySequence {
601  // Regression test for https://github.com/flutter/flutter/issues/59541#issuecomment-4617810595.
602  NSDictionary* config = self.mutableTemplateCopy;
603  [self setClientId:123 configuration:config];
604  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
605  FlutterTextInputView* inputView = inputFields[0];
606 
607  [inputView setMarkedText:@"��" selectedRange:NSMakeRange(1, 0)];
608  [inputView insertText:@"��"];
609 
610  UITextRange* range = [inputView textRangeFromPosition:inputView.beginningOfDocument
611  toPosition:inputView.endOfDocument];
612  NSString* substring = [inputView textInRange:range];
613  XCTAssertEqualObjects(substring, @"Á");
614 }
615 
616 - (void)testTextInRangeAcceptsNSNotFoundLocationGracefully {
617  NSDictionary* config = self.mutableTemplateCopy;
618  [self setClientId:123 configuration:config];
619  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
620  FlutterTextInputView* inputView = inputFields[0];
621 
622  [inputView insertText:@"text"];
623  UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(NSNotFound, 0)];
624 
625  NSString* substring = [inputView textInRange:range];
626  XCTAssertNil(substring);
627 }
628 
629 - (void)testStandardEditActions {
630  NSDictionary* config = self.mutableTemplateCopy;
631  [self setClientId:123 configuration:config];
632  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
633  FlutterTextInputView* inputView = inputFields[0];
634 
635  [inputView insertText:@"aaaa"];
636  [inputView selectAll:nil];
637  [inputView cut:nil];
638  [inputView insertText:@"bbbb"];
639  XCTAssertTrue([inputView canPerformAction:@selector(paste:) withSender:nil]);
640  [inputView paste:nil];
641  [inputView selectAll:nil];
642  [inputView copy:nil];
643  [inputView paste:nil];
644  [inputView selectAll:nil];
645  [inputView delete:nil];
646  [inputView paste:nil];
647  [inputView paste:nil];
648 
649  UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 30)];
650  NSString* substring = [inputView textInRange:range];
651  XCTAssertEqualObjects(substring, @"bbbbaaaabbbbaaaa");
652 }
653 
654 - (void)testCanPerformActionForSelectActions {
655  NSDictionary* config = self.mutableTemplateCopy;
656  [self setClientId:123 configuration:config];
657  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
658  FlutterTextInputView* inputView = inputFields[0];
659 
660  XCTAssertFalse([inputView canPerformAction:@selector(selectAll:) withSender:nil]);
661 
662  [inputView insertText:@"aaaa"];
663 
664  XCTAssertTrue([inputView canPerformAction:@selector(selectAll:) withSender:nil]);
665 }
666 
667 - (void)testCanPerformActionCaptureTextFromCamera {
668  if (@available(iOS 15.0, *)) {
669  NSDictionary* config = self.mutableTemplateCopy;
670  [self setClientId:123 configuration:config];
671  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
672  FlutterTextInputView* inputView = inputFields[0];
673 
674  [inputView becomeFirstResponder];
675  XCTAssertTrue([inputView canPerformAction:@selector(captureTextFromCamera:) withSender:nil]);
676 
677  [inputView insertText:@"test"];
678  [inputView selectAll:nil];
679  XCTAssertTrue([inputView canPerformAction:@selector(captureTextFromCamera:) withSender:nil]);
680  }
681 }
682 
683 - (void)testDeletingBackward {
684  NSDictionary* config = self.mutableTemplateCopy;
685  [self setClientId:123 configuration:config];
686  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
687  FlutterTextInputView* inputView = inputFields[0];
688 
689  [inputView insertText:@"������� text ������������������������������������������� "];
690  [inputView deleteBackward];
691  [inputView deleteBackward];
692 
693  // Thai vowel is removed.
694  XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳ด");
695  [inputView deleteBackward];
696  XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦🇺🇳");
697  [inputView deleteBackward];
698  XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰👨‍👩‍👧‍👦");
699  [inputView deleteBackward];
700  XCTAssertEqualObjects(inputView.text, @"ឹ😀 text 🥰");
701  [inputView deleteBackward];
702 
703  XCTAssertEqualObjects(inputView.text, @"ឹ😀 text ");
704  [inputView deleteBackward];
705  [inputView deleteBackward];
706  [inputView deleteBackward];
707  [inputView deleteBackward];
708  [inputView deleteBackward];
709  [inputView deleteBackward];
710 
711  XCTAssertEqualObjects(inputView.text, @"ឹ😀");
712  [inputView deleteBackward];
713  XCTAssertEqualObjects(inputView.text, @"ឹ");
714  [inputView deleteBackward];
715  XCTAssertEqualObjects(inputView.text, @"");
716 }
717 
718 // This tests the workaround to fix an iOS 16 bug
719 // See: https://github.com/flutter/flutter/issues/111494
720 - (void)testSystemOnlyAddingPartialComposedCharacter {
721  NSDictionary* config = self.mutableTemplateCopy;
722  [self setClientId:123 configuration:config];
723  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
724  FlutterTextInputView* inputView = inputFields[0];
725 
726  [inputView insertText:@"�������������������������"];
727  [inputView deleteBackward];
728 
729  // Insert the first unichar in the emoji.
730  [inputView insertText:[@"�������������������������" substringWithRange:NSMakeRange(0, 1)]];
731  [inputView insertText:@"���"];
732 
733  XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦아");
734 
735  // Deleting 아.
736  [inputView deleteBackward];
737  // 👨‍👩‍👧‍👦 should be the current string.
738 
739  [inputView insertText:@"����"];
740  [inputView deleteBackward];
741  // Insert the first unichar in the emoji.
742  [inputView insertText:[@"����" substringWithRange:NSMakeRange(0, 1)]];
743  [inputView insertText:@"���"];
744  XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦😀아");
745 
746  // Deleting 아.
747  [inputView deleteBackward];
748  // 👨‍👩‍👧‍👦😀 should be the current string.
749 
750  [inputView deleteBackward];
751  // Insert the first unichar in the emoji.
752  [inputView insertText:[@"����" substringWithRange:NSMakeRange(0, 1)]];
753  [inputView insertText:@"���"];
754 
755  XCTAssertEqualObjects(inputView.text, @"👨‍👩‍👧‍👦😀아");
756 }
757 
758 - (void)testCachedComposedCharacterClearedAtKeyboardInteraction {
759  NSDictionary* config = self.mutableTemplateCopy;
760  [self setClientId:123 configuration:config];
761  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
762  FlutterTextInputView* inputView = inputFields[0];
763 
764  [inputView insertText:@"�������������������������"];
765  [inputView deleteBackward];
766  [inputView shouldChangeTextInRange:OCMClassMock([UITextRange class]) replacementText:@""];
767 
768  // Insert the first unichar in the emoji.
769  NSString* brokenEmoji = [@"�������������������������" substringWithRange:NSMakeRange(0, 1)];
770  [inputView insertText:brokenEmoji];
771  [inputView insertText:@"���"];
772 
773  NSString* finalText = [NSString stringWithFormat:@"%@���", brokenEmoji];
774  XCTAssertEqualObjects(inputView.text, finalText);
775 }
776 
777 - (void)testPastingNonTextDisallowed {
778  NSDictionary* config = self.mutableTemplateCopy;
779  [self setClientId:123 configuration:config];
780  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
781  FlutterTextInputView* inputView = inputFields[0];
782 
783  UIPasteboard.generalPasteboard.color = UIColor.redColor;
784  XCTAssertNil(UIPasteboard.generalPasteboard.string);
785  XCTAssertFalse([inputView canPerformAction:@selector(paste:) withSender:nil]);
786  [inputView paste:nil];
787 
788  XCTAssertEqualObjects(inputView.text, @"");
789 }
790 
791 - (void)testNoZombies {
792  // Regression test for https://github.com/flutter/flutter/issues/62501.
793  FlutterSecureTextInputView* passwordView =
794  [[FlutterSecureTextInputView alloc] initWithOwner:textInputPlugin];
795 
796  @autoreleasepool {
797  // Initialize the lazy textField.
798  [passwordView.textField description];
799  }
800  XCTAssert([[passwordView.textField description] containsString:@"TextField"]);
801 }
802 
803 - (void)testInputViewCrash {
804  FlutterTextInputView* activeView = nil;
805  @autoreleasepool {
806  FlutterEngine* flutterEngine = [[FlutterEngine alloc] init];
807  FlutterTextInputPlugin* inputPlugin = [[FlutterTextInputPlugin alloc]
808  initWithDelegate:(id<FlutterTextInputDelegate>)flutterEngine];
809  activeView = inputPlugin.activeView;
810  }
811  [activeView updateEditingState];
812 }
813 
814 - (void)testDoNotReuseInputViews {
815  NSDictionary* config = self.mutableTemplateCopy;
816  [self setClientId:123 configuration:config];
817  FlutterTextInputView* currentView = textInputPlugin.activeView;
818  [self setClientId:456 configuration:config];
819 
820  XCTAssertNotNil(currentView);
821  XCTAssertNotNil(textInputPlugin.activeView);
822  XCTAssertNotEqual(currentView, textInputPlugin.activeView);
823 }
824 
825 - (void)ensureOnlyActiveViewCanBecomeFirstResponder {
826  for (FlutterTextInputView* inputView in self.installedInputViews) {
827  XCTAssertEqual(inputView.canBecomeFirstResponder, inputView == textInputPlugin.activeView);
828  }
829 }
830 
831 - (void)testPropagatePressEventsToViewController {
832  FlutterViewController* mockViewController = OCMPartialMock(viewController);
833  OCMStub([mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]);
834  OCMStub([mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]);
835 
836  textInputPlugin.viewController = mockViewController;
837 
838  NSDictionary* config = self.mutableTemplateCopy;
839  [self setClientId:123 configuration:config];
840  FlutterTextInputView* currentView = textInputPlugin.activeView;
841  [self setTextInputShow];
842 
843  [currentView pressesBegan:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil]
844  withEvent:OCMClassMock([UIPressesEvent class])];
845 
846  OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil]
847  withEvent:[OCMArg isNotNil]]);
848  OCMVerify(times(0), [mockViewController pressesEnded:[OCMArg isNotNil]
849  withEvent:[OCMArg isNotNil]]);
850 
851  [currentView pressesEnded:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil]
852  withEvent:OCMClassMock([UIPressesEvent class])];
853 
854  OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil]
855  withEvent:[OCMArg isNotNil]]);
856  OCMVerify(times(1), [mockViewController pressesEnded:[OCMArg isNotNil]
857  withEvent:[OCMArg isNotNil]]);
858 }
859 
860 - (void)testPropagatePressEventsToViewController2 {
861  FlutterViewController* mockViewController = OCMPartialMock(viewController);
862  OCMStub([mockViewController pressesBegan:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]);
863  OCMStub([mockViewController pressesEnded:[OCMArg isNotNil] withEvent:[OCMArg isNotNil]]);
864 
865  textInputPlugin.viewController = mockViewController;
866 
867  NSDictionary* config = self.mutableTemplateCopy;
868  [self setClientId:123 configuration:config];
869  [self setTextInputShow];
870  FlutterTextInputView* currentView = textInputPlugin.activeView;
871 
872  [currentView pressesBegan:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil]
873  withEvent:OCMClassMock([UIPressesEvent class])];
874 
875  OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil]
876  withEvent:[OCMArg isNotNil]]);
877  OCMVerify(times(0), [mockViewController pressesEnded:[OCMArg isNotNil]
878  withEvent:[OCMArg isNotNil]]);
879 
880  // Switch focus to a different view.
881  [self setClientId:321 configuration:config];
882  [self setTextInputShow];
883  NSAssert(textInputPlugin.activeView, @"active view must not be nil");
884  NSAssert(textInputPlugin.activeView != currentView, @"active view must change");
885  currentView = textInputPlugin.activeView;
886  [currentView pressesEnded:[NSSet setWithObjects:OCMClassMock([UIPress class]), nil]
887  withEvent:OCMClassMock([UIPressesEvent class])];
888 
889  OCMVerify(times(1), [mockViewController pressesBegan:[OCMArg isNotNil]
890  withEvent:[OCMArg isNotNil]]);
891  OCMVerify(times(1), [mockViewController pressesEnded:[OCMArg isNotNil]
892  withEvent:[OCMArg isNotNil]]);
893 }
894 
895 - (void)testHotRestart {
896  flutter::MockPlatformViewDelegate mock_platform_view_delegate;
897  auto thread = std::make_unique<fml::Thread>("TextInputHotRestart");
898  auto thread_task_runner = thread->GetTaskRunner();
899  flutter::TaskRunners runners(/*label=*/self.name.UTF8String,
900  /*platform=*/thread_task_runner,
901  /*raster=*/thread_task_runner,
902  /*ui=*/thread_task_runner,
903  /*io=*/thread_task_runner);
904  id mockFlutterView = OCMClassMock([FlutterView class]);
905  id mockFlutterTextInputPlugin = OCMClassMock([FlutterTextInputPlugin class]);
906  id mockFlutterViewController = OCMClassMock([FlutterViewController class]);
907  OCMStub([mockFlutterViewController viewIfLoaded]).andReturn(mockFlutterView);
908  OCMStub([mockFlutterViewController textInputPlugin]).andReturn(mockFlutterTextInputPlugin);
909 
910  fml::AutoResetWaitableEvent latch;
911  thread_task_runner->PostTask([&] {
912  auto platform_view = std::make_unique<flutter::PlatformViewIOS>(
913  /*delegate=*/mock_platform_view_delegate,
914  /*platform_views_controller=*/nil,
915  /*task_runners=*/runners,
916  /*is_gpu_disabled_sync_switch=*/std::make_shared<fml::SyncSwitch>());
917 
918  platform_view->SetOwnerViewController(mockFlutterViewController);
919 
920  OCMExpect([mockFlutterTextInputPlugin reset]);
921  platform_view->OnPreEngineRestart();
922  OCMVerifyAll(mockFlutterView);
923 
924  latch.Signal();
925  });
926  latch.Wait();
927 }
928 
929 - (void)testUpdateSecureTextEntry {
930  NSDictionary* config = self.mutableTemplateCopy;
931  [config setValue:@"YES" forKey:@"obscureText"];
932  [self setClientId:123 configuration:config];
933 
934  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
935  FlutterTextInputView* inputView = OCMPartialMock(inputFields[0]);
936 
937  __block int callCount = 0;
938  OCMStub([inputView reloadInputViews]).andDo(^(NSInvocation* invocation) {
939  callCount++;
940  });
941 
942  XCTAssertTrue(inputView.isSecureTextEntry);
943 
944  config = self.mutableTemplateCopy;
945  [config setValue:@"NO" forKey:@"obscureText"];
946  [self updateConfig:config];
947 
948  XCTAssertEqual(callCount, 1);
949  XCTAssertFalse(inputView.isSecureTextEntry);
950 }
951 
952 - (void)testInputActionContinueAction {
953  id mockBinaryMessenger = OCMClassMock([FlutterBinaryMessengerRelay class]);
954  FlutterEngine* testEngine = [[FlutterEngine alloc] init];
955  [testEngine setBinaryMessenger:mockBinaryMessenger];
956  [testEngine runWithEntrypoint:FlutterDefaultDartEntrypoint initialRoute:@"test"];
957 
958  FlutterTextInputPlugin* inputPlugin =
959  [[FlutterTextInputPlugin alloc] initWithDelegate:(id<FlutterTextInputDelegate>)testEngine];
960  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:inputPlugin];
961 
962  [testEngine flutterTextInputView:inputView
963  performAction:FlutterTextInputActionContinue
964  withClient:123];
965 
966  FlutterMethodCall* methodCall =
967  [FlutterMethodCall methodCallWithMethodName:@"TextInputClient.performAction"
968  arguments:@[ @(123), @"TextInputAction.continueAction" ]];
969  NSData* encodedMethodCall = [[FlutterJSONMethodCodec sharedInstance] encodeMethodCall:methodCall];
970  OCMVerify([mockBinaryMessenger sendOnChannel:@"flutter/textinput" message:encodedMethodCall]);
971 }
972 
973 - (void)testDisablingAutocorrectDisablesSpellChecking {
974  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
975 
976  // Disable the interactive selection.
977  NSDictionary* config = self.mutableTemplateCopy;
978  [inputView configureWithDictionary:config];
979 
980  XCTAssertEqual(inputView.autocorrectionType, UITextAutocorrectionTypeDefault);
981  XCTAssertEqual(inputView.spellCheckingType, UITextSpellCheckingTypeDefault);
982 
983  [config setValue:@(NO) forKey:@"autocorrect"];
984  [inputView configureWithDictionary:config];
985 
986  XCTAssertEqual(inputView.autocorrectionType, UITextAutocorrectionTypeNo);
987  XCTAssertEqual(inputView.spellCheckingType, UITextSpellCheckingTypeNo);
988 }
989 
990 - (void)testEnableInlinePredictionFromConfiguration API_AVAILABLE(ios(17.0)) {
991  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
992  NSMutableDictionary* config = self.mutableTemplateCopy;
993 
994  // Template does not include enableInlinePrediction -> disabled.
995  [inputView configureWithDictionary:config];
996  XCTAssertEqual(inputView.inlinePredictionType, UITextInlinePredictionTypeNo);
997 
998  [config setValue:@NO forKey:@"enableInlinePrediction"];
999  [inputView configureWithDictionary:config];
1000  XCTAssertEqual(inputView.inlinePredictionType, UITextInlinePredictionTypeNo);
1001 
1002  [config setValue:@YES forKey:@"enableInlinePrediction"];
1003  [inputView configureWithDictionary:config];
1004  XCTAssertEqual(inputView.inlinePredictionType, UITextInlinePredictionTypeYes);
1005 
1006  // Explicit nil / missing key -> disabled.
1007  [config removeObjectForKey:@"enableInlinePrediction"];
1008  [inputView configureWithDictionary:config];
1009  XCTAssertEqual(inputView.inlinePredictionType, UITextInlinePredictionTypeNo);
1010 
1011  // Key present with NSNull (e.g. framework sent null) -> disabled.
1012  [config setValue:[NSNull null] forKey:@"enableInlinePrediction"];
1013  [inputView configureWithDictionary:config];
1014  XCTAssertEqual(inputView.inlinePredictionType, UITextInlinePredictionTypeNo);
1015 }
1016 
1017 - (void)testReplaceTestLocalAdjustSelectionAndMarkedTextRange {
1018  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1019  [inputView setMarkedText:@"test text" selectedRange:NSMakeRange(0, 5)];
1020  NSRange selectedTextRange = ((FlutterTextRange*)inputView.selectedTextRange).range;
1021  const NSRange markedTextRange = ((FlutterTextRange*)inputView.markedTextRange).range;
1022  XCTAssertEqual(selectedTextRange.location, 0ul);
1023  XCTAssertEqual(selectedTextRange.length, 5ul);
1024  XCTAssertEqual(markedTextRange.location, 0ul);
1025  XCTAssertEqual(markedTextRange.length, 9ul);
1026 
1027  // Replaces space with space.
1028  [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(4, 1)] withText:@" "];
1029  selectedTextRange = ((FlutterTextRange*)inputView.selectedTextRange).range;
1030 
1031  XCTAssertEqual(selectedTextRange.location, 5ul);
1032  XCTAssertEqual(selectedTextRange.length, 0ul);
1033  XCTAssertEqual(inputView.markedTextRange, nil);
1034 }
1035 
1036 - (void)testFlutterTextInputViewIsNotClearWhenKeyboardShowAndHide {
1037  // Regression test for https://github.com/flutter/flutter/issues/172250.
1038  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1039  [inputView setMarkedText:@"test text" selectedRange:NSMakeRange(0, 5)];
1040  XCTAssertEqualObjects(inputView.text, @"test text");
1041 
1042  // Showing keyboard does not trigger clearing of marked text.
1043  [self setTextInputShow];
1044  XCTAssertEqualObjects(inputView.text, @"test text");
1045 
1046  // Hiding keyboard does not trigger clearing of marked text.
1047  [self setTextInputHide];
1048  XCTAssertEqualObjects(inputView.text, @"test text");
1049 }
1050 
1051 - (void)testFlutterTextInputViewOnlyRespondsToInsertionPointColorBelowIOS17 {
1052  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1053  // [UITextInputTraits insertionPointColor] is non-public API, so @selector(insertionPointColor)
1054  // would generate a compile-time warning.
1055  SEL insertionPointColor = NSSelectorFromString(@"insertionPointColor");
1056  BOOL respondsToInsertionPointColor = [inputView respondsToSelector:insertionPointColor];
1057  if (@available(iOS 17, *)) {
1058  XCTAssertFalse(respondsToInsertionPointColor);
1059  } else {
1060  XCTAssertTrue(respondsToInsertionPointColor);
1061  }
1062 }
1063 
1064 - (void)testSetAttributedMarkedTextSelectedRange API_AVAILABLE(ios(17.0)) {
1065  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1066  NSAttributedString* attributedText =
1067  [[NSAttributedString alloc] initWithString:@"inline prediction"
1068  attributes:@{
1069  NSForegroundColorAttributeName : [UIColor grayColor],
1070  }];
1071  [inputView setAttributedMarkedText:attributedText selectedRange:NSMakeRange(0, 7)];
1072 
1073  XCTAssertEqualObjects(inputView.text, @"inline prediction");
1074  NSRange selectedRange = ((FlutterTextRange*)inputView.selectedTextRange).range;
1075  XCTAssertEqual(selectedRange.location, 0ul);
1076  XCTAssertEqual(selectedRange.length, 7ul);
1077  FlutterTextRange* markedRange = (FlutterTextRange*)inputView.markedTextRange;
1078  XCTAssertNotNil(markedRange);
1079  XCTAssertEqual(markedRange.range.location, 0ul);
1080  // Marked range length must match the attributed string length (17 for "inline prediction").
1081  XCTAssertEqual(markedRange.range.length, 17ul);
1082 
1083  // Nil attributed string should behave like empty string.
1084  [inputView setAttributedMarkedText:nil selectedRange:NSMakeRange(0, 0)];
1085  XCTAssertEqualObjects(inputView.text, @"");
1086  XCTAssertNil(inputView.markedTextRange);
1087 }
1088 
1089 #pragma mark - TextEditingDelta tests
1090 - (void)testTextEditingDeltasAreGeneratedOnTextInput {
1091  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1092  inputView.enableDeltaModel = YES;
1093 
1094  __block int updateCount = 0;
1095 
1096  [inputView insertText:@"text to insert"];
1097  OCMExpect(
1098  [engine
1099  flutterTextInputView:inputView
1100  updateEditingClient:0
1101  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1102  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1103  isEqualToString:@""]) &&
1104  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1105  isEqualToString:@"text to insert"]) &&
1106  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 0) &&
1107  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 0);
1108  }]])
1109  .andDo(^(NSInvocation* invocation) {
1110  updateCount++;
1111  });
1112  XCTAssertEqual(updateCount, 0);
1113 
1114  [self flushScheduledAsyncBlocks];
1115 
1116  // Update the framework exactly once.
1117  XCTAssertEqual(updateCount, 1);
1118 
1119  [inputView deleteBackward];
1120  OCMExpect([engine flutterTextInputView:inputView
1121  updateEditingClient:0
1122  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1123  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1124  isEqualToString:@"text to insert"]) &&
1125  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1126  isEqualToString:@""]) &&
1127  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"]
1128  intValue] == 13) &&
1129  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"]
1130  intValue] == 14);
1131  }]])
1132  .andDo(^(NSInvocation* invocation) {
1133  updateCount++;
1134  });
1135  [self flushScheduledAsyncBlocks];
1136  XCTAssertEqual(updateCount, 2);
1137 
1138  inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)];
1139  OCMExpect([engine flutterTextInputView:inputView
1140  updateEditingClient:0
1141  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1142  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1143  isEqualToString:@"text to inser"]) &&
1144  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1145  isEqualToString:@""]) &&
1146  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"]
1147  intValue] == -1) &&
1148  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"]
1149  intValue] == -1);
1150  }]])
1151  .andDo(^(NSInvocation* invocation) {
1152  updateCount++;
1153  });
1154  [self flushScheduledAsyncBlocks];
1155  XCTAssertEqual(updateCount, 3);
1156 
1157  [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]
1158  withText:@"replace text"];
1159  OCMExpect(
1160  [engine
1161  flutterTextInputView:inputView
1162  updateEditingClient:0
1163  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1164  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1165  isEqualToString:@"text to inser"]) &&
1166  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1167  isEqualToString:@"replace text"]) &&
1168  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 0) &&
1169  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 1);
1170  }]])
1171  .andDo(^(NSInvocation* invocation) {
1172  updateCount++;
1173  });
1174  [self flushScheduledAsyncBlocks];
1175  XCTAssertEqual(updateCount, 4);
1176 
1177  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1178  OCMExpect([engine flutterTextInputView:inputView
1179  updateEditingClient:0
1180  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1181  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1182  isEqualToString:@"replace textext to inser"]) &&
1183  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1184  isEqualToString:@"marked text"]) &&
1185  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"]
1186  intValue] == 12) &&
1187  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"]
1188  intValue] == 12);
1189  }]])
1190  .andDo(^(NSInvocation* invocation) {
1191  updateCount++;
1192  });
1193  [self flushScheduledAsyncBlocks];
1194  XCTAssertEqual(updateCount, 5);
1195 
1196  [inputView unmarkText];
1197  OCMExpect([engine
1198  flutterTextInputView:inputView
1199  updateEditingClient:0
1200  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1201  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1202  isEqualToString:@"replace textmarked textext to inser"]) &&
1203  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1204  isEqualToString:@""]) &&
1205  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] ==
1206  -1) &&
1207  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] ==
1208  -1);
1209  }]])
1210  .andDo(^(NSInvocation* invocation) {
1211  updateCount++;
1212  });
1213  [self flushScheduledAsyncBlocks];
1214 
1215  XCTAssertEqual(updateCount, 6);
1216  OCMVerifyAll(engine);
1217 }
1218 
1219 - (void)testTextEditingDeltasAreBatchedAndForwardedToFramework {
1220  // Setup
1221  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1222  inputView.enableDeltaModel = YES;
1223 
1224  // Expected call.
1225  OCMExpect([engine flutterTextInputView:inputView
1226  updateEditingClient:0
1227  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1228  NSArray* deltas = state[@"deltas"];
1229  NSDictionary* firstDelta = deltas[0];
1230  NSDictionary* secondDelta = deltas[1];
1231  NSDictionary* thirdDelta = deltas[2];
1232  return [firstDelta[@"oldText"] isEqualToString:@""] &&
1233  [firstDelta[@"deltaText"] isEqualToString:@"-"] &&
1234  [firstDelta[@"deltaStart"] intValue] == 0 &&
1235  [firstDelta[@"deltaEnd"] intValue] == 0 &&
1236  [secondDelta[@"oldText"] isEqualToString:@"-"] &&
1237  [secondDelta[@"deltaText"] isEqualToString:@""] &&
1238  [secondDelta[@"deltaStart"] intValue] == 0 &&
1239  [secondDelta[@"deltaEnd"] intValue] == 1 &&
1240  [thirdDelta[@"oldText"] isEqualToString:@""] &&
1241  [thirdDelta[@"deltaText"] isEqualToString:@"���"] &&
1242  [thirdDelta[@"deltaStart"] intValue] == 0 &&
1243  [thirdDelta[@"deltaEnd"] intValue] == 0;
1244  }]]);
1245 
1246  // Simulate user input.
1247  [inputView insertText:@"-"];
1248  [inputView deleteBackward];
1249  [inputView insertText:@"���"];
1250 
1251  [self flushScheduledAsyncBlocks];
1252  OCMVerifyAll(engine);
1253 }
1254 
1255 - (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextReplacement {
1256  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1257  inputView.enableDeltaModel = YES;
1258 
1259  __block int updateCount = 0;
1260  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]])
1261  .andDo(^(NSInvocation* invocation) {
1262  updateCount++;
1263  });
1264 
1265  [inputView.text setString:@"Some initial text"];
1266  XCTAssertEqual(updateCount, 0);
1267 
1268  UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)];
1269  inputView.markedTextRange = range;
1270  inputView.selectedTextRange = nil;
1271  [self flushScheduledAsyncBlocks];
1272  XCTAssertEqual(updateCount, 1);
1273 
1274  [inputView setMarkedText:@"new marked text." selectedRange:NSMakeRange(0, 1)];
1275  OCMVerify([engine
1276  flutterTextInputView:inputView
1277  updateEditingClient:0
1278  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1279  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1280  isEqualToString:@"Some initial text"]) &&
1281  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1282  isEqualToString:@"new marked text."]) &&
1283  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) &&
1284  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17);
1285  }]]);
1286  [self flushScheduledAsyncBlocks];
1287  XCTAssertEqual(updateCount, 2);
1288 }
1289 
1290 - (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextInsertion {
1291  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1292  inputView.enableDeltaModel = YES;
1293 
1294  __block int updateCount = 0;
1295  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]])
1296  .andDo(^(NSInvocation* invocation) {
1297  updateCount++;
1298  });
1299 
1300  [inputView.text setString:@"Some initial text"];
1301  [self flushScheduledAsyncBlocks];
1302  XCTAssertEqual(updateCount, 0);
1303 
1304  UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)];
1305  inputView.markedTextRange = range;
1306  inputView.selectedTextRange = nil;
1307  [self flushScheduledAsyncBlocks];
1308  XCTAssertEqual(updateCount, 1);
1309 
1310  [inputView setMarkedText:@"text." selectedRange:NSMakeRange(0, 1)];
1311  OCMVerify([engine
1312  flutterTextInputView:inputView
1313  updateEditingClient:0
1314  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1315  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1316  isEqualToString:@"Some initial text"]) &&
1317  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1318  isEqualToString:@"text."]) &&
1319  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) &&
1320  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17);
1321  }]]);
1322  [self flushScheduledAsyncBlocks];
1323  XCTAssertEqual(updateCount, 2);
1324 }
1325 
1326 - (void)testTextEditingDeltasAreGeneratedOnSetMarkedTextDeletion {
1327  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1328  inputView.enableDeltaModel = YES;
1329 
1330  __block int updateCount = 0;
1331  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]])
1332  .andDo(^(NSInvocation* invocation) {
1333  updateCount++;
1334  });
1335 
1336  [inputView.text setString:@"Some initial text"];
1337  [self flushScheduledAsyncBlocks];
1338  XCTAssertEqual(updateCount, 0);
1339 
1340  UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(13, 4)];
1341  inputView.markedTextRange = range;
1342  inputView.selectedTextRange = nil;
1343  [self flushScheduledAsyncBlocks];
1344  XCTAssertEqual(updateCount, 1);
1345 
1346  [inputView setMarkedText:@"tex" selectedRange:NSMakeRange(0, 1)];
1347  OCMVerify([engine
1348  flutterTextInputView:inputView
1349  updateEditingClient:0
1350  withDelta:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1351  return ([[state[@"deltas"] objectAtIndex:0][@"oldText"]
1352  isEqualToString:@"Some initial text"]) &&
1353  ([[state[@"deltas"] objectAtIndex:0][@"deltaText"]
1354  isEqualToString:@"tex"]) &&
1355  ([[state[@"deltas"] objectAtIndex:0][@"deltaStart"] intValue] == 13) &&
1356  ([[state[@"deltas"] objectAtIndex:0][@"deltaEnd"] intValue] == 17);
1357  }]]);
1358  [self flushScheduledAsyncBlocks];
1359  XCTAssertEqual(updateCount, 2);
1360 }
1361 
1362 #pragma mark - EditingState tests
1363 
1364 - (void)testUITextInputCallsUpdateEditingStateOnce {
1365  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1366 
1367  __block int updateCount = 0;
1368  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]])
1369  .andDo(^(NSInvocation* invocation) {
1370  updateCount++;
1371  });
1372 
1373  [inputView insertText:@"text to insert"];
1374  // Update the framework exactly once.
1375  XCTAssertEqual(updateCount, 1);
1376 
1377  [inputView deleteBackward];
1378  XCTAssertEqual(updateCount, 2);
1379 
1380  inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)];
1381  XCTAssertEqual(updateCount, 3);
1382 
1383  [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]
1384  withText:@"replace text"];
1385  XCTAssertEqual(updateCount, 4);
1386 
1387  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1388  XCTAssertEqual(updateCount, 5);
1389 
1390  [inputView unmarkText];
1391  XCTAssertEqual(updateCount, 6);
1392 }
1393 
1394 - (void)testUITextInputCallsUpdateEditingStateWithDeltaOnce {
1395  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1396  inputView.enableDeltaModel = YES;
1397 
1398  __block int updateCount = 0;
1399  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]])
1400  .andDo(^(NSInvocation* invocation) {
1401  updateCount++;
1402  });
1403 
1404  [inputView insertText:@"text to insert"];
1405  [self flushScheduledAsyncBlocks];
1406  // Update the framework exactly once.
1407  XCTAssertEqual(updateCount, 1);
1408 
1409  [inputView deleteBackward];
1410  [self flushScheduledAsyncBlocks];
1411  XCTAssertEqual(updateCount, 2);
1412 
1413  inputView.selectedTextRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)];
1414  [self flushScheduledAsyncBlocks];
1415  XCTAssertEqual(updateCount, 3);
1416 
1417  [inputView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)]
1418  withText:@"replace text"];
1419  [self flushScheduledAsyncBlocks];
1420  XCTAssertEqual(updateCount, 4);
1421 
1422  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1423  [self flushScheduledAsyncBlocks];
1424  XCTAssertEqual(updateCount, 5);
1425 
1426  [inputView unmarkText];
1427  [self flushScheduledAsyncBlocks];
1428  XCTAssertEqual(updateCount, 6);
1429 }
1430 
1431 - (void)testTextChangesDoNotTriggerUpdateEditingClient {
1432  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1433 
1434  __block int updateCount = 0;
1435  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]])
1436  .andDo(^(NSInvocation* invocation) {
1437  updateCount++;
1438  });
1439 
1440  [inputView.text setString:@"BEFORE"];
1441  XCTAssertEqual(updateCount, 0);
1442 
1443  inputView.markedTextRange = nil;
1444  inputView.selectedTextRange = nil;
1445  XCTAssertEqual(updateCount, 1);
1446 
1447  // Text changes don't trigger an update.
1448  XCTAssertEqual(updateCount, 1);
1449  [inputView setTextInputState:@{@"text" : @"AFTER"}];
1450  XCTAssertEqual(updateCount, 1);
1451  [inputView setTextInputState:@{@"text" : @"AFTER"}];
1452  XCTAssertEqual(updateCount, 1);
1453 
1454  // Selection changes don't trigger an update.
1455  [inputView
1456  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @3}];
1457  XCTAssertEqual(updateCount, 1);
1458  [inputView
1459  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @3}];
1460  XCTAssertEqual(updateCount, 1);
1461 
1462  // Composing region changes don't trigger an update.
1463  [inputView
1464  setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @2}];
1465  XCTAssertEqual(updateCount, 1);
1466  [inputView
1467  setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}];
1468  XCTAssertEqual(updateCount, 1);
1469 }
1470 
1471 - (void)testTextChangesDoNotTriggerUpdateEditingClientWithDelta {
1472  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1473  inputView.enableDeltaModel = YES;
1474 
1475  __block int updateCount = 0;
1476  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withDelta:[OCMArg isNotNil]])
1477  .andDo(^(NSInvocation* invocation) {
1478  updateCount++;
1479  });
1480 
1481  [inputView.text setString:@"BEFORE"];
1482  [self flushScheduledAsyncBlocks];
1483  XCTAssertEqual(updateCount, 0);
1484 
1485  inputView.markedTextRange = nil;
1486  inputView.selectedTextRange = nil;
1487  [self flushScheduledAsyncBlocks];
1488  XCTAssertEqual(updateCount, 1);
1489 
1490  // Text changes don't trigger an update.
1491  XCTAssertEqual(updateCount, 1);
1492  [inputView setTextInputState:@{@"text" : @"AFTER"}];
1493  [self flushScheduledAsyncBlocks];
1494  XCTAssertEqual(updateCount, 1);
1495 
1496  [inputView setTextInputState:@{@"text" : @"AFTER"}];
1497  [self flushScheduledAsyncBlocks];
1498  XCTAssertEqual(updateCount, 1);
1499 
1500  // Selection changes don't trigger an update.
1501  [inputView
1502  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @3}];
1503  [self flushScheduledAsyncBlocks];
1504  XCTAssertEqual(updateCount, 1);
1505 
1506  [inputView
1507  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @3}];
1508  [self flushScheduledAsyncBlocks];
1509  XCTAssertEqual(updateCount, 1);
1510 
1511  // Composing region changes don't trigger an update.
1512  [inputView
1513  setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @2}];
1514  [self flushScheduledAsyncBlocks];
1515  XCTAssertEqual(updateCount, 1);
1516 
1517  [inputView
1518  setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}];
1519  [self flushScheduledAsyncBlocks];
1520  XCTAssertEqual(updateCount, 1);
1521 }
1522 
1523 - (void)testUITextInputAvoidUnnecessaryUndateEditingClientCalls {
1524  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1525 
1526  __block int updateCount = 0;
1527  OCMStub([engine flutterTextInputView:inputView updateEditingClient:0 withState:[OCMArg isNotNil]])
1528  .andDo(^(NSInvocation* invocation) {
1529  updateCount++;
1530  });
1531 
1532  [inputView unmarkText];
1533  // updateEditingClient shouldn't fire as the text is already unmarked.
1534  XCTAssertEqual(updateCount, 0);
1535 
1536  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1537  // updateEditingClient fires in response to setMarkedText.
1538  XCTAssertEqual(updateCount, 1);
1539 
1540  [inputView unmarkText];
1541  // updateEditingClient fires in response to unmarkText.
1542  XCTAssertEqual(updateCount, 2);
1543 }
1544 
1545 - (void)testCanCopyPasteWithScribbleEnabled {
1546  if (@available(iOS 14.0, *)) {
1547  NSDictionary* config = self.mutableTemplateCopy;
1548  [self setClientId:123 configuration:config];
1549  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
1550  FlutterTextInputView* inputView = inputFields[0];
1551 
1552  FlutterTextInputView* mockInputView = OCMPartialMock(inputView);
1553  OCMStub([mockInputView isScribbleAvailable]).andReturn(YES);
1554 
1555  [mockInputView insertText:@"aaaa"];
1556  [mockInputView selectAll:nil];
1557 
1558  XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:NULL]);
1559  XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:@"sender"]);
1560  XCTAssertFalse([mockInputView canPerformAction:@selector(paste:) withSender:NULL]);
1561  XCTAssertFalse([mockInputView canPerformAction:@selector(paste:) withSender:@"sender"]);
1562 
1563  [mockInputView copy:NULL];
1564  XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:NULL]);
1565  XCTAssertTrue([mockInputView canPerformAction:@selector(copy:) withSender:@"sender"]);
1566  XCTAssertTrue([mockInputView canPerformAction:@selector(paste:) withSender:NULL]);
1567  XCTAssertTrue([mockInputView canPerformAction:@selector(paste:) withSender:@"sender"]);
1568  }
1569 }
1570 
1571 - (void)testSetMarkedTextDuringScribbleDoesNotTriggerUpdateEditingClient {
1572  if (@available(iOS 14.0, *)) {
1573  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1574 
1575  __block int updateCount = 0;
1576  OCMStub([engine flutterTextInputView:inputView
1577  updateEditingClient:0
1578  withState:[OCMArg isNotNil]])
1579  .andDo(^(NSInvocation* invocation) {
1580  updateCount++;
1581  });
1582 
1583  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1584  // updateEditingClient fires in response to setMarkedText.
1585  XCTAssertEqual(updateCount, 1);
1586 
1587  UIScribbleInteraction* scribbleInteraction =
1588  [[UIScribbleInteraction alloc] initWithDelegate:inputView];
1589 
1590  [inputView scribbleInteractionWillBeginWriting:scribbleInteraction];
1591  [inputView setMarkedText:@"during writing" selectedRange:NSMakeRange(1, 2)];
1592  // updateEditingClient does not fire in response to setMarkedText during a scribble interaction.
1593  XCTAssertEqual(updateCount, 1);
1594 
1595  [inputView scribbleInteractionDidFinishWriting:scribbleInteraction];
1596  [inputView resetScribbleInteractionStatusIfEnding];
1597  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1598  // updateEditingClient fires in response to setMarkedText.
1599  XCTAssertEqual(updateCount, 2);
1600 
1601  inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocusing;
1602  [inputView setMarkedText:@"during focus" selectedRange:NSMakeRange(1, 2)];
1603  // updateEditingClient does not fire in response to setMarkedText during a scribble-initiated
1604  // focus.
1605  XCTAssertEqual(updateCount, 2);
1606 
1607  inputView.scribbleFocusStatus = FlutterScribbleFocusStatusFocused;
1608  [inputView setMarkedText:@"after focus" selectedRange:NSMakeRange(2, 3)];
1609  // updateEditingClient does not fire in response to setMarkedText after a scribble-initiated
1610  // focus.
1611  XCTAssertEqual(updateCount, 2);
1612 
1613  inputView.scribbleFocusStatus = FlutterScribbleFocusStatusUnfocused;
1614  [inputView setMarkedText:@"marked text" selectedRange:NSMakeRange(0, 1)];
1615  // updateEditingClient fires in response to setMarkedText.
1616  XCTAssertEqual(updateCount, 3);
1617  }
1618 }
1619 
1620 - (void)testUpdateEditingClientNegativeSelection {
1621  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1622 
1623  [inputView.text setString:@"SELECTION"];
1624  inputView.markedTextRange = nil;
1625  inputView.selectedTextRange = nil;
1626 
1627  [inputView setTextInputState:@{
1628  @"text" : @"SELECTION",
1629  @"selectionBase" : @-1,
1630  @"selectionExtent" : @-1
1631  }];
1632  [inputView updateEditingState];
1633  OCMVerify([engine flutterTextInputView:inputView
1634  updateEditingClient:0
1635  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1636  return ([state[@"selectionBase"] intValue]) == 0 &&
1637  ([state[@"selectionExtent"] intValue] == 0);
1638  }]]);
1639 
1640  // Returns (0, 0) when either end goes below 0.
1641  [inputView
1642  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @-1, @"selectionExtent" : @1}];
1643  [inputView updateEditingState];
1644  OCMVerify([engine flutterTextInputView:inputView
1645  updateEditingClient:0
1646  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1647  return ([state[@"selectionBase"] intValue]) == 0 &&
1648  ([state[@"selectionExtent"] intValue] == 0);
1649  }]]);
1650 
1651  [inputView
1652  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @-1}];
1653  [inputView updateEditingState];
1654  OCMVerify([engine flutterTextInputView:inputView
1655  updateEditingClient:0
1656  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1657  return ([state[@"selectionBase"] intValue]) == 0 &&
1658  ([state[@"selectionExtent"] intValue] == 0);
1659  }]]);
1660 }
1661 
1662 - (void)testUpdateEditingClientSelectionClamping {
1663  // Regression test for https://github.com/flutter/flutter/issues/62992.
1664  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1665 
1666  [inputView.text setString:@"SELECTION"];
1667  inputView.markedTextRange = nil;
1668  inputView.selectedTextRange = nil;
1669 
1670  [inputView
1671  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @0, @"selectionExtent" : @0}];
1672  [inputView updateEditingState];
1673  OCMVerify([engine flutterTextInputView:inputView
1674  updateEditingClient:0
1675  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1676  return ([state[@"selectionBase"] intValue]) == 0 &&
1677  ([state[@"selectionExtent"] intValue] == 0);
1678  }]]);
1679 
1680  // Needs clamping.
1681  [inputView setTextInputState:@{
1682  @"text" : @"SELECTION",
1683  @"selectionBase" : @0,
1684  @"selectionExtent" : @9999
1685  }];
1686  [inputView updateEditingState];
1687 
1688  OCMVerify([engine flutterTextInputView:inputView
1689  updateEditingClient:0
1690  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1691  return ([state[@"selectionBase"] intValue]) == 0 &&
1692  ([state[@"selectionExtent"] intValue] == 9);
1693  }]]);
1694 
1695  // No clamping needed, but in reverse direction.
1696  [inputView
1697  setTextInputState:@{@"text" : @"SELECTION", @"selectionBase" : @1, @"selectionExtent" : @0}];
1698  [inputView updateEditingState];
1699  OCMVerify([engine flutterTextInputView:inputView
1700  updateEditingClient:0
1701  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1702  return ([state[@"selectionBase"] intValue]) == 0 &&
1703  ([state[@"selectionExtent"] intValue] == 1);
1704  }]]);
1705 
1706  // Both ends need clamping.
1707  [inputView setTextInputState:@{
1708  @"text" : @"SELECTION",
1709  @"selectionBase" : @9999,
1710  @"selectionExtent" : @9999
1711  }];
1712  [inputView updateEditingState];
1713  OCMVerify([engine flutterTextInputView:inputView
1714  updateEditingClient:0
1715  withState:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
1716  return ([state[@"selectionBase"] intValue]) == 9 &&
1717  ([state[@"selectionExtent"] intValue] == 9);
1718  }]]);
1719 }
1720 
1721 - (void)testRestoringPlatformFirstResponderNotifiesFrameworkOnce {
1722  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1723  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1724  [inputView setTextInputClient:123];
1725 
1726  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1727  OCMVerify(never(), [engine flutterTextInputView:inputView
1728  didRestoreFirstResponderWithTextInputClient:123
1729  result:[OCMArg any]]);
1730 
1731  XCTAssertTrue([inputView resignFirstResponder]);
1732  OCMVerify(times(1), [engine flutterTextInputView:inputView
1733  didResignFirstResponderWithTextInputClient:123]);
1734  OCMVerify(never(), [engine flutterTextInputView:inputView
1735  didRestoreFirstResponderWithTextInputClient:123
1736  result:[OCMArg any]]);
1737  XCTAssertTrue([inputView becomeFirstResponder]);
1738  OCMVerify(times(1), [engine flutterTextInputView:inputView
1739  didRestoreFirstResponderWithTextInputClient:123
1740  result:[OCMArg any]]);
1741 
1742  XCTAssertTrue([inputView becomeFirstResponder]);
1743  OCMVerify(times(1), [engine flutterTextInputView:inputView
1744  didRestoreFirstResponderWithTextInputClient:123
1745  result:[OCMArg any]]);
1746 
1747  XCTAssertTrue([inputView resignFirstResponder]);
1748  OCMVerify(times(2), [engine flutterTextInputView:inputView
1749  didResignFirstResponderWithTextInputClient:123]);
1750  OCMVerify(times(1), [engine flutterTextInputView:inputView
1751  didRestoreFirstResponderWithTextInputClient:123
1752  result:[OCMArg any]]);
1753  XCTAssertTrue([inputView becomeFirstResponder]);
1754  OCMVerify(times(2), [engine flutterTextInputView:inputView
1755  didRestoreFirstResponderWithTextInputClient:123
1756  result:[OCMArg any]]);
1757 
1758  [inputView resignFirstResponderFromFramework];
1759  [inputView removeFromSuperview];
1760 }
1761 
1762 - (void)testFrameworkResponderChangesCancelPendingFocusRestore {
1763  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1764  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1765  [inputView setTextInputClient:123];
1766 
1767  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1768  XCTAssertTrue([inputView resignFirstResponderFromFramework]);
1769  XCTAssertTrue([inputView becomeFirstResponder]);
1770 
1771  XCTAssertTrue([inputView resignFirstResponder]);
1772  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1773 
1774  OCMVerify(never(), [engine flutterTextInputView:inputView
1775  didRestoreFirstResponderWithTextInputClient:123
1776  result:[OCMArg any]]);
1777 
1778  [inputView resignFirstResponderFromFramework];
1779  [inputView removeFromSuperview];
1780 }
1781 
1782 - (void)testInteractiveKeyboardResignDoesNotArmFocusRestore {
1783  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1784  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1785  [inputView setTextInputClient:123];
1786 
1787  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1788  inputView.preventCursorDismissWhenResignFirstResponder = YES;
1789  XCTAssertTrue([inputView resignFirstResponder]);
1790  inputView.preventCursorDismissWhenResignFirstResponder = NO;
1791  XCTAssertTrue([inputView becomeFirstResponder]);
1792 
1793  OCMVerify(never(), [engine flutterTextInputView:inputView
1794  didResignFirstResponderWithTextInputClient:123]);
1795  OCMVerify(never(), [engine flutterTextInputView:inputView
1796  didRestoreFirstResponderWithTextInputClient:123
1797  result:[OCMArg any]]);
1798 
1799  [inputView resignFirstResponderFromFramework];
1800  [inputView removeFromSuperview];
1801 }
1802 
1803 - (void)testChangingClientCancelsPendingFocusRestore {
1804  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1805  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1806  [inputView setTextInputClient:123];
1807 
1808  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1809  XCTAssertTrue([inputView resignFirstResponder]);
1810  [inputView setTextInputClient:456];
1811  XCTAssertTrue([inputView becomeFirstResponder]);
1812 
1813  OCMVerify(never(), [engine flutterTextInputView:inputView
1814  didRestoreFirstResponderWithTextInputClient:123
1815  result:[OCMArg any]]);
1816  OCMVerify(never(), [engine flutterTextInputView:inputView
1817  didRestoreFirstResponderWithTextInputClient:456
1818  result:[OCMArg any]]);
1819 
1820  [inputView resignFirstResponderFromFramework];
1821  [inputView removeFromSuperview];
1822 }
1823 
1824 - (void)testResettingSameClientCancelsPendingFocusRestore {
1825  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1826  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1827  [inputView setTextInputClient:123];
1828 
1829  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1830  XCTAssertTrue([inputView resignFirstResponder]);
1831  [inputView setTextInputClient:123];
1832  XCTAssertTrue([inputView becomeFirstResponder]);
1833 
1834  OCMVerify(never(), [engine flutterTextInputView:inputView
1835  didRestoreFirstResponderWithTextInputClient:123
1836  result:[OCMArg any]]);
1837 
1838  [inputView resignFirstResponderFromFramework];
1839  [inputView removeFromSuperview];
1840 }
1841 
1842 // Resigns and restores the first responder of |inputView| (client 123) from the platform side, and
1843 // returns the callback that delivers the framework's reply to the resulting focus restore
1844 // notification.
1845 - (FlutterResult)restorePlatformFirstResponderOfInputView:(FlutterTextInputView*)inputView {
1846  __block FlutterResult restoreResult;
1847  OCMStub([engine flutterTextInputView:inputView
1848  didRestoreFirstResponderWithTextInputClient:123
1849  result:[OCMArg any]])
1850  .andDo(^(NSInvocation* invocation) {
1851  __unsafe_unretained FlutterResult resultUnsafe;
1852  [invocation getArgument:&resultUnsafe atIndex:4];
1853  restoreResult = resultUnsafe;
1854  });
1855 
1856  XCTAssertTrue([inputView becomeFirstResponderFromFramework]);
1857  XCTAssertTrue([inputView resignFirstResponder]);
1858  XCTAssertTrue([inputView becomeFirstResponder]);
1859  XCTAssertNotNil(restoreResult);
1860  return restoreResult;
1861 }
1862 
1863 - (void)testDeclinedFocusRestoreResignsFirstResponder {
1864  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1865  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1866  [inputView setTextInputClient:123];
1867 
1868  FlutterResult restoreResult = [self restorePlatformFirstResponderOfInputView:inputView];
1869  restoreResult(@NO);
1870 
1871  XCTAssertFalse(inputView.isFirstResponder);
1872  OCMVerify(times(2), [engine flutterTextInputView:inputView
1873  didResignFirstResponderWithTextInputClient:123]);
1874 
1875  // The resign goes through the framework path, so a later restore does not notify again.
1876  XCTAssertTrue([inputView becomeFirstResponder]);
1877  OCMVerify(times(1), [engine flutterTextInputView:inputView
1878  didRestoreFirstResponderWithTextInputClient:123
1879  result:[OCMArg any]]);
1880 
1881  [inputView resignFirstResponderFromFramework];
1882  [inputView removeFromSuperview];
1883 }
1884 
1885 - (void)testAcceptedFocusRestoreKeepsFirstResponder {
1886  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1887  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1888  [inputView setTextInputClient:123];
1889 
1890  FlutterResult restoreResult = [self restorePlatformFirstResponderOfInputView:inputView];
1891  restoreResult(@YES);
1892 
1893  XCTAssertTrue(inputView.isFirstResponder);
1894  OCMVerify(times(1), [engine flutterTextInputView:inputView
1895  didResignFirstResponderWithTextInputClient:123]);
1896 
1897  [inputView resignFirstResponderFromFramework];
1898  [inputView removeFromSuperview];
1899 }
1900 
1901 - (void)testFailedFocusRestoreReplyResignsFirstResponder {
1902  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1903  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1904  [inputView setTextInputClient:123];
1905 
1906  FlutterResult restoreResult = [self restorePlatformFirstResponderOfInputView:inputView];
1907  restoreResult([FlutterError errorWithCode:@"error" message:nil details:nil]);
1908 
1909  XCTAssertFalse(inputView.isFirstResponder);
1910 
1911  [inputView removeFromSuperview];
1912 }
1913 
1914 - (void)testChangingClientIgnoresPendingFocusRestoreReply {
1915  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1916  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1917  [inputView setTextInputClient:123];
1918 
1919  FlutterResult restoreResult = [self restorePlatformFirstResponderOfInputView:inputView];
1920  [inputView setTextInputClient:456];
1921  restoreResult(@NO);
1922 
1923  XCTAssertTrue(inputView.isFirstResponder);
1924 
1925  [inputView resignFirstResponderFromFramework];
1926  [inputView removeFromSuperview];
1927 }
1928 
1929 - (void)testPluginUsesFrameworkResponderChangesForExplicitTextInputMethods {
1930  [self setClientId:123 configuration:self.mutableTemplateCopy];
1931  id mockInputView = OCMPartialMock(textInputPlugin.activeView);
1932  OCMStub([mockInputView becomeFirstResponderFromFramework]).andReturn(YES);
1933  OCMStub([mockInputView resignFirstResponderFromFramework]).andReturn(YES);
1934 
1935  [self setTextInputShow];
1936  OCMVerify(times(1), [mockInputView becomeFirstResponderFromFramework]);
1937 
1938  [self setTextInputHide];
1939  OCMVerify(times(1), [mockInputView resignFirstResponderFromFramework]);
1940 
1941  FlutterMethodCall* finishAutofillContextCall =
1942  [FlutterMethodCall methodCallWithMethodName:@"TextInput.finishAutofillContext" arguments:@NO];
1943  [textInputPlugin handleMethodCall:finishAutofillContextCall
1944  result:^(id _Nullable result){
1945  }];
1946 
1947  OCMVerify(times(2), [mockInputView resignFirstResponderFromFramework]);
1948  [mockInputView stopMocking];
1949 }
1950 
1951 - (void)testInputViewsHasNonNilInputDelegate {
1952  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1953  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
1954 
1955  [inputView setTextInputClient:123];
1956  [inputView reloadInputViews];
1957  [inputView becomeFirstResponder];
1958  NSAssert(inputView.isFirstResponder, @"inputView is not first responder");
1959  inputView.inputDelegate = nil;
1960 
1961  FlutterTextInputView* mockInputView = OCMPartialMock(inputView);
1962  [mockInputView
1963  setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}];
1964  OCMVerify([mockInputView setInputDelegate:[OCMArg isNotNil]]);
1965  [inputView removeFromSuperview];
1966 }
1967 
1968 - (void)testInputViewsDoNotHaveUITextInteractions {
1969  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
1970  BOOL hasTextInteraction = NO;
1971  for (id interaction in inputView.interactions) {
1972  hasTextInteraction = [interaction isKindOfClass:[UITextInteraction class]];
1973  if (hasTextInteraction) {
1974  break;
1975  }
1976  }
1977  XCTAssertFalse(hasTextInteraction);
1978 }
1979 
1980 #pragma mark - UITextInput methods - Tests
1981 
1982 - (void)testUpdateFirstRectForRange {
1983  [self setClientId:123 configuration:self.mutableTemplateCopy];
1984 
1985  FlutterTextInputView* inputView = textInputPlugin.activeView;
1986  textInputPlugin.viewController.view.frame = CGRectMake(0, 0, 0, 0);
1987 
1988  [inputView
1989  setTextInputState:@{@"text" : @"COMPOSING", @"composingBase" : @1, @"composingExtent" : @3}];
1990 
1991  CGRect kInvalidFirstRect = CGRectMake(-1, -1, 9999, 9999);
1992  FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)];
1993  // yOffset = 200.
1994  NSArray* yOffsetMatrix = @[ @1, @0, @0, @0, @0, @1, @0, @0, @0, @0, @1, @0, @0, @200, @0, @1 ];
1995  NSArray* zeroMatrix = @[ @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0, @0 ];
1996  // This matrix can be generated by running this dart code snippet:
1997  // Matrix4.identity()..scale(3.0)..rotateZ(math.pi/2)..translate(1.0, 2.0,
1998  // 3.0);
1999  NSArray* affineMatrix = @[
2000  @(0.0), @(3.0), @(0.0), @(0.0), @(-3.0), @(0.0), @(0.0), @(0.0), @(0.0), @(0.0), @(3.0), @(0.0),
2001  @(-6.0), @(3.0), @(9.0), @(1.0)
2002  ];
2003 
2004  // Invalid since we don't have the transform or the rect.
2005  XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range]));
2006 
2007  [inputView setEditableTransform:yOffsetMatrix];
2008  // Invalid since we don't have the rect.
2009  XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range]));
2010 
2011  // Valid rect and transform.
2012  CGRect testRect = CGRectMake(0, 0, 100, 100);
2013  [inputView setMarkedRect:testRect];
2014 
2015  CGRect finalRect = CGRectOffset(testRect, 0, 200);
2016  XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range]));
2017  // Idempotent.
2018  XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range]));
2019 
2020  // Use an invalid matrix:
2021  [inputView setEditableTransform:zeroMatrix];
2022  // Invalid matrix is invalid.
2023  XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range]));
2024  XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range]));
2025 
2026  // Revert the invalid matrix change.
2027  [inputView setEditableTransform:yOffsetMatrix];
2028  [inputView setMarkedRect:testRect];
2029  XCTAssertTrue(CGRectEqualToRect(finalRect, [inputView firstRectForRange:range]));
2030 
2031  // Use an invalid rect:
2032  [inputView setMarkedRect:kInvalidFirstRect];
2033  // Invalid marked rect is invalid.
2034  XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range]));
2035  XCTAssertTrue(CGRectEqualToRect(kInvalidFirstRect, [inputView firstRectForRange:range]));
2036 
2037  // Use a 3d affine transform that does 3d-scaling, z-index rotating and 3d translation.
2038  [inputView setEditableTransform:affineMatrix];
2039  [inputView setMarkedRect:testRect];
2040  XCTAssertTrue(
2041  CGRectEqualToRect(CGRectMake(-306, 3, 300, 300), [inputView firstRectForRange:range]));
2042 
2043  NSAssert(inputView.superview, @"inputView is not in the view hierarchy!");
2044  const CGPoint offset = CGPointMake(113, 119);
2045  CGRect currentFrame = inputView.frame;
2046  currentFrame.origin = offset;
2047  inputView.frame = currentFrame;
2048  // Moving the input view within the FlutterView shouldn't affect the coordinates,
2049  // since the framework sends us global coordinates.
2050  XCTAssertTrue(CGRectEqualToRect(CGRectMake(-306 - 113, 3 - 119, 300, 300),
2051  [inputView firstRectForRange:range]));
2052 }
2053 
2054 - (void)testFirstRectForRangeReturnsNoneZeroRectWhenScribbleIsEnabled {
2055  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2056  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2057 
2058  FlutterTextInputView* mockInputView = OCMPartialMock(inputView);
2059  OCMStub([mockInputView isScribbleAvailable]).andReturn(YES);
2060 
2061  [inputView setSelectionRects:@[
2062  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2063  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U],
2064  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2065  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U],
2066  ]];
2067 
2068  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)];
2069 
2070  if (@available(iOS 17, *)) {
2071  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100),
2072  [inputView firstRectForRange:multiRectRange]));
2073  } else {
2074  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100),
2075  [inputView firstRectForRange:multiRectRange]));
2076  }
2077 }
2078 
2079 - (void)testFirstRectForRangeReturnsCorrectRectOnASingleLineLeftToRight {
2080  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2081  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2082 
2083  [inputView setSelectionRects:@[
2084  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2085  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U],
2086  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2087  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U],
2088  ]];
2089  FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)];
2090  if (@available(iOS 17, *)) {
2091  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100),
2092  [inputView firstRectForRange:singleRectRange]));
2093  } else {
2094  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange]));
2095  }
2096 
2097  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)];
2098 
2099  if (@available(iOS 17, *)) {
2100  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100),
2101  [inputView firstRectForRange:multiRectRange]));
2102  } else {
2103  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2104  }
2105 
2106  [inputView setTextInputState:@{@"text" : @"COM"}];
2107  FlutterTextRange* rangeOutsideBounds = [FlutterTextRange rangeWithNSRange:NSMakeRange(3, 1)];
2108  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:rangeOutsideBounds]));
2109 }
2110 
2111 - (void)testFirstRectForRangeReturnsCorrectRectOnASingleLineRightToLeft {
2112  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2113  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2114 
2115  [inputView setSelectionRects:@[
2116  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U],
2117  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U],
2118  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U],
2119  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U],
2120  ]];
2121  FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)];
2122  if (@available(iOS 17, *)) {
2123  XCTAssertTrue(CGRectEqualToRect(CGRectMake(200, 0, 100, 100),
2124  [inputView firstRectForRange:singleRectRange]));
2125  } else {
2126  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange]));
2127  }
2128 
2129  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)];
2130  if (@available(iOS 17, *)) {
2131  XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100),
2132  [inputView firstRectForRange:multiRectRange]));
2133  } else {
2134  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2135  }
2136 
2137  [inputView setTextInputState:@{@"text" : @"COM"}];
2138  FlutterTextRange* rangeOutsideBounds = [FlutterTextRange rangeWithNSRange:NSMakeRange(3, 1)];
2139  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:rangeOutsideBounds]));
2140 }
2141 
2142 - (void)testFirstRectForRangeReturnsCorrectRectOnMultipleLinesLeftToRight {
2143  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2144  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2145 
2146  [inputView setSelectionRects:@[
2147  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2148  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U],
2149  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2150  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U],
2151  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:4U],
2152  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:5U],
2153  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:6U],
2154  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 100, 100, 100) position:7U],
2155  ]];
2156  FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)];
2157  if (@available(iOS 17, *)) {
2158  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 100, 100),
2159  [inputView firstRectForRange:singleRectRange]));
2160  } else {
2161  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange]));
2162  }
2163 
2164  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)];
2165 
2166  if (@available(iOS 17, *)) {
2167  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100),
2168  [inputView firstRectForRange:multiRectRange]));
2169  } else {
2170  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2171  }
2172 }
2173 
2174 - (void)testFirstRectForRangeReturnsCorrectRectOnMultipleLinesRightToLeft {
2175  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2176  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2177 
2178  [inputView setSelectionRects:@[
2179  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U],
2180  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U],
2181  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U],
2182  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U],
2183  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 100, 100, 100) position:4U],
2184  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:5U],
2185  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:6U],
2186  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:7U],
2187  ]];
2188  FlutterTextRange* singleRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 1)];
2189  if (@available(iOS 17, *)) {
2190  XCTAssertTrue(CGRectEqualToRect(CGRectMake(200, 0, 100, 100),
2191  [inputView firstRectForRange:singleRectRange]));
2192  } else {
2193  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:singleRectRange]));
2194  }
2195 
2196  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)];
2197  if (@available(iOS 17, *)) {
2198  XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100),
2199  [inputView firstRectForRange:multiRectRange]));
2200  } else {
2201  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2202  }
2203 }
2204 
2205 - (void)testFirstRectForRangeReturnsCorrectRectOnSingleLineWithVaryingMinYAndMaxYLeftToRight {
2206  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2207  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2208 
2209  [inputView setSelectionRects:@[
2210  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2211  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 10, 100, 80)
2212  position:1U], // shorter
2213  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, -10, 100, 120)
2214  position:2U], // taller
2215  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U],
2216  ]];
2217 
2218  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)];
2219 
2220  if (@available(iOS 17, *)) {
2221  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, -10, 300, 120),
2222  [inputView firstRectForRange:multiRectRange]));
2223  } else {
2224  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2225  }
2226 }
2227 
2228 - (void)testFirstRectForRangeReturnsCorrectRectOnSingleLineWithVaryingMinYAndMaxYRightToLeft {
2229  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2230  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2231 
2232  [inputView setSelectionRects:@[
2233  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U],
2234  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, -10, 100, 120)
2235  position:1U], // taller
2236  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 10, 100, 80)
2237  position:2U], // shorter
2238  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U],
2239  ]];
2240 
2241  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 3)];
2242 
2243  if (@available(iOS 17, *)) {
2244  XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, -10, 300, 120),
2245  [inputView firstRectForRange:multiRectRange]));
2246  } else {
2247  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2248  }
2249 }
2250 
2251 - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsExceedingThresholdLeftToRight {
2252  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2253  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2254 
2255  [inputView setSelectionRects:@[
2256  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2257  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U],
2258  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2259  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U],
2260  // y=60 exceeds threshold, so treat it as a new line.
2261  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 60, 100, 100) position:4U],
2262  ]];
2263 
2264  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)];
2265 
2266  if (@available(iOS 17, *)) {
2267  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 300, 100),
2268  [inputView firstRectForRange:multiRectRange]));
2269  } else {
2270  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2271  }
2272 }
2273 
2274 - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsExceedingThresholdRightToLeft {
2275  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2276  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2277 
2278  [inputView setSelectionRects:@[
2279  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:0U],
2280  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:1U],
2281  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:2U],
2282  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:3U],
2283  // y=60 exceeds threshold, so treat it as a new line.
2284  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 60, 100, 100) position:4U],
2285  ]];
2286 
2287  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)];
2288 
2289  if (@available(iOS 17, *)) {
2290  XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 300, 100),
2291  [inputView firstRectForRange:multiRectRange]));
2292  } else {
2293  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2294  }
2295 }
2296 
2297 - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsWithinThresholdLeftToRight {
2298  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2299  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2300 
2301  [inputView setSelectionRects:@[
2302  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2303  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:1U],
2304  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2305  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:3U],
2306  // y=40 is within line threshold, so treat it as the same line
2307  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(400, 40, 100, 100) position:4U],
2308  ]];
2309 
2310  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)];
2311 
2312  if (@available(iOS 17, *)) {
2313  XCTAssertTrue(CGRectEqualToRect(CGRectMake(100, 0, 400, 140),
2314  [inputView firstRectForRange:multiRectRange]));
2315  } else {
2316  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2317  }
2318 }
2319 
2320 - (void)testFirstRectForRangeReturnsCorrectRectWithOverlappingRectsWithinThresholdRightToLeft {
2321  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2322  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2323 
2324  [inputView setSelectionRects:@[
2325  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(400, 0, 100, 100) position:0U],
2326  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 0, 100, 100) position:1U],
2327  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2328  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100) position:3U],
2329  // y=40 is within line threshold, so treat it as the same line
2330  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 40, 100, 100) position:4U],
2331  ]];
2332 
2333  FlutterTextRange* multiRectRange = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 4)];
2334 
2335  if (@available(iOS 17, *)) {
2336  XCTAssertTrue(CGRectEqualToRect(CGRectMake(0, 0, 400, 140),
2337  [inputView firstRectForRange:multiRectRange]));
2338  } else {
2339  XCTAssertTrue(CGRectEqualToRect(CGRectZero, [inputView firstRectForRange:multiRectRange]));
2340  }
2341 }
2342 
2343 - (void)testClosestPositionToPoint {
2344  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2345  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2346 
2347  // Minimize the vertical distance from the center of the rects first
2348  [inputView setSelectionRects:@[
2349  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2350  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U],
2351  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:2U],
2352  ]];
2353  CGPoint point = CGPointMake(150, 150);
2354  XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index);
2355  XCTAssertEqual(UITextStorageDirectionBackward,
2356  ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity);
2357 
2358  // Then, if the point is above the bottom of the closest rects vertically, get the closest x
2359  // origin
2360  [inputView setSelectionRects:@[
2361  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2362  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U],
2363  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U],
2364  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U],
2365  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U],
2366  ]];
2367  point = CGPointMake(125, 150);
2368  XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index);
2369  XCTAssertEqual(UITextStorageDirectionForward,
2370  ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity);
2371 
2372  // However, if the point is below the bottom of the closest rects vertically, get the position
2373  // farthest to the right
2374  [inputView setSelectionRects:@[
2375  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2376  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U],
2377  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U],
2378  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U],
2379  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 300, 100, 100) position:4U],
2380  ]];
2381  point = CGPointMake(125, 201);
2382  XCTAssertEqual(4U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index);
2383  XCTAssertEqual(UITextStorageDirectionBackward,
2384  ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity);
2385 
2386  // Also check a point at the right edge of the last selection rect
2387  [inputView setSelectionRects:@[
2388  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2389  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U],
2390  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U],
2391  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U],
2392  ]];
2393  point = CGPointMake(125, 250);
2394  XCTAssertEqual(4U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index);
2395  XCTAssertEqual(UITextStorageDirectionBackward,
2396  ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity);
2397 
2398  // Minimize vertical distance if the difference is more than 1 point.
2399  [inputView setSelectionRects:@[
2400  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 2, 100, 100) position:0U],
2401  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 2, 100, 100) position:1U],
2402  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100) position:2U],
2403  ]];
2404  point = CGPointMake(110, 50);
2405  XCTAssertEqual(2U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index);
2406  XCTAssertEqual(UITextStorageDirectionForward,
2407  ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity);
2408 
2409  // In floating cursor mode, the vertical difference is allowed to be 10 points.
2410  // The closest horizontal position will now win.
2411  [inputView beginFloatingCursorAtPoint:CGPointZero];
2412  XCTAssertEqual(1U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).index);
2413  XCTAssertEqual(UITextStorageDirectionForward,
2414  ((FlutterTextPosition*)[inputView closestPositionToPoint:point]).affinity);
2415  [inputView endFloatingCursor];
2416 }
2417 
2418 - (void)testClosestPositionToPointRTL {
2419  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2420  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2421 
2422  [inputView setSelectionRects:@[
2423  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 0, 100, 100)
2424  position:0U
2425  writingDirection:NSWritingDirectionRightToLeft],
2426  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 0, 100, 100)
2427  position:1U
2428  writingDirection:NSWritingDirectionRightToLeft],
2429  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100)
2430  position:2U
2431  writingDirection:NSWritingDirectionRightToLeft],
2432  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100)
2433  position:3U
2434  writingDirection:NSWritingDirectionRightToLeft],
2435  ]];
2436  FlutterTextPosition* position =
2437  (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(275, 50)];
2438  XCTAssertEqual(0U, position.index);
2439  XCTAssertEqual(UITextStorageDirectionForward, position.affinity);
2440  position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(225, 50)];
2441  XCTAssertEqual(1U, position.index);
2442  XCTAssertEqual(UITextStorageDirectionBackward, position.affinity);
2443  position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(175, 50)];
2444  XCTAssertEqual(1U, position.index);
2445  XCTAssertEqual(UITextStorageDirectionForward, position.affinity);
2446  position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(125, 50)];
2447  XCTAssertEqual(2U, position.index);
2448  XCTAssertEqual(UITextStorageDirectionBackward, position.affinity);
2449  position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(75, 50)];
2450  XCTAssertEqual(2U, position.index);
2451  XCTAssertEqual(UITextStorageDirectionForward, position.affinity);
2452  position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(25, 50)];
2453  XCTAssertEqual(3U, position.index);
2454  XCTAssertEqual(UITextStorageDirectionBackward, position.affinity);
2455  position = (FlutterTextPosition*)[inputView closestPositionToPoint:CGPointMake(-25, 50)];
2456  XCTAssertEqual(3U, position.index);
2457  XCTAssertEqual(UITextStorageDirectionBackward, position.affinity);
2458 }
2459 
2460 - (void)testSelectionRectsForRange {
2461  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2462  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2463 
2464  CGRect testRect0 = CGRectMake(100, 100, 100, 100);
2465  CGRect testRect1 = CGRectMake(200, 200, 100, 100);
2466  [inputView setSelectionRects:@[
2467  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2470  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U],
2471  ]];
2472 
2473  // Returns the matching rects within a range
2474  FlutterTextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 2)];
2475  XCTAssertTrue(CGRectEqualToRect(testRect0, [inputView selectionRectsForRange:range][0].rect));
2476  XCTAssertTrue(CGRectEqualToRect(testRect1, [inputView selectionRectsForRange:range][1].rect));
2477  XCTAssertEqual(2U, [[inputView selectionRectsForRange:range] count]);
2478 
2479  // Returns a 0 width rect for a 0-length range
2480  range = [FlutterTextRange rangeWithNSRange:NSMakeRange(1, 0)];
2481  XCTAssertEqual(1U, [[inputView selectionRectsForRange:range] count]);
2482  XCTAssertTrue(CGRectEqualToRect(
2483  CGRectMake(testRect0.origin.x, testRect0.origin.y, 0, testRect0.size.height),
2484  [inputView selectionRectsForRange:range][0].rect));
2485 }
2486 
2487 - (void)testClosestPositionToPointWithinRange {
2488  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2489  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2490 
2491  // Do not return a position before the start of the range
2492  [inputView setSelectionRects:@[
2493  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2494  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U],
2495  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U],
2496  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U],
2497  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U],
2498  ]];
2499  CGPoint point = CGPointMake(125, 150);
2500  FlutterTextRange* range = [[FlutterTextRange rangeWithNSRange:NSMakeRange(3, 2)] copy];
2501  XCTAssertEqual(
2502  3U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).index);
2503  XCTAssertEqual(
2504  UITextStorageDirectionForward,
2505  ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).affinity);
2506 
2507  // Do not return a position after the end of the range
2508  [inputView setSelectionRects:@[
2509  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U],
2510  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 100, 100, 100) position:1U],
2511  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:2U],
2512  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 100, 100, 100) position:3U],
2513  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 200, 100, 100) position:4U],
2514  ]];
2515  point = CGPointMake(125, 150);
2516  range = [[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 1)] copy];
2517  XCTAssertEqual(
2518  1U, ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).index);
2519  XCTAssertEqual(
2520  UITextStorageDirectionForward,
2521  ((FlutterTextPosition*)[inputView closestPositionToPoint:point withinRange:range]).affinity);
2522 }
2523 
2524 - (void)testClosestPositionToPointWithPartialSelectionRects {
2525  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2526  [inputView setTextInputState:@{@"text" : @"COMPOSING"}];
2527 
2528  [inputView setSelectionRects:@[ [FlutterTextSelectionRect
2529  selectionRectWithRect:CGRectMake(0, 0, 100, 100)
2530  position:0U] ]];
2531  // Asking with a position at the end of selection rects should give you the trailing edge of
2532  // the last rect.
2533  XCTAssertTrue(CGRectEqualToRect(
2535  positionWithIndex:1
2536  affinity:UITextStorageDirectionForward]],
2537  CGRectMake(100, 0, 0, 100)));
2538  // Asking with a position beyond the end of selection rects should return CGRectZero without
2539  // crashing.
2540  XCTAssertTrue(CGRectEqualToRect(
2542  positionWithIndex:2
2543  affinity:UITextStorageDirectionForward]],
2544  CGRectZero));
2545 }
2546 
2547 #pragma mark - Floating Cursor - Tests
2548 
2549 - (void)testFloatingCursorDoesNotThrow {
2550  // The keyboard implementation may send unbalanced calls to the input view.
2551  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2552  [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)];
2553  [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)];
2554  [inputView endFloatingCursor];
2555  [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)];
2556  [inputView endFloatingCursor];
2557 }
2558 
2559 - (void)testFloatingCursor {
2560  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2561  [inputView setTextInputState:@{
2562  @"text" : @"test",
2563  @"selectionBase" : @1,
2564  @"selectionExtent" : @1,
2565  }];
2566 
2567  FlutterTextSelectionRect* first =
2568  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U];
2569  FlutterTextSelectionRect* second =
2570  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:1U];
2571  FlutterTextSelectionRect* third =
2572  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 200, 100, 100) position:2U];
2573  FlutterTextSelectionRect* fourth =
2574  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U];
2575  [inputView setSelectionRects:@[ first, second, third, fourth ]];
2576 
2577  // Verify zeroth caret rect is based on left edge of first character.
2578  XCTAssertTrue(CGRectEqualToRect(
2580  positionWithIndex:0
2581  affinity:UITextStorageDirectionForward]],
2582  CGRectMake(0, 0, 0, 100)));
2583  // Since the textAffinity is downstream, the caret rect will be based on the
2584  // left edge of the succeeding character.
2585  XCTAssertTrue(CGRectEqualToRect(
2587  positionWithIndex:1
2588  affinity:UITextStorageDirectionForward]],
2589  CGRectMake(100, 100, 0, 100)));
2590  XCTAssertTrue(CGRectEqualToRect(
2592  positionWithIndex:2
2593  affinity:UITextStorageDirectionForward]],
2594  CGRectMake(200, 200, 0, 100)));
2595  XCTAssertTrue(CGRectEqualToRect(
2597  positionWithIndex:3
2598  affinity:UITextStorageDirectionForward]],
2599  CGRectMake(300, 300, 0, 100)));
2600  // There is no subsequent character for the last position, so the caret rect
2601  // will be based on the right edge of the preceding character.
2602  XCTAssertTrue(CGRectEqualToRect(
2604  positionWithIndex:4
2605  affinity:UITextStorageDirectionForward]],
2606  CGRectMake(400, 300, 0, 100)));
2607  // Verify no caret rect for out-of-range character.
2608  XCTAssertTrue(CGRectEqualToRect(
2610  positionWithIndex:5
2611  affinity:UITextStorageDirectionForward]],
2612  CGRectZero));
2613 
2614  // Check caret rects again again when text affinity is upstream.
2615  [inputView setTextInputState:@{
2616  @"text" : @"test",
2617  @"selectionBase" : @2,
2618  @"selectionExtent" : @2,
2619  }];
2620  // Verify zeroth caret rect is based on left edge of first character.
2621  XCTAssertTrue(CGRectEqualToRect(
2623  positionWithIndex:0
2624  affinity:UITextStorageDirectionBackward]],
2625  CGRectMake(0, 0, 0, 100)));
2626  // Since the textAffinity is upstream, all below caret rects will be based on
2627  // the right edge of the preceding character.
2628  XCTAssertTrue(CGRectEqualToRect(
2630  positionWithIndex:1
2631  affinity:UITextStorageDirectionBackward]],
2632  CGRectMake(100, 0, 0, 100)));
2633  XCTAssertTrue(CGRectEqualToRect(
2635  positionWithIndex:2
2636  affinity:UITextStorageDirectionBackward]],
2637  CGRectMake(200, 100, 0, 100)));
2638  XCTAssertTrue(CGRectEqualToRect(
2640  positionWithIndex:3
2641  affinity:UITextStorageDirectionBackward]],
2642  CGRectMake(300, 200, 0, 100)));
2643  XCTAssertTrue(CGRectEqualToRect(
2645  positionWithIndex:4
2646  affinity:UITextStorageDirectionBackward]],
2647  CGRectMake(400, 300, 0, 100)));
2648  // Verify no caret rect for out-of-range character.
2649  XCTAssertTrue(CGRectEqualToRect(
2651  positionWithIndex:5
2652  affinity:UITextStorageDirectionBackward]],
2653  CGRectZero));
2654 
2655  // Verify floating cursor updates are relative to original position, and that there is no bounds
2656  // change.
2657  CGRect initialBounds = inputView.bounds;
2658  [inputView beginFloatingCursorAtPoint:CGPointMake(123, 321)];
2659  XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds));
2660  OCMVerify([engine flutterTextInputView:inputView
2661  updateFloatingCursor:FlutterFloatingCursorDragStateStart
2662  withClient:0
2663  withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
2664  return ([state[@"X"] isEqualToNumber:@(0)]) &&
2665  ([state[@"Y"] isEqualToNumber:@(0)]);
2666  }]]);
2667 
2668  [inputView updateFloatingCursorAtPoint:CGPointMake(456, 654)];
2669  XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds));
2670  OCMVerify([engine flutterTextInputView:inputView
2671  updateFloatingCursor:FlutterFloatingCursorDragStateUpdate
2672  withClient:0
2673  withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
2674  return ([state[@"X"] isEqualToNumber:@(333)]) &&
2675  ([state[@"Y"] isEqualToNumber:@(333)]);
2676  }]]);
2677 
2678  [inputView endFloatingCursor];
2679  XCTAssertTrue(CGRectEqualToRect(initialBounds, inputView.bounds));
2680  OCMVerify([engine flutterTextInputView:inputView
2681  updateFloatingCursor:FlutterFloatingCursorDragStateEnd
2682  withClient:0
2683  withPosition:[OCMArg checkWithBlock:^BOOL(NSDictionary* state) {
2684  return ([state[@"X"] isEqualToNumber:@(0)]) &&
2685  ([state[@"Y"] isEqualToNumber:@(0)]);
2686  }]]);
2687 }
2688 
2689 #pragma mark - UIKeyInput Overrides - Tests
2690 
2691 - (void)testInsertTextAddsPlaceholderSelectionRects {
2692  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
2693  [inputView
2694  setTextInputState:@{@"text" : @"test", @"selectionBase" : @1, @"selectionExtent" : @1}];
2695 
2696  FlutterTextSelectionRect* first =
2697  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(0, 0, 100, 100) position:0U];
2698  FlutterTextSelectionRect* second =
2699  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(100, 100, 100, 100) position:1U];
2700  FlutterTextSelectionRect* third =
2701  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(200, 200, 100, 100) position:2U];
2702  FlutterTextSelectionRect* fourth =
2703  [FlutterTextSelectionRect selectionRectWithRect:CGRectMake(300, 300, 100, 100) position:3U];
2704  [inputView setSelectionRects:@[ first, second, third, fourth ]];
2705 
2706  // Inserts additional selection rects at the selection start
2707  [inputView insertText:@"in"];
2708  NSArray* selectionRects =
2709  [inputView selectionRectsForRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 6)]];
2710  XCTAssertEqual(6U, [selectionRects count]);
2711 
2712  XCTAssertEqual(first.position, ((FlutterTextSelectionRect*)selectionRects[0]).position);
2713  XCTAssertTrue(CGRectEqualToRect(first.rect, ((FlutterTextSelectionRect*)selectionRects[0]).rect));
2714 
2715  XCTAssertEqual(second.position, ((FlutterTextSelectionRect*)selectionRects[1]).position);
2716  XCTAssertTrue(
2717  CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[1]).rect));
2718 
2719  XCTAssertEqual(second.position + 1, ((FlutterTextSelectionRect*)selectionRects[2]).position);
2720  XCTAssertTrue(
2721  CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[2]).rect));
2722 
2723  XCTAssertEqual(second.position + 2, ((FlutterTextSelectionRect*)selectionRects[3]).position);
2724  XCTAssertTrue(
2725  CGRectEqualToRect(second.rect, ((FlutterTextSelectionRect*)selectionRects[3]).rect));
2726 
2727  XCTAssertEqual(third.position + 2, ((FlutterTextSelectionRect*)selectionRects[4]).position);
2728  XCTAssertTrue(CGRectEqualToRect(third.rect, ((FlutterTextSelectionRect*)selectionRects[4]).rect));
2729 
2730  XCTAssertEqual(fourth.position + 2, ((FlutterTextSelectionRect*)selectionRects[5]).position);
2731  XCTAssertTrue(
2732  CGRectEqualToRect(fourth.rect, ((FlutterTextSelectionRect*)selectionRects[5]).rect));
2733 }
2734 
2735 #pragma mark - Autofill - Utilities
2736 
2737 - (NSMutableDictionary*)mutablePasswordTemplateCopy {
2738  if (!_passwordTemplate) {
2739  _passwordTemplate = @{
2740  @"inputType" : @{@"name" : @"TextInuptType.text"},
2741  @"keyboardAppearance" : @"Brightness.light",
2742  @"obscureText" : @YES,
2743  @"inputAction" : @"TextInputAction.unspecified",
2744  @"smartDashesType" : @"0",
2745  @"smartQuotesType" : @"0",
2746  @"autocorrect" : @YES
2747  };
2748  }
2749 
2750  return [_passwordTemplate mutableCopy];
2751 }
2752 
2753 - (NSArray<FlutterTextInputView*>*)viewsVisibleToAutofill {
2754  return [self.installedInputViews
2755  filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isVisibleToAutofill == YES"]];
2756 }
2757 
2758 - (void)commitAutofillContextAndVerify {
2759  FlutterMethodCall* methodCall =
2760  [FlutterMethodCall methodCallWithMethodName:@"TextInput.finishAutofillContext"
2761  arguments:@YES];
2762  [textInputPlugin handleMethodCall:methodCall
2763  result:^(id _Nullable result){
2764  }];
2765 
2766  XCTAssertEqual(self.viewsVisibleToAutofill.count,
2767  [textInputPlugin.activeView isVisibleToAutofill] ? 1ul : 0ul);
2768  XCTAssertNotEqual(textInputPlugin.textInputView, nil);
2769  // The active view should still be installed so it doesn't get
2770  // deallocated.
2771  XCTAssertEqual(self.installedInputViews.count, 1ul);
2772  XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul);
2773 }
2774 
2775 #pragma mark - Autofill - Tests
2776 
2777 - (void)testDisablingAutofillOnInputClient {
2778  NSDictionary* config = self.mutableTemplateCopy;
2779  [config setValue:@"YES" forKey:@"obscureText"];
2780 
2781  [self setClientId:123 configuration:config];
2782 
2783  FlutterTextInputView* inputView = self.installedInputViews[0];
2784  XCTAssertEqualObjects(inputView.textContentType, @"");
2785 }
2786 
2787 - (void)testAutofillEnabledByDefault {
2788  NSDictionary* config = self.mutableTemplateCopy;
2789  [config setValue:@"NO" forKey:@"obscureText"];
2790  [config setValue:@{@"uniqueIdentifier" : @"field1", @"editingValue" : @{@"text" : @""}}
2791  forKey:@"autofill"];
2792 
2793  [self setClientId:123 configuration:config];
2794 
2795  FlutterTextInputView* inputView = self.installedInputViews[0];
2796  XCTAssertNil(inputView.textContentType);
2797 }
2798 
2799 - (void)testAutofillContext {
2800  NSMutableDictionary* field1 = self.mutableTemplateCopy;
2801 
2802  [field1 setValue:@{
2803  @"uniqueIdentifier" : @"field1",
2804  @"hints" : @[ @"hint1" ],
2805  @"editingValue" : @{@"text" : @""}
2806  }
2807  forKey:@"autofill"];
2808 
2809  NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy;
2810  [field2 setValue:@{
2811  @"uniqueIdentifier" : @"field2",
2812  @"hints" : @[ @"hint2" ],
2813  @"editingValue" : @{@"text" : @""}
2814  }
2815  forKey:@"autofill"];
2816 
2817  NSMutableDictionary* config = [field1 mutableCopy];
2818  [config setValue:@[ field1, field2 ] forKey:@"fields"];
2819 
2820  [self setClientId:123 configuration:config];
2821  XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul);
2822 
2823  XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul);
2824 
2825  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
2826  XCTAssertEqual(self.installedInputViews.count, 2ul);
2827  XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]);
2828  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2829 
2830  // The configuration changes.
2831  NSMutableDictionary* field3 = self.mutablePasswordTemplateCopy;
2832  [field3 setValue:@{
2833  @"uniqueIdentifier" : @"field3",
2834  @"hints" : @[ @"hint3" ],
2835  @"editingValue" : @{@"text" : @""}
2836  }
2837  forKey:@"autofill"];
2838 
2839  NSMutableDictionary* oldContext = textInputPlugin.autofillContext;
2840  // Replace field2 with field3.
2841  [config setValue:@[ field1, field3 ] forKey:@"fields"];
2842 
2843  [self setClientId:123 configuration:config];
2844 
2845  XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul);
2846  XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul);
2847 
2848  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
2849  XCTAssertEqual(self.installedInputViews.count, 3ul);
2850  XCTAssertEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]);
2851  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2852 
2853  // Old autofill input fields are still installed and reused.
2854  for (NSString* key in oldContext.allKeys) {
2855  XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]);
2856  }
2857 
2858  // Switch to a password field that has no contentType and is not in an AutofillGroup.
2859  config = self.mutablePasswordTemplateCopy;
2860 
2861  oldContext = textInputPlugin.autofillContext;
2862  [self setClientId:124 configuration:config];
2863  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2864 
2865  XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul);
2866  XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul);
2867 
2868  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
2869  XCTAssertEqual(self.installedInputViews.count, 4ul);
2870 
2871  // Old autofill input fields are still installed and reused.
2872  for (NSString* key in oldContext.allKeys) {
2873  XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]);
2874  }
2875  // The active view should change.
2876  XCTAssertNotEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]);
2877  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2878 
2879  // Switch to a similar password field, the previous field should be reused.
2880  oldContext = textInputPlugin.autofillContext;
2881  [self setClientId:200 configuration:config];
2882 
2883  // Reuse the input view instance from the last time.
2884  XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul);
2885  XCTAssertEqual(textInputPlugin.autofillContext.count, 3ul);
2886 
2887  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
2888  XCTAssertEqual(self.installedInputViews.count, 4ul);
2889 
2890  // Old autofill input fields are still installed and reused.
2891  for (NSString* key in oldContext.allKeys) {
2892  XCTAssertEqual(oldContext[key], textInputPlugin.autofillContext[key]);
2893  }
2894  XCTAssertNotEqual(textInputPlugin.textInputView, textInputPlugin.autofillContext[@"field1"]);
2895  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2896 }
2897 
2898 - (void)testCommitAutofillContext {
2899  NSMutableDictionary* field1 = self.mutableTemplateCopy;
2900  [field1 setValue:@{
2901  @"uniqueIdentifier" : @"field1",
2902  @"hints" : @[ @"hint1" ],
2903  @"editingValue" : @{@"text" : @""}
2904  }
2905  forKey:@"autofill"];
2906 
2907  NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy;
2908  [field2 setValue:@{
2909  @"uniqueIdentifier" : @"field2",
2910  @"hints" : @[ @"hint2" ],
2911  @"editingValue" : @{@"text" : @""}
2912  }
2913  forKey:@"autofill"];
2914 
2915  NSMutableDictionary* field3 = self.mutableTemplateCopy;
2916  [field3 setValue:@{
2917  @"uniqueIdentifier" : @"field3",
2918  @"hints" : @[ @"hint3" ],
2919  @"editingValue" : @{@"text" : @""}
2920  }
2921  forKey:@"autofill"];
2922 
2923  NSMutableDictionary* config = [field1 mutableCopy];
2924  [config setValue:@[ field1, field2 ] forKey:@"fields"];
2925 
2926  [self setClientId:123 configuration:config];
2927  XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul);
2928  XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul);
2929  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2930 
2931  [self commitAutofillContextAndVerify];
2932  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2933 
2934  // Install the password field again.
2935  [self setClientId:123 configuration:config];
2936  // Switch to a regular autofill group.
2937  [self setClientId:124 configuration:field3];
2938  XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul);
2939 
2940  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
2941  XCTAssertEqual(self.installedInputViews.count, 3ul);
2942  XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul);
2943  XCTAssertNotEqual(textInputPlugin.textInputView, nil);
2944  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2945 
2946  [self commitAutofillContextAndVerify];
2947  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2948 
2949  // Now switch to an input field that does not autofill.
2950  [self setClientId:125 configuration:self.mutableTemplateCopy];
2951 
2952  XCTAssertEqual(self.viewsVisibleToAutofill.count, 0ul);
2953  // The active view should still be installed so it doesn't get
2954  // deallocated.
2955 
2956  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
2957  XCTAssertEqual(self.installedInputViews.count, 1ul);
2958  XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul);
2959  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2960 
2961  [self commitAutofillContextAndVerify];
2962  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2963 }
2964 
2965 - (void)testAutofillInputViews {
2966  NSMutableDictionary* field1 = self.mutableTemplateCopy;
2967  [field1 setValue:@{
2968  @"uniqueIdentifier" : @"field1",
2969  @"hints" : @[ @"hint1" ],
2970  @"editingValue" : @{@"text" : @""}
2971  }
2972  forKey:@"autofill"];
2973 
2974  NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy;
2975  [field2 setValue:@{
2976  @"uniqueIdentifier" : @"field2",
2977  @"hints" : @[ @"hint2" ],
2978  @"editingValue" : @{@"text" : @""}
2979  }
2980  forKey:@"autofill"];
2981 
2982  NSMutableDictionary* config = [field1 mutableCopy];
2983  [config setValue:@[ field1, field2 ] forKey:@"fields"];
2984 
2985  [self setClientId:123 configuration:config];
2986  [self ensureOnlyActiveViewCanBecomeFirstResponder];
2987 
2988  // Find all the FlutterTextInputViews we created.
2989  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
2990 
2991  // Both fields are installed and visible because it's a password group.
2992  XCTAssertEqual(inputFields.count, 2ul);
2993  XCTAssertEqual(self.viewsVisibleToAutofill.count, 2ul);
2994 
2995  // Find the inactive autofillable input field.
2996  FlutterTextInputView* inactiveView = inputFields[1];
2997  [inactiveView replaceRange:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 0)]
2998  withText:@"Autofilled!"];
2999  [self ensureOnlyActiveViewCanBecomeFirstResponder];
3000 
3001  // Verify behavior.
3002  OCMVerify([engine flutterTextInputView:inactiveView
3003  updateEditingClient:0
3004  withState:[OCMArg isNotNil]
3005  withTag:@"field2"]);
3006 }
3007 
3008 - (void)testAutofillContextPersistsAfterClearClient {
3009  NSMutableDictionary* field1 = self.mutableTemplateCopy;
3010  [field1 setValue:@{
3011  @"uniqueIdentifier" : @"field1",
3012  @"hints" : @[ @"username" ],
3013  @"editingValue" : @{@"text" : @""}
3014  }
3015  forKey:@"autofill"];
3016 
3017  NSMutableDictionary* field2 = self.mutablePasswordTemplateCopy;
3018  [field2 setValue:@{
3019  @"uniqueIdentifier" : @"field2",
3020  @"hints" : @[ @"password" ],
3021  @"editingValue" : @{@"text" : @""}
3022  }
3023  forKey:@"autofill"];
3024 
3025  NSMutableDictionary* config = [field1 mutableCopy];
3026  [config setValue:@[ field1, field2 ] forKey:@"fields"];
3027 
3028  // Verify initial state.
3029  [self setClientId:123 configuration:config];
3030  XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul);
3031  XCTAssertFalse(textInputPlugin.pendingAutofillRemoval);
3032 
3033  // Retain autofill context.
3034  [self setClientClear];
3035  XCTAssertEqual(textInputPlugin.autofillContext.count, 2ul);
3036  XCTAssertTrue(textInputPlugin.pendingAutofillRemoval);
3037 
3038  // Consume autofill context.
3039  [self commitAutofillContextAndVerify];
3040  XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul);
3041  XCTAssertFalse(textInputPlugin.pendingAutofillRemoval);
3042 }
3043 
3044 - (void)testSetClientResetsPendingAutofillRemoval {
3045  // When autofill context exists and clearClient sets pendingAutofillRemoval,
3046  // a subsequent setClient should reset the flag because a new client is
3047  // connecting and the deferred removal is no longer needed.
3048  NSMutableDictionary* field = self.mutablePasswordTemplateCopy;
3049  [field setValue:@{
3050  @"uniqueIdentifier" : @"field1",
3051  @"hints" : @[ @"password" ],
3052  @"editingValue" : @{@"text" : @""}
3053  }
3054  forKey:@"autofill"];
3055  [field setValue:@[ field ] forKey:@"fields"];
3056 
3057  // Set up autofill context.
3058  [self setClientId:123 configuration:field];
3059  XCTAssertGreaterThan(textInputPlugin.autofillContext.count, 0ul);
3060 
3061  // clearClient with autofill context sets pendingAutofillRemoval.
3062  [self setClientClear];
3063  XCTAssertTrue(textInputPlugin.pendingAutofillRemoval);
3064 
3065  // A new setClient resets the pending autofill removal flag.
3066  [self setClientId:456 configuration:self.mutableTemplateCopy];
3067  XCTAssertFalse(textInputPlugin.pendingAutofillRemoval);
3068  XCTAssertFalse(textInputPlugin.pendingInputViewRemoval);
3069 }
3070 
3071 - (void)testPendingInputViewRemovalAfterClearClient {
3072  // When autofillContext is empty and the view is first responder,
3073  // clearClient should set pendingInputViewRemoval,
3074  // and hideTextInput should consume it.
3075  NSDictionary* config = self.mutableTemplateCopy;
3076 
3077  // Verify initial state.
3078  [self setClientId:123 configuration:config];
3079  XCTAssertEqual(textInputPlugin.autofillContext.count, 0ul);
3080  XCTAssertFalse(textInputPlugin.pendingInputViewRemoval);
3081 
3082  // Stub isFirstResponder to simulate the view being first responder.
3083  // In the test environment, becomeFirstResponder does not work.
3084  id mockActiveView = OCMPartialMock(textInputPlugin.activeView);
3085  OCMStub([mockActiveView isFirstResponder]).andReturn(YES);
3086 
3087  // clearClient with no autofill context sets pendingInputViewRemoval.
3088  [self setClientClear];
3089  XCTAssertTrue(textInputPlugin.pendingInputViewRemoval);
3090  XCTAssertFalse(textInputPlugin.pendingAutofillRemoval);
3091 
3092  // hideTextInput consumes the flag and removes the view.
3093  [self setTextInputHide];
3094  XCTAssertFalse(textInputPlugin.pendingInputViewRemoval);
3095  XCTAssertNil(textInputPlugin.activeView.superview);
3096 }
3097 
3098 - (void)testHideBeforeClearClientRemovesViewImmediately {
3099  // When hideTextInput is called before clearTextInputClient,
3100  // the view is no longer first responder. clearClient should
3101  // remove the view immediately since no keyboard dismiss animation is needed.
3102  NSDictionary* config = self.mutableTemplateCopy;
3103 
3104  [self setClientId:123 configuration:config];
3105  [self setTextInputShow];
3106  XCTAssertNotNil(textInputPlugin.activeView.superview);
3107 
3108  // Hide first: resignFirstResponder, but no removeFromSuperview.
3109  [self setTextInputHide];
3110  XCTAssertNotNil(textInputPlugin.activeView.superview);
3111 
3112  // clearClient after hide: view is not first responder,
3113  // so removeFromSuperview should happen immediately.
3114  [self setClientClear];
3115  XCTAssertFalse(textInputPlugin.pendingInputViewRemoval);
3116  XCTAssertNil(textInputPlugin.activeView.superview);
3117 }
3118 
3119 - (void)testSetClientResetsPendingInputViewRemoval {
3120  // When clearClient sets pendingInputViewRemoval (no autofill, first responder),
3121  // a subsequent setClient should reset the flag because a new client is
3122  // connecting and the deferred removal is no longer needed.
3123  NSDictionary* config = self.mutableTemplateCopy;
3124 
3125  // Field 1: setClient → show → clearClient (sets pendingInputViewRemoval).
3126  [self setClientId:123 configuration:config];
3127  [self setTextInputShow];
3128 
3129  // Stub isFirstResponder to simulate the view being first responder.
3130  // In the test environment, becomeFirstResponder does not work.
3131  id mockActiveView = OCMPartialMock(textInputPlugin.activeView);
3132  OCMStub([mockActiveView isFirstResponder]).andReturn(YES);
3133 
3134  [self setClientClear];
3135  XCTAssertTrue(textInputPlugin.pendingInputViewRemoval);
3136 
3137  // Field 2: setClient resets the stale flag.
3138  [self setClientId:456 configuration:config];
3139  XCTAssertFalse(textInputPlugin.pendingInputViewRemoval);
3140 }
3141 
3142 - (void)testPasswordAutofillHack {
3143  NSDictionary* config = self.mutableTemplateCopy;
3144  [config setValue:@"YES" forKey:@"obscureText"];
3145  [self setClientId:123 configuration:config];
3146 
3147  // Find all the FlutterTextInputViews we created.
3148  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
3149 
3150  FlutterTextInputView* inputView = inputFields[0];
3151 
3152  XCTAssert([inputView isKindOfClass:[UITextField class]]);
3153  // FlutterSecureTextInputView does not respond to font,
3154  // but it should return the default UITextField.font.
3155  XCTAssertNotEqual([inputView performSelector:@selector(font)], nil);
3156 }
3157 
3158 - (void)testClearAutofillContextClearsSelection {
3159  NSMutableDictionary* regularField = self.mutableTemplateCopy;
3160  NSDictionary* editingValue = @{
3161  @"text" : @"REGULAR_TEXT_FIELD",
3162  @"composingBase" : @0,
3163  @"composingExtent" : @3,
3164  @"selectionBase" : @1,
3165  @"selectionExtent" : @4
3166  };
3167  [regularField setValue:@{
3168  @"uniqueIdentifier" : @"field2",
3169  @"hints" : @[ @"hint2" ],
3170  @"editingValue" : editingValue,
3171  }
3172  forKey:@"autofill"];
3173  [regularField addEntriesFromDictionary:editingValue];
3174  [self setClientId:123 configuration:regularField];
3175  [self ensureOnlyActiveViewCanBecomeFirstResponder];
3176  XCTAssertEqual(self.installedInputViews.count, 1ul);
3177 
3178  FlutterTextInputView* oldInputView = self.installedInputViews[0];
3179  XCTAssert([oldInputView.text isEqualToString:@"REGULAR_TEXT_FIELD"]);
3180  FlutterTextRange* selectionRange = (FlutterTextRange*)oldInputView.selectedTextRange;
3181  XCTAssert(NSEqualRanges(selectionRange.range, NSMakeRange(1, 3)));
3182 
3183  // Replace the original password field with new one. This should remove
3184  // the old password field, but not immediately.
3185  [self setClientId:124 configuration:self.mutablePasswordTemplateCopy];
3186  [self ensureOnlyActiveViewCanBecomeFirstResponder];
3187 
3188  XCTAssertEqual(self.installedInputViews.count, 2ul);
3189 
3190  [textInputPlugin cleanUpViewHierarchy:NO clearText:YES delayRemoval:NO];
3191  XCTAssertEqual(self.installedInputViews.count, 1ul);
3192 
3193  // Verify the old input view is properly cleaned up.
3194  XCTAssert([oldInputView.text isEqualToString:@""]);
3195  selectionRange = (FlutterTextRange*)oldInputView.selectedTextRange;
3196  XCTAssert(NSEqualRanges(selectionRange.range, NSMakeRange(0, 0)));
3197 }
3198 
3199 - (void)testGarbageInputViewsAreNotRemovedImmediately {
3200  // Add a password field that should autofill.
3201  [self setClientId:123 configuration:self.mutablePasswordTemplateCopy];
3202  [self ensureOnlyActiveViewCanBecomeFirstResponder];
3203 
3204  XCTAssertEqual(self.installedInputViews.count, 1ul);
3205  // Add an input field that doesn't autofill. This should remove the password
3206  // field, but not immediately.
3207  [self setClientId:124 configuration:self.mutableTemplateCopy];
3208  [self ensureOnlyActiveViewCanBecomeFirstResponder];
3209 
3210  XCTAssertEqual(self.installedInputViews.count, 2ul);
3211 
3212  [self commitAutofillContextAndVerify];
3213 }
3214 
3215 - (void)testScribbleSetSelectionRects {
3216  NSMutableDictionary* regularField = self.mutableTemplateCopy;
3217  NSDictionary* editingValue = @{
3218  @"text" : @"REGULAR_TEXT_FIELD",
3219  @"composingBase" : @0,
3220  @"composingExtent" : @3,
3221  @"selectionBase" : @1,
3222  @"selectionExtent" : @4
3223  };
3224  [regularField setValue:@{
3225  @"uniqueIdentifier" : @"field1",
3226  @"hints" : @[ @"hint2" ],
3227  @"editingValue" : editingValue,
3228  }
3229  forKey:@"autofill"];
3230  [regularField addEntriesFromDictionary:editingValue];
3231  [self setClientId:123 configuration:regularField];
3232  XCTAssertEqual(self.installedInputViews.count, 1ul);
3233  XCTAssertEqual([textInputPlugin.activeView.selectionRects count], 0u);
3234 
3235  NSArray<NSNumber*>* selectionRect = [NSArray arrayWithObjects:@0, @0, @100, @100, @0, @1, nil];
3236  NSArray* selectionRects = [NSArray arrayWithObjects:selectionRect, nil];
3237  FlutterMethodCall* methodCall =
3238  [FlutterMethodCall methodCallWithMethodName:@"Scribble.setSelectionRects"
3239  arguments:selectionRects];
3240  [textInputPlugin handleMethodCall:methodCall
3241  result:^(id _Nullable result){
3242  }];
3243 
3244  XCTAssertEqual([textInputPlugin.activeView.selectionRects count], 1u);
3245 }
3246 
3247 - (void)testDecommissionedViewAreNotReusedByAutofill {
3248  // Regression test for https://github.com/flutter/flutter/issues/84407.
3249  NSMutableDictionary* configuration = self.mutableTemplateCopy;
3250  [configuration setValue:@{
3251  @"uniqueIdentifier" : @"field1",
3252  @"hints" : @[ UITextContentTypePassword ],
3253  @"editingValue" : @{@"text" : @""}
3254  }
3255  forKey:@"autofill"];
3256  [configuration setValue:@[ [configuration copy] ] forKey:@"fields"];
3257 
3258  [self setClientId:123 configuration:configuration];
3259 
3260  [self setTextInputHide];
3261  UIView* previousActiveView = textInputPlugin.activeView;
3262 
3263  [self setClientId:124 configuration:configuration];
3264 
3265  // Make sure the autofillable view is reused.
3266  XCTAssertEqual(previousActiveView, textInputPlugin.activeView);
3267  XCTAssertNotNil(previousActiveView);
3268  // Does not crash.
3269 }
3270 
3271 - (void)testInitialActiveViewCantAccessTextInputDelegate {
3272  // Before the framework sends the first text input configuration,
3273  // the dummy "activeView" we use should never have access to
3274  // its textInputDelegate.
3275  XCTAssertNil(textInputPlugin.activeView.textInputDelegate);
3276 }
3277 
3278 - (void)testAutoFillDoesNotTriggerOnShowAndHideKeyboard {
3279  // Regression test for https://github.com/flutter/flutter/issues/145681.
3280  NSMutableDictionary* configuration = self.mutableTemplateCopy;
3281  [configuration setValue:@{
3282  @"uniqueIdentifier" : @"field1",
3283  @"hints" : @[ UITextContentTypePassword ],
3284  @"editingValue" : @{@"text" : @""}
3285  }
3286  forKey:@"autofill"];
3287  [configuration setValue:@[ [configuration copy] ] forKey:@"fields"];
3288  [self setClientId:123 configuration:configuration];
3289 
3290  [self setTextInputShow];
3291  XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul);
3292 
3293  // Hiding keyboard does not trigger showing autofill prompt.
3294  [self setTextInputHide];
3295  XCTAssertEqual(self.viewsVisibleToAutofill.count, 1ul);
3296 
3297  [self commitAutofillContextAndVerify];
3298 }
3299 
3300 #pragma mark - Accessibility - Tests
3301 
3302 - (void)testUITextInputAccessibilityNotHiddenWhenKeyboardIsShownAndHidden {
3303  [self setClientId:123 configuration:self.mutableTemplateCopy];
3304 
3305  // Find all the FlutterTextInputViews we created.
3306  NSArray<FlutterTextInputView*>* inputFields = self.installedInputViews;
3307 
3308  // The input view should not be hidden.
3309  XCTAssertEqual([inputFields count], 1u);
3310 
3311  // Send show text input method call.
3312  [self setTextInputShow];
3313 
3314  inputFields = self.installedInputViews;
3315 
3316  XCTAssertEqual([inputFields count], 1u);
3317 
3318  // Send hide text input method call.
3319  [self setTextInputHide];
3320 
3321  inputFields = self.installedInputViews;
3322 
3323  XCTAssertEqual([inputFields count], 1u);
3324 
3325  // Send clear text client method call.
3326  [self setClientClear];
3327 
3328  inputFields = self.installedInputViews;
3329 
3330  // The input view should be hidden.
3331  XCTAssertEqual([inputFields count], 0u);
3332 }
3333 
3334 - (void)testFlutterTextInputViewDirectFocusToBackingTextInput {
3335  FlutterTextInputViewSpy* inputView =
3336  [[FlutterTextInputViewSpy alloc] initWithOwner:textInputPlugin];
3337  UIView* container = [[UIView alloc] init];
3338  UIAccessibilityElement* backing =
3339  [[UIAccessibilityElement alloc] initWithAccessibilityContainer:container];
3340  inputView.backingTextInputAccessibilityObject = backing;
3341  // Simulate accessibility focus.
3342  inputView.isAccessibilityFocused = YES;
3343  [inputView accessibilityElementDidBecomeFocused];
3344 
3345  XCTAssertEqual(inputView.receivedNotification, UIAccessibilityScreenChangedNotification);
3346  XCTAssertEqual(inputView.receivedNotificationTarget, backing);
3347 }
3348 
3349 - (void)testFlutterTokenizerCanParseLines {
3350  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3351  id<UITextInputTokenizer> tokenizer = [inputView tokenizer];
3352 
3353  // The tokenizer returns zero range When text is empty.
3354  FlutterTextRange* range = [self getLineRangeFromTokenizer:tokenizer atIndex:0];
3355  XCTAssertEqual(range.range.location, 0u);
3356  XCTAssertEqual(range.range.length, 0u);
3357 
3358  [inputView insertText:@"how are you\nI am fine, Thank you"];
3359 
3360  range = [self getLineRangeFromTokenizer:tokenizer atIndex:0];
3361  XCTAssertEqual(range.range.location, 0u);
3362  XCTAssertEqual(range.range.length, 11u);
3363 
3364  range = [self getLineRangeFromTokenizer:tokenizer atIndex:2];
3365  XCTAssertEqual(range.range.location, 0u);
3366  XCTAssertEqual(range.range.length, 11u);
3367 
3368  range = [self getLineRangeFromTokenizer:tokenizer atIndex:11];
3369  XCTAssertEqual(range.range.location, 0u);
3370  XCTAssertEqual(range.range.length, 11u);
3371 
3372  range = [self getLineRangeFromTokenizer:tokenizer atIndex:12];
3373  XCTAssertEqual(range.range.location, 12u);
3374  XCTAssertEqual(range.range.length, 20u);
3375 
3376  range = [self getLineRangeFromTokenizer:tokenizer atIndex:15];
3377  XCTAssertEqual(range.range.location, 12u);
3378  XCTAssertEqual(range.range.length, 20u);
3379 
3380  range = [self getLineRangeFromTokenizer:tokenizer atIndex:32];
3381  XCTAssertEqual(range.range.location, 12u);
3382  XCTAssertEqual(range.range.length, 20u);
3383 }
3384 
3385 - (void)testFlutterTokenizerLineEnclosingEndOfDocumentInBackwardDirectionShouldNotReturnNil {
3386  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3387  [inputView insertText:@"0123456789\n012345"];
3388  id<UITextInputTokenizer> tokenizer = [inputView tokenizer];
3389 
3390  FlutterTextRange* range =
3391  (FlutterTextRange*)[tokenizer rangeEnclosingPosition:[inputView endOfDocument]
3392  withGranularity:UITextGranularityLine
3393  inDirection:UITextStorageDirectionBackward];
3394  XCTAssertEqual(range.range.location, 11u);
3395  XCTAssertEqual(range.range.length, 6u);
3396 }
3397 
3398 - (void)testFlutterTokenizerLineEnclosingEndOfDocumentInForwardDirectionShouldReturnNilOnIOS17 {
3399  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3400  [inputView insertText:@"0123456789\n012345"];
3401  id<UITextInputTokenizer> tokenizer = [inputView tokenizer];
3402 
3403  FlutterTextRange* range =
3404  (FlutterTextRange*)[tokenizer rangeEnclosingPosition:[inputView endOfDocument]
3405  withGranularity:UITextGranularityLine
3406  inDirection:UITextStorageDirectionForward];
3407  if (@available(iOS 17.0, *)) {
3408  XCTAssertNil(range);
3409  } else {
3410  XCTAssertEqual(range.range.location, 11u);
3411  XCTAssertEqual(range.range.length, 6u);
3412  }
3413 }
3414 
3415 - (void)testFlutterTokenizerLineEnclosingOutOfRangePositionShouldReturnNilOnIOS17 {
3416  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3417  [inputView insertText:@"0123456789\n012345"];
3418  id<UITextInputTokenizer> tokenizer = [inputView tokenizer];
3419 
3421  FlutterTextRange* range =
3422  (FlutterTextRange*)[tokenizer rangeEnclosingPosition:position
3423  withGranularity:UITextGranularityLine
3424  inDirection:UITextStorageDirectionForward];
3425  if (@available(iOS 17.0, *)) {
3426  XCTAssertNil(range);
3427  } else {
3428  XCTAssertEqual(range.range.location, 0u);
3429  XCTAssertEqual(range.range.length, 0u);
3430  }
3431 }
3432 
3433 - (void)testFlutterTextInputPluginRetainsFlutterTextInputView {
3434  FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
3435  FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine];
3436  myInputPlugin.viewController = flutterViewController;
3437 
3438  __weak UIView* activeView;
3439  @autoreleasepool {
3440  FlutterMethodCall* setClientCall = [FlutterMethodCall
3441  methodCallWithMethodName:@"TextInput.setClient"
3442  arguments:@[
3443  [NSNumber numberWithInt:123], self.mutablePasswordTemplateCopy
3444  ]];
3445  [myInputPlugin handleMethodCall:setClientCall
3446  result:^(id _Nullable result){
3447  }];
3448  activeView = myInputPlugin.textInputView;
3449  FlutterMethodCall* hideCall = [FlutterMethodCall methodCallWithMethodName:@"TextInput.hide"
3450  arguments:@[]];
3451  [myInputPlugin handleMethodCall:hideCall
3452  result:^(id _Nullable result){
3453  }];
3454  XCTAssertNotNil(activeView);
3455  }
3456  // This assert proves the myInputPlugin.textInputView is not deallocated.
3457  XCTAssertNotNil(activeView);
3458 }
3459 
3460 - (void)testFlutterTextInputPluginHostViewNilCrash {
3461  FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine];
3462  myInputPlugin.viewController = nil;
3463  XCTAssertThrows([myInputPlugin hostView], @"Throws exception if host view is nil");
3464 }
3465 
3466 - (void)testFlutterTextInputPluginHostViewNotNil {
3467  FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
3468  FlutterEngine* flutterEngine = [[FlutterEngine alloc] init];
3469  [flutterEngine runWithEntrypoint:nil];
3470  flutterEngine.viewController = flutterViewController;
3471  XCTAssertNotNil(flutterEngine.textInputPlugin.viewController);
3472  XCTAssertNotNil([flutterEngine.textInputPlugin hostView]);
3473 }
3474 
3475 - (void)testSetPlatformViewClient {
3476  FlutterViewController* flutterViewController = [[FlutterViewController alloc] init];
3477  FlutterTextInputPlugin* myInputPlugin = [[FlutterTextInputPlugin alloc] initWithDelegate:engine];
3478  myInputPlugin.viewController = flutterViewController;
3479 
3480  FlutterMethodCall* setClientCall = [FlutterMethodCall
3481  methodCallWithMethodName:@"TextInput.setClient"
3482  arguments:@[ [NSNumber numberWithInt:123], self.mutablePasswordTemplateCopy ]];
3483  [myInputPlugin handleMethodCall:setClientCall
3484  result:^(id _Nullable result){
3485  }];
3486  UIView* activeView = myInputPlugin.textInputView;
3487  XCTAssertNotNil(activeView.superview, @"activeView must be added to the view hierarchy.");
3488  FlutterMethodCall* setPlatformViewClientCall = [FlutterMethodCall
3489  methodCallWithMethodName:@"TextInput.setPlatformViewClient"
3490  arguments:@{@"platformViewId" : [NSNumber numberWithLong:456]}];
3491  [myInputPlugin handleMethodCall:setPlatformViewClientCall
3492  result:^(id _Nullable result){
3493  }];
3494  XCTAssertNil(activeView.superview, @"activeView must be removed from view hierarchy.");
3495 }
3496 
3497 - (void)testEditMenu_shouldSetupEditMenuDelegateCorrectly {
3498  if (@available(iOS 16.0, *)) {
3499  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3500  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
3501  XCTAssertEqual(inputView.editMenuInteraction.delegate, inputView,
3502  @"editMenuInteraction setup delegate correctly");
3503  }
3504 }
3505 
3506 - (void)testEditMenu_shouldNotPresentEditMenuIfNotFirstResponder {
3507  if (@available(iOS 16.0, *)) {
3508  FlutterTextInputPlugin* myInputPlugin =
3509  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3510  BOOL shownEditMenu = [myInputPlugin showEditMenu:@{}];
3511  XCTAssertFalse(shownEditMenu, @"Should not show edit menu if not first responder.");
3512  }
3513 }
3514 
3515 - (void)testEditMenu_shouldPresentEditMenuWithCorrectConfiguration {
3516  if (@available(iOS 16.0, *)) {
3517  FlutterTextInputPlugin* myInputPlugin =
3518  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3519  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
3520  myInputPlugin.viewController = myViewController;
3521  [myViewController loadView];
3522  FlutterMethodCall* setClientCall =
3523  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
3524  arguments:@[ @(123), self.mutableTemplateCopy ]];
3525  [myInputPlugin handleMethodCall:setClientCall
3526  result:^(id _Nullable result){
3527  }];
3528 
3529  FlutterTextInputView* myInputView = myInputPlugin.activeView;
3530  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
3531 
3532  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
3533 
3534  XCTestExpectation* expectation = [[XCTestExpectation alloc]
3535  initWithDescription:@"presentEditMenuWithConfiguration must be called."];
3536 
3537  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
3538  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
3539  OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]])
3540  .andDo(^(NSInvocation* invocation) {
3541  // arguments are released once invocation is released.
3542  [invocation retainArguments];
3543  UIEditMenuConfiguration* config;
3544  [invocation getArgument:&config atIndex:2];
3545  XCTAssertEqual(config.preferredArrowDirection, UIEditMenuArrowDirectionAutomatic,
3546  @"UIEditMenuConfiguration must use automatic arrow direction.");
3547  XCTAssert(CGPointEqualToPoint(config.sourcePoint, CGPointZero),
3548  @"UIEditMenuConfiguration must have the correct point.");
3549  [expectation fulfill];
3550  });
3551 
3552  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
3553  @{@"x" : @(0), @"y" : @(0), @"width" : @(0), @"height" : @(0)};
3554 
3555  BOOL shownEditMenu = [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect}];
3556  XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration.");
3557  [self waitForExpectations:@[ expectation ] timeout:1.0];
3558  }
3559 }
3560 
3561 - (void)testEditMenu_shouldPresentEditMenuWithCorectTargetRect {
3562  if (@available(iOS 16.0, *)) {
3563  FlutterTextInputPlugin* myInputPlugin =
3564  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3565  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
3566  myInputPlugin.viewController = myViewController;
3567  [myViewController loadView];
3568 
3569  FlutterMethodCall* setClientCall =
3570  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
3571  arguments:@[ @(123), self.mutableTemplateCopy ]];
3572  [myInputPlugin handleMethodCall:setClientCall
3573  result:^(id _Nullable result){
3574  }];
3575 
3576  FlutterTextInputView* myInputView = myInputPlugin.activeView;
3577 
3578  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
3579  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
3580 
3581  XCTestExpectation* expectation = [[XCTestExpectation alloc]
3582  initWithDescription:@"presentEditMenuWithConfiguration must be called."];
3583 
3584  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
3585  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
3586  OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]])
3587  .andDo(^(NSInvocation* invocation) {
3588  [expectation fulfill];
3589  });
3590 
3591  myInputView.frame = CGRectMake(10, 20, 30, 40);
3592  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
3593  @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)};
3594 
3595  BOOL shownEditMenu = [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect}];
3596  XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration.");
3597  [self waitForExpectations:@[ expectation ] timeout:1.0];
3598 
3599  CGRect targetRect =
3600  [myInputView editMenuInteraction:mockInteraction
3601  targetRectForConfiguration:OCMClassMock([UIEditMenuConfiguration class])];
3602  // the encoded target rect is in global coordinate space.
3603  XCTAssert(CGRectEqualToRect(targetRect, CGRectMake(90, 180, 300, 400)),
3604  @"targetRectForConfiguration must return the correct target rect.");
3605  }
3606 }
3607 
3608 - (void)testEditMenu_shouldPresentEditMenuWithSuggestedItemsByDefaultIfNoFrameworkData {
3609  if (@available(iOS 16.0, *)) {
3610  FlutterTextInputPlugin* myInputPlugin =
3611  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3612  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
3613  myInputPlugin.viewController = myViewController;
3614  [myViewController loadView];
3615 
3616  FlutterMethodCall* setClientCall =
3617  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
3618  arguments:@[ @(123), self.mutableTemplateCopy ]];
3619  [myInputPlugin handleMethodCall:setClientCall
3620  result:^(id _Nullable result){
3621  }];
3622 
3623  FlutterTextInputView* myInputView = myInputPlugin.activeView;
3624 
3625  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
3626  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
3627 
3628  XCTestExpectation* expectation = [[XCTestExpectation alloc]
3629  initWithDescription:@"presentEditMenuWithConfiguration must be called."];
3630 
3631  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
3632  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
3633  OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]])
3634  .andDo(^(NSInvocation* invocation) {
3635  [expectation fulfill];
3636  });
3637 
3638  myInputView.frame = CGRectMake(10, 20, 30, 40);
3639  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
3640  @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)};
3641  // No items provided from framework. Show the suggested items by default.
3642  BOOL shownEditMenu = [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect}];
3643  XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration.");
3644  [self waitForExpectations:@[ expectation ] timeout:1.0];
3645 
3646  UICommand* copyItem = [UICommand commandWithTitle:@"Copy"
3647  image:nil
3648  action:@selector(copy:)
3649  propertyList:nil];
3650  UICommand* pasteItem = [UICommand commandWithTitle:@"Paste"
3651  image:nil
3652  action:@selector(paste:)
3653  propertyList:nil];
3654  NSArray<UICommand*>* suggestedActions = @[ copyItem, pasteItem ];
3655 
3656  UIMenu* menu = [myInputView editMenuInteraction:mockInteraction
3657  menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class])
3658  suggestedActions:suggestedActions];
3659  XCTAssertEqualObjects(menu.children, suggestedActions,
3660  @"Must show suggested items by default.");
3661  }
3662 }
3663 
3664 - (void)testEditMenu_shouldPresentEditMenuWithCorectItemsAndCorrectOrderingForBasicEditingActions {
3665  if (@available(iOS 16.0, *)) {
3666  FlutterTextInputPlugin* myInputPlugin =
3667  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3668  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
3669  myInputPlugin.viewController = myViewController;
3670  [myViewController loadView];
3671 
3672  FlutterMethodCall* setClientCall =
3673  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
3674  arguments:@[ @(123), self.mutableTemplateCopy ]];
3675  [myInputPlugin handleMethodCall:setClientCall
3676  result:^(id _Nullable result){
3677  }];
3678 
3679  FlutterTextInputView* myInputView = myInputPlugin.activeView;
3680 
3681  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
3682  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
3683 
3684  XCTestExpectation* expectation = [[XCTestExpectation alloc]
3685  initWithDescription:@"presentEditMenuWithConfiguration must be called."];
3686 
3687  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
3688  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
3689  OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]])
3690  .andDo(^(NSInvocation* invocation) {
3691  [expectation fulfill];
3692  });
3693 
3694  myInputView.frame = CGRectMake(10, 20, 30, 40);
3695  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
3696  @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)};
3697 
3698  NSArray<NSDictionary<NSString*, id>*>* encodedItems =
3699  @[ @{@"type" : @"paste"}, @{@"type" : @"copy"} ];
3700 
3701  BOOL shownEditMenu =
3702  [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}];
3703  XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration.");
3704  [self waitForExpectations:@[ expectation ] timeout:1.0];
3705 
3706  UICommand* copyItem = [UICommand commandWithTitle:@"Copy"
3707  image:nil
3708  action:@selector(copy:)
3709  propertyList:nil];
3710  UICommand* pasteItem = [UICommand commandWithTitle:@"Paste"
3711  image:nil
3712  action:@selector(paste:)
3713  propertyList:nil];
3714  NSArray<UICommand*>* suggestedActions = @[ copyItem, pasteItem ];
3715 
3716  UIMenu* menu = [myInputView editMenuInteraction:mockInteraction
3717  menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class])
3718  suggestedActions:suggestedActions];
3719  // The item ordering should follow the encoded data sent from the framework.
3720  NSArray<UICommand*>* expectedChildren = @[ pasteItem, copyItem ];
3721  XCTAssertEqualObjects(menu.children, expectedChildren);
3722  }
3723 }
3724 
3725 - (void)testEditMenu_shouldPresentEditMenuWithCorectItemsUnderNestedSubtreeForBasicEditingActions {
3726  if (@available(iOS 16.0, *)) {
3727  FlutterTextInputPlugin* myInputPlugin =
3728  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3729  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
3730  myInputPlugin.viewController = myViewController;
3731  [myViewController loadView];
3732 
3733  FlutterMethodCall* setClientCall =
3734  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
3735  arguments:@[ @(123), self.mutableTemplateCopy ]];
3736  [myInputPlugin handleMethodCall:setClientCall
3737  result:^(id _Nullable result){
3738  }];
3739 
3740  FlutterTextInputView* myInputView = myInputPlugin.activeView;
3741 
3742  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
3743  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
3744 
3745  XCTestExpectation* expectation = [[XCTestExpectation alloc]
3746  initWithDescription:@"presentEditMenuWithConfiguration must be called."];
3747 
3748  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
3749  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
3750  OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]])
3751  .andDo(^(NSInvocation* invocation) {
3752  [expectation fulfill];
3753  });
3754 
3755  myInputView.frame = CGRectMake(10, 20, 30, 40);
3756  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
3757  @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)};
3758 
3759  NSArray<NSDictionary<NSString*, id>*>* encodedItems =
3760  @[ @{@"type" : @"cut"}, @{@"type" : @"paste"}, @{@"type" : @"copy"} ];
3761 
3762  BOOL shownEditMenu =
3763  [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}];
3764  XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration.");
3765  [self waitForExpectations:@[ expectation ] timeout:1.0];
3766 
3767  UICommand* copyItem = [UICommand commandWithTitle:@"Copy"
3768  image:nil
3769  action:@selector(copy:)
3770  propertyList:nil];
3771  UICommand* cutItem = [UICommand commandWithTitle:@"Cut"
3772  image:nil
3773  action:@selector(cut:)
3774  propertyList:nil];
3775  UICommand* pasteItem = [UICommand commandWithTitle:@"Paste"
3776  image:nil
3777  action:@selector(paste:)
3778  propertyList:nil];
3779  /*
3780  A more complex menu hierarchy for DFS:
3781 
3782  menu
3783  / | \
3784  copy menu menu
3785  | \
3786  paste menu
3787  |
3788  cut
3789  */
3790  NSArray<UIMenuElement*>* suggestedActions = @[
3791  copyItem, [UIMenu menuWithChildren:@[ pasteItem ]],
3792  [UIMenu menuWithChildren:@[ [UIMenu menuWithChildren:@[ cutItem ]] ]]
3793  ];
3794 
3795  UIMenu* menu = [myInputView editMenuInteraction:mockInteraction
3796  menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class])
3797  suggestedActions:suggestedActions];
3798  // The item ordering should follow the encoded data sent from the framework.
3799  NSArray<UICommand*>* expectedActions = @[ cutItem, pasteItem, copyItem ];
3800  XCTAssertEqualObjects(menu.children, expectedActions);
3801  }
3802 }
3803 
3804 - (void)testEditMenu_shouldPresentEditMenuWithCorectItemsForMoreAdditionalItems {
3805  if (@available(iOS 16.0, *)) {
3806  FlutterTextInputPlugin* myInputPlugin =
3807  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
3808  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
3809  myInputPlugin.viewController = myViewController;
3810  [myViewController loadView];
3811 
3812  FlutterMethodCall* setClientCall =
3813  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
3814  arguments:@[ @(123), self.mutableTemplateCopy ]];
3815  [myInputPlugin handleMethodCall:setClientCall
3816  result:^(id _Nullable result){
3817  }];
3818 
3819  FlutterTextInputView* myInputView = myInputPlugin.activeView;
3820 
3821  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
3822  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
3823 
3824  XCTestExpectation* expectation = [[XCTestExpectation alloc]
3825  initWithDescription:@"presentEditMenuWithConfiguration must be called."];
3826 
3827  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
3828  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
3829  OCMStub([mockInteraction presentEditMenuWithConfiguration:[OCMArg any]])
3830  .andDo(^(NSInvocation* invocation) {
3831  [expectation fulfill];
3832  });
3833 
3834  myInputView.frame = CGRectMake(10, 20, 30, 40);
3835  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
3836  @{@"x" : @(100), @"y" : @(200), @"width" : @(300), @"height" : @(400)};
3837 
3838  NSMutableArray<NSDictionary<NSString*, id>*>* encodedItems = [@[
3839  @{@"type" : @"searchWeb", @"title" : @"Search Web"},
3840  @{@"type" : @"lookUp", @"title" : @"Look Up"}, @{@"type" : @"share", @"title" : @"Share"}
3841  ] mutableCopy];
3842  if (@available(iOS 17.4, *)) {
3843  [encodedItems addObject:@{@"type" : @"translate", @"title" : @"Translate"}];
3844  }
3845 
3846  BOOL shownEditMenu =
3847  [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}];
3848  XCTAssertTrue(shownEditMenu, @"Should show edit menu with correct configuration.");
3849  [self waitForExpectations:@[ expectation ] timeout:1.0];
3850 
3851  NSArray<UICommand*>* suggestedActions = @[
3852  [UICommand commandWithTitle:@"copy" image:nil action:@selector(copy:) propertyList:nil],
3853  ];
3854 
3855  UIMenu* menu = [myInputView editMenuInteraction:mockInteraction
3856  menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class])
3857  suggestedActions:suggestedActions];
3858  if (@available(iOS 17.4, *)) {
3859  XCTAssert(menu.children.count == 4, @"There must be 4 menu items");
3860  } else {
3861  XCTAssert(menu.children.count == 3, @"There must be 3 menu items");
3862  }
3863 
3864  XCTAssert(((UICommand*)menu.children[0]).action == @selector(handleSearchWebAction),
3865  @"Must create search web item in the tree.");
3866  XCTAssert(((UICommand*)menu.children[1]).action == @selector(handleLookUpAction),
3867  @"Must create look up item in the tree.");
3868  XCTAssert(((UICommand*)menu.children[2]).action == @selector(handleShareAction),
3869  @"Must create share item in the tree.");
3870  if (@available(iOS 17.4, *)) {
3871  XCTAssert(((UICommand*)menu.children[3]).action == @selector(handleTranslateAction),
3872  @"Must create translate item in the tree.");
3873  }
3874  }
3875 }
3876 
3877 - (void)testInteractiveKeyboardAfterUserScrollWillResignFirstResponder {
3878  if (@available(iOS 17.0, *)) {
3879  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
3880  "https://github.com/flutter/flutter/issues/183473");
3881  }
3882  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3883  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
3884 
3885  [inputView setTextInputClient:123];
3886  [inputView reloadInputViews];
3887  [inputView becomeFirstResponder];
3888  XCTAssert(inputView.isFirstResponder);
3889 
3890  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
3891  [NSNotificationCenter.defaultCenter
3892  postNotificationName:UIKeyboardWillShowNotification
3893  object:nil
3894  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
3895  FlutterMethodCall* onPointerMoveCall =
3896  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
3897  arguments:@{@"pointerY" : @(500)}];
3898  [textInputPlugin handleMethodCall:onPointerMoveCall
3899  result:^(id _Nullable result){
3900  }];
3901  XCTAssertFalse(inputView.isFirstResponder);
3902  textInputPlugin.cachedFirstResponder = nil;
3903 }
3904 
3905 - (void)testInteractiveKeyboardAfterUserScrollToTopOfKeyboardWillTakeScreenshot {
3906  if (@available(iOS 17.0, *)) {
3907  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
3908  "https://github.com/flutter/flutter/issues/183473");
3909  }
3910  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
3911  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
3912  UIScene* scene = scenes.anyObject;
3913  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
3914  UIWindowScene* windowScene = (UIWindowScene*)scene;
3915  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
3916  UIWindow* window = windowScene.windows[0];
3917  [window addSubview:viewController.view];
3918 
3919  [viewController loadView];
3920 
3921  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3922  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
3923 
3924  [inputView setTextInputClient:123];
3925  [inputView reloadInputViews];
3926  [inputView becomeFirstResponder];
3927 
3928  if (textInputPlugin.keyboardView.superview != nil) {
3929  for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) {
3930  [subView removeFromSuperview];
3931  }
3932  }
3933  XCTAssert(textInputPlugin.keyboardView.superview == nil);
3934  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
3935  [NSNotificationCenter.defaultCenter
3936  postNotificationName:UIKeyboardWillShowNotification
3937  object:nil
3938  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
3939  FlutterMethodCall* onPointerMoveCall =
3940  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
3941  arguments:@{@"pointerY" : @(510)}];
3942  [textInputPlugin handleMethodCall:onPointerMoveCall
3943  result:^(id _Nullable result){
3944  }];
3945  XCTAssertFalse(textInputPlugin.keyboardView.superview == nil);
3946  for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) {
3947  [subView removeFromSuperview];
3948  }
3949  textInputPlugin.cachedFirstResponder = nil;
3950 }
3951 
3952 - (void)testInteractiveKeyboardScreenshotWillBeMovedDownAfterUserScroll {
3953  if (@available(iOS 17.0, *)) {
3954  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
3955  "https://github.com/flutter/flutter/issues/183473");
3956  }
3957  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
3958  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
3959  UIScene* scene = scenes.anyObject;
3960  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
3961  UIWindowScene* windowScene = (UIWindowScene*)scene;
3962  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
3963  UIWindow* window = windowScene.windows[0];
3964  [window addSubview:viewController.view];
3965 
3966  [viewController loadView];
3967 
3968  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3969  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
3970 
3971  [inputView setTextInputClient:123];
3972  [inputView reloadInputViews];
3973  [inputView becomeFirstResponder];
3974 
3975  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
3976  [NSNotificationCenter.defaultCenter
3977  postNotificationName:UIKeyboardWillShowNotification
3978  object:nil
3979  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
3980  FlutterMethodCall* onPointerMoveCall =
3981  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
3982  arguments:@{@"pointerY" : @(510)}];
3983  [textInputPlugin handleMethodCall:onPointerMoveCall
3984  result:^(id _Nullable result){
3985  }];
3986  XCTAssert(textInputPlugin.keyboardView.superview != nil);
3987 
3988  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y);
3989 
3990  FlutterMethodCall* onPointerMoveCallMove =
3991  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
3992  arguments:@{@"pointerY" : @(600)}];
3993  [textInputPlugin handleMethodCall:onPointerMoveCallMove
3994  result:^(id _Nullable result){
3995  }];
3996  XCTAssert(textInputPlugin.keyboardView.superview != nil);
3997 
3998  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, 600.0);
3999 
4000  for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) {
4001  [subView removeFromSuperview];
4002  }
4003  textInputPlugin.cachedFirstResponder = nil;
4004 }
4005 
4006 - (void)testInteractiveKeyboardScreenshotWillBeMovedToOrginalPositionAfterUserScroll {
4007  if (@available(iOS 17.0, *)) {
4008  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
4009  "https://github.com/flutter/flutter/issues/183473");
4010  }
4011  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
4012  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
4013  UIScene* scene = scenes.anyObject;
4014  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
4015  UIWindowScene* windowScene = (UIWindowScene*)scene;
4016  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
4017  UIWindow* window = windowScene.windows[0];
4018  [window addSubview:viewController.view];
4019 
4020  [viewController loadView];
4021 
4022  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4023  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
4024 
4025  [inputView setTextInputClient:123];
4026  [inputView reloadInputViews];
4027  [inputView becomeFirstResponder];
4028 
4029  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
4030  [NSNotificationCenter.defaultCenter
4031  postNotificationName:UIKeyboardWillShowNotification
4032  object:nil
4033  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
4034  FlutterMethodCall* onPointerMoveCall =
4035  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4036  arguments:@{@"pointerY" : @(500)}];
4037  [textInputPlugin handleMethodCall:onPointerMoveCall
4038  result:^(id _Nullable result){
4039  }];
4040  XCTAssert(textInputPlugin.keyboardView.superview != nil);
4041  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y);
4042 
4043  FlutterMethodCall* onPointerMoveCallMove =
4044  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4045  arguments:@{@"pointerY" : @(600)}];
4046  [textInputPlugin handleMethodCall:onPointerMoveCallMove
4047  result:^(id _Nullable result){
4048  }];
4049  XCTAssert(textInputPlugin.keyboardView.superview != nil);
4050  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, 600.0);
4051 
4052  FlutterMethodCall* onPointerMoveCallBackUp =
4053  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4054  arguments:@{@"pointerY" : @(10)}];
4055  [textInputPlugin handleMethodCall:onPointerMoveCallBackUp
4056  result:^(id _Nullable result){
4057  }];
4058  XCTAssert(textInputPlugin.keyboardView.superview != nil);
4059  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y, keyboardFrame.origin.y);
4060  for (UIView* subView in textInputPlugin.keyboardViewContainer.subviews) {
4061  [subView removeFromSuperview];
4062  }
4063  textInputPlugin.cachedFirstResponder = nil;
4064 }
4065 
4066 - (void)testInteractiveKeyboardFindFirstResponderRecursive {
4067  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4068  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
4069  [inputView setTextInputClient:123];
4070  [inputView reloadInputViews];
4071  [inputView becomeFirstResponder];
4072 
4073  UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder;
4074  XCTAssertEqualObjects(inputView, firstResponder);
4075  textInputPlugin.cachedFirstResponder = nil;
4076 }
4077 
4078 - (void)testInteractiveKeyboardFindFirstResponderRecursiveInMultipleSubviews {
4079  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4080  FlutterTextInputView* subInputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4081  FlutterTextInputView* otherSubInputView =
4082  [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4083  FlutterTextInputView* subFirstResponderInputView =
4084  [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4085  [subInputView addSubview:subFirstResponderInputView];
4086  [inputView addSubview:subInputView];
4087  [inputView addSubview:otherSubInputView];
4088  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
4089  [inputView setTextInputClient:123];
4090  [inputView reloadInputViews];
4091  [subInputView setTextInputClient:123];
4092  [subInputView reloadInputViews];
4093  [otherSubInputView setTextInputClient:123];
4094  [otherSubInputView reloadInputViews];
4095  [subFirstResponderInputView setTextInputClient:123];
4096  [subFirstResponderInputView reloadInputViews];
4097  [subFirstResponderInputView becomeFirstResponder];
4098 
4099  UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder;
4100  XCTAssertEqualObjects(subFirstResponderInputView, firstResponder);
4101  textInputPlugin.cachedFirstResponder = nil;
4102 }
4103 
4104 - (void)testInteractiveKeyboardFindFirstResponderIsNilRecursive {
4105  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4106  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
4107  [inputView setTextInputClient:123];
4108  [inputView reloadInputViews];
4109 
4110  UIView* firstResponder = UIApplication.sharedApplication.keyWindow.flutterFirstResponder;
4111  XCTAssertNil(firstResponder);
4112  textInputPlugin.cachedFirstResponder = nil;
4113 }
4114 
4115 - (void)testInteractiveKeyboardDidResignFirstResponderDelegateisCalledAfterDismissedKeyboard {
4116  if (@available(iOS 17.0, *)) {
4117  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
4118  "https://github.com/flutter/flutter/issues/183473");
4119  }
4120  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
4121  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
4122  UIScene* scene = scenes.anyObject;
4123  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
4124  UIWindowScene* windowScene = (UIWindowScene*)scene;
4125  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
4126  UIWindow* window = windowScene.windows[0];
4127  [window addSubview:viewController.view];
4128 
4129  [viewController loadView];
4130 
4131  XCTestExpectation* expectation = [[XCTestExpectation alloc]
4132  initWithDescription:
4133  @"didResignFirstResponder is called after screenshot keyboard dismissed."];
4134  OCMStub([engine flutterTextInputView:[OCMArg any] didResignFirstResponderWithTextInputClient:0])
4135  .andDo(^(NSInvocation* invocation) {
4136  [expectation fulfill];
4137  });
4138  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
4139  [NSNotificationCenter.defaultCenter
4140  postNotificationName:UIKeyboardWillShowNotification
4141  object:nil
4142  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
4143  FlutterMethodCall* initialMoveCall =
4144  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4145  arguments:@{@"pointerY" : @(500)}];
4146  [textInputPlugin handleMethodCall:initialMoveCall
4147  result:^(id _Nullable result){
4148  }];
4149  FlutterMethodCall* subsequentMoveCall =
4150  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4151  arguments:@{@"pointerY" : @(1000)}];
4152  [textInputPlugin handleMethodCall:subsequentMoveCall
4153  result:^(id _Nullable result){
4154  }];
4155 
4156  FlutterMethodCall* pointerUpCall =
4157  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard"
4158  arguments:@{@"pointerY" : @(1000)}];
4159  [textInputPlugin handleMethodCall:pointerUpCall
4160  result:^(id _Nullable result){
4161  }];
4162 
4163  [self waitForExpectations:@[ expectation ] timeout:2.0];
4164  textInputPlugin.cachedFirstResponder = nil;
4165 }
4166 
4167 - (void)testInteractiveKeyboardScreenshotDismissedAfterPointerLiftedAboveMiddleYOfKeyboard {
4168  if (@available(iOS 17.0, *)) {
4169  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
4170  "https://github.com/flutter/flutter/issues/183473");
4171  }
4172  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
4173  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
4174  UIScene* scene = scenes.anyObject;
4175  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
4176  UIWindowScene* windowScene = (UIWindowScene*)scene;
4177  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
4178  UIWindow* window = windowScene.windows[0];
4179  [window addSubview:viewController.view];
4180 
4181  [viewController loadView];
4182 
4183  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
4184  [NSNotificationCenter.defaultCenter
4185  postNotificationName:UIKeyboardWillShowNotification
4186  object:nil
4187  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
4188  FlutterMethodCall* initialMoveCall =
4189  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4190  arguments:@{@"pointerY" : @(500)}];
4191  [textInputPlugin handleMethodCall:initialMoveCall
4192  result:^(id _Nullable result){
4193  }];
4194  FlutterMethodCall* subsequentMoveCall =
4195  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4196  arguments:@{@"pointerY" : @(1000)}];
4197  [textInputPlugin handleMethodCall:subsequentMoveCall
4198  result:^(id _Nullable result){
4199  }];
4200 
4201  FlutterMethodCall* subsequentMoveBackUpCall =
4202  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4203  arguments:@{@"pointerY" : @(0)}];
4204  [textInputPlugin handleMethodCall:subsequentMoveBackUpCall
4205  result:^(id _Nullable result){
4206  }];
4207 
4208  FlutterMethodCall* pointerUpCall =
4209  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard"
4210  arguments:@{@"pointerY" : @(0)}];
4211  [textInputPlugin handleMethodCall:pointerUpCall
4212  result:^(id _Nullable result){
4213  }];
4214  NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) {
4215  return textInputPlugin.keyboardViewContainer.subviews.count == 0;
4216  }];
4217  XCTNSPredicateExpectation* expectation =
4218  [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil];
4219  [self waitForExpectations:@[ expectation ] timeout:10.0];
4220  textInputPlugin.cachedFirstResponder = nil;
4221 }
4222 
4223 - (void)testInteractiveKeyboardKeyboardReappearsAfterPointerLiftedAboveMiddleYOfKeyboard {
4224  if (@available(iOS 17.0, *)) {
4225  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
4226  "https://github.com/flutter/flutter/issues/183473");
4227  }
4228  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
4229  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
4230  UIScene* scene = scenes.anyObject;
4231  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
4232  UIWindowScene* windowScene = (UIWindowScene*)scene;
4233  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
4234  UIWindow* window = windowScene.windows[0];
4235  [window addSubview:viewController.view];
4236 
4237  [viewController loadView];
4238 
4239  FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
4240  [UIApplication.sharedApplication.keyWindow addSubview:inputView];
4241 
4242  [inputView setTextInputClient:123];
4243  [inputView reloadInputViews];
4244  [inputView becomeFirstResponder];
4245 
4246  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
4247  [NSNotificationCenter.defaultCenter
4248  postNotificationName:UIKeyboardWillShowNotification
4249  object:nil
4250  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
4251  FlutterMethodCall* initialMoveCall =
4252  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4253  arguments:@{@"pointerY" : @(500)}];
4254  [textInputPlugin handleMethodCall:initialMoveCall
4255  result:^(id _Nullable result){
4256  }];
4257  FlutterMethodCall* subsequentMoveCall =
4258  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4259  arguments:@{@"pointerY" : @(1000)}];
4260  [textInputPlugin handleMethodCall:subsequentMoveCall
4261  result:^(id _Nullable result){
4262  }];
4263 
4264  FlutterMethodCall* subsequentMoveBackUpCall =
4265  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4266  arguments:@{@"pointerY" : @(0)}];
4267  [textInputPlugin handleMethodCall:subsequentMoveBackUpCall
4268  result:^(id _Nullable result){
4269  }];
4270 
4271  FlutterMethodCall* pointerUpCall =
4272  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard"
4273  arguments:@{@"pointerY" : @(0)}];
4274  [textInputPlugin handleMethodCall:pointerUpCall
4275  result:^(id _Nullable result){
4276  }];
4277  NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) {
4278  return textInputPlugin.cachedFirstResponder.isFirstResponder;
4279  }];
4280  XCTNSPredicateExpectation* expectation =
4281  [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil];
4282  [self waitForExpectations:@[ expectation ] timeout:10.0];
4283  textInputPlugin.cachedFirstResponder = nil;
4284 }
4285 
4286 - (void)testInteractiveKeyboardKeyboardAnimatesToOriginalPositionalOnPointerUp {
4287  if (@available(iOS 17.0, *)) {
4288  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
4289  "https://github.com/flutter/flutter/issues/183473");
4290  }
4291  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
4292  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
4293  UIScene* scene = scenes.anyObject;
4294  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
4295  UIWindowScene* windowScene = (UIWindowScene*)scene;
4296  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
4297  UIWindow* window = windowScene.windows[0];
4298  [window addSubview:viewController.view];
4299 
4300  [viewController loadView];
4301 
4302  XCTestExpectation* expectation =
4303  [[XCTestExpectation alloc] initWithDescription:@"Keyboard animates to proper position."];
4304  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
4305  [NSNotificationCenter.defaultCenter
4306  postNotificationName:UIKeyboardWillShowNotification
4307  object:nil
4308  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
4309  FlutterMethodCall* initialMoveCall =
4310  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4311  arguments:@{@"pointerY" : @(500)}];
4312  [textInputPlugin handleMethodCall:initialMoveCall
4313  result:^(id _Nullable result){
4314  }];
4315  FlutterMethodCall* subsequentMoveCall =
4316  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4317  arguments:@{@"pointerY" : @(1000)}];
4318  [textInputPlugin handleMethodCall:subsequentMoveCall
4319  result:^(id _Nullable result){
4320  }];
4321  FlutterMethodCall* upwardVelocityMoveCall =
4322  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4323  arguments:@{@"pointerY" : @(500)}];
4324  [textInputPlugin handleMethodCall:upwardVelocityMoveCall
4325  result:^(id _Nullable result){
4326  }];
4327 
4328  FlutterMethodCall* pointerUpCall =
4329  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard"
4330  arguments:@{@"pointerY" : @(0)}];
4331  [textInputPlugin
4332  handleMethodCall:pointerUpCall
4333  result:^(id _Nullable result) {
4334  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y,
4335  viewController.flutterScreenIfViewLoaded.bounds.size.height -
4336  keyboardFrame.origin.y);
4337  [expectation fulfill];
4338  }];
4339  textInputPlugin.cachedFirstResponder = nil;
4340 }
4341 
4342 - (void)testInteractiveKeyboardKeyboardAnimatesToDismissalPositionalOnPointerUp {
4343  if (@available(iOS 17.0, *)) {
4344  XCTSkip(@"Interactive keyboard tests broken on iOS 17+ due to SDK bugs. See: "
4345  "https://github.com/flutter/flutter/issues/183473");
4346  }
4347  NSSet<UIScene*>* scenes = UIApplication.sharedApplication.connectedScenes;
4348  XCTAssertEqual(scenes.count, 1UL, @"There must only be 1 scene for test");
4349  UIScene* scene = scenes.anyObject;
4350  XCTAssert([scene isKindOfClass:[UIWindowScene class]], @"Must be a window scene for test");
4351  UIWindowScene* windowScene = (UIWindowScene*)scene;
4352  XCTAssert(windowScene.windows.count > 0, @"There must be at least 1 window for test");
4353  UIWindow* window = windowScene.windows[0];
4354  [window addSubview:viewController.view];
4355 
4356  [viewController loadView];
4357 
4358  XCTestExpectation* expectation =
4359  [[XCTestExpectation alloc] initWithDescription:@"Keyboard animates to proper position."];
4360  CGRect keyboardFrame = CGRectMake(0, 500, 500, 500);
4361  [NSNotificationCenter.defaultCenter
4362  postNotificationName:UIKeyboardWillShowNotification
4363  object:nil
4364  userInfo:@{UIKeyboardFrameEndUserInfoKey : @(keyboardFrame)}];
4365  FlutterMethodCall* initialMoveCall =
4366  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4367  arguments:@{@"pointerY" : @(500)}];
4368  [textInputPlugin handleMethodCall:initialMoveCall
4369  result:^(id _Nullable result){
4370  }];
4371  FlutterMethodCall* subsequentMoveCall =
4372  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerMoveForInteractiveKeyboard"
4373  arguments:@{@"pointerY" : @(1000)}];
4374  [textInputPlugin handleMethodCall:subsequentMoveCall
4375  result:^(id _Nullable result){
4376  }];
4377 
4378  FlutterMethodCall* pointerUpCall =
4379  [FlutterMethodCall methodCallWithMethodName:@"TextInput.onPointerUpForInteractiveKeyboard"
4380  arguments:@{@"pointerY" : @(1000)}];
4381  [textInputPlugin
4382  handleMethodCall:pointerUpCall
4383  result:^(id _Nullable result) {
4384  XCTAssertEqual(textInputPlugin.keyboardViewContainer.frame.origin.y,
4385  viewController.flutterScreenIfViewLoaded.bounds.size.height);
4386  [expectation fulfill];
4387  }];
4388  textInputPlugin.cachedFirstResponder = nil;
4389 }
4390 - (void)testInteractiveKeyboardShowKeyboardAndRemoveScreenshotAnimationIsNotImmediatelyEnable {
4391  [UIView setAnimationsEnabled:YES];
4392  [textInputPlugin showKeyboardAndRemoveScreenshot];
4393  XCTAssertFalse(
4394  UIView.areAnimationsEnabled,
4395  @"The animation should still be disabled following showKeyboardAndRemoveScreenshot");
4396 }
4397 
4398 - (void)testInteractiveKeyboardShowKeyboardAndRemoveScreenshotAnimationIsReenabledAfterDelay {
4399  [UIView setAnimationsEnabled:YES];
4400  [textInputPlugin showKeyboardAndRemoveScreenshot];
4401 
4402  NSPredicate* predicate = [NSPredicate predicateWithBlock:^BOOL(id item, NSDictionary* bindings) {
4403  // This will be enabled after a delay
4404  return UIView.areAnimationsEnabled;
4405  }];
4406  XCTNSPredicateExpectation* expectation =
4407  [[XCTNSPredicateExpectation alloc] initWithPredicate:predicate object:nil];
4408  [self waitForExpectations:@[ expectation ] timeout:10.0];
4409 }
4410 
4411 - (void)testEditMenu_shouldCreateCustomMenuItemWithCorrectProperties {
4412  if (@available(iOS 16.0, *)) {
4413  FlutterTextInputPlugin* myInputPlugin =
4414  [[FlutterTextInputPlugin alloc] initWithDelegate:OCMClassMock([FlutterEngine class])];
4415  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
4416  myInputPlugin.viewController = myViewController;
4417  [myViewController loadView];
4418 
4419  FlutterMethodCall* setClientCall =
4420  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
4421  arguments:@[ @(123), self.mutableTemplateCopy ]];
4422  [myInputPlugin handleMethodCall:setClientCall
4423  result:^(id _Nullable result){
4424  }];
4425 
4426  FlutterTextInputView* myInputView = myInputPlugin.activeView;
4427  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
4428  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
4429 
4430  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
4431  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
4432 
4433  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
4434  @{@"x" : @(0), @"y" : @(0), @"width" : @(100), @"height" : @(50)};
4435 
4436  NSArray<NSDictionary*>* encodedItems = @[
4437  @{@"type" : @"custom", @"id" : @"custom-action-1", @"title" : @"Custom Action 1"},
4438  @{@"type" : @"custom", @"id" : @"custom-action-2", @"title" : @"Custom Action 2"},
4439  ];
4440 
4441  BOOL shownEditMenu =
4442  [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}];
4443  XCTAssertTrue(shownEditMenu, @"Should show edit menu");
4444 
4445  UIMenu* menu = [myInputView editMenuInteraction:mockInteraction
4446  menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class])
4447  suggestedActions:@[]];
4448 
4449  XCTAssertEqual(menu.children.count, 2UL, @"Should create 2 custom menu items");
4450  UIAction* firstAction = (UIAction*)menu.children[0];
4451  UIAction* secondAction = (UIAction*)menu.children[1];
4452  XCTAssertEqualObjects(firstAction.title, @"Custom Action 1",
4453  @"First action title should match");
4454  XCTAssertEqualObjects(secondAction.title, @"Custom Action 2",
4455  @"Second action title should match");
4456  }
4457 }
4458 
4459 - (void)testEditMenu_customActionShouldTriggerDelegateCallback {
4460  if (@available(iOS 16.0, *)) {
4461  id mockEngine = OCMClassMock([FlutterEngine class]);
4462  id mockPlatformChannel = OCMClassMock([FlutterMethodChannel class]);
4463  OCMStub([mockEngine platformChannel]).andReturn(mockPlatformChannel);
4464 
4465  OCMStub([mockEngine flutterTextInputView:[OCMArg any]
4466  performContextMenuCustomActionWithActionID:@"test-callback-id"
4467  textInputClient:123])
4468  .andDo((^(NSInvocation* invocation) {
4469  [mockPlatformChannel invokeMethod:@"ContextMenu.onPerformCustomAction"
4470  arguments:@[ @(123), @"test-callback-id" ]];
4471  }));
4472 
4473  FlutterTextInputPlugin* myInputPlugin =
4474  [[FlutterTextInputPlugin alloc] initWithDelegate:mockEngine];
4475  FlutterViewController* myViewController = [[FlutterViewController alloc] init];
4476  myInputPlugin.viewController = myViewController;
4477  [myViewController loadView];
4478 
4479  FlutterMethodCall* setClientCall =
4480  [FlutterMethodCall methodCallWithMethodName:@"TextInput.setClient"
4481  arguments:@[ @(123), self.mutableTemplateCopy ]];
4482  [myInputPlugin handleMethodCall:setClientCall
4483  result:^(id _Nullable result){
4484  }];
4485 
4486  FlutterTextInputView* myInputView = myInputPlugin.activeView;
4487  FlutterTextInputView* mockInputView = OCMPartialMock(myInputView);
4488  OCMStub([mockInputView isFirstResponder]).andReturn(YES);
4489  XCTestExpectation* expectation = [[XCTestExpectation alloc]
4490  initWithDescription:@"Custom action delegate callback should be called"];
4491  OCMStub(([mockPlatformChannel invokeMethod:@"ContextMenu.onPerformCustomAction"
4492  arguments:@[ @(123), @"test-callback-id" ]]))
4493  .andDo(^(NSInvocation* invocation) {
4494  [expectation fulfill];
4495  });
4496  id mockInteraction = OCMClassMock([UIEditMenuInteraction class]);
4497  OCMStub([mockInputView editMenuInteraction]).andReturn(mockInteraction);
4498 
4499  NSDictionary<NSString*, NSNumber*>* encodedTargetRect =
4500  @{@"x" : @(0), @"y" : @(0), @"width" : @(100), @"height" : @(50)};
4501 
4502  NSArray<NSDictionary*>* encodedItems = @[
4503  @{@"type" : @"custom", @"id" : @"test-callback-id", @"title" : @"Test Action"},
4504  ];
4505 
4506  BOOL shownEditMenu =
4507  [myInputPlugin showEditMenu:@{@"targetRect" : encodedTargetRect, @"items" : encodedItems}];
4508  XCTAssertTrue(shownEditMenu, @"Should show edit menu");
4509 
4510  UIMenu* menu = [myInputView editMenuInteraction:mockInteraction
4511  menuForConfiguration:OCMClassMock([UIEditMenuConfiguration class])
4512  suggestedActions:@[]];
4513 
4514  XCTAssertEqual(menu.children.count, 1UL, @"Should have 1 custom menu item");
4515  UIAction* customAction = (UIAction*)menu.children[0];
4516  XCTAssertEqualObjects(customAction.title, @"Test Action", @"Action title should match");
4517 
4518  [myInputView.textInputDelegate flutterTextInputView:myInputView
4519  performContextMenuCustomActionWithActionID:@"test-callback-id"
4520  textInputClient:123];
4521 
4522  [self waitForExpectations:@[ expectation ] timeout:1.0];
4523  OCMVerifyAll(mockPlatformChannel);
4524  }
4525 }
4526 
4527 @end
void(^ FlutterResult)(id _Nullable result)
flutter::Settings settings_
std::unique_ptr< flutter::PlatformViewIOS > platform_view
NSArray< FlutterTextSelectionRect * > * selectionRects
BOOL isScribbleAvailable
UITextRange * markedTextRange
API_AVAILABLE(ios(13.0)) @interface FlutterTextPlaceholder UITextRange * selectedTextRange
UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0))
CGRect caretRectForPosition
const CGRect kInvalidFirstRect
NSDictionary * _passwordTemplate
FlutterViewController * viewController
FlutterTextInputPlugin * textInputPlugin
BOOL runWithEntrypoint:initialRoute:(nullable NSString *entrypoint,[initialRoute] nullable NSString *NS_SWIFT_UI_ACTOR)
void setBinaryMessenger:(FlutterBinaryMessengerRelay *binaryMessenger)
FlutterViewController * viewController
void flutterTextInputView:performAction:withClient:(FlutterTextInputView *textInputView,[performAction] FlutterTextInputAction action,[withClient] int client)
BOOL runWithEntrypoint:(nullable NSString *NS_SWIFT_UI_ACTOR)
instancetype methodCallWithMethodName:arguments:(NSString *method,[arguments] id _Nullable arguments)
UIView< UITextInput > * textInputView()
UIIndirectScribbleInteractionDelegate UIViewController * viewController
BOOL showEditMenu:(ios(16.0) API_AVAILABLE)
void handleMethodCall:result:(FlutterMethodCall *call,[result] FlutterResult result)
UIAccessibilityNotifications receivedNotification
instancetype positionWithIndex:(NSUInteger index)
UITextStorageDirection affinity
instancetype rangeWithNSRange:(NSRange range)
instancetype selectionRectWithRect:position:(CGRect rect,[position] NSUInteger position)
instancetype selectionRectWithRect:position:writingDirection:(CGRect rect,[position] NSUInteger position,[writingDirection] NSWritingDirection writingDirection)
int64_t texture_id