diff --git a/docs/design/ExternalPlatformBackends.md b/docs/design/ExternalPlatformBackends.md new file mode 100644 index 000000000000..046c0c30b76b --- /dev/null +++ b/docs/design/ExternalPlatformBackends.md @@ -0,0 +1,415 @@ +# 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); +} +``` + +### 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 +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 +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; + +// 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.TestSupport`) 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. + +It is **shared with the container-view work** from +[#37854](https://github.com/dotnet/maui/pull/37854), which introduced the same assembly to prove +`ViewHandler.SetContainerView` is reachable from a non-friend assembly. Both efforts need exactly the +same thing — an assembly outside Core's friend list that models an external backend — so they use one +project rather than two. Those sources (`ExternalBackendViewHandler.cs`, `ExternalPlatformViews.cs`) use +platform-agnostic native types, which satisfy `ViewHandler<,>`'s `TPlatformView` constraint only where +that constraint is `class`, so they are scoped to the platform-neutral and netstandard target frameworks +— precisely the set they were compiled against before this project became multi-targeted. + +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 | +| --- | --- | --- | +| `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`, +`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 +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 + +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..bbff370addc2 --- /dev/null +++ b/src/Core/src/Handlers/IElementHandlerOfT.cs @@ -0,0 +1,86 @@ +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. + /// + /// + /// 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. + /// + /// + /// + /// + /// { + /// public MyWindowHandler() : base(WindowHandler.Mapper) { } + /// protected override MyNativeWindow CreatePlatformElement() => new MyNativeWindow(); + /// } + /// + /// // 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; + /// } + /// ]]> + /// + public interface IElementHandler : IElementHandler + where TVirtualView : IElement + where TPlatformView : class + { + /// + /// 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 new file mode 100644 index 000000000000..19c92fb0226d --- /dev/null +++ b/src/Core/src/Handlers/IViewHandlerOfT.cs @@ -0,0 +1,62 @@ +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. + /// + /// + /// 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) + /// { + /// 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 + /// . 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 new file mode 100644 index 000000000000..825cd0c371c0 --- /dev/null +++ b/src/Core/src/Handlers/Layout/ILayoutHandlerOfT.cs @@ -0,0 +1,83 @@ +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. + /// + /// + /// 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 + { + /// + /// 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 d948487ce197..524cd2d7cc1b 100644 --- a/src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-android/PublicAPI.Unshipped.txt @@ -363,6 +363,18 @@ 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 Microsoft.Maui.IToolbarDrawerToggleVisible Microsoft.Maui.IToolbarDrawerToggleVisible.DrawerToggleVisible.get -> bool Microsoft.Maui.IImageSourcePaint diff --git a/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt index cc1a95514efd..85aabebd0c28 100644 --- a/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt @@ -63,6 +63,18 @@ 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 Microsoft.Maui.IToolbarDrawerToggleVisible Microsoft.Maui.IToolbarDrawerToggleVisible.DrawerToggleVisible.get -> bool Microsoft.Maui.IImageSourcePaint diff --git a/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt index 04797741c5c0..8231ea8787d6 100644 --- a/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt @@ -60,6 +60,18 @@ 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 Microsoft.Maui.IToolbarDrawerToggleVisible Microsoft.Maui.IToolbarDrawerToggleVisible.DrawerToggleVisible.get -> bool Microsoft.Maui.IImageSourcePaint diff --git a/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt index cb4cc218eba7..64bec0d2be63 100644 --- a/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt @@ -21,6 +21,18 @@ 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 Microsoft.Maui.IToolbarDrawerToggleVisible Microsoft.Maui.IToolbarDrawerToggleVisible.DrawerToggleVisible.get -> bool Microsoft.Maui.IImageSourcePaint diff --git a/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt index 47c6a047f913..e4b853c7e85d 100644 --- a/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt @@ -48,6 +48,18 @@ 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 Microsoft.Maui.IToolbarDrawerToggleVisible Microsoft.Maui.IToolbarDrawerToggleVisible.DrawerToggleVisible.get -> bool Microsoft.Maui.IImageSourcePaint diff --git a/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt index bd1446dd1a1e..33f1ecf4deaf 100644 --- a/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/net/PublicAPI.Unshipped.txt @@ -30,6 +30,18 @@ static Microsoft.Maui.Handlers.FlyoutViewHandler.MapIsGestureEnabled(Microsoft.M static Microsoft.Maui.Handlers.FlyoutViewHandler.MapIsPresented(Microsoft.Maui.Handlers.IFlyoutViewHandler! handler, Microsoft.Maui.IFlyoutView! flyoutView) -> 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 static Microsoft.Maui.Handlers.ShapeViewHandler.MapFlowDirection(Microsoft.Maui.Handlers.IShapeViewHandler! handler, Microsoft.Maui.IShapeView! shapeView) -> void static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> void static Microsoft.Maui.SafeAreaEdges.Container.get -> Microsoft.Maui.SafeAreaEdges diff --git a/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt index 1f04785c91e6..e97616c12c4a 100644 --- a/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt @@ -29,6 +29,18 @@ 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 Microsoft.Maui.IToolbarDrawerToggleVisible Microsoft.Maui.IToolbarDrawerToggleVisible.DrawerToggleVisible.get -> bool Microsoft.Maui.IImageSourcePaint diff --git a/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt b/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt index 6cbcb332f4e8..a6e48b51e43f 100644 --- a/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt +++ b/src/Core/src/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt @@ -31,6 +31,18 @@ static Microsoft.Maui.Handlers.SearchBarHandler.MapSelectionLength(Microsoft.Mau static Microsoft.Maui.Handlers.ShapeViewHandler.MapFlowDirection(Microsoft.Maui.Handlers.IShapeViewHandler! handler, Microsoft.Maui.IShapeView! shapeView) -> void static Microsoft.Maui.Handlers.SwipeItemMenuItemHandler.MapIconColor(Microsoft.Maui.Handlers.ISwipeItemMenuItemHandler! handler, Microsoft.Maui.ISwipeItemMenuItem! view) -> 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 Microsoft.Maui.IImageSourcePaint Microsoft.Maui.IImageSourcePaint.ImageSource.get -> Microsoft.Maui.IImageSource? Microsoft.Maui.Handlers.ViewHandler.SetContainerView(object? containerView) -> void diff --git a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj index fff06f6ebc5b..ffa52557c03a 100644 --- a/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj +++ b/src/Core/tests/ExternalBackend/Core.ExternalBackend.csproj @@ -1,22 +1,63 @@ - $(_MauiDotNetTfm) + + netstandard2.1;netstandard2.0;$(_MauiDotNetTfm);$(MauiPlatforms) Microsoft.Maui.Core.ExternalBackend.TestSupport Microsoft.Maui.Core.ExternalBackend.TestSupport false true enable + + true + + + + + + + + + + + + + + diff --git a/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs b/src/Core/tests/ExternalBackend/ExternalBackendContracts.cs new file mode 100644 index 000000000000..648a5e53a62e --- /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.FakeText; + } + + /// + /// 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/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 new file mode 100644 index 000000000000..9e5ec310c345 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeHandlers.cs @@ -0,0 +1,108 @@ +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 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, on every target + /// framework. + /// + /// + 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() => +#if MONOANDROID + new FakeNativeLabel(Context); +#else + new FakeNativeLabel(); +#endif + + public static void MapText(FakeLabelHandler handler, ILabel label) => + handler.PlatformView.FakeText = label.Text; + + public static void MapOpacity(FakeLabelHandler handler, ILabel label) => + handler.PlatformView.FakeOpacity = 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() => +#if MONOANDROID + new FakeNativeContentView(Context); +#else + new FakeNativeContentView(); +#endif + + public static void MapContent(FakeContentViewHandler handler, IContentView contentView) + { + handler.PlatformView.FakeContent = + (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.FakeTitle = window.Title; + } +} diff --git a/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs new file mode 100644 index 000000000000..93fd550eaa48 --- /dev/null +++ b/src/Core/tests/ExternalBackend/FakeLayoutHandler.cs @@ -0,0 +1,163 @@ +using System; +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() => +#if MONOANDROID + new FakeNativeLayoutView(Context); +#else + new FakeNativeLayoutView(); +#endif + + public void Add(IView view) + { + if (GetNativeChild(view) is FakeNativeView child) + { + PlatformView.FakeChildren.Add(child); + } + } + + public void Remove(IView view) + { + if (view.Handler?.PlatformView is FakeNativeView child) + { + PlatformView.FakeChildren.Remove(child); + } + } + + public void Clear() => PlatformView.FakeChildren.Clear(); + + public void Insert(int index, IView view) + { + if (GetNativeChild(view) is FakeNativeView child) + { + PlatformView.FakeChildren.Insert(index, child); + } + } + + public void Update(int index, IView view) + { + if (GetNativeChild(view) is FakeNativeView child) + { + PlatformView.FakeChildren[index] = child; + } + } + + public void UpdateZIndex(IView view) + { + if (view.Handler?.PlatformView is FakeNativeView child) + { + List children = PlatformView.FakeChildren; + children.Remove(child); + children.Insert(GetClampedZIndex(view, children.Count), child); + } + } + + 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) + { + 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.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.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/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.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/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 new file mode 100644 index 000000000000..7a5258a10d57 --- /dev/null +++ b/src/Core/tests/UnitTests/Handlers/ExternalBackendTargetFrameworkTests.cs @@ -0,0 +1,118 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +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. + /// + /// + /// 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 CoreProject = "ProjectFiles/Core.csproj"; + const string ExternalBackendProject = "ProjectFiles/Core.ExternalBackend.csproj"; + + [Fact] + public void ExternalBackendMirrorsCoreTargetFrameworks() + { + 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. + Assert.Equal(core, externalBackend); + } + + [Fact] + public void ExternalBackendCompilesNetStandardTargetFrameworks() + { + var externalBackend = ReadTargetFrameworks(ExternalBackendProject); + + Assert.Contains("netstandard2.0", externalBackend, StringComparison.Ordinal); + Assert.Contains("netstandard2.1", externalBackend, StringComparison.Ordinal); + } + + [Fact] + public void ExternalBackendInheritsThePlatformSetFromMauiPlatforms() + { + var externalBackend = ReadTargetFrameworks(ExternalBackendProject); + + // 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 source = ReadEmbeddedText($"ProjectFiles/{fileName}"); + + foreach (var type in new[] { "FakeNativeView", "FakeNativeLabel", "FakeNativeContentView", "FakeNativeLayoutView" }) + { + Assert.Contains($"class {type}", source, StringComparison.Ordinal); + } + } + + static string ReadTargetFrameworks(string resourceName) + { + 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. + 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 ReadEmbeddedText(string resourceName) + { + var assembly = typeof(ExternalBackendTargetFrameworkTests).Assembly; + + using var stream = assembly.GetManifestResourceStream(resourceName); + + Assert.True( + stream is not null, + $"Missing embedded resource '{resourceName}'. Available: {string.Join(", ", assembly.GetManifestResourceNames())}"); + + using var reader = new StreamReader(stream!); + + return reader.ReadToEnd(); + } + } +} diff --git a/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs new file mode 100644 index 000000000000..20225d17b1d2 --- /dev/null +++ b/src/Core/tests/UnitTests/Handlers/ExternalPlatformBackendTests.cs @@ -0,0 +1,270 @@ +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.TestSupport, 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 ExternalHandlerDoesNotImplementAliasedInterface() + { + // 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()); + } + + [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.FakeText); + + label.Text = "goodbye"; + handler.UpdateValue(nameof(ILabel.Text)); + + Assert.Equal("goodbye", handler.PlatformView.FakeText); + } + + [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.FakeOpacity); + } + + [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.FakeChildren.Count); + + layout.Insert(0, new Label { Text = "inserted" }); + 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.FakeChildren.Count); + + layout[0] = new Label { Text = "replaced" }; + Assert.Equal("replaced", Assert.IsType(handler.PlatformView.FakeChildren[0]).FakeText); + + layout.Clear(); + Assert.Empty(handler.PlatformView.FakeChildren); + } + + [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.FakeChildren); + + neutral.Clear(); + Assert.Empty(platformView.FakeChildren); + } + + [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.FakeTitle); + + IElementHandler neutral = handler; + + Assert.Same(window, neutral.VirtualView); + Assert.IsType(neutral.PlatformView); + } + } +}