Skip to content

Commit 4542a58

Browse files
committed
[iOS] Take the text input connection back when the platform reopens it
iOS takes first responder away from the FlutterTextInputView while system UI that handles text itself is up -- most notably the AutoFill sheets such as "Hide My Email" -- and gives it back once that UI is dismissed, at which point it inserts the text the user picked. That resignation is reported to the framework as TextInputClient.onConnectionClosed, which is unrecoverable: EditableText unfocuses the field and TextInput drops _currentConnection, so the text arriving afterwards is discarded by the early return in TextInput._handleTextInputInvocation. The keyboard stays up and the engine keeps the same client id the whole time, but the field stays empty. Traced on a physical device, the resignation and the text insertion are seconds apart and the application is still active when the resignation is reported, so the report cannot be suppressed or deferred on a timer. Make it recoverable instead: when the view regains first responder for the same client it reported closed, it tells the framework, which takes that same connection back and refocuses the field through the existing TextInputClient.onFocusReceived. Reusing the connection keeps the client id the platform is holding valid, and the message travels on the channel that carries the editing state updates, so the connection is restored before the inserted text arrives. Fixes flutter#157495
1 parent 9ead586 commit 4542a58

7 files changed

Lines changed: 271 additions & 0 deletions

File tree

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine.mm‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1294,6 +1294,15 @@ - (void)flutterTextInputView:(FlutterTextInputView*)textInputView
12941294
arguments:@[ @(client) ]];
12951295
}
12961296

