Skip to content

[Android] Show the keyboard when a focus trigger changes the Entry/Editor font - #39024

Closed
MykhailoDav wants to merge 4 commits into
dotnet:mainfrom
MykhailoDav:fix-38819-keyboard-font-change-on-focus
Closed

MykhailoDav wants to merge 4 commits into
dotnet:mainfrom
MykhailoDav:fix-38819-keyboard-font-change-on-focus

Conversation

@MykhailoDav

@MykhailoDav MykhailoDav commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

On Android, when a trigger (or any handler) changes the font of an Entry/Editor in response to IsFocused becoming true, the gesture that focused the control is not handled like a normal one:

  • the first tap shows no soft keyboard and doesn't place the cursor where the user tapped;
  • a first long press doesn't select the word;
  • activating the Entry with TalkBack doesn't show the keyboard.

Root cause

TextView only finishes handling a tap while its text layout is valid (mLayout != null). That covers movement handling, viewClicked, the choice between the autofill fill dialog and the soft keyboard (showAutofillDialog() / showSoftInput), and Editor.onTouchUpEvent, which places the cursor and shows the insertion handle. The EditText gains focus in the middle of that same ACTION_UP, and MAUI propagates focus synchronously (ViewHandler.OnPlatformViewFocusChange → IsFocused = true). The trigger then runs MapFont → TextView.setTypeface/setTextSize, which call nullLayouts(), so TextView skips all of that.

Two other paths focus the view and then depend on the layout in the same way:

  • a long press focuses it from the long-click callback (Editor.performLongClick → selectCurrentWordAndStartDrag → requestFocus);
  • an accessibility click focuses it inside performAccessibilityAction(ACTION_CLICK), which requests the keyboard only when mLayout != null.

Fix

EntryHandler and EditorHandler now create an internal FontDeferringAppCompatEditText : MauiAppCompatEditText. It overrides OnTouchEvent, PerformLongClick and PerformAccessibilityAction to track when it is inside one of them, and MauiMaterialEditText (used by the Material 3 handlers, already internal) does the same. A font update that TextViewExtensions.UpdateFont receives in that window is stored in a small internal TouchEventFontDeferral and applied as soon as TextView returns. It is still applied in the same call stack, before the next frame. The native handling therefore runs unchanged with a valid layout, and all its decisions stay with TextView: keyboard, fill dialog, discarded/ignored touch-ups. Font updates outside those calls are applied immediately, as before.

Once the deferred font is applied, Android reacts to it as it does to any font change: nullLayouts() → Editor.prepareCursorControllers() dismisses the insertion handle and the selection action mode. I confirmed this on a plain Entry whose font changes 1.5 s after focus.

No public API changes. The overrides live on internal types, CreatePlatformView() still returns MauiAppCompatEditText, and Core builds with -p:PublicApiType=Validate. A custom handler that overrides CreatePlatformView() and returns its own MauiAppCompatEditText doesn't get the deferral.

Tests (Issue38819; every test starts from a fresh, unfocused page)

  • The keyboard appears on the first tap: Entry, Editor.
  • The keyboard appears when the Entry is activated with PerformAccessibilityAction(ACTION_CLICK), the way TalkBack does it.
  • Tapping past the end of the text puts the cursor at the end: Entry, Editor.
  • A first long press selects the word: Entry, Editor.
  • Autofill, API 33+ only. A test-only AutofillService in the HostApp offers a fill dialog for two Entries that carry a custom autofill hint. One Entry has the font trigger and the other doesn't. The test selects the service with adb shell settings/device_config, as Issue34211 does for density, and restores both settings afterwards. It checks that the Entry with the trigger shows the fill dialog, gets autofilled, and shows or suppresses the keyboard exactly like the Entry without it. This is a comparison rather than a fixed expectation because Android suppresses the keyboard under the fill dialog on API 33 but shows it on API 36.

Verification

I ran the gestures of each test through adb at the same coordinates the tests use, one fresh page per test. I didn't run the Appium harness locally.

Emulator Without fix (main) With fix
API 30, Pixel 3 XL (the CI Android lane) 7 of 7 fail 7 of 7 pass (autofill test ignored < 33)
API 36 8 of 8 fail 8 of 8 pass (re-run after moving the overrides to the internal class)

Autofill test by API level:

  • API 33: the previous version of this PR, which re-requested the keyboard, fails because it forces the keyboard over the fill dialog.
  • API 36: main fails because the keyboard doesn't appear with the dialog as it does natively.

Limitations:

  • On CI the autofill test is ignored, because the Android UI test lane runs API 30. It needs an API 33+ device.
  • The Material 3 path has the same change and compiles, but I haven't run it on a device.

Issues Fixed

Fixes #38819

🤖 Generated with Claude Code

…itor font

