From 367520bce46720a992858b8bbf9f0c74b38eb738 Mon Sep 17 00:00:00 2001 From: redth Date: Wed, 26 Aug 2026 16:09:40 -0400 Subject: [PATCH 1/7] Add platform-neutral handler contracts for external platform backends Every per-control handler interface in Microsoft.Maui.Core declares PlatformView through a `using PlatformView = ...` alias that resolves to a different native type per target framework. That bakes MAUI's own native types into the compiled contract, so a platform backend shipping outside dotnet/maui - which owns its own native types - cannot implement them: - CS0738 on a platform TFM, where the alias is one of MAUI's native types. - CS9333 (plus CS8766, an error under TreatWarningsAsErrors) on the neutral net11.0 TFM, where the alias is a non-nullable System.Object. Both were reproduced against Microsoft.Maui.Core 11.0.0-preview.7.26406.9. Adds three additive interfaces that carry the same strong typing without the alias: - Microsoft.Maui.IElementHandler - Microsoft.Maui.IViewHandler - Microsoft.Maui.ILayoutHandler ElementHandler<,> and ViewHandler<,> implement the matching interface. Their existing public VirtualView/PlatformView members already have the right signatures, so no handler - in the box or out of it - needed a new member, and all 46 aliased handlers are covered at once. TPlatformView is covariant, so `IViewHandler` matches any label handler from any backend. ILayoutHandler carries the child-management behavior that only ILayoutHandler had. It is deliberately unrelated to ILayoutHandler by inheritance: relating them would force member hiding and break explicit interface implementations. LayoutHandler declares both. Nothing was moved, renamed or removed. Binary compatibility was verified by compiling derived and explicit-interface-implementation handlers against 11.0.0-preview.7.26406.9 and loading them against this build. Adds src/Core/tests/ExternalBackend, a separate assembly that is absent from Core's InternalsVisibleTo and builds with TreatWarningsAsErrors, so everything it compiles is provably public and warning-free for an external consumer. Tests cover contract satisfaction, covariance, handler registration, mapper composition off ViewHandler.ViewMapper, Controls' Layout command routing into an external layout handler, and that the aliased interfaces are unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Microsoft.Maui-mac.slnf | 1 + Microsoft.Maui-windows.slnf | 1 + Microsoft.Maui.sln | 7 + docs/design/ExternalPlatformBackends.md | 286 ++++++++++++++++++ .../src/Handlers/Element/ElementHandlerOfT.cs | 2 +- src/Core/src/Handlers/IElementHandlerOfT.cs | 59 ++++ src/Core/src/Handlers/IViewHandlerOfT.cs | 49 +++ .../src/Handlers/Layout/ILayoutHandlerOfT.cs | 64 ++++ src/Core/src/Handlers/Layout/LayoutHandler.cs | 2 +- src/Core/src/Handlers/View/ViewHandlerOfT.cs | 2 +- .../net-android/PublicAPI.Unshipped.txt | 12 + .../PublicAPI/net-ios/PublicAPI.Unshipped.txt | 12 + .../net-maccatalyst/PublicAPI.Unshipped.txt | 12 + .../net-tizen/PublicAPI.Unshipped.txt | 12 + .../net-windows/PublicAPI.Unshipped.txt | 12 + .../src/PublicAPI/net/PublicAPI.Unshipped.txt | 12 + .../netstandard/PublicAPI.Unshipped.txt | 12 + .../netstandard2.0/PublicAPI.Unshipped.txt | 12 + .../Core.ExternalBackend.csproj | 24 ++ .../ExternalBackendContracts.cs | 85 ++++++ .../tests/ExternalBackend/FakeHandlers.cs | 96 ++++++ .../ExternalBackend/FakeLayoutHandler.cs | 148 +++++++++ .../tests/ExternalBackend/FakeNativeViews.cs | 43 +++ .../tests/UnitTests/Core.UnitTests.csproj | 1 + .../Handlers/ExternalPlatformBackendTests.cs | 268 ++++++++++++++++ 25 files changed, 1231 insertions(+), 3 deletions(-) create mode 100644 docs/design/ExternalPlatformBackends.md create mode 100644 src/Core/src/Handlers/IElementHandlerOfT.cs create mode 100644 src/Core/src/Handlers/IViewHandlerOfT.cs create mode 100644 src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs create mode 100644 src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj create mode 100644 src/Core/tests/ExternalBackend/ExternalBackendContracts.cs create mode 100644 src/Core/tests/ExternalBackend/FakeHandlers.cs create mode 100644 src/Core/tests/ExternalBackend/FakeLayoutHandler.cs create mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.cs create mode 100644 src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs diff --git a/Microsoft.Maui-mac.slnf b/Microsoft.Maui-mac.slnf index e36ffafb00a2..cdff7648a4b1 100644 --- a/Microsoft.Maui-mac.slnf +++ b/Microsoft.Maui-mac.slnf @@ -39,6 +39,7 @@ "src\\Core\\tests\\Benchmarks\\Core.Benchmarks.csproj", "src\\Core\\tests\\DeviceTests.Shared\\Core.DeviceTests.Shared.csproj", "src\\Core\\tests\\DeviceTests\\Core.DeviceTests.csproj", + "src\\Core\\tests\\ExternalBackend\\Core.ExternalBackend.csproj", "src\\Core\\tests\\UnitTests\\Core.UnitTests.csproj", "src\\Essentials\\samples\\Sample.Server.WebAuthenticator\\Essentials.Sample.Server.WebAuthenticator.csproj", "src\\Essentials\\samples\\Samples.Server.Passkeys\\Essentials.Samples.Server.Passkeys.csproj", diff --git a/Microsoft.Maui-windows.slnf b/Microsoft.Maui-windows.slnf index b84a284cadf6..70b68b6581e9 100644 --- a/Microsoft.Maui-windows.slnf +++ b/Microsoft.Maui-windows.slnf @@ -46,6 +46,7 @@ "src\\Core\\tests\\Benchmarks\\Core.Benchmarks.csproj", "src\\Core\\tests\\DeviceTests.Shared\\Core.DeviceTests.Shared.csproj", "src\\Core\\tests\\DeviceTests\\Core.DeviceTests.csproj", + "src\\Core\\tests\\ExternalBackend\\Core.ExternalBackend.csproj", "src\\Core\\tests\\UnitTests\\Core.UnitTests.csproj", "src\\Essentials\\samples\\Sample.Server.WebAuthenticator\\Essentials.Sample.Server.WebAuthenticator.csproj", "src\\Essentials\\samples\\Samples.Server.Passkeys\\Essentials.Samples.Server.Passkeys.csproj", diff --git a/Microsoft.Maui.sln b/Microsoft.Maui.sln index fbebde122aa3..f4660399df9c 100644 --- a/Microsoft.Maui.sln +++ b/Microsoft.Maui.sln @@ -37,6 +37,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtils", "src\TestUtils\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.UnitTests", "src\Core\tests\UnitTests\Core.UnitTests.csproj", "{92644F6F-5946-48FC-A21A-A3D6EE24E8B3}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.ExternalBackend", "src\Core\tests\ExternalBackend\Core.ExternalBackend.csproj", "{7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E8AD265B-3C67-4640-AC58-A522F9FB3361}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{C564DDD6-DE79-45CD-88EA-3F690481572A}" @@ -298,6 +300,10 @@ Global {92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Debug|Any CPU.Build.0 = Debug|Any CPU {92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Release|Any CPU.ActiveCfg = Release|Any CPU {92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Release|Any CPU.Build.0 = Release|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Release|Any CPU.Build.0 = Release|Any CPU {F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Debug|Any CPU.Build.0 = Debug|Any CPU {F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -660,6 +666,7 @@ Global {DAAC2822-63B6-4DE0-83AE-04873CD2F364} = {72397ADB-40A8-4B8E-8E08-2DBE2803C845} {FBB3270F-1924-4A72-845E-A6DF39C402F6} = {7AC28763-9C68-4BF9-A1BA-25CBFFD2D15C} {92644F6F-5946-48FC-A21A-A3D6EE24E8B3} = {C564DDD6-DE79-45CD-88EA-3F690481572A} + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4} = {C564DDD6-DE79-45CD-88EA-3F690481572A} {E8AD265B-3C67-4640-AC58-A522F9FB3361} = {09C264E9-E3F3-4586-9151-DCBB1F6DA7AB} {C564DDD6-DE79-45CD-88EA-3F690481572A} = {09C264E9-E3F3-4586-9151-DCBB1F6DA7AB} {50C758FE-4E10-409A-94F5-A75480960864} = {459BF674-83CB-46F6-881F-A2D2117DBF4D} diff --git a/docs/design/ExternalPlatformBackends.md b/docs/design/ExternalPlatformBackends.md new file mode 100644 index 000000000000..d18e85fdd2b1 --- /dev/null +++ b/docs/design/ExternalPlatformBackends.md @@ -0,0 +1,286 @@ +# External platform backends and handler contracts + +This document describes the platform-neutral handler contracts added in .NET 11, why they exist, and +how an out-of-tree platform backend adopts them. + +## The problem + +Almost every per-control handler interface in `Microsoft.Maui.Core` declares `PlatformView` through a +compile-time type alias that changes per target framework. `ILabelHandler` is representative: + +```csharp +#if __IOS__ || MACCATALYST +using PlatformView = Microsoft.Maui.Platform.MauiLabel; +#elif MONOANDROID +using PlatformView = AndroidX.AppCompat.Widget.AppCompatTextView; +#elif WINDOWS +using PlatformView = Microsoft.UI.Xaml.Controls.TextBlock; +#elif TIZEN +using PlatformView = Tizen.UIExtensions.NUI.Label; +#elif (NETSTANDARD || !PLATFORM) || (NET6_0_OR_GREATER && !IOS && !TIZEN) +using PlatformView = System.Object; +#endif + +public partial interface ILabelHandler : IViewHandler +{ + new ILabel VirtualView { get; } + new PlatformView PlatformView { get; } +} +``` + +The alias is baked into the compiled contract. That means the interface can only ever be implemented by +a handler whose native view type is *exactly* the type .NET MAUI picked for that target framework. + +An external backend — a platform implementation that ships outside dotnet/maui, such as a standalone +Tizen backend — owns its own native types, so it cannot satisfy the contract: + +| Target framework the backend consumes | Compiled `PlatformView` type | Error | +| --- | --- | --- | +| A platform TFM MAUI ships (`-android`, `-ios`, `-windows`, historically `-tizen`) | MAUI's own native type | `CS0738` — the implementing member's return type does not match | +| The platform-neutral TFM (`net11.0`) | `System.Object` (non-nullable) | `CS9333` — "type must be `object` to match implemented member", plus `CS8766` because `ViewHandler.PlatformView` is `object?` | + +Both failures were reproduced against the shipped +`Microsoft.Maui.Core 11.0.0-preview.7.26406.9` package with an ordinary `net11.0` class library: + +```csharp +public class MyNativeLabel { } + +public class MyLabelHandler : ViewHandler, ILabelHandler +{ + public MyLabelHandler() : base(LabelHandler.Mapper) { } + protected override MyNativeLabel CreatePlatformView() => new(); + ILabel ILabelHandler.VirtualView => VirtualView; + MyNativeLabel ILabelHandler.PlatformView => PlatformView; // CS9333 +} +``` + +```text +error CS9333: 'MyLabelHandler.PlatformView': type must be 'object' to match implemented member 'ILabelHandler.PlatformView' +error CS8766: Nullability of reference types in return type of 'object? ViewHandler.PlatformView.get' + doesn't match implicitly implemented member 'object ILabelHandler.PlatformView.get' +``` + +`CS8766` is a warning, but external backends that build with `TreatWarningsAsErrors` (the .NET MAUI +default under `ContinuousIntegrationBuild`) see it as an error. + +46 handler interfaces in `Microsoft.Maui.Core` use the alias pattern. `ILabelHandler`, +`IContentViewHandler`, `ILayoutHandler` and `IWindowHandler` are the ones a minimal backend hits first, +because they are needed for the application → window → page → content → layout → label vertical slice. + +`ILayoutHandler` is the most damaging of the four, because it is the only one of them that carries real +behavior — `Add`, `Remove`, `Clear`, `Insert`, `Update` and `UpdateZIndex` — rather than just typed +accessors. + +## The solution + +Three new public interfaces. Nothing was moved, renamed, or removed, so the change is source and +binary compatible. + +### `IElementHandler` + +```csharp +namespace Microsoft.Maui; + +public interface IElementHandler : IElementHandler + where TVirtualView : IElement + where TPlatformView : class +{ + new TVirtualView VirtualView { get; } + new TPlatformView PlatformView { get; } +} +``` + +### `IViewHandler` + +```csharp +namespace Microsoft.Maui; + +public interface IViewHandler + : IElementHandler, IViewHandler + where TVirtualView : IView + where TPlatformView : class +{ + new TVirtualView VirtualView { get; } +} +``` + +### `ILayoutHandler` + +```csharp +namespace Microsoft.Maui; + +public interface ILayoutHandler : IViewHandler + where TPlatformView : class +{ + void Add(IView view); + void Remove(IView view); + void Clear(); + void Insert(int index, IView view); + void Update(int index, IView view); + void UpdateZIndex(IView view); +} +``` + +### Why this is the smallest change that covers everything + +`ElementHandler` and `ViewHandler` now +implement the matching new interface. Their existing public `VirtualView` and `PlatformView` members +already have exactly the right signatures, so **no handler anywhere needed a new member** — in the box +or out of it. Every one of the 46 aliased handlers, and every third-party handler derived from +`ViewHandler<,>`, satisfies the new contracts automatically. + +`TPlatformView` is covariant, so `object` acts as the platform-neutral wildcard: + +```csharp +// Matches the in-box LabelHandler on every platform AND any external backend's label handler. +if (label.Handler is IViewHandler labelHandler) +{ + ILabel virtualView = labelHandler.VirtualView; + object nativeLabel = labelHandler.PlatformView; +} +``` + +`ILayoutHandler` is intentionally **not** related to the existing `ILayoutHandler` by +inheritance. Relating them would force `ILayoutHandler` to hide the inherited members, which would break +any type that implements `Add`/`Remove`/... as *explicit* interface implementations. Keeping them +unrelated means a handler that implements those members as ordinary public methods — as the in-box +`LayoutHandler` does — satisfies both interfaces at once. `LayoutHandler` therefore declares both. + +### What deliberately did not change + +* No member was moved off `ILabelHandler`, `IContentViewHandler`, `ILayoutHandler` or `IWindowHandler`. +* No aliased interface gained or lost a base interface. +* Property mappers, command mappers, handler registration and `ToHandler`/`ToPlatform` are untouched. +* Existing casts such as `Handler as ILayoutHandler` in the Controls compatibility layer keep working + against in-box handlers exactly as before. + +### Consuming the contracts + +Because the neutral contracts come from `ElementHandler<,>`/`ViewHandler<,>`, any handler derived from +those bases — including handlers compiled against an older .NET MAUI — satisfies +`IElementHandler` / `IViewHandler` automatically. + +`ILayoutHandler` is the exception: it declares members, so a type only satisfies it if it +lists the interface. In-box `LayoutHandler` does. A pre-existing third-party type that implements +`ILayoutHandler` with *explicit* interface implementations does not. Framework and consumer code that +needs to cover both should test for both: + +```csharp +if (handler is ILayoutHandler neutral) +{ + neutral.Add(view); +} +else if (handler is ILayoutHandler legacy) +{ + legacy.Add(view); +} +``` + +Binary compatibility was verified by compiling handlers against +`Microsoft.Maui.Core 11.0.0-preview.7.26406.9` and loading them against a build that includes this +change: derived handlers, explicit-interface-implementation handlers, and all existing `is`/cast +relationships continue to work with no `TypeLoadException`. + +## Adopting this from an external backend + +An external backend derives from the public generic handler base classes and stops trying to implement +the aliased interfaces. + +```csharp +using Microsoft.Maui; +using Microsoft.Maui.Handlers; + +// The backend's own native type. MAUI knows nothing about it. +public class MyNativeLabel +{ + public string? Text { get; set; } +} + +public class MyLabelHandler : ViewHandler +{ + public static IPropertyMapper Mapper = + new PropertyMapper(ViewMapper) + { + [nameof(ILabel.Text)] = MapText, + }; + + public MyLabelHandler() : base(Mapper) { } + + protected override MyNativeLabel CreatePlatformView() => new MyNativeLabel(); + + public static void MapText(MyLabelHandler handler, ILabel label) => + handler.PlatformView.Text = label.Text; +} + +// No extra members required — this already holds: +IViewHandler typed = new MyLabelHandler(); +IViewHandler neutral = typed; +``` + +A layout handler additionally declares `ILayoutHandler` so that consumers can drive child +management without knowing the backend: + +```csharp +public class MyLayoutHandler : ViewHandler, ILayoutHandler +{ + public static CommandMapper CommandMapper = + new CommandMapper(ViewCommandMapper) + { + // Referencing ILayoutHandler for its member *names* is always allowed; + // only implementing it is blocked. These are the keys Controls' Layout raises. + [nameof(ILayoutHandler.Add)] = MapAdd, + [nameof(ILayoutHandler.Remove)] = MapRemove, + [nameof(ILayoutHandler.Clear)] = MapClear, + [nameof(ILayoutHandler.Insert)] = MapInsert, + [nameof(ILayoutHandler.Update)] = MapUpdate, + [nameof(ILayoutHandler.UpdateZIndex)] = MapUpdateZIndex, + }; + + public void Add(IView view) { /* ... */ } + public void Remove(IView view) { /* ... */ } + public void Clear() { /* ... */ } + public void Insert(int index, IView view) { /* ... */ } + public void Update(int index, IView view) { /* ... */ } + public void UpdateZIndex(IView view) { /* ... */ } + + // ... +} +``` + +Handler registration is unchanged: + +```csharp +builder.ConfigureMauiHandlers(handlers => +{ + handlers.AddHandler(); + handlers.AddHandler(); +}); +``` + +## Tests + +`src/Core/tests/ExternalBackend` is a separate assembly +(`Microsoft.Maui.Core.ExternalBackend.TestAssembly`) that is deliberately **not** in Core's +`InternalsVisibleTo` list and builds with `TreatWarningsAsErrors`. It contains fake native view types and +handlers for label, content view, layout and window, so everything it compiles is provably public API and +provably warning-free for an external consumer. + +`src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs` exercises it: contract satisfaction, +covariance, handler registration, property-mapper composition off `ViewHandler.ViewMapper`, Controls' +`Layout` command routing reaching an external layout handler, and backward-compatibility assertions that +the aliased interfaces are unchanged. + +## Follow-up coverage + +The generic contracts cover every handler automatically, so no per-control follow-up is required for +recognition or typed access. Two areas remain for a fully self-contained external backend and are +tracked separately: + +1. **Behavior-carrying handler interfaces.** `ILayoutHandler` is the only one of the four required + interfaces with behavior, and it now has a neutral counterpart. Other interfaces that carry behavior + rather than just accessors (for example `IScrollViewHandler`) can get the same treatment on demand, + following the `ILayoutHandler` pattern. +2. **Handler infrastructure that is still `internal` or TFM-locked.** `ViewHandler.ContainerView`'s + setter, `MauiContext.AddSpecific`, `LifecycleEventServiceExtensions.InvokeLifecycleEvents`, + `Microsoft.Maui.Handlers.LayoutExtensions` and `HandlerNotFoundException` are not reachable from an + external assembly. Those are separate from the interface-shape problem this document addresses. diff --git a/src/Core/src/Handlers/Element/ElementHandlerOfT.cs b/src/Core/src/Handlers/Element/ElementHandlerOfT.cs index 13597639cd23..42aafd755dba 100644 --- a/src/Core/src/Handlers/Element/ElementHandlerOfT.cs +++ b/src/Core/src/Handlers/Element/ElementHandlerOfT.cs @@ -2,7 +2,7 @@ namespace Microsoft.Maui.Handlers { - public abstract partial class ElementHandler : ElementHandler, IElementHandler + public abstract partial class ElementHandler : ElementHandler, IElementHandler, IElementHandler where TVirtualView : class, IElement where TPlatformView : class { diff --git a/src/Core/src/Handlers/IElementHandlerOfT.cs b/src/Core/src/Handlers/IElementHandlerOfT.cs new file mode 100644 index 000000000000..0cefae9a2655 --- /dev/null +++ b/src/Core/src/Handlers/IElementHandlerOfT.cs @@ -0,0 +1,59 @@ +namespace Microsoft.Maui +{ + /// + /// Defines a strongly typed, platform-neutral element handler contract. + /// + /// The cross-platform (virtual view) type this handler manages. + /// The native type this handler creates. + /// + /// + /// The per-control handler interfaces such as declare + /// PlatformView using a using PlatformView = ... alias that resolves to a different + /// native type for every target framework. That makes them impossible to implement from an + /// external platform backend whose native types are not the ones .NET MAUI ships in the box: + /// the compiler reports CS0738 (or CS9333 on the platform-neutral target framework) + /// because the implementing member's return type does not match the alias exactly. + /// + /// + /// This interface has no such alias. Both type parameters are covariant, so a handler can be + /// matched platform-neutrally by testing for IElementHandler<IWindow, object> + /// regardless of which native type it actually creates. + /// + /// + /// implements this interface, + /// so any handler derived from it — in the box or in an external backend — satisfies the contract + /// without writing any additional members. + /// + /// + /// + /// + /// { + /// public MyWindowHandler() : base(WindowHandler.Mapper) { } + /// protected override MyNativeWindow CreatePlatformElement() => new MyNativeWindow(); + /// } + /// + /// // Consumers match it platform-neutrally: + /// if (window.Handler is IElementHandler windowHandler) + /// { + /// IWindow virtualView = windowHandler.VirtualView; + /// object nativeWindow = windowHandler.PlatformView; + /// } + /// ]]> + /// + public interface IElementHandler : IElementHandler + where TVirtualView : IElement + where TPlatformView : class + { + /// + /// Gets the cross-platform virtual view associated with the handler. + /// + new TVirtualView VirtualView { get; } + + /// + /// Gets the native view associated with the handler. + /// + new TPlatformView PlatformView { get; } + } +} diff --git a/src/Core/src/Handlers/IViewHandlerOfT.cs b/src/Core/src/Handlers/IViewHandlerOfT.cs new file mode 100644 index 000000000000..35f872e5a5f8 --- /dev/null +++ b/src/Core/src/Handlers/IViewHandlerOfT.cs @@ -0,0 +1,49 @@ +namespace Microsoft.Maui +{ + /// + /// Defines a strongly typed, platform-neutral view handler contract. + /// + /// The cross-platform (virtual view) type this handler manages. + /// The native type this handler creates. + /// + /// + /// This is the counterpart of + /// . Unlike the per-control handler + /// interfaces such as , + /// or , it does not bind PlatformView to a per-target-framework + /// type alias, so an external platform backend can implement it with its own native types. + /// + /// + /// Both type parameters are covariant. Use object for + /// to match any handler for a given virtual view type, regardless of backend. + /// + /// + /// implements this interface, so + /// every handler derived from it already satisfies the contract with no extra members. + /// + /// + /// + /// labelHandler) + /// { + /// ILabel virtualView = labelHandler.VirtualView; + /// object nativeLabel = labelHandler.PlatformView; + /// } + /// ]]> + /// + public interface IViewHandler : IElementHandler, IViewHandler + where TVirtualView : IView + where TPlatformView : class + { + /// + /// Gets the cross-platform virtual view associated with the handler. + /// + /// + /// Re-declared so that lookups are unambiguous between + /// and + /// . + /// + new TVirtualView VirtualView { get; } + } +} diff --git a/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs b/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs new file mode 100644 index 000000000000..74136ed06925 --- /dev/null +++ b/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs @@ -0,0 +1,64 @@ +namespace Microsoft.Maui +{ + /// + /// Defines the platform-neutral behavior contract for a handler that manages an . + /// + /// The native type this handler creates. + /// + /// + /// declares the same child-management members, but it also declares + /// PlatformView using a per-target-framework type alias, which prevents an external platform + /// backend from implementing it. This interface carries the behavior without the alias. + /// + /// + /// The two interfaces are intentionally unrelated: is untouched, so + /// existing implementations and callers keep working. A handler that implements the members as + /// ordinary public methods — as the in-box does — satisfies + /// both interfaces at once. + /// + /// + /// Because is covariant, ILayoutHandler<object> + /// matches any layout handler regardless of backend. + /// + /// + public interface ILayoutHandler : IViewHandler + where TPlatformView : class + { + /// + /// Adds the specified child view to the end of the layout. + /// + /// The child view to add. + void Add(IView view); + + /// + /// Removes the specified child view from the layout. + /// + /// The child view to remove. + void Remove(IView view); + + /// + /// Removes all child views from the layout. + /// + void Clear(); + + /// + /// Inserts the specified child view into the layout at the given index. + /// + /// The index at which to insert the child view. + /// The child view to insert. + void Insert(int index, IView view); + + /// + /// Replaces the child view at the given index with the specified child view. + /// + /// The index of the child view to replace. + /// The replacement child view. + void Update(int index, IView view); + + /// + /// Updates the z-index ordering of the specified child view. + /// + /// The child view whose z-index changed. + void UpdateZIndex(IView view); + } +} diff --git a/src/Core/src/Handlers/Layout/LayoutHandler.cs b/src/Core/src/Handlers/Layout/LayoutHandler.cs index d3fa92de107e..d7668f3d3db8 100644 --- a/src/Core/src/Handlers/Layout/LayoutHandler.cs +++ b/src/Core/src/Handlers/Layout/LayoutHandler.cs @@ -17,7 +17,7 @@ namespace Microsoft.Maui.Handlers /// Represents the view handler for the abstract view and its platform-specific implementation. /// /// Conceptual documentation on handlers - public partial class LayoutHandler : ILayoutHandler + public partial class LayoutHandler : ILayoutHandler, ILayoutHandler { public static IPropertyMapper Mapper = new PropertyMapper(ViewMapper) { diff --git a/src/Core/src/Handlers/View/ViewHandlerOfT.cs b/src/Core/src/Handlers/View/ViewHandlerOfT.cs index 53040f66cff0..5304510d71b0 100644 --- a/src/Core/src/Handlers/View/ViewHandlerOfT.cs +++ b/src/Core/src/Handlers/View/ViewHandlerOfT.cs @@ -13,7 +13,7 @@ namespace Microsoft.Maui.Handlers { - public abstract partial class ViewHandler : ViewHandler, IViewHandler + public abstract partial class ViewHandler : ViewHandler, IViewHandler, IViewHandler where TVirtualView : class, IView #if !(NETSTANDARD || !PLATFORM) || IOS || ANDROID || WINDOWS || TIZEN where TPlatformView : PlatformView diff --git a/src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt index 59e52f9529d1..8860bbfc0bfc 100644 --- a/src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt @@ -363,3 +363,15 @@ virtual Microsoft.Maui.Platform.StackNavigationManager.OnCreateNavigationAnimati Microsoft.Maui.ISwipeItemMenuItemIconColor Microsoft.Maui.ISwipeItemMenuItemIconColor.IconColor.get -> Microsoft.Maui.Graphics.Color? static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> void +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt index f4787f33e7b9..a4bfb421019d 100644 --- a/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt @@ -63,3 +63,15 @@ virtual Microsoft.Maui.Animations.PlatformTicker.Dispose(bool disposing) -> void Microsoft.Maui.ISwipeItemMenuItemIconColor Microsoft.Maui.ISwipeItemMenuItemIconColor.IconColor.get -> Microsoft.Maui.Graphics.Color? static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> void +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt index 6f692e0aad37..50d7e5419bf6 100644 --- a/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt @@ -60,3 +60,15 @@ virtual Microsoft.Maui.Animations.PlatformTicker.Dispose(bool disposing) -> void Microsoft.Maui.ISwipeItemMenuItemIconColor Microsoft.Maui.ISwipeItemMenuItemIconColor.IconColor.get -> Microsoft.Maui.Graphics.Color? static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> void +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt index db21e60cc162..827be2cf988c 100644 --- a/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt @@ -21,3 +21,15 @@ static Microsoft.Maui.GridLength.implicit operator Microsoft.Maui.GridLength(str Microsoft.Maui.ISwipeItemMenuItemIconColor Microsoft.Maui.ISwipeItemMenuItemIconColor.IconColor.get -> Microsoft.Maui.Graphics.Color? static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> void +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt index 0e20135b6570..4d3cdcd89f05 100644 --- a/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt @@ -48,3 +48,15 @@ virtual Microsoft.Maui.MauiWinUIApplication.OnAppInstanceActivated(Microsoft.Win Microsoft.Maui.ISwipeItemMenuItemIconColor Microsoft.Maui.ISwipeItemMenuItemIconColor.IconColor.get -> Microsoft.Maui.Graphics.Color? static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> void +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt index a430354bb4c7..09259c673dd3 100644 --- a/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt @@ -31,3 +31,15 @@ static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.M static Microsoft.Maui.Handlers.ShapeViewHandler.MapFlowDirection(Microsoft.Maui.Handlers.IShapeViewHandler! handler, Microsoft.Maui.IShapeView! shapeView) -> void static Microsoft.Maui.Handlers.SearchBarHandler.MapCursorPosition(Microsoft.Maui.Handlers.ISearchBarHandler! handler, Microsoft.Maui.ISearchBar! searchBar) -> void static Microsoft.Maui.Handlers.SearchBarHandler.MapSelectionLength(Microsoft.Maui.Handlers.ISearchBarHandler! handler, Microsoft.Maui.ISearchBar! searchBar) -> void +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt index bd5088b5829e..b1fe67450771 100644 --- a/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt @@ -29,3 +29,15 @@ static Microsoft.Maui.Handlers.FlyoutViewHandler.MapFlyoutWidth(Microsoft.Maui.H static Microsoft.Maui.Handlers.FlyoutViewHandler.MapIsGestureEnabled(Microsoft.Maui.Handlers.IFlyoutViewHandler! handler, Microsoft.Maui.IFlyoutView! flyoutView) -> void static Microsoft.Maui.Handlers.FlyoutViewHandler.MapIsPresented(Microsoft.Maui.Handlers.IFlyoutViewHandler! handler, Microsoft.Maui.IFlyoutView! flyoutView) -> void static Microsoft.Maui.SafeAreaEdges.Container.get -> Microsoft.Maui.SafeAreaEdges +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt index bd5088b5829e..b1fe67450771 100644 --- a/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt @@ -29,3 +29,15 @@ static Microsoft.Maui.Handlers.FlyoutViewHandler.MapFlyoutWidth(Microsoft.Maui.H static Microsoft.Maui.Handlers.FlyoutViewHandler.MapIsGestureEnabled(Microsoft.Maui.Handlers.IFlyoutViewHandler! handler, Microsoft.Maui.IFlyoutView! flyoutView) -> void static Microsoft.Maui.Handlers.FlyoutViewHandler.MapIsPresented(Microsoft.Maui.Handlers.IFlyoutViewHandler! handler, Microsoft.Maui.IFlyoutView! flyoutView) -> void static Microsoft.Maui.SafeAreaEdges.Container.get -> Microsoft.Maui.SafeAreaEdges +Microsoft.Maui.IElementHandler +Microsoft.Maui.IElementHandler.PlatformView.get -> TPlatformView! +Microsoft.Maui.IElementHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.IViewHandler +Microsoft.Maui.IViewHandler.VirtualView.get -> TVirtualView +Microsoft.Maui.ILayoutHandler +Microsoft.Maui.ILayoutHandler.Add(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Clear() -> void +Microsoft.Maui.ILayoutHandler.Insert(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Remove(Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.Update(int index, Microsoft.Maui.IView! view) -> void +Microsoft.Maui.ILayoutHandler.UpdateZIndex(Microsoft.Maui.IView! view) -> void diff --git a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj new file mode 100644 index 000000000000..3ccd4ceca80a --- /dev/null +++ b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj @@ -0,0 +1,24 @@ + + + + $(_MauiDotNetTfm) + Microsoft.Maui.Core.ExternalBackend.TestAssembly + Microsoft.Maui.ExternalBackend + false + enable + + true + + + + + + + diff --git a/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs b/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs new file mode 100644 index 000000000000..64cbae600966 --- /dev/null +++ b/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs @@ -0,0 +1,85 @@ +using Microsoft.Maui.Handlers; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Compile-time proof that an assembly outside of dotnet/maui can participate in the strongly typed + /// handler contracts using its own native types. + /// + /// + /// Every conversion below is an implicit reference conversion. If any of them stopped compiling, an + /// external platform backend would have lost the ability to be recognized by .NET MAUI. + /// + public static class ExternalBackendContracts + { + /// + /// The backend's own native type flows out of the contract, strongly typed. + /// + public static IViewHandler TypedLabelHandler(FakeLabelHandler handler) => + handler; + + /// + /// Covariance lets consumers match any backend's label handler platform-neutrally. + /// + public static IViewHandler NeutralLabelHandler(FakeLabelHandler handler) => + handler; + + public static IViewHandler TypedContentViewHandler(FakeContentViewHandler handler) => + handler; + + public static IViewHandler NeutralContentViewHandler(FakeContentViewHandler handler) => + handler; + + public static ILayoutHandler TypedLayoutHandler(FakeLayoutHandler handler) => + handler; + + public static ILayoutHandler NeutralLayoutHandler(FakeLayoutHandler handler) => + handler; + + /// + /// A window is an element, not a view, so it uses the element-level contract. + /// + public static IElementHandler TypedWindowHandler(FakeWindowHandler handler) => + handler; + + public static IElementHandler NeutralWindowHandler(FakeWindowHandler handler) => + handler; + + /// + /// The neutral contracts still expose the base handler surface. + /// + public static IViewHandler AsViewHandler(IViewHandler handler) => handler; + + /// + /// The neutral contracts still expose the element handler surface. + /// + public static IElementHandler AsElementHandler(IElementHandler handler) => handler; + + /// + /// Reads the strongly typed members without any cast or ambiguity. + /// + public static string? ReadThroughContract(IViewHandler handler) + { + ILabel virtualView = handler.VirtualView; + FakeNativeLabel platformView = handler.PlatformView; + + return virtualView.Text ?? platformView.Text; + } + + /// + /// Reads the platform-neutral members without any cast or ambiguity. + /// + public static object ReadThroughNeutralContract(IViewHandler handler) + { + ILabel virtualView = handler.VirtualView; + + return virtualView.Text is { Length: > 0 } ? virtualView : handler.PlatformView; + } + + /// + /// The in-box mapper infrastructure accepts an external backend's handler type. + /// + public static IPropertyMapper> NeutralMapper() => + new PropertyMapper>(ViewHandler.ViewMapper); + } +} diff --git a/src/Core/tests/ExternalBackend/FakeHandlers.cs b/src/Core/tests/ExternalBackend/FakeHandlers.cs new file mode 100644 index 000000000000..acd659136918 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeHandlers.cs @@ -0,0 +1,96 @@ +using Microsoft.Maui.Handlers; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// A label handler for a platform that .NET MAUI does not ship support for. + /// + /// + /// + /// This handler cannot implement : that interface declares + /// PlatformView through a using PlatformView = ... alias that resolves to one of + /// .NET MAUI's own native types (or to System.Object on the platform-neutral target + /// framework), so an external native type produces CS0738/CS9333. + /// + /// + /// It does not need to. implements + /// , so this type already satisfies + /// IViewHandler<ILabel, FakeNativeLabel> — and, through covariance, + /// IViewHandler<ILabel, object> — with no extra members at all. + /// + /// + public class FakeLabelHandler : ViewHandler + { + public static IPropertyMapper Mapper = + new PropertyMapper(ViewMapper) + { + [nameof(ILabel.Text)] = MapText, + [nameof(IView.Opacity)] = MapOpacity, + }; + + public FakeLabelHandler() + : base(Mapper) + { + } + + protected override FakeNativeLabel CreatePlatformView() => new FakeNativeLabel(); + + public static void MapText(FakeLabelHandler handler, ILabel label) => + handler.PlatformView.Text = label.Text; + + public static void MapOpacity(FakeLabelHandler handler, ILabel label) => + handler.PlatformView.Opacity = label.Opacity; + } + + /// + /// A content view handler for a platform that .NET MAUI does not ship support for. + /// + public class FakeContentViewHandler : ViewHandler + { + public static IPropertyMapper Mapper = + new PropertyMapper(ViewMapper) + { + [nameof(IContentView.Content)] = MapContent, + }; + + public FakeContentViewHandler() + : base(Mapper) + { + } + + protected override FakeNativeContentView CreatePlatformView() => new FakeNativeContentView(); + + public static void MapContent(FakeContentViewHandler handler, IContentView contentView) + { + handler.PlatformView.Content = + (contentView.PresentedContent as IView)?.Handler?.PlatformView as FakeNativeView; + } + } + + /// + /// A window handler for a platform that .NET MAUI does not ship support for. + /// + /// + /// A window is not a view, so this derives from + /// and is matched platform-neutrally + /// through . + /// + public class FakeWindowHandler : ElementHandler + { + public static IPropertyMapper Mapper = + new PropertyMapper(ElementMapper) + { + [nameof(IWindow.Title)] = MapTitle, + }; + + public FakeWindowHandler() + : base(Mapper) + { + } + + protected override FakeNativeWindow CreatePlatformElement() => new FakeNativeWindow(); + + public static void MapTitle(FakeWindowHandler handler, IWindow window) => + handler.PlatformView.Title = window.Title; + } +} diff --git a/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs new file mode 100644 index 000000000000..14c768d165d8 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs @@ -0,0 +1,148 @@ +using System.Collections.Generic; +using Microsoft.Maui.Handlers; +using Microsoft.Maui.Platform; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// A layout handler for a platform that .NET MAUI does not ship support for. + /// + /// + /// + /// carries real behavior — Add, Remove, Clear, + /// Insert, Update and UpdateZIndex — but it also declares an aliased + /// PlatformView, so an external backend cannot implement it. + /// carries the same behavior without the alias. + /// + /// + /// The command mapper keys are taken from via nameof. Referencing + /// the interface for its member names is always fine; only implementing it is blocked. Using the same + /// keys is what keeps .NET MAUI Controls' Layout talking to this handler. + /// + /// + public class FakeLayoutHandler : ViewHandler, ILayoutHandler + { + public static IPropertyMapper Mapper = + new PropertyMapper(ViewMapper); + + public static CommandMapper CommandMapper = + new CommandMapper(ViewCommandMapper) + { + [nameof(ILayoutHandler.Add)] = MapAdd, + [nameof(ILayoutHandler.Remove)] = MapRemove, + [nameof(ILayoutHandler.Clear)] = MapClear, + [nameof(ILayoutHandler.Insert)] = MapInsert, + [nameof(ILayoutHandler.Update)] = MapUpdate, + [nameof(ILayoutHandler.UpdateZIndex)] = MapUpdateZIndex, + }; + + public FakeLayoutHandler() + : base(Mapper, CommandMapper) + { + } + + protected override FakeNativeLayoutView CreatePlatformView() => new FakeNativeLayoutView(); + + public void Add(IView view) + { + if (GetNativeChild(view) is FakeNativeView child) + { + PlatformView.Children.Add(child); + } + } + + public void Remove(IView view) + { + if (view.Handler?.PlatformView is FakeNativeView child) + { + PlatformView.Children.Remove(child); + } + } + + public void Clear() => PlatformView.Children.Clear(); + + public void Insert(int index, IView view) + { + if (GetNativeChild(view) is FakeNativeView child) + { + PlatformView.Children.Insert(index, child); + } + } + + public void Update(int index, IView view) + { + if (GetNativeChild(view) is FakeNativeView child) + { + PlatformView.Children[index] = child; + } + } + + public void UpdateZIndex(IView view) + { + if (view.Handler?.PlatformView is FakeNativeView child) + { + List children = PlatformView.Children; + children.Remove(child); + children.Insert(GetClampedZIndex(view, children.Count), child); + } + } + + FakeNativeView? GetNativeChild(IView view) => + view.ToHandler(MauiContext!).PlatformView as FakeNativeView; + + static int GetClampedZIndex(IView view, int count) + { + int index = view.ZIndex; + + if (index < 0) + { + return 0; + } + + return index > count ? count : index; + } + + public static void MapAdd(FakeLayoutHandler handler, ILayout layout, object? arg) + { + if (arg is LayoutHandlerUpdate update) + { + handler.Add(update.View); + } + } + + public static void MapRemove(FakeLayoutHandler handler, ILayout layout, object? arg) + { + if (arg is LayoutHandlerUpdate update) + { + handler.Remove(update.View); + } + } + + public static void MapClear(FakeLayoutHandler handler, ILayout layout, object? arg) => + handler.Clear(); + + public static void MapInsert(FakeLayoutHandler handler, ILayout layout, object? arg) + { + if (arg is LayoutHandlerUpdate update) + { + handler.Insert(update.Index, update.View); + } + } + + public static void MapUpdate(FakeLayoutHandler handler, ILayout layout, object? arg) + { + if (arg is LayoutHandlerUpdate update) + { + handler.Update(update.Index, update.View); + } + } + + public static void MapUpdateZIndex(FakeLayoutHandler handler, ILayout layout, object? arg) + { + if (arg is IView view) + { + handler.UpdateZIndex(view); + } + } + } +} diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.cs new file mode 100644 index 000000000000..5343c429888b --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeViews.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Stands in for the native view type of a platform .NET MAUI knows nothing about. + /// + /// + /// Deliberately does not derive from, or reference, any .NET MAUI type. This is the whole point of + /// the test assembly: a backend's native types are its own. + /// + public class FakeNativeView + { + public List Children { get; } = new List(); + + public double Opacity { get; set; } = 1; + } + + /// Native label type for the fake external platform. + public class FakeNativeLabel : FakeNativeView + { + public string? Text { get; set; } + } + + /// Native content-host type for the fake external platform. + public class FakeNativeContentView : FakeNativeView + { + public FakeNativeView? Content { get; set; } + } + + /// Native layout container type for the fake external platform. + public class FakeNativeLayoutView : FakeNativeView + { + } + + /// Native window type for the fake external platform. Not even a view. + public class FakeNativeWindow + { + public string? Title { get; set; } + + public FakeNativeView? Content { get; set; } + } +} diff --git a/src/Core/tests/UnitTests/Core.UnitTests.csproj b/src/Core/tests/UnitTests/Core.UnitTests.csproj index 9348f8b24121..1c834d31c150 100644 --- a/src/Core/tests/UnitTests/Core.UnitTests.csproj +++ b/src/Core/tests/UnitTests/Core.UnitTests.csproj @@ -33,6 +33,7 @@ + diff --git a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs new file mode 100644 index 000000000000..5fdcd8627c2f --- /dev/null +++ b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs @@ -0,0 +1,268 @@ +using System; +using Microsoft.Maui.Controls; +using Microsoft.Maui.ExternalBackend; +using Microsoft.Maui.Handlers; +using Microsoft.Maui.Hosting; +using Microsoft.Maui.Platform; +using Xunit; + +namespace Microsoft.Maui.UnitTests.Handlers +{ + /// + /// Verifies that a platform backend living in an assembly outside of dotnet/maui — with native view + /// types .NET MAUI knows nothing about — can implement, be recognized by, and be driven through the + /// public handler contracts. + /// + /// + /// The fake backend lives in Microsoft.Maui.Core.ExternalBackend.TestAssembly, which is deliberately + /// absent from Core's InternalsVisibleTo list. + /// + [Category(TestCategory.Core)] + public class ExternalPlatformBackendTests + { + static IMauiContext CreateContext() + { + var mauiApp = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => + { + handlers.AddHandler(); + handlers.AddHandler(); + handlers.AddHandler(); + handlers.AddHandler(); + }) + .Build(); + + return new MauiContext(mauiApp.Services); + } + + [Fact] + public void ExternalViewHandlerSatisfiesTypedNeutralContract() + { + var handler = new FakeLabelHandler(); + + IViewHandler typed = handler; + + Assert.Same(handler, typed); + } + + [Fact] + public void ExternalViewHandlerSatisfiesPlatformNeutralContract() + { + var handler = new FakeLabelHandler(); + + Assert.IsAssignableFrom>(handler); + Assert.IsAssignableFrom>(handler); + } + + [Fact] + public void ExternalElementHandlerSatisfiesPlatformNeutralContract() + { + var handler = new FakeWindowHandler(); + + Assert.IsAssignableFrom>(handler); + Assert.IsAssignableFrom>(handler); + } + + [Fact] + public void ExternalLayoutHandlerSatisfiesPlatformNeutralLayoutContract() + { + var handler = new FakeLayoutHandler(); + + Assert.IsAssignableFrom>(handler); + Assert.IsAssignableFrom>(handler); + } + + [Fact] + public void ExternalHandlerCannotImplementAliasedInterface() + { + // This is the gap the platform-neutral contracts exist to close: the aliased interfaces pin + // PlatformView to a type the external backend does not own, so it cannot implement them. + Assert.IsNotAssignableFrom(new FakeLabelHandler()); + Assert.IsNotAssignableFrom(new FakeLayoutHandler()); + } + + [Fact] + public void InBoxLabelHandlerSatisfiesPlatformNeutralContract() + { + var handler = new LabelHandler(); + + Assert.IsAssignableFrom>(handler); + Assert.IsAssignableFrom>(handler); + } + + [Fact] + public void InBoxContentViewHandlerSatisfiesPlatformNeutralContract() + { + Assert.IsAssignableFrom>(new ContentViewHandler()); + } + + [Fact] + public void InBoxWindowHandlerSatisfiesPlatformNeutralContract() + { + Assert.IsAssignableFrom>(new WindowHandler()); + } + + [Fact] + public void InBoxLayoutHandlerSatisfiesBothLayoutContracts() + { + var handler = new LayoutHandler(); + + // Additive: the pre-existing interface keeps working... + Assert.IsAssignableFrom(handler); + + // ...alongside the platform-neutral one. + Assert.IsAssignableFrom>(handler); + } + + [Fact] + public void AliasedLayoutHandlerContractIsUnchanged() + { + // Backward compatibility: nothing moved off ILayoutHandler. + var members = new[] + { + nameof(ILayoutHandler.Add), + nameof(ILayoutHandler.Remove), + nameof(ILayoutHandler.Clear), + nameof(ILayoutHandler.Insert), + nameof(ILayoutHandler.Update), + nameof(ILayoutHandler.UpdateZIndex), + }; + + foreach (var name in members) + { + var method = typeof(ILayoutHandler).GetMethod(name); + + Assert.NotNull(method); + Assert.Equal(typeof(ILayoutHandler), method.DeclaringType); + } + + Assert.NotNull(typeof(ILayoutHandler).GetProperty(nameof(ILayoutHandler.PlatformView))); + Assert.NotNull(typeof(ILayoutHandler).GetProperty(nameof(ILayoutHandler.VirtualView))); + } + + [Fact] + public void PlatformNeutralContractsAreCovariant() + { + ILayoutHandler typed = new FakeLayoutHandler(); + + ILayoutHandler neutral = typed; + + Assert.Same(typed, neutral); + } + + [Fact] + public void ExternalHandlerIsResolvedThroughHandlerRegistration() + { + var context = CreateContext(); + + var handler = new Label().ToHandler(context); + + Assert.IsType(handler); + } + + [Fact] + public void ExternalHandlerPropertyMapperUpdatesNativeView() + { + var context = CreateContext(); + var label = new Label { Text = "hello" }; + + var handler = (FakeLabelHandler)label.ToHandler(context); + + Assert.Equal("hello", handler.PlatformView.Text); + + label.Text = "goodbye"; + handler.UpdateValue(nameof(ILabel.Text)); + + Assert.Equal("goodbye", handler.PlatformView.Text); + } + + [Fact] + public void ExternalHandlerInheritsViewMapperFromCore() + { + var context = CreateContext(); + var label = new Label { Text = "hello", Opacity = 0.5 }; + + var handler = (FakeLabelHandler)label.ToHandler(context); + + // Opacity is chained off Core's ViewMapper, proving mapper composition still works. + Assert.Equal(0.5, handler.PlatformView.Opacity); + } + + [Fact] + public void ExternalHandlerIsReachableThroughPlatformNeutralContract() + { + var context = CreateContext(); + var label = new Label { Text = "hello" }; + + label.ToHandler(context); + + var neutral = Assert.IsAssignableFrom>(label.Handler); + + Assert.Same(label, neutral.VirtualView); + Assert.IsType(neutral.PlatformView); + } + + [Fact] + public void ControlsLayoutCommandsReachExternalLayoutHandler() + { + var context = CreateContext(); + var layout = new VerticalStackLayout(); + + var handler = (FakeLayoutHandler)layout.ToHandler(context); + + layout.Add(new Label { Text = "first" }); + layout.Add(new Label { Text = "second" }); + Assert.Equal(2, handler.PlatformView.Children.Count); + + layout.Insert(0, new Label { Text = "inserted" }); + Assert.Equal(3, handler.PlatformView.Children.Count); + Assert.Equal("inserted", Assert.IsType(handler.PlatformView.Children[0]).Text); + + layout.RemoveAt(0); + Assert.Equal(2, handler.PlatformView.Children.Count); + + layout[0] = new Label { Text = "replaced" }; + Assert.Equal("replaced", Assert.IsType(handler.PlatformView.Children[0]).Text); + + layout.Clear(); + Assert.Empty(handler.PlatformView.Children); + } + + [Fact] + public void ExternalLayoutHandlerIsDrivenThroughNeutralContract() + { + var context = CreateContext(); + var layout = new VerticalStackLayout(); + + layout.ToHandler(context); + + var neutral = Assert.IsAssignableFrom>(layout.Handler); + + var child = new Label { Text = "one" }; + child.ToHandler(context); + neutral.Add(child); + + var platformView = Assert.IsType(neutral.PlatformView); + Assert.Single(platformView.Children); + + neutral.Clear(); + Assert.Empty(platformView.Children); + } + + [Fact] + public void ExternalWindowHandlerRunsThroughElementMapper() + { + var context = CreateContext(); + var window = new Window { Title = "external" }; + + var handler = (FakeWindowHandler)((IElement)window).ToHandler(context); + + Assert.Equal("external", handler.PlatformView.Title); + + IElementHandler neutral = handler; + + Assert.Same(window, neutral.VirtualView); + Assert.IsType(neutral.PlatformView); + } + } +} From 56aaeb6085ae6f544a7d9cc51c7b4eabcbbf78db Mon Sep 17 00:00:00 2001 From: redth Date: Wed, 26 Aug 2026 17:31:00 -0400 Subject: [PATCH 2/7] Add Core.ExternalBackend to Microsoft.Maui-dev.sln The macOS CI legs build Microsoft.Maui-mac.slnf, and both solution filters resolve against Microsoft.Maui-dev.sln - not Microsoft.Maui.sln, which is what the Windows leg builds and what the new test project was added to. Listing the project in the filters without adding it to the filtered solution made solution load fail before restore: Microsoft.Maui-mac.slnf(1,1): error MSB4025: The project file could not be loaded. Data at the root level is invalid. Line 1, position 1. Reproduced locally, where MSBuild reports the underlying cause directly: error MSB5028: Solution filter file at ".../Microsoft.Maui-mac.slnf" includes project "src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj" that is not in the solution file at ".../Microsoft.Maui-dev.sln". Adds the project to Microsoft.Maui-dev.sln under the same test solution folder as Core.UnitTests. Both filters and both solutions now load cleanly. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Microsoft.Maui-dev.sln | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Microsoft.Maui-dev.sln b/Microsoft.Maui-dev.sln index 0f45585050d8..d1845ed331aa 100644 --- a/Microsoft.Maui-dev.sln +++ b/Microsoft.Maui-dev.sln @@ -37,6 +37,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtils", "src\TestUtils\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.UnitTests", "src\Core\tests\UnitTests\Core.UnitTests.csproj", "{92644F6F-5946-48FC-A21A-A3D6EE24E8B3}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.ExternalBackend", "src\Core\tests\ExternalBackend\Core.ExternalBackend.csproj", "{7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E8AD265B-3C67-4640-AC58-A522F9FB3361}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{C564DDD6-DE79-45CD-88EA-3F690481572A}" @@ -309,6 +311,10 @@ Global {92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Debug|Any CPU.Build.0 = Debug|Any CPU {92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Release|Any CPU.ActiveCfg = Release|Any CPU {92644F6F-5946-48FC-A21A-A3D6EE24E8B3}.Release|Any CPU.Build.0 = Release|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4}.Release|Any CPU.Build.0 = Release|Any CPU {F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Debug|Any CPU.Build.0 = Debug|Any CPU {F7F2B379-52CE-4802-9EC9-0D7967B6BFB7}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -679,6 +685,7 @@ Global {DAAC2822-63B6-4DE0-83AE-04873CD2F364} = {72397ADB-40A8-4B8E-8E08-2DBE2803C845} {FBB3270F-1924-4A72-845E-A6DF39C402F6} = {7AC28763-9C68-4BF9-A1BA-25CBFFD2D15C} {92644F6F-5946-48FC-A21A-A3D6EE24E8B3} = {C564DDD6-DE79-45CD-88EA-3F690481572A} + {7B2E1C4D-9A5F-4E38-8D6B-2C0F1A73E9D4} = {C564DDD6-DE79-45CD-88EA-3F690481572A} {E8AD265B-3C67-4640-AC58-A522F9FB3361} = {09C264E9-E3F3-4586-9151-DCBB1F6DA7AB} {C564DDD6-DE79-45CD-88EA-3F690481572A} = {09C264E9-E3F3-4586-9151-DCBB1F6DA7AB} {50C758FE-4E10-409A-94F5-A75480960864} = {459BF674-83CB-46F6-881F-A2D2117DBF4D} From 9d4f2d326e56b82c2fc801326530150646a36b34 Mon Sep 17 00:00:00 2001 From: redth Date: Wed, 26 Aug 2026 21:06:37 -0400 Subject: [PATCH 3/7] Compile the external-backend tests on every target framework The external-backend test assembly only targeted the platform-neutral TFM, so it only ever proved the CS9333/CS8766 half of the problem. The CS0738 half - where the aliased interfaces pin PlatformView to one of .NET MAUI's own concrete native types - only occurs on a platform TFM and was therefore untested. Multi-targets Core.ExternalBackend across $(_MauiDotNetTfm);$(MauiPlatforms), so the same external-backend sources are compiled against every target framework Core ships. The fake native view types become per-platform, because ViewHandler<,> constrains TPlatformView differently per TFM: net11.0 class (derives from nothing) net11.0-android Android.Views.View Android.Views.View net11.0-ios/-maccatalyst UIKit.UIView UIKit.UIView net11.0-windows Microsoft.UI.Xaml.FrameworkElement Controls.Panel That mirrors reality: a real external backend's views do derive from the platform's base view type. What makes it external is that its concrete types are its own, and so are never the types the aliased interfaces are pinned to. That is precisely the CS0738 case. ElementHandler<,> constrains TPlatformView only to class everywhere, so the fake native window type stays a single shared definition. Fake members are prefixed Fake (FakeText, FakeOpacity, FakeChildren) so one set of handler sources compiles on every TFM without colliding with a real platform base type's members - notably FrameworkElement.Opacity on Windows. Adds ExternalBackendTfmContracts.cs, which compiles unchanged on every TFM and asserts at compile time that the backend's own native type survives a round trip through both the typed and neutral contracts, that the layout contract's behavior is callable, and that the in-box handlers satisfy the same neutral contracts. No product code changes: Microsoft.Maui and its PublicAPI files are untouched. Verified locally: net11.0, net11.0-android37.0 and net11.0-maccatalyst26.5 all build clean with TreatWarningsAsErrors; Core.UnitTests 966 passed / 0 failed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/design/ExternalPlatformBackends.md | 45 +++++++++- .../Core.ExternalBackend.csproj | 20 ++++- .../ExternalBackendContracts.cs | 2 +- .../ExternalBackendTfmContracts.cs | 88 +++++++++++++++++++ .../tests/ExternalBackend/FakeHandlers.cs | 30 +++++-- .../ExternalBackend/FakeLayoutHandler.cs | 19 ++-- .../FakeNativeViews.Android.cs | 60 +++++++++++++ .../FakeNativeViews.Standard.cs | 49 +++++++++++ .../FakeNativeViews.Windows.cs | 41 +++++++++ .../tests/ExternalBackend/FakeNativeViews.cs | 43 --------- .../ExternalBackend/FakeNativeViews.iOS.cs | 40 +++++++++ .../tests/ExternalBackend/FakeNativeWindow.cs | 18 ++++ .../Handlers/ExternalPlatformBackendTests.cs | 24 ++--- 13 files changed, 402 insertions(+), 77 deletions(-) create mode 100644 src/Core/tests/ExternalBackend/ExternalBackendTfmContracts.cs create mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.Android.cs create mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.Standard.cs create mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.Windows.cs delete mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.cs create mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.iOS.cs create mode 100644 src/Core/tests/ExternalBackend/FakeNativeWindow.cs diff --git a/docs/design/ExternalPlatformBackends.md b/docs/design/ExternalPlatformBackends.md index d18e85fdd2b1..e1d88beabfde 100644 --- a/docs/design/ExternalPlatformBackends.md +++ b/docs/design/ExternalPlatformBackends.md @@ -186,6 +186,14 @@ relationships continue to work with no `TypeLoadException`. An external backend derives from the public generic handler base classes and stops trying to implement the aliased interfaces. +> **Note on the native type.** On a platform target framework, +> `ViewHandler` constrains `TPlatformView` to that platform's base view +> type (`UIKit.UIView`, `Android.Views.View`, `Microsoft.UI.Xaml.FrameworkElement`, +> `Tizen.NUI.BaseComponents.View`). An external backend's views already satisfy that. The constraint was +> never the problem — the *aliased interfaces* were, because they pin `PlatformView` to one exact +> concrete type. `ElementHandler` constrains `TPlatformView` only to +> `class`, on every target framework. + ```csharp using Microsoft.Maui; using Microsoft.Maui.Handlers; @@ -265,10 +273,39 @@ builder.ConfigureMauiHandlers(handlers => handlers for label, content view, layout and window, so everything it compiles is provably public API and provably warning-free for an external consumer. -`src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs` exercises it: contract satisfaction, -covariance, handler registration, property-mapper composition off `ViewHandler.ViewMapper`, Controls' -`Layout` command routing reaching an external layout handler, and backward-compatibility assertions that -the aliased interfaces are unchanged. +It **multi-targets every target framework Core ships** — the platform-neutral one plus each platform TFM +— because the failure it guards against is target-framework specific: `CS9333`/`CS8766` on the neutral +TFM, `CS0738` on the platform TFMs. Compiling the same external-backend sources against all of them is +the only way to prove the contracts close the gap everywhere. + +The fake native view types are therefore per-platform, because +`ViewHandler` constrains `TPlatformView` differently per TFM: + +| Target framework | `ViewHandler<,>` constraint on `TPlatformView` | Fake native view derives from | +| --- | --- | --- | +| `net11.0` (neutral) | `class` | *(nothing)* | +| `net11.0-android` | `Android.Views.View` | `Android.Views.View` | +| `net11.0-ios`, `net11.0-maccatalyst` | `UIKit.UIView` | `UIKit.UIView` | +| `net11.0-windows` | `Microsoft.UI.Xaml.FrameworkElement` | `Microsoft.UI.Xaml.Controls.Panel` | + +This mirrors reality: a real external backend's views *do* derive from the platform's base view type. +What makes it external is that its **concrete** types are its own, and so are never the types the aliased +interfaces are pinned to (`MauiLabel`, `AppCompatTextView`, `TextBlock`) — which is exactly what produces +`CS0738`. `ElementHandler<,>` constrains `TPlatformView` only to `class` on every TFM, so the fake native +*window* type is a single definition shared across all of them. + +Fake members are prefixed `Fake` (`FakeText`, `FakeOpacity`, `FakeChildren`) so the same handler sources +compile on every TFM without colliding with a real platform base type's members — for example +`FrameworkElement.Opacity` on Windows. + +`ExternalBackendTfmContracts.cs` compiles unchanged on every TFM and asserts, at compile time, that the +backend's own native type survives a round trip through the typed and neutral contracts, that the layout +contract's behavior is callable, and that .NET MAUI's in-box handlers satisfy the same neutral contracts. + +`src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs` exercises runtime behavior on the +neutral TFM: contract satisfaction, covariance, handler registration, property-mapper composition off +`ViewHandler.ViewMapper`, Controls' `Layout` command routing reaching an external layout handler, and +backward-compatibility assertions that the aliased interfaces are unchanged. ## Follow-up coverage diff --git a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj index 3ccd4ceca80a..c07dd3c5b66e 100644 --- a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj +++ b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj @@ -1,7 +1,19 @@  - $(_MauiDotNetTfm) + + $(_MauiDotNetTfm);$(MauiPlatforms) Microsoft.Maui.Core.ExternalBackend.TestAssembly Microsoft.Maui.ExternalBackend false @@ -17,8 +29,14 @@ true + + + + + + diff --git a/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs b/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs index 64cbae600966..648a5e53a62e 100644 --- a/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs +++ b/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs @@ -63,7 +63,7 @@ public static IElementHandler NeutralWindowHandler(FakeWindowHa ILabel virtualView = handler.VirtualView; FakeNativeLabel platformView = handler.PlatformView; - return virtualView.Text ?? platformView.Text; + return virtualView.Text ?? platformView.FakeText; } /// diff --git a/src/Core/tests/ExternalBackend/ExternalBackendTfmContracts.cs b/src/Core/tests/ExternalBackend/ExternalBackendTfmContracts.cs new file mode 100644 index 000000000000..33a1bc3be2d8 --- /dev/null +++ b/src/Core/tests/ExternalBackend/ExternalBackendTfmContracts.cs @@ -0,0 +1,88 @@ +using Microsoft.Maui.Handlers; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Per-target-framework proof that the platform-neutral contracts are usable from an external + /// assembly on every target framework .NET MAUI ships, and that the backend's own native type + /// survives the round trip. + /// + /// + /// + /// This file compiles unchanged on the platform-neutral target framework and on every platform + /// target framework. That is the point: the aliased handler interfaces cannot be implemented on any + /// of them by an external backend, while these contracts can be implemented on all of them. + /// + /// + /// Every conversion below is an implicit reference conversion resolved at compile time. If the + /// contracts regressed, this file would stop compiling — on the specific target framework that + /// regressed. + /// + /// + public static class ExternalBackendTfmContracts + { + /// + /// The backend's own native type — which on a platform target framework derives from that + /// platform's base view type, and on the neutral one derives from nothing — flows out of the + /// contract strongly typed. + /// + public static FakeNativeLabel TypedPlatformViewSurvivesRoundTrip(FakeLabelHandler handler) + { + IViewHandler typed = handler; + + return typed.PlatformView; + } + + /// + /// The same handler is matchable without naming the backend's type at all. + /// + public static object NeutralPlatformViewSurvivesRoundTrip(FakeLabelHandler handler) + { + IViewHandler neutral = handler; + + return neutral.PlatformView; + } + + /// + /// The layout contract carries behavior, so verify the members are callable through it. + /// + public static int LayoutBehaviorIsReachableThroughContract(FakeLayoutHandler handler, IView child) + { + ILayoutHandler typed = handler; + ILayoutHandler neutral = typed; + + neutral.Add(child); + neutral.Insert(0, child); + neutral.Update(0, child); + neutral.UpdateZIndex(child); + neutral.Remove(child); + neutral.Clear(); + + return typed.PlatformView.FakeChildren.Count; + } + + /// + /// A window is an element rather than a view, and its native type is unconstrained on every + /// target framework. + /// + public static FakeNativeWindow WindowPlatformViewSurvivesRoundTrip(FakeWindowHandler handler) + { + IElementHandler typed = handler; + IElementHandler neutral = typed; + + _ = neutral.PlatformView; + + return typed.PlatformView; + } + + /// + /// .NET MAUI's own in-box handlers satisfy the same neutral contracts on this target framework, + /// so a consumer can write one code path for in-box and external backends alike. + /// + public static bool InBoxHandlersSatisfyNeutralContracts() => + new LabelHandler() is IViewHandler && + new ContentViewHandler() is IViewHandler && + new WindowHandler() is IElementHandler && + new LayoutHandler() is ILayoutHandler; + } +} diff --git a/src/Core/tests/ExternalBackend/FakeHandlers.cs b/src/Core/tests/ExternalBackend/FakeHandlers.cs index acd659136918..9e5ec310c345 100644 --- a/src/Core/tests/ExternalBackend/FakeHandlers.cs +++ b/src/Core/tests/ExternalBackend/FakeHandlers.cs @@ -9,14 +9,16 @@ namespace Microsoft.Maui.ExternalBackend /// /// This handler cannot implement : that interface declares /// PlatformView through a using PlatformView = ... alias that resolves to one of - /// .NET MAUI's own native types (or to System.Object on the platform-neutral target - /// framework), so an external native type produces CS0738/CS9333. + /// .NET MAUI's own native types on a platform target framework (MauiLabel, + /// AppCompatTextView, TextBlock), or to System.Object on the platform-neutral + /// one. An external native type therefore produces CS0738 or CS9333. /// /// /// It does not need to. implements /// , so this type already satisfies /// IViewHandler<ILabel, FakeNativeLabel> — and, through covariance, - /// IViewHandler<ILabel, object> — with no extra members at all. + /// IViewHandler<ILabel, object> — with no extra members at all, on every target + /// framework. /// /// public class FakeLabelHandler : ViewHandler @@ -33,13 +35,18 @@ public FakeLabelHandler() { } - protected override FakeNativeLabel CreatePlatformView() => new FakeNativeLabel(); + protected override FakeNativeLabel CreatePlatformView() => +#if MONOANDROID + new FakeNativeLabel(Context); +#else + new FakeNativeLabel(); +#endif public static void MapText(FakeLabelHandler handler, ILabel label) => - handler.PlatformView.Text = label.Text; + handler.PlatformView.FakeText = label.Text; public static void MapOpacity(FakeLabelHandler handler, ILabel label) => - handler.PlatformView.Opacity = label.Opacity; + handler.PlatformView.FakeOpacity = label.Opacity; } /// @@ -58,11 +65,16 @@ public FakeContentViewHandler() { } - protected override FakeNativeContentView CreatePlatformView() => new FakeNativeContentView(); + protected override FakeNativeContentView CreatePlatformView() => +#if MONOANDROID + new FakeNativeContentView(Context); +#else + new FakeNativeContentView(); +#endif public static void MapContent(FakeContentViewHandler handler, IContentView contentView) { - handler.PlatformView.Content = + handler.PlatformView.FakeContent = (contentView.PresentedContent as IView)?.Handler?.PlatformView as FakeNativeView; } } @@ -91,6 +103,6 @@ public FakeWindowHandler() protected override FakeNativeWindow CreatePlatformElement() => new FakeNativeWindow(); public static void MapTitle(FakeWindowHandler handler, IWindow window) => - handler.PlatformView.Title = window.Title; + handler.PlatformView.FakeTitle = window.Title; } } diff --git a/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs index 14c768d165d8..a33cafd357ad 100644 --- a/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs +++ b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs @@ -41,13 +41,18 @@ public FakeLayoutHandler() { } - protected override FakeNativeLayoutView CreatePlatformView() => new FakeNativeLayoutView(); + protected override FakeNativeLayoutView CreatePlatformView() => +#if MONOANDROID + new FakeNativeLayoutView(Context); +#else + new FakeNativeLayoutView(); +#endif public void Add(IView view) { if (GetNativeChild(view) is FakeNativeView child) { - PlatformView.Children.Add(child); + PlatformView.FakeChildren.Add(child); } } @@ -55,17 +60,17 @@ public void Remove(IView view) { if (view.Handler?.PlatformView is FakeNativeView child) { - PlatformView.Children.Remove(child); + PlatformView.FakeChildren.Remove(child); } } - public void Clear() => PlatformView.Children.Clear(); + public void Clear() => PlatformView.FakeChildren.Clear(); public void Insert(int index, IView view) { if (GetNativeChild(view) is FakeNativeView child) { - PlatformView.Children.Insert(index, child); + PlatformView.FakeChildren.Insert(index, child); } } @@ -73,7 +78,7 @@ public void Update(int index, IView view) { if (GetNativeChild(view) is FakeNativeView child) { - PlatformView.Children[index] = child; + PlatformView.FakeChildren[index] = child; } } @@ -81,7 +86,7 @@ public void UpdateZIndex(IView view) { if (view.Handler?.PlatformView is FakeNativeView child) { - List children = PlatformView.Children; + List children = PlatformView.FakeChildren; children.Remove(child); children.Insert(GetClampedZIndex(view, children.Count), child); } diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.Android.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.Android.cs new file mode 100644 index 000000000000..994515d5ad0d --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeViews.Android.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using Android.Content; +using Android.Views; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Android variant of the external platform's native view type. + /// + /// + /// On a platform target framework, + /// constrains TPlatformView to the platform's own base view type — here + /// Android.Views.View. A real external backend's views satisfy that too. What makes it + /// an external backend is that its concrete types are its own, and therefore are not the + /// types the aliased handler interfaces are pinned to (AppCompatTextView for + /// ILabelHandler on Android). That mismatch is what produces CS0738. + /// + public class FakeNativeView : View + { + public FakeNativeView(Context context) + : base(context) + { + } + + public List FakeChildren { get; } = new List(); + + public double FakeOpacity { get; set; } = 1; + } + + /// Native label type for the fake external platform. + public class FakeNativeLabel : FakeNativeView + { + public FakeNativeLabel(Context context) + : base(context) + { + } + + public string? FakeText { get; set; } + } + + /// Native content-host type for the fake external platform. + public class FakeNativeContentView : FakeNativeView + { + public FakeNativeContentView(Context context) + : base(context) + { + } + + public FakeNativeView? FakeContent { get; set; } + } + + /// Native layout container type for the fake external platform. + public class FakeNativeLayoutView : FakeNativeView + { + public FakeNativeLayoutView(Context context) + : base(context) + { + } + } +} diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.Standard.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.Standard.cs new file mode 100644 index 000000000000..00cdc756723d --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeViews.Standard.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Stands in for the native view type of a platform .NET MAUI knows nothing about, on the + /// platform-neutral target framework. + /// + /// + /// + /// Deliberately does not derive from, or reference, any .NET MAUI type. This is the whole point of + /// the test assembly: a backend's native types are its own. + /// + /// + /// On the platform-neutral target framework, + /// constrains TPlatformView only to class, so a completely unrelated type is legal. + /// The platform variants of this file derive from the platform's own base view type, because that + /// is what the constraint requires there. + /// + /// + /// Members are prefixed Fake so that the same member names are usable on every target + /// framework without colliding with a real platform base type's members (for example + /// FrameworkElement.Opacity on Windows). + /// + /// + public class FakeNativeView + { + public List FakeChildren { get; } = new List(); + + public double FakeOpacity { get; set; } = 1; + } + + /// Native label type for the fake external platform. + public class FakeNativeLabel : FakeNativeView + { + public string? FakeText { get; set; } + } + + /// Native content-host type for the fake external platform. + public class FakeNativeContentView : FakeNativeView + { + public FakeNativeView? FakeContent { get; set; } + } + + /// Native layout container type for the fake external platform. + public class FakeNativeLayoutView : FakeNativeView + { + } +} diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.Windows.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.Windows.cs new file mode 100644 index 000000000000..a1b31dd4d90c --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeViews.Windows.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using Microsoft.UI.Xaml.Controls; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Windows variant of the external platform's native view type. + /// + /// + /// On a platform target framework, + /// constrains TPlatformView to the platform's own base view type — here + /// Microsoft.UI.Xaml.FrameworkElement. This derives from Microsoft.UI.Xaml.Controls.Panel, which satisfies + /// that constraint and is the same base .NET MAUI's own ContentPanel and LayoutPanel + /// derive from. What makes it an external backend is that its concrete types are its own, + /// and therefore are not the types the aliased handler interfaces are pinned to (TextBlock + /// for ILabelHandler on Windows). That mismatch is what produces CS0738. + /// + public class FakeNativeView : Panel + { + public List FakeChildren { get; } = new List(); + + public double FakeOpacity { get; set; } = 1; + } + + /// Native label type for the fake external platform. + public class FakeNativeLabel : FakeNativeView + { + public string? FakeText { get; set; } + } + + /// Native content-host type for the fake external platform. + public class FakeNativeContentView : FakeNativeView + { + public FakeNativeView? FakeContent { get; set; } + } + + /// Native layout container type for the fake external platform. + public class FakeNativeLayoutView : FakeNativeView + { + } +} diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.cs deleted file mode 100644 index 5343c429888b..000000000000 --- a/src/Core/tests/ExternalBackend/FakeNativeViews.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Collections.Generic; - -namespace Microsoft.Maui.ExternalBackend -{ - /// - /// Stands in for the native view type of a platform .NET MAUI knows nothing about. - /// - /// - /// Deliberately does not derive from, or reference, any .NET MAUI type. This is the whole point of - /// the test assembly: a backend's native types are its own. - /// - public class FakeNativeView - { - public List Children { get; } = new List(); - - public double Opacity { get; set; } = 1; - } - - /// Native label type for the fake external platform. - public class FakeNativeLabel : FakeNativeView - { - public string? Text { get; set; } - } - - /// Native content-host type for the fake external platform. - public class FakeNativeContentView : FakeNativeView - { - public FakeNativeView? Content { get; set; } - } - - /// Native layout container type for the fake external platform. - public class FakeNativeLayoutView : FakeNativeView - { - } - - /// Native window type for the fake external platform. Not even a view. - public class FakeNativeWindow - { - public string? Title { get; set; } - - public FakeNativeView? Content { get; set; } - } -} diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.iOS.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.iOS.cs new file mode 100644 index 000000000000..06471a287281 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeViews.iOS.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using UIKit; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// iOS and Mac Catalyst variant of the external platform's native view type. + /// + /// + /// On a platform target framework, + /// constrains TPlatformView to the platform's own base view type — here + /// UIKit.UIView. A real external backend's views satisfy that too. What makes it an + /// external backend is that its concrete types are its own, and therefore are not the types + /// the aliased handler interfaces are pinned to (MauiLabel for ILabelHandler on iOS). + /// That mismatch is what produces CS0738. + /// + public class FakeNativeView : UIView + { + public List FakeChildren { get; } = new List(); + + public double FakeOpacity { get; set; } = 1; + } + + /// Native label type for the fake external platform. + public class FakeNativeLabel : FakeNativeView + { + public string? FakeText { get; set; } + } + + /// Native content-host type for the fake external platform. + public class FakeNativeContentView : FakeNativeView + { + public FakeNativeView? FakeContent { get; set; } + } + + /// Native layout container type for the fake external platform. + public class FakeNativeLayoutView : FakeNativeView + { + } +} diff --git a/src/Core/tests/ExternalBackend/FakeNativeWindow.cs b/src/Core/tests/ExternalBackend/FakeNativeWindow.cs new file mode 100644 index 000000000000..13e003818513 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeWindow.cs @@ -0,0 +1,18 @@ +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Native window type for the fake external platform. Not a view, and not related to any platform + /// type on any target framework. + /// + /// + /// constrains + /// TPlatformView only to class on every target framework, so this single definition + /// works everywhere — unlike the view types, which must satisfy the platform's base view constraint. + /// + public class FakeNativeWindow + { + public string? FakeTitle { get; set; } + + public object? FakeContent { get; set; } + } +} diff --git a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs index 5fdcd8627c2f..db6d6a234bda 100644 --- a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs +++ b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs @@ -168,12 +168,12 @@ public void ExternalHandlerPropertyMapperUpdatesNativeView() var handler = (FakeLabelHandler)label.ToHandler(context); - Assert.Equal("hello", handler.PlatformView.Text); + Assert.Equal("hello", handler.PlatformView.FakeText); label.Text = "goodbye"; handler.UpdateValue(nameof(ILabel.Text)); - Assert.Equal("goodbye", handler.PlatformView.Text); + Assert.Equal("goodbye", handler.PlatformView.FakeText); } [Fact] @@ -185,7 +185,7 @@ public void ExternalHandlerInheritsViewMapperFromCore() var handler = (FakeLabelHandler)label.ToHandler(context); // Opacity is chained off Core's ViewMapper, proving mapper composition still works. - Assert.Equal(0.5, handler.PlatformView.Opacity); + Assert.Equal(0.5, handler.PlatformView.FakeOpacity); } [Fact] @@ -212,20 +212,20 @@ public void ControlsLayoutCommandsReachExternalLayoutHandler() layout.Add(new Label { Text = "first" }); layout.Add(new Label { Text = "second" }); - Assert.Equal(2, handler.PlatformView.Children.Count); + Assert.Equal(2, handler.PlatformView.FakeChildren.Count); layout.Insert(0, new Label { Text = "inserted" }); - Assert.Equal(3, handler.PlatformView.Children.Count); - Assert.Equal("inserted", Assert.IsType(handler.PlatformView.Children[0]).Text); + Assert.Equal(3, handler.PlatformView.FakeChildren.Count); + Assert.Equal("inserted", Assert.IsType(handler.PlatformView.FakeChildren[0]).FakeText); layout.RemoveAt(0); - Assert.Equal(2, handler.PlatformView.Children.Count); + Assert.Equal(2, handler.PlatformView.FakeChildren.Count); layout[0] = new Label { Text = "replaced" }; - Assert.Equal("replaced", Assert.IsType(handler.PlatformView.Children[0]).Text); + Assert.Equal("replaced", Assert.IsType(handler.PlatformView.FakeChildren[0]).FakeText); layout.Clear(); - Assert.Empty(handler.PlatformView.Children); + Assert.Empty(handler.PlatformView.FakeChildren); } [Fact] @@ -243,10 +243,10 @@ public void ExternalLayoutHandlerIsDrivenThroughNeutralContract() neutral.Add(child); var platformView = Assert.IsType(neutral.PlatformView); - Assert.Single(platformView.Children); + Assert.Single(platformView.FakeChildren); neutral.Clear(); - Assert.Empty(platformView.Children); + Assert.Empty(platformView.FakeChildren); } [Fact] @@ -257,7 +257,7 @@ public void ExternalWindowHandlerRunsThroughElementMapper() var handler = (FakeWindowHandler)((IElement)window).ToHandler(context); - Assert.Equal("external", handler.PlatformView.Title); + Assert.Equal("external", handler.PlatformView.FakeTitle); IElementHandler neutral = handler; From 581c8f426fdf71137c3a315f654dde7639b48406 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 01:57:13 -0400 Subject: [PATCH 4/7] Mirror Core's full target framework list in the external-backend guard The guard assembly only proves what it is compiled against, so a target framework Microsoft.Maui.Core ships but the guard does not compile is an untested target framework - and the gap is silent. Two such gaps existed: * netstandard2.0 and netstandard2.1 were missing entirely, even though Core ships both and the aliased interfaces resolve PlatformView to a non-nullable System.Object there, exactly as on the neutral TFM. * Tizen reached the guard through $(MauiPlatforms), so when IncludeTizenTargetFrameworks is turned back on the guard would evaluate a Tizen target with no FakeNativeView/FakeNativeLabel/FakeNativeContentView/ FakeNativeLayoutView definitions and simply fail to compile. TargetFrameworks now mirrors Core's exactly: netstandard2.1;netstandard2.0;$(_MauiDotNetTfm);$(MauiPlatforms) Adds FakeNativeViews.Tizen.cs, deriving from the Tizen platform SDK's own Tizen.NUI.BaseComponents.View - which is what ViewHandler<,> constrains TPlatformView to on Tizen - rather than from Tizen.UIExtensions.NUI.ViewGroup, which is what MAUI's in-box Tizen views use. An external backend depends on the platform SDK, not on MAUI's platform helper packages, and that is precisely why the aliased interfaces are unimplementable there. Tizen is therefore gated only by the unavailable workload, never by missing source. Adds ExternalBackendTargetFrameworkTests, which reads both project files and compares the raw TargetFrameworks expressions. Comparing the expressions rather than the expanded lists is deliberate: both sides expand the same $(MauiPlatforms), so the platform set - including whether Tizen is enabled - cannot drift between them. It also asserts a fake-native-view source exists for every platform. Both guards were verified to fail when the drift they detect is injected. Documents the handler lifecycle consequence of the typed contracts: the typed PlatformView is non-nullable and throws when the handler is disconnected (ElementHandler.DisconnectHandler nulls PlatformView before invoking the disconnect callback), so teardown paths should read the nullable IElementHandler.PlatformView instead. Pre-existing behavior, not changed here. No product code changes: Microsoft.Maui and its PublicAPI files are untouched. Verified locally: netstandard2.0, netstandard2.1, net11.0, net11.0-android37.0, net11.0-ios26.5 and net11.0-maccatalyst26.5 all build clean with TreatWarningsAsErrors; the 8 new guard tests pass. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/design/ExternalPlatformBackends.md | 69 +++++++-- .../Core.ExternalBackend.csproj | 14 +- .../ExternalBackend/FakeNativeViews.Tizen.cs | 49 +++++++ .../ExternalBackendTargetFrameworkTests.cs | 131 ++++++++++++++++++ 4 files changed, 248 insertions(+), 15 deletions(-) create mode 100644 src/Core/tests/ExternalBackend/FakeNativeViews.Tizen.cs create mode 100644 src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs diff --git a/docs/design/ExternalPlatformBackends.md b/docs/design/ExternalPlatformBackends.md index e1d88beabfde..f767ce527dd5 100644 --- a/docs/design/ExternalPlatformBackends.md +++ b/docs/design/ExternalPlatformBackends.md @@ -181,6 +181,42 @@ Binary compatibility was verified by compiling handlers against change: derived handlers, explicit-interface-implementation handlers, and all existing `is`/cast relationships continue to work with no `TypeLoadException`. +### Handler lifecycle and `PlatformView` nullability + +`IElementHandler.PlatformView` is `object?`, but +`IElementHandler.PlatformView` is non-nullable `TPlatformView`, matching the +existing non-nullable `ElementHandler<,>.PlatformView` / `ViewHandler<,>.PlatformView` properties it is +satisfied by. Those properties **throw** rather than return `null` when the handler is not connected: + +```csharp +public new TPlatformView PlatformView +{ + get => (TPlatformView?)base.PlatformView + ?? throw new InvalidOperationException($"PlatformView cannot be null here"); + ... +} +``` + +That is pre-existing behavior and is deliberately not changed here, but it has a consequence worth +knowing when consuming the typed contracts: a handler is only guaranteed to have a `PlatformView` +between `SetVirtualView` and `DisconnectHandler`. `DisconnectHandler` clears `PlatformView` before +invoking the disconnect callback, so reading `PlatformView` through a typed contract after disconnect +throws. + +For code that may run outside a connected window — teardown paths, weak-reference caches, diagnostics — +prefer the nullable base member, which never throws: + +```csharp +// Safe at any point in the lifecycle. +if (handler.PlatformView is FakeNativeLabel nativeLabel) { /* ... */ } + +// Only safe while the handler is connected. +FakeNativeLabel nativeLabel = typedHandler.PlatformView; +``` + +Property and command mappers always run while the handler is connected, so mapper code can use the +typed member freely — which is what the in-box handlers and the tests here do. + ## Adopting this from an external backend An external backend derives from the public generic handler base classes and stops trying to implement @@ -273,25 +309,40 @@ builder.ConfigureMauiHandlers(handlers => handlers for label, content view, layout and window, so everything it compiles is provably public API and provably warning-free for an external consumer. -It **multi-targets every target framework Core ships** — the platform-neutral one plus each platform TFM -— because the failure it guards against is target-framework specific: `CS9333`/`CS8766` on the neutral -TFM, `CS0738` on the platform TFMs. Compiling the same external-backend sources against all of them is -the only way to prove the contracts close the gap everywhere. - -The fake native view types are therefore per-platform, because +It **mirrors `Microsoft.Maui.Core`'s own `TargetFrameworks` exactly** — +`netstandard2.1;netstandard2.0;$(_MauiDotNetTfm);$(MauiPlatforms)` — because the failure it guards +against is target-framework specific: `CS9333`/`CS8766` on the platform-neutral and netstandard TFMs, +`CS0738` on the platform TFMs. A target framework Core ships but the guard project does not compile +would be an untested target framework, and the gap would be silent. + +Both projects expand the same `$(MauiPlatforms)`, so the platform set — **including whether Tizen is +enabled** — cannot drift between them. Tizen is currently absent from real builds only because +`IncludeTizenTargetFrameworks` is off repo-wide, **not** because the guard project lacks sources for it: +`FakeNativeViews.Tizen.cs` exists and derives from `Tizen.NUI.BaseComponents.View`, so the matrix builds +the moment the workload is re-enabled. `ExternalBackendTargetFrameworkTests` enforces all of this — it +compares the two `TargetFrameworks` expressions directly and asserts a fake-native-view source exists for +every platform. + +The fake native view types are per-platform, because `ViewHandler` constrains `TPlatformView` differently per TFM: | Target framework | `ViewHandler<,>` constraint on `TPlatformView` | Fake native view derives from | | --- | --- | --- | -| `net11.0` (neutral) | `class` | *(nothing)* | +| `netstandard2.0`, `netstandard2.1`, `net11.0` | `class` | *(nothing)* | | `net11.0-android` | `Android.Views.View` | `Android.Views.View` | | `net11.0-ios`, `net11.0-maccatalyst` | `UIKit.UIView` | `UIKit.UIView` | | `net11.0-windows` | `Microsoft.UI.Xaml.FrameworkElement` | `Microsoft.UI.Xaml.Controls.Panel` | +| `net11.0-tizen` *(gated off)* | `Tizen.NUI.BaseComponents.View` | `Tizen.NUI.BaseComponents.View` | This mirrors reality: a real external backend's views *do* derive from the platform's base view type. What makes it external is that its **concrete** types are its own, and so are never the types the aliased -interfaces are pinned to (`MauiLabel`, `AppCompatTextView`, `TextBlock`) — which is exactly what produces -`CS0738`. `ElementHandler<,>` constrains `TPlatformView` only to `class` on every TFM, so the fake native +interfaces are pinned to (`MauiLabel`, `AppCompatTextView`, `TextBlock`, +`Tizen.UIExtensions.NUI.Label`) — which is exactly what produces `CS0738`. Note the Tizen fake derives +from the platform SDK's own `Tizen.NUI.BaseComponents.View` rather than from +`Tizen.UIExtensions.NUI.ViewGroup`, which is what .NET MAUI's in-box Tizen views use: an external backend +depends on the platform SDK, not on .NET MAUI's platform helper packages. + +`ElementHandler<,>` constrains `TPlatformView` only to `class` on every TFM, so the fake native *window* type is a single definition shared across all of them. Fake members are prefixed `Fake` (`FakeText`, `FakeOpacity`, `FakeChildren`) so the same handler sources diff --git a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj index c07dd3c5b66e..3043e353e7a0 100644 --- a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj +++ b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj @@ -2,18 +2,20 @@ - $(_MauiDotNetTfm);$(MauiPlatforms) + netstandard2.1;netstandard2.0;$(_MauiDotNetTfm);$(MauiPlatforms) Microsoft.Maui.Core.ExternalBackend.TestAssembly Microsoft.Maui.ExternalBackend false diff --git a/src/Core/tests/ExternalBackend/FakeNativeViews.Tizen.cs b/src/Core/tests/ExternalBackend/FakeNativeViews.Tizen.cs new file mode 100644 index 000000000000..24614d10f3c3 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeNativeViews.Tizen.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using Tizen.NUI.BaseComponents; + +namespace Microsoft.Maui.ExternalBackend +{ + /// + /// Tizen variant of the external platform's native view type. + /// + /// + /// + /// On a platform target framework, + /// constrains TPlatformView to the platform's own base view type — here + /// Tizen.NUI.BaseComponents.View, which comes from the Tizen platform SDK itself. + /// + /// + /// Deliberately does not derive from Tizen.UIExtensions.NUI.ViewGroup, which is what + /// .NET MAUI's own in-box Tizen views derive from. An external backend takes a dependency on the + /// platform SDK, not on .NET MAUI's platform helper packages — and that is exactly the situation + /// these contracts have to support. It is also why the aliased interfaces are unimplementable here: + /// on Tizen ILayoutHandler.PlatformView is pinned to + /// Microsoft.Maui.Platform.LayoutViewGroup and ILabelHandler.PlatformView to + /// Tizen.UIExtensions.NUI.Label — .NET MAUI's types, not the backend's. That mismatch is what + /// produces CS0738. + /// + /// + public class FakeNativeView : View + { + public List FakeChildren { get; } = new List(); + + public double FakeOpacity { get; set; } = 1; + } + + /// Native label type for the fake external platform. + public class FakeNativeLabel : FakeNativeView + { + public string? FakeText { get; set; } + } + + /// Native content-host type for the fake external platform. + public class FakeNativeContentView : FakeNativeView + { + public FakeNativeView? FakeContent { get; set; } + } + + /// Native layout container type for the fake external platform. + public class FakeNativeLayoutView : FakeNativeView + { + } +} diff --git a/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs new file mode 100644 index 000000000000..9c6d53ab5e50 --- /dev/null +++ b/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs @@ -0,0 +1,131 @@ +using System; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Xml.Linq; +using Xunit; + +namespace Microsoft.Maui.UnitTests.Handlers +{ + /// + /// Guards the external-backend test assembly against target-framework drift. + /// + /// + /// + /// Core.ExternalBackend only proves what it is compiled against. The failure it guards is + /// target-framework specific — CS0738 on a platform target framework, CS9333/ + /// CS8766 on the platform-neutral and netstandard ones — so a target framework that + /// Microsoft.Maui.Core ships but the guard project does not compile is an untested target + /// framework, and the gap would be silent. + /// + /// + /// These tests read both project files and compare them directly, so adding a target framework to + /// Core without adding it here fails the build rather than quietly reducing coverage. + /// + /// + [Category(TestCategory.Core)] + public class ExternalBackendTargetFrameworkTests + { + const string CoreProjectPath = "src/Core/src/Core.csproj"; + const string ExternalBackendProjectPath = "src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj"; + + [Fact] + public void ExternalBackendMirrorsCoreTargetFrameworks() + { + var core = ReadTargetFrameworks(CoreProjectPath); + var externalBackend = ReadTargetFrameworks(ExternalBackendProjectPath); + + // Compared as the raw MSBuild expression on purpose. Both sides expand the same + // $(MauiPlatforms), so keeping the expressions identical is what makes the platform set - + // including whether Tizen is currently enabled - impossible to drift between the two. + Assert.Equal(core, externalBackend); + } + + [Fact] + public void ExternalBackendCompilesNetStandardTargetFrameworks() + { + var externalBackend = ReadTargetFrameworks(ExternalBackendProjectPath); + + Assert.Contains("netstandard2.0", externalBackend, StringComparison.Ordinal); + Assert.Contains("netstandard2.1", externalBackend, StringComparison.Ordinal); + } + + [Fact] + public void ExternalBackendInheritsThePlatformSetFromMauiPlatforms() + { + var externalBackend = ReadTargetFrameworks(ExternalBackendProjectPath); + + // Every platform target framework - Android, iOS, Mac Catalyst, Windows and Tizen - reaches + // both projects through this one property. Tizen is therefore gated purely by + // IncludeTizenTargetFrameworks, identically for Core and for this guard project. + Assert.Contains("$(MauiPlatforms)", externalBackend, StringComparison.Ordinal); + } + + [Theory] + [InlineData("FakeNativeViews.Standard.cs")] + [InlineData("FakeNativeViews.Android.cs")] + [InlineData("FakeNativeViews.iOS.cs")] + [InlineData("FakeNativeViews.Windows.cs")] + [InlineData("FakeNativeViews.Tizen.cs")] + public void EveryPlatformHasFakeNativeViewSources(string fileName) + { + // MultiTargeting.targets selects these by file suffix. A platform that is in the target + // framework list but has no sources would fail to compile the moment it is enabled, so the + // sources exist for every platform - including Tizen, which is currently gated off by + // IncludeTizenTargetFrameworks rather than by missing source. + var path = Path.Combine(RepoRoot, "src", "Core", "tests", "ExternalBackend", fileName); + + Assert.True(File.Exists(path), $"Missing external-backend platform source: {fileName}"); + + var source = File.ReadAllText(path); + + foreach (var type in new[] { "FakeNativeView", "FakeNativeLabel", "FakeNativeContentView", "FakeNativeLayoutView" }) + { + Assert.Contains($"class {type}", source, StringComparison.Ordinal); + } + } + + static string ReadTargetFrameworks(string relativeProjectPath) + { + var path = Path.Combine(RepoRoot, relativeProjectPath.Replace('/', Path.DirectorySeparatorChar)); + + Assert.True(File.Exists(path), $"Could not find project: {relativeProjectPath}"); + + var project = XDocument.Load(path); + + // The unconditioned TargetFrameworks element. Core also has a second, conditioned one for + // IncludePreviousTfms, which is not part of the shipping set. + var targetFrameworks = project + .Descendants() + .Where(e => e.Name.LocalName == "TargetFrameworks" && e.Attribute("Condition") is null) + .Select(e => e.Value.Trim()) + .ToList(); + + Assert.Single(targetFrameworks); + + return targetFrameworks[0]; + } + + static string RepoRoot => FindRepoRoot(GetSourceDirectory()); + + static string FindRepoRoot(string start) + { + var directory = new DirectoryInfo(start); + + while (directory is not null) + { + if (File.Exists(Path.Combine(directory.FullName, "Microsoft.Maui.sln"))) + { + return directory.FullName; + } + + directory = directory.Parent; + } + + throw new InvalidOperationException($"Could not locate the repository root above '{start}'."); + } + + static string GetSourceDirectory([CallerFilePath] string filePath = "") => + Path.GetDirectoryName(filePath) ?? throw new InvalidOperationException("Could not resolve the test source directory."); + } +} From 669f90b15a6abb464b678ded843afb0ffcca2ec2 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 03:05:47 -0400 Subject: [PATCH 5/7] Make the target framework drift guard hermetic for Helix ExternalBackendTargetFrameworkTests read Core.csproj, Core.ExternalBackend.csproj and the FakeNativeViews.*.cs sources from the working tree, locating the repository root by walking up from [CallerFilePath]. Unit tests run on Helix from a payload directory with no repository on disk, so all 8 tests failed there: System.InvalidOperationException : Could not locate the repository root above '\_\src\Core\tests\UnitTests\Handlers'. That failed Microsoft.Maui.UnitTests.dll with exit code 1 on all four Helix queues (osx.15.arm64 and windows.10.amd64, Debug and Release) - deterministically, and only that assembly. Caught on build 1569779. Embeds the project files and the per-platform fake-native-view sources into the test assembly at build time instead. Embedding still captures the live files on every build, so genuine drift is still detected - verified by re-injecting the netstandard drift after the rewrite and confirming the same two tests fail. Being hermetic also makes the guard meaningful where it actually runs: Helix is where these unit tests execute in CI, so a repository-dependent assertion would have been either red or skipped there, never useful. Verified by copying the built test assembly to a directory with no repository above it - simulating the Helix payload layout - where all 8 tests pass. All 26 external-backend tests (18 behavior + 8 guard) pass locally. No product code changes: Microsoft.Maui and its PublicAPI files are untouched. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/UnitTests/Core.UnitTests.csproj | 13 ++++ .../ExternalBackendTargetFrameworkTests.cs | 67 ++++++++----------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/Core/tests/UnitTests/Core.UnitTests.csproj b/src/Core/tests/UnitTests/Core.UnitTests.csproj index 1c834d31c150..dc9eafbaef82 100644 --- a/src/Core/tests/UnitTests/Core.UnitTests.csproj +++ b/src/Core/tests/UnitTests/Core.UnitTests.csproj @@ -16,6 +16,19 @@ + + + + + + + diff --git a/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs index 9c6d53ab5e50..7a5258a10d57 100644 --- a/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs +++ b/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; using System.Linq; -using System.Runtime.CompilerServices; +using System.Reflection; using System.Xml.Linq; using Xunit; @@ -19,32 +19,34 @@ namespace Microsoft.Maui.UnitTests.Handlers /// framework, and the gap would be silent. /// /// - /// These tests read both project files and compare them directly, so adding a target framework to - /// Core without adding it here fails the build rather than quietly reducing coverage. + /// The inputs are embedded into this assembly at build time (see the EmbeddedResource items in + /// Core.UnitTests.csproj) rather than read from the working tree, because unit tests run on Helix + /// from a payload directory with no repository on disk. Embedding still captures the live files on + /// every build, so real drift is caught, and the assertion is hermetic wherever it runs. /// /// [Category(TestCategory.Core)] public class ExternalBackendTargetFrameworkTests { - const string CoreProjectPath = "src/Core/src/Core.csproj"; - const string ExternalBackendProjectPath = "src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj"; + const string CoreProject = "ProjectFiles/Core.csproj"; + const string ExternalBackendProject = "ProjectFiles/Core.ExternalBackend.csproj"; [Fact] public void ExternalBackendMirrorsCoreTargetFrameworks() { - var core = ReadTargetFrameworks(CoreProjectPath); - var externalBackend = ReadTargetFrameworks(ExternalBackendProjectPath); + var core = ReadTargetFrameworks(CoreProject); + var externalBackend = ReadTargetFrameworks(ExternalBackendProject); // Compared as the raw MSBuild expression on purpose. Both sides expand the same - // $(MauiPlatforms), so keeping the expressions identical is what makes the platform set - - // including whether Tizen is currently enabled - impossible to drift between the two. + // $(MauiPlatforms), so keeping the expressions identical is what makes the platform set — + // including whether Tizen is currently enabled — impossible to drift between the two. Assert.Equal(core, externalBackend); } [Fact] public void ExternalBackendCompilesNetStandardTargetFrameworks() { - var externalBackend = ReadTargetFrameworks(ExternalBackendProjectPath); + var externalBackend = ReadTargetFrameworks(ExternalBackendProject); Assert.Contains("netstandard2.0", externalBackend, StringComparison.Ordinal); Assert.Contains("netstandard2.1", externalBackend, StringComparison.Ordinal); @@ -53,9 +55,9 @@ public void ExternalBackendCompilesNetStandardTargetFrameworks() [Fact] public void ExternalBackendInheritsThePlatformSetFromMauiPlatforms() { - var externalBackend = ReadTargetFrameworks(ExternalBackendProjectPath); + var externalBackend = ReadTargetFrameworks(ExternalBackendProject); - // Every platform target framework - Android, iOS, Mac Catalyst, Windows and Tizen - reaches + // Every platform target framework — Android, iOS, Mac Catalyst, Windows and Tizen — reaches // both projects through this one property. Tizen is therefore gated purely by // IncludeTizenTargetFrameworks, identically for Core and for this guard project. Assert.Contains("$(MauiPlatforms)", externalBackend, StringComparison.Ordinal); @@ -71,13 +73,9 @@ public void EveryPlatformHasFakeNativeViewSources(string fileName) { // MultiTargeting.targets selects these by file suffix. A platform that is in the target // framework list but has no sources would fail to compile the moment it is enabled, so the - // sources exist for every platform - including Tizen, which is currently gated off by + // sources exist for every platform — including Tizen, which is currently gated off by // IncludeTizenTargetFrameworks rather than by missing source. - var path = Path.Combine(RepoRoot, "src", "Core", "tests", "ExternalBackend", fileName); - - Assert.True(File.Exists(path), $"Missing external-backend platform source: {fileName}"); - - var source = File.ReadAllText(path); + var source = ReadEmbeddedText($"ProjectFiles/{fileName}"); foreach (var type in new[] { "FakeNativeView", "FakeNativeLabel", "FakeNativeContentView", "FakeNativeLayoutView" }) { @@ -85,13 +83,9 @@ public void EveryPlatformHasFakeNativeViewSources(string fileName) } } - static string ReadTargetFrameworks(string relativeProjectPath) + static string ReadTargetFrameworks(string resourceName) { - var path = Path.Combine(RepoRoot, relativeProjectPath.Replace('/', Path.DirectorySeparatorChar)); - - Assert.True(File.Exists(path), $"Could not find project: {relativeProjectPath}"); - - var project = XDocument.Load(path); + var project = XDocument.Parse(ReadEmbeddedText(resourceName)); // The unconditioned TargetFrameworks element. Core also has a second, conditioned one for // IncludePreviousTfms, which is not part of the shipping set. @@ -106,26 +100,19 @@ static string ReadTargetFrameworks(string relativeProjectPath) return targetFrameworks[0]; } - static string RepoRoot => FindRepoRoot(GetSourceDirectory()); - - static string FindRepoRoot(string start) + static string ReadEmbeddedText(string resourceName) { - var directory = new DirectoryInfo(start); + var assembly = typeof(ExternalBackendTargetFrameworkTests).Assembly; - while (directory is not null) - { - if (File.Exists(Path.Combine(directory.FullName, "Microsoft.Maui.sln"))) - { - return directory.FullName; - } + using var stream = assembly.GetManifestResourceStream(resourceName); - directory = directory.Parent; - } + Assert.True( + stream is not null, + $"Missing embedded resource '{resourceName}'. Available: {string.Join(", ", assembly.GetManifestResourceNames())}"); - throw new InvalidOperationException($"Could not locate the repository root above '{start}'."); - } + using var reader = new StreamReader(stream!); - static string GetSourceDirectory([CallerFilePath] string filePath = "") => - Path.GetDirectoryName(filePath) ?? throw new InvalidOperationException("Could not resolve the test source directory."); + return reader.ReadToEnd(); + } } } From 5d65992a2621f82cb0044890475aa1dbf1f7b685 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 09:12:09 -0400 Subject: [PATCH 6/7] Address remaining review threads: lifecycle docs, interop docs, test polish Four review findings, no API redesign. Microsoft.Maui's PublicAPI files are unchanged - the product edits are XML documentation only. (A) Typed VirtualView/PlatformView throw while disconnected. IElementHandler<,>.VirtualView/PlatformView are non-nullable, matching the non-nullable properties on ElementHandler<,>/ViewHandler<,> that satisfy them - and those throw InvalidOperationException rather than returning null once the handler is disconnected, because DisconnectHandler clears the platform view before invoking the disconnect callback. The inherited IElementHandler members return null in that state and never throw. The blocks demonstrated the unguarded pattern, which would convert a caller's null check into an exception path during a lifecycle transition. They now guard on the nullable IElementHandler.PlatformView first, and the behavior is documented on the interfaces and on each member. (B) How Controls actually reaches a layout handler. Microsoft.Maui.Controls.Layout does not cast to either layout interface - it raises Add/Remove/Clear/Insert/Update/UpdateZIndex as command mapper keys via Handler.Invoke(nameof(ILayoutHandler.Add), ...). That dispatch is type-agnostic and reaches an external backend exactly as it reaches the in-box handler, which is what ControlsLayoutCommandsReachExternalLayoutHandler already proves. Documents the one real gap: the obsolete Compatibility.Layout.LayoutHandler property evaluates `Handler as ILayoutHandler` and so returns null for a handler implementing only the generic interface. It is the sole remaining runtime cast to ILayoutHandler in MAUI, nothing in-box reads it, and its declaring type is [Obsolete], so layout behavior is unaffected. Converting a shipped public property's semantics is a separable decision and is deliberately out of scope here. (C) FakeLayoutHandler no longer uses MauiContext!. The null-forgiving operator would have turned a missing context into a bare NullReferenceException. Since this assembly models good external-backend practice, it now throws an actionable InvalidOperationException naming the type and the required SetMauiContext call. (D) ExternalHandlerCannotImplementAliasedInterface renamed. The name implied a compile-time restriction while the body asserts runtime non-implementation. Renamed to ExternalHandlerDoesNotImplementAliasedInterface, with a comment pointing at where the compile-time half is actually proven: the Core.ExternalBackend assembly, across every target framework Core ships. Verified: Core net11.0 builds with PublicApiType=Validate and zero PublicAPI diff; Core.ExternalBackend builds clean on netstandard2.0, netstandard2.1, net11.0 and net11.0-android37.0 with TreatWarningsAsErrors; all 26 external-backend tests pass, the 8 guard tests still pass from a repo-less directory, and Controls.Core.UnitTests is 6207 passed / 0 failed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/design/ExternalPlatformBackends.md | 32 +++++++++++++++++++ src/Core/src/Handlers/IElementHandlerOfT.cs | 31 ++++++++++++++++-- src/Core/src/Handlers/IViewHandlerOfT.cs | 19 +++++++++-- .../src/Handlers/Layout/ILayoutHandlerOfT.cs | 19 +++++++++++ .../ExternalBackend/FakeLayoutHandler.cs | 16 ++++++++-- .../Handlers/ExternalPlatformBackendTests.cs | 9 ++++-- 6 files changed, 115 insertions(+), 11 deletions(-) diff --git a/docs/design/ExternalPlatformBackends.md b/docs/design/ExternalPlatformBackends.md index f767ce527dd5..f4ac966f18f0 100644 --- a/docs/design/ExternalPlatformBackends.md +++ b/docs/design/ExternalPlatformBackends.md @@ -176,6 +176,38 @@ else if (handler is ILayoutHandler legacy) } ``` +### How Controls reaches a layout handler + +`Microsoft.Maui.Controls.Layout` does **not** cast to either layout interface. It raises the +child-management operations as **command mapper keys**: + +```csharp +// src/Controls/src/Core/Layout/Layout.cs +Handler?.Invoke(nameof(ILayoutHandler.Add), new LayoutHandlerUpdate(index, view)); +Handler?.Invoke(nameof(ILayoutHandler.Clear)); +``` + +That dispatch is type-agnostic, so it reaches an external backend's handler exactly as it reaches the +in-box one. Referencing `ILayoutHandler` for its member *names* via `nameof` is always allowed — only +*implementing* it is blocked — so an external backend should register those same key strings in its +command mapper, and Controls interop keeps working unchanged. This is what +`ControlsLayoutCommandsReachExternalLayoutHandler` verifies end to end. + +**One known gap.** The obsolete `Microsoft.Maui.Controls.Compatibility.Layout.LayoutHandler` property +is declared as `ILayoutHandler` and evaluates `Handler as ILayoutHandler`, so it returns `null` for a +handler that implements only `ILayoutHandler`: + +```csharp +// src/Controls/src/Core/LegacyLayouts/Layout.cs:35 +public ILayoutHandler LayoutHandler => Handler as ILayoutHandler; +``` + +This is the **only** remaining runtime cast to `ILayoutHandler` in .NET MAUI. It is a public convenience +property that no in-box code path reads, and its declaring type carries `[Obsolete]`, so it does not +affect layout behavior for an external backend. It is documented here because for that one legacy +property, `ILayoutHandler` is a compile-time contract only. Converting it was deliberately +left out of scope: changing a shipped public property's semantics is a larger, separable decision. + Binary compatibility was verified by compiling handlers against `Microsoft.Maui.Core 11.0.0-preview.7.26406.9` and loading them against a build that includes this change: derived handlers, explicit-interface-implementation handlers, and all existing `is`/cast diff --git a/src/Core/src/Handlers/IElementHandlerOfT.cs b/src/Core/src/Handlers/IElementHandlerOfT.cs index 0cefae9a2655..bbff370addc2 100644 --- a/src/Core/src/Handlers/IElementHandlerOfT.cs +++ b/src/Core/src/Handlers/IElementHandlerOfT.cs @@ -24,6 +24,21 @@ namespace Microsoft.Maui /// so any handler derived from it — in the box or in an external backend — satisfies the contract /// without writing any additional members. /// + /// + /// Lifecycle. and are non-nullable here, + /// matching the non-nullable properties on + /// that satisfy them — and those + /// properties throw rather than returning + /// once the handler is disconnected. + /// clears the platform view before invoking the + /// disconnect callback, so a handler is only guaranteed to have one between + /// and . + /// The inherited and + /// return in exactly that state and + /// never throw, so code that can run outside a connected window — teardown paths, weak-reference + /// caches, diagnostics — should read those instead. Property and command mappers always run while + /// the handler is connected and can use the typed members freely. + /// /// /// /// new MyNativeWindow(); /// } /// - /// // Consumers match it platform-neutrally: - /// if (window.Handler is IElementHandler windowHandler) + /// // Consumers match it platform-neutrally. The typed members below throw once the handler is + /// // disconnected, so guard on the nullable IElementHandler.PlatformView first. + /// if (window.Handler is { PlatformView: not null } handler && + /// handler is IElementHandler windowHandler) /// { /// IWindow virtualView = windowHandler.VirtualView; /// object nativeWindow = windowHandler.PlatformView; @@ -49,11 +66,21 @@ public interface IElementHandler : IElement /// /// Gets the cross-platform virtual view associated with the handler. /// + /// + /// Throws when the handler is not connected. Read + /// the nullable instead on paths that can run while + /// disconnected. + /// new TVirtualView VirtualView { get; } /// /// Gets the native view associated with the handler. /// + /// + /// Throws when the handler is not connected. Read + /// the nullable instead on paths that can run while + /// disconnected. + /// new TPlatformView PlatformView { get; } } } diff --git a/src/Core/src/Handlers/IViewHandlerOfT.cs b/src/Core/src/Handlers/IViewHandlerOfT.cs index 35f872e5a5f8..19c92fb0226d 100644 --- a/src/Core/src/Handlers/IViewHandlerOfT.cs +++ b/src/Core/src/Handlers/IViewHandlerOfT.cs @@ -21,11 +21,21 @@ namespace Microsoft.Maui /// implements this interface, so /// every handler derived from it already satisfies the contract with no extra members. /// + /// + /// Lifecycle. As with + /// , the typed + /// and PlatformView members throw rather + /// than returning once the handler is disconnected. Use the nullable + /// and on paths + /// that can run outside a connected window. + /// /// /// /// labelHandler) + /// // Works for the in-box LabelHandler and for an external backend's label handler alike. The typed + /// // members throw once the handler is disconnected, so guard on the nullable one first. + /// if (label.Handler is { PlatformView: not null } handler && + /// handler is IViewHandler labelHandler) /// { /// ILabel virtualView = labelHandler.VirtualView; /// object nativeLabel = labelHandler.PlatformView; @@ -42,7 +52,10 @@ public interface IViewHandler : IElementHan /// /// Re-declared so that lookups are unambiguous between /// and - /// . + /// . Throws + /// when the handler is not connected; read the + /// nullable instead on paths that can run while + /// disconnected. /// new TVirtualView VirtualView { get; } } diff --git a/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs b/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs index 74136ed06925..825cd0c371c0 100644 --- a/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs +++ b/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs @@ -20,6 +20,25 @@ namespace Microsoft.Maui /// Because is covariant, ILayoutHandler<object> /// matches any layout handler regardless of backend. /// + /// + /// How .NET MAUI Controls reaches a layout handler. Microsoft.Maui.Controls.Layout does + /// not cast to either layout interface. It raises the child-management operations as command + /// mapper keys — Handler.Invoke(nameof(ILayoutHandler.Add), new LayoutHandlerUpdate(index, + /// view)) and so on — which is type-agnostic and therefore reaches an external backend's handler + /// exactly as it reaches the in-box one. Referencing for its member + /// names is always allowed; only implementing it is blocked. An external backend should use + /// those same key strings so Controls interop keeps working. + /// + /// + /// Known gap. The obsolete + /// Microsoft.Maui.Controls.Compatibility.Layout<T>.LayoutHandler property is declared as + /// and evaluates Handler as ILayoutHandler, so it returns + /// for a handler that implements only this generic interface. It is the sole + /// runtime cast to left in .NET MAUI, it is a public convenience + /// property that no in-box code path reads, and its declaring type is [Obsolete] — so it does + /// not affect layout behavior. It is called out here because this interface is, for that legacy + /// property specifically, a compile-time contract only. + /// /// public interface ILayoutHandler : IViewHandler where TPlatformView : class diff --git a/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs index a33cafd357ad..93fd550eaa48 100644 --- a/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs +++ b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Microsoft.Maui.Handlers; using Microsoft.Maui.Platform; @@ -92,8 +93,17 @@ public void UpdateZIndex(IView view) } } - FakeNativeView? GetNativeChild(IView view) => - view.ToHandler(MauiContext!).PlatformView as FakeNativeView; + FakeNativeView? GetNativeChild(IView view) + { + // An external backend should surface a missing context as an actionable error rather than + // letting a null-forgiving operator turn it into a bare NullReferenceException. This mirrors + // the null-safety pattern the in-box handlers use for their non-nullable members. + var mauiContext = MauiContext + ?? throw new InvalidOperationException( + $"{nameof(MauiContext)} cannot be null here. {nameof(FakeLayoutHandler)} must be connected via SetMauiContext before its children are realized."); + + return view.ToHandler(mauiContext).PlatformView as FakeNativeView; + } static int GetClampedZIndex(IView view, int count) { diff --git a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs index db6d6a234bda..f873f6b5e8ed 100644 --- a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs +++ b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs @@ -73,10 +73,13 @@ public void ExternalLayoutHandlerSatisfiesPlatformNeutralLayoutContract() } [Fact] - public void ExternalHandlerCannotImplementAliasedInterface() + public void ExternalHandlerDoesNotImplementAliasedInterface() { - // This is the gap the platform-neutral contracts exist to close: the aliased interfaces pin - // PlatformView to a type the external backend does not own, so it cannot implement them. + // Runtime assertion only: these handlers do not implement the aliased interfaces. The + // compile-time half of the claim - that they *cannot* - is proven by the Core.ExternalBackend + // assembly, which compiles the same handler shapes against every target framework Core ships. + // Attempting to implement ILabelHandler/ILayoutHandler there fails with CS0738 on a platform + // target framework and CS9333 on the platform-neutral and netstandard ones. Assert.IsNotAssignableFrom(new FakeLabelHandler()); Assert.IsNotAssignableFrom(new FakeLayoutHandler()); } From d94349c85d26202453329985c52dd019a7874c28 Mon Sep 17 00:00:00 2001 From: redth Date: Thu, 27 Aug 2026 20:40:23 -0400 Subject: [PATCH 7/7] Remove unused external backend test import Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1279cef0-092d-4b50-9497-8565b890e8de --- .../tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs index 7de4c3cd6550..20225d17b1d2 100644 --- a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs +++ b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls; using Microsoft.Maui.ExternalBackend; using Microsoft.Maui.Handlers; using Microsoft.Maui.Hosting;