using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using Chronos.Core.Localization; using Chronos.Testing; using Chronos.Ui.Controls; using Chronos.Ui.Theming; using Chronos.Ui.Visuals; namespace Chronos.App.Tests.Visuals; /// /// 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. /// [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(); Host(card); 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(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, TestTiming.Budget(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); }); [Test] public void ListsKeepTheirFillWhenDisabled() => WpfHost.Run(() => { var surface = ColorOf("Brush.Surface"); foreach (var list in new[] { new ListBox(), new ListBox { Style = (Style)Application.Current.FindResource("ListBox.Cards") } }) { list.Background = (Brush)Application.Current.FindResource("Brush.Surface"); list.ItemsSource = new[] { "Harbour sunset" }; list.IsEnabled = false; var bitmap = Render(list, 200, 100); Assert.NotNull(VisualTreeHelper.GetChild(list, 0) as Border, "the theme's list frame"); Assert.True(Near(PixelAt(bitmap, 100, 95), surface, 1), "a disabled list keeps its fill instead of the system's white"); } // A list view keeps the system template, which carries the column headers. var view = new ListView { ItemsSource = new[] { "Harbour sunset" }, View = new GridView { Columns = { new GridViewColumn { Header = "Title" } } } }; Render(view, 200, 100); Assert.NotNull(FindChild(view), "the column header row"); }); [Test] public void ChartLabelsAreMutedAndMonthsWithoutDataTakeTheStrokeTone() => WpfHost.Run(() => { foreach (var theme in new[] { AppTheme.Dark, AppTheme.Light }) { ThemeManager.Apply(theme); var (muted, faint, stroke, card) = (ColorOf("Brush.TextMuted"), ColorOf("Brush.TextFaint"), ColorOf("Brush.Stroke"), ColorOf("Brush.Card")); // Zero values draw no bars: what remains is the labels. var bars = Covered(Render(new BarChart { Items = [new ChartItem("Canon EOS R6", 0), new ChartItem("Nikon Z 8", 0)], ShowValues = false }, 300, 60)); Assert.NotEmpty(bars); Assert.True(bars.All(c => Near(c, muted)), $"bar labels are TextMuted in {theme}, not TextFaint ({faint})"); var months = new[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" }; var empty = new ChartRow("2027", Enumerable.Repeat(double.NaN, 12).ToArray()); var heatmap = Covered(Render(new HeatmapStrip { Rows = [empty], ColumnLabels = months, ShowScale = false }, 400, 60)); Assert.Contains(heatmap, c => Near(c, stroke)); Assert.False(heatmap.Any(c => Near(c, card) && !Near(c, stroke)), $"months without data are not the card colour in {theme}"); Assert.True(heatmap.All(c => Near(c, stroke) || Near(c, muted)), $"heatmap labels are TextMuted in {theme}"); } ThemeManager.Apply(AppTheme.Dark); }); [Test] public void ChartsTakeTheHandAndTheKeyboardOnlyWhileSomethingHandlesActivation() => WpfHost.Run(() => { var items = new[] { new ChartItem("2025", 2), new ChartItem("2026", 1) }; var bars = new BarChart { Items = items }; var stacked = new StackedBar { Items = items }; var heatmap = new HeatmapStrip { Rows = [new ChartRow("2026", [1, 2, 3])], ColumnLabels = ["J", "F", "M"] }; ChartItemEventHandler handler = (_, _) => { }; var charts = new (DrawingElement Chart, Action Attach, Action Detach)[] { (bars, () => bars.ItemActivated += handler, () => bars.ItemActivated -= handler), (stacked, () => stacked.ItemActivated += handler, () => stacked.ItemActivated -= handler), (heatmap, () => heatmap.CellActivated += handler, () => heatmap.CellActivated -= handler), }; foreach (var (chart, attach, detach) in charts) { Render(chart, 300, 80); var name = chart.GetType().Name; Assert.False(ShowsHand(chart), $"{name}: no hand cursor while nothing handles a click"); Assert.False(chart.Focusable, $"{name}: no tab stop while nothing handles Enter"); attach(); Assert.True(ShowsHand(chart), $"{name}: the hand over an item once a handler is attached"); Assert.True(chart.Focusable, $"{name}: the keyboard reaches it once a handler is attached"); detach(); Assert.False(ShowsHand(chart), $"{name}: no hand once the handler is gone"); Assert.False(chart.Focusable, $"{name}: no tab stop once the handler is gone"); } }); [Test] public void TheKeyboardChoosesAndActivatesABar() => WpfHost.Run(() => { var bars = new BarChart { Items = [new ChartItem("2024", 3), new ChartItem("2025", 2), new ChartItem("2026", 1)] }; var host = new Border { Child = bars }; var window = new Window { Content = host, Width = 320, Height = 160, WindowStyle = WindowStyle.None, WindowStartupLocation = WindowStartupLocation.Manual, Left = -20000, Top = -20000, ShowActivated = false, ShowInTaskbar = false, }; window.Show(); try { window.UpdateLayout(); var bubbled = new List(); host.AddHandler(BarChart.ItemActivatedEvent, new ChartItemEventHandler((_, e) => bubbled.Add(e.Row))); Press(bars, Key.Enter); Assert.Empty(bubbled, "Enter does nothing while no handler is attached to the chart"); var rows = new List(); bars.ItemActivated += (_, e) => rows.Add(e.Row); Press(bars, Key.Down); Press(bars, Key.Down); Press(bars, Key.Down); Press(bars, Key.Enter); Press(bars, Key.Home); Press(bars, Key.Space); Assert.SequenceEqual([2, 0], rows, "Down stops at the last bar; Home goes back to the first"); Assert.Contains("2024", UIElementAutomationPeer.CreatePeerForElement(bars).GetItemStatus()); } finally { window.Close(); } }); [Test] public void CategoryBarsStartOnTheReadingSideWhileMonthsKeepTheirOrder() => WpfHost.Run(() => { var accent = ColorOf("Brush.Accent"); var culture = Loc.Culture; try { foreach (var (language, rightToLeft) in new[] { ("en", false), ("ar", true) }) { Loc.SetCulture(CultureInfo.GetCultureInfo(language)); // Rows 22 px apart: the short second bar (y 26–40) grows from the labels' side. var bars = Render(new BarChart { Items = [new ChartItem("A", 4), new ChartItem("B", 1)], ShowValues = false }, 300, 44); var (left, right) = Extent(bars, accent, 33); Assert.True(rightToLeft ? left > 150 : right < 150 && right > 0, $"{language}: the short bar spans {left}–{right}"); // The largest segment comes first, on the reading side. var stacked = Render(new StackedBar { Items = [new ChartItem("A", 3), new ChartItem("B", 1)], ShowLegend = false }, 300, 12); (left, right) = Extent(stacked, accent, 6); Assert.True(rightToLeft ? left > 60 && right >= 296 : left is >= 0 and <= 3 && right < 240, $"{language}: the first segment spans {left}–{right}"); // The full month (January) stays on the left: months are a time axis. var months = Render(new HeatmapStrip { Rows = [new ChartRow("2026", [5, 0, 0, 0])], ColumnLabels = ["1", "2", "3", "4"], ShowScale = false }, 300, 60); (left, right) = Extent(months, accent, 31); Assert.True(left > 0 && right < 150, $"{language}: January spans {left}–{right}"); } } finally { Loc.SetCulture(culture); } }); 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 { 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 Color ColorOf(string key) => ((SolidColorBrush)Application.Current.FindResource(key)).Color; private static Color PixelAt(BitmapSource bitmap, int x, int y) { var pixel = new byte[4]; bitmap.CopyPixels(new Int32Rect(x, y, 1, 1), pixel, 4, 0); return Color.FromArgb(pixel[3], pixel[2], pixel[1], pixel[0]); } /// The colours drawn at least two-thirds opaque, un-premultiplied: text edges keep the colour of their brush. private static List Covered(BitmapSource bitmap) { var stride = bitmap.PixelWidth * 4; var pixels = new byte[stride * bitmap.PixelHeight]; bitmap.CopyPixels(pixels, stride, 0); var colours = new List(); for (var i = 0; i < pixels.Length; i += 4) { var a = pixels[i + 3]; if (a < 170) continue; colours.Add(Color.FromRgb((byte)(pixels[i + 2] * 255 / a), (byte)(pixels[i + 1] * 255 / a), (byte)(pixels[i] * 255 / a))); } return colours; } private static bool Near(Color a, Color b, int tolerance = 12) => Math.Abs(a.R - b.R) <= tolerance && Math.Abs(a.G - b.G) <= tolerance && Math.Abs(a.B - b.B) <= tolerance; /// First and last x of row drawn in at full opacity; (−1, −1) when none. private static (int Left, int Right) Extent(BitmapSource bitmap, Color colour, int y) { var (left, right) = (-1, -1); for (var x = 0; x < bitmap.PixelWidth; x++) { var pixel = PixelAt(bitmap, x, y); if (pixel.A != 255 || !Near(pixel, colour, 2)) continue; if (left < 0) left = x; right = x; } return (left, right); } private static bool ShowsHand(DrawingElement chart) { for (var y = 0.0; y < chart.ActualHeight; y += 2) { for (var x = 0.0; x < chart.ActualWidth; x += 2) if (chart.CursorAt(new Point(x, y)) == Cursors.Hand) return true; } return false; } private static void Press(UIElement target, Key key) => target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent }); private static RenderTargetBitmap Render(FrameworkElement element, double width, double height) { var host = Host(element); host.Measure(new Size(width, height)); host.Arrange(new Rect(0, 0, width, height)); host.UpdateLayout(); var bitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32); bitmap.Render(host); return bitmap; } /// /// Gives the element a visual parent, as in a real window: WPF fetches implicit and theme styles (and with them /// templates) only once an element is initialized, which a bare element created in code never is. /// private static Border Host(FrameworkElement element) => element.Parent as Border ?? new Border { Child = element }; 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(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(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 GetAsync(int index, int pixelWidth, CancellationToken cancellationToken) { Requests++; LastPixelWidth = pixelWidth; return ValueTask.FromResult(_frame); } } /// Runs on the dispatcher of the shared WPF . private static class WpfHost { public static void Run(Action action) => Windows.WpfApplication.Dispatcher.Invoke(action); /// Processes queued dispatcher work (async continuations) on the current dispatcher. 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); } } }