Files
DodoSSH/tests/DodoSSH.Client.App.Layout.Tests/LayoutHarness.cs
T
jaap-jan c5dec2d68e Measure the vault column instead of arguing about it
Nothing in this repository loaded a .axaml, so the one class of defect this
window has actually shipped — a control arranged past the edge of its container,
where it cannot be clicked — was the one class nothing could catch. The setup
screens rendered sliced once, with their buttons unreachable. The vault column is
the next candidate: 340 pixels wide, two lists and two editors, and the only
thing keeping it from clipping its own Save button at the window's 520-pixel
minimum is a state rule that one editor may be open at a time.

That rule was added on the strength of an argument. This adds an
Avalonia.Headless project that lays real XAML out at a real size and reports
what a user could not reach, and the argument is now a number: with both editors
open the column overflows, so the rule is load-bearing rather than defensive.
BothEditorsAtOnce_DoNotFit_WhichIsWhyTheRuleExists is the test, and it says what
to do if it ever starts passing — the column has room, so delete the rule, not
the test.

Two findings arrived by measuring rather than by reasoning, and the first one
changed the design.

MainWindow cannot be shown headlessly at all. Showing it attaches the terminal's
NativeWebView, whose Win32 adapter initialises WebView2 on attach, and WebView2
refuses a non-STA thread — which is exactly why Program.Main carries [STAThread]
and is written down in that comment. A HeadlessUnitTestSession owns its
dispatcher thread and offers no apartment choice, so the whole window is out of
reach at any size. That is pinned as a test asserting RPC_E_CHANGED_MODE by
HResult rather than by message, so a future Avalonia that makes the adapter lazy
will fail it and the harness can be widened.

So the column had to become its own control to be measurable, which is the
extraction the type-selector rework wanted anyway. Keyboard release moved with
it: MainWindow used to call Focus() on HostList by name, and now asks
VaultColumn.KeyboardTarget. The window decides that the keyboard should leave the
terminal and the column decides where it lands — which is the seam the rework
needs, because once the column shows one list at a time, "which list owns the
keyboard" is a question only the column can answer.

The second finding is the way this kind of test lies quietly. The hint class
lived in MainWindow.Styles and carries TextWrapping. A Window's styles reach its
whole tree, so nothing about the application depended on where it lived — but a
control laid out on its own loses them, and every hint paragraph would have
measured as a single line. The harness would have passed while measuring heights
that were all too small. The three shared classes now live in App.axaml, which
changes no rendering and makes the measurement honest.

The detector is calibrated in both directions, because a clipping detector that
never fires reads as a guarantee: a deliberately clipped Save button is caught by
name, and a list longer than its viewport is exempt. Scrolling is how a list is
supposed to handle more rows than fit, and without that exemption the host list
would fail the moment it had content. It also mis-fired once and the rule is
narrower for it — an empty ListBox is zero pixels tall and correct, so "arranged
with no size" now applies only to controls the theme gives a height to.

Skia rather than the headless drawing stub, deliberately. The stub's font manager
invents glyph metrics, and text height is an input to every stacked panel in this
column, so measuring against it would produce numbers that are self-consistent
and unrelated to the application.

A separate test project rather than more tests in DodoSSH.Client.App.Tests.
Avalonia's application, dispatcher and platform are process-global singletons
initialised once, and that project's identity is the shell's state machine
without Avalonia — the whole reason sign-in is a delegate. The fakes needed to
reach a real unlocked vault are shared from DodoSSH.Client.Session.Tests by
source link: a project reference would make one test project a library of
another, and a copy would be a third implementation of the same decision table
drifting from the other two.

855 tests green, 10 of them new. Zero warnings, dotnet format clean.

Not done, and this is groundwork rather than the item itself: the type selector.
The column still holds both lists at once, so a third item type would still
recreate the defect the one-editor rule works around. What is different is that
the rework can now be checked instead of eyeballed — including the claim it is
being made for, that one editor at a time stops being a runtime rule and becomes
a fact about what is in the visual tree.

What this harness will never catch is the terminal's native child window
compositing over Avalonia content. That is a Win32 property of a real window, no
headless surface reproduces it, and it is the reason the WebView is collapsed
rather than covered.
2026-07-30 11:34:09 +02:00

186 lines
8.0 KiB
C#

