Files
Chronos/tests/Chronos.App.Tests/Editor/RenderMenuTests.cs
T
Alby96andClaude Opus 5.5 728ffa35cb
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder.

Closes #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-05 09:18:40 +01:00

302 lines
17 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.Text.Json;
using Chronos.App.Editor;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
using Chronos.Data.Archiving.Jobs;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Visuals;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// The editor's Render ▾ menu (owner review 1, R3, decisions 1, 2 and 12): grouped presets with the current one checked,
/// recent presets from the render history, Save frame and why it waits, still jobs, the Render tooltip.
/// </summary>
public sealed class RenderMenuTests
{
private static readonly RelayCommand Select = new(_ => { });
[Test]
public void TheMenuPutsTheCurrentTheRecommendedTheBatchAndTheRecentPresetsFirstAndGroupsTheRest()
{
var menu = RenderMenu.Build(new RenderMenuState
{
CurrentPresetId = "4k-hevc",
BasePresetId = "4k-hevc",
RecommendedPresetId = "4k-hevc10-archive",
Batch = ["1080p-h264", "4k-hevc10-archive"],
Recent = ["vertical-1080x1920", "1080p-h264", "gif-preview", "apng", "png-sequence"],
Details = p => p.Id + " details",
SelectPreset = Select,
});
// The current preset, listed by no section, comes first and is the one checked.
Assert.Equal("preset:4k-hevc", menu[0].Id);
Assert.True(menu[0].IsChecked);
Assert.Equal(Loc.L("Export.Preset.4kHevc"), menu[0].Label);
Assert.Equal("4k-hevc details", menu[0].Details);
Assert.Same(Select, menu[0].Command);
Assert.Equal("4k-hevc", menu[0].CommandParameter);
Assert.Count(1, menu.SelectMany(m => m.Flatten()).Where(m => m.IsChecked));
var top = menu.TakeWhile(m => m.Kind != RenderMenuItemKind.Submenu).ToList();
Assert.SequenceEqual(
[
"preset:4k-hevc", Loc.L("Editor.RenderMenu.Recommended"), "preset:4k-hevc10-archive", Loc.L("Export.Footer.Batch", 2), "preset:1080p-h264",
Loc.L("Editor.RenderMenu.Recent"), "preset:vertical-1080x1920", "preset:gif-preview", "preset:apng",
], top.Select(m => m.Id ?? m.Label).ToList());
Assert.True(top.Where(m => m.Kind == RenderMenuItemKind.Header).All(h => h.Command is null), "headers are titles");
Assert.Contains(Loc.L("Tooltips.Editor.RenderMenu.Recommended"), top[2].ToolTip!);
Assert.Contains(Loc.L("Tooltips.Editor.RenderMenu.Recent"), top[6].ToolTip!);
// Other presets ›: every preset not listed above, under its group's title, the groups in the Export step's order.
var other = Assert.Contains(menu, m => m.Id == "other");
Assert.Equal(RenderMenuItemKind.Submenu, other.Kind);
var headers = other.Children.Where(c => c.Kind == RenderMenuItemKind.Header).Select(c => c.Label).ToList();
Assert.SequenceEqual([.. new[] { "video", "social", "intermediate", "sequence" }.Select(RenderMenu.GroupLabel)], headers,
"the Web group, both of its presets already listed above, has no title of its own");
var listed = menu.SelectMany(m => m.Flatten()).Where(m => m.Kind == RenderMenuItemKind.Preset).Select(m => (string)m.CommandParameter!).ToList();
Assert.Equal(ExportPresets.BuiltIn.Count, listed.Count, "every preset once");
Assert.Equal(ExportPresets.BuiltIn.Count, listed.Distinct().Count());
Assert.True(menu.SelectMany(m => m.Flatten()).All(m => m.Kind is RenderMenuItemKind.Header or RenderMenuItemKind.Separator || m.ToolTip is { Length: > 0 }),
"every entry that does something has a tooltip");
// The lower part, in its order.
Assert.SequenceEqual(["batch", "queue", "frame", "videos"], menu.SkipWhile(m => m.Kind != RenderMenuItemKind.Separator).Skip(1).Select(m => m.Id!).ToList());
Assert.Equal(Loc.L("Editor.RenderMenu.Batch", 2), Assert.Contains(menu, m => m.Id == "batch").Label);
}
[Test]
public void APresetAlreadyRecommendedIsNotListedAgainAndACustomExportChecksNone()
{
var menu = RenderMenu.Build(new RenderMenuState
{
CurrentPresetId = null,
BasePresetId = "4k-hevc10-archive",
RecommendedPresetId = "4k-hevc10-archive",
Recent = ["4k-hevc10-archive"],
});
Assert.Equal(RenderMenuItemKind.Header, menu[0].Kind, "the base preset is the recommended one: no separate first entry");
Assert.Count(1, menu.SelectMany(m => m.Flatten()).Where(m => m.Id == "preset:4k-hevc10-archive"));
Assert.False(menu.SelectMany(m => m.Flatten()).Any(m => m.IsChecked), "Custom values match no preset");
Assert.False(menu.Any(m => m.Label == Loc.L("Editor.RenderMenu.Recent")), "no recent preset left to show");
}
[Test]
public void ThePresetDetailsFollowTheChosenProportions()
{
var portrait = new CameraSettings { Aspect = new Auto<string>().WithManual("9:16") };
Assert.Equal(Loc.L("Editor.RenderMenu.Details", "2160×3840", Loc.L("Export.Codec.HevcMain10"), Loc.L("Editor.Value.Fps", "24")),
RenderMenu.PresetDetails(new ExportSettings(), "4k-hevc10-archive", portrait, 6000, 4000));
Assert.True(RenderMenu.PresetDetails(new ExportSettings(), "png-sequence", new CameraSettings(), 6000, 4000).StartsWith("6000×4000", StringComparison.Ordinal),
"an image sequence keeps the source's size");
Assert.True(RenderMenu.PresetDetails(new ExportSettings(), "png-sequence", new CameraSettings(), 0, 0).StartsWith(Loc.L("Export.Resolution.Source"), StringComparison.Ordinal));
}
[Test]
public void RecentPresetsComeFromTheRenderHistoryNewestFirst()
{
var sequence = Guid.CreateVersion7();
var settings = new ProjectSettings { Export = new ExportSettings { Preset = new Auto<string>().WithManual("4k-h264") } }.ToJson();
var custom = new ProjectSettings { Export = new ExportSettings { Preset = new Auto<string>().WithManual("4k-h264"), Overrides = new ExportOverrides { BitRate = 1 } } }.ToJson();
IReadOnlyList<Render> renders =
[
Render(sequence, "whatever", settings),
Render(sequence, Loc.L("Export.Preset.Png"), null) with { Kind = RenderKind.Still },
Render(sequence, Loc.L("Export.Preset.1080pShare"), null),
Render(sequence, "Custom", custom),
Render(sequence, Loc.L("Export.Preset.4kH264"), settings),
Render(sequence, Loc.L("Export.Preset.Gif"), "{not json"),
Render(sequence, Loc.L("Export.Preset.Vertical"), null),
];
Assert.SequenceEqual(["4k-h264", "1080p-h264", "gif-preview"], [.. RenderMenu.RecentPresets(renders)],
"settings first, else the name; a saved frame, a custom export and a repeat do not count; three at most");
Assert.Null(RenderMenu.PresetOf(Render(sequence, "Custom", custom)));
}
[Test]
public void SaveFrameWaitsWithTheReason()
{
Assert.Equal(Loc.L("Tooltips.Export.StillReadOnly"), RenderMenu.SaveFrameBlockedReason(false, null, readOnly: true, hasFrame: true, true, null, null));
Assert.Equal(Loc.L("Tooltips.Export.StillNeedsFrame"), RenderMenu.SaveFrameBlockedReason(false, null, false, hasFrame: false, true, null, null));
Assert.Equal(Loc.L("Tooltips.Editor.Outdated", "Studio NAS"), RenderMenu.SaveFrameBlockedReason(outdated: true, "Studio NAS", true, false, true, null, null), "out of date first");
var older = ServerJobs.StillNeedsNewerServer(serverFormat: 2);
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), older);
Assert.Null(ServerJobs.StillNeedsNewerServer(RenderRules.StillFormat), "a format-3 server takes still jobs");
Assert.Equal(older, RenderMenu.SaveFrameBlockedReason(false, "Studio NAS", false, true, true, older, null));
Assert.Equal(Loc.L("Tooltips.Editor.Render.NameError", "bad"), RenderMenu.SaveFrameBlockedReason(false, null, false, true, true, null, "bad"));
Assert.Equal(Loc.L("Tooltips.Export.StillWorkspace"), RenderMenu.SaveFrameBlockedReason(false, null, false, true, sourceSavesFrames: false, null, null),
"a source that renders elsewhere without still jobs of its own");
Assert.Null(RenderMenu.SaveFrameBlockedReason(false, null, false, true, true, null, null));
// In the menu: Save frame › and its formats are disabled and say why.
var menu = RenderMenu.Build(new RenderMenuState { SaveFrameBlocked = older });
var frame = Assert.Contains(menu, m => m.Id == "frame");
Assert.False(frame.IsEnabled);
Assert.Equal(older, frame.ToolTip);
Assert.SequenceEqual(["frame:pngsequence", "frame:jpegsequence", "frame:tiff16sequence"], [.. frame.Children.Select(c => c.Id!)]);
Assert.True(frame.Children.All(c => !c.IsEnabled && c.ToolTip == older));
Assert.SequenceEqual(["PNG", "JPEG", Loc.L("Export.Codec.Tiff16Sequence")], [.. frame.Children.Select(c => c.Label)]);
var ready = Assert.Contains(RenderMenu.Build(new RenderMenuState()), m => m.Id == "frame");
Assert.True(ready.IsEnabled);
Assert.Equal(VideoCodec.JpegSequence, ready.Children[1].CommandParameter);
Assert.Equal(Loc.L("Tooltips.Editor.RenderMenu.SaveFormat", "JPEG"), ready.Children[1].ToolTip);
}
[Test]
public void APlaybackExportNeedsAFormatThreeServer()
{
var playback = new ExportSettings { Playback = new PlaybackSettings { Direction = PlaybackDirection.Boomerang } };
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), ServerJobs.RenderNeedsNewerServer(new ProjectSettings(), playback, 6000, 4000, serverFormat: 2));
Assert.Null(ServerJobs.RenderNeedsNewerServer(new ProjectSettings(), playback, 6000, 4000, serverFormat: 3));
Assert.Null(ServerJobs.RenderNeedsNewerServer(new ProjectSettings(), new ExportSettings(), 6000, 4000, serverFormat: 1), "no playback: format 1");
// The format is read from the export rendered, not from the project's own export.
Assert.NotNull(ServerJobs.RenderNeedsNewerServer(new ProjectSettings { Export = new ExportSettings() }, playback, 6000, 4000, serverFormat: 2));
}
[Test]
public async Task AStillJobCarriesTheFrameAndItsPhoto()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
content = content with { Frames = [.. content.Frames.Select((f, i) => f with { Sha256 = $"{i:X64}" })] };
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
await using var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.3 } });
Assert.True(session.CanSaveFrames);
var export = session.Project.Export with { Playback = new PlaybackSettings { Direction = PlaybackDirection.Reverse }, Batch = ["1080p-h264"] };
var request = Assert.Contains(Assert.NotNull(session.StillRequests(export, VideoCodec.PngSequence, 5)), _ => true);
Assert.Equal(JobKind.Render, request.Kind);
Assert.SequenceEqual([content.Sequence.Id], [.. request.Targets]);
var parameters = Assert.NotNull(JsonSerializer.Deserialize(request.ParametersJson!, ProtocolJson.Default.RenderJobParameters));
Assert.Equal(5, parameters.StillFrame);
Assert.Equal($"{5:x64}", parameters.StillPhoto, "the photo's hash, lower case");
Assert.True(parameters.IsStill);
Assert.GreaterOrEqual(parameters.RequiredSettingsFormat, RenderRules.StillFormat, "an older node never claims it");
Assert.Equal("pngsequence", parameters.Codec);
Assert.Equal(0.3, ProjectSettings.FromJson(parameters.SettingsJson!).Exposure.ExposureOffsetEv, "the project as the editor holds it");
Assert.Throws<ArgumentOutOfRangeException>(() => session.StillRequests(export, VideoCodec.PngSequence, content.Count));
// A server sequence: one job too.
var remote = new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = true };
await using var remoteSession = new EditorSession(remote, content, [], TimeSpan.FromMilliseconds(20));
Assert.Count(1, Assert.NotNull(remoteSession.StillRequests(export, VideoCodec.Tiff16Sequence, 0)));
}
[Test]
public async Task AWorkspaceProjectSavesNoFrameUntilItMakesItsOwnStillJobs()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var fake = new FakeSequenceSource(EditorFixture.Sunset, content);
await using (var session = new EditorSession(new HomeRenders(fake), content, [], TimeSpan.FromMilliseconds(20)))
{
Assert.False(session.CanSaveFrames);
Assert.Null(session.StillRequests(session.Project.Export, VideoCodec.PngSequence, 0));
}
var stills = new HomeStills(fake);
await using (var session = new EditorSession(stills, content, [], TimeSpan.FromMilliseconds(20)))
{
Assert.True(session.CanSaveFrames);
Assert.Count(1, Assert.NotNull(session.StillRequests(session.Project.Export, VideoCodec.JpegSequence, 3)));
Assert.Equal((VideoCodec.JpegSequence, 3), stills.Asked);
}
}
[Test]
public void TheRenderTooltipGivesThePresetTheSizeTheCodecAndTheEstimates()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var plan = Assert.NotNull(new ExportPlanner(content, [], EncoderHost.Client).Plan(content.Project with
{
Export = new ExportSettings { Preset = new Auto<string>().WithManual("4k-hevc10-archive") },
}));
var tip = RenderMenu.RenderToolTip(plan, null, null);
var (width, height) = plan.EncodedSize;
Assert.Contains(plan.PresetName, tip);
Assert.Contains(EditorText.Size(width, height), tip);
Assert.Contains(Loc.L("Export.Codec.HevcMain10"), tip);
Assert.Contains("Ctrl+R", tip);
var blocked = RenderMenu.RenderToolTip(plan, "Fix it first", "Studio NAS");
Assert.True(blocked.StartsWith("Fix it first" + Environment.NewLine, StringComparison.Ordinal), "the reason comes first");
Assert.False(blocked.Contains(Loc.L("Tooltips.Editor.RenderServer", "Studio NAS"), StringComparison.Ordinal));
Assert.True(RenderMenu.RenderToolTip(plan, null, "Studio NAS").EndsWith(Loc.L("Tooltips.Editor.RenderServer", "Studio NAS"), StringComparison.Ordinal));
Assert.Equal("Planning", RenderMenu.RenderToolTip(null, "Planning", null));
}
private static Render Render(Guid sequence, string presetName, string? settings) => new()
{
Id = Guid.CreateVersion7(),
SequenceId = sequence,
PresetName = presetName,
SettingsJson = settings,
OutputPath = "C:/out/" + presetName,
};
/// <summary>A source that renders at a home of its own (as a workspace project), delegating the rest.</summary>
private class HomeRenders(FakeSequenceSource inner) : ISequenceSource, IProjectRenders
{
public bool IsRemote => inner.IsRemote;
public bool IsReadOnly => inner.IsReadOnly;
public bool IsOutdated => inner.IsOutdated;
public bool RendersLocally => false;
public event Action? ReadOnlyChanged
{
add => inner.ReadOnlyChanged += value;
remove => inner.ReadOnlyChanged -= value;
}
public event Action<Job>? JobChanged
{
add => inner.JobChanged += value;
remove => inner.JobChanged -= value;
}
public IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight) => [];
public Task<SequenceContent> LoadAsync(CancellationToken cancellationToken) => inner.LoadAsync(cancellationToken);
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken) => inner.FramesCurrentAsync(cancellationToken);
public ValueTask<Core.Imaging.ImageBuffer?> DecodeAsync(int index, int maxLongEdge, Core.Imaging.DecodePurpose purpose, CancellationToken cancellationToken) =>
inner.DecodeAsync(index, maxLongEdge, purpose, cancellationToken);
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken) =>
inner.SaveProjectAsync(project, basis, cancellationToken);
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) => inner.SubmitAsync(request, cancellationToken);
public Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) => inner.ListJobsAsync(cancellationToken);
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => inner.CancelJobAsync(jobId, cancellationToken);
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => inner.RetryJobAsync(jobId, cancellationToken);
public ValueTask DisposeAsync() => inner.DisposeAsync();
}
/// <summary>A home-rendering source that makes its own still jobs.</summary>
private sealed class HomeStills(FakeSequenceSource inner) : HomeRenders(inner), IProjectStills
{
public (VideoCodec Codec, int Frame)? Asked { get; private set; }
public IReadOnlyList<ArchiveJobRequest> StillRequests(Sequence sequence, ProjectSettings project, ExportSettings export, VideoCodec codec, int frameIndex,
string? photoSha256, int sourceWidth, int sourceHeight)
{
Asked = (codec, frameIndex);
return [new ArchiveJobRequest(JobKind.Render, [sequence.Id], "still", null, JobPriority.User)];
}
}
}