Repository navigation
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
Have FlutterView report itself as a text editor while a framework text input client is active, and restore Android view focus before window focus only when the IME was visible before the view was hidden. This lets Android apply its native soft input policy on resume without reopening a keyboard that the user explicitly hid. Fixes flutter#52599
60d6724 to
b5e890a
Compare
There was a problem hiding this comment.
Code Review
This pull request modifies FlutterView to track IME visibility and manage text input focus restoration when the view's visibility changes. It overrides onCheckIsTextEditor and introduces helper methods to determine if a framework text input client is active. Unit tests are added to verify focus restoration behavior under various visibility and IME states. There are no review comments, and I have no feedback to provide.
|
/cc @camsim99 from text input triage |
| // FlutterView owns the Android input connection while the actual editor lives in the Flutter | ||
| // tree. Android checks this signal when applying the window's soft input visibility policy. | ||
| @Override | ||
| public boolean onCheckIsTextEditor() { |
There was a problem hiding this comment.
Based on the docs it does look like we should override this. However, just out of curiosity, did this functionally do anything towards fixing the issue this PR addresses?
There was a problem hiding this comment.
Good question. I had tested the complete fix before, but had not isolated this override specifically, so I ran an A/B/A test.
I built two profile APKs from the same Flutter/engine revision and repro app. The embedding source differed only by the onCheckIsTextEditor() override, and I verified the difference in the packaged DEX.
On a Pixel 7 running Android 17 / API 37:
- With the override: the IME remained visible after Home → Recents in 3/3 attempts.
- Without the override: the IME was missing after resume in 3/3 attempts, and the text field had to be tapped again.
- After restoring the override: the IME remained visible in another 3/3 attempts.
So yes, this override functionally contributes to the fix on the tested device. This is consistent with Android using onCheckIsTextEditor() during window-focus handling to identify the focused view as a text editor.
There was a problem hiding this comment.
Thanks for the clarification! SGTM. I actually just approved another PR that overrides the same method in the same way for another fix: #189662. I don't think the PRs are inherently related but just wanted to bring that to your attention in case it lands first.
Are you planning to continue work on this PR? Should we re-open it?
There was a problem hiding this comment.
Yes, I plan to continue working on this. We already have this fix deployed in our production apps.
There was a problem hiding this comment.
I think the only difference between #189662 and this PR is that #189662 also includes inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW in its TextInputPlugin.isTextInputClientActive/isInputConnectionTarget, while this PR additionally includes TextInputType.NONE. Maybe we should just close out the other PR and have this one add inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW to its text input cases.
|
Thank you for your contribution. I'm going to close this PR for now since there are outstanding comments, just to get this off our PR review queue. Please don't hesitate to submit a new PR if you have the time to address the review comments. Thanks! |
|
An existing Git SHA, To re-trigger presubmits after closing or re-opeing a PR, or pushing a HEAD commit (i.e. with |
camsim99
left a comment
There was a problem hiding this comment.
LGTM. Let's get a second review!
Renzo-Olivares
left a comment
There was a problem hiding this comment.
Thank you for the contribution @saibotma! Mostly looks good to me with a few questions.
| && textInputPlugin.isTextInputClientActive(); | ||
| } | ||
|
|
||
| private boolean isImeVisible() { |
There was a problem hiding this comment.
I think we can use the isImeVisible field directly instead of adding this getter since this getter is private anyways.
| // FlutterView owns the Android input connection while the actual editor lives in the Flutter | ||
| // tree. Android checks this signal when applying the window's soft input visibility policy. | ||
| @Override | ||
| public boolean onCheckIsTextEditor() { |
There was a problem hiding this comment.
I think the only difference between #189662 and this PR is that #189662 also includes inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW in its TextInputPlugin.isTextInputClientActive/isInputConnectionTarget, while this PR additionally includes TextInputType.NONE. Maybe we should just close out the other PR and have this one add inputTarget.type == InputTarget.Type.VIRTUAL_DISPLAY_PLATFORM_VIEW to its text input cases.
| viewportMetrics.viewInsetRight = 0; | ||
| viewportMetrics.viewInsetBottom = guessBottomKeyboardInset(insets); | ||
| viewportMetrics.viewInsetLeft = 0; | ||
| isImeVisible = viewportMetrics.viewInsetBottom > 0; |
There was a problem hiding this comment.
We should add a test that exercises this path, currently the added tests in FlutterView target API 30 which misses this path.
| viewportMetrics.viewInsetRight = imeInsets.right; | ||
| viewportMetrics.viewInsetBottom = imeInsets.bottom; // Typically, only bottom is non-zero | ||
| viewportMetrics.viewInsetLeft = imeInsets.left; | ||
| isImeVisible = insets.isVisible(android.view.WindowInsets.Type.ime()); |
There was a problem hiding this comment.
Not super familiar with this code, but is it possible for onApplyWindowInsets to be called after the IME is hidden and before setVisibility has a chance to read isImeVisible causing restoreTextInputFocusOnVisibilityChange to be false when it should be true? or is there a guarantee that won't happen?
| restoreTextInputFocusOnVisibilityChange = false; | ||
| // The text input client may have changed while FlutterView was hidden. | ||
| if (hasActiveFrameworkTextInputClient() && !hasFocus()) { | ||
| requestFocus(); |
There was a problem hiding this comment.
Can this focus request potentially steal the focus from a native element in add2app unintentionally? For example if the FlutterView is hidden, then a native element is focused, would the FlutterView reappearing steal that focus away?
|
This pull request is being closed because it has not been updated in the last 21 days after a request for more information. If you are still working on this, please feel free to reopen it or file a new pull request. Thanks for your contribution. |
|
Looking forward to #52599 getting fixed. I'd be glad to take this on to continue working on this PR if that's helpful. |
|
@hunterwilhelm Help would be very welcome. Don't find a time slot to work on this atm., unfortunately. |
…t is attached (flutter#193074) <!-- Thanks for filing a pull request! Reviewers are typically assigned within a week of filing a request. To learn more about code review, see our documentation on Tree Hygiene: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md --> `FlutterView` never overrides [`View.onCheckIsTextEditor()`](https://developer.android.com/reference/android/view/View#onCheckIsTextEditor()), so it always reports `false`. Android's `InputMethodManager` turns that into the `IS_TEXT_EDITOR` start-input flag ([`InputMethodManager.java#L2945`](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android14-release/core/java/android/view/inputmethod/InputMethodManager.java#2945)), and devices that ship `config_preventImeStartupUnlessTextEditor=true` (default `false` in [`config.xml#L3198`](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android14-release/core/res/res/values/config.xml#3198); set by the low-RAM Android TV overlay on Chromecast with Google TV, Philips/TCL Google TVs) answer every `startInput` without that flag with `NO_EDITOR` and unbind the IME, unless a show is already pending for the window ([`InputMethodManagerService.startInputUncheckedLocked`](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android14-release/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java#2598), [`shouldPreventImeStartupLocked`](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android14-release/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java#2647)). On those devices the sequence for a Flutter `TextField` is: 1. Every Flutter-originated `startInput` returns `NO_EDITOR` and kills the IME service: window focus gain, the `restartInput` in [`TextInputPlugin.setTextInputEditingState`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java#L528), and the `restartInput` in the [IME hide listener](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java#L98-L106). The client records no bind sequence (`mBindSequence=-1`). 2. [`showTextInput`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java#L431-L440) → `showSoftInput` marks a show as requested, so IMMS binds the IME again (logcat shows `GoogleInputMethodService.onCreate()` ~30 ms after the show) and creates a session. 3. IMMS sends the client `onBindMethod` with the new sequence, which the client discards because its own sequence is `-1`: ``` W InputMethodManager: Ignoring onBind: cur seq=-1, given seq=626 ``` The keyboard is drawn (IME `mInputViewStarted=true`) but the app holds no session (`mCurMethod=null`, IME `mInputBinding=null`). 4. With no session, `ViewRootImpl`'s `ImeInputStage` returns `DISPATCH_NOT_HANDLED` for every key, so D-pad events fall through to the view hierarchy, Flutter moves focus, the field detaches, and the keyboard hides. That is the "keyboard disappears on any button" from the issue. This also explains both workarounds reported on the issue: a platform-view `EditText` works because `EditText.onCheckIsTextEditor()` is `true`, and a hot restart heals it (until Back closes the keyboard) because a `startInput` issued while a show is pending bypasses `shouldPreventImeStartupLocked` and records a real sequence. `dumpsys input_method` on a Chromecast 4K (Android 14, Gboard TV 17.3.09) while the keyboard was visible but dead: ``` # IMMS mCurClient=ClientState{... mPid=13034} mCurSeq=627 mCurId=.../LatinIME mHaveConnection=true mBoundToMethod=true mInputShown=true # app client (pid 13034) mBindSequence=-1 mCurImeId=null mCurMethod= null mServedView=io.flutter.embedding.android.FlutterView{...} mCurrentEditorInfo: inputType=0x80091 imeOptions=0x2000002 # IME service mInputBinding=null mInputConnection=null mInputStarted=true mInputViewStarted=true ``` Every `StartInput` history entry has reason `SESSION_CREATED_BY_IME` with a fresh `imeToken`. On a Google TV Streamer (4 GB, flag off, same Gboard build) the same flow shows `mBindSequence == mCurSeq`, `mCurMethod` populated, and reasons `WINDOW_FOCUS_GAIN` / `APP_CALLED_RESTART_INPUT_API` with a stable token. ### Change `FlutterView.onCheckIsTextEditor()` now returns `isAttachedToFlutterEngine() && textInputPlugin.isTextEditor()`, mirroring the guard in [`onCreateInputConnection`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/engine/src/flutter/shell/platform/android/io/flutter/embedding/android/FlutterView.java#L906-L914). The new `TextInputPlugin.isTextEditor()` is `true` when a framework client with an input type other than `TextInputType.none` is attached (the same condition `showTextInput` already uses to decide whether to show the keyboard), or when a virtual-display platform view is the input target (its `InputConnection` is [proxied through `FlutterView`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java#L327-L336)). Hybrid-composition platform views own their `InputConnection`, so they stay `false`. Ordering is already right on the framework side: [`EditableText._openInputConnection`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/packages/flutter/lib/src/widgets/editable_text.dart#L4131) calls `TextInput.attach` (`setClient`) before `setEditingState` and `show`, so the input target is `FRAMEWORK_CLIENT` by the time the flag is read. [`clearTextInputClient`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/engine/src/flutter/shell/platform/android/io/flutter/plugin/editing/TextInputPlugin.java#L578) resets the target, so the flag drops when the field detaches, which matches `EditText` being a text editor for as long as it exists. This is the union of the two earlier attempts at this override: flutter#189662 (`FRAMEWORK_CLIENT || VIRTUAL_DISPLAY_PLATFORM_VIEW`) and flutter#187778 (`FRAMEWORK_CLIENT` with a non-`none` input type), which @Renzo-Olivares suggested combining in flutter#187778 (comment). Both were closed without landing; this PR only carries the `onCheckIsTextEditor` part, not the focus-restore logic from flutter#187778. ### Behavior to call out `IS_TEXT_EDITOR` (`hasEditorFocused()` in [`ImeVisibilityStateComputer.computeState`](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/android14-release/services/core/java/com/android/server/inputmethod/ImeVisibilityStateComputer.java#398)) feeds three IMMS decisions, and this change flips all of them for a `FlutterView` with an attached client: 1. The startup-prevention gate above, which is the bug. 2. `SOFT_INPUT_STATE_UNSPECIFIED` + window focus gain: today IMMS hides the IME (`HIDE_UNSPECIFIED_WINDOW`) because the focused view is not an editor. With this change, regaining window focus while a `TextField` is attached no longer hides the keyboard, same as a native `EditText`. This likely fixes a class of "keyboard closes when a system dialog/popup is dismissed" reports; [flutter#187778 measured](flutter#187778 (comment)) this override alone as the difference for keyboard restore after Home → Recents on a Pixel 7. 3. `SOFT_INPUT_STATE_UNSPECIFIED` + `adjustResize` (or a large layout) + `SOFT_INPUT_IS_FORWARD_NAVIGATION` + text editor: IMMS auto-shows the IME on window focus gain (`SHOW_AUTO_EDITOR_FORWARD_NAV`). `EditText` apps get this today; Flutter apps with an attached client start getting it too. Flutter's app template sets [`windowSoftInputMode="adjustResize"`](https://github.com/flutter/flutter/blob/19946f91c8d9de18a4674460d015229cc0b2534f/packages/flutter_tools/templates/app/android.tmpl/app/src/main/AndroidManifest.xml.tmpl), so this applies to most apps. The flag is computed by the framework from `onCheckIsTextEditor()` regardless of start reason, so it cannot be suppressed for `WINDOW_GAINED_FOCUS` only; flagging it here for reviewers to weigh. Not affected: key routing (`FlutterView.dispatchKeyEvent` is unchanged), `InputConnectionAdaptor`, IME insets sync, and autofill (`notifyViewEntered` already uses `mView`). ### Verification The affected Robolectric classes were run locally against this branch with the `shell/platform/android/test_runner` Gradle configuration (compileSdk 36, Robolectric 4.16, Mockito 5.17.0, embedding dependencies from `tools/androidx/files.json`) without a full engine build: | class | tests | result | |---|---|---| | `io.flutter.embedding.android.FlutterViewTest` | 89 | all pass | | `io.flutter.plugin.editing.TextInputPluginTest` | 117 | all pass | `FlutterViewTest.onCheckIsTextEditor_reflectsAttachedTextInputClient` fails at the assertion after `setClient` with the `FlutterView` override removed and passes with it. The Java files are formatted with google-java-format 1.7, the version pinned in `DEPS`. The same mechanism is what Plezy ships today as an app-side workaround on Android TV: a 1×1 focusable child of `FlutterView` that reports `onCheckIsTextEditor()` from a Dart-side flag, delegates `onCreateInputConnection` to `FlutterView`, and returns `true` from `checkInputConnectionProxy(flutterView)`; D-pad input in `TextField`s works on the affected Chromecast with that in place. This engine change makes the proxy view unnecessary. Fixes flutter#177360 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [flutter/website]: https://github.com/flutter/website [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Camille Simon <[email protected]>
Fixes #52599
On Android, restore FlutterView focus before window focus when a framework text input client was active and the IME was visible before the view was hidden. This lets Android apply its native soft-input policy on resume so the keyboard is already visible instead of animating in later.
If the user explicitly hid the keyboard while the text field remained focused, the IME remains hidden on resume.
Tests:
TextInputPluginTestFlutterViewTestFlutterActivityAndFragmentDelegateTestPre-launch Checklist
///).If you need help, consider asking for advice on the #hackers-new channel on Discord.
If this change needs to override an active code freeze, provide a comment explaining why. The code freeze workflow can be overridden by code reviewers. See pinned issues for any active code freezes with guidance.
Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the
gemini-code-assistbot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.