TextView only requests the soft keyboard on ACTION_UP while its text layout
is valid. The EditText gains focus inside that same event and MAUI updates
IsFocused synchronously, so a trigger on IsFocused that changes
FontAttributes calls setTypeface, which nulls the layout before TextView
reaches the keyboard request. The keyboard then only shows on the second tap.

MauiAppCompatEditText and MauiMaterialEditText now check whether the layout
was invalidated during a touch-up that left the view focused, and request
the keyboard themselves in that case.

Fixes dotnet#38819

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39024

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39024"

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Sep 30, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @@MykhailoDav! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @MykhailoDav! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@kubaflo

kubaflo commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Please revise this approach before merging. The root-cause explanation makes sense, and the fallback may restore the keyboard for the reported case, but it does not preserve the native touch-handling contract.

In ShowSoftInputIfSkippedOnTouchUp, a layout becoming null is treated as evidence that the keyboard should be requested. That does not establish why Android skipped the request:

  • Android also honors discarded/ignored touch-up events and suppresses the IME when showing an autofill dialog. The helper does not preserve those decisions, so the description should not claim it uses the same conditions. It checks that the view is focused, not that this event acquired focus; an already-focused field with selection-driven font changes can also meet the guard.
  • The null-layout guard skips more than keyboard activation: movement handling, viewClicked, and Editor.onTouchUpEvent are also inside it. Calling ShowSoftInput() alone does not restore the normal cursor/insertion-handle behavior.

Please address the reentrant font/layout update without replacing the native keyboard decision with this heuristic. Deferring only the font application that occurs during native touch handling is one approach worth investigating, rather than dispatching every font update asynchronously. The revised approach should also cover cursor placement, selection/drag release, and autofill behavior, not just keyboard visibility after the first tap.

The mismatch with the native implementation is established from source; I have not reproduced a user-visible regression from these adjacent scenarios, so those remain risks to resolve rather than confirmed regressions.

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kubaflo

This comment has been minimized.

@kubaflo

kubaflo commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

/azp run

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 30, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@github-actions

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15520408 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

… keyboard

Address review feedback: the previous fallback only re-requested the soft
keyboard when TextView had skipped it, but a null layout also makes TextView
skip movement handling, viewClicked, Editor.onTouchUpEvent (cursor placement,
insertion handle) and its own autofill/discarded-touch-up decisions.

MauiAppCompatEditText and MauiMaterialEditText now track when they are inside
OnTouchEvent or PerformLongClick (a long press focuses the view from the
long-click callback, not from the touch event). UpdateFont called in that
window is applied right after TextView finishes, so the native handling runs
unchanged with a valid layout. Other font updates are applied immediately as
before.

The UI tests now also cover cursor placement after the first tap and word
selection on the first long press, for both Entry and Editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MauiBot

This comment was marked as outdated.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 30, 2026
@kubaflo

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@MykhailoDav
MykhailoDav requested review from MauiBot and kubaflo October 1, 2026 09:55
kubaflo added a commit that referenced this pull request Oct 1, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

## Summary

