Skip to content

Commit

Permalink
Make the text selection code more defensive (flutter#4291)
Browse files Browse the repository at this point in the history
* Make the text selection code more defensive

* format

* Move validation to a method

* Fix math

* rename
  • Loading branch information
xster authored Nov 2, 2017
1 parent 9a960f8 commit 8d8203c
Showing 1 changed file with 15 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ - (void)setTextInputState:(NSDictionary*)state {

NSInteger selectionBase = [state[@"selectionBase"] intValue];
NSInteger selectionExtent = [state[@"selectionExtent"] intValue];
NSUInteger start = MIN(MAX(0, MIN(selectionBase, selectionExtent)), (NSInteger)self.text.length);
NSUInteger end = MIN(MAX(0, MAX(selectionBase, selectionExtent)), (NSInteger)self.text.length);
NSRange selectedRange = NSMakeRange(start, end - start);
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) {
Expand All @@ -214,6 +214,12 @@ - (void)setTextInputState:(NSDictionary*)state {
}
}

- (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);
}

#pragma mark - UIResponder Overrides

- (BOOL)canBecomeFirstResponder {
Expand Down Expand Up @@ -268,8 +274,10 @@ - (void)replaceRange:(UITextRange*)range withText:(NSString*)text {
selectedRange.length -= intersectionRange.length;
}

[self.text replaceCharactersInRange:replaceRange withString:text];
[self setSelectedTextRange:[FlutterTextRange rangeWithNSRange:selectedRange]
[self.text replaceCharactersInRange:[self clampSelection:replaceRange forText:self.text]
withString:text];
[self setSelectedTextRange:[FlutterTextRange rangeWithNSRange:[self clampSelection:selectedRange
forText:self.text]]
updateEditingState:NO];

[self updateEditingState];
Expand Down Expand Up @@ -309,7 +317,8 @@ - (void)setMarkedText:(NSString*)markedText selectedRange:(NSRange)markedSelecte

NSUInteger selectionLocation = markedSelectedRange.location + markedTextRange.location;
selectedRange = NSMakeRange(selectionLocation, markedSelectedRange.length);
[self setSelectedTextRange:[FlutterTextRange rangeWithNSRange:selectedRange]
[self setSelectedTextRange:[FlutterTextRange rangeWithNSRange:[self clampSelection:selectedRange
forText:self.text]]
updateEditingState:YES];
}

Expand Down

0 comments on commit 8d8203c

Please sign in to comment.