using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Chronos.App.DesignTime;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Testing;
using Chronos.Ui.Controls;
using Chronos.Ui.Theming;
using Chronos.Ui.Visuals;
namespace Chronos.App.Tests.Editor;
///
/// The sequence editor in the real main window, off screen at the minimum capture size, on the synthetic sunset of
/// --capture (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.
///
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class EditorSmokeTests
{
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light];
/// Here rather than with the other texts: it switches the UI language, which only a serial class may do.
[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("Chronos — 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(window).Single(b => b.IsVisible);
Assert.True(Find(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(window).Single(v => v.IsVisible);
Assert.NotNull(editor.PreviewImage, $"{tab.Key}: the preview shows pixels");
ExpectMeasure(view, tab);
Assert.True(Find(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().Single();
editor.ShowVectors = true;
editor.SelectedTab = export;
await SettleAsync(window);
Assert.False(Find(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(window).Single(b => ReferenceEquals(b.Command, export.BatchCommand));
Assert.False(batchButton.IsEnabled);
export.Presets.First(c => c.CanBatch).IsInBatch = true;
await SettleAsync(window);
Assert.True(batchButton.IsEnabled, "ticking a preset 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().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();
}
});
///
/// 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.
///
[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(window).Single(v => v.IsVisible);
Assert.True(Find(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().Single();
editor.SelectedTab = export;
await SettleAsync(window);
Assert.Equal(ExportSyncGate.Remote, editor.SyncGate);
Assert.False(Find(view).Single(c => ReferenceEquals(c.DataContext, export) && c.IsVisible).IsEnabled, "Sync: the server's renders stay there");
Assert.False(Find(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();
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []);
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\.chronos\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();
}
});
///
/// 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.
///
[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 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);
}
});
///
/// A Reorganize of this PC moves the folder of the sequence open in the editor: the editor reads it again where it is
/// now as soon as its step is done, so its frames decode and its project goes there.
///
[Test]
public Task AnOpenSequenceIsReadAgainWhereAReorganizeMovedIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var id = await app.Sample.FillEditorAsync();
var db = app.Services.Database!;
var archives = app.Services.Archives!;
var source = new LocalSequenceSource(db, id, Chronos.Core.Imaging.Decoders.DecoderFactory.CreateClient(null), null);
var content = await source.LoadAsync(CancellationToken.None);
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
await using (editor)
{
var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId))!;
var templates = new Chronos.Core.Archiving.RenameTemplates("Moved/{date}");
var plan = await archives.PlanReorganizeAsync(archive.Id, [id], templates, CancellationToken.None);
var moved = plan.Steps.Single().ToFolder;
await using var engine = new Chronos.Data.Jobs.JobEngine(db, archives.CreateJobHandlers(), new Chronos.Data.Jobs.JobEngineOptions
{
WorkerId = "test",
Kinds = [JobKind.Move],
PollInterval = TimeSpan.FromMilliseconds(50),
});
await engine.StartAsync(CancellationToken.None);
var job = await Chronos.Data.Archiving.ArchiveJobs.EnqueueAsync(engine, Chronos.Data.Archiving.ArchiveJobs.Reorganize(archive, plan, templates));
// The editor reads its photos as it opens; on Windows the folder cannot move while one is open, and the job that
// failed holds the plan for its retry.
for (var attempt = 1; ; attempt++)
{
Job? ended = null;
for (var i = 0; i < 1200 && ended is null; i++)
{
await Task.Delay(25);
if (await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } now) ended = now;
}
Assert.NotNull(ended, "the move job ends");
if (ended!.State == JobState.Done) break;
Assert.True(ended.State == JobState.Failed && attempt < 20, ended.Error);
await Task.Delay(250);
await engine.ResumeAsync(job.Id, CancellationToken.None);
}
for (var i = 0; i < 400 && editor.Session.Content.Sequence.Folder != moved; i++) await Task.Delay(25);
Assert.Equal(moved, editor.Session.Content.Sequence.Folder);
Assert.True(await source.FramesCurrentAsync(CancellationToken.None), "the editor holds the frames where they are now");
using var frame = await source.DecodeAsync(0, 32, Chronos.Core.Imaging.DecodePurpose.Thumbnail, CancellationToken.None);
Assert.NotNull(frame, "its frames decode");
}
});
///
/// 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.
///
[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(app.Window).Single(v => v.IsVisible);
var (left, right) = Span(viewport, app.Window);
var tools = Find(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();
}
});
///
/// The Camera step edits the crop box on the preview (owner review 1, R5): its mask is on by default and shows the box the
/// render fits, a drag on the picture is one undo step, a run of key presses another, the box is locked to the output
/// proportions with the offsets at 0, and a quarter turn shows the turned view frame.
///
[Test]
public Task TheCameraStepEditsTheCropBoxOnThePreview() => 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;
Assert.False(editor.ShowCropMask, "the other steps keep their mask off");
Assert.False(editor.CropEditable);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.View"), editor.PreviewToolTip);
editor.SelectedTab = editor.Tabs.OfType().Single();
Assert.True(editor.ShowCropMask, "on by default on the Camera step");
Assert.True(editor.CropEditable);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.CropEdit"), editor.PreviewToolTip);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
await SettleAsync(app.Window);
var (width, height) = (editor.Session.Content.SourceWidth, editor.Session.Content.SourceHeight);
RenderGeometry Geometry() => RenderGeometry.Create(editor.Session.Project.Camera, ExportResolver.Resolve(editor.Session.Project.Export), width, height);
static Rect RectOf(Chronos.Core.Imaging.Geometry.RectD r) => new(r.X, r.Y, r.Width, r.Height);
Assert.Equal(RectOf(Geometry().EditableCrop), editor.EditCrop, "the mask is the box the render fits");
Assert.Equal(editor.EditCrop, editor.CropRect);
var viewport = Find(app.Window).Single(v => v.IsVisible);
Assert.True(viewport.CropEditable);
Assert.Equal(editor.EditCrop, viewport.EditCrop);
Assert.Equal(editor.CropLockRatio, viewport.CropLockRatio);
Assert.Equal(editor.PreviewToolTip, viewport.ToolTip);
// The bottom-right handle dragged in: one undo step, the box locked, the offsets at 0.
Point At(double nx, double ny)
{
var (x, y) = viewport.View.ToView(nx * viewport.ImageSize.Width, ny * viewport.ImageSize.Height);
return new Point(x, y);
}
var before = editor.Session.Project.Camera;
var box = viewport.EditCrop;
viewport.Press(At(box.Right, box.Bottom));
viewport.DragTo(At(box.X + box.Width * 0.7, box.Y + box.Height * 0.7), aboutCentre: false);
Assert.Same(before, editor.Session.Project.Camera, "nothing changes while dragging");
viewport.EndDrag(commit: true);
var cropped = editor.Session.Project.Camera;
var crop = Assert.NotNull(cropped.Crop);
Assert.Approximately(0, cropped.OffsetX, 0);
Assert.Approximately(0, cropped.OffsetY, 0);
Assert.Approximately(editor.CropLockRatio, crop[2] / crop[3], 1e-9, "locked to the proportions");
Assert.Less(crop[3], box.Height);
Assert.Approximately(box.X, crop[0], 1e-9, "anchored at the opposite corner");
Assert.Equal(new Rect(crop[0], crop[1], crop[2], crop[3]), editor.EditCrop);
// Two nudges are one more step.
Assert.True(viewport.IsCropSelected, "the press took the box");
Assert.True(viewport.Nudge(Key.Right, ModifierKeys.None));
Assert.True(viewport.Nudge(Key.Down, ModifierKeys.None));
editor.Session.EndEditRun();
var nudged = Assert.NotNull(editor.Session.Project.Camera.Crop);
Assert.Approximately(crop[0] + 0.01, nudged[0], 1e-9);
Assert.Approximately(crop[1] + 0.01, nudged[1], 1e-9);
editor.UndoCommand.Execute(null);
Assert.SequenceEqual(crop, editor.Session.Project.Camera.Crop!, "one undo takes both nudges back");
editor.UndoCommand.Execute(null);
Assert.SequenceEqual(before.Crop ?? [], editor.Session.Project.Camera.Crop ?? [], "and one more the drag");
editor.RedoCommand.Execute(null);
Assert.SequenceEqual(crop, editor.Session.Project.Camera.Crop!);
// The straighten grid shows while the slider is used, on the Camera step only.
editor.IsStraightening = true;
await SettleAsync(app.Window);
Assert.True(viewport.ShowGrid);
editor.IsStraightening = false;
Assert.False(viewport.ShowGrid);
// A quarter turn: the box waits for the turned picture, then maps onto it.
var ratio = editor.CropLockRatio;
editor.Session.Edit(p => p with { Camera = p.Camera with { Rotate = 90, Crop = null } });
Assert.Equal(ratio, editor.CropLockRatio, "the box of the picture on screen until the turned one comes");
Assert.False(editor.CropEditable, "and it cannot be dragged meanwhile: it would land in the turned frame");
Assert.False(editor.CommitCropCommand.CanExecute(editor.EditCrop));
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
Assert.True(editor.CropEditable, "the turned picture is on screen");
var picture = (System.Windows.Media.Imaging.BitmapSource)editor.PreviewImage!;
Assert.Less(picture.PixelWidth, picture.PixelHeight, "the landscape source shows turned");
Assert.Equal(Geometry().LockRatio, editor.CropLockRatio);
Assert.Equal(RectOf(Geometry().EditableCrop), editor.EditCrop);
editor.UndoCommand.Execute(null);
await editor.Session.FlushAsync();
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)));
// Read-only and newer-format projects are drawn, never edited.
var content = EditorFixture.Content(EditorFixture.Sunset);
foreach (var (source, reason) in new[]
{
(new FakeSequenceSource(EditorFixture.Sunset, content) { IsReadOnly = true }, "read-only"),
(new FakeSequenceSource(EditorFixture.Sunset, content with { Project = content.Project with { Version = ProjectSettings.CurrentVersion + 1 } }), "newer format"),
})
{
var locked = new EditorViewModel(app.Shell, new EditorSession(source, source.Content, []), [], EncoderHost.Client);
await using (locked)
{
locked.SelectedTab = locked.Tabs.OfType().Single();
Assert.True(locked.ShowCropMask, reason);
Assert.False(locked.CropEditable, reason);
Assert.False(locked.CommitCropCommand.CanExecute(new Rect(0.1, 0.1, 0.5, 0.5)), reason);
Assert.Equal(Loc.L("Tooltips.Editor.Preview.View"), locked.PreviewToolTip);
}
}
}
finally
{
await app.Shell.Sequence.CloseAsync();
}
});
///
/// 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).
///
[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(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();
}
});
///
/// 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).
///
[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(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();
}
});
/// The width needs in the font, numerals and formatting of .
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;
}
/// The left and right edges of an element in window coordinates, whichever way the window reads.
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));
}
/// The measuring tool of each section has content.
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(view).Any(i => i.DataContext is AnalysisFinding && i.IsVisible)
|| Find(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(view).Where(i => i.DataContext is FrameRow && i.IsVisible));
break;
case CameraTab or TimeTab:
Assert.NotEmpty(Find(view).Where(c => c.IsVisible && c.ActualHeight > 50));
break;
case ExportTab export:
Assert.NotEmpty(export.Presets);
Assert.NotEmpty(Find(view).Where(b => b.DataContext is PresetRow && b.IsVisible));
Assert.True(export.Presets.Any(c => c.EstimatedSize is not null), "estimates in the preset table");
break;
default:
var chart = Find(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();
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 Find(DependencyObject root)
where T : DependencyObject
{
var found = new List();
var stack = new Stack([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;
}
/// Dialogs that answer like a user who cancels everything.
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> signIn) => false;
}
}