Files
Chronos/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs
T
Alby96 5aeb6aa787 Add comprehensive tests for EditSection functionality in the Windows application
- Implement tests for picker behavior, including loading sequences, searching, and handling empty libraries.
- Validate sequence opening via Enter key and double-click actions.
- Ensure proper handling of unsaved edits and sequence deletion scenarios.
- Verify accessibility features for picker rows across different languages.
- Introduce a dialog counting mechanism to manage unsaved edit confirmations.
2026-10-19 12:10:42 +02:00

572 lines
28 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Advice;
using Titano.Core.Analysis;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Editor;
/// <summary>
/// The sequence editor in the real main window, off screen at the minimum capture size, on the synthetic sunset of
/// <c>--capture</c> (real JPEG frames, deep analysis, advised project): every section shows its measuring tool, its
/// settings and preview pixels in both themes, and an edit goes through undo and redo.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditorSmokeTests
{
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
/// <summary>Here rather than with the other texts: it switches the UI language, which only a serial class may do.</summary>
[Test]
public void AnOptimiseLinePointsFromTheOldValueToTheNewOneInEitherReadingDirection()
{
var change = new SettingChange(AdvisorParameters.DeflickerWindow, 21, 41, "reason", []);
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Equal("Deflicker window: 21 frames → 41 frames", EditorText.Change(change));
Loc.SetCulture(CultureInfo.GetCultureInfo("ar"));
Assert.Equal(Loc.L("Editor.Optimise.ChangeRtl", Loc.L("Editor.Exposure.Window"), Loc.Plural("Editor.Value.Frames", 21), Loc.Plural("Editor.Value.Frames", 41)),
EditorText.Change(change), "Arabic reads the old value first, from the right");
Assert.Contains("←", EditorText.Change(change));
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
[Test]
public Task EverySectionOfTheEditorRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply("en");
ThemeManager.Apply(AppTheme.Dark);
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
var shell = new ShellViewModel(services);
var window = new MainWindow(shell)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 1200,
Height = 788,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
await sample.OpenEmptyAsync();
await shell.StartAsync();
var id = await sample.FillEditorAsync();
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(shell.Sequence.Editor);
Assert.Equal(96, editor.FrameCount);
Assert.NotNull(editor.Session.Content.Deep, "the sample is analysed");
Assert.True(editor.Session.Project.Exposure.Deflicker.HasAdvice, "the advice is in the project");
Assert.Equal("Harbour sunset", editor.Title);
Assert.Equal("Titano — Harbour sunset", shell.WindowTitle, "the window title follows the open sequence");
Assert.False(shell.IsJobBarVisible, "the idle job bar gives its height to the editor");
// The Render split button can be clicked once the plan exists (its command re-reads its state).
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(window);
Assert.True(editor.CanRender, editor.RenderBlockedReason ?? "renderable");
var render = Find<SplitButton>(window).Single(b => b.IsVisible);
Assert.True(Find<Button>(render).First().IsEnabled, "Render is enabled");
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
foreach (var tab in editor.Tabs)
{
editor.SelectedTab = tab;
await SettleAsync(window);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), $"{tab.Key}: still busy");
await SettleAsync(window);
var view = Find<SequenceView>(window).Single(v => v.IsVisible);
Assert.NotNull(editor.PreviewImage, $"{tab.Key}: the preview shows pixels");
ExpectMeasure(view, tab);
Assert.True(Find<ContentPresenter>(view).Any(p => ReferenceEquals(p.Content, tab) && p.ActualHeight > 100), $"{tab.Key}: settings column");
Assert.Greater(Distinct(Render(window)), 40, $"{tab.Key} drew almost nothing in {theme}");
}
}
// The Export tab: Add to queue and Batch follow the plan and the ticked presets.
ThemeManager.Apply(AppTheme.Dark);
var export = editor.Tabs.OfType<ExportTab>().Single();
editor.ShowVectors = true;
editor.SelectedTab = export;
await SettleAsync(window);
Assert.False(Find<PreviewViewport>(window).Single(p => p.IsVisible).ShowVectors, "a tool without a button on the Export tab draws nothing");
Assert.True(export.AddToQueueCommand.CanExecute(null));
Assert.False(export.BatchCommand.CanExecute(null), "nothing ticked");
var batchButton = Find<Button>(window).Single(b => ReferenceEquals(b.Command, export.BatchCommand));
Assert.False(batchButton.IsEnabled);
export.Cards.First(c => c.CanBatch).IsInBatch = true;
await SettleAsync(window);
Assert.True(batchButton.IsEnabled, "ticking a card enables Batch…");
editor.ShowVectors = false;
// The waveform of the Exposure tab is measured from the preview.
editor.SelectedTab = editor.Exposure;
editor.Exposure.ChartMode = ExposureChart.Waveform;
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.NotNull(editor.WaveformImage, "the waveform shows the frame on screen");
editor.Exposure.ChartMode = ExposureChart.Luminance;
// 1:1 renders the source's own pixels; Fit returns to the view's size.
editor.ZoomMode = PreviewZoomMode.Actual;
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.Equal(editor.Session.Content.SourceWidth, ((BitmapSource)editor.PreviewImage!).PixelWidth, "1:1 shows source pixels");
editor.ZoomMode = PreviewZoomMode.Fit;
// A language switch makes again what the tabs keep in objects: the chart legend and the Auto chips follow at once.
var chip = editor.Exposure.Rows.OfType<AutoSwitchRow>().First();
var english = chip.AutoText;
UiLanguage.Apply("it");
try
{
Assert.True(editor.Exposure.Legend.Any(i => i.Text == "luminanza misurata"), "the legend follows the language");
Assert.Equal(Loc.L("Common.Auto") + Loc.Separator + Loc.L(chip.IsOn ? "Editor.Value.On" : "Editor.Value.Off"), chip.AutoText);
Assert.NotEqual(english, chip.AutoText);
}
finally
{
UiLanguage.Apply("en");
}
// An edit through the session is undone and redone (Ctrl+Z / Ctrl+Y run the same commands).
ThemeManager.Apply(AppTheme.Dark);
var before = editor.Session.Project.Exposure.ExposureOffsetEv;
editor.Session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } });
editor.UndoCommand.Execute(null);
Assert.Equal(before, editor.Session.Project.Exposure.ExposureOffsetEv);
editor.RedoCommand.Execute(null);
Assert.Equal(0.5, editor.Session.Project.Exposure.ExposureOffsetEv);
await editor.Session.FlushAsync();
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.NotNull(editor.Plan, "the export is planned");
}
finally
{
ThemeManager.Apply(AppTheme.Dark);
window.Close();
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
environment.DeleteCaptureData();
}
});
/// <summary>
/// A server sequence opened with this PC's proxies (the sample server's Sunrise over Superga): the header names the
/// server, the preview shows a proxy, Save to and Sync wait for the server, and Render posts a server job.
/// </summary>
[Test]
public Task AServerSequenceOpensWithItsProxies() => ScreenHost.RunAsync(async () =>
{
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply("en");
ThemeManager.Apply(AppTheme.Dark);
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
var shell = new ShellViewModel(services);
var window = new MainWindow(shell)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 1200,
Height = 788,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
await sample.OpenEmptyAsync();
await shell.StartAsync();
await sample.FillAsync();
await services.Server.RestoreAsync();
await services.Sync.RefreshAsync();
await sample.CacheProxiesAsync();
var id = sample.ProxiedSequenceId;
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(shell.Sequence.Editor);
Assert.True(editor.IsRemote);
Assert.Equal("Studio NAS", editor.RemoteText);
Assert.Equal(3, editor.FrameCount);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(window);
Assert.NotNull(editor.PreviewImage, "the preview shows a proxy");
var view = Find<SequenceView>(window).Single(v => v.IsVisible);
Assert.True(Find<StatusGlyph>(view).Any(g => g is { Kind: StatusKind.Remote, IsVisible: true, Text: "Studio NAS" }), "the header names the server");
Assert.Greater(Distinct(Render(window)), 40, "the remote editor drew almost nothing");
var export = editor.Tabs.OfType<ExportTab>().Single();
editor.SelectedTab = export;
await SettleAsync(window);
Assert.Equal(ExportSyncGate.Remote, editor.SyncGate);
Assert.False(Find<CheckBox>(view).Single(c => ReferenceEquals(c.DataContext, export) && c.IsVisible).IsEnabled, "Sync: the server's renders stay there");
Assert.False(Find<ComboBox>(view).Single(c => ReferenceEquals(c.ItemsSource, export.SaveChoices)).IsEnabled, "Save to: the server's exports folder");
Assert.True(editor.CanRender, editor.RenderBlockedReason ?? "renderable");
await editor.RenderAsync(JobPriority.User, batch: false);
var queued = Assert.Contains(await editor.Session.Source.ListJobsAsync(CancellationToken.None), _ => true);
Assert.Equal(JobKind.Render, queued.Kind);
// Without the Edit right a server sequence is only shown: every change is disabled and says why.
var content = EditorFixture.Content(EditorFixture.Sunset);
var looking = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = true, IsReadOnly = true }, content, []);
var viewer = new EditorViewModel(shell, looking, [], EncoderHost.Client);
await using (viewer)
{
Assert.False(viewer.IsEditable);
Assert.Equal(Loc.L("Tooltips.Editor.ReadOnly"), viewer.LockedToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.ReadOnly"), viewer.Frames.HeroToolTip);
Assert.False(viewer.Frames.SetHeroCommand.CanExecute(null));
Assert.False(viewer.OptimiseAllCommand.CanExecute(null));
Assert.False(viewer.AnalyseCommand.CanExecute(null));
}
// A failed save says why in one localized sentence (BRIEF §0.2 rule 6); the exception's own text stays in the log.
// The editor's own reasons keep their sentence (they are I/O failures too, which would read "does not answer").
var toasts = new List<Toast>();
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
shell.PendingToasts.CollectionChanged += collect;
try
{
foreach (var (remote, failure, cause) in new (bool, Exception, string)[]
{
(true, new HttpRequestException("No such host is known."), "Server.Error.Unreachable"),
(false, new UnauthorizedAccessException(@"Access to the path 'D:\Archive\.titano\sequence.json' is denied."), "Archive.Failed.Access"),
(true, new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")), "Editor.Error.FramesChanged"),
(true, new EditorException(Loc.L("Editor.Error.RemoteReadOnly")), "Editor.Error.RemoteReadOnly"),
(false, new EditorException(Loc.L("Editor.Error.SaveConflict")), "Editor.Error.SaveConflict"),
(false, new EditorException(Loc.L("Editor.Error.Project"), new InvalidDataException("project.json version 9 is newer")), "Editor.Error.Project"),
})
{
toasts.Clear();
var saving = new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = remote, FailNextSave = failure };
var failing = new EditorViewModel(shell, new EditorSession(saving, content, []), [], EncoderHost.Client);
await using (failing)
{
failing.Session.Edit(p => p with { HeroFrame = 1 });
Assert.False(await failing.Session.FlushAsync(), "the save failed");
var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Editor.Save.Failed"));
Assert.Equal(Loc.L(cause), toast.Message);
}
}
}
finally
{
shell.PendingToasts.CollectionChanged -= collect;
}
}
finally
{
window.Close();
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
environment.DeleteCaptureData();
}
});
/// <summary>
/// Frames inserted under the editor (a sync download, an import of earlier photos) move the frame on screen with its
/// photo: what the frame actions (Exclude, Set hero, a keyframe) apply to stays the photo the user looks at.
/// </summary>
[Test]
public Task TheFrameOnScreenStaysWhenFramesAreInsertedBeforeIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var content = EditorFixture.Content(EditorFixture.Sunset, deep: false);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
await using (editor)
{
editor.CurrentIndex = 5;
var shown = content.Frames[5].Id;
// An earlier photo arrives and the last frame goes: as many frames as before, each one place later.
var first = content.Frames[0];
IReadOnlyList<Titano.Core.Model.Frame> frames =
[.. new[] { first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(-1) } }.Concat(content.Frames.SkipLast(1))
.Select((f, i) => f with { Index = i })];
source.Content = content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) };
await editor.Session.ReloadAsync();
Assert.Equal(6, editor.CurrentIndex);
Assert.Equal(shown, editor.Session.Content.Frames[editor.CurrentIndex].Id);
Assert.Equal(6, editor.Frames.Selected?.Index);
}
});
/// <summary>
/// At the 1200 px minimum beside the 200 px rail (owner review 1, R1), the preview's tools stay inside the preview in
/// every language, crop mask on (the crop-result tool enabled): they take a second line rather than lose Play and Full screen.
/// </summary>
[Test]
public Task ThePreviewToolsStayInsideThePreviewInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
var id = await app.Sample.FillEditorAsync();
app.Shell.OpenSequence(id);
await app.Shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
try
{
editor.SelectedTab = editor.Exposure;
editor.ShowCropMask = true;
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await SettleAsync(app.Window);
var viewport = Find<PreviewViewport>(app.Window).Single(v => v.IsVisible);
var (left, right) = Span(viewport, app.Window);
var tools = Find<System.Windows.Controls.Primitives.ButtonBase>(viewport).Where(b => b.IsVisible).ToList();
Assert.True(tools.Count >= 8, $"{language}: every tool shows ({tools.Count})");
foreach (var tool in tools)
{
var (start, end) = Span(tool, app.Window);
Assert.True(start >= left - 0.5 && end <= right + 0.5,
$"{language}: the tool '{System.Windows.Automation.AutomationProperties.GetName(tool)}{tool.Content}' spans {start:0}–{end:0} px, the preview {left:0}–{right:0} px");
}
}
}
finally
{
UiLanguage.Apply("en");
await app.Shell.Sequence.CloseAsync();
}
});
/// <summary>
/// At the 1200 px minimum beside the 200 px rail (owner review 1, R1), a server sequence's job keeps its Cancel whole in every
/// language, also read-only (the longest place line): the title and the summary give way first (BRIEF §11.5, cancel always stays).
/// </summary>
[Test]
public Task AServerJobKeepsItsCancelAtTheMinimumWidthInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
await app.Sample.FillAsync();
await app.Services.Server.RestoreAsync();
await app.Services.Sync.RefreshAsync();
await app.Sample.CacheProxiesAsync();
await app.Sample.RestrictAccountAsync();
var id = app.Sample.ProxiedSequenceId;
app.Shell.OpenSequence(id);
await app.Shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
try
{
Assert.True(editor.IsReadOnly, "the account may not edit");
app.Sample.RunServerRender();
await editor.AttachJobsAsync();
Assert.NotNull(editor.ServerJobText, "the server's render shows");
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await SettleAsync(app.Window);
var cancel = Find<Button>(app.Window).Single(b => b.IsVisible && ReferenceEquals(b.Command, editor.CancelServerJobCommand));
// Drawn whole: its left edge, its middle and its right edge each take the pointer (a layout clip would not).
foreach (var x in new[] { 2.0, cancel.ActualWidth / 2, cancel.ActualWidth - 2 })
{
var point = cancel.TranslatePoint(new Point(x, cancel.ActualHeight / 2), app.Window);
Assert.True(app.Window.InputHitTest(point) is DependencyObject hit && IsWithin(hit, cancel),
$"{language}: Cancel is cut at {x:0} px of its {cancel.ActualWidth:0}");
}
}
}
finally
{
UiLanguage.Apply("en");
app.Sample.EndServerJobs();
await app.Shell.Sequence.CloseAsync();
}
});
/// <summary>
/// At the 1200 px minimum beside the 200 px rail (owner review 1, R1), the frame table's Time column holds the widest time
/// of every shipped language (two-digit hours, morning and afternoon marks).
/// </summary>
[Test]
public Task TheFrameTableShowsWholeTimesInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Window.Width = 1200;
app.Window.Height = 788;
var id = await app.Sample.FillEditorAsync();
app.Shell.OpenSequence(id);
await app.Shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(app.Shell.Sequence.Editor);
try
{
editor.SelectedTab = editor.Frames;
var times = new[] { new DateTime(2026, 1, 1, 12, 59, 59), new DateTime(2026, 1, 1, 22, 58, 48), new DateTime(2026, 1, 1, 10, 48, 58) };
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
await SettleAsync(app.Window);
var cell = Find<TextBlock>(app.Window).First(t => t.IsVisible && t.DataContext is FrameRow row && row.Time.Length > 0 && t.Text == row.Time);
var widest = times.Max(t => Measure(cell, t.ToString("T", Loc.Culture)));
Assert.True(widest <= cell.ActualWidth + 1, $"{language}: the widest time needs {widest:0} px, the column gives {cell.ActualWidth:0}");
}
}
finally
{
UiLanguage.Apply("en");
await app.Shell.Sequence.CloseAsync();
}
});
/// <summary>The width <paramref name="text"/> needs in the font, numerals and formatting of <paramref name="like"/>.</summary>
private static double Measure(TextBlock like, string text)
{
var probe = new TextBlock
{
Text = text,
FontFamily = like.FontFamily,
FontSize = like.FontSize,
FontStyle = like.FontStyle,
FontWeight = like.FontWeight,
FontStretch = like.FontStretch,
FlowDirection = like.FlowDirection,
Language = like.Language,
};
System.Windows.Documents.Typography.SetNumeralAlignment(probe, System.Windows.Documents.Typography.GetNumeralAlignment(like));
TextOptions.SetTextFormattingMode(probe, TextOptions.GetTextFormattingMode(like));
probe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
return probe.DesiredSize.Width;
}
private static bool IsWithin(DependencyObject node, DependencyObject ancestor)
{
for (var at = node; at is not null; at = VisualTreeHelper.GetParent(at))
{
if (ReferenceEquals(at, ancestor)) return true;
}
return false;
}
/// <summary>The left and right edges of an element in window coordinates, whichever way the window reads.</summary>
private static (double Left, double Right) Span(FrameworkElement element, Window window)
{
var a = element.TranslatePoint(new Point(0, 0), window).X;
var b = element.TranslatePoint(new Point(element.ActualWidth, 0), window).X;
return (Math.Min(a, b), Math.Max(a, b));
}
/// <summary>The measuring tool of each section has content.</summary>
private static void ExpectMeasure(SequenceView view, EditorTab tab)
{
switch (tab)
{
case AnalysisTab analysis:
// The findings, each with the step that deals with it, or the sentence that there are none.
Assert.True(Find<ListBoxItem>(view).Any(i => i.DataContext is AnalysisFinding && i.IsVisible)
|| Find<EmptyState>(view).Any(e => e.IsVisible && e.Message == analysis.EmptyText), "Analysis: findings or why there are none");
break;
case FramesTab frames:
Assert.Equal(96, frames.Frames.Count);
Assert.NotEmpty(Find<ListBoxItem>(view).Where(i => i.DataContext is FrameRow && i.IsVisible));
break;
case CameraTab or TimeTab:
Assert.NotEmpty(Find<CurveEditor>(view).Where(c => c.IsVisible && c.ActualHeight > 50));
break;
case ExportTab export:
Assert.NotEmpty(export.Cards);
Assert.NotEmpty(Find<Button>(view).Where(b => b.DataContext is PresetCard && b.IsVisible));
Assert.True(export.Cards.Any(c => c.Estimate is not null), "estimates on the cards");
break;
default:
var chart = Find<SeriesChart>(view).Single(c => c.IsVisible);
Assert.True(chart.ActualHeight > 50, $"{tab.Key}: chart height");
Assert.NotEmpty(chart.Series!);
break;
}
}
private static async Task SettleAsync(Window window)
{
window.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
private static RenderTargetBitmap Render(Window window)
{
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var bitmap = new RenderTargetBitmap((int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX), (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY),
dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
bitmap.Render(root);
return bitmap;
}
private static int Distinct(BitmapSource bitmap)
{
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
var colours = new HashSet<int>();
for (var i = 0; i < pixels.Length && colours.Count < 2000; i += 4 * 5) colours.Add(BitConverter.ToInt32(pixels, i));
return colours.Count;
}
private static List<T> Find<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
var stack = new Stack<DependencyObject>([root]);
while (stack.TryPop(out var node))
{
if (node is T match) found.Add(match);
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) stack.Push(VisualTreeHelper.GetChild(node, i));
}
return found;
}
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}