This repository was archived by the owner on Feb 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy pathFlutterTextInputPlugin.mm
More file actions
1322 lines (1114 loc) · 46.6 KB
/
FlutterTextInputPlugin.mm
File metadata and controls
1322 lines (1114 loc) · 46.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
#include "flutter/fml/platform/darwin/string_range_sanitization.h"
#include <Foundation/Foundation.h>
#include <UIKit/UIKit.h>
static const char _kTextAffinityDownstream[] = "TextAffinity.downstream";
static const char _kTextAffinityUpstream[] = "TextAffinity.upstream";
#pragma mark - TextInputConfiguration Field Names
static NSString* const kSecureTextEntry = @"obscureText";
static NSString* const kKeyboardType = @"inputType";
static NSString* const kKeyboardAppearance = @"keyboardAppearance";
static NSString* const kInputAction = @"inputAction";
static NSString* const kSmartDashesType = @"smartDashesType";
static NSString* const kSmartQuotesType = @"smartQuotesType";
static NSString* const kAssociatedAutofillFields = @"fields";
// TextInputConfiguration.autofill and sub-field names
static NSString* const kAutofillProperties = @"autofill";
static NSString* const kAutofillId = @"uniqueIdentifier";
static NSString* const kAutofillEditingValue = @"editingValue";
static NSString* const kAutofillHints = @"hints";
static NSString* const kAutocorrectionType = @"autocorrect";
#pragma mark - Static Functions
static UIKeyboardType ToUIKeyboardType(NSDictionary* type) {
NSString* inputType = type[@"name"];
if ([inputType isEqualToString:@"TextInputType.address"])
return UIKeyboardTypeDefault;
if ([inputType isEqualToString:@"TextInputType.datetime"])
return UIKeyboardTypeNumbersAndPunctuation;
if ([inputType isEqualToString:@"TextInputType.emailAddress"])
return UIKeyboardTypeEmailAddress;
if ([inputType isEqualToString:@"TextInputType.multiline"])
return UIKeyboardTypeDefault;
if ([inputType isEqualToString:@"TextInputType.name"])
return UIKeyboardTypeNamePhonePad;
if ([inputType isEqualToString:@"TextInputType.number"]) {
if ([type[@"signed"] boolValue])
return UIKeyboardTypeNumbersAndPunctuation;
if ([type[@"decimal"] boolValue])
return UIKeyboardTypeDecimalPad;
return UIKeyboardTypeNumberPad;
}
if ([inputType isEqualToString:@"TextInputType.phone"])
return UIKeyboardTypePhonePad;
if ([inputType isEqualToString:@"TextInputType.text"])
return UIKeyboardTypeDefault;
if ([inputType isEqualToString:@"TextInputType.url"])
return UIKeyboardTypeURL;
return UIKeyboardTypeDefault;
}
static UITextAutocapitalizationType ToUITextAutoCapitalizationType(NSDictionary* type) {
NSString* textCapitalization = type[@"textCapitalization"];
if ([textCapitalization isEqualToString:@"TextCapitalization.characters"]) {
return UITextAutocapitalizationTypeAllCharacters;
} else if ([textCapitalization isEqualToString:@"TextCapitalization.sentences"]) {
return UITextAutocapitalizationTypeSentences;
} else if ([textCapitalization isEqualToString:@"TextCapitalization.words"]) {
return UITextAutocapitalizationTypeWords;
}
return UITextAutocapitalizationTypeNone;
}
static UIReturnKeyType ToUIReturnKeyType(NSString* inputType) {
// Where did the term "unspecified" come from? iOS has a "default" and Android
// has "unspecified." These 2 terms seem to mean the same thing but we need
// to pick just one. "unspecified" was chosen because "default" is often a
// reserved word in languages with switch statements (dart, java, etc).
if ([inputType isEqualToString:@"TextInputAction.unspecified"])
return UIReturnKeyDefault;
if ([inputType isEqualToString:@"TextInputAction.done"])
return UIReturnKeyDone;
if ([inputType isEqualToString:@"TextInputAction.go"])
return UIReturnKeyGo;
if ([inputType isEqualToString:@"TextInputAction.send"])
return UIReturnKeySend;
if ([inputType isEqualToString:@"TextInputAction.search"])
return UIReturnKeySearch;
if ([inputType isEqualToString:@"TextInputAction.next"])
return UIReturnKeyNext;
if (@available(iOS 9.0, *))
if ([inputType isEqualToString:@"TextInputAction.continueAction"])
return UIReturnKeyContinue;
if ([inputType isEqualToString:@"TextInputAction.join"])
return UIReturnKeyJoin;
if ([inputType isEqualToString:@"TextInputAction.route"])
return UIReturnKeyRoute;
if ([inputType isEqualToString:@"TextInputAction.emergencyCall"])
return UIReturnKeyEmergencyCall;
if ([inputType isEqualToString:@"TextInputAction.newline"])
return UIReturnKeyDefault;
// Present default key if bad input type is given.
return UIReturnKeyDefault;
}
static UITextContentType ToUITextContentType(NSArray<NSString*>* hints) {
if (hints == nil || hints.count == 0) {
return @"";
}
NSString* hint = hints[0];
if (@available(iOS 10.0, *)) {
if ([hint isEqualToString:@"addressCityAndState"]) {
return UITextContentTypeAddressCityAndState;
}
if ([hint isEqualToString:@"addressState"]) {
return UITextContentTypeAddressState;
}
if ([hint isEqualToString:@"addressCity"]) {
return UITextContentTypeAddressCity;
}
if ([hint isEqualToString:@"sublocality"]) {
return UITextContentTypeSublocality;
}
if ([hint isEqualToString:@"streetAddressLine1"]) {
return UITextContentTypeStreetAddressLine1;
}
if ([hint isEqualToString:@"streetAddressLine2"]) {
return UITextContentTypeStreetAddressLine2;
}
if ([hint isEqualToString:@"countryName"]) {
return UITextContentTypeCountryName;
}
if ([hint isEqualToString:@"fullStreetAddress"]) {
return UITextContentTypeFullStreetAddress;
}
if ([hint isEqualToString:@"postalCode"]) {
return UITextContentTypePostalCode;
}
if ([hint isEqualToString:@"location"]) {
return UITextContentTypeLocation;
}
if ([hint isEqualToString:@"creditCardNumber"]) {
return UITextContentTypeCreditCardNumber;
}
if ([hint isEqualToString:@"email"]) {
return UITextContentTypeEmailAddress;
}
if ([hint isEqualToString:@"jobTitle"]) {
return UITextContentTypeJobTitle;
}
if ([hint isEqualToString:@"givenName"]) {
return UITextContentTypeGivenName;
}
if ([hint isEqualToString:@"middleName"]) {
return UITextContentTypeMiddleName;
}
if ([hint isEqualToString:@"familyName"]) {
return UITextContentTypeFamilyName;
}
if ([hint isEqualToString:@"name"]) {
return UITextContentTypeName;
}
if ([hint isEqualToString:@"namePrefix"]) {
return UITextContentTypeNamePrefix;
}
if ([hint isEqualToString:@"nameSuffix"]) {
return UITextContentTypeNameSuffix;
}
if ([hint isEqualToString:@"nickname"]) {
return UITextContentTypeNickname;
}
if ([hint isEqualToString:@"organizationName"]) {
return UITextContentTypeOrganizationName;
}
if ([hint isEqualToString:@"telephoneNumber"]) {
return UITextContentTypeTelephoneNumber;
}
}
if (@available(iOS 11.0, *)) {
if ([hint isEqualToString:@"password"]) {
return UITextContentTypePassword;
}
}
if (@available(iOS 12.0, *)) {
if ([hint isEqualToString:@"oneTimeCode"]) {
return UITextContentTypeOneTimeCode;
}
if ([hint isEqualToString:@"newPassword"]) {
return UITextContentTypeNewPassword;
}
}
return hints[0];
}
// Retrieves the autofillId from an input field's configuration. Returns
// nil if the field is nil and the input field is not a password field.
static NSString* autofillIdFromDictionary(NSDictionary* dictionary) {
NSDictionary* autofill = dictionary[kAutofillProperties];
if (autofill) {
return autofill[kAutofillId];
}
// When autofill is nil, the field may still need an autofill id
// if the field is for password.
return [dictionary[kSecureTextEntry] boolValue] ? @"password" : nil;
}
// There're 2 types of autofills on native iOS:
// - Regular autofill, includes contact information autofill and
// one-time-code autofill, takes place in the form of predictive
// text in the quick type bar. This type of autofill does not save
// user input.
// - Password autofill, includes automatic strong password and regular
// password autofill. The former happens automatically when a
// "new password" field is detected, and only that password field
// will be populated. The latter appears in the quick type bar when
// an eligible input field becomes the first responder, and may
// fill both the username and the password fields. iOS will attempt
// to save user input for both kinds of password fields.
typedef NS_ENUM(NSInteger, FlutterAutofillType) {
// The field does not have autofillable content. Additionally if
// the field is currently in the autofill context, it will be
// removed from the context without triggering autofill save.
FlutterAutofillTypeNone,
FlutterAutofillTypeRegular,
FlutterAutofillTypePassword,
};
static BOOL isFieldPasswordRelated(NSDictionary* configuration) {
if (@available(iOS 10.0, *)) {
BOOL isSecureTextEntry = [configuration[kSecureTextEntry] boolValue];
if (isSecureTextEntry)
return YES;
if (!autofillIdFromDictionary(configuration)) {
return NO;
}
NSDictionary* autofill = configuration[kAutofillProperties];
UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]);
if (@available(iOS 11.0, *)) {
if ([contentType isEqualToString:UITextContentTypePassword] ||
[contentType isEqualToString:UITextContentTypeUsername]) {
return YES;
}
}
if (@available(iOS 12.0, *)) {
if ([contentType isEqualToString:UITextContentTypeNewPassword]) {
return YES;
}
}
}
return NO;
}
static FlutterAutofillType autofillTypeOf(NSDictionary* configuration) {
for (NSDictionary* field in configuration[kAssociatedAutofillFields]) {
if (isFieldPasswordRelated(field)) {
return FlutterAutofillTypePassword;
}
}
if (isFieldPasswordRelated(configuration)) {
return FlutterAutofillTypePassword;
}
if (@available(iOS 10.0, *)) {
NSDictionary* autofill = configuration[kAutofillProperties];
UITextContentType contentType = ToUITextContentType(autofill[kAutofillHints]);
return [contentType isEqualToString:@""] ? FlutterAutofillTypeNone : FlutterAutofillTypeRegular;
}
return FlutterAutofillTypeNone;
}
#pragma mark - FlutterTextPosition
@implementation FlutterTextPosition
+ (instancetype)positionWithIndex:(NSUInteger)index {
return [[[FlutterTextPosition alloc] initWithIndex:index] autorelease];
}
- (instancetype)initWithIndex:(NSUInteger)index {
self = [super init];
if (self) {
_index = index;
}
return self;
}
@end
#pragma mark - FlutterTextRange
@implementation FlutterTextRange
+ (instancetype)rangeWithNSRange:(NSRange)range {
return [[[FlutterTextRange alloc] initWithNSRange:range] autorelease];
}
- (instancetype)initWithNSRange:(NSRange)range {
self = [super init];
if (self) {
_range = range;
}
return self;
}
- (UITextPosition*)start {
return [FlutterTextPosition positionWithIndex:self.range.location];
}
- (UITextPosition*)end {
return [FlutterTextPosition positionWithIndex:self.range.location + self.range.length];
}
- (BOOL)isEmpty {
return self.range.length == 0;
}
- (id)copyWithZone:(NSZone*)zone {
return [[FlutterTextRange allocWithZone:zone] initWithNSRange:self.range];
}
- (BOOL)isEqualTo:(FlutterTextRange*)other {
return NSEqualRanges(self.range, other.range);
}
@end
// A FlutterTextInputView that masquerades as a UITextField, and forwards
// selectors it can't respond to to a shared UITextField instance.
//
// Relevant API docs claim that password autofill supports any custom view
// that adopts the UITextInput protocol, automatic strong password seems to
// currently only support UITextFields, and password saving only supports
// UITextFields and UITextViews, as of iOS 13.5.
@interface FlutterSecureTextInputView : FlutterTextInputView
@property(nonatomic, strong, readonly) UITextField* textField;
@end
@implementation FlutterSecureTextInputView {
UITextField* _textField;
}
- (void)dealloc {
[_textField release];
[super dealloc];
}
- (UITextField*)textField {
if (_textField == nil) {
_textField = [[[UITextField alloc] init] autorelease];
}
return _textField;
}
- (BOOL)isKindOfClass:(Class)aClass {
return [super isKindOfClass:aClass] || (aClass == [UITextField class]);
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];
if (!signature) {
signature = [self.textField methodSignatureForSelector:aSelector];
}
return signature;
}
- (void)forwardInvocation:(NSInvocation*)anInvocation {
[anInvocation invokeWithTarget:self.textField];
}
@end
@interface FlutterTextInputView ()
@property(nonatomic, copy) NSString* autofillId;
@property(nonatomic) BOOL isVisibleToAutofill;
@end
@implementation FlutterTextInputView {
int _textInputClient;
const char* _selectionAffinity;
FlutterTextRange* _selectedTextRange;
}
@synthesize tokenizer = _tokenizer;
- (instancetype)init {
self = [super init];
if (self) {
_textInputClient = 0;
_selectionAffinity = _kTextAffinityUpstream;
// UITextInput
_text = [[NSMutableString alloc] init];
_markedText = [[NSMutableString alloc] init];
_selectedTextRange = [[FlutterTextRange alloc] initWithNSRange:NSMakeRange(0, 0)];
// UITextInputTraits
_autocapitalizationType = UITextAutocapitalizationTypeSentences;
_autocorrectionType = UITextAutocorrectionTypeDefault;
_spellCheckingType = UITextSpellCheckingTypeDefault;
_enablesReturnKeyAutomatically = NO;
_keyboardAppearance = UIKeyboardAppearanceDefault;
_keyboardType = UIKeyboardTypeDefault;
_returnKeyType = UIReturnKeyDone;
_secureTextEntry = NO;
if (@available(iOS 11.0, *)) {
_smartQuotesType = UITextSmartQuotesTypeYes;
_smartDashesType = UITextSmartDashesTypeYes;
}
}
return self;
}
- (void)configureWithDictionary:(NSDictionary*)configuration {
NSDictionary* inputType = configuration[kKeyboardType];
NSString* keyboardAppearance = configuration[kKeyboardAppearance];
NSDictionary* autofill = configuration[kAutofillProperties];
self.secureTextEntry = [configuration[kSecureTextEntry] boolValue];
self.keyboardType = ToUIKeyboardType(inputType);
self.keyboardType = UIKeyboardTypeNamePhonePad;
self.returnKeyType = ToUIReturnKeyType(configuration[kInputAction]);
self.autocapitalizationType = ToUITextAutoCapitalizationType(configuration);
if (@available(iOS 11.0, *)) {
NSString* smartDashesType = configuration[kSmartDashesType];
// This index comes from the SmartDashesType enum in the framework.
bool smartDashesIsDisabled = smartDashesType && [smartDashesType isEqualToString:@"0"];
self.smartDashesType =
smartDashesIsDisabled ? UITextSmartDashesTypeNo : UITextSmartDashesTypeYes;
NSString* smartQuotesType = configuration[kSmartQuotesType];
// This index comes from the SmartQuotesType enum in the framework.
bool smartQuotesIsDisabled = smartQuotesType && [smartQuotesType isEqualToString:@"0"];
self.smartQuotesType =
smartQuotesIsDisabled ? UITextSmartQuotesTypeNo : UITextSmartQuotesTypeYes;
}
if ([keyboardAppearance isEqualToString:@"Brightness.dark"]) {
self.keyboardAppearance = UIKeyboardAppearanceDark;
} else if ([keyboardAppearance isEqualToString:@"Brightness.light"]) {
self.keyboardAppearance = UIKeyboardAppearanceLight;
} else {
self.keyboardAppearance = UIKeyboardAppearanceDefault;
}
NSString* autocorrect = configuration[kAutocorrectionType];
self.autocorrectionType = autocorrect && ![autocorrect boolValue]
? UITextAutocorrectionTypeNo
: UITextAutocorrectionTypeDefault;
if (@available(iOS 10.0, *)) {
self.autofillId = autofillIdFromDictionary(configuration);
if (autofill == nil) {
self.textContentType = @"";
} else {
self.textContentType = ToUITextContentType(autofill[kAutofillHints]);
[self setTextInputState:autofill[kAutofillEditingValue]];
NSAssert(_autofillId, @"The autofill configuration must contain an autofill id");
}
// The input field needs to be visible for the system autofill
// to find it.
self.isVisibleToAutofill = autofill || _secureTextEntry;
}
}
- (UITextContentType)textContentType {
return _textContentType;
}
- (void)dealloc {
[_text release];
[_markedText release];
[_markedTextRange release];
[_selectedTextRange release];
[_tokenizer release];
[_autofillId release];
[super dealloc];
}
- (void)setTextInputClient:(int)client {
_textInputClient = client;
}
// Return true if the new input state needs to be synced back to the framework.
- (BOOL)setTextInputState:(NSDictionary*)state {
NSString* newText = state[@"text"];
BOOL textChanged = ![self.text isEqualToString:newText];
if (textChanged) {
[self.inputDelegate textWillChange:self];
[self.text setString:newText];
}
BOOL needsEditingStateUpdate = textChanged;
NSInteger composingBase = [state[@"composingBase"] intValue];
NSInteger composingExtent = [state[@"composingExtent"] intValue];
NSRange composingRange = [self clampSelection:NSMakeRange(MIN(composingBase, composingExtent),
ABS(composingBase - composingExtent))
forText:self.text];
FlutterTextRange* newMarkedRange =
composingRange.length > 0 ? [FlutterTextRange rangeWithNSRange:composingRange] : nil;
needsEditingStateUpdate =
needsEditingStateUpdate || newMarkedRange == nil
? self.markedTextRange == nil
: [newMarkedRange isEqualTo:(FlutterTextRange*)self.markedTextRange];
self.markedTextRange = newMarkedRange;
NSInteger selectionBase = [state[@"selectionBase"] intValue];
NSInteger selectionExtent = [state[@"selectionExtent"] intValue];
NSRange selectedRange = [self clampSelection:NSMakeRange(MIN(selectionBase, selectionExtent),
ABS(selectionBase - selectionExtent))
forText:self.text];
NSRange oldSelectedRange = [(FlutterTextRange*)self.selectedTextRange range];
if (selectedRange.location != oldSelectedRange.location ||
selectedRange.length != oldSelectedRange.length) {
needsEditingStateUpdate = YES;
[self.inputDelegate selectionWillChange:self];
// The state may contain an invalid selection, such as when no selection was
// explicitly set in the framework. This is handled here by setting the
// selection to (0,0). In contrast, Android handles this situation by
// clearing the selection, but the result in both cases is that the cursor
// is placed at the beginning of the field.
bool selectionBaseIsValid = selectionBase > 0 && selectionBase <= ((NSInteger)self.text.length);
bool selectionExtentIsValid =
selectionExtent > 0 && selectionExtent <= ((NSInteger)self.text.length);
if (selectionBaseIsValid && selectionExtentIsValid) {
[self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:selectedRange]];
} else {
[self setSelectedTextRangeLocal:[FlutterTextRange rangeWithNSRange:NSMakeRange(0, 0)]];
}
_selectionAffinity = _kTextAffinityDownstream;
if ([state[@"selectionAffinity"] isEqualToString:@(_kTextAffinityUpstream)])
_selectionAffinity = _kTextAffinityUpstream;
[self.inputDelegate selectionDidChange:self];
}
if (textChanged) {
[self.inputDelegate textDidChange:self];
}
// For consistency with Android behavior, send an update to the framework if anything changed.
return needsEditingStateUpdate;
}
- (NSRange)clampSelection:(NSRange)range forText:(NSString*)text {
int start = MIN(MAX(range.location, 0), text.length);
int length = MIN(range.length, text.length - start);
return NSMakeRange(start, length);
}
- (BOOL)isVisibleToAutofill {
return self.frame.size.width > 0 && self.frame.size.height > 0;
}
// An input view is generally ignored by password autofill attempts, if it's
// not the first responder and is zero-sized. For input fields that are in the
// autofill context but do not belong to the current autofill group, setting
// their frames to CGRectZero prevents ios autofill from taking them into
// account.
- (void)setIsVisibleToAutofill:(BOOL)isVisibleToAutofill {
self.frame = isVisibleToAutofill ? CGRectMake(0, 0, 1, 1) : CGRectZero;
}
#pragma mark - UIResponder Overrides
- (BOOL)canBecomeFirstResponder {
// Only the currently focused input field can
// become the first responder. This prevents iOS
// from changing focus by itself (the framework
// focus will be out of sync if that happens).
return _textInputClient != 0;
}
#pragma mark - UITextInput Overrides
- (id<UITextInputTokenizer>)tokenizer {
if (_tokenizer == nil) {
_tokenizer = [[UITextInputStringTokenizer alloc] initWithTextInput:self];
}
return _tokenizer;
}
- (UITextRange*)selectedTextRange {
return [[_selectedTextRange copy] autorelease];
}
// Change the range of selected text, without notifying the framework.
- (void)setSelectedTextRangeLocal:(UITextRange*)selectedTextRange {
if (_selectedTextRange != selectedTextRange) {
UITextRange* oldSelectedRange = _selectedTextRange;
if (self.hasText) {
FlutterTextRange* flutterTextRange = (FlutterTextRange*)selectedTextRange;
_selectedTextRange = [[FlutterTextRange
rangeWithNSRange:fml::RangeForCharactersInRange(self.text, flutterTextRange.range)] copy];
} else {
_selectedTextRange = [selectedTextRange copy];
}
[oldSelectedRange release];
}
}
- (void)setSelectedTextRange:(UITextRange*)selectedTextRange {
[self setSelectedTextRangeLocal:selectedTextRange];
[self updateEditingState];
}
- (id)insertDictationResultPlaceholder {
return @"";
}
- (void)removeDictationResultPlaceholder:(id)placeholder willInsertResult:(BOOL)willInsertResult {
}
- (NSString*)textInRange:(UITextRange*)range {
if (!range) {
return nil;
}
NSAssert([range isKindOfClass:[FlutterTextRange class]],
@"Expected a FlutterTextRange for range (got %@).", [range class]);
NSRange textRange = ((FlutterTextRange*)range).range;
NSAssert(textRange.location != NSNotFound, @"Expected a valid text range.");
return [self.text substringWithRange:textRange];
}
// Replace the text within the specified range with the given text,
// without notifying the framework.
- (void)replaceRangeLocal:(NSRange)range withText:(NSString*)text {
NSRange selectedRange = _selectedTextRange.range;
// Adjust the text selection:
// * reduce the length by the intersection length
// * adjust the location by newLength - oldLength + intersectionLength
NSRange intersectionRange = NSIntersectionRange(range, selectedRange);
if (range.location <= selectedRange.location)
selectedRange.location += text.length - range.length;
if (intersectionRange.location != NSNotFound) {
selectedRange.location += intersectionRange.length;
selectedRange.length -= intersectionRange.length;
}
[self.text replaceCharactersInRange:[self clampSelection:range forText:self.text]
withString:text];
[self setSelectedTextRangeLocal:[FlutterTextRange
rangeWithNSRange:[self clampSelection:selectedRange
forText:self.text]]];
}
- (void)replaceRange:(UITextRange*)range withText:(NSString*)text {
NSRange replaceRange = ((FlutterTextRange*)range).range;
[self replaceRangeLocal:replaceRange withText:text];
[self updateEditingState];
}
- (BOOL)shouldChangeTextInRange:(UITextRange*)range replacementText:(NSString*)text {
if (self.returnKeyType == UIReturnKeyDefault && [text isEqualToString:@"\n"]) {
[_textInputDelegate performAction:FlutterTextInputActionNewline withClient:_textInputClient];
return YES;
}
if ([text isEqualToString:@"\n"]) {
FlutterTextInputAction action;
switch (self.returnKeyType) {
case UIReturnKeyDefault:
action = FlutterTextInputActionUnspecified;
break;
case UIReturnKeyDone:
action = FlutterTextInputActionDone;
break;
case UIReturnKeyGo:
action = FlutterTextInputActionGo;
break;
case UIReturnKeySend:
action = FlutterTextInputActionSend;
break;
case UIReturnKeySearch:
case UIReturnKeyGoogle:
case UIReturnKeyYahoo:
action = FlutterTextInputActionSearch;
break;
case UIReturnKeyNext:
action = FlutterTextInputActionNext;
break;
case UIReturnKeyContinue:
action = FlutterTextInputActionContinue;
break;
case UIReturnKeyJoin:
action = FlutterTextInputActionJoin;
break;
case UIReturnKeyRoute:
action = FlutterTextInputActionRoute;
break;
case UIReturnKeyEmergencyCall:
action = FlutterTextInputActionEmergencyCall;
break;
}
[_textInputDelegate performAction:action withClient:_textInputClient];
return NO;
}
return YES;
}
- (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelectedRange {
NSRange selectedRange = _selectedTextRange.range;
NSRange markedTextRange = ((FlutterTextRange*)self.markedTextRange).range;
if (markedText == nil)
markedText = @"";
if (markedTextRange.length > 0) {
// Replace text in the marked range with the new text.
[self replaceRangeLocal:markedTextRange withText:markedText];
markedTextRange.length = markedText.length;
} else {
// Replace text in the selected range with the new text.
[self replaceRangeLocal:selectedRange withText:markedText];
markedTextRange = NSMakeRange(selectedRange.location, markedText.length);
}
self.markedTextRange =
markedTextRange.length > 0 ? [FlutterTextRange rangeWithNSRange:markedTextRange] : nil;
NSUInteger selectionLocation = markedSelectedRange.location + markedTextRange.location;
selectedRange = NSMakeRange(selectionLocation, markedSelectedRange.length);
[self setSelectedTextRangeLocal:[FlutterTextRange
rangeWithNSRange:[self clampSelection:selectedRange
forText:self.text]]];
[self updateEditingState];
}
- (void)unmarkText {
self.markedTextRange = nil;
[self updateEditingState];
}
- (UITextRange*)textRangeFromPosition:(UITextPosition*)fromPosition
toPosition:(UITextPosition*)toPosition {
NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index;
NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index;
if (toIndex >= fromIndex) {
return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)];
} else {
// toIndex may be less than fromIndex, because
// UITextInputStringTokenizer does not handle CJK characters
// well in some cases. See:
// https://github.com/flutter/flutter/issues/58750#issuecomment-644469521
// Swap fromPosition and toPosition to match the behavior of native
// UITextViews.
return [FlutterTextRange rangeWithNSRange:NSMakeRange(toIndex, fromIndex - toIndex)];
}
}
- (NSUInteger)decrementOffsetPosition:(NSUInteger)position {
return fml::RangeForCharacterAtIndex(self.text, MAX(0, position - 1)).location;
}
- (NSUInteger)incrementOffsetPosition:(NSUInteger)position {
NSRange charRange = fml::RangeForCharacterAtIndex(self.text, position);
return MIN(position + charRange.length, self.text.length);
}
- (UITextPosition*)positionFromPosition:(UITextPosition*)position offset:(NSInteger)offset {
NSUInteger offsetPosition = ((FlutterTextPosition*)position).index;
NSInteger newLocation = (NSInteger)offsetPosition + offset;
if (newLocation < 0 || newLocation > (NSInteger)self.text.length) {
return nil;
}
if (offset >= 0) {
for (NSInteger i = 0; i < offset && offsetPosition < self.text.length; ++i)
offsetPosition = [self incrementOffsetPosition:offsetPosition];
} else {
for (NSInteger i = 0; i < ABS(offset) && offsetPosition > 0; ++i)
offsetPosition = [self decrementOffsetPosition:offsetPosition];
}
return [FlutterTextPosition positionWithIndex:offsetPosition];
}
- (UITextPosition*)positionFromPosition:(UITextPosition*)position
inDirection:(UITextLayoutDirection)direction
offset:(NSInteger)offset {
// TODO(cbracken) Add RTL handling.
switch (direction) {
case UITextLayoutDirectionLeft:
case UITextLayoutDirectionUp:
return [self positionFromPosition:position offset:offset * -1];
case UITextLayoutDirectionRight:
case UITextLayoutDirectionDown:
return [self positionFromPosition:position offset:1];
}
}
- (UITextPosition*)beginningOfDocument {
return [FlutterTextPosition positionWithIndex:0];
}
- (UITextPosition*)endOfDocument {
return [FlutterTextPosition positionWithIndex:self.text.length];
}
- (NSComparisonResult)comparePosition:(UITextPosition*)position toPosition:(UITextPosition*)other {
NSUInteger positionIndex = ((FlutterTextPosition*)position).index;
NSUInteger otherIndex = ((FlutterTextPosition*)other).index;
if (positionIndex < otherIndex)
return NSOrderedAscending;
if (positionIndex > otherIndex)
return NSOrderedDescending;
return NSOrderedSame;
}
- (NSInteger)offsetFromPosition:(UITextPosition*)from toPosition:(UITextPosition*)toPosition {
return ((FlutterTextPosition*)toPosition).index - ((FlutterTextPosition*)from).index;
}
- (UITextPosition*)positionWithinRange:(UITextRange*)range
farthestInDirection:(UITextLayoutDirection)direction {
NSUInteger index;
switch (direction) {
case UITextLayoutDirectionLeft:
case UITextLayoutDirectionUp:
index = ((FlutterTextPosition*)range.start).index;
break;
case UITextLayoutDirectionRight:
case UITextLayoutDirectionDown:
index = ((FlutterTextPosition*)range.end).index;
break;
}
return [FlutterTextPosition positionWithIndex:index];
}
- (UITextRange*)characterRangeByExtendingPosition:(UITextPosition*)position
inDirection:(UITextLayoutDirection)direction {
NSUInteger positionIndex = ((FlutterTextPosition*)position).index;
NSUInteger startIndex;
NSUInteger endIndex;
switch (direction) {
case UITextLayoutDirectionLeft:
case UITextLayoutDirectionUp:
startIndex = [self decrementOffsetPosition:positionIndex];
endIndex = positionIndex;
break;
case UITextLayoutDirectionRight:
case UITextLayoutDirectionDown:
startIndex = positionIndex;
endIndex = [self incrementOffsetPosition:positionIndex];
break;
}
return [FlutterTextRange rangeWithNSRange:NSMakeRange(startIndex, endIndex - startIndex)];
}
#pragma mark - UITextInput text direction handling
- (UITextWritingDirection)baseWritingDirectionForPosition:(UITextPosition*)position
inDirection:(UITextStorageDirection)direction {
// TODO(cbracken) Add RTL handling.
return UITextWritingDirectionNatural;
}
- (void)setBaseWritingDirection:(UITextWritingDirection)writingDirection
forRange:(UITextRange*)range {
// TODO(cbracken) Add RTL handling.
}
#pragma mark - UITextInput cursor, selection rect handling
// The following methods are required to support force-touch cursor positioning
// and to position the
// candidates view for multi-stage input methods (e.g., Japanese) when using a
// physical keyboard.
- (CGRect)firstRectForRange:(UITextRange*)range {
// multi-stage text is handled in the framework.
if (_markedTextRange != nil) {
return CGRectZero;
}
NSUInteger start = ((FlutterTextPosition*)range.start).index;
NSUInteger end = ((FlutterTextPosition*)range.end).index;
[_textInputDelegate showAutocorrectionPromptRectForStart:start
end:end
withClient:_textInputClient];
// TODO(cbracken) Implement.
return CGRectZero;
}
- (CGRect)caretRectForPosition:(UITextPosition*)position {
// TODO(cbracken) Implement.
return CGRectZero;
}
- (UITextPosition*)closestPositionToPoint:(CGPoint)point {
// TODO(cbracken) Implement.
NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index;
return [FlutterTextPosition positionWithIndex:currentIndex];
}
- (NSArray*)selectionRectsForRange:(UITextRange*)range {
// TODO(cbracken) Implement.
return @[];
}
- (UITextPosition*)closestPositionToPoint:(CGPoint)point withinRange:(UITextRange*)range {
// TODO(cbracken) Implement.
return range.start;
}
- (UITextRange*)characterRangeAtPoint:(CGPoint)point {
// TODO(cbracken) Implement.
NSUInteger currentIndex = ((FlutterTextPosition*)_selectedTextRange.start).index;
return [FlutterTextRange rangeWithNSRange:fml::RangeForCharacterAtIndex(self.text, currentIndex)];
}
- (void)beginFloatingCursorAtPoint:(CGPoint)point {
[_textInputDelegate updateFloatingCursor:FlutterFloatingCursorDragStateStart
withClient:_textInputClient
withPosition:@{@"X" : @(point.x), @"Y" : @(point.y)}];
}
- (void)updateFloatingCursorAtPoint:(CGPoint)point {
[_textInputDelegate updateFloatingCursor:FlutterFloatingCursorDragStateUpdate
withClient:_textInputClient
withPosition:@{@"X" : @(point.x), @"Y" : @(point.y)}];
}
- (void)endFloatingCursor {
[_textInputDelegate updateFloatingCursor:FlutterFloatingCursorDragStateEnd
withClient:_textInputClient
withPosition:@{@"X" : @(0), @"Y" : @(0)}];
}
#pragma mark - UIKeyInput Overrides
- (void)updateEditingState {
NSUInteger selectionBase = ((FlutterTextPosition*)_selectedTextRange.start).index;
NSUInteger selectionExtent = ((FlutterTextPosition*)_selectedTextRange.end).index;
// Empty compositing range is represented by the framework's TextRange.empty.
NSInteger composingBase = -1;
NSInteger composingExtent = -1;
if (self.markedTextRange != nil) {
composingBase = ((FlutterTextPosition*)self.markedTextRange.start).index;
composingExtent = ((FlutterTextPosition*)self.markedTextRange.end).index;
}
NSDictionary* state = @{
@"selectionBase" : @(selectionBase),
@"selectionExtent" : @(selectionExtent),
@"selectionAffinity" : @(_selectionAffinity),
@"selectionIsDirectional" : @(false),
@"composingBase" : @(composingBase),
@"composingExtent" : @(composingExtent),
@"text" : [NSString stringWithString:self.text],
};
if (_textInputClient == 0 && _autofillId != nil) {
[_textInputDelegate updateEditingClient:_textInputClient withState:state withTag:_autofillId];
} else {
[_textInputDelegate updateEditingClient:_textInputClient withState:state];