diff --git a/CHANGELOG.md b/CHANGELOG.md index 20ab496521..d6057acba6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -138,6 +138,59 @@ Conventions for contributors: ### Fixed +- **A pooled control no longer hands its previous renter's padding, background, + border or enabled state to the next one (issue #985).** + `Reconciler.ApplyModifiers` writes `Padding`, `CornerRadius`, + `BorderThickness`, `BorderBrush`, `Background` and `IsEnabled` onto `Control`, + `Border`, `Panel` and `StackPanel` receivers, but `ElementPool.CleanElement` + only ever reset the `Border` arm. On mount there is no previous element, so no + unset arm runs — a recycled `Button`, `ScrollViewer`, `Grid` or `VStack` + therefore started life carrying the *local* values the last renter had set, and + a local value outranks every `Style` setter in WinUI's dependency-property + precedence order. `Panel.Background` was the widest hole, since `VStack` / + `HStack` / `Grid` are all poolable. `CleanElement` now clears all six, in the + `FrameworkElement`-common region so the pool ⇄ analyzer consistency invariants + can see them. This is the pooling half of #952, whose fix corrected the *shape* + of the reset (`ClearValue` instead of assigning a default) but not its absence. + `TextBlock.Padding` — reset since #950, but from a case arm past the point the + scanners stop reading — moved into the same region, so all four of the + receivers `ApplyModifiers` writes `Padding` to are now covered by one chain and + verified by the same invariants. + + User-visible fallout: those six properties are now marked `poolReset` in the + analyzer's modifier table, so `.Set(c => c.Padding = …)` and friends report + **`REACTOR_POOL_001` (Warning)** where they previously reported + `REACTOR_MOD_002` (Info) — but only on a receiver `ElementPool` actually + recycles (see the receiver-aware selection entry below); a `CheckBox` or + `RelativePanel` keeps reporting `REACTOR_MOD_002`. The suggested fix is + unchanged — use the fluent modifier (`.Padding(…)`) — and the provided code fix + still applies it automatically. Projects building with `TreatWarningsAsErrors` + may need to convert those call sites (or suppress the id) when upgrading. + +- **`REACTOR_POOL_001` is no longer reported for receivers the pool does not + recycle (issue #1051).** Rule selection was `poolReset ? POOL_001 : MOD_002`, + decided per *property* and blind to the receiver, while the control gates it + reports through name inheritance roots — `Control` admits every WinUI control, + `Panel` admits every panel. `ElementPool` matches on the *exact* runtime type + (`PoolableTypes.Contains(element.GetType())`), so the two sets never agreed: + `.Set(cb => cb.IsEnabled = false)` on a `CheckBox`, or + `.Set(rp => rp.Background = brush)` on a `RelativePanel`, claimed *"is reset on + pool return"* for a control that is never pooled. `PoolResetSetAnalyzer` now + mirrors `ElementPool.PoolableTypes` exactly and falls back to + `REACTOR_MOD_002` (Info) outside it — the hazard those receivers really do + have, with the same advice and the same code fix. A parity test fails the build + if the mirror and `PoolableTypes` ever diverge in either direction. The change + is strictly de-escalating, and it also covers the twelve properties + (`Margin`, `Width`, `Height`, `Min`/`Max` sizes, alignments, `Opacity`, + `AccessKey`, `IsTabStop`) that had the same over-breadth before this release, + and the attached-property half of the rule + (`.Set(cb => AutomationProperties.SetName(cb, "Save"))`), which reported + `REACTOR_POOL_001` unconditionally. Both halves now resolve poolability once + from the `.Set` lambda parameter, so a body mixing an instance write with an + attached one cannot report two different ids for the same receiver. + Custom subclasses (`class MyButton : Button`) report `REACTOR_MOD_002` too, + matching the pool, which does not recycle them either. + - **Accessibility environment hooks now report the real system value on the first render (issue #983).** `UseReducedMotion()`, `UseHighContrast()` and `UseHighContrastScheme()` seeded their state inside `UseEffect`, which does @@ -166,6 +219,7 @@ Conventions for contributors: `AnimationsEnabledChanged`, gated behind an `ApiInformation` probe because that event needs Windows 10 2004 (19041) and Reactor's minimum is 17763; on older builds the existing `ColorValuesChanged` re-read remains as the fallback. + - **`DataGrid`'s Shift+Tab now moves focus backward (issue #987).** The grid's routed `KeyDown` handler captured only the raw `VirtualKey` and then deferred dispatch through diff --git a/docs/_pipeline/templates/analyzer-architecture.md.dt b/docs/_pipeline/templates/analyzer-architecture.md.dt index 0e0fe011c6..e3dd1bf55e 100644 --- a/docs/_pipeline/templates/analyzer-architecture.md.dt +++ b/docs/_pipeline/templates/analyzer-architecture.md.dt @@ -269,11 +269,14 @@ was structurally invisible to the whole family: .Set(fe => AutomationProperties.SetName(fe, "Save")) ``` -`ElementPool.CleanElement` clears far more attached properties than -instance ones, so this was the larger half of `REACTOR_POOL_001`'s +`ElementPool.CleanElement` used to clear far more attached properties +than instance ones, so this was the larger half of `REACTOR_POOL_001`'s subject matter — all of it in the "your write is silently discarded" -class. The failure is identical either way, so both shapes report the -*same* diagnostic id rather than a new one; only the matching differs. +class. Issue #985 has since closed the gap from the other side (the +receiver-gated `Padding` / `CornerRadius` / `Border*` / `Background` / +`IsEnabled` chain), so the two halves are now comparable in size. The +failure is identical either way, so both shapes report the *same* +diagnostic id rather than a new one; only the matching differs. **Keyed by owner, not by property name.** The instance table, `ModifierTable.Properties`, is keyed by the bare property name, and diff --git a/docs/guide/analyzer-architecture.md b/docs/guide/analyzer-architecture.md index 58588b4409..e5bc954feb 100644 --- a/docs/guide/analyzer-architecture.md +++ b/docs/guide/analyzer-architecture.md @@ -347,11 +347,14 @@ was structurally invisible to the whole family: .Set(fe => AutomationProperties.SetName(fe, "Save")) ``` -`ElementPool.CleanElement` clears far more attached properties than -instance ones, so this was the larger half of `REACTOR_POOL_001`'s +`ElementPool.CleanElement` used to clear far more attached properties +than instance ones, so this was the larger half of `REACTOR_POOL_001`'s subject matter — all of it in the "your write is silently discarded" -class. The failure is identical either way, so both shapes report the -*same* diagnostic id rather than a new one; only the matching differs. +class. Issue #985 has since closed the gap from the other side (the +receiver-gated `Padding` / `CornerRadius` / `Border*` / `Background` / +`IsEnabled` chain), so the two halves are now comparable in size. The +failure is identical either way, so both shapes report the *same* +diagnostic id rather than a new one; only the matching differs. **Keyed by owner, not by property name.** The instance table, `ModifierTable.Properties`, is keyed by the bare property name, and diff --git a/plugins/reactor/skills/reactor-build-and-check/SKILL.md b/plugins/reactor/skills/reactor-build-and-check/SKILL.md index 6837fd36ee..54c668c630 100644 --- a/plugins/reactor/skills/reactor-build-and-check/SKILL.md +++ b/plugins/reactor/skills/reactor-build-and-check/SKILL.md @@ -111,9 +111,9 @@ Additional flags: | `REACTOR_CTRL_001` | warning | `.Set(x => x.SelectedItem/SelectedValue = ...)` on a selector that also sets `SelectedIndex` | Delete the `.Set(...)` — controlled `SelectedIndex` is the authority. Don't drive selection from two places. | | `REACTOR_VIS_001` | warning | Imperative `.Set(c => c.Visibility = Visibility.Collapsed)` | Use `.IsVisible(false)` / `.IsVisible(true)` (or conditional inclusion `cond ? el : null`). `.Set` writes aren't reconciled. | | `REACTOR_EVENT_001` | warning | Event subscription via `.Set(c => c.Event += h)` (re-subscribes every render) | Use the declarative `.On(h)` modifier where one exists, else `.OnMountAdd(c => ((TControl)c).Event += h).OnUnmountAdd(c => ((TControl)c).Event -= h)` with a stable `h` (static method or field). | -| `REACTOR_MOD_002` | info | `.Set(c => c.Prop = v)` where a first-class `.Prop(v)` modifier exists | Use the modifier. `.Set` setters re-run every render, are never unwound when a later render drops them, and `Element.SettersEqual` pins the element to the reconciler's update path. The fix rewrites the whole `.Set` — including multi-statement bodies — into a modifier chain. | +| `REACTOR_MOD_002` | info | `.Set(c => c.Prop = v)` where a first-class `.Prop(v)` modifier exists — **or** an attached setter `.Set(c => Owner.SetProp(c, v))` whose receiver is a type `ElementPool` never holds, which reports `MOD_002` rather than `POOL_001` | Use the modifier. `.Set` setters re-run every render, are never unwound when a later render drops them, and `Element.SettersEqual` pins the element to the reconciler's update path. The fix rewrites the whole `.Set` — including multi-statement bodies — into a modifier chain. | | `REACTOR_MOD_003` | warning | A common modifier that `ApplyModifiers` never writes to this element's control (`.Background(...)` on a `Rectangle`, `.Padding(...)` on a `Canvas`, `.CornerRadius(...)` on an `Image`) | The call compiles and is silently discarded. On a shape use the paint modifier (`.Fill(...)` / `.Stroke(...)` / `.StrokeThickness(...)` — the fix does the rewrite); otherwise host the element in a control that supports it. Gates: `Background` → Panel/Control/Border; `Foreground` and fonts → Control/TextBlock; `Padding` → Control/Border/Grid/StackPanel/RelativePanel/TextBlock; `CornerRadius` → Control/Border/Grid/StackPanel/RelativePanel; `BorderBrush`/`BorderThickness` → Control/Border. | -| `REACTOR_POOL_001` | warning | `.Set` writes a property `ElementPool.CleanElement` clears on pool return — either `c.Prop = v` or an attached setter `Owner.SetProp(c, v)` (`AutomationProperties.*`, `ToolTipService.*`, `TitleBar.IsDragRegion`, `FlexPanel.*`) | Use the surviving modifier — the value is stored on `Element.Modifiers` and re-applied every render, whereas the `.Set` write is silently discarded when the control is reused. Most map 1:1 and ship a fix (`AutomationProperties.SetName` → `.AutomationName(...)`, `ToolTipService.SetToolTip` → `.ToolTip(...)`); the rest are diagnostic-only because the modifier's shape differs — `.PositionInSet(position, size)`, `.Required()`, `.Flex(grow: ...)`. | +| `REACTOR_POOL_001` | warning | `.Set` writes a property `ElementPool.CleanElement` clears on pool return — either an instance write `c.Prop = v` (layout/appearance: `Margin`, `Width`/`Height`, `Min`/`Max` sizes, `HorizontalAlignment`/`VerticalAlignment`, `Opacity`, `AccessKey`, `IsTabStop`, plus `Padding`, `CornerRadius`, `BorderThickness`, `BorderBrush`, `Background` and `IsEnabled` on their supported receivers) or an attached setter `Owner.SetProp(c, v)` (`AutomationProperties.*`, `ToolTipService.*`, `TitleBar.IsDragRegion`, `FlexPanel.*`). **Receiver-aware:** fires only when the `.Set` lambda parameter's *exact* type is one `ElementPool` recycles — `TextBlock`, `RichTextBlock`, `StackPanel`, `Grid`, `Border`, `ScrollViewer`, `Canvas`, `Viewbox`, `ProgressBar`, `ProgressRing`, `Image`, `InfoBadge`, `Button`, `TextBox`, `ToggleSwitch`. The identical write on a receiver the pool never holds (`CheckBox`, `RelativePanel`, a user subclass of a pooled type) reports `REACTOR_MOD_002` instead — same modifier advice, minus the pool-return claim: the write lands and is never unwound, so what it costs is the element's structural skip (`Element.SettersEqual`), not the value. | Use the surviving modifier — the value is stored on `Element.Modifiers` and re-applied every render, whereas the `.Set` write is silently discarded when the control is reused. Most map 1:1 and ship a fix (`.Padding(...)`, `.Background(...)`, `AutomationProperties.SetName` → `.AutomationName(...)`, `ToolTipService.SetToolTip` → `.ToolTip(...)`); the rest are diagnostic-only because the modifier's shape differs — `.PositionInSet(position, size)`, `.Required()`, `.Flex(grow: ...)`. | | `REACTOR_A11Y_004` | warning | Clickable container (`Border`/`Grid`/`Canvas`/`Rectangle`/`Ellipse`/`VStack`/`HStack`) has `.OnTapped` but is not keyboard-reachable | Add `.IsTabStop(true)` and pair with `.OnKeyDown` for Enter/Space activation. | | `REACTOR_INPUT_001` | warning | Ctrl/Alt chord tested inside a `.OnKeyDown` lambda (focus-scoped, fires only while the element has focus) | Register it app-wide as a `Command` accelerator: `new Command { …, Accelerator = Accelerator(VirtualKey.S, VirtualKeyModifiers.Control) }`, then drop the `.OnKeyDown` chord. | | `REACTOR_ANIM_002` | info | `.Keyframes(name, trigger, …)` trigger changes every render (`DateTime.Now`, `Guid.NewGuid()`, a fresh allocation) | Pass a stable trigger — a `UseState`/`UseReducer` counter you increment only when you mean to retrigger. Recomputed values restart the animation each reconcile (flicker). | diff --git a/src/Reactor.Analyzers/ModifierTable.cs b/src/Reactor.Analyzers/ModifierTable.cs index 641f5e8859..e3e7cbebe8 100644 --- a/src/Reactor.Analyzers/ModifierTable.cs +++ b/src/Reactor.Analyzers/ModifierTable.cs @@ -12,12 +12,14 @@ internal ModifierInfo( string modifier, bool poolReset = false, string[]? controlGate = null, - string[]? elementTypes = null) + string[]? elementTypes = null, + string[]? poolResetGate = null) { Modifier = modifier; PoolReset = poolReset; ControlGate = controlGate; ElementTypes = elementTypes; + PoolResetGate = poolResetGate; } /// Name of the fluent modifier method to suggest. @@ -28,6 +30,11 @@ internal ModifierInfo( /// .Set write is silently lost on pool reuse. Selects the higher-severity /// REACTOR_POOL_001; everything else reports REACTOR_MOD_002. /// + /// + /// Property-level. Where the reset only applies to some of the gated receivers, + /// narrows it — see that member for why the distinction is + /// load-bearing rather than cosmetic. + /// public bool PoolReset { get; } /// @@ -58,6 +65,34 @@ internal ModifierInfo( /// /// public string[]? ElementTypes { get; } + + /// + /// The subset of the pool actually resets, or null when + /// every gated receiver is reset. + /// + /// + /// + /// is per-property, but poolability is per-receiver, and the two + /// do not coincide: ApplyModifiers writes Padding to RelativePanel, + /// yet RelativePanel is absent from ElementPool.PoolableTypes, so nothing + /// is ever recycled and no write is ever unwound. Reporting REACTOR_POOL_001 there + /// states something false — and at Warning severity, which becomes a build break for + /// consumers using TreatWarningsAsErrors. Narrowing to this list reports + /// REACTOR_MOD_002 instead, which keeps the modifier suggestion and drops only the + /// pool-return claim: the write lands and is never unwound, so what it costs is the + /// element's structural skip (Element.SettersEqual), not the value. + /// + /// + /// This is a name-level mirror of ControlGate ∩ ElementPool.PoolableTypes, kept + /// here because the analyzer targets netstandard2.0 and cannot reference + /// src/Reactor. It is not maintained by hand: + /// ModifierUnsetClearValueTests.Every_Poolable_Gated_Receiver_Is_Released_By_CleanElement + /// derives the same intersection from both real sources, and + /// Every_Pool_Reset_Gate_Matches_The_Poolable_Intersection fails if this list + /// drifts from it in either direction. + /// + /// + public string[]? PoolResetGate { get; } } /// @@ -75,11 +110,22 @@ internal ModifierInfo( /// FlexPanel.SetMinWidth writes FlexMinWidthProperty. /// /// -/// Every entry is pool-reset by construction: -/// only lists properties ElementPool.CleanElement clears, so they all report -/// REACTOR_POOL_001. There is deliberately no attached equivalent of the Info tier -/// (REACTOR_MOD_002) — the value is concentrated in "your write is silently -/// discarded". +/// Every entry is pool-reset as a property by construction: +/// only lists properties +/// ElementPool.CleanElement clears, so there is no per-entry poolReset flag +/// and no attached analogue of . +/// +/// +/// That is not the same as "every attached write reports REACTOR_POOL_001". +/// CleanElement only runs on a control the pool recycles, so +/// PoolResetSetAnalyzer also requires the .Set lambda parameter's exact type +/// to be in ; on anything else the same write reports +/// REACTOR_MOD_002: the modifier still exists, but the pool-return claim does not — the +/// write lands and is never unwound, so what it costs is the element's structural skip +/// (Element.SettersEqual), not the value. The instance and attached +/// halves resolve that one fact the same way and once per .Set body, so a body +/// mixing both shapes on one receiver cannot report two different ids. See +/// Attached_Setter_Reports_ModifierAvailable_On_An_Unpooled_Receiver. /// /// internal sealed class AttachedModifierInfo @@ -232,6 +278,54 @@ internal static class ModifierTable private static readonly string[] RichTextBlockOnly = { "RichTextBlockElement" }; private static readonly string[] TextOrRichTextBlock = { "TextBlockElement", "RichTextBlockElement" }; + // The two groups above minus RelativePanel, which ApplyModifiers writes to but + // ElementPool never recycles. Used as poolResetGate, never as controlGate. + private static readonly string[] ControlBorderGridStackText = { "Control", "Border", "Grid", "StackPanel", "TextBlock" }; + private static readonly string[] ControlBorderGridStack = { "Control", "Border", "Grid", "StackPanel" }; + + /// + /// The exact WinUI control type names ElementPool recycles — a mirror of + /// ElementPool.PoolableTypes. + /// + /// + /// + /// The pool tests membership with PoolableTypes.Contains(element.GetType()): an + /// exact-type lookup, not an assignability walk. This mirror is matched the same way, and + /// that distinction is the whole reason it exists. A control gate names the base type an + /// ApplyModifiers arm dispatches on, so Control admits every WinUI control and + /// Panel admits every panel, while the pool recycles these fifteen types and nothing + /// else. Selecting REACTOR_POOL_001 from a gate alone therefore asserts "reset on pool + /// return" for receivers such as CheckBox and RelativePanel that are never + /// pooled — at Warning severity, which is a build break for a consumer using + /// TreatWarningsAsErrors. Those receivers fall to REACTOR_MOD_002, which drops + /// only the pool-return claim: the write lands and is never unwound, and the cost is + /// the element's structural skip (Element.SettersEqual) rather than the value. + /// + /// + /// Matching the receiver's own type rather than its base chain costs no signal here, because + /// every .Set overload in the DSL is declared per element type over the concrete + /// control (ButtonElement takes Action<Button>), so the receiver the + /// analyzer sees is the type the pool would key on. + /// + /// + /// Not hand-maintained: ModifierUnsetClearValueTests reads + /// ElementPool.PoolableTypes by reflection and fails if the two sets drift. + /// + /// + private static readonly HashSet PoolableTypeNameSet = + new HashSet(System.StringComparer.Ordinal) + { + "TextBlock", "RichTextBlock", "StackPanel", "Grid", "Border", "ScrollViewer", + "Canvas", "Viewbox", "ProgressBar", "ProgressRing", "Image", "InfoBadge", + "Button", "TextBox", "ToggleSwitch", + }; + + /// The mirrored poolable type names, for the parity test that keeps them honest. + public static IEnumerable PoolableTypeNames => PoolableTypeNameSet; + + /// True when ElementPool recycles exactly this type. + public static bool IsPoolableTypeName(string name) => PoolableTypeNameSet.Contains(name); + /// /// Property name → modifier mapping. Keyed by the WinUI property name as written inside /// the .Set lambda. @@ -254,23 +348,55 @@ internal static class ModifierTable { "AccessKey", new ModifierInfo("AccessKey", poolReset: true) }, { "IsTabStop", new ModifierInfo("IsTabStop", poolReset: true) }, + // Pool-reset but only on some receivers (issue #985). CleanElement clears these + // through a Control | Border | Panel/Grid/StackPanel | TextBlock chain that mirrors + // the receivers ApplyModifiers writes them to, so the control gates below still + // apply: the gate decides whether the modifier reaches the control at all, + // poolReset decides which rule id reports it. + // + // poolReset is per-property but poolability is per-receiver, so POOL_001 needs two + // independent facts about the receiver and neither implies the other: + // + // 1. the pool recycles it at all -> PoolableTypeNames, matched on the exact + // type, exactly as the pool matches it + // 2. CleanElement clears THIS property -> poolResetGate, matched on the base chain, + // once it is recycled exactly as CleanElement's `is` arms match + // + // RelativePanel fails (1) for every property: it is gated for Padding, CornerRadius + // and Background but never recycled. CheckBox fails (1) too — Control is in three of + // these gates and admits every WinUI control, while the pool holds seven. Both + // reported POOL_001 before issue #1051, asserting "reset on pool return" of a + // receiver that is never pooled, at Warning severity — a build break for a consumer + // using TreatWarningsAsErrors. They fall to MOD_002 instead, which keeps the modifier + // suggestion and drops only the pool-return claim: the write lands and is never + // unwound, costing the element's structural skip rather than the value. + // + // Nothing here is hand-maintained. ModifierUnsetClearValueTests reads + // ElementPool.PoolableTypes for (1) and derives the gated-receiver intersection for + // (2), and fails if either drifts. Closes issue #1051. + // + // WinUI declares most of these on Panel subclasses too, and the allow-lists + // genuinely differ: Panel itself declares only Background; Grid, StackPanel, and + // RelativePanel each declare their own border-box properties, and TextBlock takes + // Padding but not CornerRadius. IsEnabled needs no gate — WinUI declares it on + // Control, so if the .Set lambda compiles the receiver already qualifies. The three + // rows without a poolResetGate need none: CleanElement clears Background for every + // Panel and both Border* for the whole Control and Border arms, so once (1) holds + // there is no gated receiver left for (2) to exclude. + { "IsEnabled", new ModifierInfo("IsEnabled", poolReset: true) }, + { "Padding", new ModifierInfo("Padding", poolReset: true, controlGate: ControlBorderGridStackRelativeText, poolResetGate: ControlBorderGridStackText) }, + { "CornerRadius", new ModifierInfo("CornerRadius", poolReset: true, controlGate: ControlBorderGridStackRelative, poolResetGate: ControlBorderGridStack) }, + { "BorderThickness", new ModifierInfo("BorderThickness", poolReset: true, controlGate: ControlBorder) }, + { "BorderBrush", new ModifierInfo("BorderBrush", poolReset: true, controlGate: ControlBorder) }, + { "Background", new ModifierInfo("Background", poolReset: true, controlGate: PanelControlBorder) }, + // ── Generic modifier, no runtime gate (REACTOR_MOD_002, Info) ──────────── - // IsEnabled and the content-alignment pair ARE Control-gated in ApplyModifiers, - // but WinUI declares those DPs only on Control — if the .Set lambda compiles the - // receiver already qualifies, so no predicate is needed. - { "IsEnabled", new ModifierInfo("IsEnabled") }, + // The content-alignment pair IS Control-gated in ApplyModifiers, but WinUI + // declares those DPs only on Control — if the .Set lambda compiles the receiver + // already qualifies, so no predicate is needed. { "HorizontalContentAlignment", new ModifierInfo("HorizontalContentAlignment") }, { "VerticalContentAlignment", new ModifierInfo("VerticalContentAlignment") }, - // ── Generic modifier, control-gated (REACTOR_MOD_002, Info) ────────────── - // The allow-lists genuinely differ. Panel itself declares only Background; Grid, - // StackPanel, and RelativePanel each declare their own border-box properties. - { "Padding", new ModifierInfo("Padding", controlGate: ControlBorderGridStackRelativeText) }, - { "CornerRadius", new ModifierInfo("CornerRadius", controlGate: ControlBorderGridStackRelative) }, - { "BorderThickness", new ModifierInfo("BorderThickness", controlGate: ControlBorder) }, - { "BorderBrush", new ModifierInfo("BorderBrush", controlGate: ControlBorder) }, - { "Background", new ModifierInfo("Background", controlGate: PanelControlBorder) }, - // Fonts have BOTH a generic modifier and type-specific overloads, and the two // cover different receivers — so the gates are OR'd (see ModifierInfo.ElementTypes). // The generic path only reaches Control|TextBlock in ApplyModifiers; RichTextBlock @@ -360,7 +486,9 @@ internal static class ModifierTable /// /// A null is ambiguous between "the reconciler applies /// this unconditionally" and "the reconciler gates it, but this rule's direction cannot reach a - /// non-qualifying receiver anyway". REACTOR_MOD_002 reads .Set(x => x.IsEnabled = v), + /// non-qualifying receiver anyway". reads + /// .Set(x => x.IsEnabled = v) (as REACTOR_POOL_001 since issue #985 made the + /// pool clear it; REACTOR_MOD_002 before that), /// where the lambda parameter is already a Control because WinUI declares the dependency /// property only there — so no predicate is needed. reads /// .IsEnabled(v), a generic modifier callable on any element, where the same @@ -565,6 +693,17 @@ internal static class ModifierTable /// , with the reason. PoolResetSetConsistencyTests /// requires every attached reset with a same-named modifier to appear in one of the two. /// + /// + /// Every entry must be a genuine attached property that the Owner.SetPROP(x, v) rule + /// cannot match. It is not a place to silence a property the attached scan claimed by + /// mistake: Grid.Padding and Grid.CornerRadius sat here after the #1003 union + /// with reasons that said, in as many words, "instance dependency property on Grid, not an + /// attached property" — which is a misclassification to fix at the source, not to record. + /// They are now declared instance properties via InstancePropertyOwners, so the scan + /// never claims them and nothing needs excluding. Suppressing that kind of entry here is + /// actively harmful, because a genuinely attached Grid.* reset added later would land + /// in the same bucket and read as already-triaged. + /// public static readonly IReadOnlyDictionary DeliberatelyExcludedAttached = new Dictionary(System.StringComparer.Ordinal) { @@ -577,9 +716,6 @@ internal static class ModifierTable ["AutomationProperties.DescribedBy"] = "No static setter — WinUI exposes GetDescribedBy(...) returning a mutable IList.", ["AutomationProperties.FlowsTo"] = "No static setter — WinUI exposes GetFlowsTo(...) returning a mutable IList.", ["AutomationProperties.FlowsFrom"] = "No static setter — WinUI exposes GetFlowsFrom(...) returning a mutable IList.", - ["Grid.Padding"] = "Instance dependency property on Grid, not an attached property with a static setter.", - ["Grid.CornerRadius"] = "Instance dependency property on Grid, not an attached property with a static setter.", - ["StackPanel.CornerRadius"] = "Instance dependency property on StackPanel, not an attached property with a static setter.", }; private static IReadOnlyDictionary BuildAttached( diff --git a/src/Reactor.Analyzers/PoolResetSetAnalyzer.cs b/src/Reactor.Analyzers/PoolResetSetAnalyzer.cs index 20740c2f8a..2040043b7e 100644 --- a/src/Reactor.Analyzers/PoolResetSetAnalyzer.cs +++ b/src/Reactor.Analyzers/PoolResetSetAnalyzer.cs @@ -224,6 +224,13 @@ private static void AnalyzeInvocation(SyntaxNodeAnalysisContext context) return; var paramName = lambdaParam.Identifier.Text; + // Both write paths — instance assignment and attached setter call — are gated to the + // lambda parameter itself, so whether the pool recycles the receiver is one fact about + // the whole body. Computing it once here keeps the two halves of REACTOR_POOL_001 from + // disagreeing about the same control: a mixed body on an unpooled receiver used to + // report an instance write as MOD_002 and an attached write as POOL_001. + var receiverIsPooled = IsPooledReceiver(context, lambdaParam); + // Detection considers every write in the body, not just a lone one: a modifier-backed // write is no less wrong for sharing a block with other statements. This is // deliberately wider than the fix, which converts a body only when EVERY statement is @@ -290,7 +297,10 @@ bool IsReactorSet() { reportable.Add(( assignment.SpanStart, hit.PropName, hit.PropName, - "." + hit.Info.Modifier + "(...)", hit.Info.PoolReset)); + "." + hit.Info.Modifier + "(...)", + hit.Info.PoolReset + && receiverIsPooled + && PassesPoolResetGate(context, hit.Info, leftAccess))); } else { @@ -322,7 +332,7 @@ bool IsReactorSet() if (!fixable) unfixableIds.Add(id); - reportable.Add((attachedCall.SpanStart, id, info.Key, info.ModifierUsage, PoolReset: true)); + reportable.Add((attachedCall.SpanStart, id, info.Key, info.ModifierUsage, PoolReset: receiverIsPooled)); } if (reportable.Count == 0) @@ -462,6 +472,78 @@ private static (string PropName, ModifierInfo Info)? ClassifyAssignment( return (propName, info); } + /// + /// True when ElementPool recycles the receiver's own type, so it can carry a stale + /// local value into its next renter at all. + /// + /// + /// + /// This is the first of the two facts REACTOR_POOL_001 needs, and it is the one a + /// control gate cannot supply. A gate names the base type an ApplyModifiers arm + /// dispatches on and is matched down the base chain, so Control admits CheckBox + /// and Panel admits RelativePanel — neither of which the pool recycles. The + /// pool keys on element.GetType(), so this matches the receiver's own type and not its + /// base chain, deliberately: it is a mirror of the pool's own membership test, and a + /// subclass of a poolable type is no more poolable than an unrelated one. + /// + /// + /// An unresolved receiver falls to REACTOR_MOD_002. That is the safe direction — the + /// modifier suggestion stays, only the claim about pool return is dropped. + /// + /// + /// Resolved from the lambda parameter's declared type rather than from each write's + /// receiver expression: both write paths are already gated to that parameter, so this is + /// one fact per .Set body and the instance and attached halves cannot disagree. + /// + /// + private static bool IsPooledReceiver( + SyntaxNodeAnalysisContext context, + ParameterSyntax lambdaParam) + { + var controlType = context.SemanticModel + .GetDeclaredSymbol(lambdaParam, context.CancellationToken)?.Type; + + return controlType is not null + && ModifierTable.IsPoolableTypeName(controlType.Name) + && controlType.ContainingNamespace?.ToDisplayString() == "Microsoft.UI.Xaml.Controls"; + } + + /// + /// True when CleanElement clears this particular property on this receiver, once + /// has established the receiver is recycled at all. + /// + /// + /// + /// This is the second of REACTOR_POOL_001's two facts, and it is independent of the + /// first: being recycled does not mean every gated property is cleared for you. + /// CleanElement's Panel arm clears only Background; Padding and + /// CornerRadius are cleared for Grid and StackPanel specifically, + /// because Panel declares neither. A poolable panel added to one of those gates + /// without a matching arm would be recycled and still not cleared — so this is matched down + /// the base chain, mirroring how CleanElement dispatches with is. + /// + /// + /// No gate means no receiver restriction — the reset applies wherever the property is + /// written — so the absence of a list is a pass here, unlike + /// where absence means "not applicable" and must fail. + /// The two read alike and mean opposite things, which is why they are separate methods. + /// + /// + private static bool PassesPoolResetGate( + SyntaxNodeAnalysisContext context, + ModifierInfo info, + MemberAccessExpressionSyntax leftAccess) + { + if (info.PoolResetGate is not { } gate) + return true; + + var controlType = context.SemanticModel + .GetTypeInfo(leftAccess.Expression, context.CancellationToken).Type; + + return gate.Any(allowed => + SetLambdaHelpers.InheritsFrom(controlType, allowed, "Microsoft.UI.Xaml.Controls")); + } + /// /// True when ApplyModifiers would actually write the generic modifier to this /// runtime control type. False when no control gate is declared — the caller OR-combines diff --git a/src/Reactor/Core/ElementPool.cs b/src/Reactor/Core/ElementPool.cs index 19228402f1..42466f3fb6 100644 --- a/src/Reactor/Core/ElementPool.cs +++ b/src/Reactor/Core/ElementPool.cs @@ -42,6 +42,32 @@ internal static bool IsCompositorTainted(UIElement element) /// public bool Enabled { get; set; } = true; + /// + /// The exact runtime types and recycle. + /// Membership is tested with on + /// , so it is an exact-type set: a subclass of a + /// listed type is not poolable. CheckBox and RelativePanel are the cases + /// that catch people out — they pass the Control and Panel gates + /// ApplyModifiers dispatches on, but they are not here. + /// + /// + /// + /// This list is mirrored by name in ModifierTable.PoolableTypeNames + /// (namespace Microsoft.UI.Reactor.Analyzers, assembly Reactor.Analyzers), + /// whose ModifierTable.IsPoolableTypeName membership test PoolResetSetAnalyzer + /// uses to decide whether REACTOR_POOL_001 (the receiver is recycled, so the write + /// is unwound on pool return) or REACTOR_MOD_002 + /// (the receiver is not recycled, so the write is never unwound — it costs the element's + /// structural skip, not the value) describes a .Set write. The analyzer targets + /// netstandard2.0 and cannot reference this assembly, hence the copy. + /// + /// + /// Adding or removing a type here without updating that mirror fails + /// Analyzer_Poolable_Type_Mirror_Matches_ElementPool, and adding one that + /// does not reset fails + /// Every_Poolable_Gated_Receiver_Is_Released_By_CleanElement. + /// + /// private static readonly HashSet PoolableTypes = new() { typeof(TextBlock), @@ -256,6 +282,92 @@ internal static void CleanElement(FrameworkElement fe) fe.ClearValue(UIElement.IsHitTestVisibleProperty); if (fe is Control tabStopControl) tabStopControl.ClearValue(Control.IsTabStopProperty); + + // Issue #985: six common modifiers are written by ApplyModifiers onto receivers + // this method never reset, so a pooled control handed its previous renter's local + // Padding / CornerRadius / BorderThickness / BorderBrush / Background / IsEnabled + // to the next one — and a local value outranks every Style setter (same precedence + // trap as #952, but caused by a *missing* reset rather than a wrong-shaped one). + // + // These live here, in the FE-common region, and not in the type-specific arms + // below: the pool/analyzer consistency invariants (PoolResetSetConsistencyTests) + // stop scanning at the type dispatch, so a clear placed after it is invisible to + // them and ModifierTable would keep claiming the property is not pool-reset. + // Placement is the fix, not an implementation detail. + // + // The chain mirrors ApplyModifiers' receiver types for the receivers that are actually + // pooled (Reconciler.cs): Padding → Control | Border | Grid | StackPanel | TextBlock, + // CornerRadius → Control | Border | Grid | StackPanel, BorderBrush/BorderThickness → + // Control | Border, Background → Panel | Control | Border, IsEnabled → Control. + // The Padding and CornerRadius gates also admit RelativePanel, which gets no clear + // here because RelativePanel is not in PoolableTypes — it is never returned to the + // pool, so there is no local value for a later renter to inherit. Canvas is the + // opposite case and is covered: it is poolable, and the only gate that admits it is + // Background, which the Panel arm clears for every Panel. + // + // Two claims live here and only the first is structural. Dispatch: Control, Border, + // Panel and TextBlock are pairwise disjoint, so `else if` selects exactly one arm — + // true regardless of what the gates say. Coverage is not: each arm clears a + // per-property allow-list, and the Panel arm clears Background for every Panel but + // Padding and CornerRadius only for Grid and StackPanel, because Panel itself + // declares neither. Any other poolable Panel subclass added to one of those gates + // lands in this arm and gets no clear — the disjointness sentence stays true while + // the guarantee it implies quietly narrows. Widening a gate obliges you to widen the + // arm, and that is not hypothetical: #1003 widened Padding/CornerRadius to the + // concrete panels and this arm had to grow with it in the same merge. + // Two tests in ModifierUnsetClearValueTests now make that reminder mechanical rather + // than a matter of vigilance, and each was measured firing alone: widening a + // poolResetGate the pool does not honour trips + // Every_Pool_Reset_Gate_Matches_The_Poolable_Intersection, and widening controlGate + // and poolResetGate together without growing this arm trips + // Every_Poolable_Gated_Receiver_Is_Released_By_CleanElement. Both range over + // gate ∩ PoolableTypes — the reachable subset of #1017, which remains open for the + // non-poolable receivers a gate may also admit. + if (fe is Control resetControl) + { + resetControl.ClearValue(Control.PaddingProperty); + resetControl.ClearValue(Control.CornerRadiusProperty); + resetControl.ClearValue(Control.BorderThicknessProperty); + resetControl.ClearValue(Control.BorderBrushProperty); + resetControl.ClearValue(Control.BackgroundProperty); + resetControl.ClearValue(Control.IsEnabledProperty); + } + else if (fe is WinUI.Border resetBorder) + { + resetBorder.ClearValue(WinUI.Border.PaddingProperty); + resetBorder.ClearValue(WinUI.Border.CornerRadiusProperty); + resetBorder.ClearValue(WinUI.Border.BorderThicknessProperty); + resetBorder.ClearValue(WinUI.Border.BorderBrushProperty); + resetBorder.ClearValue(WinUI.Border.BackgroundProperty); + } + else if (fe is WinUI.Panel resetPanel) + { + // Panel itself declares only Background; Padding and CornerRadius are declared by + // the concrete panel types, so they nest under this arm instead of forming a + // second receiver chain lower down. Both forms run and both sit above the type + // dispatch, but one chain keeps the receiver gating in a single place and avoids + // declaring resetStack twice in two scopes that must be kept in agreement. + resetPanel.ClearValue(WinUI.Panel.BackgroundProperty); + if (resetPanel is WinUI.Grid resetGrid) + { + resetGrid.ClearValue(WinUI.Grid.PaddingProperty); + resetGrid.ClearValue(WinUI.Grid.CornerRadiusProperty); + } + else if (resetPanel is WinUI.StackPanel resetStack) + { + resetStack.ClearValue(WinUI.StackPanel.PaddingProperty); + resetStack.ClearValue(WinUI.StackPanel.CornerRadiusProperty); + } + } + else if (fe is TextBlock resetText) + { + // TextBlock's padding reset predates #985 (it arrived with #950) but lived in + // the case arm below, where no scanner could see it — so ModifierTable's claim + // that Padding is pool-reset on TextBlock was the one receiver in the gate that + // nothing verified. Deleting the line used to break no test. Now it does. + resetText.ClearValue(TextBlock.PaddingProperty); + } + // spec 059: clear the TitleBar.IsDragRegion attached prop so a pooled // control marked .IsDragRegion(...) can't poison the next renter. fe.ClearValue(WinUI.TitleBar.IsDragRegionProperty); @@ -300,19 +412,6 @@ internal static void CleanElement(FrameworkElement fe) fe.ClearValue(Layout.FlexPanel.RightProperty); fe.ClearValue(Layout.FlexPanel.BottomProperty); - // These properties are declared by the concrete panel types, not by Panel. - // Keep their resets above the type dispatch so the pool/reset consistency - // tests can account for the concrete-panel resets added by this gate widening. - if (fe is WinUI.Grid resetGrid) - { - resetGrid.ClearValue(WinUI.Grid.PaddingProperty); - resetGrid.ClearValue(WinUI.Grid.CornerRadiusProperty); - } - else if (fe is WinUI.StackPanel resetStack) - { - resetStack.ClearValue(WinUI.StackPanel.CornerRadiusProperty); - } - // Type-specific cleanup switch (fe) { @@ -321,14 +420,8 @@ internal static void CleanElement(FrameworkElement fe) break; case WinUI.Border border: border.Child = null; - // ClearValue, not `= null` / `= default` — see the FE-common block above - // (issue #952). These five mirror common modifiers whose ApplyModifiers - // unset arms clear the same DPs. - border.ClearValue(WinUI.Border.BackgroundProperty); - border.ClearValue(WinUI.Border.BorderBrushProperty); - border.ClearValue(WinUI.Border.BorderThicknessProperty); - border.ClearValue(WinUI.Border.CornerRadiusProperty); - border.ClearValue(WinUI.Border.PaddingProperty); + // Border's five modifier-backed DPs are cleared in the FE-common block + // above (issue #985) so the consistency scan can see them. break; case WinUI.ScrollViewer sv: sv.Content = null; @@ -356,13 +449,10 @@ internal static void CleanElement(FrameworkElement fe) tb.ClearValue(TextBlock.TextTrimmingProperty); tb.ClearValue(TextBlock.IsTextSelectionEnabledProperty); tb.ClearValue(TextBlock.FontFamilyProperty); - // Issue #950 made ApplyModifiers write Padding to TextBlock, so a pooled - // TextBlock could otherwise hand its padding to the next element that sets - // none. Control/Border/StackPanel have the same leak and are NOT cleared - // anywhere — see #965; fixing those means moving the clears into the - // FE-common block above, which forces Padding to poolReset: true and - // escalates .Set(c => c.Padding = ...) to REACTOR_POOL_001. - tb.ClearValue(TextBlock.PaddingProperty); + // Padding moved to the FE-common chain above (issue #985) so the pool ⇄ + // analyzer consistency scan can see it — ModifierTable's Padding row names + // TextBlock in its control gate, and a clear the scan cannot reach is a + // claim nothing verifies. break; case WinUI.RichTextBlock rtb: Reconciler.CancelInlineUiExtentPin(rtb); @@ -395,7 +485,6 @@ internal static void CleanElement(FrameworkElement fe) // element from Tag at invocation time, so stale closures are harmless. case WinUI.Button button: button.Content = null; - button.ClearValue(Control.IsEnabledProperty); button.Flyout = null; VisualStateManager.GoToState(button, "Normal", false); break; @@ -410,7 +499,6 @@ internal static void CleanElement(FrameworkElement fe) break; case WinUI.ToggleSwitch toggle: toggle.ClearValue(WinUI.ToggleSwitch.IsOnProperty); - toggle.ClearValue(Control.IsEnabledProperty); toggle.OnContent = null; toggle.OffContent = null; toggle.Header = null; diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/Issue950TextBlockPaddingFixture.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/Issue950TextBlockPaddingFixture.cs index 858d66e566..b0e52fd866 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/Issue950TextBlockPaddingFixture.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/Issue950TextBlockPaddingFixture.cs @@ -279,6 +279,13 @@ public override async Task RunAsync() // under a local zero and the themed value under a clear. H.Check("Issue950_Unset_ControlFallsBackToThemedPadding", btn.Padding == themed); + // Same reason as the StackPanel pin below: TextBlock.Padding is released by + // ElementPool.CleanElement, so a stale `inlineTb` would read UnsetValue because + // the pool cleaned it — indistinguishable from the unset arm having cleared it + // on the live control. Without this, the next check cannot fail for its reason. + H.Check("Issue950_Unset_InlineSameInstance", + ReferenceEquals(inlineTb, H.FindText("Issue950_inline_only"))); + H.Check("Issue950_Unset_InlineOnlyLocalValueCleared", ReferenceEquals( DependencyProperty.UnsetValue, @@ -408,6 +415,14 @@ public override async Task RunAsync() H.Check("Issue950_AllTypes_StackApplied", sp.Padding == new Thickness(22)); H.Check("Issue950_AllTypes_InlineEndApplied", tb.Padding == new Thickness(0, 0, 23, 0)); + // Sentinel for the pool, written natively so no modifier ever touches it: + // ElementPool.CleanElement releases Panel.Background (#985), and this element + // never declares `.Background(...)`, so ApplyModifiers has no unset arm to run + // against it. If `sp` survives the toggle, this brush survives with it; if the + // pool recycled `sp`, CleanElement wiped it. See the StackSameInstance comment. + sp.Background = new global::Microsoft.UI.Xaml.Media.SolidColorBrush( + global::Microsoft.UI.Colors.Red); + H.ClickButton("Issue950_AllTypes_Toggle"); await Harness.Render(); @@ -419,11 +434,38 @@ public override async Task RunAsync() ReferenceEquals( DependencyProperty.UnsetValue, bdr.ReadLocalValue(WinUI.Border.PaddingProperty))); + + // Load-bearing, not decorative: StackPanel.Padding is now released by + // ElementPool.CleanElement (#985). That makes the absence check below + // fail-open on its own — a recycled `sp` reads UnsetValue because the + // pool cleaned it, which is indistinguishable from the unset arm having + // cleared it on the live control. + // + // Identity alone does NOT rule that out. ElementPool.Return pushes onto a + // per-type stack and TryRent pops it, so an unmount immediately followed by a + // remount of the same type hands back *that exact instance* — ReferenceEquals + // stays true across a round-trip that ran CleanElement. Identity is the cheap + // half; the Background sentinel written before the toggle is what actually + // closes the LIFO hole, because CleanElement would have wiped it. Together + // they make the next assertion a statement about ApplyModifiers. + H.Check("Issue950_AllTypes_StackSameInstance", + ReferenceEquals(sp, H.FindControl(s => + s.Children.Count == 1 && s.Children[0] is WinUI.TextBlock c + && c.Text == "Issue950_AllTypes_StackChild"))); + H.Check("Issue950_AllTypes_StackNotPooled", + !ReferenceEquals( + DependencyProperty.UnsetValue, + sp.ReadLocalValue(WinUI.Panel.BackgroundProperty))); H.Check("Issue950_AllTypes_StackCleared", ReferenceEquals( DependencyProperty.UnsetValue, sp.ReadLocalValue(WinUI.StackPanel.PaddingProperty))); + // Pins identity for the same reason as the StackPanel check above — TextBlock.Padding + // is pool-released, so a recycled `tb` reads UnsetValue regardless of the unset arm. + H.Check("Issue950_AllTypes_TextSameInstance", + ReferenceEquals(tb, H.FindText("Issue950_AllTypes_InlineEnd"))); + // oldM.Padding is null on this one — only PaddingInlineEnd was ever set — so a // `hadPadding` that forgot the InlineEnd slot would leave (0,0,23,0) in place. H.Check("Issue950_AllTypes_InlineEndCleared", diff --git a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs index 2be30adc28..1ac5f27c63 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/Fixtures/ModifierEventFixtures.cs @@ -5,6 +5,7 @@ using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using static Microsoft.UI.Reactor.Factories; +using WinUI = Microsoft.UI.Xaml.Controls; using AP = Microsoft.UI.Xaml.Automation.AutomationProperties; using APeers = Microsoft.UI.Xaml.Automation.Peers; @@ -1105,6 +1106,8 @@ public override async Task RunAsync() .Padding(21) .CornerRadius(13) .BorderThickness(7) + .BorderBrush("#FF66AA33") + .Background("#FF113355") .WithContextFlyout(MenuItems(MenuItem("PoolCtrlMenu"))), 1 => Empty(), // Remounted with no modifiers at all. @@ -1119,11 +1122,19 @@ public override async Task RunAsync() H.Check("PoolCtrl_Phase0_LocalValuesWritten", first is not null && first.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.PaddingProperty) != DependencyProperty.UnsetValue + && first.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.BorderBrushProperty) != DependencyProperty.UnsetValue + && first.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.BackgroundProperty) != DependencyProperty.UnsetValue && first.ReadLocalValue(UIElement.ContextFlyoutProperty) != DependencyProperty.UnsetValue); H.ClickButton("DropPoolCtrl"); await Harness.Render(); - + // Load-bearing premise, not a status report: it is the *drop* that forces the + // pool round-trip. Without it the reconciler could update the Border in place, + // and every "cleared" check below would be testing ApplyModifiers' unset arm + // instead of CleanElement — passing for entirely the wrong reason. + H.Check("PoolCtrl_Phase1_Returned", + H.FindControl(b => + b.Child is TextBlock tb && tb.Text == "pool-ctrl-carrier") is null); H.ClickButton("RemountPoolCtrl"); await Harness.Render(); var second = H.FindControl(b => @@ -1144,6 +1155,294 @@ first is not null second.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.CornerRadiusProperty) == DependencyProperty.UnsetValue); H.Check("PoolCtrl_Phase2_BorderThicknessCleared", second.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.BorderThicknessProperty) == DependencyProperty.UnsetValue); + // Issue #985 moved Border's five clears into CleanElement's FE-common chain. + // BorderBrush and Background were the two that no live fixture exercised — + // only the source-scanning invariants pinned them, and a scanner cannot tell + // whether the line it found actually runs for a Border receiver. + H.Check("PoolCtrl_Phase2_BorderBrushCleared", + second.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.BorderBrushProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCtrl_Phase2_BackgroundCleared", + second.ReadLocalValue(Microsoft.UI.Xaml.Controls.Border.BackgroundProperty) == DependencyProperty.UnsetValue); + } + } + + // ════════════════════════════════════════════════════════════════════ + // Issue #985 — the Control and Panel halves of the same contract. + // ApplyModifiers writes Padding / CornerRadius / BorderThickness / + // BorderBrush / Background / IsEnabled onto a *Control* receiver and + // Background onto a *Panel*, but CleanElement only ever reset the Border + // arm. A recycled ScrollViewer or Grid was therefore handed to its next + // renter still carrying the previous renter's LOCAL values — and a local + // value outranks every Style setter in WinUI's precedence order, so the + // new renter could never show its styled padding/background again. + // + // ScrollViewer is the Control carrier precisely because ScrollViewerElement + // declares none of the six properties: any local value that survives the + // recycle came from ApplyModifiers, not from the descriptor re-writing it + // on the second mount. A Button would be vacuous for IsEnabled — + // ButtonElement writes EffectiveIsEnabled unconditionally on every mount, + // so `IsEnabled` would read as a local value whether or not the pool + // cleared it. Grid is the Panel carrier for the same reason. + // + // Both carriers are remounted with NO modifiers at all, so ApplyModifiers' + // unset arms cannot run on them: CleanElement is the only thing that could + // have released these values. One check per property, so deleting a single + // ClearValue turns exactly one check red. + // ════════════════════════════════════════════════════════════════════ + + internal class ModifierPoolClearValueControlPanel(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + var host = H.CreateHost(); + + host.Mount(ctx => + { + var (phase, set) = ctx.UseState(0); + return VStack( + Button("DropPoolCp", () => set(1)), + Button("RemountPoolCp", () => set(2)), + phase switch + { + 0 => Factories.ScrollViewer(Factories.TextBlock("pool-cp-control")) + .Padding(23) + .CornerRadius(11) + .BorderThickness(6) + .BorderBrush("#FF3366CC") + .Background("#FF224466") + .IsEnabled(false), + 1 => Empty(), + // Remounted with no modifiers at all. + _ => Factories.ScrollViewer(Factories.TextBlock("pool-cp-control-2")), + }, + phase switch + { + // Padding and CornerRadius are declared by Grid, not by Panel, so they + // exercise the nested arm inside CleanElement's Panel branch. Without + // them the Grid carrier reaches only Panel.Background and the two + // Grid-specific clears are covered by the raw source scan alone — + // which cannot tell a live clear from a commented-out one. + 0 => Factories.Grid([GridSize.Star()], [GridSize.Star()], + Factories.TextBlock("pool-cp-panel")) + .Background("#FF884422") + .Padding(19) + .CornerRadius(7), + 1 => Empty(), + _ => Factories.Grid([GridSize.Star()], [GridSize.Star()], + Factories.TextBlock("pool-cp-panel-2")), + }); + }); + + await Harness.Render(); + var firstControl = H.FindControl(sv => + sv.Content is TextBlock tb && tb.Text == "pool-cp-control"); + var firstPanel = H.FindControl(g => + g.Children.Count > 0 && g.Children[0] is TextBlock tb && tb.Text == "pool-cp-panel"); + H.Check("PoolCp_Phase0_Present", firstControl is not null && firstPanel is not null); + + // Establishes that the modifiers really wrote LOCAL values, which is what makes + // every "cleared" assertion below able to come out the other way. + H.Check("PoolCp_Phase0_ControlLocalValuesWritten", + firstControl is not null + && firstControl.ReadLocalValue(Control.PaddingProperty) != DependencyProperty.UnsetValue + && firstControl.ReadLocalValue(Control.CornerRadiusProperty) != DependencyProperty.UnsetValue + && firstControl.ReadLocalValue(Control.BorderThicknessProperty) != DependencyProperty.UnsetValue + && firstControl.ReadLocalValue(Control.BorderBrushProperty) != DependencyProperty.UnsetValue + && firstControl.ReadLocalValue(Control.BackgroundProperty) != DependencyProperty.UnsetValue + && firstControl.ReadLocalValue(Control.IsEnabledProperty) != DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase0_PanelLocalValuesWritten", + firstPanel is not null + && firstPanel.ReadLocalValue(Panel.BackgroundProperty) != DependencyProperty.UnsetValue + && firstPanel.ReadLocalValue(WinUI.Grid.PaddingProperty) != DependencyProperty.UnsetValue + && firstPanel.ReadLocalValue(WinUI.Grid.CornerRadiusProperty) != DependencyProperty.UnsetValue); + + H.ClickButton("DropPoolCp"); + await Harness.Render(); + // Load-bearing premise, one per carrier. Without the drop the reconciler could + // update in place, and the cleared checks below would be exercising + // ApplyModifiers' unset arm rather than CleanElement — passing for the wrong + // reason. The ReferenceEquals guards further down do not cover this: an in-place + // update reuses the instance too, so instance identity cannot tell a pool + // round-trip from an update. Both carriers need their own check, or the half + // that lacks one can silently go vacuous. + H.Check("PoolCp_Phase1_Returned", + H.FindControl(sv => + sv.Content is TextBlock tb && tb.Text == "pool-cp-control") is null); + H.Check("PoolCp_Phase1_PanelReturned", + H.FindControl(g => + g.Children.Count > 0 && g.Children[0] is TextBlock tb + && tb.Text == "pool-cp-panel") is null); + + H.ClickButton("RemountPoolCp"); + await Harness.Render(); + var secondControl = H.FindControl(sv => + sv.Content is TextBlock tb && tb.Text == "pool-cp-control-2"); + var secondPanel = H.FindControl(g => + g.Children.Count > 0 && g.Children[0] is TextBlock tb && tb.Text == "pool-cp-panel-2"); + + // Load-bearing: without instance reuse every check below passes trivially, + // because a freshly constructed control has no local values to begin with. + H.Check("PoolCp_Phase2_ReusedControlInstance", + firstControl is not null && ReferenceEquals(firstControl, secondControl)); + H.Check("PoolCp_Phase2_ReusedPanelInstance", + firstPanel is not null && ReferenceEquals(firstPanel, secondPanel)); + if (secondControl is null || secondPanel is null) return; + + // Cleared, not "reset to the default value" — ReadLocalValue is the only oracle + // that tells those two apart, and that difference is the whole of the bug. + H.Check("PoolCp_Phase2_ControlPaddingCleared", + secondControl.ReadLocalValue(Control.PaddingProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_ControlCornerRadiusCleared", + secondControl.ReadLocalValue(Control.CornerRadiusProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_ControlBorderThicknessCleared", + secondControl.ReadLocalValue(Control.BorderThicknessProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_ControlBorderBrushCleared", + secondControl.ReadLocalValue(Control.BorderBrushProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_ControlBackgroundCleared", + secondControl.ReadLocalValue(Control.BackgroundProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_ControlIsEnabledCleared", + secondControl.ReadLocalValue(Control.IsEnabledProperty) == DependencyProperty.UnsetValue + && secondControl.IsEnabled); + H.Check("PoolCp_Phase2_PanelBackgroundCleared", + secondPanel.ReadLocalValue(Panel.BackgroundProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_PanelPaddingCleared", + secondPanel.ReadLocalValue(WinUI.Grid.PaddingProperty) == DependencyProperty.UnsetValue); + H.Check("PoolCp_Phase2_PanelCornerRadiusCleared", + secondPanel.ReadLocalValue(WinUI.Grid.CornerRadiusProperty) == DependencyProperty.UnsetValue); + } + } + + // ════════════════════════════════════════════════════════════════════ + // Issue #985, StackPanel half — StackPanel is a Panel, not a Control, so + // its Padding and CornerRadius need their own clears inside the Panel + // arm. It gets its own fixture because the Grid above cannot reach those + // lines: CleanElement's Grid and StackPanel arms are mutually exclusive + // `else if` branches under the same Panel receiver, so a Grid takes the + // first arm and never executes the StackPanel one. (Both types do carry + // the properties — #1003 widened the gates to Grid — which is exactly why + // the exclusivity, not the property set, is what splits the fixtures.) + // ════════════════════════════════════════════════════════════════════ + + internal class ModifierPoolClearValueStackPadding(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + var host = H.CreateHost(); + + host.Mount(ctx => + { + var (phase, set) = ctx.UseState(0); + return VStack( + Button("DropPoolStack", () => set(1)), + Button("RemountPoolStack", () => set(2)), + phase switch + { + 0 => VStack(Factories.TextBlock("pool-stack-carrier")) + .Padding(17) + .CornerRadius(9) + .Background("#FF335577"), + 1 => Empty(), + // Remounted with no modifiers at all. + _ => VStack(Factories.TextBlock("pool-stack-carrier-2")), + }); + }); + + await Harness.Render(); + var first = H.FindControl(sp => + sp.Children.Count > 0 && sp.Children[0] is TextBlock tb && tb.Text == "pool-stack-carrier"); + H.Check("PoolStack_Phase0_Present", first is not null); + H.Check("PoolStack_Phase0_LocalValuesWritten", + first is not null + && first.ReadLocalValue(StackPanel.PaddingProperty) != DependencyProperty.UnsetValue + && first.ReadLocalValue(StackPanel.CornerRadiusProperty) != DependencyProperty.UnsetValue + && first.ReadLocalValue(Panel.BackgroundProperty) != DependencyProperty.UnsetValue); + + H.ClickButton("DropPoolStack"); + await Harness.Render(); + // Load-bearing premise, not a status report — see PoolCtrl_Phase1_Returned. + // Without the drop the reconciler could update the StackPanel in place, and the + // cleared checks below would be exercising ApplyModifiers' unset arm rather + // than CleanElement. + H.Check("PoolStack_Phase1_Returned", + H.FindControl(sp => + sp.Children.Count > 0 && sp.Children[0] is TextBlock tb + && tb.Text == "pool-stack-carrier") is null); + H.ClickButton("RemountPoolStack"); + await Harness.Render(); + var second = H.FindControl(sp => + sp.Children.Count > 0 && sp.Children[0] is TextBlock tb && tb.Text == "pool-stack-carrier-2"); + // Load-bearing: without instance reuse every check below passes trivially. + H.Check("PoolStack_Phase2_ReusedInstance", + first is not null && ReferenceEquals(first, second)); + if (second is null) return; + + H.Check("PoolStack_Phase2_PaddingCleared", + second.ReadLocalValue(StackPanel.PaddingProperty) == DependencyProperty.UnsetValue); + H.Check("PoolStack_Phase2_CornerRadiusCleared", + second.ReadLocalValue(StackPanel.CornerRadiusProperty) == DependencyProperty.UnsetValue); + H.Check("PoolStack_Phase2_BackgroundCleared", + second.ReadLocalValue(Panel.BackgroundProperty) == DependencyProperty.UnsetValue); + } + } + + // ════════════════════════════════════════════════════════════════════ + // Issue #985, TextBlock half — TextBlock is the fourth Padding receiver + // ApplyModifiers writes to, and it is neither a Control, a Border nor a + // Panel, so it needs its own arm. The clear itself predates #985 (it + // arrived with #950) but lived in CleanElement's TextBlock case arm, + // past the point every source-scanning invariant stops reading — so the + // one receiver in Padding's control gate that no scanner and no fixture + // covered was the one that had shipped longest. #985 moved the line into + // the FE-common chain; this fixture is the live half of that. + // ════════════════════════════════════════════════════════════════════ + + internal class ModifierPoolClearValueTextPadding(Harness h) : SelfTestFixtureBase(h) + { + public override async Task RunAsync() + { + var host = H.CreateHost(); + + host.Mount(ctx => + { + var (phase, set) = ctx.UseState(0); + return VStack( + Button("DropPoolText", () => set(1)), + Button("RemountPoolText", () => set(2)), + phase switch + { + 0 => Factories.TextBlock("pool-text-carrier").Padding(23), + 1 => Empty(), + // Remounted with no modifiers at all. + _ => Factories.TextBlock("pool-text-carrier-2"), + }); + }); + + await Harness.Render(); + var first = H.FindControl(tb => tb.Text == "pool-text-carrier"); + H.Check("PoolText_Phase0_Present", first is not null); + H.Check("PoolText_Phase0_LocalValueWritten", + first is not null + && first.ReadLocalValue(Microsoft.UI.Xaml.Controls.TextBlock.PaddingProperty) != DependencyProperty.UnsetValue); + + H.ClickButton("DropPoolText"); + await Harness.Render(); + // Load-bearing premise, not a status report — see PoolCtrl_Phase1_Returned. + // Without the drop the reconciler could update the TextBlock in place, and the + // cleared check below would be exercising ApplyModifiers' unset arm rather + // than CleanElement. + H.Check("PoolText_Phase1_Returned", + H.FindControl(tb => tb.Text == "pool-text-carrier") is null); + + H.ClickButton("RemountPoolText"); + await Harness.Render(); + var second = H.FindControl(tb => tb.Text == "pool-text-carrier-2"); + // Load-bearing: without instance reuse the check below passes trivially. + H.Check("PoolText_Phase2_ReusedInstance", + first is not null && ReferenceEquals(first, second)); + if (second is null) return; + + H.Check("PoolText_Phase2_PaddingCleared", + second.ReadLocalValue(Microsoft.UI.Xaml.Controls.TextBlock.PaddingProperty) == DependencyProperty.UnsetValue); } } diff --git a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs index 680863777c..475c960190 100644 --- a/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs +++ b/tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs @@ -420,6 +420,9 @@ internal static class SelfTestFixtureRegistry "ModifierEvent_StyleUnsetRestore", "ModifierEvent_PoolClearValueOnRent", "ModifierEvent_PoolClearValueControl", + "ModifierEvent_PoolClearValueControlPanel", + "ModifierEvent_PoolClearValueStackPadding", + "ModifierEvent_PoolClearValueTextPadding", "ModifierEvent_InlineMarginCarryForward", "ModifierEvent_InlineDropRestoresPhysical", "ModifierEvent_AccessibilityClearResets", @@ -2058,6 +2061,9 @@ internal static class SelfTestFixtureRegistry "ModifierEvent_StyleUnsetRestore" => new ModifierEventFixtures.ModifierStyleUnsetRestore(harness), "ModifierEvent_PoolClearValueOnRent" => new ModifierEventFixtures.ModifierPoolClearValueOnRent(harness), "ModifierEvent_PoolClearValueControl" => new ModifierEventFixtures.ModifierPoolClearValueControl(harness), + "ModifierEvent_PoolClearValueControlPanel" => new ModifierEventFixtures.ModifierPoolClearValueControlPanel(harness), + "ModifierEvent_PoolClearValueStackPadding" => new ModifierEventFixtures.ModifierPoolClearValueStackPadding(harness), + "ModifierEvent_PoolClearValueTextPadding" => new ModifierEventFixtures.ModifierPoolClearValueTextPadding(harness), "ModifierEvent_InlineMarginCarryForward" => new ModifierEventFixtures.ModifierInlineMarginCarryForward(harness), "ModifierEvent_InlineDropRestoresPhysical" => new ModifierEventFixtures.ModifierInlineDropRestoresPhysical(harness), "ModifierEvent_AccessibilityClearResets" => new ModifierEventFixtures.AccessibilityModifierClearResets(harness), diff --git a/tests/Reactor.Tests/AnalyzerTests/ModifierAvailableAnalyzerTests.cs b/tests/Reactor.Tests/AnalyzerTests/ModifierAvailableAnalyzerTests.cs index 6ae883bc7e..01f7b9b681 100644 --- a/tests/Reactor.Tests/AnalyzerTests/ModifierAvailableAnalyzerTests.cs +++ b/tests/Reactor.Tests/AnalyzerTests/ModifierAvailableAnalyzerTests.cs @@ -97,6 +97,10 @@ public class TextBlock : FrameworkElement } public class Button : Control { } + + // Not in ElementPool.PoolableTypes, unlike Button. Same base, so every control gate that + // names Control admits both — which is precisely why poolability cannot be read off a gate. + public class CheckBox : Control { } } namespace Microsoft.UI.Reactor @@ -106,6 +110,7 @@ namespace Microsoft.UI.Reactor using Microsoft.UI.Xaml.Controls; public record ButtonElement; + public record CheckBoxElement; public record GridElement; public record StackElement; public record RelativePanelElement; @@ -115,6 +120,7 @@ public record TextBlockElement; public static class Ext { public static ButtonElement Set(this ButtonElement el, Action