From e3f23590e636f075e4e443518b7fc8b87c9a13e3 Mon Sep 17 00:00:00 2001 From: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com> Date: Wed, 17 Jun 2020 11:38:03 -0700 Subject: [PATCH] [iOS] handle text plugin negative range (flutter/engine#19068) --- .../ios/framework/Source/FlutterTextInputPlugin.mm | 12 +++++++++++- .../framework/Source/FlutterTextInputPluginTest.m | 13 +++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm index 225b1e51bd..20e36c4595 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm @@ -549,7 +549,17 @@ static NSString* uniqueIdFromDictionary(NSDictionary* dictionary) { toPosition:(UITextPosition*)toPosition { NSUInteger fromIndex = ((FlutterTextPosition*)fromPosition).index; NSUInteger toIndex = ((FlutterTextPosition*)toPosition).index; - return [FlutterTextRange rangeWithNSRange:NSMakeRange(fromIndex, toIndex - fromIndex)]; + 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 { diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m index 678ed1543c..4f20c4d9da 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m @@ -235,4 +235,17 @@ FLUTTER_ASSERT_ARC // Clean up mocks [engine stopMocking]; } + +- (void)testTextRangeFromPositionMatchesUITextViewBehavior { + FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithFrame:CGRectZero]; + FlutterTextPosition* fromPosition = [[FlutterTextPosition alloc] initWithIndex:2]; + FlutterTextPosition* toPosition = [[FlutterTextPosition alloc] initWithIndex:0]; + + FlutterTextRange* flutterRange = (FlutterTextRange*)[inputView textRangeFromPosition:fromPosition + toPosition:toPosition]; + NSRange range = flutterRange.range; + + XCTAssertEqual(range.location, 0); + XCTAssertEqual(range.length, 2); +} @end