Repository navigation
[XSG] Trimmable Styles - #33561
[XSG] Trimmable Styles#33561
Conversation
bfcfe86 to
01cf3de
Compare
64a71d2 to
eab10eb
Compare
There was a problem hiding this comment.
Pull request overview
This PR implements lazy/trimmable styles for XAML Source Generation, enabling the IL trimmer to remove unused styles and their target types from compiled apps. The feature addresses issue #33156 by deferring style initialization until first application and using string-based type names instead of Type objects for AOT compatibility.
Changes:
- Added new
Style(string assemblyQualifiedTargetTypeName)constructor andLazyInitializationproperty for deferred initialization - Modified
IStyle.TargetTypeto be nullable (Type?) to support trimmed types - Updated source generator to emit lazy style initialization code with type guards
- Extended visitor infrastructure with
StopOnStyle,VisitNodeOnStyle, andIsStylemethods across all visitors (both SourceGen and XamlC)
Reviewed changes
Copilot reviewed 47 out of 47 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| Style.cs | Adds lazy constructor, LazyInitialization property, nullable TargetType resolution, and TargetTypeFullName for trim-safe type comparison |
| IStyle.cs | Changes TargetType to nullable Type? to support trimmed types |
| MergedStyle.cs | Updates to handle nullable TargetType from IStyle |
| ResourceDictionary.cs | Uses TargetTypeFullName instead of TargetType.FullName for adding styles |
| CreateValuesVisitor.cs | Implements TryCreateTrimmableStyle to generate string-based Style constructor |
| SetPropertiesVisitor.cs | Generates LazyInitialization lambda with type guard before style property assignment |
| SetNamescopesAndRegisterNamesVisitor.cs | Adds null checks for nodes not in Variables dictionary (Style content) |
| XamlNode.cs | Implements IsStyleContent logic for skipping Style children during normal traversal |
| XmlName.cs | Adds _StyleContent marker for identifying styles needing lazy initialization |
| All visitor files (20+) | Implements StopOnStyle, VisitNodeOnStyle, and IsStyle interface methods |
| PublicAPI files (7) | Adds new public API entries for Style constructor and LazyInitialization setter |
| Test files (10+) | Updates tests to call InitializeIfNeeded for SourceGen inflator, adds comprehensive lazy style tests |
e7d801f to
d0c0ce4
Compare
|
/rebase |
|
@copilot this PR needs a proper rebase with conflict resolution. open a PR which addresses this issue. make sure it is up to date with the base net11.0 branch. |
|
@simonrozsival I've opened a new pull request, #34011, to work on those changes. Once the pull request is ready, I'll request review from you. |
3536086 to
fefc63a
Compare
…hanges These changes belong in separate PRs: - #33611 (CSS StyleSheet trimming) - #33561 (EventTrigger trimming) - #33160 (HybridWebView trimming) Reverted files to their main branch state, keeping only the [ElementHandler] attribute addition on HybridWebView. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
fefc63a to
59a9982
Compare
This comment has been minimized.
This comment has been minimized.
Only NativeAOT removes the setters behind the generated `is T` check. ILLink keeps them: a trimmed (non-AOT) publish kept the unused style's control and payload, just like an eager style. So MauiXamlTrimmableStyles now defaults to $(PublishAot), and the generator creates eager styles when the property is not set. Generated styles now use `new Style(typeof(T))`. With NativeAOT, typeof(T) keeps only T's type descriptor (316 bytes in the sample app) and the guarded setters are still removed. This drops the Style(string) constructor, Type.GetType and its IL2057 suppression, the nullable TargetType and name-based matching. Implicit-style keys stay strings. Fix Hot Reload replacing the setters of a lazy style that has not been applied yet: its first apply added the stale XAML setters back. The initializer's setters are now discarded in that case; its triggers and behaviors are kept. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
9e047dc to
144cbed
Compare
…spec Setting PublishAot for only some configurations is an app configuration choice, not something this feature needs to document. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
CI on
UI tests haven't run on this PR yet. I'll re-run them once |
|
/review |
This comment has been minimized.
This comment has been minimized.
|
Warning Your |
- Don't assign fields for x:Name inside a Style. Code-behind declares no field for them, so SetFieldsForXNamesVisitor emitted an assignment to a missing field (CS1061) for eager styles. With trimmable styles the generator crashed instead, because the style content is created later inside the lazy initializer. - Roll back setters, triggers and behaviors added by an initializer that throws, so a later apply doesn't duplicate them. - Keep XAML-declared triggers and behaviors ahead of ones added from code, as already done for setters. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved issues can leave null-valued platform setters, apply styles after removal, resolve TargetType in the wrong namespace scope, and emit misleading target-type warnings.
4 open issues
1 file not reviewed
src/Controls/src/SourceGen/xlf/MauiGResources.Designer.cs: Generated file
Review effort: Balanced
| if (string.IsNullOrEmpty(targetType)) | ||
| return null; | ||
|
|
||
| return TypeArgumentsParser.ParseSingle(targetType, namespaceResolver, lineInfo); |
| if (!_targets.TryGetValue(bindable, out _)) | ||
| return; |
| // For Setters, only inline-initialized instances should call TryProvideValue; otherwise | ||
| // the normal property assignments should remain intact. | ||
| var isInlineInitializedSetter = IsInlineInitializedSetter(node, out var isSetter); | ||
| if (!isSetter || isInlineInitializedSetter) | ||
| node.TryProvideValue(Writer, Context, getNodeValue); |
| if (resource is null || !resource.IsStyle(Context)) | ||
| return; |
|
The validation-only PR #40667 surfaced a possible lazy-style visual regression that should not be dismissed as a pre-existing failure:
This is evidence for investigation, not yet proof that lazy styles caused the visual difference: the control is a different source snapshot, and the screenshot attachments have not been compared here. No baseline images were changed. The latest full UI run is still in progress, so this is not an all-clear. |
<!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `cdeafb72937dc746d00866464afe6553904c7d9f` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 7/10 | ↑ Two review rounds addressed: most-specific interface resolution, plus Hot Reload replacement of attribute and default handlers (scoped per app, reinstalled after removal). Each fix has tests that fail without it.<br>↑ Rebased onto the reviewed lower layers. Core 1,279 tests pass under dotnet test and xunit.console, and Controls 7,532 pass. Controls compiles for Android, iOS and MacCatalyst.<br>↑ The new Android compatibility-renderer default activation device test passes 3/3 on an emulator.<br>↓ CI and the full device suites on this head are not yet assessed.<br>↓ Windows paths are compile-only; no Windows device coverage is added. | <!-- /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 --> Follow-up to #28357 targeting **main / .NET 12**. Rebased onto the trimmable-styles merge (#33561), `04d36966ed9d334c056872d83741e973d61f6c55`. #### Stack This PR is **layer 4 of 5** in a stack split from the original single PR for easier review. It is based on #40728, and its own diff covers only the attribute-based resolution: 1. #40721: context-aware handler activation and Hot Reload type matching. 2. #40725: mapper infrastructure that preserves app customizations, the `*ForControls` remap helpers and sealed framework mappings. 3. #40728: lazy Controls mapper remapping on first handler attachment. 4. **This PR**: `[ElementHandler]` attributes on Controls types, removal of the eager default DI registrations, resolution precedence and caches, Hot Reload cache invalidation, Material3 and Apple Shell attribute selection, Windows `PreventGestureBubbling` overrides and the constructor-argument diagnostic. 5. #40715: Copilot guidance for working with handlers and mappers. The sections below describe the combined feature; the activation, mapper and lazy-remap sections are reviewed in layers 1–3. The combined tree is unchanged from the reviewed `5db8263312bf8ea352e8f5a40b04e148c235f4cc` except for the follow-up below. Built-in Controls primarily declare `[ElementHandler]` instead of being rooted by an eager default DI registration table. Controls-specific mapper changes run lazily when handlers attach, while preserving recorded application customizations. Open review items are listed below; this description is not a merge-readiness approval. #### Attribute-based handler resolution `ElementHandlerAttribute` remains internal. The concrete handler type is statically referenced for trimming/AOT. Although the attribute has `Inherited = false`, the factory explicitly walks the base-type hierarchy for fallback. Nested control-specific attributes preserve conditional Android Material3 selection and Windows CollectionView handler selection without unconditionally referencing both alternatives on the active path. `GetHandler(Type)` and `GetHandlerType(Type)` share the resolution order: 1. Exact DI registration. 2. Attribute declared directly on the requested type. 3. The more specific of the nearest registered base class and the nearest inherited attribute. An inherited attribute ranks like the built-in registration its declaring class used to have; a registration on that class or a subclass wins. 4. The most specific registered interface. With Controls defaults on, the `IContentButton`/`IContentView` defaults compete here as interface registrations. 5. Content interface fallbacks: `IContentButton` → `ContentButtonHandler`, then `IContentView` → `ContentViewHandler`. A conditional attribute can declare no handler, for example Apple `ShellItem` when `UseiOSShellHandler` is off; resolution then continues as if it were absent. An exact `AddHandler` still overrides defaults. A registration for `Button` applies to an unannotated `FancyButton : Button`, but registering `IButton` or `View` does not divert it from `ButtonHandler`. Factory registrations remain authoritative even when `GetHandlerType` cannot report an `ImplementationType` and therefore returns `null`. Controls enables an `ElementHandlerDefaultsEnabled` policy per app's handler collection: `TryAddHandler` does not replace a directly declared default or the `IContentButton`/`IContentView` defaults, but still registers custom derived types that only inherit an attribute fallback. Apps without Controls defaults retain normal `TryAddHandler` behavior; `AddHandler` always remains an override. `UseMauiApp` enables the policy before registration callbacks execute regardless of builder-chain order. `AddMauiControlsHandlers` remains a non-obsolete compatibility no-op returning the original collection, without enabling defaults or eagerly remapping controls. #### Cache ownership and invalidation Only attribute and assignable-registration lookups are cached. The complete resolution result and constructor-activation strategy are **not** cached; current registrations and delegates are consulted on every request, and transient requests create fresh handlers. Each factory owns its resolution caches and builds its assignable index from current descriptors, including raw DI registrations. Built-in collection mutations (`Add`, `Insert`, indexer replacement, `Remove`, `RemoveAt`, `Clear`) advance a version. Hot Reload metadata updates, cache clearing, replaced-view callbacks and reset advance a checked generation before views are recreated. Hot Reload registration replacement also changes the collection version. A new cache generation replaces the old dictionaries, preventing concurrent old-generation readers from repopulating new state. Custom collections without mutation tracking do not retain resolution caches. Descriptor lookup stays consistent with indexer/list changes; removing the last registration restores the preceding descriptor for that service type. Cache lookup supports concurrent readers, but collection mutation retains the standard `IServiceCollection` contract and must not run concurrently with resolution. #### Context-aware activation without an activation cache `ElementExtensions.ToHandler` delegates reflection-based construction to the factory. A public parameterless constructor is preferred when present; otherwise `ActivatorUtilities.CreateInstance` resolves dependencies from the current context (including its Android context). Value-type handlers keep default construction. The constructor-presence check avoids using `MissingMethodException` as ordinary control flow, including first activation, without additional cache ownership/invalidation complexity. Direct public `GetHandler` callers retain parameterless-constructor behavior. Custom factories retain their existing exception-based injection fallback. Dependency failures propagate without retrying the entire injection. Factory activation still uses the current service provider/`IMauiContext`, and activated factory types participate in Hot Reload replacement. Historical matched **.NET 11** managed Release microbenchmarks measured warm injected activation at roughly 9 µs with exception-first construction versus 0.10–0.16 µs when missing-constructor exceptions were avoided. Constructor checks were comparable to a factory-owned activation cache; shared-host noise prevents claiming a small difference between those alternatives. These are **not .NET 12 measurements, Android startup claims, or APK-size results**. #### Lazy mapper remapping and main integration Controls `Element.SetHandler` invokes the remap hook before attaching any handler, including compatibility renderers. `ElementHandler.SetVirtualView` also invokes it for direct attachment outside Controls. Each remappable type calls its base hook and owns a blocking one-time initialization action; unrelated controls do not share a global initialization lock. Built-in mapper declarations seal their initial framework mappings. Controls property/command remaps update those mappings underneath recorded app customizations, preserving direct indexer overrides and `AppendToMapping`, `PrependToMapping`, `ModifyMapping`, and `ReplaceMapping` in registration order, including keys that are absent until a lazy remap and keys inherited from chained mappers. See `docs/design/HandlerResolution.md` for the ordering rules. Command-property dependency setup remains in control initialization, independent of handler attachment. The main rebase preserves newer upstream functionality: - `ContentButton` has its own handler attribute, `IContentButton` fallback, sealed mapper and lazy Android ripple remapping. - Switch OnColor remapping uses the lazy hook and customization-preserving prepend behavior on Apple platforms. - Android toolbar drawer-toggle remapping and the current Android/Windows common-mapping scope are retained. - RoundRectangle retains `IShapeWithStroke`; Shell retains the reentrant-navigation unsubscribe fix; handler instrumentation is preserved. - Android ListView/TableView/Frame compatibility attributes retain context-accepting activation through the factory's current-context injection path. - HybridWebView remains a deferred factory registration. Cell attributes retain their platform scopes, and Windows CollectionView feature-switch selection remains conditional. - Controls navigation-transition hooks are installed independently of the removed eager remapping helper. Obsolete eager registration/remapping helpers and Android-context-specific handler interfaces/attributes are removed. Detailed resolution and activation contracts are documented in `docs/design/HandlerResolution.md`. #### Updated Android APK measurements (.NET 12) **Trimmable styles + handlers reduce the plain template's signed NativeAOT APK by 756 KiB (4.64%) compared with neither optimization.** Since styles are already merged into main, this PR's incremental saving over styles alone is **712 KiB**. The 4.64% figure is the combined effect, not a handlers-only measurement. | Framework state | NativeAOT APK (bytes) | Release/CoreCLR APK (bytes) | | --- | ---: | ---: | | Neither styles nor handlers | 16,686,161 | 18,591,480 | | Trimmable styles only | 16,641,105 | 18,591,480 | | Trimmable styles + handlers | 15,912,017 | 18,398,968 | Styles alone save 44 KiB with NativeAOT. Ordinary Release/CoreCLR saves **188 KiB (1.04%)** with handlers; styles alone do not change that APK's size under its default settings. Measured the same unmodified `dotnet new maui -n Template --framework net12.0` source, **without `--sample-content`**, as signed ARM64 APKs. Framework revisions were `f38825f543a18fdcf5ac672b73835e50edd159f6` (neither), `04d36966ed9d334c056872d83741e973d61f6c55` (styles), and `9d2e9cf9b649b647777ec885cd31d1e303e3d49e` (both). The matched local builds use SDK `12.0.100-alpha.1.26523.103`, Android workload `37.99.0-preview.1.358`, and the same MAUI package version `12.0.0-pr29952.local`, with separate feeds/caches. Non-MAUI dependencies, runtime native libraries, signing key, app source and relevant build settings were matched and package hashes checked. NativeAOT uses full trimming and default trimmable styles; ordinary Release uses CoreCLR, partial trimming and default composite R2R. Both retain the SDK's default trimmable typemap and shipped/default profile policy: **no app-trained or custom MIBC**. These are APK file-size measurements, **not startup/JIT/runtime measurements**. No handlers-only arm was measured; the incremental handler saving includes its interaction with merged styles. Local artifact build commands (all **passed**): `bash artifacts/apk-styles-handlers-20261126/build-app.sh baseline aot`, `bash artifacts/apk-styles-handlers-20261126/build-app.sh none aot`, `bash artifacts/apk-styles-handlers-20261126/build-app.sh both aot`, and the same three commands with `release` instead of `aot`. The historical directory name `none` contains the styles-only revision; provenance is checked against `source.sha`, not inferred from directory labels. `python3 artifacts/apk-styles-handlers-20261126/measure.py` — **passed**; verifies all six APKs and records exact source/settings/package/profile identities in `results.json` alongside retained commands, logs and binlogs. These scripts and outputs are local investigation artifacts, not files added by this PR. #### Local validation after the styles rebase (9d2e9cf) The latest English-locale `net12.0` runs passed: - `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Core/tests/UnitTests/Core.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q` — **1,198 passed**. - `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q` — **7,522 passed, 30 skipped**. - `LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj -c Release -p:MauiPlatforms= -m:1 -v:q` — **910 passed, 71 skipped**. The previously reported comma-decimal failures were independently reproduced on clean main and pass with the English locale; they are not this PR's regressions. Existing coverage includes collection mutation/raw registrations, custom unversioned collections, metadata and handler replacement, context/app isolation, dependency errors without retry, constructor preference/value types, first-use exception elimination, recorded mapper customization and ContentButton activation/type lookup. Local Android framework packaging and the six trimmed/NativeAOT template builds above passed. This does **not** establish device/UI behavior or iOS/MacCatalyst/Windows validation for this head; CI attribution and remaining review findings are still being assessed. #### Review follow-up in 714715d - **Handler precedence:** An inherited attribute ranks like the built-in registration its declaring class used to have. The most specific concrete candidate wins, and registered concrete types outrank interfaces. With Controls defaults on, `IContentButton`/`IContentView` defaults compete as interface registrations, and `TryAddHandler` no longer replaces them. - **Mapper customizations:** Lazy Controls remaps now compose underneath app customizations, as if they had run at startup. This covers post-seal assignments to absent keys, child customizations of parent keys that only appear in a later lazy remap, and delegates read before a remap. App-created mapper chains keep capture-at-customization semantics, and wrapping a mapping read from a mapper no longer recurses. - **Apple Shell:** `UseiOSShellHandler` again selects `ShellHandler` or `ShellRenderer`, along with the item, section and content handlers. Conditional attributes may declare no handler, so inactive handlers remain trimmable. - **CI fixes:** Hot Reload handler replacement matches by type name; xunit.console loads the test assembly twice. The Material3 Picker expectation is corrected, there is a blocking `OneTimeInitializationAction` test, and the constructor-argument diagnostic is clearer. Validation: Core unit tests passed 1,223/1,223 under `dotnet test` and xunit.console with `DOTNET_MODIFIABLE_ASSEMBLIES=debug`. Controls unit tests passed 7,530, with 30 skipped. `Controls.Core` compiles for `net12.0-ios27.1` and `net12.0-maccatalyst27.0`. The new Shell resolution device tests passed 2/2 on MacCatalyst via `.github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform maccatalyst -TestFilter "Category=Shell" -IncludeClasses "Microsoft.Maui.DeviceTests.ShellHandlerResolutionTests"`. Android and iOS device runs and CI are not yet assessed on this head, and the APK measurements above predate it. Follow-up in 5db8263: lazy RadioButton (Android) and TabbedPage remaps keep a `PlatformViewFactory` the app sets during startup. Resolution fetches its cache once per request, and the typed `*ForControls` mapper helpers check view and handler types before casting. Follow-up when splitting the stack: - Restores the iOS/MacCatalyst `UpdateCollectionViewAccessibilityTraits` refresh on semantics changes. A rebase in 7fba985 had accidentally dropped it. - `VisualElementMapperTests` trigger the lazy remap before reading global mapper keys. They previously passed only when another test had attached a handler first. - `HandlerResolution.md` gains the lower layers' more precise activation and remapping text. Validation on `c1de79de46`: - Core unit tests: 1,225 passed under `dotnet test` and xunit.console. - Controls unit tests: 7,530 passed, 30 skipped. - The three mapper key-order tests pass when run on their own. - `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1` and `net12.0-maccatalyst27.0`. Review follow-up (rebased; now in cdeafb7): - **Interface resolution:** resolution now picks the most specific matching interface before reporting an ambiguity. A concrete `IContentButton` with `IButton` and `IContentView` registered resolves to `ContentButtonHandler`, or to a registered `IContentButton` handler. Unrelated registrations remain ambiguous. - **Hot Reload:** pending handler replacements also apply to handlers resolved from `[ElementHandler]` or the content interface defaults. These have no collection descriptor, so the replacement is registered for the requested view type the next time it is resolved. - **Lower layers:** this PR was rebased onto #40728. That carries the lower layers' review fixes: injected handlers are never retained as singletons, the mapper fixes, and Label's public appends are back at type initialization. HandlerResolution.md now has a combined "Behavior changes" section with migration guidance. Second review round: - **Hot Reload:** replacements of attribute and default handlers apply only to the collection passed to `RegisterHandlers`. A newly registered collection receives replacements that were already applied to the previous one, and a replacement whose registration was removed is installed again. - **Registration order:** HandlerResolution.md documents the changes. `AddHandler` before `UseMauiApp()` now wins, `AddMauiControlsHandlers()` no longer restores a replaced handler, and `RemoveAll` followed by `TryAddHandler` no longer replaces an attributed default (use `AddHandler`). - **Android device test:** `CompatibilityRendererDefaultActivationTests` covers default activation of the `ListView`, `TableView` and `Frame` renderers with the current Android `Context`. Validation on `cdeafb7293`: - Core unit tests: 1,279 passed under `dotnet test` and xunit.console. - Controls unit tests: 7,532 passed, 30 skipped. - `Controls.Core` compiles for Android, iOS and MacCatalyst. - The Android device test above passed 3/3. Earlier validation on `a0f29fdbde`: - Core unit tests: 1,271 passed under `dotnet test` and xunit.console. - Controls unit tests: 7,531 passed, 30 skipped. - `Controls.Core` compiles for `net12.0-android37.0`, `net12.0-ios27.1` and `net12.0-maccatalyst27.0`. #### Behavior changes - **`AddMauiControlsHandlers()`:** Remains a compatibility no-op. Calling it after registering a custom handler, for example `AddHandler(typeof(Button), typeof(CustomButtonHandler))`, no longer restores `ButtonHandler`. Remove the custom registration instead. - **Custom `IMauiHandlersFactory` implementations:** Not supported. Built-in defaults are resolved from attributes by the built-in factory, not exposed as descriptors in `IMauiHandlersCollection`, so a replacement factory can no longer resolve Controls views. A follow-up will discourage and eventually remove this extension point. `IMauiContext.Handlers` exposes the interface, so this needs a replacement design rather than just `[Obsolete]`. - **Lazy remaps:** Controls mapper remaps run on each control type's first attachment instead of at `UseMauiApp`. App customizations made during startup are preserved as described above. Label keeps its pre-PR timing: its remaps already ran lazily from its static constructor. Windows CollectionView, ListView and TableView device coverage is left to the Windows controls maintainers. ### 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. --> Supports the trimmable handler work started in #28357. <!-- 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>
… remove unused handlers (#40952) <!-- copilot-assessment:v1 --> ### Agent assessment Self-reported assessment, not an independent review. Assessed revision: `104dba74af898b0de2de5ecb752be7e1186d07b1` | Dimension | Assessment | Rationale | |---|---|---| | Change confidence | 8/10 | ↑ Android NativeAOT template app: APK −204,800 B, .so −584,048 B (98% of the unused-styles-deleted ceiling).<br>↑ Emulator screenshot (API 35) pixel-identical to main; no crash or style warning.<br>↑ Style tests: Controls.Core 255/255, Xaml 100/100, SourceGen 964 passed / 0 failed.<br>↓ Only one app (the template) measured; iOS/Mac Catalyst NativeAOT not measured.<br>↓ CI not yet run. | | Diagnosis confidence | 9/10 | ↑ ILC scan DGML on main shows ActivityIndicator type metadata plus the get_CustomAttributes conditional node leading to the handler ctor; with this change ActivityIndicatorHandler has 0 nodes (350 on main).<br>↑ A console NativeAOT probe reproduces the retention with typeof and its removal with a string. | | Evidence fit | 9/10 | ↑ The removed handlers (ActivityIndicator, DatePicker, Picker, Slider, Switch, TimePicker, RefreshView, SwipeItemMenuItem) are exactly the unused style targets in the template's Styles.xaml. | <!-- /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 Trimmable styles (#33561) generate a style whose setters are behind an `is T` check, so NativeAOT can remove them when `T` is never instantiated. The merged version creates the style with `new Style(typeof(T))`, on the assumption that `typeof(T)` only keeps a small type descriptor. In a MAUI app it keeps much more: 1. `typeof(T)` (`ldtoken`) gives `T` reflection metadata in NativeAOT. 2. `MauiHandlersFactory.FindElementHandlerAttributes` calls `GetCustomAttribute<ElementHandlerAttribute>()`, so ILC keeps the `[ElementHandler]` attribute on every type that has metadata. 3. The attribute's constructor parameter and `GetHandlerType()` are annotated `[DynamicallyAccessedMembers(PublicConstructors)]`, so the handler's constructors are kept, and with them its mappers and platform code (both Handler and Handler2 when `UseMaterial3` is unset). So every style target in `Styles.xaml` keeps its handler, even when the app never uses the control. This PR goes back to the earlier design from #33561: generated styles use `new Style("Namespace.Type, Assembly")` for non-generic targets. Generic targets keep `typeof(T)`, because their assembly-qualified names depend on reference assemblies. The Hot Reload fix and the `MauiXamlTrimmableStyles` = `PublishAot` default from the merged version are kept. Changes: - `Style(string assemblyQualifiedTargetTypeName)` constructor, `[EditorBrowsable(Never)]`. - `Style.TargetType` resolves the name lazily with `Type.GetType` (IL2057 suppressed). - Style matching, implicit-style keys (`ResourceDictionary`) and the mismatch warning use the target type's full name. - `IStyle.TargetType` is nullable; `MergedStyle` and `BasedOn` validation handle null. - The source generator emits the assembly-qualified name (`CreateValuesVisitor`, `ISymbolExtensions.GetAssemblyQualifiedName`). - `docs/trimmable-styles-spec.md` explains why `typeof` is not used. #### Size (plain `dotnet new maui`, Release, net12.0-android, android-arm64, `PublishAot=true`) | Build | Signed APK (B) | libTrimProbe.so (B) | |---|---|---| | main (`typeof`) | 16,030,802 | 20,727,560 | | **This PR** | **15,826,002 (−204,800)** | **20,143,512 (−584,048)** | | main with unused styles deleted from Styles.xaml (ceiling) | 15,821,906 | 20,115,936 | The handler constructors of ActivityIndicator, DatePicker, Picker, Slider, Switch, TimePicker, RefreshView and SwipeItemMenuItem are gone from the map. In the ILC scan graph, `ActivityIndicatorHandler` appears 0 times (350 on main) and `ActivityIndicator` has no metadata node. #### Tradeoffs - New hidden public API: `Style(string)` (added to `PublicAPI.Unshipped.txt`). Runtime-inflated XAML, XamlC, Hot Reload and user code keep using the `Type` constructor. - `Type.GetType` on a string needs an IL2057 suppression and costs a one-time lookup on first `TargetType` read. - `Style.TargetType` can be `null`, but only for a generator-created style whose target type was trimmed away (that style can never be applied). Alternatives considered: a generic `Style<T>` still keeps the handler (its `TargetType => typeof(T)` keeps metadata), and keying styles without any `Type` would break the public `Style.TargetType`. Possible longer-term follow-up: make handler discovery independent of type metadata (instead of `GetCustomAttribute` + `DynamicallyAccessedMembers` on `[ElementHandler]`). That would also stop other `typeof(Control)` uses (`DataTemplate`, `x:Type`, `BindableProperty` owner types) from keeping whole handlers. #### Validation - Published the template app with Android NativeAOT using packages built from this branch; sizes above. - Ran it on an API 35 arm64 emulator: cold start OK, screenshot pixel-identical to main, no crash, no "Style TargetType ... is not compatible" warning. - `dotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csproj --filter "FullyQualifiedName~Style"`: passed (255/255). - `dotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj --filter "FullyQualifiedName~Style"`: passed (100/100). - `dotnet test src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj`: passed (964 passed, 0 failed); 4 assertions updated to expect the assembly-qualified name. - Not run: iOS/Mac Catalyst NativeAOT size comparison. ### Issues Fixed Follow-up to #33561. No separate issue filed. ### 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>

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!
Target Branch
mainnet11, for reviewFor .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.This is .NET 12 feature work with new public API, so it now targets
main. It was rebased fromnet11.0ontomainatf38825f543.Description of Change
With NativeAOT and XAML SourceGen, a style no longer keeps its setters, triggers and behaviors (and everything they reference) when the app never creates an instance of the style's
TargetType.This is one of a series of PRs needed for full trimming. It removes style-related roots; it does not make a whole MAUI app fully trimmable on its own.
The feature is on by default only for NativeAOT apps (
MauiXamlTrimmableStylesdefaults to$(PublishAot)). ILLink does not remove code behind type checks: in a trimmed (non-AOT) publish of the sample below, the unused style's control and payload survived exactly as with an eager style. Other apps would get the behavior changes and no size benefit, so they keep eager styles. Their generated code differs frommainonly in that implicit styles are registered under a string key; behavior is the same.Generated code
With trimmable styles enabled, a style whose
TargetTypeis known at compile time is generated as:Tis never instantiated, NativeAOT folds__target is Ttofalseand removes the body. Keep this shape; a negative early return would not be removed. No helper method,NoInliningorGC.KeepAliveis emitted.typeof(T)keeps only the type's identity. In the sample app, an unused target kept just its 316-byte type descriptor, and its setters were still removed. So the style keeps usingStyle(Type); no new constructor or reflection is needed.Type.FullNameformat, with+for nested types) instead ofAddFactory(typeof(T), …), so noType.FullNamelookup runs at startup. Constructed generic targets keeptypeof(T)keys, because their runtime names include assembly-qualified type arguments.TypeLoadExceptioninMaui37888Tests.TargetTypevalues such as{x:Static}create the style eagerly, as before. A missing or unresolvableTargetTypereports MAUIG1001.MarkDeferredStyleContentVisitor, marks the content of each style.XamlNode.Acceptthen skips only that content, so the style's own properties, diagnostics and Hot Reload registration are still generated in the normal pass. InlineBasedOnstyles get their own initializer.Runtime behavior
Style.LazyInitialization { internal get; set; }(Func<Style, BindableObject, bool>,EditorBrowsable(Never)), intended for the source generator.Setters,TriggersandBehaviors. XAML-declared setters stay ahead of setters added from code. On later applies, the initializer is called with anullstyle and only checks the target type.TargetType. A mismatched element gets nothing, and the mismatch is logged through the element's logger, then the app's logger, thenTrace. Mismatched targets are not tracked, soUnApplyignores them.Behavior differences and opt-out
With trimmable styles enabled:
Style.Setters,TriggersandBehaviorsare empty until the style is first applied to a compatible element.Styleis set explicitly (StaticResource,DynamicResource, a binding or code); implicit and class styles are already filtered by type.StaticResourcevalues inside setters are resolved on first apply, not at page load.MAUIX2024 (warning) reports a same-file
{StaticResource}style whoseTargetTypedoesn't match the element. MAUIX2020 was already taken onmain.MauiXamlTrimmableStylesdefaults to$(PublishAot). It can be set globally or per file:See
docs/trimmable-styles-spec.md.Rebase onto
mainStyle.ReplaceSettersstays, and Hot Reload patches for implicit styles use the string keys (this.Remove("Microsoft.Maui.Controls.Label")).GetStyleTargetTypeExpressionnow reuses the PR's target-type resolution.Review feedback addressed
Style(string)constructor was a C# display name, not a CLR assembly-qualified name. That constructor is gone; styles are identified withtypeof(T).Gh2064is reported again.Maui32879Tests,SetterCompiledConvertersandSimplifyOnPlatformfailed the earlier gate. They are now unchanged frommainand pass.Validation
Run on
144cbed9ce(macOS arm64, SDK12.0.100-alpha.1.26523.103,LC_ALL=en_US.UTF-8). Each build passed-p:IncludeAndroidTargetFrameworks=false -p:IncludeIosTargetFrameworks=false -p:IncludeMacCatalystTargetFrameworks=false -p:IncludeMacOSTargetFrameworks=false -p:IncludeWindowsTargetFrameworks=false.dotnet build src/Controls/tests/SourceGen.UnitTests/SourceGen.UnitTests.csproj, thenDOTNET_MODIFIABLE_ASSEMBLIES=debug dotnet test artifacts/bin/SourceGen.UnitTests/Debug/net12.0/Microsoft.Maui.Controls.SourceGen.UnitTests.dlldotnet test src/Controls/tests/Core.UnitTests/Controls.Core.UnitTests.csprojdotnet test src/Controls/tests/Xaml.UnitTests/Controls.Xaml.UnitTests.csproj(setsMauiXamlTrimmableStyles=true, so its SourceGen fixtures use lazy styles)dotnet msbuild -getProperty:MauiXamlTrimmableStyleson a project importingMicrosoft.Maui.Controls.Common.targets''withoutPublishAot,truewith-p:PublishAot=true,falsewith an explicit overridenpx cspell --config ./eng/automation/cspell/cSpell.json "docs/**/*.md"git diff --checkThe new
LazyStyleKeepsSettersReplacedBeforeInitializationtest failed before the Hot Reload fix (3 setters instead of 1, and a removed setter was still applied).Trimming check. A console app references this branch's
Microsoft.Maui.Controlsbuild and has three styles: an implicit style for a control it creates, one for a control it never creates, and an{x:Static}-typed style as an eager baseline. Symbols for the unused control and its setter's payload type in the NativeAOT map file (dotnet publish -c Release -r osx-arm64,PublishAot=true):MauiXamlTrimmableStyles=trueMauiXamlTrimmableStyles=falseThe used style is applied in both cases. With ILLink (
PublishTrimmed=true,TrimMode=full, no AOT), the unused control's.cctorand accessors and the payload type all survived, the same as for the eager baseline. This is a small sample, not a full MAUI app.Not yet validated:
PublishAot.Issues Fixed
Contributes to #33156 as part of the full-trimming work; this PR alone is not the complete solution.