diff --git a/src/Titano.Ui/Visuals/CurveMath.cs b/src/Titano.Ui/Visuals/CurveMath.cs
new file mode 100644
index 00000000..846ce462
--- /dev/null
+++ b/src/Titano.Ui/Visuals/CurveMath.cs
@@ -0,0 +1,77 @@
+namespace Titano.Ui.Visuals;
+
+///
+/// Editing rules of in normalised [0, 1]² space: control points stay ordered by X with
+/// a minimum gap, optionally with the end points pinned to X = 0 and X = 1 (time remap).
+///
+public static class CurveMath
+{
+ /// Default minimum X distance between two control points.
+ public const double DefaultMinGap = 0.001;
+
+ ///
+ /// X the point may take when dragged to : strictly between its
+ /// neighbours (by at least ), inside [0, 1], and fixed at 0 or 1 for the end points
+ /// when .
+ ///
+ public static double ConstrainX(ReadOnlySpan xs, int index, double proposedX, double minGap, bool pinEnds)
+ {
+ var n = xs.Length;
+ if (index < 0 || index >= n) throw new ArgumentOutOfRangeException(nameof(index));
+ if (pinEnds && n > 1)
+ {
+ if (index == 0) return 0;
+ if (index == n - 1) return 1;
+ }
+ var gap = Math.Max(0, minGap);
+ var low = index > 0 ? xs[index - 1] + gap : 0;
+ var high = index < n - 1 ? xs[index + 1] - gap : 1;
+ low = Math.Max(0, low);
+ high = Math.Min(1, high);
+ if (low > high) return Math.Clamp((low + high) / 2, 0, 1);
+ return Math.Clamp(double.IsNaN(proposedX) ? xs[index] : proposedX, low, high);
+ }
+
+ /// Clamps a Y value to [0, 1].
+ public static double ConstrainY(double y) => double.IsNaN(y) ? 0 : Math.Clamp(y, 0, 1);
+
+ ///
+ /// Index at which a new point at keeps ascending, or −1 when it would
+ /// sit closer than to an existing point, outside [0, 1], or outside the pinned ends.
+ ///
+ public static int InsertionIndex(ReadOnlySpan xs, double x, double minGap, bool pinEnds)
+ {
+ if (double.IsNaN(x) || x < 0 || x > 1) return -1;
+ var gap = Math.Max(0, minGap);
+ var index = 0;
+ while (index < xs.Length && xs[index] < x) index++;
+ if (index > 0 && x - xs[index - 1] < gap) return -1;
+ if (index < xs.Length && xs[index] - x < gap) return -1;
+ if (pinEnds && xs.Length >= 2 && (index == 0 || index == xs.Length)) return -1;
+ return index;
+ }
+
+ /// Whether point may be deleted: two points always remain and pinned ends stay.
+ public static bool CanRemove(int count, int index, bool pinEnds) =>
+ count > 2 && index >= 0 && index < count && (!pinEnds || (index > 0 && index < count - 1));
+
+ /// Index of the point nearest to (, ) within , or −1; coordinates in one space.
+ public static int HitTest(ReadOnlySpan xs, ReadOnlySpan ys, double x, double y, double radius)
+ {
+ var best = -1;
+ var bestDistance = radius * radius;
+ var n = Math.Min(xs.Length, ys.Length);
+ for (var i = 0; i < n; i++)
+ {
+ var dx = xs[i] - x;
+ var dy = ys[i] - y;
+ var d = dx * dx + dy * dy;
+ if (d <= bestDistance)
+ {
+ bestDistance = d;
+ best = i;
+ }
+ }
+ return best;
+ }
+}
diff --git a/src/Titano.Ui/Visuals/LruCache.cs b/src/Titano.Ui/Visuals/LruCache.cs
new file mode 100644
index 00000000..49d43d35
--- /dev/null
+++ b/src/Titano.Ui/Visuals/LruCache.cs
@@ -0,0 +1,81 @@
+namespace Titano.Ui.Visuals;
+
+/// Fixed-capacity map that evicts the least recently used entry (decoded thumbnails).
+public sealed class LruCache
+ where TKey : notnull
+{
+ private readonly Dictionary>> _map;
+ private readonly LinkedList> _order = new();
+ private int _capacity;
+
+ public LruCache(int capacity)
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
+ _capacity = capacity;
+ _map = new Dictionary>>(capacity);
+ }
+
+ public int Count => _map.Count;
+
+ /// Maximum entries; lowering it evicts the oldest entries at once.
+ public int Capacity
+ {
+ get => _capacity;
+ set
+ {
+ ArgumentOutOfRangeException.ThrowIfLessThan(value, 1);
+ _capacity = value;
+ Trim();
+ }
+ }
+
+ /// Looks up and marks it as the most recently used.
+ public bool TryGet(TKey key, out TValue value)
+ {
+ if (_map.TryGetValue(key, out var node))
+ {
+ _order.Remove(node);
+ _order.AddFirst(node);
+ value = node.Value.Value;
+ return true;
+ }
+ value = default!;
+ return false;
+ }
+
+ /// Inserts or replaces as the most recently used entry.
+ public void Set(TKey key, TValue value)
+ {
+ if (_map.TryGetValue(key, out var node))
+ {
+ _order.Remove(node);
+ node.Value = new KeyValuePair(key, value);
+ _order.AddFirst(node);
+ return;
+ }
+ _map[key] = _order.AddFirst(new KeyValuePair(key, value));
+ Trim();
+ }
+
+ public bool Remove(TKey key)
+ {
+ if (!_map.Remove(key, out var node)) return false;
+ _order.Remove(node);
+ return true;
+ }
+
+ public void Clear()
+ {
+ _map.Clear();
+ _order.Clear();
+ }
+
+ private void Trim()
+ {
+ while (_map.Count > _capacity && _order.Last is { } oldest)
+ {
+ _order.RemoveLast();
+ _map.Remove(oldest.Value.Key);
+ }
+ }
+}
diff --git a/src/Titano.Ui/Visuals/MinMaxDecimator.cs b/src/Titano.Ui/Visuals/MinMaxDecimator.cs
new file mode 100644
index 00000000..4152d027
--- /dev/null
+++ b/src/Titano.Ui/Visuals/MinMaxDecimator.cs
@@ -0,0 +1,80 @@
+namespace Titano.Ui.Visuals;
+
+///
+/// Reduces a long series to at most two samples per pixel column (its minimum and maximum, in index order) so a
+/// line over 100k+ points draws in time proportional to the plot width while every spike stays visible.
+///
+public static class MinMaxDecimator
+{
+ /// Index written to the output where the line must break (a run without finite samples).
+ public const int Gap = -1;
+
+ /// Output capacity needed for samples over columns.
+ public static int Capacity(int count, int columns) => Math.Max(0, Math.Min(count, 2 * Math.Max(1, columns)));
+
+ ///
+ /// Writes ascending sample indices to draw into and returns how many were written.
+ /// When the series has at most two samples per column every finite sample is kept; otherwise each column
+ /// keeps the indices of its minimum and maximum. Non-finite samples are skipped and a run of them (or a
+ /// column without any finite sample) becomes one entry.
+ ///
+ public static int Decimate(ReadOnlySpan values, int columns, Span output)
+ {
+ columns = Math.Max(1, columns);
+ var n = values.Length;
+ if (output.Length < Capacity(n, columns))
+ throw new ArgumentException("Output span is smaller than Capacity(count, columns).", nameof(output));
+
+ var written = 0;
+ if (n <= 2 * columns)
+ {
+ for (var i = 0; i < n; i++)
+ {
+ if (double.IsFinite(values[i])) output[written++] = i;
+ else if (written > 0 && output[written - 1] != Gap) output[written++] = Gap;
+ }
+ return Trim(output, written);
+ }
+
+ for (var c = 0; c < columns; c++)
+ {
+ var start = (int)((long)c * n / columns);
+ var end = (int)((long)(c + 1) * n / columns);
+ int minIndex = -1, maxIndex = -1;
+ double min = double.PositiveInfinity, max = double.NegativeInfinity;
+ for (var i = start; i < end; i++)
+ {
+ var v = values[i];
+ if (!double.IsFinite(v)) continue;
+ if (v < min)
+ {
+ min = v;
+ minIndex = i;
+ }
+ if (v > max)
+ {
+ max = v;
+ maxIndex = i;
+ }
+ }
+ if (minIndex < 0)
+ {
+ if (written > 0 && output[written - 1] != Gap) output[written++] = Gap;
+ continue;
+ }
+ if (minIndex == maxIndex)
+ {
+ output[written++] = minIndex;
+ }
+ else
+ {
+ output[written++] = Math.Min(minIndex, maxIndex);
+ output[written++] = Math.Max(minIndex, maxIndex);
+ }
+ }
+ return Trim(output, written);
+ }
+
+ /// A trailing gap carries no information.
+ private static int Trim(Span output, int written) => written > 0 && output[written - 1] == Gap ? written - 1 : written;
+}
diff --git a/src/Titano.Ui/Visuals/NiceScale.cs b/src/Titano.Ui/Visuals/NiceScale.cs
new file mode 100644
index 00000000..64c0648f
--- /dev/null
+++ b/src/Titano.Ui/Visuals/NiceScale.cs
@@ -0,0 +1,91 @@
+namespace Titano.Ui.Visuals;
+
+/// Evenly spaced axis ticks: , + , … up to .
+public readonly record struct AxisTicks(double First, double Last, double Step)
+{
+ /// Number of ticks (0 when the scale is empty).
+ public int Count => Step > 0 && Last >= First ? (int)Math.Round((Last - First) / Step) + 1 : 0;
+
+ /// Value of tick , computed from integer multiples of the step to limit drift.
+ public double this[int i] => (Math.Round(First / Step) + i) * Step;
+}
+
+/// "Nice" numbers for axes (1, 2, 5 × 10ⁿ), padded data ranges and tick placement.
+public static class NiceScale
+{
+ ///
+ /// Heckbert's nice number: the 1/2/5 × 10ⁿ value closest to when
+ /// , otherwise the smallest one that is ≥ .
+ ///
+ public static double NiceNumber(double value, bool round)
+ {
+ if (!double.IsFinite(value) || value <= 0) return 1;
+ var exponent = Math.Floor(Math.Log10(value));
+ var magnitude = Math.Pow(10, exponent);
+ var fraction = value / magnitude;
+ double nice;
+ if (round)
+ nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10;
+ else
+ nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
+ return nice * magnitude;
+ }
+
+ /// Nice tick step giving at most (≥ 2) ticks inside [min, max].
+ public static double Step(double min, double max, int maxTicks)
+ {
+ var span = max - min;
+ if (!double.IsFinite(span) || span <= 0) return 1;
+ var intervals = Math.Max(2, maxTicks) - 1;
+ var step = NiceNumber(NiceNumber(span, false) / intervals, true);
+ // Rounding the step down can overshoot the budget (e.g. 1/7 → 0.1); climb the 1-2-5 ladder until it fits.
+ while (span / step > intervals + 1e-9) step = NextNice(step);
+ return step;
+ }
+
+ /// Ticks inside [min, max] (none outside), for gridlines over a fixed data range.
+ public static AxisTicks Inner(double min, double max, int maxTicks)
+ {
+ if (!double.IsFinite(min) || !double.IsFinite(max) || max <= min) return default;
+ var step = Step(min, max, maxTicks);
+ var first = Math.Ceiling(min / step - 1e-9) * step;
+ var last = Math.Floor(max / step + 1e-9) * step;
+ return last < first ? default : new AxisTicks(first, last, step);
+ }
+
+ /// Range widened outward to whole steps, for axes that should start and end on a tick (e.g. bars from zero).
+ public static AxisTicks Outer(double min, double max, int maxTicks)
+ {
+ if (!double.IsFinite(min) || !double.IsFinite(max)) return default;
+ if (max <= min) (min, max) = Expand(min);
+ var step = Step(min, max, maxTicks);
+ return new AxisTicks(Math.Floor(min / step + 1e-9) * step, Math.Ceiling(max / step - 1e-9) * step, step);
+ }
+
+ ///
+ /// Data range padded by of its span on both sides; a flat range is widened around
+ /// its value so the line sits in the middle.
+ ///
+ public static (double Min, double Max) Pad(double min, double max, double fraction)
+ {
+ if (!double.IsFinite(min) || !double.IsFinite(max)) return (0, 1);
+ if (max < min) (min, max) = (max, min);
+ if (max == min) return Expand(min);
+ var pad = (max - min) * Math.Max(0, fraction);
+ return (min - pad, max + pad);
+ }
+
+ /// The next value of the 1-2-5 ladder above .
+ private static double NextNice(double step)
+ {
+ var magnitude = Math.Pow(10, Math.Floor(Math.Log10(step)));
+ var fraction = step / magnitude;
+ return (fraction < 1.5 ? 2 : fraction < 3.5 ? 5 : 10) * magnitude;
+ }
+
+ private static (double Min, double Max) Expand(double v)
+ {
+ var half = v == 0 ? 1 : Math.Abs(v) * 0.1;
+ return (v - half, v + half);
+ }
+}
diff --git a/src/Titano.Ui/Visuals/PixelGrid.cs b/src/Titano.Ui/Visuals/PixelGrid.cs
new file mode 100644
index 00000000..99ce0114
--- /dev/null
+++ b/src/Titano.Ui/Visuals/PixelGrid.cs
@@ -0,0 +1,32 @@
+namespace Titano.Ui.Visuals;
+
+/// Device-pixel alignment for drawn lines and edges (scale = device pixels per DIP).
+public static class PixelGrid
+{
+ /// Rounds to the nearest device-pixel boundary.
+ public static double Snap(double value, double scale)
+ {
+ if (!(scale > 0) || !double.IsFinite(value)) return value;
+ return Math.Round(value * scale) / scale;
+ }
+
+ ///
+ /// Position of the centre of a line DIPs wide drawn at so it
+ /// covers whole device pixels: odd pixel widths sit on pixel centres, even ones on pixel boundaries.
+ ///
+ public static double SnapLine(double value, double thickness, double scale)
+ {
+ if (!(scale > 0) || !double.IsFinite(value)) return value;
+ var pixels = Math.Max(1, Math.Round(thickness * scale));
+ var device = value * scale;
+ var snapped = pixels % 2 == 1 ? Math.Floor(device) + 0.5 : Math.Round(device);
+ return snapped / scale;
+ }
+
+ /// Line thickness in DIPs that renders as whole device pixels (at least one).
+ public static double SnapThickness(double thickness, double scale)
+ {
+ if (!(scale > 0)) return thickness;
+ return Math.Max(1, Math.Round(thickness * scale)) / scale;
+ }
+}
diff --git a/src/Titano.Ui/Visuals/StripLayout.cs b/src/Titano.Ui/Visuals/StripLayout.cs
new file mode 100644
index 00000000..80d554d1
--- /dev/null
+++ b/src/Titano.Ui/Visuals/StripLayout.cs
@@ -0,0 +1,123 @@
+namespace Titano.Ui.Visuals;
+
+///
+/// Cells of a filmstrip: as many cells of about the target width as fit, each standing for a contiguous run of
+/// frames and showing the frame in the middle of its run; X positions map continuously to frames for seeking.
+///
+public readonly struct StripLayout
+{
+ public StripLayout(double width, double targetCellWidth, double gap, int frameCount)
+ {
+ Width = double.IsFinite(width) ? Math.Max(0, width) : 0;
+ Gap = double.IsFinite(gap) ? Math.Max(0, gap) : 0;
+ FrameCount = Math.Max(0, frameCount);
+ var target = double.IsFinite(targetCellWidth) && targetCellWidth > 1 ? targetCellWidth : 1;
+ CellCount = FrameCount == 0 || Width <= 0
+ ? 0
+ : (int)Math.Min(FrameCount, Math.Max(1, Math.Floor((Width + Gap) / (target + Gap))));
+ CellWidth = CellCount == 0 ? 0 : Math.Max(0, (Width - Gap * (CellCount - 1)) / CellCount);
+ }
+
+ public double Width { get; }
+
+ public double Gap { get; }
+
+ public int FrameCount { get; }
+
+ public int CellCount { get; }
+
+ public double CellWidth { get; }
+
+ public double CellLeft(int cell) => cell * (CellWidth + Gap);
+
+ /// Cell whose run contains .
+ public int CellForFrame(int frame)
+ {
+ if (CellCount == 0) return -1;
+ return (int)((long)Math.Clamp(frame, 0, FrameCount - 1) * CellCount / FrameCount);
+ }
+
+ /// Frame shown by : the middle of the frames that map to it.
+ public int FrameForCell(int cell)
+ {
+ if (CellCount == 0) return -1;
+ cell = Math.Clamp(cell, 0, CellCount - 1);
+ var first = FirstFrame(cell);
+ var last = FirstFrame(cell + 1) - 1;
+ return first + (last - first) / 2;
+ }
+
+ /// Frame under (continuous across cells and gaps), clamped to the sequence.
+ public int FrameAt(double x)
+ {
+ if (FrameCount == 0 || Width <= 0) return -1;
+ return (int)Math.Clamp(Math.Floor(x / Width * FrameCount), 0, FrameCount - 1);
+ }
+
+ /// Centre X of on the continuous frame axis.
+ public double XForFrame(double frame) => FrameCount == 0 ? 0 : (frame + 0.5) / FrameCount * Width;
+
+ /// Smallest frame f with CellForFrame(f) = cell, i.e. ⌈cell · frames / cells⌉.
+ private int FirstFrame(int cell) => (int)(((long)cell * FrameCount + CellCount - 1) / CellCount);
+}
+
+/// A grid of square cells with gaps (heatmap): cell origins and hit testing that excludes the gaps.
+public readonly struct CellGridLayout
+{
+ public CellGridLayout(double left, double top, int rows, int columns, double cellSize, double gap)
+ {
+ Left = left;
+ Top = top;
+ Rows = Math.Max(0, rows);
+ Columns = Math.Max(0, columns);
+ CellSize = Math.Max(0, cellSize);
+ Gap = Math.Max(0, gap);
+ }
+
+ public double Left { get; }
+
+ public double Top { get; }
+
+ public int Rows { get; }
+
+ public int Columns { get; }
+
+ public double CellSize { get; }
+
+ public double Gap { get; }
+
+ public double Pitch => CellSize + Gap;
+
+ public double Width => Columns == 0 ? 0 : Columns * Pitch - Gap;
+
+ public double Height => Rows == 0 ? 0 : Rows * Pitch - Gap;
+
+ public (double X, double Y) CellOrigin(int row, int column) => (Left + column * Pitch, Top + row * Pitch);
+
+ /// Largest square cell (≤ ) letting the grid fit in width × height.
+ public static double FitCellSize(double width, double height, int rows, int columns, double gap, double maxCell)
+ {
+ if (rows <= 0 || columns <= 0) return 0;
+ var byWidth = double.IsFinite(width) ? (width - gap * (columns - 1)) / columns : double.PositiveInfinity;
+ var byHeight = double.IsFinite(height) ? (height - gap * (rows - 1)) / rows : double.PositiveInfinity;
+ var size = Math.Min(Math.Min(byWidth, byHeight), maxCell);
+ return double.IsFinite(size) ? Math.Max(0, size) : Math.Max(0, maxCell);
+ }
+
+ /// Cell under (, ); false over gaps and outside the grid.
+ public bool TryHit(double x, double y, out int row, out int column)
+ {
+ row = column = -1;
+ if (Rows == 0 || Columns == 0 || CellSize <= 0) return false;
+ var dx = x - Left;
+ var dy = y - Top;
+ if (dx < 0 || dy < 0) return false;
+ var c = (int)Math.Floor(dx / Pitch);
+ var r = (int)Math.Floor(dy / Pitch);
+ if (c >= Columns || r >= Rows) return false;
+ if (dx - c * Pitch > CellSize || dy - r * Pitch > CellSize) return false;
+ row = r;
+ column = c;
+ return true;
+ }
+}
diff --git a/src/Titano.Ui/Visuals/ViewportMath.cs b/src/Titano.Ui/Visuals/ViewportMath.cs
new file mode 100644
index 00000000..3a5c67f6
--- /dev/null
+++ b/src/Titano.Ui/Visuals/ViewportMath.cs
@@ -0,0 +1,70 @@
+namespace Titano.Ui.Visuals;
+
+/// Uniform scale and translation from image pixels to view units: view = image × + offset.
+public readonly record struct ViewTransform(double Scale, double OffsetX, double OffsetY)
+{
+ public (double X, double Y) ToView(double x, double y) => (x * Scale + OffsetX, y * Scale + OffsetY);
+
+ public (double X, double Y) ToImage(double x, double y) => ((x - OffsetX) / Scale, (y - OffsetY) / Scale);
+}
+
+/// Zoom and pan math of the preview: fit, zoom around a fixed point, panning limits and pixel alignment.
+public static class ViewportMath
+{
+ /// Largest scale at which the whole image fits the view (0 when either is empty).
+ public static double FitScale(double imageWidth, double imageHeight, double viewWidth, double viewHeight)
+ {
+ if (!(imageWidth > 0) || !(imageHeight > 0) || !(viewWidth > 0) || !(viewHeight > 0)) return 0;
+ return Math.Min(viewWidth / imageWidth, viewHeight / imageHeight);
+ }
+
+ /// The image at , centred in the view.
+ public static ViewTransform Centered(double scale, double imageWidth, double imageHeight, double viewWidth, double viewHeight) =>
+ new(scale, (viewWidth - imageWidth * scale) / 2, (viewHeight - imageHeight * scale) / 2);
+
+ ///
+ /// Changes the scale to keeping the image point under (,
+ /// ) where it is.
+ ///
+ public static ViewTransform ZoomAt(ViewTransform t, double scale, double viewX, double viewY)
+ {
+ if (!(t.Scale > 0) || !(scale > 0)) return t;
+ var k = scale / t.Scale;
+ return new ViewTransform(scale, viewX - (viewX - t.OffsetX) * k, viewY - (viewY - t.OffsetY) * k);
+ }
+
+ ///
+ /// Keeps the image covering the view on each axis where it is larger than the view, and centred on each axis
+ /// where it is smaller, so panning can never lose the picture.
+ ///
+ public static ViewTransform Clamp(ViewTransform t, double imageWidth, double imageHeight, double viewWidth, double viewHeight) =>
+ t with
+ {
+ OffsetX = ClampAxis(t.OffsetX, imageWidth * t.Scale, viewWidth),
+ OffsetY = ClampAxis(t.OffsetY, imageHeight * t.Scale, viewHeight),
+ };
+
+ /// Moves the offset by (, ) view units.
+ public static ViewTransform Pan(ViewTransform t, double dx, double dy) => t with { OffsetX = t.OffsetX + dx, OffsetY = t.OffsetY + dy };
+
+ /// Rounds the offset to whole device pixels ( device pixels per view unit) so 1:1 shows raw pixels.
+ public static ViewTransform SnapOffset(ViewTransform t, double pixelsPerUnit)
+ {
+ if (!(pixelsPerUnit > 0)) return t;
+ return t with
+ {
+ OffsetX = Math.Round(t.OffsetX * pixelsPerUnit) / pixelsPerUnit,
+ OffsetY = Math.Round(t.OffsetY * pixelsPerUnit) / pixelsPerUnit,
+ };
+ }
+
+ /// Next zoom level for a wheel movement of (positive = in), by a factor of 1.25 per notch.
+ public static double WheelZoom(double scale, double notches, double minScale, double maxScale) =>
+ Math.Clamp(scale * Math.Pow(1.25, notches), minScale, maxScale);
+
+ private static double ClampAxis(double offset, double size, double view)
+ {
+ if (size <= view) return (view - size) / 2;
+ return Math.Clamp(offset, view - size, 0);
+ }
+}
diff --git a/src/Titano.Ui/Visuals/WrapLayout.cs b/src/Titano.Ui/Visuals/WrapLayout.cs
new file mode 100644
index 00000000..52a26cab
--- /dev/null
+++ b/src/Titano.Ui/Visuals/WrapLayout.cs
@@ -0,0 +1,180 @@
+namespace Titano.Ui.Visuals;
+
+/// Keyboard steps inside a wrapped grid.
+public enum WrapStep
+{
+ Left,
+ Right,
+ Up,
+ Down,
+ PageUp,
+ PageDown,
+ First,
+ Last,
+}
+
+///
+/// Geometry of a grid of fixed-size items wrapped into rows: O(1) mapping between item index, row, column and
+/// pixel offset, visible ranges, minimal scroll to reveal an item and keyboard navigation targets.
+///
+public readonly struct WrapLayout
+{
+ private const double Epsilon = 1e-9;
+
+ /// Number of items.
+ /// Width available for the rows; infinite puts every item on one row.
+ /// Slot width of one item.
+ /// Slot height of one item.
+ /// Gap between columns and between rows.
+ /// Spread the leftover width over the column gaps so the grid spans the viewport.
+ public WrapLayout(int itemCount, double viewportWidth, double itemWidth, double itemHeight, double spacing, bool justify = false)
+ {
+ ItemCount = Math.Max(0, itemCount);
+ ItemWidth = Positive(itemWidth);
+ ItemHeight = Positive(itemHeight);
+ Spacing = double.IsFinite(spacing) ? Math.Max(0, spacing) : 0;
+ var finiteWidth = double.IsFinite(viewportWidth);
+ Columns = finiteWidth ? ColumnsFor(viewportWidth, ItemWidth, Spacing) : Math.Max(1, ItemCount);
+ Rows = ItemCount == 0 ? 0 : (ItemCount + Columns - 1) / Columns;
+ RowPitch = ItemHeight + Spacing;
+ ColumnPitch = justify && finiteWidth && Columns > 1
+ ? Math.Max(ItemWidth + Spacing, (viewportWidth - ItemWidth) / (Columns - 1))
+ : ItemWidth + Spacing;
+ }
+
+ public int ItemCount { get; }
+
+ public double ItemWidth { get; }
+
+ public double ItemHeight { get; }
+
+ public double Spacing { get; }
+
+ public int Columns { get; }
+
+ public int Rows { get; }
+
+ /// Distance between the tops of two consecutive rows.
+ public double RowPitch { get; }
+
+ /// Distance between the left edges of two consecutive columns.
+ public double ColumnPitch { get; }
+
+ /// Height of all rows, without a trailing gap.
+ public double ExtentHeight => Rows == 0 ? 0 : Rows * RowPitch - Spacing;
+
+ /// Width spanned by the columns, without a trailing gap.
+ public double ExtentWidth => ItemCount == 0 ? 0 : (Math.Min(Columns, ItemCount) - 1) * ColumnPitch + ItemWidth;
+
+ /// Columns that fit in (at least one).
+ public static int ColumnsFor(double width, double itemWidth, double spacing)
+ {
+ if (!double.IsFinite(width) || width <= 0) return 1;
+ var pitch = Positive(itemWidth) + Math.Max(0, spacing);
+ return Math.Max(1, (int)Math.Floor((width + Math.Max(0, spacing)) / pitch + Epsilon));
+ }
+
+ public int RowOf(int index) => index / Columns;
+
+ public int ColumnOf(int index) => index % Columns;
+
+ public double LeftOf(int index) => ColumnOf(index) * ColumnPitch;
+
+ public double TopOf(int index) => RowOf(index) * RowPitch;
+
+ /// Row whose slot band [top, top + pitch) contains , clamped to the rows.
+ public int RowAt(double y)
+ {
+ if (Rows == 0) return -1;
+ if (!(y > 0)) return 0;
+ return (int)Math.Min(Rows - 1, Math.Floor(y / RowPitch));
+ }
+
+ ///
+ /// First and last item index whose slot intersects [offset, offset + viewportHeight), widened by
+ /// rows on each side. Returns (0, −1) when nothing is visible.
+ ///
+ public (int First, int Last) VisibleRange(double offset, double viewportHeight, int cacheRows = 0)
+ {
+ if (Rows == 0 || !(viewportHeight > 0)) return (0, -1);
+ if (double.IsInfinity(viewportHeight)) return (0, ItemCount - 1);
+ // Row r occupies [r·pitch, r·pitch + itemHeight): visible when it starts before the bottom edge and ends after the top edge.
+ var firstRow = (long)Math.Floor((offset - ItemHeight) / RowPitch + Epsilon) + 1;
+ var lastRow = (long)Math.Ceiling((offset + viewportHeight) / RowPitch - Epsilon) - 1;
+ firstRow = Math.Max(0, firstRow - Math.Max(0, cacheRows));
+ lastRow = Math.Min(Rows - 1, lastRow + Math.Max(0, cacheRows));
+ if (firstRow > lastRow) return (0, -1);
+ var first = (int)(firstRow * Columns);
+ var last = (int)Math.Min(ItemCount - 1, (lastRow + 1) * Columns - 1);
+ return (first, last);
+ }
+
+ /// Clamps a vertical offset to [0, extent − viewport].
+ public double ClampOffset(double offset, double viewportHeight)
+ {
+ var max = Math.Max(0, ExtentHeight - Math.Max(0, viewportHeight));
+ return double.IsNaN(offset) ? 0 : Math.Clamp(offset, 0, max);
+ }
+
+ /// Smallest change of that shows [top, top + height) fully; a band taller than the viewport is aligned to its top.
+ public static double OffsetToReveal(double top, double height, double offset, double viewportHeight)
+ {
+ if (top < offset || height >= viewportHeight) return top;
+ if (top + height > offset + viewportHeight) return top + height - viewportHeight;
+ return offset;
+ }
+
+ /// Clamped offset that shows item fully with the least scrolling.
+ public double OffsetToReveal(int index, double offset, double viewportHeight)
+ {
+ if (index < 0 || index >= ItemCount) return ClampOffset(offset, viewportHeight);
+ return ClampOffset(OffsetToReveal(TopOf(index), ItemHeight, offset, viewportHeight), viewportHeight);
+ }
+
+ /// Whole rows that fit in the viewport (at least one): the PageUp/PageDown step.
+ public int PageRows(double viewportHeight) =>
+ double.IsFinite(viewportHeight) ? Math.Max(1, (int)Math.Floor((viewportHeight + Spacing) / RowPitch + Epsilon)) : Math.Max(1, Rows);
+
+ ///
+ /// Target of a keyboard step from . Left/Right walk the reading order (wrapping across
+ /// rows); Up/Down keep the column; Down from a row above a shorter last row lands on the last item; page steps
+ /// move rows in the same column. Returns −1 when there are no items.
+ ///
+ public int Navigate(int index, WrapStep step, int pageRows)
+ {
+ if (ItemCount == 0) return -1;
+ index = Math.Clamp(index, 0, ItemCount - 1);
+ var last = ItemCount - 1;
+ var page = Math.Max(1, pageRows);
+ switch (step)
+ {
+ case WrapStep.Left:
+ return Math.Max(0, index - 1);
+ case WrapStep.Right:
+ return Math.Min(last, index + 1);
+ case WrapStep.Up:
+ return index >= Columns ? index - Columns : index;
+ case WrapStep.Down:
+ if (index + Columns <= last) return index + Columns;
+ return RowOf(index) < Rows - 1 ? last : index;
+ case WrapStep.PageUp:
+ {
+ var row = Math.Max(0, RowOf(index) - page);
+ return row * Columns + ColumnOf(index);
+ }
+ case WrapStep.PageDown:
+ {
+ var row = Math.Min(Rows - 1, RowOf(index) + page);
+ return Math.Min(last, row * Columns + ColumnOf(index));
+ }
+ case WrapStep.First:
+ return 0;
+ case WrapStep.Last:
+ return last;
+ default:
+ return index;
+ }
+ }
+
+ private static double Positive(double v) => double.IsFinite(v) && v > 0 ? v : 1;
+}
diff --git a/tests/Titano.App.Tests/Visuals/CurveMathTests.cs b/tests/Titano.App.Tests/Visuals/CurveMathTests.cs
new file mode 100644
index 00000000..ee5b9abf
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/CurveMathTests.cs
@@ -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));
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/LruCacheTests.cs b/tests/Titano.App.Tests/Visuals/LruCacheTests.cs
new file mode 100644
index 00000000..21186f4f
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/LruCacheTests.cs
@@ -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(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(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(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(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(() => _ = new LruCache(0));
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs b/tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs
new file mode 100644
index 00000000..ba7df1d9
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/MinMaxDecimatorTests.cs
@@ -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(() => 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;
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/NiceScaleTests.cs b/tests/Titano.App.Tests/Visuals/NiceScaleTests.cs
new file mode 100644
index 00000000..cc83c820
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/NiceScaleTests.cs
@@ -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);
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/PixelGridTests.cs b/tests/Titano.App.Tests/Visuals/PixelGridTests.cs
new file mode 100644
index 00000000..871fbeb1
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/PixelGridTests.cs
@@ -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);
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/StripLayoutTests.cs b/tests/Titano.App.Tests/Visuals/StripLayoutTests.cs
new file mode 100644
index 00000000..030a191a
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/StripLayoutTests.cs
@@ -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);
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/ViewportMathTests.cs b/tests/Titano.App.Tests/Visuals/ViewportMathTests.cs
new file mode 100644
index 00000000..cea6efe8
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/ViewportMathTests.cs
@@ -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);
+ }
+}
diff --git a/tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs b/tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs
new file mode 100644
index 00000000..2492e1e2
--- /dev/null
+++ b/tests/Titano.App.Tests/Visuals/WrapLayoutTests.cs
@@ -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));
+ }
+}