Follow-up to #38324. The first production `/review performance` run
successfully published its report, but used flat Markdown instead of the
agreed expandable presentation: [example on
#39024](#39024 (comment)).

- Restore **Performance Review Summary**, the actual PR author/pinned
commit notification, and truthful Scope/Result/Commit badges as the
visible header.
- Put the verdict, coverage and benchmark table inside **Performance
Results**, and static findings, recommendations and next action inside
**Findings & Follow-up**. Both sections are closed by default for
static-only, measured and incomplete reports.
- Pass trusted PR metadata into rendering and validation. Reject flat,
expanded, nested, extra or incorrectly named sections, stray expanded
narrative, mismatched authors/commits and misleading badges. Escape
narrative HTML and block fences so generated prose cannot break the
layout.
- Allow `img.shields.io` in gh-aw's safe-output URL policy without
expanding the agent network allowlist, and regenerate the workflow with
gh-aw v0.86.2.

Measurement, verdict, coverage, permissions and stale-evidence rules are
unchanged. This does not modify the existing production comment; the new
layout takes effect for commands after this fix reaches the default
branch.

## GPT-6.1 Sol alignment

Includes the merged #39036 model migration, retaining `gpt-6.1-sol`,
Responses API configuration and shared pricing for all 14 gh-aw
workflows, including agent and threat-detection execution. Corrects the
stale hosted-model sentence identified in [this review
thread](#39036 (comment)),
while preserving the independent configuration of local runners and
evaluations.

## Validation

- All five existing perf-analysis suites pass; report-component coverage
includes every verdict, both report profiles and 12 malformed-layout
rejection cases. No pipeline/YAML configuration tests were added.
- Replayed the trusted Render stage using production run `36778478869`
evidence and original narrative, without posting a comment. Re-rendered
the measured ABBA report from run `36765284345` with unchanged evidence
and narrative.
- GitHub's Markdown API rendered both reports with exactly two closed
sibling accordions, three visible badges and the managed benchmark table
inside Performance Results. The exact previously published flat report
now fails presentation validation.
- All 14 workflows compile with pinned gh-aw v0.86.2. Inspected all 28
generated agent/detection environments: `gpt-6.1-sol` and `responses`.
Native actionlint passes with the documented baseline exclusions;
PowerShell/JSON parsing and scoped formatting pass.
- **Fresh staged fork canary passed:** [run
36784039109](https://github.com/kubaflo/maui/actions/runs/36784039109),
based on production commit `b509aa2fa89c2c93fe40bfac57729e8ac20d72a5`.
All executed jobs succeeded, report validation is `valid: true` with no
errors, and runtime logs confirm GPT-6.1 Sol/Responses in both agent and
detection. Safe-output processing reports one staged operation with no
failed operations. The report artifact contains the restored layout; no
live performance comment was posted.

The canary differs only in the two workflow files: exact
dedicated-fork/manual-dispatch guards, an existing personal inference
secret, a fixed upstream target and forced staging. Production files are
restored and clean. The known non-fatal staged-mode `safe-outputs-items`
missing-artifact annotation remains; report validation and safe-output
processing succeed.

The upstream Skill Validation check is blocked before evaluating PR
content by the existing `actions/checkout` refusal to run fork code in
`pull_request_target`. This PR does not weaken that guard.

---------
@kubaflo

This comment has been minimized.

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you fix it without modifying the public api files?

@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Performance Review Summary

@MykhailoDav — performance review for commit 9a8a91aad9bd.

Scope Static review Result Coverage incomplete Commit 9a8a91aad9bd


Performance Results

Verdict: 🟢 No performance blocker found; coverage incomplete

The supplied bundle contains no managed run manifest, comparison summary, or measurement table; the selector chose no managed suites and classified the changed Android product paths as static-only. No measured timing or allocation conclusion is available, and the selector's prNumber is 0 rather than the pinned PR number 39024; these limitations do not establish a performance regression or whole-PR clearance.

Coverage

Product files: 4; directly managed-measured: 0; device-required: 0; static-reviewed: 4. Sampled subsets: managed 0, device 0.


Findings & Follow-up

Static hot-path review

No concrete hot-path performance concern was identified in the pinned diff. MauiAppCompatEditText.cs:26-39 and the corresponding MauiMaterialEditText.OnTouchEvent override add depth bookkeeping around each native touch callback, including callbacks with no font change. TouchEventFontDeferral.cs:23-49 uses depth checks and reference assignments, retains only the latest deferred request, and applies it when the outermost callback finishes; the diff introduces no per-callback closure, collection traversal, formatting, or synchronization. Each edited native control receives one helper object at construction, which is a setup allocation rather than a per-touch allocation. TextViewExtensions.UpdateFont adds type dispatch and a deferral check; their runtime cost and any effect on native text layout remain unmeasured.

Recommended next action

no_perf_action_needed

The deterministic baseline's no_perf_action_needed action is limited to the absence of an identified static performance concern; it is not acceptance of a measured tradeoff or clearance of the native paths. The selector supplies neither a managed measurement path nor a selected device scenario, and its requiresDeviceMeasurement=false flag does not establish native coverage. Device measurement required: the supplied evidence does not cover the changed native handler path, so the whole PR cannot receive a clean performance verdict. Android touch dispatch, long-click selection, accessibility activation, deferred font application, and autofill/keyboard behavior remain unmeasured for both AppCompat and Material controls. The added UI tests express intended correctness checks but no execution results are supplied, so correctness benefits, actual callback frequency, and alternatives are unverified. Native coverage and the selector identifier discrepancy require human discussion rather than rerunning unrelated managed benchmarks; this workflow provides no native execution or scheduled follow-up.

Maintainers: comment /review performance to refresh this report.

Automated analysis by the perf-analysis skill.

Address review feedback to avoid public API changes: the OnTouchEvent,
PerformLongClick and PerformAccessibilityAction overrides now live on a new
internal FontDeferringAppCompatEditText that derives from
MauiAppCompatEditText. EntryHandler and EditorHandler create it, and their
CreatePlatformView() signatures still return MauiAppCompatEditText.
MauiMaterialEditText was already internal and keeps its overrides.
MauiAppCompatEditText and PublicAPI.Unshipped.txt are back to their main
versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MykhailoDav

Copy link
Copy Markdown
Contributor Author

Done in ddd64b4. The overrides moved from the public MauiAppCompatEditText to a new internal FontDeferringAppCompatEditText : MauiAppCompatEditText, which EntryHandler and EditorHandler now create. Their CreatePlatformView() signatures are unchanged. MauiMaterialEditText was already internal and keeps its overrides.

MauiAppCompatEditText.cs and PublicAPI.Unshipped.txt are back to their main versions, and Core builds with -p:PublicApiType=Validate with no RS0016/RS0017.

One trade-off: a custom handler that overrides CreatePlatformView() and returns its own MauiAppCompatEditText doesn't get the deferral. If you'd rather have it on the public type, I can move the overrides there in a net11.0 follow-up.

I re-ran the Issue38819 scenarios on an API 36 emulator after the change, and 8 of 8 pass.

@MykhailoDav
MykhailoDav requested a review from kubaflo October 1, 2026 11:34
@kubaflo

This comment has been minimized.

@kubaflo

kubaflo commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

/azp run

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Oct 1, 2026
@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Note

🔍 /review started

AzDO build 15533693 is running for android.

The s/agent-review-in-progress label stays on this PR while the run is active. The final recommendation and outcome labels are posted only after Gate, expert review, and Deep UI tests finish.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@kubaflo

This comment has been minimized.

@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Tests Failure Analysis

@MykhailoDav — test-failure analysis for commit ddd64b4.

Scope CI failures Commit ddd64b4


🧪 CI Analysis — click to expand
📊 maui-pr

No failures found.


🧪 maui-pr-devicetests
  • 🟡 Needs human investigation — Gesture Does Not Leak: PinchGestureRecognizer (Android CoreCLR): Label retained; no equivalent target failure establishes causality; isolate with/without the fix.
  • 🟡 Needs human investigation — ImageWithUndefinedSizeAndWithBackgroundSetRenders (Android CoreCLR, Mono): missing red pixels recur on main, but historical runtime is unspecified; compare each runtime.
  • Insufficient data — those two work items are flagged incomplete without a crash diagnostic; verify completion before attributing their downstream PowerShell failures.

🧪 maui-pr-uitests

🧭 Follow-up — actions and refresh

Next action: Restore task/completion evidence and isolate unresolved failures.

Maintainers: comment /review tests to refresh this report.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review Summary

@MykhailoDav — new AI review results are available based on commit ddd64b4.

Gate Passed Confidence Unknown Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: b9dc0cc2

Test Without Fix (expect FAIL) With Fix (expect PASS)
🖥️ Issue38819 Issue38819 ✅ FAIL — 2701s ✅ PASS — 680s
🔴 Without fix — 🖥️ Issue38819: FAIL ✅ · 2701s

Error-relevant lines (filtered from the build log):

   at Microsoft.Maui.TestCases.Tests._IssuesUITest.NavigateToIssue(String issue) in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/_IssuesUITest.cs:line 54
   at Microsoft.Maui.TestCases.Tests._IssuesUITest.TryToResetTestState() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/_IssuesUITest.cs:line 25
   at Microsoft.Maui.TestCases.Tests.UITest.FixtureSetup() in /_/src/Controls/tests/TestCases.Shared.Tests/UITest.cs:line 579
     at UITest.Appium.NUnit.UITestBase.UITestBaseTearDown() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 159
   at UITest.Appium.NUnit.UITestBase.TestTearDown() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 45
   at InvokeStub_UITestBase.TestTearDown(Object, Object, IntPtr*)
   at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse, String commandToExecute)
   at OpenQA.Selenium.WebDriver.ExecuteAsync(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Appium.MobileBy.FindElements(ISearchContext context)
   at OpenQA.Selenium.Appium.AppiumDriver.FindElements(By by)
   at UITest.Appium.AppiumQuery.FindElements(AppiumApp appiumApp) in /_/src/TestUtils/src/UITest.Appium/AppiumQuery.cs:line 125
   at UITest.Appium.AppiumQueryable.ById(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumQueryable.cs:line 16
   at UITest.Appium.AppiumAndroidQueryable.ById(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumAndroidQueryable.cs:line 17
   at UITest.Appium.AppiumApp.FindElement(String id) in /_/src/TestUtils/src/UITest.Appium/AppiumApp.cs:line 74
   at UITest.Appium.HelperExtensions.FindElement(IApp app, String element) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2831
   at UITest.Appium.HelperExtensions.<>c__DisplayClass56_0.<WaitForElement>g__result|0() in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 825
   at UITest.Appium.HelperExtensions.Wait(Func`1 query, Func`2 satisfactory, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFrequency) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2794
   at UITest.Appium.HelperExtensions.WaitForAtLeastOne(Func`1 query, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFrequency) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 2817
   at UITest.Appium.HelperExtensions.WaitForElement(IApp app, String marked, String timeoutMessage, Nullable`1 timeout, Nullable`1 retryFrequency, Nullable`1 postTimeout) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 826
   at Microsoft.Maui.TestCases.Tests.UtilExtensions.WaitForGoToTestButtonWithRecovery(IApp app, String timeoutMessage) in /_/src/Controls/tests/TestCases.Shared.Tests/UtilExtensions.cs:line 80
     at Microsoft.Maui.TestCases.Tests.Issues.Issue38819.FirstTapPlacesCursorWhenEntryFontChangesOnFocus() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs:line 68
     at Microsoft.Maui.TestCases.Tests.Issues.Issue38819.KeyboardAppearsOnAccessibilityClickWhenEntryFontChangesOnFocus() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs:line 55
     at Microsoft.Maui.TestCases.Tests.Issues.Issue38819.KeyboardAppearsOnFirstTapWhenEditorFontChangesOnFocus() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs:line 43
     at Microsoft.Maui.TestCases.Tests.Issues.Issue38819.KeyboardAppearsOnFirstTapWhenEntryFontChangesOnFocus() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs:line 32
     at Microsoft.Maui.TestCases.Tests.Issues.Issue38819.LongPressSelectsWordWhenEditorFontChangesOnFocus() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs:line 107
     at Microsoft.Maui.TestCases.Tests.Issues.Issue38819.LongPressSelectsWordWhenEntryFontChangesOnFocus() in /_/src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs:line 94
🟢 With fix — 🖥️ Issue38819: PASS ✅ · 680s

(no coded error found; showing last 1200 chars)

> 10/01/2026 13:03:25 FixtureSetup for KeyboardAppearsOnFirstTapWhenEntryFontChangesOnFocus
>>>>> 10/01/2026 13:03:34 KeyboardAppearsOnFirstTapWhenEntryFontChangesOnFocus Stop
  Passed KeyboardAppearsOnFirstTapWhenEntryFontChangesOnFocus [11 s]
>>>>> 10/01/2026 13:03:37 LongPressSelectsWordWhenEditorFontChangesOnFocus Start
>>>>> 10/01/2026 13:03:37 FixtureSetup for LongPressSelectsWordWhenEditorFontChangesOnFocus
>>>>> 10/01/2026 13:03:46 LongPressSelectsWordWhenEditorFontChangesOnFocus Stop
  Passed LongPressSelectsWordWhenEditorFontChangesOnFocus [10 s]
>>>>> 10/01/2026 13:03:47 LongPressSelectsWordWhenEntryFontChangesOnFocus Start
>>>>> 10/01/2026 13:03:47 FixtureSetup for LongPressSelectsWordWhenEntryFontChangesOnFocus
>>>>> 10/01/2026 13:03:56 LongPressSelectsWordWhenEntryFontChangesOnFocus Stop
  Passed LongPressSelectsWordWhenEntryFontChangesOnFocus [10 s]
NUnit Adapter 4.5.0.0: Test execution complete
Results File: /home/vsts/work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue38819.trx
Test Run Successful.
Total tests: 8
     Passed: 7
    Skipped: 1
 Total time: 1.5366 Minutes
>>> TRX_RESULT_FILE: /home/vsts/work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue38819.trx
📁 Fix files reverted (4 files)
  • src/Core/src/Handlers/Editor/EditorHandler.Android.cs
  • src/Core/src/Handlers/Entry/EntryHandler.Android.cs
  • src/Core/src/Platform/Android/Material3Controls/MauiMaterialEditText.cs
  • src/Core/src/Platform/Android/TextViewExtensions.cs

New files (not reverted):

  • src/Core/src/Platform/Android/FontDeferringAppCompatEditText.cs
  • src/Core/src/Platform/Android/TouchEventFontDeferral.cs

📋 Pre-Flight — Context & Validation

PR #39024 Pre-Flight

Context

  • PR: [Android] Show the keyboard when a focus trigger changes the Entry/Editor font
  • Issue: #38819, modifying FontAttributes prevents the keyboard from appearing
  • Platform: Android
  • Materialized review commit: 2ec896fc4b98b978d34b97fe730d2afeb68fa95d
  • Gate merge base: b9dc0cc2
  • Gate: PASSED. The Issue38819 fixture failed without the production fix and passed with it.

The bug occurs when an Entry or Editor gains focus during Android native input handling and an IsFocused trigger synchronously changes its font. TextView.setTypeface/setTextSize invalidates the native text layout before TextView finishes the same touch, long-click, or accessibility-click call. Android then skips cursor placement, word selection, autofill/keyboard selection, and soft-keyboard display.

Existing PR Approach

The PR replaces the standard Entry/Editor platform view with an internal FontDeferringAppCompatEditText, adds equivalent handling to the Material 3 edit text, and wraps OnTouchEvent, PerformLongClick, and PerformAccessibilityAction. TextViewExtensions.UpdateFont detects these views and stores the latest requested font in TouchEventFontDeferral while native handling is active. The deferred font is applied synchronously when the outermost native call returns.

This preserves Android's native input/autofill decision path and covers normal taps, cursor placement, long press, accessibility activation, Entry, Editor, and Material 3. It intentionally does not affect custom handlers that return their own MauiAppCompatEditText.

Direct Diff Inspection

Production changes:

  • src/Core/src/Handlers/Editor/EditorHandler.Android.cs: creates FontDeferringAppCompatEditText.
  • src/Core/src/Handlers/Entry/EntryHandler.Android.cs: creates FontDeferringAppCompatEditText.
  • src/Core/src/Platform/Android/FontDeferringAppCompatEditText.cs: new platform view that brackets touch, long-click, and accessibility calls.
  • src/Core/src/Platform/Android/Material3Controls/MauiMaterialEditText.cs: adds the same bracketing to Material 3.
  • src/Core/src/Platform/Android/TextViewExtensions.cs: defers UpdateFont while native handling is active.
  • src/Core/src/Platform/Android/TouchEventFontDeferral.cs: new depth-aware holder for the latest pending font update.

Test changes:

  • src/Controls/tests/TestCases.HostApp/Issues/Issue38819.cs: Entry/Editor reproduction page.
  • src/Controls/tests/TestCases.HostApp/Platforms/Android/Issue38819AutofillService.cs: API 33+ comparison autofill service.
  • src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38819.cs: eight Android UI tests.

The gate's baseline process reverted four modified production files but left the two newly added production files present. The try-fix safety script may therefore classify the attempt as blocked when .github/.baseline-state.json reports non-empty NewFiles; each attempt must honor that boundary and restore only with EstablishBrokenBaseline.ps1 -Restore.

Bounded Validation

Run only:

pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38819"

This one fixture is both the primary test and regression scope. It covers:

  • first-tap keyboard display for Entry and Editor;
  • accessibility-click keyboard display for Entry;
  • first-tap cursor placement for Entry and Editor;
  • first-long-press word selection for Entry and Editor;
  • native-equivalent autofill/keyboard behavior on API 33+.

The prior gate ran eight tests on API 30: seven passed with the PR fix and the API 33+ autofill test was skipped. Do not rerun gate verification and do not run a full test suite.

Candidate Constraints

Each candidate must use a root-cause mechanism different from the PR's general-purpose font-deferral wrapper and different from any earlier candidate. It gets one implementation/test pass and at most one focused correction/retest. A blocked attempt must be recorded honestly without unsafe edits.


🔬 Code Review — Deep Analysis

Expert PR Evaluation

Verdict

NEEDS_DISCUSSION with low confidence, solely because the required-check set could not be authoritatively classified in the unauthenticated review environment. The trusted Gate result independently passed: the regression tests fail without the fix and pass with it.

Independent Assessment

The submitted Android fix prevents Entry and Editor font updates from invalidating the native TextView layout while Android is still processing touch-up, long-click, or accessibility-click input. FontDeferringAppCompatEditText and MauiMaterialEditText bracket those native event windows, while TouchEventFontDeferral retains the latest requested font and applies it when the outermost event returns.

The approach is mechanically sound:

  • deferral is scoped to the native paths whose remaining work depends on a valid layout;
  • nested/reentrant event handling is balanced by the depth counter;
  • the latest font update wins while an event is active;
  • classic Entry/Editor and Material handler paths are covered;
  • no subscriptions, process-wide mutable state, startup behavior, or public API are introduced; and
  • the added Issue38819 coverage exercises first tap, cursor placement, first long press, accessibility activation, and API 33+ autofill behavior.

Findings

No actionable file:line findings were identified. inline-findings.json contains an empty JSON array.

Prior Review Reconciliation

Earlier error-level feedback concerned a now-removed ShowSoftInputIfSkippedOnTouchUp fallback. Those findings are obsolete because the submitted revision preserves Android's native input path through bounded font deferral rather than attempting to recreate only the keyboard side effect. No prior error-level finding remains applicable to the reviewed HEAD.

Blast Radius and Failure Modes

  • The behavior is per platform-view instance and limited to MAUI's Android Entry/Editor platform-view types.
  • Nested calls defer until the outermost event exits; ordinary updates outside an event remain immediate.
  • Handler disconnect/reconnect adds no lifecycle obligation because the new implementation registers no listeners or callbacks.
  • Custom handlers returning their own MauiAppCompatEditText retain prior behavior, consistently with the submitted scope.
  • Native touch, selection, accessibility, autofill, and keyboard decisions remain owned by TextView.

CI Status

The expert could not authoritatively determine required checks because GitHub CLI authentication was unavailable. Public REST exposed completed checks but not a reliable required-check classification, so the code-review skill requires NEEDS_DISCUSSION rather than LGTM. This is an evidence limitation, not a code finding.

Reviewer Refinement

No reviewer-driven source change is justified. A pr-plus-reviewer candidate should therefore remain byte-for-byte identical to the submitted PR and be recorded as having no patch rather than introducing speculative changes.


🛠️ Try-Fix — Analysis & Comparison

PR #39024 Alternative Fix Candidates

Pre-flight context: ../pre-flight/content.md

Candidate 1 — Posted IME/Selection Refresh

  • Result: Blocked before edits or tests.
  • Mechanism: Apply the font immediately, then post InputMethodManager.RestartInput plus a selection refresh after native handling, rather than deferring the font through an event-depth wrapper.
  • Diff: None.
  • Validation: Not run. The baseline state contained newly added production files, which the try-fix restore contract cannot safely manage.
  • Analysis: This remains an unvalidated idea and may not preserve Android's native autofill/keyboard decision. See ../try-fix-1/content.md.

Candidate 1 restored the baseline successfully (Restored True).

Candidate 2 — Synchronous Native Layout Rebuild

  • Result: Blocked before edits or tests.
  • Mechanism: Apply the font immediately and synchronously rebuild the focused EditText layout at its current dimensions before Android resumes native input handling.
  • Difference: Unlike the PR, this does not defer the font or track native-call depth. Unlike Candidate 1, it does not post an IME/selection repair.
  • Diff: None.
  • Validation: Not run. The baseline state again contained newly added production files, which the try-fix restore contract cannot safely manage.
  • Analysis: This remains unvalidated and would need proof that supported Android APIs can rebuild TextView layout synchronously without re-entrant layout hazards. See ../try-fix-2/content.md.

Candidate 2 restored the baseline successfully (Restored True).

Aggregate Outcome

Two candidates were generated, matching the execution cap. Both were blocked by the same mandatory restoration boundary before implementation, so neither candidate has a tested diff and neither can displace the gate-proven PR fix. No additional candidates or test suites were launched.


🏁 Report — Final Recommendation

✅ Final Recommendation: APPROVE

Winner: pr

The submitted PR is the single winning candidate. It is the only distinct implementation with direct regression evidence, and the expert reviewer found no actionable correctness, lifecycle, API, threading, accessibility, autofill, or native-event-semantics defect.

Comparative Ranking

Rank Candidate Implementation Regression evidence Expert assessment Decision
1 pr Submitted depth-aware font deferral around Android touch, long-click, and accessibility-click handling PASSED trusted Gate: Issue38819 fails without the production fix and passes at submitted HEAD (7 passed, 1 API 33+ skip) No actionable findings Winner
2 pr-plus-reviewer Byte-for-byte identical to pr; reviewer patch is empty Same evidence as pr because there is no code delta No refinement was justified Equivalent behavior, but no improvement over the raw submission
3 try-fix-1 Proposed posted IME restart/selection refresh Not run; blocked before implementation Unproven and may not preserve Android's autofill/keyboard decision path Cannot displace a passing implementation
4 try-fix-2 Proposed synchronous native layout rebuild Not run; blocked before implementation Unproven and risks unsupported/reentrant native layout work Cannot displace a passing implementation

Why pr Wins

The submitted mechanism fixes the root cause rather than recreating selected effects after Android has already skipped native work. Font changes are delayed only while a relevant native event is active, nested calls drain at the outermost boundary, and the latest pending font is applied synchronously before the next frame. This preserves Android's own cursor, selection, keyboard, accessibility, and autofill decisions.

The change is per-view, introduces no static mutable state or event subscriptions, preserves immediate font updates outside the affected event windows, covers both classic and Material Android edit-text paths, and intentionally leaves custom handler platform views unchanged. The targeted UI fixture exercises first tap, cursor placement, first long press, accessibility activation, and autofill comparison.

Reviewer Refinement

The single expert review produced inline-findings.json as []. Because there was no actionable feedback, adding a speculative pr-plus-reviewer change would reduce confidence rather than improve the PR. Its empty reviewer.patch and clean sandbox confirm that it is not a distinct candidate.

Evidence Limits

The expert environment could not authoritatively classify the live GitHub required-check set because GitHub CLI authentication was unavailable. That limitation lowered the standalone code-review skill's confidence, but it did not identify a code defect or a candidate-specific regression. For this requested comparison, the supplied trusted Gate explicitly passed and no blocking expert error or discussion item applies to the implementation.

Final Assessment

Approve the raw submitted fix. The two alternative candidates have neither an implementation nor validation, while the PR has root-cause alignment, focused regression coverage, a passing trusted Gate, and no actionable expert finding.


📱 UI Tests — Editor,Entry,ViewBaseTests

Detected UI test categories: Editor,Entry,ViewBaseTests

❌ Deep UI tests — 321 passed, 1 failed, 6 skipped across 3 categories on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
Editor 88/91 (3 skipped) ✓ —
Entry 115/118 (1 ❌, 2 skipped) —
ViewBaseTests 118/119 (1 skipped) ✓ —
🔍 AI analysis of failures — PR-related vs unrelated

🔍 AI-generated triage (GitHub Copilot CLI) — a heuristic judgement of whether each deep UI test failure is connected to this PR's changes. Verify before relying on it.

Likely PR-related: one or more failures appear connected to this PR's changes.

  • ✗ PR-related — Android Entry interaction (~1 test): EntryClearButtonColorShouldUpdateOnThemeChange taps an Entry whose Android platform view and touch handling are changed by this PR, making the click-path failure plausibly connected despite the stack ending in the Appium helper.

Strongest signal: the failure occurs on Android in the same Entry interaction path modified by the PR.

❌ Entry — 1 failed test
EntryClearButtonColorShouldUpdateOnThemeChange
System.NullReferenceException : Object reference not set to an instance of an object.
at UITest.Appium.HelperExtensions.Click(IUIElement element) in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 445
   at UITest.Appium.HelperExtensions.<>c__DisplayClass2_0.<Tap>b__0() in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 36
   at UITest.Appium.HelperExtensions.<>c__DisplayClass187_0.<RunWithTimeout>b__0() in /_/src/TestUtils/src/UITest.Appium/HelperExtensions.cs:line 3108
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Tas
...

📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)


🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues and removed s/agent-approved AI agent recommends approval - PR fix is correct and optimal s/agent-review-in-progress AI review is currently running for this PR labels Oct 1, 2026
@MykhailoDav
MykhailoDav requested a review from MauiBot October 1, 2026 21:26
@kubaflo

kubaflo commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

For the original #38819 app scenario, I would prefer a small opt-in workaround over replacing the default native text control and adding touch / long-click / accessibility interception for every Android Entry and Editor.

I verified that simply queuing the application's focus-driven font change works with the affected, released MAUI 10.0.110 packages. This recording does not use the framework fix from this PR; both controls remain stock MauiAppCompatEditText.

Remove the synchronous FontAttributes setter from the IsFocused trigger, keep the initial italic font, and attach this helper instead:

entry.FontAttributes = FontAttributes.Italic;
DeferFocusFont(entry);

editor.FontAttributes = FontAttributes.Italic;
DeferFocusFont(editor);

static void DeferFocusFont(InputView input)
{
    input.Focused += UpdateFont;
    input.Unfocused += UpdateFont;

    void UpdateFont(object? sender, FocusEventArgs args)
    {
        if (!input.Dispatcher.Dispatch(() =>
        {
            if (input.Handler is not null)
                input.FontAttributes = input.IsFocused
                    ? FontAttributes.None
                    : FontAttributes.Italic;
        }))
        {
            throw new InvalidOperationException("Unable to dispatch the focus font change.");
        }
    }
}

Dispatcher.Dispatch queues the update until Android finishes handling the gesture. There is no timer or explicit keyboard request. MainThread.BeginInvokeOnMainThread is not equivalent here because it can execute inline on the UI thread.

Before/after proof — Android 14 / API 34, released MAUI 10.0.110, visible touch indicators:

issue38819-workaround-proof-playback.mp4
Control Original synchronous trigger Queued font update
Entry Keyboard requires a second tap Keyboard appears on the first tap
Editor Keyboard requires a second tap Keyboard appears on the first tap

In both workaround scenarios the font still changes from italic to normal, and the first tap places the cursor at the tapped end of the text. I repeated each scenario three times, plus the recorded comparison, checking actual keyboard visibility, UI state, and application logs.

This demonstrates an app-side workaround for the reported scenario, not equivalent coverage for all the paths this PR addresses. TalkBack, autofill, long-press behavior, and Material 3 were not validated here; the Appium harness was not run. Given the scope of the default-control changes, I would consider documenting this workaround before expanding the framework implementation.

@kubaflo

kubaflo commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Thank you for the careful investigation and test coverage. The underlying issue is real, but replacing the default native text controls and adding touch, long-click, and accessibility interception across Android Entry and Editor is a broad framework change for this specific focus-trigger scenario.

The app-side workaround and recording show that the original keyboard issue can be addressed by queuing the font update with Dispatcher.Dispatch, without changing the default handlers. Given this smaller, opt-in alternative, we do not consider the scope and ongoing maintenance/regression risk of this implementation proportionate to the use case.

@kubaflo kubaflo closed this Oct 2, 2026
@MykhailoDav
MykhailoDav deleted the fix-38819-keyboard-font-change-on-focus branch October 2, 2026 12:53
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 2, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-keyboard Keyboard, soft keyboard community ✨ Community Contribution platform/android s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

modifying FontAttributes prevents the keyboard from appearing

3 participants