CI / Build and test (push) Successful in 8m19s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 12m9s
CI / PostgreSQL 16 integration (push) Successful in 7m49s
CI / PostgreSQL 17 integration (push) Successful in 7m19s
CI / Docker image (push) Successful in 46s
Release / Server image (push) Successful in 1m14s
Owner review 1 R5 + R6. Camera rotation, mirror, flip, straighten and crop handles locked to the output; an Exposure Look group; Export output size ("proportions win"); settings format 2 with older-node gates. Also fixes project text and hashes differing between Windows and Linux.
Closes #19
Closes #20
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
755 lines
34 KiB
C#
755 lines
34 KiB
C#
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;
|
||
|
||
/// <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();
|
||
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<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, 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<GridViewHeaderRowPresenter>(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<int>();
|
||
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<int>();
|
||
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);
|
||
}
|
||
});
|
||
|
||
[Test]
|
||
public void ACropDragMovesThenResizesLockedAndIsReportedOncePerDrag() => WpfHost.Run(() =>
|
||
{
|
||
var preview = CropPreview(new Rect(0.3, 0.2, 0.3, 0.6), ratio: 0.5);
|
||
Render(preview, 800, 450);
|
||
var edits = new List<CropEditEventArgs>();
|
||
preview.CropEditCompleted += (_, e) => edits.Add(e);
|
||
|
||
// Inside the box: a move; only the overlay follows the pointer until the button is released.
|
||
preview.Press(At(preview, 0.45, 0.5));
|
||
Assert.Equal(PreviewViewport.DragMode.MoveCrop, preview.Dragging);
|
||
preview.DragTo(At(preview, 0.55, 0.55), aboutCentre: false);
|
||
Assert.Empty(edits, "nothing is reported while dragging");
|
||
Assert.Approximately(0.4, preview.ShownCrop.X, 1e-6, "the overlay follows");
|
||
Assert.Approximately(0.3, preview.EditCrop.X, 0, "the box itself waits for the release");
|
||
preview.EndDrag(commit: true);
|
||
var moved = Assert.Contains(edits, _ => true).Crop;
|
||
Assert.Within(0.4, 0.25, moved.X, moved.Y, 1e-6);
|
||
Assert.False(edits[0].IsNudge);
|
||
Assert.Equal(moved, preview.EditCrop, "the finished box is the edited one");
|
||
|
||
// The bottom-right handle, dragged far outside: anchored at the top-left corner, locked, clamped to the view.
|
||
preview.Press(At(preview, 0.7, 0.85));
|
||
Assert.Equal(PreviewViewport.DragMode.ResizeCrop, preview.Dragging);
|
||
preview.DragTo(At(preview, 1.5, 1.5), aboutCentre: false);
|
||
preview.EndDrag(commit: true);
|
||
Assert.Count(2, edits);
|
||
var resized = edits[1].Crop;
|
||
Assert.Within(0.4, 0.25, resized.X, resized.Y, 1e-9, "anchored at the opposite corner");
|
||
Assert.Approximately(0.5, resized.Width / resized.Height, 1e-9, "the ratio stays locked");
|
||
Assert.Approximately(1, resized.Bottom, 1e-9, "as large as the view lets it be");
|
||
Assert.LessOrEqual(resized.Right, 1);
|
||
|
||
// Alt resizes about the centre.
|
||
preview.Press(At(preview, resized.Right, resized.Bottom));
|
||
preview.DragTo(At(preview, resized.Right - 0.05, resized.Bottom - 0.1), aboutCentre: true);
|
||
preview.EndDrag(commit: true);
|
||
var centred = edits[2].Crop;
|
||
Assert.Within(resized.X + resized.Width / 2, resized.Y + resized.Height / 2, centred.X + centred.Width / 2, centred.Y + centred.Height / 2, 1e-9);
|
||
Assert.Approximately(0.5, centred.Width / centred.Height, 1e-9);
|
||
|
||
// A press released where it started, and a pan outside the box, report nothing.
|
||
preview.Press(At(preview, centred.X + centred.Width / 2, centred.Y + centred.Height / 2));
|
||
preview.EndDrag(commit: true);
|
||
preview.Press(At(preview, 0.05, 0.05));
|
||
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging);
|
||
preview.DragTo(At(preview, 0.1, 0.1), aboutCentre: false);
|
||
preview.EndDrag(commit: true);
|
||
Assert.Count(3, edits);
|
||
});
|
||
|
||
[Test]
|
||
public void APressTakesAHandleThenTheDividerThenTheBoxThenPansAtEveryZoom() => WpfHost.Run(() =>
|
||
{
|
||
var preview = CropPreview(new Rect(0.4, 0.4, 0.2, 0.2), ratio: 1);
|
||
preview.OriginalSource = Bitmap(2000, 1500);
|
||
preview.IsCompareEnabled = true;
|
||
preview.WipePosition = 0.5;
|
||
Render(preview, 800, 450);
|
||
var surface = Assert.NotNull(FindChild<PreviewSurface>(preview));
|
||
foreach (var zoom in new double?[] { null, 1, 2 })
|
||
{
|
||
if (zoom is { } z) preview.Zoom = z;
|
||
var label = zoom is null ? "fit" : $"zoom {zoom}";
|
||
// The image column under the divider, and a box of 0.06 × 0.12 around it (corner handles well away).
|
||
var divider = surface.ActualWidth / 2;
|
||
var nx = preview.View.ToImage(divider, 0).X / 2000;
|
||
var y = At(preview, 0, 0.5).Y;
|
||
PreviewViewport.DragMode Take(Rect box, double x)
|
||
{
|
||
preview.EditCrop = box;
|
||
preview.Press(new Point(x, y));
|
||
var mode = preview.Dragging;
|
||
preview.EndDrag(commit: false);
|
||
return mode;
|
||
}
|
||
Assert.Equal(PreviewViewport.DragMode.ResizeCrop, Take(new Rect(nx, 0.44, 0.06, 0.12), divider), $"{label}: a handle on the divider");
|
||
Assert.Equal(PreviewViewport.DragMode.Wipe, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), divider), $"{label}: the divider inside the box");
|
||
Assert.Equal(PreviewViewport.DragMode.MoveCrop, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), At(preview, nx + 0.012, 0.5).X), $"{label}: inside");
|
||
Assert.Equal(PreviewViewport.DragMode.Pan, Take(new Rect(nx - 0.03, 0.44, 0.06, 0.12), At(preview, nx + 0.06, 0.5).X), $"{label}: outside");
|
||
}
|
||
|
||
// A box that spans the view both ways (no crop) cannot move: zoomed in, a press inside pans; the middle button pans
|
||
// anywhere, inside a box that can move too.
|
||
preview.IsCompareEnabled = false;
|
||
preview.Zoom = 2;
|
||
preview.EditCrop = new Rect(0, 0, 1, 1);
|
||
preview.Press(At(preview, 0.5, 0.5));
|
||
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging, "zoomed, the whole view: pan");
|
||
preview.EndDrag(commit: false);
|
||
preview.EditCrop = new Rect(0.4, 0.4, 0.2, 0.2);
|
||
preview.PressPan(At(preview, 0.5, 0.5));
|
||
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging, "middle button inside a box");
|
||
preview.EndDrag(commit: false);
|
||
|
||
// Not editable: no handle and no box to take, the divider and pan only.
|
||
preview.CropEditable = false;
|
||
preview.EditCrop = new Rect(0.4, 0.4, 0.2, 0.2);
|
||
preview.Press(At(preview, 0.4, 0.4));
|
||
Assert.Equal(PreviewViewport.DragMode.Pan, preview.Dragging);
|
||
preview.EndDrag(commit: false);
|
||
});
|
||
|
||
[Test]
|
||
public void EscCancelsADragAndTheKeysNudgeTheBoxOnceItIsTaken() => WpfHost.Run(() =>
|
||
{
|
||
var preview = CropPreview(new Rect(0.3, 0.2, 0.3, 0.6), ratio: 0.5);
|
||
var window = OffScreen(preview, 800, 450);
|
||
try
|
||
{
|
||
var edits = new List<CropEditEventArgs>();
|
||
preview.CropEditCompleted += (_, e) => edits.Add(e);
|
||
Assert.False(Press(preview, Key.Right), "until the box is taken, the arrows step frames");
|
||
|
||
// Esc cancels a drag: the box stays, nothing is reported.
|
||
preview.Press(At(preview, 0.45, 0.5));
|
||
preview.DragTo(At(preview, 0.6, 0.6), aboutCentre: false);
|
||
Assert.True(Press(preview, Key.Escape));
|
||
Assert.Equal(PreviewViewport.DragMode.None, preview.Dragging);
|
||
Assert.Equal(new Rect(0.3, 0.2, 0.3, 0.6), preview.EditCrop);
|
||
Assert.Equal(new Rect(0.3, 0.2, 0.3, 0.6), preview.ShownCrop);
|
||
Assert.Empty(edits);
|
||
|
||
// The press took the box: the arrows move it 1 %, + and − resize it about its centre, each reported as a nudge.
|
||
Assert.True(preview.IsCropSelected);
|
||
Assert.True(Press(preview, Key.Right));
|
||
Assert.Count(1, edits);
|
||
Assert.True(edits[0].IsNudge);
|
||
Assert.Approximately(0.31, preview.EditCrop.X, 1e-9);
|
||
Assert.True(preview.Nudge(Key.Down, ModifierKeys.Shift), "Shift moves 10 %");
|
||
Assert.Approximately(0.3, preview.EditCrop.Y, 1e-9);
|
||
var before = preview.EditCrop;
|
||
Assert.True(Press(preview, Key.OemMinus));
|
||
var shrunk = preview.EditCrop;
|
||
Assert.Less(shrunk.Height, before.Height);
|
||
Assert.Approximately(0.5, shrunk.Width / shrunk.Height, 1e-9);
|
||
Assert.Within(before.X + before.Width / 2, before.Y + before.Height / 2, shrunk.X + shrunk.Width / 2, shrunk.Y + shrunk.Height / 2, 1e-9);
|
||
Assert.Count(3, edits);
|
||
|
||
// Esc gives the arrows back; Enter takes the box from the keyboard.
|
||
Assert.True(Press(preview, Key.Escape));
|
||
Assert.False(preview.IsCropSelected);
|
||
Assert.False(Press(preview, Key.Left));
|
||
Assert.True(Press(preview, Key.Enter));
|
||
Assert.True(Press(preview, Key.Left));
|
||
Assert.Count(4, edits);
|
||
|
||
// A box that can no longer change gives the keys back.
|
||
preview.CropEditable = false;
|
||
Assert.False(preview.IsCropSelected);
|
||
Assert.False(Press(preview, Key.Right));
|
||
}
|
||
finally
|
||
{
|
||
window.Close();
|
||
}
|
||
});
|
||
|
||
[Test]
|
||
public void TheEditableBoxDrawsItsHandlesAndScreenReadersReadIt() => WpfHost.Run(() =>
|
||
{
|
||
var card = ColorOf("Brush.Card");
|
||
var preview = CropPreview(new Rect(0.25, 0.2, 0.5, 0.6), ratio: 0.5 / 0.6);
|
||
Render(preview, 800, 450);
|
||
var surface = Assert.NotNull(FindChild<PreviewSurface>(preview));
|
||
Color HandlePixel(double nx, double ny)
|
||
{
|
||
var bitmap = Render(preview, 800, 450);
|
||
var (x, y) = preview.View.ToView(nx * 2000, ny * 1500);
|
||
var p = surface.TranslatePoint(new Point(x, y), preview);
|
||
return PixelAt(bitmap, (int)Math.Round(p.X), (int)Math.Round(p.Y));
|
||
}
|
||
foreach (var (nx, ny) in new[] { (0.25, 0.2), (0.75, 0.8), (0.5, 0.2), (0.75, 0.5) })
|
||
Assert.True(Near(HandlePixel(nx, ny), card, 8), $"a Card handle at ({nx}, {ny})");
|
||
preview.CropMaskMode = CropMaskMode.ShowResult;
|
||
Assert.True(Near(HandlePixel(0.25, 0.8), card, 8), "the handles draw in either mask mode");
|
||
|
||
var peer = UIElementAutomationPeer.CreatePeerForElement(preview);
|
||
var value = Assert.NotNull(peer.GetPattern(PatternInterface.Value) as System.Windows.Automation.Provider.IValueProvider);
|
||
Assert.Equal(Loc.L("Editor.Preview.CropValue", Loc.L("Common.Percent", 25), Loc.L("Common.Percent", 20), Loc.L("Common.Percent", 60)), value.Value);
|
||
Assert.True(value.IsReadOnly);
|
||
|
||
preview.CropMaskMode = CropMaskMode.ShowLoss;
|
||
preview.CropEditable = false;
|
||
Assert.False(Near(HandlePixel(0.25, 0.2), card, 8), "no handles while the box cannot change");
|
||
Assert.Null(peer.GetPattern(PatternInterface.Value), "and no value to read");
|
||
});
|
||
|
||
private static PreviewViewport CropPreview(Rect crop, double ratio) => new()
|
||
{
|
||
Source = Bitmap(2000, 1500),
|
||
ShowCropMask = true,
|
||
CropEditable = true,
|
||
CropLockRatio = ratio,
|
||
EditCrop = crop,
|
||
};
|
||
|
||
/// <summary>The surface point of the normalised image point (<paramref name="nx"/>, <paramref name="ny"/>) of a 2000 × 1500 preview.</summary>
|
||
private static Point At(PreviewViewport preview, double nx, double ny)
|
||
{
|
||
var (x, y) = preview.View.ToView(nx * 2000, ny * 1500);
|
||
return new Point(x, y);
|
||
}
|
||
|
||
/// <summary>A window off screen around <paramref name="element"/>, so it has a presentation source for key events.</summary>
|
||
private static Window OffScreen(FrameworkElement element, double width, double height)
|
||
{
|
||
var window = new Window
|
||
{
|
||
Content = new Border { Child = element },
|
||
Width = width,
|
||
Height = height,
|
||
WindowStyle = WindowStyle.None,
|
||
WindowStartupLocation = WindowStartupLocation.Manual,
|
||
Left = -20000,
|
||
Top = -20000,
|
||
ShowActivated = false,
|
||
ShowInTaskbar = false,
|
||
};
|
||
window.Show();
|
||
window.UpdateLayout();
|
||
return window;
|
||
}
|
||
|
||
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 ("PreviewViewport.CropEdit", new PreviewViewport
|
||
{
|
||
Source = Bitmap(2000, 1500),
|
||
ShowCropMask = true,
|
||
CropEditable = true,
|
||
CropLockRatio = 0.5,
|
||
EditCrop = new Rect(0.3, 0.2, 0.3, 0.6),
|
||
ShowGrid = true,
|
||
}, 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]);
|
||
}
|
||
|
||
/// <summary>The colours drawn at least two-thirds opaque, un-premultiplied: text edges keep the colour of their brush.</summary>
|
||
private static List<Color> Covered(BitmapSource bitmap)
|
||
{
|
||
var stride = bitmap.PixelWidth * 4;
|
||
var pixels = new byte[stride * bitmap.PixelHeight];
|
||
bitmap.CopyPixels(pixels, stride, 0);
|
||
var colours = new List<Color>();
|
||
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;
|
||
|
||
/// <summary>First and last x of row <paramref name="y"/> drawn in <paramref name="colour"/> at full opacity; (−1, −1) when none.</summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Raises a key press on <paramref name="target"/>; true when something handled it.</summary>
|
||
private static bool Press(UIElement target, Key key)
|
||
{
|
||
var args = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent };
|
||
target.RaiseEvent(args);
|
||
return args.Handled;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
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<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>Runs on the dispatcher of the shared WPF <see cref="Application"/>.</summary>
|
||
private static class WpfHost
|
||
{
|
||
public static void Run(Action action) => Windows.WpfApplication.Dispatcher.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);
|
||
}
|
||
}
|
||
}
|