merge: visual controls (virtualizing card grid, filmstrip, charts, preview viewport, curve editor)

This commit is contained in:
Claude committed 2026-10-02 10:40:04 +00:00
commit ffa67da4eb
37 files changed
+5950

No files matched your search

@@ -0,0 +1,85 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class CurveMathTests
{
private const double Gap = CurveMath.DefaultMinGap;
[Test]
public void DraggedPointCannotPassItsNeighbours()
{
double[] xs = [0, 0.3, 0.6, 1];
Assert.Approximately(0.6 - Gap, CurveMath.ConstrainX(xs, 1, 0.9, Gap, pinEnds: true), 1e-12);
Assert.Approximately(0 + Gap, CurveMath.ConstrainX(xs, 1, -0.4, Gap, pinEnds: true), 1e-12);
Assert.Approximately(0.45, CurveMath.ConstrainX(xs, 1, 0.45, Gap, pinEnds: true), 1e-12);
}
[Test]
public void PinnedEndsStayAtZeroAndOne()
{
double[] xs = [0, 0.5, 1];
Assert.Approximately(0, CurveMath.ConstrainX(xs, 0, 0.2, Gap, pinEnds: true), 0);
Assert.Approximately(1, CurveMath.ConstrainX(xs, 2, 0.7, Gap, pinEnds: true), 0);
}
[Test]
public void FreeEndsMoveInsideTheUnitInterval()
{
double[] xs = [0.1, 0.5, 0.9];
Assert.Approximately(0, CurveMath.ConstrainX(xs, 0, -3, Gap, pinEnds: false), 0);
Assert.Approximately(0.5 - Gap, CurveMath.ConstrainX(xs, 0, 0.8, Gap, pinEnds: false), 1e-12);
Assert.Approximately(1, CurveMath.ConstrainX(xs, 2, 4, Gap, pinEnds: false), 0);
}
[Test]
public void AnySequenceOfDragsKeepsXStrictlyIncreasing()
{
var random = new Random(11);
double[] xs = [0, 0.2, 0.4, 0.6, 0.8, 1];
for (var step = 0; step < 10_000; step++)
{
var i = random.Next(xs.Length);
xs[i] = CurveMath.ConstrainX(xs, i, random.NextDouble() * 1.4 - 0.2, Gap, pinEnds: true);
for (var k = 1; k < xs.Length; k++) Assert.True(xs[k] - xs[k - 1] >= Gap - 1e-12, $"x[{k - 1}]={xs[k - 1]} x[{k}]={xs[k]}");
Assert.Approximately(0, xs[0], 0);
Assert.Approximately(1, xs[^1], 0);
}
}
[Test]
public void InsertionKeepsOrderAndRespectsGapAndPins()
{
double[] xs = [0, 0.5, 1];
Assert.Equal(1, CurveMath.InsertionIndex(xs, 0.25, Gap, pinEnds: true));
Assert.Equal(2, CurveMath.InsertionIndex(xs, 0.75, Gap, pinEnds: true));
Assert.Equal(-1, CurveMath.InsertionIndex(xs, 0.5 + Gap / 2, Gap, pinEnds: true));
Assert.Equal(-1, CurveMath.InsertionIndex(xs, 1.2, Gap, pinEnds: false));
double[] free = [0.2, 0.6];
Assert.Equal(0, CurveMath.InsertionIndex(free, 0.1, Gap, pinEnds: false));
Assert.Equal(2, CurveMath.InsertionIndex(free, 0.9, Gap, pinEnds: false));
Assert.Equal(-1, CurveMath.InsertionIndex(free, 0.1, Gap, pinEnds: true));
}
[Test]
public void RemovalKeepsTwoPointsAndPinnedEnds()
{
Assert.False(CurveMath.CanRemove(2, 1, pinEnds: false));
Assert.True(CurveMath.CanRemove(3, 0, pinEnds: false));
Assert.False(CurveMath.CanRemove(3, 0, pinEnds: true));
Assert.True(CurveMath.CanRemove(3, 1, pinEnds: true));
Assert.False(CurveMath.CanRemove(3, 2, pinEnds: true));
}
[Test]
public void HitTestPicksTheNearestPointWithinRadius()
{
double[] xs = [10, 50, 54];
double[] ys = [10, 10, 10];
Assert.Equal(2, CurveMath.HitTest(xs, ys, 53, 11, 6));
Assert.Equal(1, CurveMath.HitTest(xs, ys, 51, 10, 6));
Assert.Equal(-1, CurveMath.HitTest(xs, ys, 30, 10, 6));
}
}
@@ -0,0 +1,59 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class LruCacheTests
{
[Test]
public void EvictsTheLeastRecentlyUsedEntry()
{
var cache = new LruCache<int, string>(2);
cache.Set(1, "a");
cache.Set(2, "b");
Assert.True(cache.TryGet(1, out _));
cache.Set(3, "c");
Assert.False(cache.TryGet(2, out _));
Assert.True(cache.TryGet(1, out var one));
Assert.Equal("a", one);
Assert.True(cache.TryGet(3, out _));
Assert.Equal(2, cache.Count);
}
[Test]
public void ReplacingAValueRefreshesItsRecency()
{
var cache = new LruCache<int, string>(2);
cache.Set(1, "a");
cache.Set(2, "b");
cache.Set(1, "a2");
cache.Set(3, "c");
Assert.True(cache.TryGet(1, out var value));
Assert.Equal("a2", value);
Assert.False(cache.TryGet(2, out _));
}
[Test]
public void ShrinkingCapacityEvictsOldestFirst()
{
var cache = new LruCache<int, int>(10);
for (var i = 0; i < 10; i++) cache.Set(i, i);
cache.Capacity = 3;
Assert.Equal(3, cache.Count);
for (var i = 0; i < 7; i++) Assert.False(cache.TryGet(i, out _));
for (var i = 7; i < 10; i++) Assert.True(cache.TryGet(i, out _));
}
[Test]
public void RemoveAndClear()
{
var cache = new LruCache<string, int>(4);
cache.Set("x", 1);
cache.Set("y", 2);
Assert.True(cache.Remove("x"));
Assert.False(cache.Remove("x"));
cache.Clear();
Assert.Equal(0, cache.Count);
Assert.Throws<ArgumentOutOfRangeException>(() => _ = new LruCache<int, int>(0));
}
}
@@ -0,0 +1,106 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class MinMaxDecimatorTests
{
[Test]
public void ShortSeriesKeepsEverySample()
{
double[] values = [3, 1, 4, 1, 5];
var output = new int[MinMaxDecimator.Capacity(values.Length, 10)];
var n = MinMaxDecimator.Decimate(values, 10, output);
Assert.SequenceEqual([0, 1, 2, 3, 4], output[..n]);
}
[Test]
public void LongSeriesKeepsAtMostTwoSamplesPerColumn()
{
var values = Noise(200_000, seed: 1);
const int columns = 800;
var output = new int[MinMaxDecimator.Capacity(values.Length, columns)];
var n = MinMaxDecimator.Decimate(values, columns, output);
Assert.LessOrEqual(n, 2 * columns);
Assert.Monotonic(output[..n].Select(i => (double)i), strict: true);
}
[Test]
public void EveryColumnPreservesItsMinimumAndMaximum()
{
var values = Noise(123_457, seed: 2);
// Plant spikes that a naive stride sampler would miss.
values[50_001] = 1000;
values[99_999] = -1000;
const int columns = 640;
var output = new int[MinMaxDecimator.Capacity(values.Length, columns)];
var n = MinMaxDecimator.Decimate(values, columns, output);
var kept = output[..n];
for (var c = 0; c < columns; c++)
{
var start = (int)((long)c * values.Length / columns);
var end = (int)((long)(c + 1) * values.Length / columns);
double min = double.PositiveInfinity, max = double.NegativeInfinity;
double keptMin = double.PositiveInfinity, keptMax = double.NegativeInfinity;
for (var i = start; i < end; i++)
{
min = Math.Min(min, values[i]);
max = Math.Max(max, values[i]);
}
foreach (var i in kept)
{
if (i < start || i >= end) continue;
keptMin = Math.Min(keptMin, values[i]);
keptMax = Math.Max(keptMax, values[i]);
}
Assert.Equal(min, keptMin, $"column {c} min");
Assert.Equal(max, keptMax, $"column {c} max");
}
Assert.Contains(50_001, kept);
Assert.Contains(99_999, kept);
}
[Test]
public void NonFiniteRunsBecomeSingleGaps()
{
double[] values = [1, double.NaN, double.NaN, 2, double.PositiveInfinity, 3, double.NaN];
var output = new int[values.Length];
var n = MinMaxDecimator.Decimate(values, 100, output);
Assert.SequenceEqual([0, MinMaxDecimator.Gap, 3, MinMaxDecimator.Gap, 5], output[..n]);
}
[Test]
public void EmptyColumnsBreakTheLineInDecimatedMode()
{
var values = new double[1000];
for (var i = 0; i < values.Length; i++) values[i] = i < 400 || i >= 600 ? i : double.NaN;
var output = new int[MinMaxDecimator.Capacity(values.Length, 10)];
var n = MinMaxDecimator.Decimate(values, 10, output);
// Columns 4 and 5 (indices 400–599) hold no finite sample: exactly one gap between columns 3 and 6.
Assert.SequenceEqual([0, 99, 100, 199, 200, 299, 300, 399, MinMaxDecimator.Gap, 600, 699, 700, 799, 800, 899, 900, 999], output[..n]);
}
[Test]
public void FlatColumnsEmitOneSample()
{
var values = Enumerable.Repeat(5.0, 1000).ToArray();
var output = new int[MinMaxDecimator.Capacity(values.Length, 4)];
var n = MinMaxDecimator.Decimate(values, 4, output);
Assert.SequenceEqual([0, 250, 500, 750], output[..n]);
}
[Test]
public void UndersizedOutputIsRejected()
{
Assert.Throws<ArgumentException>(() => MinMaxDecimator.Decimate(new double[100], 10, new int[5]));
}
private static double[] Noise(int count, int seed)
{
var random = new Random(seed);
var values = new double[count];
for (var i = 0; i < count; i++) values[i] = Math.Sin(i * 0.001) + random.NextDouble() * 0.2;
return values;
}
}
@@ -0,0 +1,91 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class NiceScaleTests
{
[Theory]
[Case(0.6, true, 0.5)]
[Case(1.2, true, 1.0)]
[Case(2.9, true, 2.0)]
[Case(3.1, true, 5.0)]
[Case(7.5, true, 10.0)]
[Case(1.2, false, 2.0)]
[Case(4.0, false, 5.0)]
[Case(5.0, false, 5.0)]
[Case(1234.0, false, 2000.0)]
[Case(0.025, true, 0.02)]
public void NiceNumbersAreOneTwoOrFiveTimesAPowerOfTen(double value, bool round, double expected)
{
Assert.Approximately(expected, NiceScale.NiceNumber(value, round), expected * 1e-12);
}
[Test]
public void InnerTicksStayInsideTheRangeOnNiceMultiples()
{
var ticks = NiceScale.Inner(0.13, 0.87, 5);
Assert.Approximately(0.2, ticks.Step, 1e-12);
Assert.Equal(4, ticks.Count);
Assert.Approximately(0.2, ticks[0], 1e-12);
Assert.Approximately(0.8, ticks[3], 1e-12);
for (var i = 0; i < ticks.Count; i++) Assert.InRange(ticks[i], 0.13, 0.87);
}
[Test]
public void OuterTicksEncloseTheRange()
{
var ticks = NiceScale.Outer(3, 1870, 5);
Assert.Approximately(500, ticks.Step, 1e-9);
Assert.Approximately(0, ticks.First, 1e-9);
Assert.Approximately(2000, ticks.Last, 1e-9);
Assert.Equal(5, ticks.Count);
}
[Test]
public void TickValuesDoNotDriftOverManySteps()
{
var ticks = NiceScale.Inner(-1e6, 1e6, 11);
Assert.Approximately(200_000, ticks.Step, 1e-6);
Assert.Approximately(0, ticks[5], 1e-6);
Assert.Approximately(1e6, ticks[ticks.Count - 1], 1e-6);
}
[Test]
public void TickCountNeverExceedsTheRequest()
{
var random = new Random(7);
for (var i = 0; i < 1000; i++)
{
var a = (random.NextDouble() - 0.5) * Math.Pow(10, random.Next(-3, 7));
var b = a + random.NextDouble() * Math.Pow(10, random.Next(-3, 7)) + 1e-9;
var max = random.Next(2, 12);
var ticks = NiceScale.Inner(a, b, max);
Assert.LessOrEqual(ticks.Count, max);
}
}
[Test]
public void PadWidensBothSidesAndCentresFlatData()
{
var (min, max) = NiceScale.Pad(10, 20, 0.1);
Assert.Approximately(9, min, 1e-12);
Assert.Approximately(21, max, 1e-12);
var (flatMin, flatMax) = NiceScale.Pad(5, 5, 0.1);
Assert.Approximately(5, (flatMin + flatMax) / 2, 1e-12);
Assert.Greater(flatMax - flatMin, 0);
var (zeroMin, zeroMax) = NiceScale.Pad(0, 0, 0.1);
Assert.Approximately(-1, zeroMin, 1e-12);
Assert.Approximately(1, zeroMax, 1e-12);
Assert.Equal((0.0, 1.0), NiceScale.Pad(double.NaN, 3, 0.1));
}
[Test]
public void DegenerateRangesGiveNoInnerTicks()
{
Assert.Equal(0, NiceScale.Inner(4, 4, 5).Count);
Assert.Equal(0, NiceScale.Inner(double.NaN, 4, 5).Count);
}
}
@@ -0,0 +1,34 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class PixelGridTests
{
[Theory]
[Case(1.0)]
[Case(1.25)]
[Case(1.5)]
[Case(2.0)]
public void HairlinesCoverWholeDevicePixels(double scale)
{
var thickness = PixelGrid.SnapThickness(1, scale);
var devicePixels = thickness * scale;
Assert.Approximately(Math.Round(devicePixels), devicePixels, 1e-9);
for (var v = 0.0; v < 50; v += 0.37)
{
var centre = PixelGrid.SnapLine(v, thickness, scale) * scale;
var left = centre - devicePixels / 2;
Assert.Approximately(Math.Round(left), left, 1e-9, $"v={v}");
Assert.LessOrEqual(Math.Abs(centre - v * scale), 1);
}
}
[Test]
public void SnapRoundsToDevicePixelBoundaries()
{
Assert.Approximately(10, PixelGrid.Snap(10.2, 1), 1e-12);
Assert.Approximately(10 + 2 / 3.0, PixelGrid.Snap(10.6, 1.5), 1e-12);
Assert.Approximately(3.3, PixelGrid.Snap(3.3, 0), 0);
}
}
@@ -0,0 +1,85 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class StripLayoutTests
{
[Test]
public void CellsFillTheWidthExactly()
{
var strip = new StripLayout(898, 36, 2, 3600);
Assert.Equal(23, strip.CellCount);
Assert.Approximately(898, strip.CellLeft(strip.CellCount - 1) + strip.CellWidth, 1e-9);
}
[Test]
public void ShortSequencesGetOneCellPerFrame()
{
var strip = new StripLayout(898, 36, 2, 5);
Assert.Equal(5, strip.CellCount);
for (var c = 0; c < 5; c++) Assert.Equal(c, strip.FrameForCell(c));
}
[Theory]
[Case(3600, 23)]
[Case(5, 4)]
[Case(7, 7)]
[Case(1001, 24)]
[Case(24, 23)]
public void EachCellShowsAFrameFromItsOwnRun(int frames, int cells)
{
var strip = new StripLayout(cells * 40 - 2, 38, 2, frames);
Assert.Equal(Math.Min(cells, frames), strip.CellCount);
var previous = -1;
for (var c = 0; c < strip.CellCount; c++)
{
var frame = strip.FrameForCell(c);
Assert.Equal(c, strip.CellForFrame(frame));
Assert.Greater(frame, previous);
previous = frame;
}
}
[Test]
public void SeekingMapsXToFramesContinuously()
{
var strip = new StripLayout(900, 36, 2, 3600);
Assert.Equal(0, strip.FrameAt(-5));
Assert.Equal(0, strip.FrameAt(0));
Assert.Equal(1800, strip.FrameAt(450));
Assert.Equal(3599, strip.FrameAt(900));
Assert.Equal(3599, strip.FrameAt(5000));
Assert.Equal(412, strip.FrameAt(strip.XForFrame(412)));
}
[Test]
public void EmptyStripHasNoCells()
{
var strip = new StripLayout(900, 36, 2, 0);
Assert.Equal(0, strip.CellCount);
Assert.Equal(-1, strip.FrameAt(10));
Assert.Equal(-1, strip.FrameForCell(0));
}
[Test]
public void HeatmapHitTestExcludesGaps()
{
var grid = new CellGridLayout(30, 20, 8, 12, 16, 3);
Assert.True(grid.TryHit(30 + 19 * 2 + 5, 20 + 19 * 7 + 15.5, out var row, out var column));
Assert.Equal(7, row);
Assert.Equal(2, column);
Assert.False(grid.TryHit(30 + 16.5, 25, out _, out _));
Assert.False(grid.TryHit(29, 25, out _, out _));
Assert.False(grid.TryHit(30 + grid.Width + 1, 25, out _, out _));
Assert.Approximately(12 * 19 - 3, grid.Width, 1e-12);
}
[Test]
public void HeatmapCellsFitTheSmallerAxis()
{
Assert.Approximately(16, CellGridLayout.FitCellSize(500, 149, 8, 12, 3, 24), 1e-9);
Assert.Approximately(24, CellGridLayout.FitCellSize(5000, 5000, 8, 12, 3, 24), 1e-9);
Assert.Approximately((260 - 33) / 12.0, CellGridLayout.FitCellSize(260, double.PositiveInfinity, 8, 12, 3, 24), 1e-9);
}
}
@@ -0,0 +1,72 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class ViewportMathTests
{
[Test]
public void FitUsesTheLimitingAxisAndCentres()
{
// 8192×5464 into 900×430: height limits.
var scale = ViewportMath.FitScale(8192, 5464, 900, 430);
Assert.Approximately(430.0 / 5464, scale, 1e-12);
var t = ViewportMath.Centered(scale, 8192, 5464, 900, 430);
Assert.Approximately(0, t.OffsetY, 1e-9);
Assert.Approximately((900 - 8192 * scale) / 2, t.OffsetX, 1e-9);
Assert.Approximately(0, ViewportMath.FitScale(0, 100, 900, 430), 0);
}
[Test]
public void ZoomAtKeepsThePointUnderTheCursorFixed()
{
var t = new ViewTransform(0.25, 37, -12);
var (ix, iy) = t.ToImage(410, 220);
var zoomed = ViewportMath.ZoomAt(t, 1.7, 410, 220);
var (vx, vy) = zoomed.ToView(ix, iy);
Assert.Within(410, 220, vx, vy, 1e-9);
Assert.Approximately(1.7, zoomed.Scale, 0);
}
[Test]
public void WheelZoomStepsGeometricallyAndClamps()
{
Assert.Approximately(1.25, ViewportMath.WheelZoom(1, 1, 0.01, 32), 1e-12);
Assert.Approximately(1 / 1.5625, ViewportMath.WheelZoom(1, -2, 0.01, 32), 1e-12);
Assert.Approximately(32, ViewportMath.WheelZoom(30, 3, 0.01, 32), 0);
}
[Test]
public void ClampCentresSmallImagesAndCoversWithLargeOnes()
{
// Image 400×300 at scale 1 inside 900×430: centred on both axes whatever the offset.
var small = ViewportMath.Clamp(new ViewTransform(1, -500, 999), 400, 300, 900, 430);
Assert.Approximately(250, small.OffsetX, 1e-9);
Assert.Approximately(65, small.OffsetY, 1e-9);
// Image 4000×3000 at scale 1: the view must stay covered.
var large = ViewportMath.Clamp(new ViewTransform(1, 100, -5000), 4000, 3000, 900, 430);
Assert.Approximately(0, large.OffsetX, 1e-9);
Assert.Approximately(430 - 3000, large.OffsetY, 1e-9);
}
[Test]
public void PanMovesAndRoundTripsThroughImageCoordinates()
{
var t = ViewportMath.Pan(new ViewTransform(2, 10, 20), -4, 6);
Assert.Approximately(6, t.OffsetX, 0);
Assert.Approximately(26, t.OffsetY, 0);
var (x, y) = t.ToView(123.5, 77.25);
var (ix, iy) = t.ToImage(x, y);
Assert.Within(123.5, 77.25, ix, iy, 1e-12);
}
[Test]
public void SnapOffsetAlignsToDevicePixels()
{
// 150 % DPI: 1.5 device pixels per DIP.
var t = ViewportMath.SnapOffset(new ViewTransform(1, 10.4, -3.1), 1.5);
Assert.Approximately(Math.Round(10.4 * 1.5), t.OffsetX * 1.5, 1e-9);
Assert.Approximately(Math.Round(-3.1 * 1.5), t.OffsetY * 1.5, 1e-9);
}
}
@@ -0,0 +1,322 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
/// <summary>
/// Loads the real theme (Controls.xaml + Visuals.xaml) on an STA dispatcher and measures, arranges and renders
/// every visual off screen in both themes: catches template, resource and layout errors that compile cleanly.
/// </summary>
[WindowsOnly]
[Serial]
public sealed class VisualsSmokeTests
{
[Test]
public void ThemeProvidesVisualStyles() => WpfHost.Run(() =>
{
Assert.True(Application.Current.TryFindResource(typeof(SequenceCard)) is Style);
Assert.True(Application.Current.TryFindResource(typeof(PreviewViewport)) is Style);
Assert.True(Application.Current.TryFindResource("ListBox.Cards") is Style);
Assert.True(Application.Current.TryFindResource("ListBoxItem.Card") is Style);
});
[Test]
public void EveryVisualRendersInBothThemes() => WpfHost.Run(() =>
{
foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light })
{
ThemeManager.Apply(theme);
foreach (var (name, element, width, height) in Samples())
{
var pixels = Painted(Render(element, width, height));
Assert.Greater(pixels, 0, $"{name} drew nothing in {theme}");
}
}
ThemeManager.Apply(AppTheme.Dark);
});
[Test]
public void CardFitsTheDefaultGridSlot() => WpfHost.Run(() =>
{
var card = SampleCard();
card.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Assert.Approximately(236, card.DesiredSize.Width, 0.5);
Assert.LessOrEqual(card.DesiredSize.Height, (double)VirtualizingWrapPanel.ItemHeightProperty.DefaultMetadata.DefaultValue + 0.5);
});
[Test]
public void WrapPanelVirtualizesHalfAMillionItems() => WpfHost.Run(() =>
{
var list = new ListBox
{
Style = (Style)Application.Current.FindResource("ListBox.Cards"),
ItemsSource = Enumerable.Range(0, 500_000).ToArray(),
};
Render(list, 1300, 900);
var panel = Assert.NotNull(FindChild<VirtualizingWrapPanel>(list));
var columns = WrapLayout.ColumnsFor(1300 - 40, panel.ItemWidth, panel.Spacing);
var rows = (int)Math.Ceiling(900 / (panel.ItemHeight + panel.Spacing)) + 3;
Assert.LessOrEqual(panel.Children.Count, rows * columns);
Assert.Approximately(100_000 * (panel.ItemHeight + panel.Spacing) - panel.Spacing + 16, panel.ExtentHeight, 1);
var stopwatch = Stopwatch.StartNew();
for (var i = 0; i < 300; i++)
{
panel.SetVerticalOffset(panel.VerticalOffset + 37);
list.UpdateLayout();
}
stopwatch.Stop();
Assert.Less(stopwatch.Elapsed.TotalSeconds, 5, "300 scroll steps");
Assert.LessOrEqual(panel.Children.Count, rows * columns);
panel.SetVerticalOffset(panel.ExtentHeight / 2);
list.UpdateLayout();
var first = (int)((ListBoxItem)panel.Children[0]).Content;
Assert.InRange(first, 249_000, 251_000);
list.ScrollIntoView(400_000);
list.UpdateLayout();
Assert.NotNull(list.ItemContainerGenerator.ContainerFromIndex(400_000));
Assert.LessOrEqual(panel.Children.Count, rows * columns);
});
[Test]
public void PreviewZoomModesMapToDevicePixels() => WpfHost.Run(() =>
{
var preview = new PreviewViewport { Source = Bitmap(2000, 1500) };
Render(preview, 800, 450);
var dpi = VisualTreeHelper.GetDpi(preview).DpiScaleX;
Assert.Approximately(Math.Min(800 / 2000.0, 450 / 1500.0) * dpi, preview.Zoom, 1e-6);
preview.ZoomMode = PreviewZoomMode.Actual;
Assert.Approximately(1, preview.Zoom, 1e-9);
preview.Zoom = 2;
Assert.Equal(PreviewZoomMode.Custom, preview.ZoomMode);
Assert.Approximately(2 / dpi, preview.View.Scale, 1e-9);
});
[Test]
public void SegmentsKnowTheirPosition() => WpfHost.Run(() =>
{
var control = SampleSegments();
Render(control, 120, 32);
Assert.Equal(SegmentPosition.First, ((SegmentedItem)control.Items[0]).Position);
Assert.Equal(SegmentPosition.Middle, ((SegmentedItem)control.Items[1]).Position);
Assert.Equal(SegmentPosition.Last, ((SegmentedItem)control.Items[2]).Position);
});
[Test]
public void FilmstripRequestsThumbnailsAsynchronously() => WpfHost.Run(() =>
{
var source = new FakeFrames(3600);
var strip = new Filmstrip { Source = source, CurrentIndex = 412 };
Render(strip, 900, 58);
WpfHost.DoEvents();
Assert.Greater(source.Requests, 0);
Assert.Greater(source.LastPixelWidth, 0);
Render(strip, 900, 58);
Assert.Equal(412, strip.CurrentIndex);
});
private static IEnumerable<(string Name, FrameworkElement Element, double Width, double Height)> Samples()
{
var n = 120_000;
var measured = new double[n];
var target = new double[n];
var sky = new double[n];
var random = new Random(3);
for (var i = 0; i < n; i++)
{
target[i] = 0.8 - i / (double)n * 0.6;
measured[i] = target[i] + (random.NextDouble() - 0.5) * 0.05;
sky[i] = i is > 500 and < 900 ? double.NaN : target[i] + 0.1;
}
var markers = new[] { new TimelineMarker(30_000, MarkerKind.ExposureStep, "-1 EV"), new TimelineMarker(70_000, MarkerKind.Keyframe) };
yield return ("SeriesChart", new SeriesChart
{
Series =
[
new ChartSeries("measured", measured, "Brush.Sun") { Thickness = 1.4 },
new ChartSeries("target", target, "Brush.Accent") { Thickness = 2.2 },
new ChartSeries("sky", sky, "Brush.Region") { Dash = LineDash.Dashed },
],
Markers = markers,
Summary = "summary",
CurrentIndex = 1000,
XLabelFormatter = v => v.ToString("N0"),
}, 900, 200);
var items = new[] { new ChartItem("2019", 0.3), new ChartItem("2020", 0.5), new ChartItem("2021", 1.8, "1.8 TB") };
yield return ("BarChart.Horizontal", new BarChart { Items = items, MinimumOpacity = 0.5 }, 300, 120);
yield return ("BarChart.Vertical", new BarChart { Items = items, Orientation = Orientation.Vertical, ShowGrid = true }, 300, 160);
yield return ("StackedBar", new StackedBar { Items = items }, 300, 60);
var months = new[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" };
var rows = Enumerable.Range(2019, 8).Select(y => new ChartRow(y.ToString(), Enumerable.Range(0, 12).Select(m => y == 2026 && m > 8 ? double.NaN : (double)(m * y % 97)).ToArray())).ToArray();
yield return ("HeatmapStrip", new HeatmapStrip { Rows = rows, ColumnLabels = months }, 300, 220);
yield return ("TimelineBands", new TimelineBands { Bands = rows, SlotLabels = months, CurrentBand = 1, CurrentSlot = 3 }, 600, 520);
yield return ("Filmstrip", new Filmstrip { Source = new FakeFrames(3600), Markers = markers, CurrentIndex = 500 }, 900, 58);
yield return ("CurveEditor", new CurveEditor
{
Points = new ObservableCollection<Point> { new(0, 0), new(0.5, 0.3), new(1, 1) },
Evaluator = x => x * x,
Mode = CurveEditMode.TimeRemap,
ShowDiagonal = true,
PlayheadPosition = 0.4,
SelectedIndex = 1,
}, 400, 200);
yield return ("PreviewViewport", new PreviewViewport
{
Source = Bitmap(2000, 1500),
OriginalSource = Bitmap(1000, 750),
IsCompareEnabled = true,
WipeLabel = "original | corrected",
InfoText = "0413 / 3,600",
ShowVectors = true,
MotionVectors = [new MotionVector(100, 100, 3, -2), new MotionVector(900, 700, -1, 4)],
VectorScale = 20,
ShowRegions = true,
RegionBoundary = [new Point(0, 800), new Point(1000, 760), new Point(2000, 820)],
ShowCropMask = true,
CropRect = new Rect(0.1, 0.1, 0.8, 0.8),
}, 800, 450);
yield return ("SequenceCard", SampleCard(), 236, 208);
yield return ("SegmentedControl", SampleSegments(), 120, 32);
yield return ("SplitButton", new SplitButton { Content = "Render", ItemsSource = new[] { "4K", "1080p" }, IsPrimary = true }, 200, 32);
}
private static SequenceCard SampleCard() => new()
{
Title = "Harbour sunset",
Subtitle = "3,600 · Canon EOS R5 · 2 h 00 m",
Badge = "3,600",
Thumbnail = Bitmap(320, 180),
IsSelected = true,
Statuses = new[] { new CardStatus(StatusKind.Analysed, "a"), new CardStatus(StatusKind.Rendered, "2"), new CardStatus(StatusKind.Synced) },
};
private static SegmentedControl SampleSegments()
{
var control = new SegmentedControl();
foreach (var key in new[] { "Icon.ViewGrid", "Icon.ViewList", "Icon.ViewTimeline" })
control.Items.Add(new SegmentedItem { Glyph = (IconData)Application.Current.FindResource(key), ToolTip = key });
control.SelectedIndex = 0;
return control;
}
private static BitmapSource Bitmap(int width, int height)
{
var pixels = new byte[width * height * 4];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var i = (y * width + x) * 4;
pixels[i] = (byte)(x * 255 / width);
pixels[i + 1] = (byte)(y * 255 / height);
pixels[i + 2] = 128;
pixels[i + 3] = 255;
}
}
var bitmap = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, pixels, width * 4);
bitmap.Freeze();
return bitmap;
}
private static RenderTargetBitmap Render(FrameworkElement element, double width, double height)
{
element.Measure(new Size(width, height));
element.Arrange(new Rect(0, 0, width, height));
element.UpdateLayout();
var bitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(element);
return bitmap;
}
private static int Painted(BitmapSource bitmap)
{
var stride = bitmap.PixelWidth * 4;
var pixels = new byte[stride * bitmap.PixelHeight];
bitmap.CopyPixels(pixels, stride, 0);
var count = 0;
for (var i = 3; i < pixels.Length; i += 4)
if (pixels[i] != 0) count++;
return count;
}
private static T? FindChild<T>(DependencyObject root)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match) return match;
if (FindChild<T>(child) is { } nested) return nested;
}
return null;
}
private sealed class FakeFrames(int count) : IThumbnailSource
{
private readonly BitmapSource _frame = Bitmap(64, 36);
public int Count => count;
public int Requests { get; private set; }
public int LastPixelWidth { get; private set; }
public ValueTask<ImageSource?> GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
{
Requests++;
LastPixelWidth = pixelWidth;
return ValueTask.FromResult<ImageSource?>(_frame);
}
}
/// <summary>One STA dispatcher with an Application and the Titano theme, shared by the WPF tests.</summary>
private static class WpfHost
{
private static readonly Lazy<Dispatcher> Dispatcher = new(Start);
public static void Run(Action action) => Dispatcher.Value.Invoke(action);
/// <summary>Processes queued dispatcher work (async continuations) on the current dispatcher.</summary>
public static void DoEvents()
{
var frame = new DispatcherFrame();
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, () => frame.Continue = false);
System.Windows.Threading.Dispatcher.PushFrame(frame);
}
private static Dispatcher Start()
{
Dispatcher? dispatcher = null;
using var ready = new ManualResetEventSlim();
var thread = new Thread(() =>
{
var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
ThemeManager.Initialize(app, AppTheme.Dark);
dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
ready.Set();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
ready.Wait();
return dispatcher!;
}
}
}
@@ -0,0 +1,144 @@
using Titano.Testing;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Visuals;
public sealed class WrapLayoutTests
{
[Theory]
[Case(0.0, 1)]
[Case(235.0, 1)]
[Case(236.0, 1)]
[Case(487.0, 1)]
[Case(488.0, 2)]
[Case(1252.0, 5)]
[Case(1255.0, 5)]
public void ColumnsCountWholeItemsWithGapsBetween(double width, int expected)
{
// 236-px cards with 16-px gaps: n columns need n·236 + (n−1)·16 px.
Assert.Equal(expected, WrapLayout.ColumnsFor(width, 236, 16));
}
[Test]
public void RowsAndExtentLeaveNoTrailingGap()
{
var layout = new WrapLayout(11, 1252, 236, 208, 16);
Assert.Equal(5, layout.Columns);
Assert.Equal(3, layout.Rows);
Assert.Approximately(3 * 224 - 16, layout.ExtentHeight, 1e-9);
Assert.Approximately(5 * 236 + 4 * 16, layout.ExtentWidth, 1e-9);
Assert.Approximately(0, new WrapLayout(0, 1252, 236, 208, 16).ExtentHeight, 1e-9);
}
[Test]
public void IndexMapsToRowColumnAndPixelOrigin()
{
var layout = new WrapLayout(500_000, 1252, 236, 208, 16);
Assert.Equal(1234, layout.RowOf(6172));
Assert.Equal(2, layout.ColumnOf(6172));
Assert.Approximately(2 * 252, layout.LeftOf(6172), 1e-9);
Assert.Approximately(1234 * 224, layout.TopOf(6172), 1e-6);
Assert.Equal(100_000, layout.Rows);
}
[Test]
public void VisibleRangeIsConstantTimeAndCoversPartialRows()
{
var layout = new WrapLayout(500_000, 1252, 236, 208, 16);
// Offset in the middle of row 50 000's gap: row 50 000 has ended, row 50 001 starts at 50 001·224.
var offset = 50_000 * 224.0 + 210;
var (first, last) = layout.VisibleRange(offset, 600);
Assert.Equal(50_001 * 5, first);
// Bottom edge at offset + 600 = 50 000·224 + 810 → rows up to 50 003 (starts at +672) are visible.
Assert.Equal(50_004 * 5 - 1, last);
var (cachedFirst, cachedLast) = layout.VisibleRange(offset, 600, cacheRows: 1);
Assert.Equal(first - 5, cachedFirst);
Assert.Equal(last + 5, cachedLast);
}
[Test]
public void VisibleRangeExcludesRowStartingAtBottomEdge()
{
var layout = new WrapLayout(100, 1252, 236, 208, 16);
var (first, last) = layout.VisibleRange(0, 224);
Assert.Equal(0, first);
Assert.Equal(4, last);
}
[Test]
public void VisibleRangeClampsToLastPartialRow()
{
var layout = new WrapLayout(12, 1252, 236, 208, 16);
var (first, last) = layout.VisibleRange(0, 10_000, cacheRows: 2);
Assert.Equal(0, first);
Assert.Equal(11, last);
Assert.Equal((0, -1), new WrapLayout(0, 1252, 236, 208, 16).VisibleRange(0, 500));
}
[Test]
public void OffsetToRevealScrollsTheLeastAmount()
{
var layout = new WrapLayout(100, 1252, 236, 208, 16);
// Row 3 spans [672, 880): below a viewport [0, 600) → bottom-aligned.
Assert.Approximately(880 - 600, layout.OffsetToReveal(15, 0, 600), 1e-9);
// Already visible → unchanged.
Assert.Approximately(300, layout.OffsetToReveal(15, 300, 600), 1e-9);
// Above the viewport → top-aligned.
Assert.Approximately(224, layout.OffsetToReveal(5, 1000, 600), 1e-9);
// Taller than the viewport → top-aligned.
Assert.Approximately(672, WrapLayout.OffsetToReveal(672, 208, 0, 100), 1e-9);
}
[Test]
public void ClampOffsetKeepsViewportInsideExtent()
{
var layout = new WrapLayout(10, 1252, 236, 208, 16);
Assert.Approximately(432 - 300, layout.ClampOffset(5000, 300), 1e-9);
Assert.Approximately(0, layout.ClampOffset(-20, 300), 1e-9);
Assert.Approximately(0, layout.ClampOffset(50, 1000), 1e-9);
}
[Test]
public void JustifySpreadsLeftoverWidthOverGaps()
{
var layout = new WrapLayout(10, 1300, 236, 208, 16, justify: true);
Assert.Equal(5, layout.Columns);
Assert.Approximately(1300, layout.LeftOf(4) + 236, 1e-9);
Assert.Approximately(1300, layout.ExtentWidth, 1e-9);
}
[Theory]
[Case(7, WrapStep.Left, 6)]
[Case(5, WrapStep.Left, 4)]
[Case(0, WrapStep.Left, 0)]
[Case(4, WrapStep.Right, 5)]
[Case(11, WrapStep.Right, 11)]
[Case(7, WrapStep.Up, 2)]
[Case(2, WrapStep.Up, 2)]
[Case(2, WrapStep.Down, 7)]
[Case(9, WrapStep.Down, 11)]
[Case(11, WrapStep.Down, 11)]
[Case(7, WrapStep.First, 0)]
[Case(7, WrapStep.Last, 11)]
public void KeyboardStepsFollowReadingOrderAndColumns(int from, WrapStep step, int expected)
{
// 12 items in rows of 5: 0–4, 5–9, 10–11.
var layout = new WrapLayout(12, 1252, 236, 208, 16);
Assert.Equal(expected, layout.Navigate(from, step, pageRows: 2));
}
[Test]
public void PageStepsMoveWholeViewportRowsInTheSameColumn()
{
var layout = new WrapLayout(1000, 1252, 236, 208, 16);
var pageRows = layout.PageRows(700);
Assert.Equal(3, pageRows);
Assert.Equal(2 + 3 * 5, layout.Navigate(2, WrapStep.PageDown, pageRows));
Assert.Equal(2, layout.Navigate(2 + 3 * 5, WrapStep.PageUp, pageRows));
Assert.Equal(3, layout.Navigate(8, WrapStep.PageUp, pageRows));
// From row 198 a page down is clamped to the last row, same column.
Assert.Equal(999, layout.Navigate(994, WrapStep.PageDown, pageRows));
Assert.Equal(-1, new WrapLayout(0, 1252, 236, 208, 16).Navigate(0, WrapStep.Down, 1));
}
}