using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace DodoSSH.Client.App.Layout.Tests;
/// <summary>
/// Lays out real XAML at a real size and reports anything a user could not click.
/// </summary>
/// <remarks>
/// <para>
/// The defect this exists for is a control arranged past the edge of its container. It is invisible to every
/// other suite here — no other test loads a <c>.axaml</c> — and this window has shipped it once, when the
/// setup screens rendered sliced with their buttons unreachable at the default width.
/// </para>
/// <para>
/// A control inside a <see cref="ScrollViewer"/> is exempt, and that exemption is load-bearing rather than a
/// convenience: a list longer than its viewport is the normal case, and treating a row scrolled out of sight
/// as a defect would make this harness cry wolf on every populated list. What is left after the exemption is
/// the class of thing that has no way to come back into view.
/// </para>
/// </remarks>
internal static class LayoutHarness
{
/// <summary>The window's own declared minimum, which is the size that has to work.</summary>
/// <remarks>
/// Taken from <c>MainWindow.axaml</c>'s <c>MinWidth</c>/<c>MinHeight</c> by hand. A test asserts these
/// two constants still match the XAML, so the harness cannot quietly start measuring a window larger
/// than the one a user is allowed to drag to.
/// </remarks>
internal const double MinimumWidth = 820;
/// <inheritdoc cref="MinimumWidth" />
internal const double MinimumHeight = 520;
/// <summary>The vault column's fixed width, from <c>MainWindow</c>'s <c>ColumnDefinitions</c>.</summary>
internal const double VaultColumnWidth = 340;
/// <summary>
/// What the account bar takes off the top before the column gets any height at all.
/// </summary>
/// <remarks>
/// The bar is <c>Padding="12,8"</c> around a row whose tallest child is a themed <see cref="Button"/>, so
/// its height is the button's plus sixteen. Stated as a constant with a test holding the button to
/// thirty-two rather than measured from the bar itself, because measuring the bar would mean showing
/// <c>MainWindow</c>, and that cannot be done here at all — see the harness's own tests.
/// </remarks>
internal const double AccountBarHeight = 48;
/// <summary>The height the column actually gets at the window's minimum.</summary>
internal static double VaultColumnHeight => MinimumHeight - AccountBarHeight;
private static readonly HeadlessUnitTestSession Session =
HeadlessUnitTestSession.GetOrStartForAssembly(typeof(LayoutHarness).Assembly);
/// <summary>
/// Runs one body on Avalonia's dispatcher thread.
/// </summary>
/// <remarks>
/// Everything that touches a control has to happen here. The session owns the thread and the
/// application, so this is also what serialises the suite — Avalonia's platform is process-global and
/// two tests laying out windows at once would share one dispatcher.
/// </remarks>
internal static Task OnTheUiThreadAsync(Action body, CancellationToken cancellationToken) =>
Session.Dispatch(body, cancellationToken);
/// <summary>Shows a window at a given size and lets layout finish.</summary>
internal static void Settle(Window window, double width, double height)
{
ArgumentNullException.ThrowIfNull(window);
window.Width = width;
window.Height = height;
// None, because a headless window still reserves space for decorations it does not draw, and the
// budget being measured is the client area the application actually gets.
window.WindowDecorations = WindowDecorations.None;
window.Show();
// Show() queues layout rather than performing it. Without this the tree is measured but not
// arranged, and every Bounds read below would be a zero rectangle — which would make this harness
// report the whole window as unreachable, or worse, report nothing at all.
Dispatcher.UIThread.RunJobs();
window.UpdateLayout();
}
/// <summary>Wraps a control in a host window sized to the application's minimum.</summary>
internal static Window HostAtMinimumSize(Control content, double width, double height)
{
var window = new Window { Content = content };
Settle(window, width, height);
return window;
}
/// <summary>
/// Every interactive control that is laid out where it cannot be used, described for a failure message.
/// </summary>
/// <remarks>
/// Returns descriptions rather than controls because the value of this harness is entirely in what it
/// says when it fails: "something is clipped" sends the reader back to a 500-line XAML file, while
/// "Button 'Save' at 8,486 486x32 falls outside 820x520" names the control and the edge it crossed.
/// </remarks>
internal static IReadOnlyList<string> Unreachable(Window window)
{
ArgumentNullException.ThrowIfNull(window);
var client = new Rect(window.ClientSize);
var found = new List<string>();
foreach (var control in window.GetVisualDescendants().OfType<Control>())
{
if (Fault(control, client, window) is { } fault)
{
found.Add(fault);
}
}
return found;
}
private static string? Fault(Control control, Rect client, Visual window)
{
if (!IsInteractive(control) || !control.IsEffectivelyVisible || IsScrollable(control))
{
return null;
}
if (control.TranslatePoint(default, window) is not { } origin)
{
return null;
}
var box = new Rect(origin, control.Bounds.Size);
// Zero size is a defect for a control the theme gives a height to and a normal state for one sized by
// its content: an empty list is zero pixels tall and correct, a squashed button is neither. Learned
// from this firing on KeyList in a vault with no keys in it.
if (control is not ListBox && (box.Width <= 0 || box.Height <= 0))
{
return Describe(control, box, client, "was arranged with no size");
}
return client.Contains(box) ? null : Describe(control, box, client, "falls outside the window");
}
/// <remarks>
/// The controls a user has to be able to reach. A clipped <see cref="TextBlock"/> is a cosmetic problem
/// and a clipped <see cref="Button"/> is a dead end, so only the second kind is worth failing a build
/// over — and keeping the list short is what stops this harness from becoming a pixel-diff nobody
/// trusts.
/// </remarks>
private static bool IsInteractive(Control control) =>
control is Button or TextBox or CheckBox or ComboBox or NumericUpDown or ListBox;
private static bool IsScrollable(Control control) =>
control.GetVisualAncestors().OfType<ScrollViewer>().Any();
private static string Describe(Control control, Rect box, Rect client, string fault)
{
var name = control.Name is { Length: > 0 } named ? $" '{named}'" : Label(control);
return string.Create(
CultureInfo.InvariantCulture,
$"{control.GetType().Name}{name} {fault}: {Format(box)} is not inside {Format(client)}");
}
/// <remarks>
/// A button's caption, because "Save" identifies the control to a reader far better than its position
/// in a visual tree does.
/// </remarks>
private static string Label(Control control) => control switch
{
Button { Content: string caption } => $" '{caption}'",
TextBox { PlaceholderText: { Length: > 0 } placeholder } => $" (placeholder '{placeholder}')",
_ => string.Empty,
};
private static string Format(Rect rect) => string.Create(
CultureInfo.InvariantCulture,
$"{rect.X:0.#},{rect.Y:0.#} {rect.Width:0.#}x{rect.Height:0.#}");
}