Files
Chronos/src/Chronos.App/Shell/ScreenCapture.cs
T
Alby96andClaude Opus 5.5 3c99badcfe fix(copies): close the third verification round and add the match baselines
Integrate trashes a server photo only for the sequence's owner or an admin, a
Details stage stops instead of overwriting a server change the user had kept
this PC's value against, a merge retried after a stop plans again when work
reached the other sequence, detection keeps pairs answered while it ran, and a
sync row whose match the server deleted offers Keep here, Upload again and To
trash. The Integrate and merge logs say in the UI language why a version was
kept.

The edit-picker-twins capture scene showed no Twin chip, since a capture has no
workspace: it now lists sample workspace projects of the sample matches. The
screenshot baselines gain the 38 Matches screens and take the Matches chip,
the three Settings > Server rows, the longer priority list and 1.2.0.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:01:37 +01:00

798 lines
39 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.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Chronos.App.Archiving;
using Chronos.App.DesignTime;
using Chronos.App.Editor;
using Chronos.App.Import;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Server;
using Chronos.App.Server.Copies;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Imaging.Geometry;
using Chronos.Ui.Controls;
using Chronos.Ui.Theming;
using Chronos.Ui.Visuals;
namespace Chronos.App.Shell;
/// <summary>
/// <c>Chronos.exe --capture &lt;dir&gt;</c>: renders every client screen at 1440×900 in the dark and light themes to
/// <c>&lt;screen&gt;-&lt;theme&gt;.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
/// one, then the Videos section, then the sync table with transfers, a conflict and its confirmation, then the server's jobs, then the sequence editor on an archive
/// sequence and on a server sequence with proxies, its server job and a read-only account), plus the Library, the
/// editor's Exposure tab and the import plan in Arabic (<c>*-rtl-dark.png</c>, right to left), for visual review,
/// the pixel diff against <c>tests/visual/baselines</c> and phase reports (BRIEF §20.2), then exits. The pictures are
/// the same on any day and machine: the clock stands at <see cref="SampleData.Now"/>, formats are English and nothing
/// animates.
/// </summary>
public static class ScreenCapture
{
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
public static async Task RunAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var written = 0;
try
{
Directory.CreateDirectory(directory);
AppClock.Freeze(SampleData.Now);
CultureInfo.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("en");
Motion.SetIsEnabled(window, false);
window.WindowStartupLocation = WindowStartupLocation.Manual;
window.Left = -20000;
window.Top = -20000;
window.Width = 1440;
window.Height = 900;
window.ShowActivated = false;
window.ShowInTaskbar = false;
window.Show();
// The Server section's job list reads the sample server's jobs, none until its own scene.
var serverJobs = new SampleServerJobs();
shell.Server.JobsConnection = _ => serverJobs;
// First run: empty index, nothing connected, the welcome dialog over the empty Library.
await sample.OpenEmptyAsync();
await shell.StartAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Navigate(SectionKey.Library);
shell.ShowWelcome();
shell.Welcome!.ShowDiscovered(new Server.DiscoveredServer("Studio NAS", "https://nas.local:8443"));
written += await SaveAsync(window, directory, "welcome", theme);
shell.CompleteWelcome();
written += await SaveAsync(window, directory, "library-empty", theme);
shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server-signedout", theme);
}
// A populated archive, jobs in every state and a signed-in server.
await sample.FillAsync();
await shell.Library.RefreshAsync();
await shell.Jobs.ReloadAsync();
// The sample wrote its schedules into the index, past the scheduler's events.
await shell.Jobs.Schedules.Attached;
await shell.Jobs.Schedules.ReloadAsync();
await shell.Services.Server.RestoreAsync();
await shell.Services.Sync.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
// The server's sequences without a copy here join the Library as remote cards.
await shell.Library.RefreshAsync();
// Settings › Updates shows the result of a check made without the network.
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
await shell.Settings.DetectFormatsAsync(refresh: false);
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Library.LayoutIndex = 0;
shell.Library.ClearSelectionCommand.Execute(null);
shell.Navigate(SectionKey.Library);
written += await SaveAsync(window, directory, "library", theme, waitForThumbnails: shell);
if (shell.Library.Items.Count > 0) shell.Library.Items[0].IsSelected = true;
written += await SaveAsync(window, directory, "library-selection", theme, waitForThumbnails: shell);
shell.Library.LayoutIndex = 1;
written += await SaveAsync(window, directory, "library-list", theme, waitForThumbnails: shell);
shell.Library.LayoutIndex = 0;
shell.Library.ClearSelectionCommand.Execute(null);
shell.IsRailCollapsed = true;
written += await SaveAsync(window, directory, "library-rail-collapsed", theme, waitForThumbnails: shell);
shell.IsRailCollapsed = false;
written += await CaptureLibraryScenesAsync(window, shell, directory, theme);
shell.Navigate(SectionKey.Jobs);
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
written += await SaveAsync(window, directory, "jobs", theme);
written += await CaptureSchedulesAsync(window, shell, directory, theme);
shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server", theme);
// This PC's library shared (owner review 5, #67), then one that could not start.
SampleData.ShowShare(shell.Services);
written += await SaveAsync(window, directory, "server-share", theme);
SampleData.ShowShareFailed(shell.Services);
written += await SaveAsync(window, directory, "server-share-failed", theme);
SampleData.HideShare(shell.Services);
// Every page, About last (owner review 2, R5).
shell.Navigate(SectionKey.Settings);
foreach (var page in Enum.GetValues<SettingsPage>())
{
shell.Settings.Page = page;
written += await SaveAsync(window, directory, "settings-" + page.ToString().ToLowerInvariant(), theme);
}
// Edit with no sequence open: the picker (owner review 1, R7).
shell.Navigate(SectionKey.Edit);
await shell.Sequence.Picker.Loading;
written += await SaveAsync(window, directory, "edit-picker", theme, waitForThumbnails: shell);
foreach (var state in ImportScenes.States)
{
DismissToasts(window);
await ImportScenes.ShowAsync(shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(window);
written += await SaveAsync(window, directory, "import-" + state, theme);
}
DismissToasts(window);
foreach (var view in ArchiveScenes.Views)
{
await ArchiveScenes.ShowAsync(shell, view);
written += await SaveAsync(window, directory, "archive-" + view, theme);
}
}
written += await CaptureVideosAsync(window, shell, sample, directory);
// The sync table with proxies kept here and transfers in every state, then filtered to the conflict, then the
// conflict's confirmation (after the other screens, so the Jobs capture keeps its own sample).
await sample.CacheProxiesAsync();
await sample.FillSyncAsync();
await shell.Server.Sync.ReloadAsync();
// The job bar follows the upload the sync sample runs.
await shell.Jobs.ReloadAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Navigate(SectionKey.Server);
SelectSyncFilter(shell, SyncFilter.All);
written += await SaveAsync(window, directory, "server-sync", theme);
SelectSyncFilter(shell, SyncFilter.Conflicts);
written += await SaveAsync(window, directory, "server-conflict", theme);
if (shell.Server.Sync.Rows.FirstOrDefault() is { } conflict)
written += await SaveDialogAsync(new ConfirmDialog(SyncTableViewModel.ConflictRequest(conflict.Entry, SyncAction.KeepMine)), directory,
"server-conflict-confirm", theme);
SelectSyncFilter(shell, SyncFilter.All);
}
// The server's jobs running and paused above the sync table, with what each does now (owner review 5, #65); the
// sample account is an editor, so the list is read-only.
serverJobs.Fill();
await shell.Server.Jobs.ReloadAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
shell.Navigate(SectionKey.Server);
written += await SaveAsync(window, directory, "server-jobs", theme);
}
serverJobs.Clear();
await shell.Server.Jobs.ReloadAsync();
written += await CaptureEditorAsync(window, shell, sample, directory);
written += await CaptureRemoteEditorAsync(window, shell, sample, directory);
written += await CaptureCopiesAsync(window, shell, sample, directory);
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
if (written == 0) Environment.ExitCode = 1;
}
catch (Exception ex)
{
Log.Error("capture", "Capture failed", ex);
Environment.ExitCode = 1;
}
finally
{
Application.Current.Shutdown();
}
}
/// <summary>
/// <c>library-timeline</c>, <c>library-mass</c> (the selection with the whole bar), <c>library-delete</c> (the dry run
/// of deleting that selection, behind its typed confirmation), <c>library-remote</c> (the server's sequences as
/// remote cards) and <c>library-viewname</c> (Save view), then the Library as it was.
/// </summary>
private static async Task<int> CaptureLibraryScenesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
{
var written = 0;
foreach (var scene in LibraryScenes.Scenes)
{
DismissToasts(window);
await LibraryScenes.ShowAsync(shell, scene);
written += await SaveAsync(window, directory, "library-" + scene, theme, waitForThumbnails: shell);
if (scene == "mass" && await LibraryScenes.DeleteRequestAsync(shell) is { } request)
written += await SaveDialogAsync(new ConfirmDialog(request), directory, "library-delete", theme);
}
shell.Library.Dialog?.CloseCommand.Execute(null);
shell.Library.ClearSelectionCommand.Execute(null);
shell.Library.ClearFiltersCommand.Execute(null);
shell.Library.LayoutIndex = 0;
await shell.Library.RefreshAsync();
return written;
}
/// <summary>
/// <c>jobs-scheduled</c> (owner review 2, R10: the Scheduled tab with the weekly integrity check selected and its last
/// run) and <c>jobs-schedule-editor</c> (that schedule in the editor), then the Queue tab again.
/// </summary>
private static async Task<int> CaptureSchedulesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
{
var schedules = shell.Jobs.Schedules;
shell.Jobs.TabIndex = 1;
var written = 0;
if ((schedules.Rows.FirstOrDefault(r => !r.IsSystem && r.IsEnabled) ?? schedules.Rows.FirstOrDefault()) is { } row)
{
schedules.Selected = row;
await schedules.RunsLoading;
written += await SaveAsync(window, directory, "jobs-scheduled", theme);
row.EditCommand.Execute(null);
written += await SaveAsync(window, directory, "jobs-schedule-editor", theme);
schedules.Editor?.CloseCommand.Execute(null);
schedules.Selected = null;
}
shell.Jobs.TabIndex = 0;
return written;
}
/// <summary>
/// The Videos section (owner review 1, R9) on <see cref="SampleData.FillVideosAsync"/> in both themes: the cards of this
/// PC's, the server's and the workspace's renders (<c>videos</c>), then the list with the still selected and shown in the
/// player pane (<c>videos-list</c>), then the Board's two lanes (<c>videos-board</c>); the cards again after, with nothing
/// selected.
/// </summary>
private static async Task<int> CaptureVideosAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var videos = shell.Videos;
await sample.FillVideosAsync(videos);
var written = 0;
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
DismissToasts(window);
videos.LayoutIndex = 0;
shell.Navigate(SectionKey.Videos);
await videos.RefreshAsync();
await Settle(window);
// The cards ask for their covers once shown; the covers decode off the UI thread.
for (var i = 0; i < 40 && videos.Rows.Any(r => r.Entry.IsLocal && r.Poster is null); i++) await Task.Delay(50);
written += await SaveAsync(window, directory, "videos", theme, waitForThumbnails: shell);
videos.LayoutIndex = 1;
if (videos.Rows.FirstOrDefault(r => r.Entry.Kind == Core.Model.RenderKind.Still) is { } still)
{
still.IsSelected = true;
videos.PlayCommand.Execute(still);
}
written += await SaveAsync(window, directory, "videos-list", theme);
videos.ClosePlayerCommand.Execute(null);
videos.ClearSelectionCommand.Execute(null);
// The Board (owner request of 2026-11-06): Published beside Workspace, the workspace's sent render among its own.
videos.LayoutIndex = 2;
written += await SaveAsync(window, directory, "videos-board", theme);
videos.LayoutIndex = 0;
}
return written;
}
/// <summary>
/// Matches (owner review 6, #73, design §8.7), last as they add sequences of their own: the list, its toast, the dialog
/// at each part and list, the plan with and without a block, the merge, the two destructive confirmations, the sync rows
/// a pair marks, the Library's cards, the empty list, and the list signed out (local pairs only).
/// </summary>
private static async Task<int> CaptureCopiesAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var written = 0;
var engine = await sample.FillCopiesAsync();
await shell.Library.RefreshAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
foreach (var view in CopyScenes.Views)
{
DismissToasts(window);
await CopyScenes.ShowAsync(shell, view);
// Edit's picker with its Twin chip draws the sequences' thumbnails.
written += await SaveAsync(window, directory, view, theme, waitForThumbnails: view.StartsWith("edit-", StringComparison.Ordinal) ? shell : null);
}
CopyScenes.Reset(shell);
if (await CopyScenes.ReplaceRequestAsync(shell) is { } replace)
written += await SaveDialogAsync(new ConfirmDialog(replace), directory, "server-copies-replace-confirm", theme);
if (await CopyScenes.MergeRequestAsync(shell) is { } merge)
written += await SaveDialogAsync(new ConfirmDialog(merge), directory, "server-copies-confirm", theme);
CopyScenes.Reset(shell);
DismissToasts(window);
await LibraryScenes.ShowCopiesAsync(shell, CopyScenes.Alps);
written += await SaveAsync(window, directory, "library-copies", theme, waitForThumbnails: shell);
shell.Library.SearchText = string.Empty;
}
// No pair at all, then signed out: only this PC's own pairs stay (the chip shows with two archives).
shell.Services.Sync.Copies = new SampleCopyEngine();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
DismissToasts(window);
await CopyScenes.ShowAsync(shell, "server-copies");
written += await SaveAsync(window, directory, "server-copies-empty", theme);
}
shell.Services.Sync.Copies = engine;
CopyScenes.Reset(shell);
await shell.Services.Server.SignOutAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
DismissToasts(window);
await CopyScenes.ShowAsync(shell, "server-copies");
written += await SaveAsync(window, directory, "server-copies-signedout", theme);
}
return written;
}
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
/// <summary>A dialog shown off screen, saved, then closed.</summary>
private static async Task<int> SaveDialogAsync(Window dialog, string directory, string screen, AppTheme theme)
{
dialog.WindowStartupLocation = WindowStartupLocation.Manual;
dialog.Left = -20000;
dialog.Top = -20000;
dialog.ShowActivated = false;
dialog.ShowInTaskbar = false;
Motion.SetIsEnabled(dialog, false);
dialog.Show();
try
{
return await SaveAsync(dialog, directory, screen, theme);
}
finally
{
dialog.Close();
}
}
/// <summary>
/// The editor on the synthetic sunset: every step of the Edit path in both themes (<c>edit-&lt;step&gt;-&lt;theme&gt;.png</c>,
/// the Camera step with a keyframe selected, the Export step as Export.html with the crop mask and no compare), then
/// the preview overlays, the waveform, the "what changed" toast of Optimise all, the picker over the open sequence
/// (<c>edit-change</c>), the crop box, straighten and look scenes (<see cref="CaptureFramingAsync"/>), the Export groups
/// and the Render menu (<see cref="CaptureExportAsync"/>), the Export step of the sequence once the server has it (Sync on) with two "Save both" copies
/// to restore, and the Analysis step while the analysis runs (<c>edit-busy</c>).
/// </summary>
private static async Task<int> CaptureEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var written = 0;
var id = await sample.FillEditorAsync();
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
if (shell.Sequence.Editor is not { } editor)
{
Log.Warning("capture", "The editor sample did not open");
return 0;
}
foreach (var camera in editor.Tabs.OfType<CameraTab>()) camera.SelectedKey = 1;
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
foreach (var tab in editor.Tabs)
{
editor.SelectedTab = tab;
editor.IsCompare = tab is not ExportTab;
editor.CurrentIndex = tab is ExportTab ? 40 : 45;
written += await SaveEditorAsync(window, editor, directory, "edit-" + tab.Key.ToLowerInvariant(), theme);
}
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
editor.ShowVectors = editor.ShowRegions = true;
written += await SaveEditorAsync(window, editor, directory, "edit-exposure-overlays", theme);
editor.ShowVectors = editor.ShowRegions = false;
editor.Exposure.ChartMode = ExposureChart.Waveform;
written += await SaveEditorAsync(window, editor, directory, "edit-exposure-waveform", theme);
editor.Exposure.ChartMode = ExposureChart.Luminance;
editor.OptimiseAllCommand.Execute(null);
written += await SaveEditorAsync(window, editor, directory, "edit-optimise", theme);
editor.Session.Undo();
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
// Change sequence: the picker over the open sequence, which stays open behind it until another opens.
shell.Sequence.ChangeSequenceCommand.Execute(null);
await shell.Sequence.Picker.Loading;
written += await SaveAsync(window, directory, "edit-change", theme, waitForThumbnails: shell);
shell.Sequence.CancelPickCommand.Execute(null);
}
written += await CaptureFramingAsync(window, editor, directory);
written += await CaptureExportAsync(window, editor, directory);
// The server has the sequence (Sync can be ticked) and two copies of this PC's settings were kept by "Save both".
await sample.KeepEditorCopiesAsync(id);
await editor.Session.ReloadAsync();
await editor.RefreshSyncGateAsync();
var export = editor.Tabs.OfType<ExportTab>().Single();
export.SyncToServer = true;
editor.SelectedTab = export;
editor.IsCompare = false;
// Sync and Restore are rows of the File group: the groups above it folded to their summaries.
var groups = OpenGroups(export, export.FileGroup);
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
written += await SaveEditorAsync(window, editor, directory, "edit-export-copies", theme);
}
RestoreGroups(export, groups);
export.SyncToServer = false;
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
written += await CaptureRightToLeftAsync(window, shell, editor, directory);
// Last, as it stays: an analysis of the sequence running (settings disabled, viewing tools live), on the step that follows it.
await sample.MarkAnalysingAsync(id);
await editor.AttachJobsAsync();
editor.SelectedTab = editor.Analysis;
// The job bar shows the analysis, the one job running.
await shell.Jobs.ReloadAsync();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
written += await SaveEditorAsync(window, editor, directory, "edit-busy", theme);
}
return written;
}
/// <summary>
/// The framing and look of owner review 1 (R5/R6) in both themes, each undone after: the Camera step with a 9:16 crop
/// box moved off centre and its handles (<c>edit-camera-crop</c>); the same view turned right and straightened 3° with
/// the straighten grid (<c>edit-camera-straighten</c>); the Exposure step with the Sepia look at 60 % and the compare
/// wipe (<c>edit-exposure-look</c>).
/// </summary>
private static async Task<int> CaptureFramingAsync(MainWindow window, EditorViewModel editor, string directory)
{
var written = 0;
var session = editor.Session;
var camera = editor.Tabs.OfType<CameraTab>().Single();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
editor.SelectedTab = camera;
editor.IsCompare = false;
editor.CurrentIndex = 45;
var steps = 0;
if (session.Edit(p => SampleData.PortraitCrop(session, p))) steps++;
written += await SaveEditorAsync(window, editor, directory, "edit-camera-crop", theme);
if (session.Orient(OrientationOp.RotateRight)) steps++;
if (session.Edit(SampleData.Straightened)) steps++;
editor.IsStraightening = true;
written += await SaveEditorAsync(window, editor, directory, "edit-camera-straighten", theme);
editor.IsStraightening = false;
for (; steps > 0; steps--) session.Undo();
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
var look = session.Edit(SampleData.SepiaLook);
await Settle(window);
// The Look group sits at the end of the step's rows: the panel is scrolled down to it.
var panel = ScrollerOf<GroupRow>(window);
panel?.ScrollToBottom();
written += await SaveEditorAsync(window, editor, directory, "edit-exposure-look", theme);
panel?.ScrollToTop();
if (look) session.Undo();
}
return written;
}
/// <summary>
/// The Export step of owner review 1 (R3) in both themes: Output and File folded to their summary lines, Encoding and
/// Playback open on a boomerang played twice with fades, scrolled down to Playback's last row (<c>edit-export-playback</c>),
/// undone after with the groups as they were; then the header's Render ▾ menu dropped down over the Export step
/// (<c>edit-render-menu</c>).
/// </summary>
private static async Task<int> CaptureExportAsync(MainWindow window, EditorViewModel editor, string directory)
{
var written = 0;
var session = editor.Session;
var export = editor.Tabs.OfType<ExportTab>().Single();
var frame = editor.CurrentIndex;
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
editor.SelectedTab = export;
editor.IsCompare = false;
editor.CurrentIndex = 40;
var open = OpenGroups(export, export.EncodingGroup, export.PlaybackGroup);
var played = session.Edit(SampleData.Boomerang);
await Settle(window);
// The panel ends with Playback's last row: scrolled down to it, with as much of Encoding as fits above.
var panel = ScrollerOf<SettingGroup>(window);
panel?.ScrollToBottom();
written += await SaveEditorAsync(window, editor, directory, "edit-export-playback", theme);
panel?.ScrollToTop();
if (played) session.Undo();
RestoreGroups(export, open);
await Settle(window);
if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", "edit-render-menu was still busy");
written += await SaveRenderMenuAsync(window, editor, directory, theme);
}
// The scenes after keep the frame they had.
editor.CurrentIndex = frame;
return written;
}
private static SettingGroup[] GroupsOf(ExportTab export) => [export.OutputGroup, export.EncodingGroup, export.PlaybackGroup, export.FileGroup];
/// <summary>Opens the Export step's groups <paramref name="open"/> and folds the others; returns which were open, for <see cref="RestoreGroups"/>.</summary>
private static bool[] OpenGroups(ExportTab export, params SettingGroup[] open)
{
var groups = GroupsOf(export);
var before = groups.Select(g => g.IsExpanded).ToArray();
foreach (var group in groups) group.IsExpanded = open.Contains(group);
return before;
}
/// <summary>The Export step's groups open or folded as <see cref="OpenGroups"/> found them (the app keeps them for the next run).</summary>
private static void RestoreGroups(ExportTab export, bool[] open)
{
var groups = GroupsOf(export);
for (var i = 0; i < groups.Length; i++) groups[i].IsExpanded = open[i];
}
/// <summary>
/// The window with the header's Render ▾ menu dropped down below its button, as the menu shows it. A context menu opens
/// in a popup of its own, on screen, which the window's picture does not hold: the menu is made from the same entries
/// (<see cref="SplitButton.CreateItem"/>), laid out apart and drawn over the window where it drops down (kept inside the
/// window, as Windows keeps it on the screen).
/// </summary>
private static async Task<int> SaveRenderMenuAsync(MainWindow window, EditorViewModel editor, string directory, AppTheme theme)
{
await Settle(window);
if (FindVisual<SplitButton>(window, b => b.Name == "RenderButton") is not { } button)
{
Log.Warning("capture", "The Render button is not shown; edit-render-menu skipped");
return 0;
}
var menu = new ContextMenu { FlowDirection = window.FlowDirection };
var template = button.TryFindResource(SplitButton.ItemTemplateKey) as DataTemplate;
foreach (var entry in editor.RenderMenuItems) menu.Items.Add(SplitButton.CreateItem(entry, template));
menu.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
menu.Arrange(new Rect(menu.DesiredSize));
menu.UpdateLayout();
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
menu.UpdateLayout();
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
// Below the button, 4 px apart (SplitButton's placement), its left edge on the button's.
var at = button.TranslatePoint(new Point(0, button.ActualHeight + 4), root);
at = new Point(Math.Round(Math.Clamp(at.X, 0, Math.Max(0, root.ActualWidth - menu.ActualWidth))), Math.Round(at.Y));
return Save(window, Path.Combine(directory, $"edit-render-menu-{theme.ToString().ToLowerInvariant()}.png"), (menu, at)) ? 1 : 0;
}
/// <summary>The first shown element of type <typeparamref name="T"/> under <paramref name="root"/> that <paramref name="match"/> takes; null when none.</summary>
private static T? FindVisual<T>(DependencyObject root, Func<T, bool> match)
where T : FrameworkElement
{
var pending = new Stack<DependencyObject>([root]);
while (pending.Count > 0)
{
var node = pending.Pop();
if (node is T { IsVisible: true } found && match(found)) return found;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) pending.Push(VisualTreeHelper.GetChild(node, i));
}
return null;
}
/// <summary>The scroll viewer around the shown row whose data is a <typeparamref name="TRow"/>; null when none is shown.</summary>
private static ScrollViewer? ScrollerOf<TRow>(DependencyObject root)
{
var pending = new Stack<DependencyObject>([root]);
while (pending.Count > 0)
{
var node = pending.Pop();
if (node is FrameworkElement { DataContext: TRow, IsVisible: true } row)
{
for (DependencyObject? up = row; up is not null; up = VisualTreeHelper.GetParent(up))
if (up is ScrollViewer scroller) return scroller;
return null;
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) pending.Push(VisualTreeHelper.GetChild(node, i));
}
return null;
}
/// <summary>
/// The Library, the editor's Exposure tab and the import plan in Arabic, dark: the layout mirrors while photos,
/// charts, the filmstrip and templates stay left to right. English is restored whatever happens.
/// </summary>
private static async Task<int> CaptureRightToLeftAsync(MainWindow window, ShellViewModel shell, EditorViewModel editor, string directory)
{
var written = 0;
var frame = editor.CurrentIndex;
ThemeManager.Apply(AppTheme.Dark);
UiLanguage.Apply("ar");
try
{
DismissToasts(window);
shell.Navigate(SectionKey.Library);
written += await SaveAsync(window, directory, "library-rtl", AppTheme.Dark, waitForThumbnails: shell);
shell.Navigate(SectionKey.Edit);
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
editor.CurrentIndex = 45;
written += await SaveEditorAsync(window, editor, directory, "edit-exposure-rtl", AppTheme.Dark);
await ImportScenes.ShowAsync(shell, "plan");
DismissToasts(window);
written += await SaveAsync(window, directory, "import-plan-rtl", AppTheme.Dark);
}
finally
{
UiLanguage.Apply("en");
}
shell.Navigate(SectionKey.Edit);
editor.CurrentIndex = frame;
return written;
}
/// <summary>
/// A server sequence open with this PC's proxies (Sunrise over Superga, cached by the sync captures): the server in
/// the header, the preview from the proxies, the project from the server (<c>edit-remote</c>); its Export tab,
/// where the server picks the encoder and keeps the renders (<c>edit-remote-export</c>); a render running on the
/// server with its bar and Cancel (<c>edit-remote-running</c>); then, last as it stays, the sequence opened by an
/// account without the Edit right (<c>edit-remote-readonly</c>).
/// </summary>
private static async Task<int> CaptureRemoteEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
{
var written = 0;
var id = sample.ProxiedSequenceId;
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
if (shell.Sequence.Editor is not { IsRemote: true } editor)
{
Log.Warning("capture", "The server sequence did not open in the editor");
return 0;
}
DismissToasts(window);
var export = editor.Tabs.OfType<ExportTab>().Single();
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
written += await SaveEditorAsync(window, editor, directory, "edit-remote", theme);
editor.SelectedTab = export;
editor.IsCompare = false;
// The server's encoder is the Encoding group's first row, the folder it keeps the renders in the File group's.
var groups = OpenGroups(export, export.EncodingGroup, export.FileGroup);
written += await SaveEditorAsync(window, editor, directory, "edit-remote-export", theme);
RestoreGroups(export, groups);
}
sample.RunServerRender();
await editor.AttachJobsAsync();
editor.SelectedTab = editor.Exposure;
editor.IsCompare = true;
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
written += await SaveEditorAsync(window, editor, directory, "edit-remote-running", theme);
}
sample.EndServerJobs();
await sample.RestrictAccountAsync();
await shell.Sequence.OpenAsync(id, reload: true);
if (shell.Sequence.Editor is not { IsReadOnly: true } viewer)
{
Log.Warning("capture", "The server sequence did not open read-only");
return written;
}
DismissToasts(window);
viewer.SelectedTab = viewer.Exposure;
foreach (var theme in Themes)
{
ThemeManager.Apply(theme);
written += await SaveEditorAsync(window, viewer, directory, "edit-remote-readonly", theme);
}
return written;
}
private static async Task<int> SaveEditorAsync(Window window, EditorViewModel editor, string directory, string screen, AppTheme theme)
{
await Settle(window);
if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", $"{screen} was still busy");
return await SaveAsync(window, directory, screen, theme);
}
/// <summary>Toasts of one screen's scene stay out of the next screen's picture.</summary>
private static void DismissToasts(MainWindow window)
{
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
}
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
{
await Settle(window);
if (waitForThumbnails?.Services.Thumbnails is { } thumbnails)
{
// Thumbnails decode on the thread pool; give them a moment, then settle again.
for (var i = 0; i < 40 && thumbnails.PendingLoads > 0; i++) await Task.Delay(50);
await Task.Delay(100);
await Settle(window);
}
return Save(window, Path.Combine(directory, $"{screen}-{theme.ToString().ToLowerInvariant()}.png")) ? 1 : 0;
}
private static async Task Settle(Window window)
{
window.UpdateLayout();
// Let bindings, templates, async continuations and deferred renders complete.
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(30);
await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
window.UpdateLayout();
}
/// <param name="overlay">An element laid out apart (a drop-down menu) drawn over the window with its top left at the point given.</param>
private static bool Save(Window window, string path, (FrameworkElement Element, Point At)? overlay = null)
{
if (VisualTreeHelper.GetChildrenCount(window) == 0) window.ApplyTemplate();
if (VisualTreeHelper.GetChildrenCount(window) == 0)
{
Log.Warning("capture", "Window has no visual tree; nothing to render");
return false;
}
var root = (FrameworkElement)VisualTreeHelper.GetChild(window, 0);
var dpi = VisualTreeHelper.GetDpi(window);
var width = (int)Math.Ceiling(root.ActualWidth * dpi.DpiScaleX);
var height = (int)Math.Ceiling(root.ActualHeight * dpi.DpiScaleY);
if (width <= 0 || height <= 0)
{
Log.Warning("capture", $"Root element has no size ({root.ActualWidth}×{root.ActualHeight}); skipped {Path.GetFileName(path)}");
return false;
}
var bitmap = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
// A right-to-left window's content already renders mirrored, as on screen.
bitmap.Render(root);
BitmapSource picture = bitmap;
if (overlay is ({ } element, var at))
{
var layer = new RenderTargetBitmap((int)Math.Ceiling(element.ActualWidth * dpi.DpiScaleX), (int)Math.Ceiling(element.ActualHeight * dpi.DpiScaleY),
dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
layer.Render(element);
var drawing = new DrawingVisual();
using (var context = drawing.RenderOpen())
{
context.DrawImage(bitmap, new Rect(0, 0, width / dpi.DpiScaleX, height / dpi.DpiScaleY));
context.DrawImage(layer, new Rect(at, new Size(layer.PixelWidth / dpi.DpiScaleX, layer.PixelHeight / dpi.DpiScaleY)));
}
var composed = new RenderTargetBitmap(width, height, dpi.PixelsPerInchX, dpi.PixelsPerInchY, PixelFormats.Pbgra32);
composed.Render(drawing);
picture = composed;
}
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(picture));
using var stream = File.Create(path);
encoder.Save(stream);
return true;
}
}