Repository navigation
[Android] Fix for Memory leak in MAUI Graphics text drawing and measurement during repeated rendering - #39914
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 39914Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 39914" |
|
Hey there @@Shalini-Ashokan! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect. No interpretable test-group summary was produced. No additional test execution is inferred. Setup did not capture a verified PR head; no commit is claimed as tested. No immutable without-fix baseline was prepared. |
This comment has been minimized.
This comment has been minimized.
Tests Failure Analysis
🧪 CI Analysis — click to expand📊 maui-prNo failures found. 🧪 maui-pr-devicetests
🧪 maui-pr-uitestsMacCatalyst CoreCLR:
🧭 Follow-up — actions and refreshNext action: Compare Windows initialization/brush diagnostics and MacCatalyst snapshots against equivalent target configurations; latest-five target evidence is incomplete.
|
Retain independent text-operation and path-operation Java peer disposal regression tests alongside both production fixes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Resolved the conflict with Preserved both independent regression suites in |
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes #39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…rement during repeated rendering (dotnet#39914) <!-- 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! <!-- !!!!!!! MAIN IS THE ONLY ACTIVE BRANCH. MAKE SURE THIS PR IS TARGETING MAIN. !!!!!!! --> ### Issue Details Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow. Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed. ### Root Cause The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering. ### Description of Change The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint. Validated the behavior in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Issues Fixed Fixes dotnet#39676 ### Output ScreenShot |Before|After| |--|--| | <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/318bff5d-653d-4311-bc60-8c2676a558b8" />| <img width="712" height="1428" alt="image" src="https://github.com/user-attachments/assets/1c922af6-12f7-4330-b703-e08a36898377" />| --------- Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…ths (#40902) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `584853032461f4bf7d3983bf37be87fb4cdb1955` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8.5/10 | ↑ Android allocations drop by exactly 3,999 B per row bound (−20%) in 10 paired benchmark launches.<br>↑ Android screenshots of the benchmark are pixel-identical to `main`.<br>↑ Graphics device tests pass on Android 15 (39/39, including 6 new ones); Core unit tests pass (1,411/1,411).<br>↑ Controls unit tests all pass (7,909) with the leak-test fixes that `main` has since made (#40882).<br>↑ An independent review found two issues; both are fixed and the re-review was clean.<br>↓ The CPU and rebind-time gains aren't significant on the emulator.<br>↓ Not built or run on Windows or run on iOS; Mac Catalyst rendering wasn't checked visually.<br>↓ Controls device tests and UI tests weren't run locally; CI is pending.<br>↓ Each Android canvas keeps up to 4 pooled states with 3 Java paints each. | <!-- /copilot-assessment --> <!-- 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! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change <!-- Enter description of the fix in this section --> On Android, every draw of a `BoxView` or another shape created about 21 Java `Paint`s, 2 Java `Path`s and 3 `PathF`s. A shape's view (`MauiShapeView`) is a `PlatformGraphicsView`, which draws a `ShapeDrawable` through a `ScalingCanvas` around the Android `PlatformCanvas`: - **Canvas states.** A draw resets the canvas state three times: the view sets the canvas's `Canvas` before and after drawing, and resets the `ScalingCanvas`. Each reset disposed the state and created a new one with three new paints, and `PlatformCanvas.ResetState` then replaced those with three more copies of the same defaults. `ShapeDrawable`'s `SaveState` created one more state. - **Paths.** `ShapeDrawable` clips to the shape's path and fills it. For each, `ScalingCanvas` created a scaled copy of the `PathF`, and `PlatformCanvas` converted the copy into a new Android `Path`. - **BoxView.** `PathForBounds` built a new rounded-rectangle path for every draw, with zero-radius curves when there are no rounded corners. A `CollectionView` redraws a row's `BoxView` whenever the row is rebound with a different color. In the [CollectionView scroll benchmark](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark) (on a branch for reference; not part of this PR), drawing it took 13% of the UI thread's CPU samples and about 20% of its allocations. #40881 lists `ShapeDrawable` among the allocations it leaves. #### Changes **Microsoft.Maui.Graphics on Android** - `PlatformCanvas` reuses canvas states. `AbstractCanvas` now releases the states it no longer uses through a new `private protected virtual ReleaseState`, which by default disposes them, as before. `PlatformCanvas` returns them to its `PlatformCanvasStateService`. The service keeps up to 4, and makes a released state a copy of the default or saved state by copying paints with `Paint.Set` instead of creating new ones. Only `PlatformCanvas` itself reuses states: subclasses can reach the states' paints through `CurrentState`, so they still get new states. - `PlatformCanvas.ResetState` no longer replaces the paints of the state it has just created with new copies of the same defaults. - `PlatformCanvas` converts the paths it draws, fills or clips to into one Android `Path` that it reuses. It converts again only for a different path, a changed path or a different scale. To detect changes, `PathF` gets an internal version that `Invalidate()` increments; all of `PathF`'s mutators call it. - `ScalingCanvas` passes its scale to `PlatformCanvas` (through the internal `IScaledPathCanvas`) instead of creating scaled copies of paths. Other canvases and `PlatformCanvas` subclasses still get scaled copies. - `AsAndroidPath` no longer allocates an enumerator. **Core and Controls** - A `BoxView` without rounded corners has a rectangle path. - `ShapeDrawable` draws a path that the shape can reuse while its bounds don't change. This is the internal `IShapeWithReusablePath`, which `BoxView` implements by caching its path for the bounds and corner radius. `ShapeDrawable` doesn't use it when it has a render transform to apply to the path, or on Windows, whose canvas keeps device-dependent geometry with the path. `IShape.PathForBounds` still returns a new path every time. - On Android, `UpdateShape` reuses the view's `ShapeDrawable`, reset to how a new one starts, instead of creating a new one for every change of the shape. There are no public API changes. #### Why it's safe - A reused state is the same as the state that the old code created: - The copy constructor and the in-place copy share one routine. - A reused default state is a copy of a template state that holds the default paints. - Font paints are copied the way `new TextPaint(Paint)` copies them, which leaves the fields that `TextPaint` adds at their defaults. - Shaders are cleared before a state is pooled, so pooled states don't keep bitmaps alive. - Android canvases copy the paths that they record or clip to, so changing the reused Android `Path` doesn't change what was drawn before. The conversion is keyed by a weak reference to the `PathF`, its version and the scale; a conversion that throws is done again. - Converting with the scale produces the same coordinates as converting `AsScaledPath`'s copy. - Nothing changes the reusable `BoxView` path: `ShapeDrawable` only clips to it, fills it and strokes it. On iOS and Mac Catalyst, the canvas now also reuses the `CGPath` that it caches on the path. - `PlatformCanvas` subclasses and `BoxView` subclasses, which can reimplement `IShape.PathForBounds`, keep the previous behavior. #### Behavior changes - Rendering doesn't change. On an Android emulator, screenshots of the benchmark's rows are pixel-identical to `main`, both before and after scrolling. - Memory: an Android `PlatformCanvas` keeps up to 4 released states, with 3 Java paints each, and one Android `Path` until it's disposed. A `BoxView`'s canvas keeps one state more than before. In exchange, drawing no longer creates Java objects. #### Measurements The benchmark scrolls a `CollectionView` of 1,000 items by 100 dp per frame, for 240 frames per pass. Its row template is a `Grid` with a `BoxView` whose `Color` is bound, 7 `Label`s, a `ProgressBar` and a `CheckBox`. Each launch runs a cold pass, a warm-up pass and 5 warm passes; a pass binds 267 rows. Setup: Android 15 emulator (`sdk_gphone64_arm64`, Pixel 6 profile, 4 cores, 4 GB) on an Apple silicon Mac; Release; CoreCLR .NET 12.0.0-alpha.1.26523.103 (SDK 12.0.100-alpha.1.26523.103). `main` bd40bc6 against 5a4448b, the first commit of this PR, in 10 interleaved launch pairs. Values are medians over the launches of each launch's warm-pass median, with the median paired difference and its 95% sign-test interval: | Metric | `main` | This PR | Paired difference [95% CI] | |---|---:|---:|---:| | Allocated per row bound | 20,009 B | 16,010 B | **−3,999 B (−20.0%)** [−3,999 .. −3,999] | | UI-thread CPU time per row | 1,547.8 µs | 1,320.2 µs | −53.9 µs (−3.5%) [−527.0 .. +188.3] | | Rebind time per row | 265.6 µs | 217.3 µs | −7.8 µs (−2.9%) [−130.8 .. +41.5] | | Gen0 GCs per pass | 2 | 2 | 0 | | Cold pass: allocated per row | 21,467 B | 17,482 B | −3,986 B [−4,168 .. −3,981] | | Cold pass: methods JIT-compiled on the UI thread | 54 | 60 | +6 | | Cold pass: methods JIT-compiled on all threads | 4,092 | 3,794 | −290 [−509 .. −193] | - The time intervals include zero: on this emulator, the benchmark can only resolve changes of about 20%. - The second commit only changes how subclasses and font paints are handled. In 2 more launch pairs, it allocated the same 16,010 B per row. - EventPipe sample-profiler traces of 8 warm passes (2,136 rows; one trace each, of `main` and of the final commit): `PlatformGraphicsView.Draw` dropped from 187 to 35 UI-thread samples (13.0% → 3.0%), and from 20.1% to 0.6% of the UI thread's sampled allocations. Within it, `AbstractCanvas.ResetState` dropped from 66 samples to 2, `Paint` constructors from 42 to 0, and `AsAndroidPath` from 28 to 0. - Mac Catalyst (Apple silicon, 18 cores, 2 launch pairs of the final commit): allocations dropped from 29,207 to 28,240 B per row (−967 B). UI-thread CPU time per row was 9.6% and 7.7% lower in the two pairs, but two pairs are too few for an interval. #### Tests New tests: - `BoxViewUnitTests` (Controls): the path without rounded corners is a rectangle; one rounded corner gives a rounded path; the reusable path is kept until the bounds or the corner radius change; a subclass's `PathForBounds` is used. - `ShapeDrawableTests` (Core): the shape's reusable path is drawn; a render transform isn't applied to it. - `PlatformCanvasTests` (Graphics device tests, Android): saving, restoring and resetting states doesn't allocate; reused states start from their prototype (color, alpha, gradient shader and shadow don't carry over); a changed path is converted again; the winding mode follows each fill; `ScalingCanvas` clips to and fills scaled paths, and passes scaled copies to subclasses. Commands, with `.dotnet` linked to the SDK from `global.json`: - `.dotnet/dotnet build src/Core/tests/UnitTests/Core.UnitTests.csproj`, then `artifacts/bin/Core.UnitTests/Debug/net12.0/Microsoft.Maui.UnitTests`: 1,411 passed, 0 failed. - `.dotnet/dotnet build src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj`, then `artifacts/bin/Controls.Core.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.Core.UnitTests`: 7,878 passed, 30 skipped, 31 failed. The 31 are GC leak tests (tests named `*DoesNotLeak*`, `CommandsSubscribedToCanExecuteCollect` and three `TransformGroupTests`). The same 31 fail on `main` bd40bc6's sources, where 7,874 pass without the 4 new tests, and #40882 has since fixed them on `main`. With #40882's test changes applied to this branch: 7,909 passed, 30 skipped, 0 failed. - `pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Graphics -Platform android -DeviceUdid emulator-5600 -DotnetPath .dotnet/dotnet`: 39 passed, 0 failed, on the Android 15 emulator, including the 6 new tests. - `.dotnet/dotnet format whitespace --folder --include <changed files> --verify-no-changes`: no changes. - Builds without errors or warnings (warnings are errors in this repo): Graphics for `net12.0`, `net12.0-android37.0`, `net12.0-ios27.1` and `net12.0-maccatalyst27.0`; Core and Controls for `net12.0` and `net12.0-android37.0`; and Release builds of the benchmark for Android and Mac Catalyst, which validate the PublicAPI files. - Benchmark, from the benchmark branch: `Build-ScrollBenchmark.ps1 -Variant fix -Platform android -MauiRoot <this checkout>`, `Invoke-ScrollBenchmark.ps1 -Variants base,fix -Platform android -Rounds 10 -Serial emulator-5600` and `Compare-ScrollBenchmark.ps1 <results>.jsonl -Baseline base -Candidate fix`. Not run: - Windows: not built or run. The shared code compiles for `net12.0`, Windows-specific code is unchanged, and `ShapeDrawable` doesn't reuse paths on Windows. - iOS: not run. Mac Catalyst: the benchmark ran, but its rendering wasn't checked visually. - Controls device tests (`BoxViewTests`, `ShapeTests`), UI tests, physical Android devices and other Android API levels. ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> No issue filed; this is a performance improvement. Related: #40881 (fewer temporary allocations while scrolling a `CollectionView` on Android; no files in common), and #39909 and #39914 (deterministic disposal of Android Graphics objects, which this keeps). ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…d cached paints (#41316) <!-- 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! ### Target Branch | This PR is for | Initial base | | --- | --- | | New features, API changes, or .NET 12 work (including .NET 12 fixes) | `main` | | .NET 11 servicing fixes | `net11`, for review | | Older servicing, release integration, infrastructure, or documentation | The branch designated for that work | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). For .NET 11 fixes, only a maintainer retargets the approved PR to the active inflight lane and merges it after CI validates that final base. Do not merge individual fixes directly into `net11`; agents must not retarget or merge. ### Description of Change `maui-pr-devicetests` on `main` fails `GraphicsTests.TextOperationsDisposeTemporaryJavaPeers` on Android (Core device tests). Three cases fail with `Assert.Empty() Failure: Collection: [android.text.TextPaint@...]`, and `GetStringSizeWithAlignment` throws `ObjectDisposedException ... Android.Text.TextPaint at Android.Graphics.Paint.Reset()` from `PlatformStringSizeService.GetStringSize`. Cause: #41182 made Android Graphics share lazily created static paints (`PlatformStringSizeService.s_measuringPaint` and `DefaultPaints.Font`). The test snapshots existing peers *before* the first call, so the shared paint created by that first call is counted as a leak. The test's `finally` then disposes it, so the next case uses a disposed cached paint. Fix (test only): run the operation once before taking the snapshot, as `PathOperationsDisposeTemporaryJavaPeers` already does. A per-call leak (#39914) still adds 20 new peers and still fails the test. Evidence: raw log of main build [1708935](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1708935) (Android core device tests); the same failure was seen on the earlier main build. Local causal validation on a freshly provisioned API 33 emulator (`pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform android -IncludeClasses Microsoft.Maui.DeviceTests.GraphicsTests -IncludeMethods TextOperationsDisposeTemporaryJavaPeers -Rebuild`): | Step | Result | |---|---| | Baseline (no warm-up) | Failed 4/4: `Assert.Empty() Failure: Collection: [android.text.TextPaint@…]`, later rows hit disposed-peer `AssertSelf` | | Fix | Passed 4/4 | | Fix reverted | Failed 4/4 (same `TextPaint` assertion) | | Fix restored | Passed 4/4 | ### Issues Fixed Fixes main CI `maui-pr-devicetests` Android Graphics failures (no tracking issue). ### Let AI finish this PR - [ ] **Let the MAUI agent address review feedback and fix remaining issues on this PR.** Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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 from this PR and let us know in a comment if this change resolves your issue. Thank you!
Issue Details
Repeatedly drawing or measuring text with MAUI Graphics on Android causes memory usage to grow.
Extra memory remains after garbage collection because temporary Android text resources are not consistently disposed.
Root Cause
The issue occurs because of missing deterministic disposal of temporary Android graphics objects during repeated text drawing and measurement. Both PlatformCanvas.DrawString implementations created undisposed StaticLayout objects, both GetStringSize overloads left TextPaint objects undisposed, and layout creation left the builder wrapper undisposed. Their cleanup depended on garbage collection and finalization, contributing to memory growth during sustained rendering.
Description of Change
The fix involves using scoped disposal for temporary layouts in both DrawString implementations and for paints and layouts in both GetStringSize overloads, ensuring cleanup even when subsequent operations throw. It also disposes the StaticLayout.Builder wrapper after building the layout. This provides timely resource cleanup while preserving text layout, alignment, and shared canvas-owned paint.
Validated the behavior in the following platforms
Issues Fixed
Fixes #39676
Output ScreenShot