1297+
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
1298+
didReopenFirstResponderWithTextInputClient:(int)client {
1299+
// The platform gave text input focus back to a client whose connection was
1300+
// reported closed, so the framework can take that connection back instead of
1301+
// dropping the text that is about to arrive.
1302+
[self.textInputChannel invokeMethod:@"TextInputClient.onConnectionReopened"
1303+
arguments:@[ @(client) ]];
1304+
}
1305+
12971306
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
12981307
didResignFirstResponderWithTextInputClient:(int)client {
12991308
// When flutter text input view resign first responder, send a message to

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ typedef NS_ENUM(NSInteger, FlutterFloatingCursorDragState) {
6565
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView removeTextPlaceholder:(int)client;
6666
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
6767
didResignFirstResponderWithTextInputClient:(int)client;
68+
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
69+
didReopenFirstResponderWithTextInputClient:(int)client;
6870
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView
6971
willDismissEditMenuWithTextInputClient:(int)client;
7072
- (void)flutterTextInputView:(FlutterTextInputView*)textInputView

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,9 @@ @implementation FlutterTextInputView {
826826
CGPoint _floatingCursorOffset;
827827
bool _enableInteractiveSelection;
828828
UITextInteraction* _textInteraction API_AVAILABLE(ios(13.0));
829+
// The text input client this view last reported a closed connection for, or 0.
830+
// See -becomeFirstResponder.
831+
int _clientWithClosedConnection;
829832
}
830833

831834
@synthesize tokenizer = _tokenizer;
@@ -837,6 +840,7 @@ - (instancetype)initWithOwner:(FlutterTextInputPlugin*)textInputPlugin {
837840
_textInputClient = 0;
838841
_selectionAffinity = kTextAffinityUpstream;
839842
_preventCursorDismissWhenResignFirstResponder = NO;
843+
_clientWithClosedConnection = 0;
840844

841845
// UITextInput
842846
_text = [[NSMutableString alloc] init];
@@ -1180,6 +1184,7 @@ - (BOOL)respondsToSelector:(SEL)selector {
11801184
}
11811185

11821186
- (void)setTextInputClient:(int)client {
1187+
_clientWithClosedConnection = 0;
11831188
_textInputClient = client;
11841189
_hasPlaceholder = NO;
11851190
}
@@ -1352,13 +1357,37 @@ - (BOOL)resignFirstResponder {
13521357
BOOL success = [super resignFirstResponder];
13531358
if (success) {
13541359
if (!_preventCursorDismissWhenResignFirstResponder) {
1360+
_clientWithClosedConnection = _textInputClient;
13551361
[self.textInputDelegate flutterTextInputView:self
13561362
didResignFirstResponderWithTextInputClient:_textInputClient];
13571363
}
13581364
}
13591365
return success;
13601366
}
13611367

1368+
- (BOOL)becomeFirstResponder {
1369+
BOOL success = [super becomeFirstResponder];
1370+
if (success && _textInputClient != 0 && _clientWithClosedConnection == _textInputClient) {
1371+
// iOS takes first responder away from this view while system UI that handles
1372+
// text itself is up -- most notably the AutoFill sheets ("Hide My Email",
1373+
// password AutoFill) -- and gives it back once that UI is dismissed, at
1374+
// which point it inserts the text the user picked.
1375+
//
1376+
// The resignation was reported to the framework as a closed connection,
1377+
// which unfocused the text field and detached it, so the text would be
1378+
// discarded on arrival. Now that the same client has focus again, tell the
1379+
// framework to take the connection back. This message is sent on the same
1380+
// channel as the editing state updates that follow it, so the connection is
1381+
// restored before the inserted text arrives.
1382+
//
1383+
// See https://github.com/flutter/flutter/issues/157495.
1384+
_clientWithClosedConnection = 0;
1385+
[self.textInputDelegate flutterTextInputView:self
1386+
didReopenFirstResponderWithTextInputClient:_textInputClient];
1387+
}
1388+
return success;
1389+
}
1390+
13621391
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
13631392
if (action == @selector(paste:)) {
13641393
// Forbid pasting images, memojis, or other non-string content.

‎engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.mm‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3064,6 +3064,80 @@ - (void)testAutoFillDoesNotTriggerOnShowAndHideKeyboard {
30643064
[self commitAutofillContextAndVerify];
30653065
}
30663066

3067+
#pragma mark - Connection reopening - Tests
3068+
3069+
- (FlutterTextInputView*)focusedInputViewWithClient:(int)client {
3070+
FlutterTextInputView* inputView = [[FlutterTextInputView alloc] initWithOwner:textInputPlugin];
3071+
[UIApplication.sharedApplication.keyWindow addSubview:inputView];
3072+
[inputView setTextInputClient:client];
3073+
[inputView reloadInputViews];
3074+
XCTAssertTrue([inputView becomeFirstResponder]);
3075+
XCTAssertTrue(inputView.isFirstResponder);
3076+
return inputView;
3077+
}
3078+
3079+
// Regression test for https://github.com/flutter/flutter/issues/157495.
3080+
//
3081+
// iOS takes first responder away while an AutoFill sheet such as "Hide My
3082+
// Email" is up and gives it back when the sheet is dismissed, then inserts the
3083+
// text the user picked. The framework has torn the connection down by then, so
3084+
// it has to be told to take it back before that text arrives.
3085+
- (void)testRegainingFirstResponderReopensTheConnection {
3086+
FlutterTextInputView* inputView = [self focusedInputViewWithClient:123];
3087+
3088+
XCTAssertTrue([inputView resignFirstResponder]);
3089+
OCMVerify([engine flutterTextInputView:inputView didResignFirstResponderWithTextInputClient:123]);
3090+
3091+
XCTAssertTrue([inputView becomeFirstResponder]);
3092+
OCMVerify([engine flutterTextInputView:inputView didReopenFirstResponderWithTextInputClient:123]);
3093+
3094+
[inputView removeFromSuperview];
3095+
}
3096+
3097+
- (void)testBecomingFirstResponderWithoutAPriorResignDoesNotReopen {
3098+
FlutterTextInputView* inputView = [self focusedInputViewWithClient:123];
3099+
3100+
OCMVerify(never(), [engine flutterTextInputView:inputView
3101+
didReopenFirstResponderWithTextInputClient:123]);
3102+
3103+
[inputView removeFromSuperview];
3104+
}
3105+
3106+
- (void)testTheConnectionIsOnlyReopenedOnce {
3107+
FlutterTextInputView* inputView = [self focusedInputViewWithClient:123];
3108+
3109+
XCTAssertTrue([inputView resignFirstResponder]);
3110+
XCTAssertTrue([inputView becomeFirstResponder]);
3111+
OCMVerify(times(1), [engine flutterTextInputView:inputView
3112+
didReopenFirstResponderWithTextInputClient:123]);
3113+
3114+
// Losing and regaining focus again without a new resign report must not
3115+
// reopen a connection the framework never closed.
3116+
[inputView resignFirstResponder];
3117+
[inputView becomeFirstResponder];
3118+
OCMVerify(times(2), [engine flutterTextInputView:inputView
3119+
didReopenFirstResponderWithTextInputClient:123]);
3120+
3121+
[inputView removeFromSuperview];
3122+
}
3123+
3124+
// A new client means the framework attached a fresh connection, so an earlier
3125+
// closed-connection report is stale and must not be reopened.
3126+
- (void)testANewClientDoesNotReopenTheOldConnection {
3127+
FlutterTextInputView* inputView = [self focusedInputViewWithClient:123];
3128+
3129+
XCTAssertTrue([inputView resignFirstResponder]);
3130+
[inputView setTextInputClient:456];
3131+
XCTAssertTrue([inputView becomeFirstResponder]);
3132+
3133+
OCMVerify(never(), [engine flutterTextInputView:inputView
3134+
didReopenFirstResponderWithTextInputClient:456]);
3135+
OCMVerify(never(), [engine flutterTextInputView:inputView
3136+
didReopenFirstResponderWithTextInputClient:123]);
3137+
3138+
[inputView removeFromSuperview];
3139+
}
3140+
30673141
#pragma mark - Accessibility - Tests
30683142

30693143
- (void)testUITextInputAccessibilityNotHiddenWhenKeyboardIsShownAndHidden {

‎packages/flutter/lib/src/services/text_input.dart‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2212,6 +2212,25 @@ class TextInput {
22122212
case 'TextInputClient.scribbleInteractionFinished':
22132213
_scribbleInProgress = false;
22142214
return;
2215+
case 'TextInputClient.onConnectionReopened':
2216+
// The platform gave text input focus back to a client whose connection
2217+
// it had already reported as closed, which happens on iOS when system
2218+
// UI that handles text itself -- an AutoFill sheet such as "Hide My
2219+
// Email" -- is dismissed. Take the same connection back instead of
2220+
// attaching a new one, so the text the platform is about to deliver
2221+
// still carries a client id this end recognizes.
2222+
// See https://github.com/flutter/flutter/issues/157495.
2223+
final args = methodCall.arguments as List<dynamic>;
2224+
final clientId = args[0] as int;
2225+
final TextInputConnection? closed = _lastConnection;
2226+
if (_currentConnection == null && closed != null && closed._id == clientId) {
2227+
_currentConnection = closed;
2228+
if (!closed._client.onFocusReceived()) {
2229+
// The client is gone or refused focus, so leave it detached.
2230+
_currentConnection = null;
2231+
}
2232+
}
2233+
return;
22152234
case 'TextInputClient.onFocusReceived':
22162235
final args = methodCall.arguments as List<dynamic>;
22172236
final clientId = args[0] as int;

‎packages/flutter/lib/src/widgets/editable_text.dart‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2560,6 +2560,11 @@ class EditableTextState extends State<EditableText>
25602560
TextInputConnection? _textInputConnection;
25612561
bool get _hasInputConnection => _textInputConnection?.attached ?? false;
25622562

2563+
// The connection the platform last reported closed, kept only so that
2564+
// [onFocusReceived] can take it back if the platform reattaches it. See
2565+
// [connectionClosed].
2566+
TextInputConnection? _closedConnection;
2567+
25632568
TextSelectionOverlay? _selectionOverlay;
25642569
ScrollNotificationObserverState? _scrollNotificationObserver;
25652570
({TextEditingValue value, Rect selectionBounds})? _dataWhenToolbarShowScheduled;
@@ -4143,6 +4148,7 @@ class EditableTextState extends State<EditableText>
41434148
// _needsAutofill changes to false from true, the platform needs to be
41444149
// notified to exclude this field from the autofill context. So we need to
41454150
// provide the autofillId.
4151+
_closedConnection = null;
41464152
_textInputConnection = _needsAutofill && currentAutofillScope != null
41474153
? currentAutofillScope!.attach(this, _effectiveAutofillClient.textInputConfiguration)
41484154
: TextInput.attach(this, _effectiveAutofillClient.textInputConfiguration);
@@ -4229,6 +4235,14 @@ class EditableTextState extends State<EditableText>
42294235
@override
42304236
bool onFocusReceived() {
42314237
if (mounted && !_hasFocus && widget.focusNode.canRequestFocus) {
4238+
// If the platform reattached the connection it had reported as closed,
4239+
// take it back rather than letting _openInputConnection attach a new one,
4240+
// so the client id the platform is using keeps matching this end.
4241+
final TextInputConnection? closed = _closedConnection;
4242+
if (_textInputConnection == null && (closed?.attached ?? false)) {
4243+
_textInputConnection = closed;
4244+
}
4245+
_closedConnection = null;
42324246
widget.focusNode.requestFocus();
42334247
return true;
42344248
}
@@ -4239,6 +4253,7 @@ class EditableTextState extends State<EditableText>
42394253
void connectionClosed() {
42404254
if (_hasInputConnection) {
42414255
_textInputConnection!.connectionClosedReceived();
4256+
_closedConnection = _textInputConnection;
42424257
_textInputConnection = null;
42434258
_lastKnownRemoteTextEditingValue = null;
42444259
widget.focusNode.unfocus();

‎packages/flutter/test/widgets/editable_text_test.dart‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1996,6 +1996,129 @@ void main() {
19961996
expect(focusNode.hasFocus, isTrue);
19971997
});
19981998

1999+
// Regression test for https://github.com/flutter/flutter/issues/157495.
2000+
//
2001+
// On iOS the AutoFill sheets ("Hide My Email", password AutoFill) take first
2002+
// responder away from the text input view and give it back when dismissed,
2003+
// then insert the text the user picked. The resignation is reported as a
2004+
// closed connection, so the platform asks for that same connection back
2005+
// before it delivers the text.
2006+
testWidgets('takes the connection back when the platform reopens it', (
2007+
WidgetTester tester,
2008+
) async {
2009+
Future<void> send(String method, List<dynamic> args) async {
2010+
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
2011+
SystemChannels.textInput.name,
2012+
SystemChannels.textInput.codec.encodeMethodCall(MethodCall(method, args)),
2013+
(_) {},
2014+
);
2015+
}
2016+
2017+
await tester.pumpWidget(
2018+
MediaQuery(
2019+
data: const MediaQueryData(),
2020+
child: Directionality(
2021+
textDirection: TextDirection.ltr,
2022+
child: FocusScope(
2023+
node: focusScopeNode,
2024+
autofocus: true,
2025+
child: EditableText(
2026+
backgroundCursorColor: Colors.grey,
2027+
controller: controller,
2028+
focusNode: focusNode,
2029+
style: textStyle,
2030+
autofocus: true,
2031+
cursorColor: cursorColor,
2032+
autofillHints: const <String>[AutofillHints.email],
2033+
),
2034+
),
2035+
),
2036+
),
2037+
);
2038+
expect(focusNode.hasFocus, isTrue);
2039+
2040+
final clientId =
2041+
(tester.testTextInput.log
2042+
.lastWhere((MethodCall call) => call.method == 'TextInput.setClient')
2043+
.arguments
2044+
as List<dynamic>)[0]
2045+
as int;
2046+
2047+
await send('TextInputClient.onConnectionClosed', <dynamic>[clientId]);
2048+
await tester.pump();
2049+
expect(focusNode.hasFocus, isFalse);
2050+
2051+
await send('TextInputClient.onConnectionReopened', <dynamic>[clientId]);
2052+
await tester.pump();
2053+
expect(focusNode.hasFocus, isTrue);
2054+
2055+
// The platform delivers the picked text using the client id it still holds.
2056+
await send('TextInputClient.updateEditingState', <dynamic>[
2057+
clientId,
2058+
const TextEditingValue(
2059+
2060+
selection: TextSelection.collapsed(offset: 17),
2061+
).toJSON(),
2062+
]);
2063+
await tester.pump();
2064+
expect(controller.text, '[email protected]');
2065+
});
2066+
2067+
testWidgets('ignores a reopen for a connection that is not the last one', (
2068+
WidgetTester tester,
2069+
) async {
2070+
Future<void> send(String method, List<dynamic> args) async {
2071+
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
2072+
SystemChannels.textInput.name,
2073+
SystemChannels.textInput.codec.encodeMethodCall(MethodCall(method, args)),
2074+
(_) {},
2075+
);
2076+
}
2077+
2078+
await tester.pumpWidget(
2079+
MediaQuery(
2080+
data: const MediaQueryData(),
2081+
child: Directionality(
2082+
textDirection: TextDirection.ltr,
2083+
child: FocusScope(
2084+
node: focusScopeNode,
2085+
autofocus: true,
2086+
child: EditableText(
2087+
backgroundCursorColor: Colors.grey,
2088+
controller: controller,
2089+
focusNode: focusNode,
2090+
style: textStyle,
2091+
autofocus: true,
2092+
cursorColor: cursorColor,
2093+
),
2094+
),
2095+
),
2096+
),
2097+
);
2098+
2099+
final clientId =
2100+
(tester.testTextInput.log
2101+
.lastWhere((MethodCall call) => call.method == 'TextInput.setClient')
2102+
.arguments
2103+
as List<dynamic>)[0]
2104+
as int;
2105+
2106+
await send('TextInputClient.onConnectionClosed', <dynamic>[clientId]);
2107+
await tester.pump();
2108+
expect(focusNode.hasFocus, isFalse);
2109+
2110+
await send('TextInputClient.onConnectionReopened', <dynamic>[clientId + 99]);
2111+
await tester.pump();
2112+
expect(focusNode.hasFocus, isFalse);
2113+
2114+
await send('TextInputClient.updateEditingState', <dynamic>[
2115+
clientId,
2116+
const TextEditingValue(text: 'discarded').toJSON(),
2117+
]);
2118+
await tester.pump();
2119+
expect(controller.text, isEmpty);
2120+
});
2121+
19992122
testWidgets('can re-acquire focus in Offstage', (WidgetTester tester) async {
20002123
final editableTextKey = GlobalKey<EditableTextState>();
20012124
await tester.pumpWidget(

0 commit comments

Comments
 (0)