diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 90100c261ad7..b8d42e61feba 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -223,6 +223,14 @@ git commit -m "Fix: Description of the change" - Follow existing code documentation patterns - Update relevant docs in `docs/` folder when needed +### Code Comments +- **Do NOT emit "fake region" banner/separator comments** — e.g. lines like + `// -----------------------------`, or a three-line block of dashes wrapping a section + label (`// ----` / `// Helpers` / `// ----`). These are `#region`/`#endregion` in disguise, + add noise, and are not wanted. Let the code structure speak for itself; use a plain one-line + `//` comment only where a specific piece of logic genuinely needs clarification. +- Prefer XML doc comments (`///`) for public/internal members over banner comments. + ### Opening PRs All PRs are required to have this at the top of the description: diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a6db7db80e08..92c89437fe63 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -40,6 +40,7 @@ updates: patterns: - "Microsoft.Graphics.Win2D" - "Microsoft.Windows.SDK.BuildTools" + - "Microsoft.Windows.SDK.BuildTools.WinApp" - "Microsoft.WindowsAppSDK" - "Microsoft.Web.WebView2" xunit: diff --git a/.github/docs/maui-ci-facts.md b/.github/docs/maui-ci-facts.md index 8fbfbd586e6d..d345bf117eda 100644 --- a/.github/docs/maui-ci-facts.md +++ b/.github/docs/maui-ci-facts.md @@ -87,6 +87,13 @@ and `maui-pr-uitests` may not run automatically depending on the changed files. ## Setup-only retries +Shared provisioning initializes `DOTNET_CLI_HOME` under the agent's per-job +temporary directory before invoking .NET. It preserves an existing +`NUGET_PACKAGES`, or pins the original user-profile package cache when unset, +so NuGet restores and Arcade's MSBuild task imports use the same cache. +An unwritable CLI-state directory fails preparation rather than changing +permissions on the hosted agent's shared home directory. + Shared test preparation uses **at most five total attempts per setup operation**, not five additional retries or five whole-job reruns. Azure task-level recovery uses `retryCountOnTaskFailure: 4`, with the agent's backoff and attempt diagnostics. @@ -148,8 +155,25 @@ existing policies; shared agent setup does not wrap or resubmit those test runs. ## MAUI-specific quirks +### Android activity isolation + +External-intent fixtures must remain scoped to the test package and an unhandled +action after component sanitization, rather than opening the resolver or system +settings. Assert that the original activity is `RESUMED` before and after +navigation. `HasWindowFocus` is not a lifecycle check: the notification shade can +take focus while that same activity remains resumed. + ### XHarness exit-0 blind spot +Windows device categories also require complete, parseable xUnit output. The +Windows runner fails empty/malformed results and abnormal process exits, while +preserving valid category results for upload. WinUI `Application.Exit()` may +return `-1` normally; that code alone is not a crash. A successful build or a +partial merged XML does not prove every category executed. +The packaged launcher retains a native process handle before waiting: Windows +PowerShell's .NET Framework cannot read `ExitCode` afterward without that handle. +An unavailable exit code must not be treated as a successful exit. + XHarness (iOS/Android device tests in `maui-pr-devicetests`) **exits with code 0 even when tests fail**. So the AzDO job shows ✅ "Succeeded", `ci-analysis` may report no failures, but real failures are hidden inside the Helix work items. @@ -388,6 +412,7 @@ error XAGRDL0000: Could not GET '...pkgs.dev.azure.com/.../maven/v1/...' |---------|-------|-------| | `error CS####` | `maui-pr` | C# compiler error — check file/line | | `error XA####` | `maui-pr` | Android build error | +| `java_home -X` / `Root element is missing` / invalid JDK `jar` path | `maui-pr` Android builds and integration tests | Android SDK discovery can inspect broken system registrations or archive parent directories even with `JAVA_HOME` set. `ProvisionJdk` must also publish the validated JDK home as `JavaSdkDirectory` for downstream MSBuild processes. Do not suppress these diagnostics or allow-list the tooling warnings. | | `error : ... Failed to load assembly` | `maui-pr` `Build ` leg | **crossgen2 / ReadyToRun (R2R)** break — a failed **build job**, not a test, with no test name. Common after an SDK/runtime (`dotnet/dotnet`) bump on a flow PR. Job-level baseline diff: red on PR vs green on base ⇒ PR-caused. | | `error IL####` / `ILC####` / NativeAOT publish fail | `maui-pr` AOT legs, `Run Integration Tests – AOT` | **NativeAOT / ILC** trim-analysis break. May be pre-existing (e.g. HybridWebView `IL2026`) — confirm with a job- AND test-level baseline diff before attributing to the PR. | | `error NETSDK1144` | `maui-pr` TrimFull legs | Optimizing assemblies for size failed (often an ILLink warning promoted to error). Check whether the same leg is red on the base branch. | @@ -395,6 +420,15 @@ error XAGRDL0000: Could not GET '...pkgs.dev.azure.com/.../maven/v1/...' | `WMC0612` / XBF `0x09C4` / `Property Not Found` after adding native Windows `x:DataType` | `maui-pr` Windows build/pack | The native XBF generator rejects the annotations introduced by #38735 on classic `{Binding}` templates. Restore the prior metadata without replacing bindings or converters. XML/source-only checks cannot validate XBF compilation; require an actual Windows build. | | `WMC9999` on overloaded table collections, `WMC0821` on open generic types, or invalid generated `XamlTypeInfo.g.cs` after adding native `[Bindable]` | `maui-pr` Windows build/pack | These were successive failures from #38735's new metadata in the Windows investigation on #39608. Restore the pre-cleanup native metadata baseline rather than changing public collection APIs, generic types, or generated code. Preserve existing runtime binding behavior and validate with the native Windows compiler. | | `error XAGRDL0000` / `401` / `No local versions` | `maui-pr` or official build | Gradle/Maven feed issue — see above | +| Apple workload install cannot find a `net10.0` SDK pack | `maui-pr` SDK provisioning | The .NET 11 Apple manifests also install .NET 10 compatibility packs. Resolve the exact missing version's feed with `darc get-asset`; the current .NET 11 feed alone may not contain it. Do not copy another branch's compatibility feed without checking its manifest versions. | +| `NETSDK1140` rejects the Apple target platform version | `maui-pr` build/pack | Align current Apple target-framework versions and SDK defaults in `Directory.Build.props` with the selected Apple SDK. net11.0 uses 26.5; the RC2 release branch uses 27.0. Preserve previous-.NET compatibility targets. | +| Xcode 27 rejects native iOS 12.x / mapped macOS 10.15 deployment targets | `maui-pr` native interop archive | On branches using Apple 27, align the native framework and managed iOS minimum to 15.0, already used by app templates. This maps to macOS 12.0 for Mac Catalyst. Do not raise minimums on Apple 26.5 branches solely to match RC2. | +| Apple `bgen.dll` exits 150 requesting a newer .NET runtime | `maui-pr` Apple binding generation | Keep bootstrap (`global.json`), workload provisioning (`MicrosoftNETSdkPackageVersion`), and SDK provenance pins aligned with a compatible host runtime. SDK `11.0.100-rc.2.26470.103` satisfies the Apple 27 generator's `26465.108` requirement and is already selected on net11.0. | +| Resizetizer raster test assertions pass but `Dispose` fails with a Windows sharing violation | Helix Windows unit tests | Keep temporary images under `BaseTest.DestinationDirectory` and reuse its bounded, logged cleanup retries from #38124. Dispose raster tools deterministically; preserve all image assertions and let exhausted cleanup retries fail the test. | +| `Svg.Animation` / `Svg.SceneGraph` `NU1603`, or `SKPathBuilder` `CS0246` | `maui-pr` restore/build | Release merges can preserve old `eng/Versions.props` pins while importing Skia 4 source and packaging changes. Restore the coordinated SkiaSharp/HarfBuzz/SVG dependency versions, not just the first missing package. | +| Required Xcode is missing / requested iOS runtime is unavailable | `maui-pr` macOS provisioning | Select an image or agents providing the branch's required Xcode. net11.0 retains Aces with Xcode 26.5; RC2 needs the MAUI pool's Xcode 27 RC agents. Do not fall back to an unrelated Xcode or purge runtimes to repair a version mismatch. The legacy Provisionator task is unavailable in `dnceng-public`; enabling it prevents pipeline startup. | +| `iOS 27.0 (universal) is not available for download` | `maui-pr` simulator provisioning | Request the `arm64` runtime on Apple Silicon agents; retain `universal` on Intel. Keep all downloads version-pinned. An unavailable download can also return exit code 70, so do not treat every exit 70 as a wedged CoreSimulator or delete installed runtimes. | +| Helix monitor cannot use `NetCore-Svc-Public` | `maui-pr` release branches | The monitor must use the pipeline's selected Helix submission pool, with its Linux image demand, rather than independently selecting an unauthorized pool from the branch name. | | `XHarness timeout` | `maui-pr-devicetests` Helix logs | Test killed by infrastructure; may be transient | | `No test result files found` | `maui-pr-devicetests` Helix logs | Tests never ran or app crashed on launch | | UI test screenshot diff | `maui-pr-uitests` | Visual regression; check baseline images | diff --git a/.github/instructions/collectionview-handler-detection.instructions.md b/.github/instructions/collectionview-handler-detection.instructions.md index 24556e39b869..cb002aedc812 100644 --- a/.github/instructions/collectionview-handler-detection.instructions.md +++ b/.github/instructions/collectionview-handler-detection.instructions.md @@ -7,23 +7,37 @@ applyTo: "src/Controls/src/Core/Handlers/Items/**,src/Controls/src/Core/Handlers ## Handler Implementation Status -There are **TWO separate handler implementations**, but they apply to **different platforms**: +There are **TWO separate handler implementations**, with platform- and control-specific coverage: -1. **Items/** (`Handlers/Items/`) - Contains code for **ALL platforms** (Android, iOS, Windows, MacCatalyst, Tizen) -2. **Items2/** (`Handlers/Items2/`) - Contains code for **iOS/MacCatalyst ONLY** +1. **Items/** (`Handlers/Items/`) - Contains code for **ALL built-in platforms** (Android, iOS, Windows, MacCatalyst) +2. **Items2/** (`Handlers/Items2/`) - Contains code for **iOS/MacCatalyst** and **Windows CollectionView** ### Platform-Specific Deprecation -The deprecation of Items/ **only applies to iOS/MacCatalyst**: +The deprecation of Items/ depends on both platform and control: -| Platform | Active Handler | Notes | -|----------|----------------|-------| -| **Android** | `Items/Android/` | **ONLY implementation** - Items2/ has no Android code | -| **Windows** | `Items/` | **ONLY implementation** - Items2/ has no Windows code | -| **iOS** | `Items2/iOS/` | Items/ iOS code is deprecated | -| **MacCatalyst** | `Items2/iOS/` | Items/ MacCatalyst code is deprecated | +| Platform | Control | Active Handler | Notes | +|----------|---------|----------------|-------| +| **Android** | CollectionView / CarouselView | `Items/Android/` | **ONLY implementation** - Items2/ has no Android code | +| **Windows** | CollectionView | `Items2/Windows/` | Default on .NET 11; Items/ is the obsolete feature-switch fallback | +| **Windows** | CarouselView | `Items/` | **ONLY implementation** - there is no Windows CarouselViewHandler2 | +| **iOS** | CollectionView / CarouselView | `Items2/iOS/` | Items/ iOS code is deprecated | +| **MacCatalyst** | CollectionView / CarouselView | `Items2/iOS/` | Items/ MacCatalyst code is deprecated | -**CRITICAL**: Items2/ is **iOS/MacCatalyst only**. There is NO Items2/ code for Android or Windows. +**CRITICAL**: Items2/ does not replace Items/ wholesale. Android uses Items/ for both controls, and Windows CarouselView still uses Items/. + +### Shared iOS/Mac Catalyst Infrastructure + +Items2 intentionally reuses these public Items types: + +- `IItemsViewSource` +- `IObservableItemsViewSource` +- `ILoopItemsViewSource` +- `MauiCollectionView` +- `IndexPathHelpers` +- `ScrollToPositionExtensions` + +It also reuses internal item-source, template, index-path, snap, scroll-tracking, and reorder helpers from Items/. Do not classify or obsolete a type solely from its Items/ path; check Items2 references first. --- @@ -32,13 +46,17 @@ The deprecation of Items/ **only applies to iOS/MacCatalyst**: ### Decision Tree by Platform ``` -Is the issue/PR for Android or Windows? +Is the issue/PR for Android? YES → Work on Items/ (it's the ONLY implementation) NO → Continue... Is the issue/PR for iOS or MacCatalyst? YES → Work on Items2/ (Items/ is deprecated for iOS) - NO → Check platform and find appropriate handler + NO → Continue... + +Is the issue/PR for Windows CollectionView? + YES → Work on Items2/ (Items/ is the obsolete feature-switch fallback) + NO → Work on Items/ for Windows CarouselView ``` ### Detection Algorithm @@ -51,9 +69,11 @@ git diff .. --name-only | grep -i "handlers/items" # Look for path pattern: # - Contains "/Items/Android/" → Android (ONLY implementation, work here) -# - Contains "/Items/Windows/" or ".Windows.cs" → Windows (ONLY implementation, work here) +# - Contains "/Items2/Windows/" or "Items2/*.Windows.cs" → Windows CollectionView (CURRENT) +# - Contains "/Items/*.Windows.cs" → Windows CarouselView or deprecated CollectionView fallback # - Contains "/Items2/iOS/" or "Items2/*.iOS.cs" → iOS/MacCatalyst (CURRENT) -# - Contains "/Items/*.iOS.cs" (not Items2) → iOS (DEPRECATED, prefer Items2/) +# - Contains "/Items/iOS/" or "Items/*.iOS.cs" (not Items2) → iOS/MacCatalyst legacy code; +# prefer Items2/ unless the type is part of the shared infrastructure listed above ``` ### Default Behavior by Platform @@ -61,7 +81,8 @@ git diff .. --name-only | grep -i "handlers/items" | Platform | Default Action | |----------|----------------| | **Android** | ✅ Work on `Items/Android/` - it's the only option | -| **Windows** | ✅ Work on `Items/` Windows files - it's the only option | +| **Windows CollectionView** | ✅ Work on `Items2/` Windows files - this is the .NET 11 default | +| **Windows CarouselView** | ✅ Work on `Items/` Windows files - it's the only option | | **iOS/MacCatalyst** | ✅ Work on `Items2/` - Items/ is deprecated for iOS | ### When to Work on Items/ for iOS (Deprecated) @@ -78,18 +99,22 @@ Only work on Items/ iOS code when: | Path Pattern | Platform | Status | |--------------|----------|--------| | `Handlers/Items/Android/` | Android | **ACTIVE** (only implementation) | -| `Handlers/Items/*.Windows.cs` | Windows | **ACTIVE** (only implementation) | +| `Handlers/Items2/Windows/`, `Handlers/Items2/*.Windows.cs` | Windows CollectionView | **ACTIVE** (default) | +| `Handlers/Items/*.Windows.cs` | Windows | **ACTIVE** for CarouselView; **DEPRECATED** CollectionView fallback | | `Handlers/Items2/iOS/` | iOS/MacCatalyst | **ACTIVE** (current) | -| `Handlers/Items/*.iOS.cs` | iOS/MacCatalyst | **DEPRECATED** (use Items2/) | +| `Handlers/Items/iOS/`, `Handlers/Items/*.iOS.cs` | iOS/MacCatalyst | **DEPRECATED** handler implementation; retain Items types reused by Items2 | --- ## Common Mistakes to Avoid -❌ **Wrong**: "Items/ is deprecated, so I should check if Items2/ needs the same Android fix" -- Items2/ has NO Android code - there's nothing to check +❌ **Wrong**: "Items/ is deprecated everywhere" +- Items/ remains the only implementation for Android and Windows CarouselView + +❌ **Wrong**: "Items2/ is iOS-only" +- Items2/ also contains the default .NET 11 Windows CollectionView implementation ❌ **Wrong**: "This Android fix should also go in Items2/" -- Items2/ is iOS-only, Android code only exists in Items/ +- Items2/ has no Android code, so Android work stays in Items/ ✅ **Correct**: "This is an Android-only issue, so I work in Items/Android/ which is the only Android implementation" diff --git a/.github/instructions/collectionview-windows.instructions.md b/.github/instructions/collectionview-windows.instructions.md index a9eff1612549..ca3b5d099cfb 100644 --- a/.github/instructions/collectionview-windows.instructions.md +++ b/.github/instructions/collectionview-windows.instructions.md @@ -2,10 +2,20 @@ applyTo: - "src/Controls/src/Core/Handlers/Items/*.Windows.cs" - "src/Controls/src/Core/Handlers/Items/*.windows.cs" + - "src/Controls/src/Core/Handlers/Items2/*.Windows.cs" + - "src/Controls/src/Core/Handlers/Items2/*.windows.cs" + - "src/Controls/src/Core/Handlers/Items2/Windows/**" --- -# CollectionView — Windows (Items/ Handler) +# CollectionView — Windows -Items/ is the **ONLY** Windows CollectionView implementation. Items2/ has NO Windows code. +On .NET 11, Items2/ is the default Windows CollectionView implementation. Items/ remains the obsolete CollectionView fallback behind `RuntimeFeature.IsWindowsCollectionView2HandlerEnabled` and the only Windows CarouselView implementation. + +## Which Handler to Change + +- CollectionView work targets `Items2/`. +- CarouselView work targets `Items/`. +- Change the Items/ CollectionView path only for explicit legacy fallback maintenance. +- Keep `ItemsViewHandler` active because Windows CarouselView still derives from it; the Structured/Selectable/Groupable/Reorderable Items handler chain is CollectionView-specific and obsolete. ## WinUI ListView/ItemsRepeater Patterns - Preserve WinUI XAML styles applied via native theming — clearing a MAUI property must restore the style-applied value, not a hardcoded default diff --git a/.github/instructions/integration-tests.instructions.md b/.github/instructions/integration-tests.instructions.md index 3990d8fc8393..330047653fe0 100644 --- a/.github/instructions/integration-tests.instructions.md +++ b/.github/instructions/integration-tests.instructions.md @@ -111,7 +111,7 @@ public void RunOniOS(string id, string config, string framework, RuntimeVariant runtimeIdentifier: TestEnvironment.IOSSimulatorRuntimeIdentifier)); // Run with XHarness (omit UDID to let XHarness control simulator lifecycle) - Assert.IsTrue(XHarness.RunAppleForTimeout(appPath, resultDir, TestSimulator.XHarnessID)); + Assert.IsTrue(XHarness.RunApple(appPath, resultDir, TestSimulator.XHarnessID, completionMarker)); } ``` @@ -206,6 +206,7 @@ The skill sets these automatically, but for manual runs: |----------|----------|---------| | `MAUI_PACKAGE_VERSION` | Yes | Version of MAUI packages being tested | | `IOS_TEST_DEVICE` | No | iOS simulator target (e.g., `ios-simulator-64_18.5`) | +| `IOS_TEST_DEVICE_UDID` | No | UUID of a dedicated simulator for both fixture and XHarness; fixture boots/shuts it down, so never select a shared device | | `SKIP_XCODE_VERSION_CHECK` | No | Set to `true` to bypass Xcode version validation | ### Manual Run Commands (Fallback Only) @@ -233,11 +234,30 @@ dotnet test src/TestUtils/src/Microsoft.Maui.IntegrationTests \ | Template not found | Verify workloads installed, `MAUI_PACKAGE_VERSION` set | | Xcode version mismatch | Set `SKIP_XCODE_VERSION_CHECK=true` | | Device/simulator not found | Verify `IOS_TEST_DEVICE` or emulator is running | -| XHarness timeout on iOS | Expected behavior - app runs until timeout | +| XHarness timeout on iOS | Failure: discovery/install/launch share the command timeout; timeout alone never proves startup | | Architecture mismatch | Use `TestEnvironment.IOSSimulatorRuntimeIdentifier` | ## Best Practices +The iOS template smoke tests inject `AppleTemplateLaunchProbe.cs` into the generated +app (not the shipped templates). Both application `OnActivated` and +`SceneOnActivated` start the same guarded main-run-loop timer, which waits +15 seconds, writes a unique per-test completion marker, and exits with code zero. +`XHarness.RunApple` requires both that marker in the application logs and exit code +zero. Its existing 300-second command budget covers discovery, installation, +launch, and execution; it is not the app's 15-second observation interval. +Do not accept timeout codes or SIGKILL as evidence that the app started. + +For local template validation, set `DOTNET_CLI_HOME` to a session-owned directory +before restoring tools and invoking the integration-test skill. This isolates +user-installed templates that can otherwise override the workload's templates. +Verify the selected template pack path/version in that home's +`.templateengine/dotnetcli//templatecache.json`, along with the +generated `Platforms/iOS/SceneDelegate.cs` and `UIApplicationSceneManifest`. +Correct NuGet library versions alone do not establish template provenance. +Exercise both scene-based templates and a test-only legacy lifecycle fixture; +application activation alone is not raised for scene-based apps. + ### DO - Use `BuildProps` from base class for isolation - Apply `[Category]` at the **class level** when all tests share the same category diff --git a/.github/instructions/resizetizer.instructions.md b/.github/instructions/resizetizer.instructions.md index 80a272e9e272..8de989ca2aa7 100644 --- a/.github/instructions/resizetizer.instructions.md +++ b/.github/instructions/resizetizer.instructions.md @@ -105,7 +105,6 @@ ResizetizeCollectItems ← Collects items from project + references | **Android** | `BeforeTargets=_ComputeAndroidResourcePaths` | `AfterTargets=ResizetizeCollectItems` | `AfterTargets=ResizetizeCollectItems` | | **Windows** | Via `DependsOnTargets` (from `ResizetizeImages`/`ProcessMauiFonts`) | `BeforeTargets=AssignTargetPaths` | `BeforeTargets=AssignTargetPaths` | | **WPF** | Via `DependsOnTargets` (from `ResizetizeImages`/`ProcessMauiFonts`) | `BeforeTargets=FileClassification` | `BeforeTargets=FileClassification` | -| **Tizen** | Via `DependsOnTargets` (from `ResizetizeImages`/`ProcessMauiFonts`) | `AfterTargets=ResizetizeCollectItems` | `AfterTargets=ResizetizeCollectItems` | ## ⚠️ Critical Pattern: Inputs/Outputs and Item Registration @@ -190,7 +189,6 @@ MSBuild's `Inputs`/`Outputs` incremental check skips **targets** when outputs ar | **Android** | `AndroidAsset` | `Link` | | **Windows** | `ContentWithTargetPath` | `TargetPath`, `CopyToPublishDirectory` | | **WPF** | `Resource` | `LogicalName`, `Link` | -| **Tizen** | `TizenTpkUserIncludeFiles` | `TizenTpkSubDir` | **Image Items** (from `ResizetizeImages`): @@ -200,7 +198,6 @@ MSBuild's `Inputs`/`Outputs` incremental check skips **targets** when outputs ar | **Android** | `LibraryResourceDirectories` | `StampFile` | | **Windows** | `ContentWithTargetPath` | `TargetPath`, `CopyToPublishDirectory` | | **WPF** | `Resource` | `LogicalName`, `Link` | -| **Tizen** | `TizenTpkUserIncludeFiles` | `TizenTpkSubDir` | ### iOS-Specific: Info.plist Font Registration @@ -283,7 +280,6 @@ Predictive mapping from the source items is also preferred over a filesystem glo | `_ResizetizerIsiOSApp` | iOS/MacCatalyst application (includes both) | | `_ResizetizerIsWindowsAppSdk` | Windows App SDK (WinUI) | | `_ResizetizerIsWPFApp` | WPF application | -| `_ResizetizerIsTizenApp` | Tizen application | | `_ResizetizerIsCompatibleApp` | Any of the above | ## Testing MSBuild Target Changes diff --git a/.github/instructions/templates.instructions.md b/.github/instructions/templates.instructions.md index 5783c485803b..95cd0cf5a6cc 100644 --- a/.github/instructions/templates.instructions.md +++ b/.github/instructions/templates.instructions.md @@ -42,8 +42,8 @@ Platform-specific `#if` directives (like `#if WINDOWS`, `#if ANDROID`, `#if IOS` //-:cnd:noEmit #if WINDOWS - Microsoft.Maui.Controls.Handlers.Items.CollectionViewHandler.Mapper.AppendToMapping( - "KeyboardAccessibleCollectionView", + Microsoft.Maui.Controls.Handlers.Items2.CollectionViewHandler2.Mapper.AppendToMapping( + "ConfigureCollectionView", (handler, view) => { /* ... */ }); #endif //+:cnd:noEmit diff --git a/.github/instructions/workload-msi.instructions.md b/.github/instructions/workload-msi.instructions.md new file mode 100644 index 000000000000..1764f4e1c43d --- /dev/null +++ b/.github/instructions/workload-msi.instructions.md @@ -0,0 +1,95 @@ +--- +description: "Guidelines for working with workload MSI generation (WiX 6) in src/Workload/" +globs: + - "src/Workload/**" + - "eng/NuGetVersions.targets" + - "eng/Versions.props" +--- + +# Workload MSI Generation (WiX 6) + +## Architecture Overview + +`src/Workload/workloads.csproj` generates MSIs for Visual Studio workload insertion using the arcade `CreateVisualStudioWorkload` task. As of .NET 11, this uses **WiX 6** (wix.exe) instead of WiX 3 (candle/light). + +Full documentation: [docs/design/WorkloadMsi.md](/docs/design/WorkloadMsi.md) + +## Critical Rules + +### DO NOT + +- **Do NOT change TargetFramework** from `netstandard2.0` — this avoids NU1212 errors with `Microsoft.Wix` (DotnetTool package type) +- **Do NOT remove `ExcludeAssets="all"`** from `Microsoft.Wix` PackageReference — required for DotnetTool compatibility +- **Do NOT remove `GenerateDependencyFile=false`** — needed for netstandard2.0 project that doesn't produce binaries +- **Do NOT add `UseWorkloadPackGroupsForVS`** — removed in arcade 11.x, will cause build errors +- **Do NOT use `WixToolsetPath`** — that's the WiX 3 parameter; use `WixExe`/`HeatExe`/`WixExtensions` instead +- **Do NOT reference `Microsoft.Signed.WiX`** — that's the old WiX 3 package + +### MUST + +- **Keep WiX package versions in sync** — All 5 WiX packages must use `$(MicrosoftWixVersion)` from `eng/Versions.props` +- **Use `GeneratePathProperty="true"`** on all WiX PackageReferences — needed for `$(Pkg*)` path resolution +- **Extension path pattern**: `$(Pkg)\wixext6\WixToolset..wixext.dll` +- **Test on internal pipeline** (ID 1095 at dnceng/internal) — MSI signing only works in internal builds + +## Key Files + +| File | Purpose | +|------|---------| +| `src/Workload/workloads.csproj` | Main MSI generation project — WiX 6 config + task invocation | +| `eng/Versions.props` | `MicrosoftWixVersion` property + arcade task versions | +| `eng/NuGetVersions.targets` | Central package version pins for WiX packages | + +## WiX 6 Package Dependencies + +```xml + +Microsoft.Wix +Microsoft.WixToolset.Heat +Microsoft.WixToolset.UI.wixext +Microsoft.WixToolset.Dependency.wixext +Microsoft.WixToolset.Util.wixext +``` + +## Arcade Task Parameters (WiX 6) + +```xml + + HeatExe="$(HeatExe)" + WixExtensions="@(WixExtensions)" + ... /> +``` + +The task requires arcade version **11.0.0-beta.26330.112** or later for WiX 6 support. + +## SWIX Build + +SWIX projects are built using `MicroBuild.Plugins.SwixBuild.Dotnet`. If this variant is deprecated in the future, the fallback is to use desktop MSBuild via `Exec` (as done in dotnet/dotnet#5265). + +## Validation + +After any MSI-related changes, verify on internal CI: + +1. `Wix4DependencyProvider` table exists in generated MSIs +2. `ProviderKeyName` is populated in `data/msi.json` (format: `PackageName,Version,Arch`) +3. All 3 VSDrop zips are produced (components, components-pre, packs) +4. SWIX vsman JSON has correct providerKey and installSizes + +## Troubleshooting + +### NU1212: Microsoft.Wix package type incompatibility +**Cause**: Project TFM is not `netstandard2.0` +**Fix**: Ensure `netstandard2.0` and `ExcludeAssets="all"` on Microsoft.Wix + +### "WixExe" or "HeatExe" parameter not recognized +**Cause**: Arcade version too old +**Fix**: Update `Microsoft.DotNet.Build.Tasks.Workloads` to 11.0.0-beta.26330.112+ + +### SWIX build failures / CodeTaskFactory errors +**Cause**: SwixBuild.Dotnet variant incompatible with current .NET +**Fix**: May need to switch to desktop MSBuild pattern (see dotnet/dotnet#5265) + +### Missing WiX extension at expected path +**Cause**: `GeneratePathProperty="true"` missing from PackageReference +**Fix**: Add `GeneratePathProperty="true"` to the PackageReference; path follows pattern `$(Pkg)\wixext6\...` diff --git a/.github/scripts/CopilotPipeline.Tests.ps1 b/.github/scripts/CopilotPipeline.Tests.ps1 index dc0f8429b7ea..013f7e3cdf93 100644 --- a/.github/scripts/CopilotPipeline.Tests.ps1 +++ b/.github/scripts/CopilotPipeline.Tests.ps1 @@ -67,7 +67,7 @@ Describe 'Copilot reviewer base branch allowlist' { $reviewTestsScript = Get-Content -Raw -LiteralPath ( Join-Path $PSScriptRoot 'Review-Tests.ps1') - $reviewTestsScript | Should -Match ([regex]::Escape('$model = "gpt-5.6-sol"')) + $reviewTestsScript | Should -Match ([regex]::Escape('$model = "gpt-6-astra"')) $reviewTestsScript | Should -Not -Match 'COPILOT_REVIEW_TESTS_MODEL' } } diff --git a/.github/scripts/Review-PR.Tests.ps1 b/.github/scripts/Review-PR.Tests.ps1 index 29b71074e7b6..9ecbe6af8e70 100644 --- a/.github/scripts/Review-PR.Tests.ps1 +++ b/.github/scripts/Review-PR.Tests.ps1 @@ -323,9 +323,9 @@ Describe 'Copilot reviewer configuration' { $content | Should -Not -Match 'transient auth-validation 401' } - It 'pins the local test reviewer to GPT-5.6 Sol with long context' { + It 'pins the local test reviewer to GPT-6 Astra with long context' { $reviewTests = Get-Content -Raw (Join-Path $PSScriptRoot 'Review-Tests.ps1') - $reviewTests | Should -Match ([regex]::Escape('$model = "gpt-5.6-sol"')) + $reviewTests | Should -Match ([regex]::Escape('$model = "gpt-6-astra"')) $reviewTests | Should -Not -Match 'COPILOT_REVIEW_TESTS_MODEL' $reviewTests | Should -Match ([regex]::Escape('"--context", "long_context"')) } @@ -984,6 +984,94 @@ Describe 'Snapshot diff asset publishing' { } Describe 'Simulator runtime provisioning contract' { + It 'pins every recovery download and smoke test to the selected Xcode version' { + $provisionContent | Should -Match ([regex]::Escape( + 'DOWNLOAD_ARGS=(-downloadPlatform iOS -architectureVariant "$RUNTIME_ARCHITECTURE" -buildVersion "${MAJOR}.${MINOR}")')) + ([regex]::Matches($provisionContent, [regex]::Escape( + 'sudo xcodebuild "${DOWNLOAD_ARGS[@]}"'))).Count | Should -Be 3 + $provisionContent | Should -Match 'SMOKE_RT=.*--arg req "\$\{MAJOR\}\.\$\{MINOR\}".*== \$req' + } + + It 'selects simulator downloads on for Xcode ' -TestCases @( + @{ HostArchitecture = 'arm64'; RuntimeArchitecture = 'arm64'; XcodeVersion = '26.5' }, + @{ HostArchitecture = 'x86_64'; RuntimeArchitecture = 'universal'; XcodeVersion = '26.5' }, + @{ HostArchitecture = 'arm64'; RuntimeArchitecture = 'arm64'; XcodeVersion = '27.0' }, + @{ HostArchitecture = 'x86_64'; RuntimeArchitecture = 'universal'; XcodeVersion = '27.0' } + ) -Skip:(-not (Get-Command bash -ErrorAction SilentlyContinue)) { + param($HostArchitecture, $RuntimeArchitecture, $XcodeVersion) + + $selection = [regex]::Match( + $provisionContent, + '(?ms)^\s*RUNTIME_ARCHITECTURE=universal.*?^\s*DOWNLOAD_ARGS=.*?\r?$') + $selection.Success | Should -BeTrue + $script = @' +HOST_ARCH="$1" +uname() { printf '%s\n' "$HOST_ARCH"; } +MAJOR="${2%.*}" +MINOR="${2#*.}" +'@ + "`n" + $selection.Value + "`n" + 'printf "%s\n" "${DOWNLOAD_ARGS[@]}"' + $actual = & bash -c $script -- $HostArchitecture $XcodeVersion + + $LASTEXITCODE | Should -Be 0 + ($actual -join ' ') | Should -Be "-downloadPlatform iOS -architectureVariant $RuntimeArchitecture -buildVersion $XcodeVersion" + } + + It 'handles before simulator recovery' -TestCases @( + @{ Case = 'unavailable 26.5 runtime'; Message = 'iOS 26.5 (arm64) is not available for download.'; DownloadExitCode = 70; ExpectedExitCode = 1 }, + @{ Case = 'unavailable 27.0 runtime'; Message = 'iOS 27.0 (arm64) is not available for download.'; DownloadExitCode = 70; ExpectedExitCode = 1 }, + @{ Case = 'CoreSimulator connection failure'; Message = 'Unable to connect to simulator'; DownloadExitCode = 70; ExpectedExitCode = 0 }, + @{ Case = 'successful download'; Message = 'Download complete'; DownloadExitCode = 0; ExpectedExitCode = 0 } + ) -Skip:(-not (Get-Command bash -ErrorAction SilentlyContinue)) { + param($Case, $Message, $DownloadExitCode, $ExpectedExitCode) + + $download = [regex]::Match( + $provisionContent, + '(?ms)^\s*DOWNLOAD_LOG=\$\(mktemp\).*?(?=^\s*if \[\[ "\$RC" != "0" \]\]; then)') + $download.Success | Should -BeTrue + $script = @' +DOWNLOAD_MESSAGE="$1" +DOWNLOAD_EXIT_CODE="$2" +sudo() { printf '%s\n' "$DOWNLOAD_MESSAGE"; return "$DOWNLOAD_EXIT_CODE"; } +MAJOR=26 +MINOR=5 +RUNTIME_ARCHITECTURE=arm64 +DOWNLOAD_ARGS=(-downloadPlatform iOS) +'@ + "`n" + $download.Value + "`n" + 'echo "RECOVERY_CHECK_RC=$RC"' + $actual = & bash -c $script -- $Message $DownloadExitCode + + $LASTEXITCODE | Should -Be $ExpectedExitCode + if ($ExpectedExitCode -eq 1) { + ($actual -join "`n") | Should -Match 'simulator recovery cannot fix an unavailable download' + ($actual -join "`n") | Should -Not -Match 'RECOVERY_CHECK_RC' + } else { + ($actual -join "`n") | Should -Match "RECOVERY_CHECK_RC=$DownloadExitCode" + } + } + + It 'requires a Ready runtime matching Xcode rather than any installed runtime' -Skip:(-not (Get-Command jq -ErrorAction SilentlyContinue)) { + $filterMatch = [regex]::Match( + $provisionContent, + '(?ms)IOS_MATCH_COUNT=\$\(xcrun simctl runtime list -j \| jq --arg id "\$REQUIRED_RUNTIME_ID" --arg req "\$\{MAJOR\}\.\$\{MINOR\}" ''(?.*?)''\)') + $filterMatch.Success | Should -BeTrue + $filter = $filterMatch.Groups['filter'].Value + + foreach ($case in @( + @{ Json = '{"x":{"state":"Ready","runtimeIdentifier":"com.apple.CoreSimulator.SimRuntime.iOS-26-4"}}'; Expected = 1 }, + @{ Json = '[{"state":"Ready","platformIdentifier":"com.apple.platform.iphonesimulator","version":"26.4.1"}]'; Expected = 1 }, + @{ Json = '{"x":{"state":"Ready","runtimeIdentifier":"com.apple.CoreSimulator.SimRuntime.iOS-26-5"}}'; Expected = 0 }, + @{ Json = '{"x":{"state":"Ready","runtimeIdentifier":"com.apple.CoreSimulator.SimRuntime.iOS-18-5"}}'; Expected = 0 }, + @{ Json = '{"x":{"state":"Deleting","runtimeIdentifier":"com.apple.CoreSimulator.SimRuntime.iOS-26-4"}}'; Expected = 0 }, + @{ Json = '{"x":{"runtimeIdentifier":"com.apple.CoreSimulator.SimRuntime.iOS-26-4"}}'; Expected = 0 } + )) { + $actual = $case.Json | & jq --arg id 'com.apple.CoreSimulator.SimRuntime.iOS-26-4' --arg req '26.4' $filter + + $LASTEXITCODE | Should -Be 0 + [int]$actual | Should -Be $case.Expected + } + + $provisionContent | Should -Match 'if \[\[ -z "\$IOS_MATCH_COUNT" \|\| "\$IOS_MATCH_COUNT" == "0" \]\]; then' + } + It 'normalizes array and object-map JSON before counting Ready runtime images' -Skip:(-not (Get-Command jq -ErrorAction SilentlyContinue)) { $filterMatch = [regex]::Match( $provisionContent, diff --git a/.github/scripts/Review-Tests.Tests.ps1 b/.github/scripts/Review-Tests.Tests.ps1 index 0c3f78eba267..953f06833fc0 100644 --- a/.github/scripts/Review-Tests.Tests.ps1 +++ b/.github/scripts/Review-Tests.Tests.ps1 @@ -82,8 +82,6 @@ Describe 'Review tests workflow contract' { $workflow | Should -Match 'add-comment:\r?\n max: 1' $workflow | Should -Match 'roles: \[admin, maintain, write\]' $workflow | Should -Match 'persist-credentials: false' - $workflow | Should -Match '(?m)^model: gpt-5.6-sol\r?$' - $workflowLock | Should -Match 'COPILOT_MODEL: gpt-5.6-sol' $evalSpec = Get-Content -LiteralPath (Join-Path $PSScriptRoot '../skills/review-test-failures/tests/eval.vally.yaml') -Raw $evalSpec | Should -Match '(?m)^ model: gpt-6.1-sol\r?$' $evalSpec | Should -Match '(?m)^ judge_model: gpt-6.1-sol\r?$' diff --git a/.github/scripts/RunTests.ps1 b/.github/scripts/RunTests.ps1 index 86a243e044e5..0448201eb5cf 100644 --- a/.github/scripts/RunTests.ps1 +++ b/.github/scripts/RunTests.ps1 @@ -147,7 +147,6 @@ $UnitTestProjects = [ordered]@{ "Essentials" = "src/Essentials/test/UnitTests/Essentials.UnitTests.csproj" "Graphics" = "src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj" "Resizetizer" = "src/SingleProject/Resizetizer/test/UnitTests/Resizetizer.UnitTests.csproj" - "Compatibility" = "src/Compatibility/Core/tests/Compatibility.UnitTests/Compatibility.Core.UnitTests.csproj" "DualScreen" = "src/Controls/Foldable/test/Controls.Foldable.UnitTests.csproj" } diff --git a/.github/scripts/Set-ScreenResolution.Tests.ps1 b/.github/scripts/Set-ScreenResolution.Tests.ps1 new file mode 100644 index 000000000000..f3762e7d5044 --- /dev/null +++ b/.github/scripts/Set-ScreenResolution.Tests.ps1 @@ -0,0 +1,76 @@ +#!/usr/bin/env pwsh +#Requires -Modules Pester + +BeforeAll { + $screenResolutionScript = Join-Path $PSScriptRoot '../../eng/scripts/Set-ScreenResolution.ps1' + $tokens = $null + $parseErrors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile( + $screenResolutionScript, + [ref]$tokens, + [ref]$parseErrors) + + if ($parseErrors.Count -gt 0) { + throw "Set-ScreenResolution.ps1 has parse errors: $($parseErrors -join '; ')" + } + + $functionDefinitions = $ast.FindAll({ + param($node) + $node -is [System.Management.Automation.Language.FunctionDefinitionAst] + }, $true) + + foreach ($functionName in @( + 'Get-ScreenResolutionProbeAction', + 'Test-ScreenResolutionApplySucceeded' + )) { + $definition = $functionDefinitions | + Where-Object Name -EQ $functionName | + Select-Object -First 1 + + if ($null -eq $definition) { + throw "Function '$functionName' was not found in Set-ScreenResolution.ps1" + } + + Invoke-Expression $definition.Extent.Text + } + + $setResolutionDefinition = $functionDefinitions | + Where-Object Name -EQ 'Set-ScreenResolution' | + Select-Object -First 1 + + if ($null -eq $setResolutionDefinition) { + throw "Function 'Set-ScreenResolution' was not found in Set-ScreenResolution.ps1" + } + + $setResolutionBody = $setResolutionDefinition.Extent.Text +} + +Describe 'Set-ScreenResolution native result decisions' { + It 'returns for CDS_TEST result ' -ForEach @( + @{ Result = 0; Expected = 'Apply' } + @{ Result = -1; Expected = 'Apply' } + @{ Result = -2; Expected = 'Reject' } + @{ Result = -3; Expected = 'Apply' } + @{ Result = -4; Expected = 'Apply' } + @{ Result = -5; Expected = 'Apply' } + ) { + Get-ScreenResolutionProbeAction -Result $Result | Should -Be $Expected + } + + It 'returns for real apply result ' -ForEach @( + @{ Result = 0; Expected = $true } + @{ Result = 1; Expected = $true } + @{ Result = -1; Expected = $false } + @{ Result = -2; Expected = $false } + @{ Result = -3; Expected = $false } + @{ Result = -4; Expected = $false } + @{ Result = -5; Expected = $false } + ) { + Test-ScreenResolutionApplySucceeded -Result $Result | Should -Be $Expected + } + + It 'uses the pure decisions in the native flow' { + $setResolutionBody | Should -Match 'Get-ScreenResolutionProbeAction\s+-Result\s+\$testResult' + $setResolutionBody | Should -Match 'Test-ScreenResolutionApplySucceeded\s+-Result\s+\$changeResult' + } +} diff --git a/.github/scripts/shared/Detect-TestsInDiff.ps1 b/.github/scripts/shared/Detect-TestsInDiff.ps1 index a3111c9191b4..055214f9a739 100644 --- a/.github/scripts/shared/Detect-TestsInDiff.ps1 +++ b/.github/scripts/shared/Detect-TestsInDiff.ps1 @@ -194,7 +194,6 @@ $UnitTestProjects = @{ "Essentials.UnitTests" = "src/Essentials/test/UnitTests/" "Graphics.Tests" = "src/Graphics/tests/Graphics.Tests/" "Resizetizer.UnitTests" = "src/SingleProject/Resizetizer/test/UnitTests/" - "Compatibility.Core.UnitTests" = "src/Compatibility/Core/tests/Compatibility.UnitTests/" "Controls.Foldable.UnitTests" = "src/Controls/Foldable/test/" } @@ -207,7 +206,6 @@ $UnitTestProjectPaths = @{ "Essentials.UnitTests" = "src/Essentials/test/UnitTests/Essentials.UnitTests.csproj" "Graphics.Tests" = "src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj" "Resizetizer.UnitTests" = "src/SingleProject/Resizetizer/test/UnitTests/Resizetizer.UnitTests.csproj" - "Compatibility.Core.UnitTests" = "src/Compatibility/Core/tests/Compatibility.UnitTests/Compatibility.Core.UnitTests.csproj" "Controls.Foldable.UnitTests" = "src/Controls/Foldable/test/Controls.Foldable.UnitTests.csproj" } diff --git a/.github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 b/.github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 index 1aa7ee32bcae..cd65fea7fea4 100644 --- a/.github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 +++ b/.github/skills/verify-tests-fail-without-fix/scripts/verify-tests-fail.ps1 @@ -288,7 +288,6 @@ $script:UnitTestProjectMap = @{ "Essentials.UnitTests" = "src/Essentials/test/UnitTests/Essentials.UnitTests.csproj" "Graphics.Tests" = "src/Graphics/tests/Graphics.Tests/Graphics.Tests.csproj" "Resizetizer.UnitTests" = "src/SingleProject/Resizetizer/test/UnitTests/Resizetizer.UnitTests.csproj" - "Compatibility.Core.UnitTests" = "src/Compatibility/Core/tests/Compatibility.UnitTests/Compatibility.Core.UnitTests.csproj" } # Maps device test project keys to the -Project parameter of Run-DeviceTests.ps1 diff --git a/.github/workflows/bump-global-json.yml b/.github/workflows/bump-global-json.yml index d38dc9ad6d2d..becb0780af8c 100644 --- a/.github/workflows/bump-global-json.yml +++ b/.github/workflows/bump-global-json.yml @@ -26,7 +26,8 @@ jobs: run: | set -exo pipefail - sudo apt-get install libxml2-utils + sudo apt-get update + sudo apt-get install --yes libxml2-utils DOTNET_VERSION=$(xmllint --xpath '/Project/PropertyGroup/MicrosoftNETSdkPackageVersion/text()' eng/Versions.props) jq --arg v "$DOTNET_VERSION" '.tools.dotnet = $v' global.json > global.json.tmp diff --git a/.github/workflows/powershell-script-tests.yml b/.github/workflows/powershell-script-tests.yml index f0ae5f92f8ae..29ea0c302501 100644 --- a/.github/workflows/powershell-script-tests.yml +++ b/.github/workflows/powershell-script-tests.yml @@ -25,6 +25,13 @@ on: - '.github/skills/trace-regression/**' - '.github/workflows/**' - 'eng/scripts/**' + - 'Directory.Build.props' + - 'global.json' + - 'eng/Versions.props' + - 'eng/Version.Details.xml' + - 'eng/helix.proj' + - 'eng/pipelines/arcade/stage-helix-tests.yml' + - 'eng/pipelines/ci.Tests.ps1' - 'eng/pipelines/ci-copilot.yml' - 'eng/pipelines/ci-official.yml' - 'eng/pipelines/ci-official.Tests.ps1' @@ -98,6 +105,7 @@ jobs: '.github/scripts' '.github/skills/run-device-tests/scripts' '.github/skills/verify-tests-fail-without-fix/scripts' + 'eng/pipelines/ci.Tests.ps1' 'eng/pipelines/ci-official.Tests.ps1' 'eng/pipelines/ci-official-release.Tests.ps1' 'eng/scripts/nuget_release_packages.Tests.ps1' diff --git a/Directory.Build.Override.props.in b/Directory.Build.Override.props.in index c04c2e7095b8..bb35a1797fcc 100644 --- a/Directory.Build.Override.props.in +++ b/Directory.Build.Override.props.in @@ -5,7 +5,6 @@ Cake writes out to these properties when you've used a specific target switch --> <_IncludeWindows> - <_IncludeTizen> <_IncludeAndroid> <_IncludeIos> <_IncludeMacCatalyst> @@ -13,10 +12,9 @@ - <_SpecificPlatformRequested Condition="'$(_IncludeAndroid)' == 'true' OR '$(_IncludeWindows)' == 'true' OR '$(_IncludeTizen)' == 'true' OR '$(_IncludeIos)' == 'true' OR '$(_IncludeMacCatalyst)' == 'true' OR '$(_IncludeMacOS)' == 'true'">true + <_SpecificPlatformRequested Condition="'$(_IncludeAndroid)' == 'true' OR '$(_IncludeWindows)' == 'true' OR '$(_IncludeIos)' == 'true' OR '$(_IncludeMacCatalyst)' == 'true' OR '$(_IncludeMacOS)' == 'true'">true false false - false false false false diff --git a/Directory.Build.props b/Directory.Build.props index 0ce7564bcca6..c770b367790d 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,16 +2,6 @@ - - - - <_MauiXamlSourceGenBackCompat>true - $(DefineConstants);_MAUIXAML_SOURCEGEN_BACKCOMPAT - - true @@ -58,12 +48,12 @@ - <_MauiDotNetVersionMajor Condition="'$(_MauiDotNetVersionMajor)' == ''">10 + <_MauiDotNetVersionMajor Condition="'$(_MauiDotNetVersionMajor)' == ''">11 <_MauiDotNetVersionMinor Condition="'$(_MauiDotNetVersionMinor)' == ''">0 <_MauiDotNetVersion Condition="'$(_MauiDotNetVersion)' == ''">$(_MauiDotNetVersionMajor).$(_MauiDotNetVersionMinor) <_MauiDotNetTfm Condition="'$(_MauiDotNetTfm)' == ''">net$(_MauiDotNetVersion) - <_MauiPreviousDotNetVersionMajor Condition="'$(_MauiPreviousDotNetVersionMajor)' == ''">9 + <_MauiPreviousDotNetVersionMajor Condition="'$(_MauiPreviousDotNetVersionMajor)' == ''">10 <_MauiPreviousDotNetVersionMinor Condition="'$(_MauiPreviousDotNetVersionMinor)' == ''">0 <_MauiPreviousDotNetVersion Condition="'$(_MauiPreviousDotNetVersion)' == ''">$(_MauiPreviousDotNetVersionMajor).$(_MauiPreviousDotNetVersionMinor) <_MauiPreviousDotNetVersionNoDot Condition="'$(_MauiPreviousDotNetVersionNoDot)' == ''">$(_MauiPreviousDotNetVersionMajor)$(_MauiPreviousDotNetVersionMinor) @@ -93,8 +83,6 @@ <_MauiTargetPlatformIstvOS Condition="'$(_MauiTargetPlatformIdentifier)' == 'tvos'">True <_MauiTargetPlatformIsWindows>false <_MauiTargetPlatformIsWindows Condition="$(_MauiTargetPlatformIdentifier.Contains('windows')) == 'True'">True - <_MauiTargetPlatformIsTizen>false - <_MauiTargetPlatformIsTizen Condition="'$(_MauiTargetPlatformIdentifier)' == 'tizen'">True @@ -111,26 +99,19 @@ $(DotNetWorkloadInstallLocation)..\..\packs\ $([System.Text.RegularExpressions.Regex]::Match($([System.IO.File]::ReadAllText('$(DotNetWorkloadInstallLocation)\microsoft.net.sdk.macos\WorkloadManifest.json')), '$(DotNetWorkloadVersionRegex)')) - $([System.Text.RegularExpressions.Regex]::Match($([System.IO.File]::ReadAllText('$(DotNetWorkloadInstallLocation)\samsung.net.sdk.tizen\WorkloadManifest.json')), $(DotNetWorkloadVersionRegex))) true - true true true - true true true true - false - true true - - false true true true @@ -139,7 +120,6 @@ $(DefineConstants);WINDOWS - $(DefineConstants);COMPATIBILITY_ENABLED $(DefineConstants);ENABLE_PREVIOUS_TFM_BUILDS @@ -167,20 +147,19 @@ - 26.0 - 26.0 - 26.0 - 26.0 - 36.0 + 27.0 + 27.0 + 27.0 + 27.0 + 37.0 - 26.0 - 26.0 - 26.0 - 26.0 - 36.0 + 27.0 + 27.0 + 27.0 + 27.0 + 37.0 10.0.19041.0 10.0.20348.0 - 7.0 18.0 18.0 @@ -189,7 +168,6 @@ 35.0 10.0.19041.0 10.0.20348.0 - 7.0 10.0.17763.0 @@ -199,7 +177,6 @@ net$(_MauiDotNetVersion)-windows$(WindowsTargetFrameworkVersion);net$(_MauiDotNetVersion)-windows$(Windows2TargetFrameworkVersion) - net$(_MauiDotNetVersion)-tizen$(TizenTargetFrameworkVersion);$(MauiPlatforms) $(WindowsMauiPlatforms);$(MauiPlatforms) net$(_MauiDotNetVersion)-android$(AndroidTargetFrameworkVersion);$(MauiPlatforms) net$(_MauiDotNetVersion)-android;$(MauiPlatforms) @@ -210,42 +187,38 @@ net$(_MauiPreviousDotNetVersion)-windows$(WindowsPreviousTargetFrameworkVersion);net$(_MauiPreviousDotNetVersion)-windows$(Windows2PreviousTargetFrameworkVersion) - net$(_MauiPreviousDotNetVersion)-tizen$(TizenPreviousTargetFrameworkVersion);$(MauiPreviousPlatforms) $(WindowsMauiPreviousPlatforms);$(MauiPreviousPlatforms) net$(_MauiPreviousDotNetVersion)-android$(AndroidPreviousTargetFrameworkVersion);$(MauiPreviousPlatforms) net$(_MauiPreviousDotNetVersion)-maccatalyst$(MacCatalystPreviousTargetFrameworkVersion);$(MauiPreviousPlatforms) net$(_MauiPreviousDotNetVersion)-ios$(IosPreviousTargetFrameworkVersion);$(MauiPreviousPlatforms) - net$(_MauiDotNetVersion)-tizen;$(MauiSamplePlatforms) $(WindowsMauiPlatforms);$(MauiSamplePlatforms) net$(_MauiDotNetVersion)-android;$(MauiSamplePlatforms) net$(_MauiDotNetVersion)-maccatalyst;$(MauiSamplePlatforms) net$(_MauiDotNetVersion)-ios;$(MauiSamplePlatforms) - net$(_MauiPreviousDotNetVersion)-tizen;$(MauiSamplePreviousPlatforms) $(WindowsMauiPreviousPlatforms);$(MauiSamplePreviousPlatforms) net$(_MauiPreviousDotNetVersion)-android;$(MauiSamplePreviousPlatforms) net$(_MauiPreviousDotNetVersion)-maccatalyst;$(MauiSamplePreviousPlatforms) net$(_MauiPreviousDotNetVersion)-ios;$(MauiSamplePreviousPlatforms) - + $(WindowsMauiPlatforms);$(MauiDeviceTestsPlatforms) net$(_MauiDotNetVersion)-android;$(MauiDeviceTestsPlatforms) net$(_MauiDotNetVersion)-maccatalyst;$(MauiDeviceTestsPlatforms) net$(_MauiDotNetVersion)-ios;$(MauiDeviceTestsPlatforms) - + $(WindowsMauiPlatforms);$(MauiEmbeddingPlatforms) net$(_MauiDotNetVersion)-android;$(MauiEmbeddingPlatforms) net$(_MauiDotNetVersion)-maccatalyst;$(MauiEmbeddingPlatforms) net$(_MauiDotNetVersion)-ios;$(MauiEmbeddingPlatforms) - + $(WindowsMauiPlatforms);$(MauiManualTestsPlatforms) net$(_MauiDotNetVersion)-android;$(MauiManualTestsPlatforms) net$(_MauiDotNetVersion)-maccatalyst;$(MauiManualTestsPlatforms) net$(_MauiDotNetVersion)-ios;$(MauiManualTestsPlatforms) - net$(_MauiPreviousDotNetVersion)-tizen;$(MauiManualTestsPreviousPlatforms) $(WindowsMauiPreviousPlatforms);$(MauiManualTestsPreviousPlatforms) net$(_MauiPreviousDotNetVersion)-android;$(MauiManualTestsPreviousPlatforms) net$(_MauiPreviousDotNetVersion)-maccatalyst;$(MauiManualTestsPreviousPlatforms) @@ -293,4 +266,10 @@ $(CoreCompileDependsOn);CreateCompilerGeneratedFilesOutputPath + + + + + true + diff --git a/Directory.Build.targets b/Directory.Build.targets index 6713b61f0524..830c2a839eb9 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -33,36 +33,32 @@ - $(NoWarn);NETSDK1206;NU1702 + + $(NoWarn);NETSDK1206;NU1702;IL6001;AD0001 $(MSBuildWarningsAsMessages);MSB4011;MSB3277;NETSDK1206;NU1702 - 13.0 - 13.0 + 15.0 + 15.0 10.0 10.0 - 15.0 - 15.0 + 17.0 + 17.0 12.0 12.0 - 21.0 - 21.0 - - - 6.5 - 6.5 + 24.0 + 24.0 - - + + + + + + + + + - - - - - - - @@ -25,7 +26,12 @@ - + + + + + + diff --git a/docs/DevelopmentTips.md b/docs/DevelopmentTips.md index 11c2f633173b..37b113671261 100644 --- a/docs/DevelopmentTips.md +++ b/docs/DevelopmentTips.md @@ -23,11 +23,50 @@ The below parameters can be used with the `dotnet cake` command in the root of y > **Note:** For provisioning .NET SDK and workloads, prefer using `./build.sh -restore` (or `./build.cmd -restore` on Windows) instead of Cake. The Cake targets below are utility commands. +#### Apple builds on .NET 11 + +The `net11.0` branch uses the Apple 27.0 workload and requires Xcode 27. +The managed and native iOS deployment minimum is 15.0; the Mac Catalyst +minimum remains 17.0. The Apple workload manifests also require the .NET 10 +26.5.10322 compatibility SDK packs, which are pinned separately from the +.NET 11 packs. + +CI compiles Apple frameworks, apps and packages on the GoldenGate Aces image +until standard hosted images provide Xcode 27. Prebuilt iOS UI-test apps +continue to execute on Tahoe with Xcode 26.5, and Mac Catalyst UI tests use +macOS 14, because the GoldenGate Appium execution environment has not been +validated. These execution images do not determine the app's build SDK. +Simulator runtime provisioning and its bounded recovery remain enabled. +The macOS 14 execution image is scheduled to retire on November 2, 2026; +its replacement needs separate Mac2 validation. + +Normal builds validate the Xcode version rather than bypassing an SDK mismatch. +To use a particular installed Xcode without changing the global selection, +set `DEVELOPER_DIR` for the build command: + +```bash +DEVELOPER_DIR=/Applications/Xcode_27.app/Contents/Developer ./build.sh -restore -build +``` + +#### Tizen backends on .NET 11 + +Starting with .NET 11, this repository no longer includes a Tizen platform implementation or +builds and packages Tizen target frameworks. Tizen backends must supply their own native +dependencies, handlers, lifecycle integration, and resource and manifest processing outside +this repository. + +Platform-neutral compatibility APIs remain available for external backends, including +`DevicePlatform.Tizen`, the legacy `Device.Tizen` constant, `OnPlatformExtension.Tizen`, +`PlatformConfiguration.Tizen`, and the managed `TizenSpecific` attached properties. +External backends can use the [platform-neutral handler contracts](design/ExternalPlatformBackends.md) +and register their platform folders with `MauiPlatformSpecificFolder`; the built-in +`Platforms/Tizen` registration and `IncludeTizenTargetFrameworks` build switch have been removed. + #### PublicAPI Management `--target=publicapi` - Clears and regenerates PublicAPI.Unshipped.txt files across all MAUI projects (Core, Controls, Essentials, Graphics) - Use this when you've added new public APIs and are getting build errors about missing API declarations -- Automatically skips Windows-specific files when not running on Windows, and always skips Tizen files +- Automatically skips Windows-specific files when not running on Windows ```bash dotnet cake --target=publicapi @@ -224,6 +263,29 @@ The harness regression tests do not require MAUI workloads or an emulator: dotnet test src/TestUtils/src/Microsoft.Maui.IntegrationTests --filter "FullyQualifiedName~ToolRunnerTests|FullyQualifiedName~BuildWarningsUtilitiesTests" ``` +## Handler Initialization Attribution + +`Microsoft.Maui` contains opt-in instrumentation that attributes handler initialization time +(`ElementHandler.SetVirtualView`, `PropertyMapper.UpdateProperties`/`UpdateProperty`) using +`System.Diagnostics.Activity`. It is **compile-time** opt-in: it is only compiled when the +`MauiEnableHandlerInstrumentation` MSBuild property is set to `true`, which defines the +`HANDLER_INSTRUMENTATION` constant. A default build compiles none of it, so the handler/mapper hot +paths are unchanged. + +```bash +# Build Core (and anything referencing it) with the instrumentation compiled in +dotnet build src/Core/src/Core.csproj -p:MauiEnableHandlerInstrumentation=true + +# Build and run the Core unit tests with the instrumented code path (also run in CI) +dotnet cake --target=dotnet-test-handler-instrumentation +``` + +The spans are emitted on the same `ActivitySource` name/version as the rest of MAUI's diagnostics +(`Microsoft.Maui`, `1.0.0`, see `DiagnosticsIdentity`), so a single `ActivityListener` subscription +observes handler, mapper, and layout spans. Emitted operations: `SetVirtualView`, +`CreatePlatformElement`, `AssignHandler`, `ConnectHandler`, `ResolveMapper`, `UpdateProperties`, and +`MapProperty` (tagged with `element.type`, `handler.type`, and, for `MapProperty`, `mapper.property`). + ## Running Device Tests on Helix .NET MAUI now supports running device tests on [.NET Engineering Services Helix](https://helix.dot.net) using XHarness. Helix provides cloud-based device testing infrastructure that enables running tests across multiple platforms and devices in parallel. diff --git a/docs/UITesting-Guide.md b/docs/UITesting-Guide.md index af1d6707ef04..58e36229f2a3 100644 --- a/docs/UITesting-Guide.md +++ b/docs/UITesting-Guide.md @@ -49,6 +49,62 @@ dotnet build ./src/Provisioning/Provisioning.csproj -t:ProvisionAppium -p:SkipAp - Xcode with command-line tools installed - iOS Simulator configured +## Android Shell Handler and Renderer Lanes + +The main Android UI-test stage runs `Shell1` and `Shell2` as separate matrix jobs +using Shell Handler. The separate `android_ui_tests_shell_renderer` stage runs the +same two shards as separate matrix jobs using Shell Renderer. Each renderer job +uses its shard category as the test filter, so the entire Shell suite is not +repeated in each job. Both stages depend on `build_ui_tests_coreclr` and download +the same `ui-tests-samples-coreclr` artifact; there is no separate app build or +MSBuild property for Shell selection. + +Android Mono is not supported when targeting .NET 11 or later. Enabling +`UseMonoRuntime=true` for `net11.0-android` fails with `NETSDK1242`, so there is no +Android Mono build or test lane on this branch. Mono coverage requires a separate +.NET 10-targeted app build; the shared templates' `Mono` option does not make a +.NET 11 Android app compatible with Mono. + +The renderer lane sets `testConfigurationArgs: "ShellRenderer"`. The Android Cake +runner forwards this through `TEST_CONFIGURATION_ARGS` to Appium, which passes it +as an activity intent extra on startup and relaunch. `MainActivity` reads the +setting before creating the window, and the Shell handler factory in +`MauiProgram.cs` selects the renderer when each Shell is created. Without the +setting, it selects Shell Handler. The selected implementation is logged to logcat +under the `MauiUITests` tag. + +To run the renderer configuration locally with an already-built HostApp: + +```bash +./build.sh -Script eng/devices/android.cake --target=uitest \ + --test-filter="TestCategory=Shell" --TEST_CONFIGURATION_ARGS="ShellRenderer" +``` + +The `Shell` umbrella category still selects the complete suite locally. Use +`TestCategory=Shell1` or `TestCategory=Shell2` to run an individual shard, matching +the CI jobs. + +Omit `--TEST_CONFIGURATION_ARGS` (and unset that environment variable) to run the +default Shell Handler configuration. Both configurations use the existing Android +snapshot baselines. + +For a known renderer-only failure, call the shared test extension at the start of +the affected test, including the tracking issue in the reason: + +```csharp +this.IgnoreOnAndroidShellRenderer( + "Fails with Android ShellRenderer: https://github.com/dotnet/maui/issues/39461"); +``` + +This reports the test as ignored only in the Android Shell Renderer configuration. +The default Handler lane and other platforms continue running the test. + +For a known Handler-only failure, use +`this.IgnoreOnAndroidShellHandler("Reason and tracking issue URL")` instead. This +skips only the Android Handler configuration, leaving Renderer coverage enabled. +Both helpers leave other platforms unaffected. Use only the relevant helper for +each affected test and remove the call when its issue is fixed. + ## Creating a UI Test ### Step 1: Create the HostApp Page diff --git a/docs/design/APIChangeTracking.md b/docs/design/APIChangeTracking.md index de31c16181da..408a7b985413 100644 --- a/docs/design/APIChangeTracking.md +++ b/docs/design/APIChangeTracking.md @@ -132,9 +132,6 @@ PublicAPI ├─ net-maccatalyst │ ├─ PublicAPI.Shipped.txt │ └─ PublicAPI.Unshipped.txt - ├─ net-tizen - │ ├─ PublicAPI.Shipped.txt - │ └─ PublicAPI.Unshipped.txt ├─ net-windows │ ├─ PublicAPI.Shipped.txt │ └─ PublicAPI.Unshipped.txt diff --git a/docs/design/BlazorWebViewExternalBackends.md b/docs/design/BlazorWebViewExternalBackends.md new file mode 100644 index 000000000000..d35c34cbf2df --- /dev/null +++ b/docs/design/BlazorWebViewExternalBackends.md @@ -0,0 +1,175 @@ +# External BlazorWebView backends + +`BlazorWebView` ships built-in handlers for Android, iOS, MacCatalyst and Windows. A third-party +package can supply a handler for any other platform by implementing +`Microsoft.AspNetCore.Components.WebView.Maui.IBlazorWebViewHandler` and registering it with +`IMauiBlazorWebViewBuilder.UsePlatformHandler`. + +This document describes the public seams such a backend needs. Everything here is usable from a +package that only references the shipped MAUI NuGet packages — no `InternalsVisibleTo`, no +reflection, and no copied source. `src/BlazorWebView/tests/MauiBlazorWebView.ExternalHandler.UnitTests` +is an in-repo assembly that is deliberately *not* granted `InternalsVisibleTo` and exercises each of +these seams the way an external backend would. + +## Registration + +```csharp +builder.Services + .AddMauiBlazorWebView() + .UsePlatformHandler(); +``` + +Registration is last-registration-wins through the MAUI handler collection, so call +`UsePlatformHandler` *after* `AddMauiBlazorWebView()` and after any downstream library that calls +`AddMauiBlazorWebView()` again. + +## Dispatcher + +A `WebViewManager` needs a Blazor `Dispatcher`. Rather than writing an adapter, construct MAUI's +public `MauiDispatcher` over the `IDispatcher` from the handler's services, so Blazor's thread +affinity matches the rest of MAUI on that platform: + +```csharp +var dispatcher = new MauiDispatcher(Services!.GetRequiredService()); +``` + +## Surfacing the native web view + +`BlazorWebViewInitializedEventArgs` declares a strongly typed `WebView` property only for the target +frameworks that MAUI has a built-in backend for. A backend for any other platform supplies the +native control through the constructor instead: + +```csharp +VirtualView.BlazorWebViewInitializing(new BlazorWebViewInitializingEventArgs()); +VirtualView.BlazorWebViewInitialized(new BlazorWebViewInitializedEventArgs(PlatformView)); +``` + +App code then reads it from the platform-neutral, read-only `PlatformWebView` property: + +```csharp +blazorWebView.BlazorWebViewInitialized += (s, e) => +{ + var native = (MyPlatformWebView)e.PlatformWebView!; +}; +``` + +`PlatformWebView` is deliberately read-only and write-once: only the handler raising the event can +supply the value, so one event subscriber cannot change what later subscribers observe. On target +frameworks where the strongly typed `WebView` property exists, both properties report the same +instance, and `WebView` reports `null` if the stored value is not of that platform's web view type. +The property is scoped to the MAUI package; the WPF and WinForms BlazorWebView packages keep only +their existing strongly typed `WebView` property. + +## Root components + +`RootComponent.AddToWebViewManagerAsync` and `RootComponent.RemoveFromWebViewManagerAsync` apply the +validation that MAUI's built-in handlers rely on (a `Selector` is required for both, and a +`ComponentType` is required to add). A backend should call them rather than reimplementing the +validation, so that error messages and ordering stay consistent across platforms: + +```csharp +foreach (var rootComponent in VirtualView.RootComponents) +{ + // Before the page is attached this completes synchronously. + _ = rootComponent.AddToWebViewManagerAsync(_webViewManager); +} +``` + +Call both methods on the `WebViewManager.Dispatcher` thread, and keep handling +`RootComponentsCollection.CollectionChanged` so components added or removed after startup are +applied to the manager. + +## Static content hot reload + +Static content hot reload (serving updated `wwwroot` assets, most notably CSS, without restarting +the app) is exposed through `BlazorWebViewStaticContentHotReload`. A backend participates in two +places, mirroring what the built-in handlers do — the built-in MAUI handlers call this same public +seam. + +Once, after creating the `WebViewManager` and before navigating: + +```csharp +_ = BlazorWebViewStaticContentHotReload.TryAttachToWebViewManager(_webViewManager); +``` + +`TryAttachToWebViewManager` returns `null` when hot reload is not supported by the current runtime +and nothing was attached, or a `Task` that completes when the notifier root component has been +registered. Awaiting it is optional when attaching before navigation, because registration completes +synchronously until a page is attached. Attaching is idempotent per `WebViewManager` instance: +concurrent and repeat calls return the current attach task rather than failing on the notifier's +fixed root component selector. If an attach fails, a later call retries the registration. + +On teardown, **if your handler disposes its `WebViewManager` — as all the built-in handlers do — there +is nothing to detach.** Disposing tears the notifier down along with the renderer, and a reconnected +handler builds a new manager, which attaches cleanly. Do not call detach and then immediately dispose: + +```csharp +// DON'T: the detach is still in flight when disposal tears down the renderer underneath it. +_ = BlazorWebViewStaticContentHotReload.TryDetachFromWebViewManager(_webViewManager); +await _webViewManager.DisposeAsync(); +``` + +`TryDetachFromWebViewManager` is for the narrower case of a handler that **keeps a manager alive** and +wants to stop, and possibly later restart, hot reload on it — detaching is what allows a later +`TryAttachToWebViewManager` on that same manager to take effect. Await it if you need the notifier to +be gone before you continue: + +```csharp +var detach = BlazorWebViewStaticContentHotReload.TryDetachFromWebViewManager(_webViewManager); +if (detach is not null) +{ + await detach; +} +``` + +It returns `null` when nothing was attached, so it is safe to call unconditionally and is idempotent. +If the manager is disposed while a detach is still in flight, the returned task completes successfully +rather than faulting, so discarding it cannot produce an unobserved exception. A subsequent attach is +sequenced after an in-flight detach even when the detach task was discarded. Detaching is never required +to prevent a leak — the attachment is tracked weakly and the notifier unsubscribes when its root +component is disposed. + +And while resolving each static content request: + +```csharp +if (BlazorWebViewStaticContentHotReload.TryGetUpdatedStaticContent( + _contentRootRelativeToAppRoot, requestAbsoluteUri, out var hotReloaded, out var hotReloadedContentType)) +{ + originalContent?.Dispose(); + statusCode = 200; + content = hotReloaded!; + if (hotReloadedContentType is not null) + { + headers["Content-Type"] = hotReloadedContentType; + } +} +``` + +This is a query, not a mutation: it reports content and lets the handler apply it to whatever +response state it owns. The returned stream is fresh per call and the caller is responsible for +disposing it, along with any content it had already resolved. The in-box Android, iOS and +Windows web view managers apply hot-reloaded content through exactly this call, so the public seam +is the same code path MAUI itself ships on. + +Both members are inert when hot reload is unavailable — that is, when +`System.Reflection.Metadata.MetadataUpdater.IsSupported` is `false` — so they can be called +unconditionally. Static content hot reload is distinct from Razor component hot reload, which needs +no handler participation. + +## What is intentionally not public + +The static content **response cache** and its policy helpers (`StaticContentResponseCache`, +`StaticContentResponseCachePolicy`, `StaticContentCacheControl`, `QueryStringHelper`) remain +internal. They implement the caching behavior that `BlazorWebView.StaticContentCacheControlProvider` +opts into, but the storage shape, eviction, entry-size limits and `Cache-Control`/`Pragma` parsing +are implementation details we want to keep free to change. An external backend is expected to +implement its own request caching, and to call +`IBlazorWebView.StaticContentCacheControlProvider` — which *is* public — to let apps influence the +`Cache-Control` header it emits. If you need the shared cache itself, please open an issue +describing the scenario rather than duplicating the internals. + +## Windows note + +On Windows, a handler that owns a `WebView2` must either expose it directly as its `PlatformView`, +so the framework can close it when the window is destroyed, or close the wrapped control from its +own disconnect logic. This preserves the built-in workaround for microsoft-ui-xaml issue 6872. diff --git a/docs/design/ExternalPlatformBackends.md b/docs/design/ExternalPlatformBackends.md new file mode 100644 index 000000000000..0c1fb6e0c8e0 --- /dev/null +++ b/docs/design/ExternalPlatformBackends.md @@ -0,0 +1,407 @@ +# 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 (NETSTANDARD || !PLATFORM) || (NET6_0_OR_GREATER && !IOS) +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 an in-box platform target framework, +> `ViewHandler` constrains `TPlatformView` to that platform's base view +> type (`UIKit.UIView`, `Android.Views.View`, `Microsoft.UI.Xaml.FrameworkElement`). +> 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 supported platform set cannot drift between +them. Tizen is no longer an in-box target framework; an out-of-tree Tizen backend can consume the +platform-neutral contracts instead. `ExternalBackendTargetFrameworkTests` enforces the shared matrix — 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` | + +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`. 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/docs/design/FeatureSwitches.md b/docs/design/FeatureSwitches.md index bbf71be51c53..96e531331907 100644 --- a/docs/design/FeatureSwitches.md +++ b/docs/design/FeatureSwitches.md @@ -6,13 +6,14 @@ The following switches are toggled for applications running on Mono for `TrimMod | MSBuild Property Name | AppContext Setting | Description | |-|-|-| +| MauiXamlInflator | N/A | Controls how XAML files are processed. See [XAML Inflator](#mauixamlinflator) section below. | +| MauiCssEnabled | Microsoft.Maui.RuntimeFeature.IsCssEnabled | When disabled, CSS stylesheets cannot be used. Defaults to `false` when no `MauiCss` items are present in the project, and `true` otherwise. | | MauiEnableIVisualAssemblyScanning | Microsoft.Maui.RuntimeFeature.IsIVisualAssemblyScanningEnabled | When enabled, MAUI will scan assemblies for types implementing `IVisual` and for `[assembly: Visual(...)]` attributes and register these types. | | MauiShellSearchResultsRendererDisplayMemberNameSupported | Microsoft.Maui.RuntimeFeature.IsShellSearchResultsRendererDisplayMemberNameSupported | When disabled, it is necessary to always set `ItemTemplate` of any `SearchHandler`. Displaying search results through `DisplayMemberName` will not work. | | MauiQueryPropertyAttributeSupport | Microsoft.Maui.RuntimeFeature.IsQueryPropertyAttributeSupported | When disabled, the `[QueryProperty(...)]` attributes won't be used to set values to properties when navigating. | | MauiImplicitCastOperatorsUsageViaReflectionSupport | Microsoft.Maui.RuntimeFeature.IsImplicitCastOperatorsUsageViaReflectionSupported | When disabled, MAUI won't look for implicit cast operators when converting values from one type to another. This feature is not trim-compatible. | | _MauiBindingInterceptorsSupport | Microsoft.Maui.RuntimeFeature.AreBindingInterceptorsSupported | When disabled, MAUI won't intercept any calls to `SetBinding` methods and try to compile them. Enabled by default. | | MauiEnableXamlCBindingWithSourceCompilation | Microsoft.Maui.RuntimeFeature.XamlCBindingWithSourceCompilationEnabled | When enabled, MAUI will compile all bindings, including those where the `Source` property is used. | -| MauiHybridWebViewSupported | Microsoft.Maui.RuntimeFeature.IsHybridWebViewSupported | Enables HybridWebView, which makes use of dynamic System.Text.Json serialization features | | MauiNamescopesSupported | Microsoft.Maui.RuntimeFeature.AreNamescopesSupported | Enable support for Namescopes, FindByName if the application uses it, or to keep supporting runtime and XamlC XAML inflators | | EnableDiagnostics | Microsoft.Maui.RuntimeFeature.EnableDiagnostics | Enables diagnostic for the running app | | EnableMauiDiagnostics | Microsoft.Maui.RuntimeFeature.EnableMauiDiagnostics | Enables MAUI specific diagnostics, like VisualDiagnostics and BindingDiagnostics. Defaults to EnableDiagnostics | @@ -34,6 +35,56 @@ Set the maximum `UriImageSource` download size in the app project: ``` +## MauiXamlInflator + +Controls how XAML files are processed and compiled. Starting with .NET 11, the default value is `SourceGen`. + +**Available Values:** +- `SourceGen` (default) - XAML is compiled to C# at build time using a source generator. This provides the best performance and debugging experience, including full XAML Hot Reload support. +- `Runtime` - XAML is inflated at runtime. This has negative performance impact and is deprecated. +- `XamlC` - XAML is compiled using the XamlC IL weaver after compilation. This prevents some debugging capabilities like XAML Hot Reload and is deprecated. + +**Example:** +```xml + + + + + + Runtime + +``` + +**Per-file override:** +You can override the inflator for individual XAML files using item metadata: +```xml + + + +``` + +**Changes in .NET 11:** +- The default inflator changed from configuration-based (Runtime in Debug, XamlC in Release) to `SourceGen` for all configurations. +- The `[XamlCompilation]` attribute is deprecated (produces warning) but still functional. + +**Changes in .NET 12:** +- The `[XamlCompilation]` attribute will be obsolete with `error: true` and becomes a no-op. Use MSBuild properties or item metadata instead. + +## MauiCssEnabled + +When this feature is disabled, CSS stylesheets cannot be parsed or applied to UI elements. Any attempt to use CSS will throw a `NotSupportedException`. + +**Default behavior**: In optimized builds (`PublishAot=true` or `TrimMode=full`), this feature is automatically disabled when your project has no `MauiCss` items (CSS files), and automatically enabled when CSS files are present. In development builds, CSS is always enabled regardless of whether `MauiCss` items are present. + +**When to enable manually**: If your app loads CSS stylesheets dynamically at runtime (e.g., from a network source or embedded resources) rather than including them as `MauiCss` build items, you need to explicitly enable this feature in your optimized builds: + +```xml + + true + +``` + +**Trimming benefits**: When disabled, the .NET trimmer can eliminate CSS-related code paths, reducing the final application size. ## MauiEnableIVisualAssemblyScanning When this feature is not enabled, custom and third party `IVisual` types will not be automatically discovered and registered. @@ -64,9 +115,7 @@ This feature is a counterpart of [XAML Compiled bindings](https://learn.microsof It is necessary to use this feature instead of the string-based bindings in NativeAOT apps and in apps with full trimming enabled. -## MauiHybridWebViewSupported - -When this feature is disabled, `HybridWebView` will not be available. This is the default for projects using `TrimMode=full` or `PublishAot=true`. +## MauiEnableXamlCBindingWithSourceCompilation ### Example use-case @@ -88,8 +137,6 @@ Compiled binding in XAML: