merge: phase 5 parcel P5

This commit is contained in:
Alby96 committed 2026-11-05 02:29:44 +01:00
commit 18cb8c88c0
9 files changed
+1137 -29

No files matched your search

+40
View File
@@ -2,6 +2,7 @@ using Chronos.Core.Advice;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Core.Video;
@@ -263,6 +264,34 @@ public sealed class EditorSession : IAsyncDisposable
_ => [RenderRequest(export)],
};
/// <summary>
/// A source can save one frame as an image (owner review 1, R8, "Save frame"): a sequence of this PC or of a server, or a
/// source that makes its own still jobs (<see cref="IProjectStills"/>). A workspace project renders at its home with
/// its portable settings (<see cref="IProjectRenders"/>) and saves no frame until it makes still jobs of its own.
/// </summary>
public bool CanSaveFrames => Source is IProjectStills or not IProjectRenders;
/// <summary>
/// The job that saves frame <paramref name="frameIndex"/> as one <paramref name="codec"/> image (one of
/// <see cref="RenderRules.StillCodecs"/>) at the output size of <paramref name="export"/>, with every correction of the
/// project as it is now and no playback (<see cref="ProcessingJobs.Still"/>): routed as <see cref="RenderRequests"/> is,
/// on this PC's engine or on the server, as one job. The frame is named by its position and by its photo, whose hash
/// wins when frames moved meanwhile. Null when the source saves no frames (<see cref="CanSaveFrames"/>).
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="frameIndex"/> is not a frame of the sequence, or <paramref name="codec"/> is no still format.</exception>
public IReadOnlyList<ArchiveJobRequest>? StillRequests(ExportSettings export, VideoCodec codec, int frameIndex)
{
ArgumentNullException.ThrowIfNull(export);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)frameIndex, (uint)Content.Count, nameof(frameIndex));
var photo = Content.Frames[frameIndex].Sha256;
return Source switch
{
IProjectStills stills => stills.StillRequests(Content.Sequence, Project, export, codec, frameIndex, photo, Content.SourceWidth, Content.SourceHeight),
IProjectRenders => null,
_ => [ProcessingJobs.Still(Content.Sequence, export, codec, frameIndex, photo, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })],
};
}
/// <summary>
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
/// </summary>
@@ -608,6 +637,17 @@ public sealed class EditorSession : IAsyncDisposable
}
}
/// <summary>
/// A source whose saved frames are made otherwise than from the project as the editor holds it (as <see cref="IProjectRenders"/>
/// for renders): a workspace project would name the frame and its settings as its home reads them.
/// </summary>
public interface IProjectStills
{
/// <summary>The jobs that save frame <paramref name="frameIndex"/> (photo <paramref name="photoSha256"/>) of <paramref name="project"/> with <paramref name="export"/>.</summary>
IReadOnlyList<ArchiveJobRequest> StillRequests(Sequence sequence, ProjectSettings project, ExportSettings export, VideoCodec codec, int frameIndex, string? photoSha256,
int sourceWidth, int sourceHeight);
}
/// <summary>
/// A "Save both" copy made the project (<see cref="EditorSession.RestoreAsync"/>). Its Undo brings back the project from
/// before as a new step, and only while the restore is still the last change: after another edit, an undo or a merged
+138 -12
View File
@@ -49,6 +49,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private readonly SequenceJobs _jobs;
private readonly AsyncRelayCommand _analyse;
private readonly AsyncRelayCommand _render;
private readonly AsyncRelayCommand _renderBatch;
private readonly AsyncRelayCommand _addToQueue;
private readonly AsyncRelayCommand _saveFrame;
private readonly AsyncRelayCommand _cancelServerJob;
private PreviewRenderer _renderer;
private int _currentIndex;
@@ -117,10 +120,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
_player = new DispatcherTimer(DispatcherPriority.Background, _dispatcher);
_player.Tick += (_, _) => Advance();
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsLocked && !IsAnalysing);
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsLocked);
_render = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: false), () => CanRender);
_renderBatch = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: true), () => CanRender && RenderMenu.BatchPresets(RenderExport).Count > 0);
_addToQueue = new AsyncRelayCommand(() => RenderAsync(JobPriority.Normal, batch: false), () => CanRender);
_saveFrame = new AsyncRelayCommand((p, _) => SaveFrameAsync(p), p => p is VideoCodec codec && RenderRules.StillCodecs.Contains(codec) && SaveFrameBlockedReason is null);
SelectPresetCommand = new RelayCommand(p =>
{
if (p is string id) SelectedRenderChoice = RenderChoices.FirstOrDefault(c => string.Equals((string)c.Value, id, StringComparison.OrdinalIgnoreCase));
});
ShowVideosCommand = new RelayCommand(ShowVideos, () => VideosSection is not null);
_cancelServerJob = new AsyncRelayCommand(CancelServerJobAsync, () => ServerJob is not null);
UndoCommand = new RelayCommand(() => Session.Undo(), () => !IsLocked && Session.History.CanUndo);
RedoCommand = new RelayCommand(() => Session.Redo(), () => !IsLocked && Session.History.CanRedo);
@@ -141,7 +153,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Analysis = new AnalysisTab(this);
Frames = new FramesTab(this);
Exposure = new ExposureTab(this);
Tabs = [Analysis, Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
Export = new ExportTab(this);
Tabs = [Analysis, Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), Export];
for (var i = 0; i < Tabs.Count; i++)
{
Tabs[i].Number = i + 1;
@@ -154,7 +167,6 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
_currentFrameId = FrameId(_currentIndex);
// Until the link is read (AttachJobsAsync), a sequence of this PC cannot send its renders.
_syncGate = session.IsRemote ? ExportSyncGate.Remote : ExportSyncGate.SignedOut;
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
_shownOrientation = OrientationOf(session.Project.Camera);
UpdateCropBox();
@@ -272,6 +284,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
public ExposureTab Exposure { get; }
/// <summary>The last step; the project ▾ menu's "Save project file" is its command (owner review 1, R3).</summary>
public ExportTab Export { get; }
/// <summary>The steps of the Edit path, in order (owner review 1, R7).</summary>
public IReadOnlyList<EditorTab> Tabs { get; }
@@ -624,29 +639,107 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
? Session.ExportFor(id) with { Batch = Session.Project.Export.Batch }
: Session.Project.Export;
/// <summary>"Render · 4K archive".</summary>
public string RenderText => Loc.L("Editor.Render", Plan?.PresetName ?? string.Empty);
/// <summary>"Render" whatever the preset (owner review 1, R3, decision 1): the header keeps its width; the tooltip and the menu's check say which.</summary>
public string RenderText => Loc.L("Editor.RenderButton");
public string RenderToolTip => RenderBlockedReason ?? (IsRemote ? Loc.L("Tooltips.Editor.RenderServer", ServerName) : Loc.L("Tooltips.Editor.Render"));
/// <summary>Why Render waits, then what it renders: preset, size, codec, frame rate, estimated size and time (<see cref="RenderMenu.RenderToolTip"/>).</summary>
public string RenderToolTip => RenderMenu.RenderToolTip(Plan, RenderBlockedReason, IsRemote ? ServerName : null);
/// <summary>The ▾ part of Render: another preset for the project, or only for this render when the project cannot change.</summary>
public string RenderChoiceToolTip => Loc.L(IsReadOnly ? "Tooltips.Editor.RenderChoiceReadOnly" : "Tooltips.Editor.RenderChoice");
/// <summary>
/// The Render ▾ menu (<see cref="RenderMenu"/>): made again whenever it is read, so the menu, which reads it each time it
/// opens, shows the presets, the batch, the history and the reasons as they are then.
/// </summary>
public IReadOnlyList<RenderMenuItem> RenderMenuItems
{
get
{
var export = RenderExport;
var batch = RenderMenu.BatchPresets(export);
var (camera, width, height) = (Session.Project.Camera, Session.Content.SourceWidth, Session.Content.SourceHeight);
return RenderMenu.Build(new RenderMenuState
{
CurrentPresetId = RenderPresetId(basis: false),
BasePresetId = RenderPresetId(basis: true),
RecommendedPresetId = Session.Advice.Find(AdvisorParameters.ExportPreset)?.Value as string,
Batch = batch,
Recent = RenderMenu.RecentPresets(Session.Content.Renders),
Details = preset => RenderMenu.PresetDetails(export, preset.Id, camera, width, height),
SelectPreset = SelectPresetCommand,
RenderBatch = _renderBatch,
RenderBatchToolTip = RenderBlockedReason,
AddToQueue = _addToQueue,
AddToQueueToolTip = RenderBlockedReason,
SaveFrame = _saveFrame,
SaveFrameBlocked = SaveFrameBlockedReason,
ShowVideos = ShowVideosCommand,
});
}
}
/// <summary>Chooses the preset Render renders (<see cref="SelectedRenderChoice"/>); its parameter is the preset id.</summary>
public ICommand SelectPresetCommand { get; }
/// <summary>Render batch (n): the export and each preset of its batch.</summary>
public ICommand RenderBatchCommand => _renderBatch;
/// <summary>Add to queue: the render at a normal priority, the editing goes on.</summary>
public ICommand AddToQueueCommand => _addToQueue;
/// <summary>Save frame › PNG, JPEG or TIFF 16-bit (decision 12); its parameter is the <see cref="VideoCodec"/>.</summary>
public ICommand SaveFrameCommand => _saveFrame;
/// <summary>The videos of this sequence (decision 20); disabled until this Chronos has a Videos section.</summary>
public ICommand ShowVideosCommand { get; }
/// <summary>
/// Why the frame under the cursor cannot be saved now (<see cref="RenderMenu.SaveFrameBlockedReason"/>): out of date or
/// read-only, no frame the render keeps under the cursor, a workspace project, no right to render on the server or a
/// server too old for still jobs (format 3), a wrong file name; null when it can.
/// </summary>
public string? SaveFrameBlockedReason
{
get
{
var hasFrame = FrameCount > 0 && !Session.Project.ExcludedFrames.Contains(CurrentIndex) && !Session.Content.NotRenderable().Contains(CurrentIndex);
string? server = null;
if (IsRemote && Session.CanSaveFrames)
{
var sync = Shell.Services.Sync;
server = !sync.CanRender ? Loc.L("Tooltips.Editor.Render.NoRight", ServerName)
: ServerJobs.StillNeedsNewerServer(sync.SettingsFormat)
?? ServerJobs.RenderNeedsNewerServer(Session.Project, RenderExport, Session.Content.SourceWidth, Session.Content.SourceHeight, sync.SettingsFormat);
}
return RenderMenu.SaveFrameBlockedReason(IsOutdated, ServerName, IsReadOnly, hasFrame, Session.CanSaveFrames, server, Plan?.NameError);
}
}
public bool CanRender => RenderBlockedReason is null;
/// <summary>The settings format a render of <see cref="RenderExport"/> needs (<see cref="Chronos.Data.Processing.ProcessingJobs.RequiredFormat"/>).</summary>
private int RenderFormat =>
Chronos.Data.Processing.ProcessingJobs.RequiredFormat(Session.Project, RenderExport, Session.Content.SourceWidth, Session.Content.SourceHeight);
/// <summary>
/// The preset Render renders (<paramref name="basis"/>: the one its values start from, a custom export's included), as
/// chosen for this render in a read-only session, else as planned, else as the project names it.
/// </summary>
private string? RenderPresetId(bool basis) =>
(IsReadOnly ? _renderPreset : null) ?? (basis ? Plan?.Export.BasePresetId : Plan?.Export.PresetId) ?? EditorSettings.ExportPreset.Effective(Session.Project, null);
/// <summary>The Videos section of this Chronos (owner review 1, R9; P7 adds it); null while there is none.</summary>
private SectionKey? VideosSection =>
Enum.TryParse<SectionKey>("Videos", out var key) && Shell.AllSections.Any(s => s.Key == key) ? key : null;
/// <summary>Why the project's export cannot be rendered now, localised; null when it can.</summary>
public string? RenderBlockedReason => Plan switch
{
_ when IsRemote && !Shell.Services.Sync.CanRender => Loc.L("Tooltips.Editor.Render.NoRight", ServerName),
// Settings or proportions the server would render otherwise (owner review 1, phase 4: an older server, Send and render too).
// A workspace project rendered on this PC from its originals (phase 5c) renders with this PC's engine: the server's
// format does not decide (sending its version home is held by the workspace's own gate).
// Settings or proportions the server would render otherwise (owner review 1, phase 4: an older server, Send and render too;
// phase 5: playback needs format 3, read from the export rendered). A workspace project rendered on this PC from its
// originals (phase 5c) renders with this PC's engine: the server's format does not decide (sending its version home is
// held by the workspace's own gate).
_ when IsRemote && Session.Source is not IProjectRenders { RendersLocally: true }
&& ServerJobs.NeedsNewerServer(RenderFormat, Shell.Services.Sync.SettingsFormat) is { } newer => newer,
&& ServerJobs.RenderNeedsNewerServer(Session.Project, RenderExport, Session.Content.SourceWidth, Session.Content.SourceHeight,
Shell.Services.Sync.SettingsFormat) is { } newer => newer,
_ when IsOutdated => Loc.L("Tooltips.Editor.Outdated", ServerName),
null when _planned => Loc.L("Tooltips.Editor.Render.NoSource"),
null => Loc.L("Tooltips.Editor.Render.Planning"),
@@ -732,11 +825,42 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
/// <summary>
/// "Save frame ›" (owner review 1, R8, decision 12): queues the frame under the cursor as one <paramref name="parameter"/>
/// image (a <see cref="VideoCodec"/> of <see cref="RenderRules.StillCodecs"/>) at the export's output size, with every
/// correction and no playback; on this PC's engine, or as one server job for a server sequence. The frame is the one on
/// screen wherever frames read again before the job put it.
/// </summary>
public async Task SaveFrameAsync(object? parameter)
{
if (parameter is not VideoCodec codec || !RenderRules.StillCodecs.Contains(codec) || SaveFrameBlockedReason is not null) return;
var frame = _currentFrameId;
await Session.EnsureFramesAsync();
if (IsOutdated || IndexOfFrame(frame) is not { } index) return;
if (Session.StillRequests(RenderExport with { Batch = [] }, codec, index) is not [_, ..] requests) return;
foreach (var request in requests) await Session.SubmitAsync(request);
var label = requests[0].Label + Loc.Separator + EditorText.Position(index, FrameCount);
if (IsRemote) Shell.Notify(Loc.L("Editor.Still.Queued"), label);
else Shell.Notify(Loc.L("Editor.Still.Queued"), label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
/// <summary>
/// The videos of this sequence (Render ▾ › Videos). Until the Videos section takes a sequence filter (P7), it opens the
/// section as it is.
/// </summary>
private void ShowVideos()
{
if (VideosSection is { } key) Shell.Navigate(key);
}
/// <summary>Re-reads the enabled state of every command (the async ones keep their own event).</summary>
public void RefreshCommands()
{
_analyse.RaiseCanExecuteChanged();
_render.RaiseCanExecuteChanged();
_renderBatch.RaiseCanExecuteChanged();
_addToQueue.RaiseCanExecuteChanged();
_saveFrame.RaiseCanExecuteChanged();
_cancelServerJob.RaiseCanExecuteChanged();
foreach (var tab in Tabs) tab.RefreshCommands();
CommandManager.InvalidateRequerySuggested();
@@ -1523,6 +1647,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
OnPropertyChanged(nameof(RenderToolTip));
OnPropertyChanged(nameof(RenderBlockedReason));
OnPropertyChanged(nameof(CanRender));
OnPropertyChanged(nameof(SaveFrameBlockedReason));
OnPropertyChanged(nameof(RenderMenuItems));
}
/// <summary>A rendered preview as frozen bitmaps and overlays in picture pixels (built off the UI thread).</summary>
+308
View File
@@ -0,0 +1,308 @@
using System.IO;
using System.Text.Json;
using System.Windows.Input;
using Chronos.App.Infrastructure;
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.Ui.Visuals;
namespace Chronos.App.Editor;
/// <summary>
/// What the editor's Render ▾ menu is made from (owner review 1, R3, decision 2): the presets to put first, the commands
/// of its lower part and why Save frame waits, when it does.
/// </summary>
public sealed record RenderMenuState
{
/// <summary>The preset the export renders (checked); null for values that match no preset ("Custom").</summary>
public string? CurrentPresetId { get; init; }
/// <summary>The preset the export starts from (Custom included): listed at the top when no section below lists it.</summary>
public string? BasePresetId { get; init; }
/// <summary>The advisor's pick for this sequence; null when it has none.</summary>
public string? RecommendedPresetId { get; init; }
/// <summary>The export's batch presets besides its own (<see cref="RenderMenu.BatchPresets"/>).</summary>
public IReadOnlyList<string> Batch { get; init; } = [];
/// <summary>Presets the sequence was rendered with, newest first (<see cref="RenderMenu.RecentPresets"/>).</summary>
public IReadOnlyList<string> Recent { get; init; } = [];
/// <summary>The details line of a preset: "3840×2160 · HEVC Main10 · 24 fps" (<see cref="RenderMenu.PresetDetails"/>).</summary>
public Func<ExportPreset, string> Details { get; init; } = _ => string.Empty;
/// <summary>Chooses a preset; its parameter is the preset id.</summary>
public ICommand? SelectPreset { get; init; }
public ICommand? RenderBatch { get; init; }
/// <summary>Why Render batch waits; null shows what it does.</summary>
public string? RenderBatchToolTip { get; init; }
public ICommand? AddToQueue { get; init; }
/// <summary>Why Add to queue waits; null shows what it does.</summary>
public string? AddToQueueToolTip { get; init; }
/// <summary>Saves the frame under the cursor; its parameter is one of <see cref="RenderRules.StillCodecs"/>.</summary>
public ICommand? SaveFrame { get; init; }
/// <summary>Why no frame can be saved now (<see cref="RenderMenu.SaveFrameBlockedReason"/>); null when one can.</summary>
public string? SaveFrameBlocked { get; init; }
/// <summary>Opens the videos of this sequence.</summary>
public ICommand? ShowVideos { get; init; }
}
/// <summary>
/// The editor's Render ▾ menu (owner review 1, R3, decisions 1 and 2): short and structured instead of every preset in a
/// row. In order: the current preset when no section lists it, the advisor's pick, the batch presets, up to three presets
/// this sequence was rendered with, "Other presets ›" grouped as the Export step groups them; then Render batch (n), Add to
/// queue, Save frame › (PNG, JPEG, TIFF 16-bit) and the videos of the sequence. Each preset reads as two lines, its name
/// and a muted "size · codec · fps"; estimates stay out of the menu (they cost a plan per preset) and live in the Render
/// button's tooltip (<see cref="RenderToolTip"/>). Every entry has a tooltip; a disabled one says why.
/// </summary>
public static class RenderMenu
{
/// <summary>The presets of the render history the menu puts first, at most.</summary>
public const int RecentCount = 3;
/// <summary>The preset groups in the order the menu and the Export step list them; another group follows them.</summary>
public static IReadOnlyList<string> GroupOrder { get; } = ["video", "social", "intermediate", "sequence", "web"];
/// <summary>The menu for <paramref name="state"/>.</summary>
public static IReadOnlyList<RenderMenuItem> Build(RenderMenuState state)
{
ArgumentNullException.ThrowIfNull(state);
var shown = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var recommended = Find(state.RecommendedPresetId);
var batch = state.Batch.Select(Find).OfType<ExportPreset>().Where(p => !Same(p, recommended)).DistinctBy(p => p.Id).ToList();
var recent = state.Recent.Select(Find).OfType<ExportPreset>().Where(p => !Same(p, recommended) && !batch.Contains(p)).DistinctBy(p => p.Id)
.Take(RecentCount).ToList();
var items = new List<RenderMenuItem>();
if (Find(state.BasePresetId) is { } current && !Same(current, recommended) && !batch.Contains(current) && !recent.Contains(current))
items.Add(Preset(current, null));
if (recommended is not null)
{
items.Add(RenderMenuItem.Header(Loc.L("Editor.RenderMenu.Recommended")));
items.Add(Preset(recommended, Loc.L("Tooltips.Editor.RenderMenu.Recommended")));
}
if (batch.Count > 0)
{
// The count is the batch's (as Render batch says), a preset listed above among them.
items.Add(RenderMenuItem.Header(Loc.L("Export.Footer.Batch", state.Batch.Count)));
items.AddRange(batch.Select(p => Preset(p, null)));
}
if (recent.Count > 0)
{
items.Add(RenderMenuItem.Header(Loc.L("Editor.RenderMenu.Recent")));
items.AddRange(recent.Select(p => Preset(p, Loc.L("Tooltips.Editor.RenderMenu.Recent"))));
}
var others = new List<RenderMenuItem>();
foreach (var group in ExportPresets.BuiltIn.Where(p => !shown.Contains(p.Id)).GroupBy(p => p.Group, StringComparer.OrdinalIgnoreCase).OrderBy(g => GroupRank(g.Key)))
{
others.Add(RenderMenuItem.Header(GroupLabel(group.Key)));
others.AddRange(group.Select(p => Preset(p, null)));
}
if (others.Count > 0)
{
items.Add(new RenderMenuItem
{
Kind = RenderMenuItemKind.Submenu,
Id = "other",
Label = Loc.L("Editor.RenderMenu.Other"),
ToolTip = Loc.L("Tooltips.Editor.RenderMenu.Other"),
Children = others,
});
}
items.Add(RenderMenuItem.Separator);
items.Add(new RenderMenuItem
{
Kind = RenderMenuItemKind.Command,
Id = "batch",
Label = Loc.L("Editor.RenderMenu.Batch", state.Batch.Count),
Command = state.RenderBatch,
ToolTip = state.RenderBatchToolTip ?? Loc.L(state.Batch.Count == 0 ? "Tooltips.Editor.RenderMenu.BatchEmpty" : "Tooltips.Editor.RenderMenu.Batch"),
});
items.Add(new RenderMenuItem
{
Kind = RenderMenuItemKind.Command,
Id = "queue",
Label = Loc.L("Editor.Export.AddToQueue"),
Command = state.AddToQueue,
ToolTip = state.AddToQueueToolTip ?? Loc.L("Tooltips.Editor.RenderMenu.AddToQueue"),
});
items.Add(new RenderMenuItem
{
Kind = RenderMenuItemKind.Submenu,
Id = "frame",
Label = Loc.L("Editor.RenderMenu.SaveFrame"),
IsEnabled = state.SaveFrameBlocked is null,
ToolTip = state.SaveFrameBlocked ?? Loc.L("Tooltips.Editor.RenderMenu.SaveFrame"),
Children = [.. RenderRules.StillCodecs.Select(codec => new RenderMenuItem
{
Kind = RenderMenuItemKind.Command,
Id = "frame:" + Data.Processing.ProcessingJobs.CodecName(codec),
Label = StillFormatName(codec),
Command = state.SaveFrame,
CommandParameter = codec,
IsEnabled = state.SaveFrameBlocked is null,
ToolTip = state.SaveFrameBlocked ?? Loc.L("Tooltips.Editor.RenderMenu.SaveFormat", StillFormatName(codec)),
})],
});
items.Add(new RenderMenuItem
{
Kind = RenderMenuItemKind.Command,
Id = "videos",
Label = Loc.L("Editor.RenderMenu.Videos"),
Command = state.ShowVideos,
ToolTip = Loc.L("Tooltips.Editor.RenderMenu.Videos"),
});
return items;
RenderMenuItem Preset(ExportPreset preset, string? why)
{
shown.Add(preset.Id);
var name = Loc.L(preset.NameKey);
var details = state.Details(preset);
var tip = Loc.L("Tooltips.Editor.RenderMenu.Preset", name, details);
return new RenderMenuItem
{
Kind = RenderMenuItemKind.Preset,
Id = "preset:" + preset.Id,
Label = name,
Details = details.Length > 0 ? details : null,
IsChecked = string.Equals(preset.Id, state.CurrentPresetId, StringComparison.OrdinalIgnoreCase),
Command = state.SelectPreset,
CommandParameter = preset.Id,
ToolTip = why is null ? tip : tip + Loc.Separator + why,
};
}
}
/// <summary>"Video", "Social"…: the name of a preset group.</summary>
public static string GroupLabel(string group)
{
ArgumentException.ThrowIfNullOrEmpty(group);
return Loc.L("Export.Preset.Group." + char.ToUpperInvariant(group[0]) + group[1..].ToLowerInvariant());
}
/// <summary>"PNG", "JPEG", "TIFF 16-bit": a Save frame format.</summary>
public static string StillFormatName(VideoCodec codec) => Loc.L("Export.Codec." + codec);
/// <summary>
/// "3840×2160 · HEVC Main10 · 24 fps": the size <paramref name="presetId"/> renders this sequence at (the preset's box
/// fitted to the chosen proportions, as the render does), its codec and its frame rate, with the export's own values
/// for the rest (as choosing it in the menu makes it); the preset's own size without a source size.
/// </summary>
public static string PresetDetails(ExportSettings export, string presetId, CameraSettings camera, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(export);
ArgumentNullException.ThrowIfNull(camera);
var resolved = ExportResolver.Resolve(export with { Preset = export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] });
var (width, height) = sourceWidth > 0 && sourceHeight > 0 ? RenderSize.Of(camera, resolved, sourceWidth, sourceHeight) : (resolved.Width, resolved.Height);
var size = width > 0 && height > 0 ? EditorText.Size(width, height) : Loc.L("Export.Resolution.Source");
return Loc.L("Editor.RenderMenu.Details", size, EditorText.CodecName(resolved.Codec, resolved.Profile, resolved.BitDepth),
Loc.L("Editor.Value.Fps", EditorText.FrameRate(resolved.FrameRate)));
}
/// <summary>
/// The Render button's tooltip (decision 1): why it waits, when it does, then what it renders, "Render 4K HEVC ·
/// 3840×2160 · HEVC Main10 · 24 fps · ~1.2 GB · ~4 min · Ctrl+R" (the size the encoder makes); for a server sequence,
/// where it renders.
/// </summary>
public static string RenderToolTip(ExportPlan? plan, string? blocked, string? server)
{
var lines = new List<string>(3);
if (blocked is { Length: > 0 }) lines.Add(blocked);
if (plan is not null)
{
var (width, height) = plan.EncodedSize;
lines.Add(Loc.L("Tooltips.Editor.RenderDetails", plan.PresetName, width > 0 && height > 0 ? EditorText.Size(width, height) : Loc.L("Export.Resolution.Source"),
EditorText.CodecName(plan.Export.Codec, plan.Export.Profile, plan.Export.BitDepth), Loc.L("Editor.Value.Fps", EditorText.FrameRate(plan.Setup.Plan.FrameRate)),
Formatting.Bytes(plan.Estimate.Bytes), Formatting.Duration(plan.Estimate.Time)));
}
if (blocked is null && server is not null) lines.Add(Loc.L("Tooltips.Editor.RenderServer", server));
if (lines.Count == 0) lines.Add(Loc.L("Tooltips.Editor.Render"));
return string.Join(Environment.NewLine, lines);
}
/// <summary>The batch presets of an export besides its own, each once, in the order ticked (blank entries skipped).</summary>
public static IReadOnlyList<string> BatchPresets(ExportSettings export)
{
ArgumentNullException.ThrowIfNull(export);
var own = ExportResolver.Resolve(export).BasePresetId;
return [.. export.Batch.Where(id => !string.IsNullOrWhiteSpace(id) && !id.Equals(own, StringComparison.OrdinalIgnoreCase)).Distinct(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// The presets <paramref name="renders"/> (newest first, as <see cref="SequenceContent.Renders"/>) were made with, newest
/// first and each once, at most <paramref name="count"/>; saved frames do not count.
/// </summary>
public static IReadOnlyList<string> RecentPresets(IReadOnlyList<Render> renders, int count = RecentCount)
{
ArgumentNullException.ThrowIfNull(renders);
return [.. renders.Where(r => RenderKind.Of(r) != RenderKind.Still).Select(PresetOf).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase).Take(count)];
}
/// <summary>
/// The built-in preset a render was made with: from the settings it recorded, else from its preset name in the language
/// of the moment; null when neither tells (a custom export, settings no longer readable).
/// </summary>
public static string? PresetOf(Render render)
{
ArgumentNullException.ThrowIfNull(render);
if (render.SettingsJson is { Length: > 0 } json)
{
try
{
var resolved = ExportResolver.Resolve(ProjectSettings.FromJson(json, allowNewer: true).Export);
if (!resolved.IsCustom && Find(resolved.BasePresetId) is { } preset) return preset.Id;
}
catch (Exception ex) when (ex is JsonException or InvalidDataException or ArgumentException)
{
// Settings no longer readable say nothing: the name may still tell.
}
}
return ExportPresets.BuiltIn.FirstOrDefault(p => string.Equals(Loc.L(p.NameKey), render.PresetName, StringComparison.OrdinalIgnoreCase))?.Id;
}
/// <summary>
/// Why Save frame waits (decision 12), in this order: the frames changed on the server, the project is shown read-only,
/// there is no frame to save under the cursor (none, or one the render leaves out), the source cannot save frames, the
/// server cannot (<paramref name="serverReason"/>: no right, or an older Chronos), the file name is wrong; null when a
/// frame can be saved.
/// </summary>
public static string? SaveFrameBlockedReason(bool outdated, string? server, bool readOnly, bool hasFrame, bool sourceSavesFrames, string? serverReason,
string? nameError)
{
if (outdated) return Loc.L("Tooltips.Editor.Outdated", server);
if (readOnly) return Loc.L("Tooltips.Export.StillReadOnly");
if (!hasFrame) return Loc.L("Tooltips.Export.StillNeedsFrame");
// Missing key Tooltips.Export.StillWorkspace (a workspace project saves no frame yet): the closest reason until P8 adds it.
if (!sourceSavesFrames) return Loc.L("Tooltips.Export.StillReadOnly");
if (serverReason is not null) return serverReason;
return nameError is null ? null : Loc.L("Tooltips.Editor.Render.NameError", nameError);
}
private static ExportPreset? Find(string? id) => id is { Length: > 0 } ? ExportPresets.Find(id) : null;
private static bool Same(ExportPreset preset, ExportPreset? other) => other is not null && preset.Id.Equals(other.Id, StringComparison.OrdinalIgnoreCase);
private static int GroupRank(string group)
{
for (var i = 0; i < GroupOrder.Count; i++)
{
if (GroupOrder[i].Equals(group, StringComparison.OrdinalIgnoreCase)) return i;
}
return GroupOrder.Count;
}
}
+21
View File
@@ -5,8 +5,11 @@ using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Protocol;
using Chronos.Protocol.Client;
@@ -63,6 +66,24 @@ internal sealed class ServerJobs : IAsyncDisposable
/// </summary>
public static string? NeedsNewerServer(int required, int serverFormat) => required > serverFormat ? Loc.L("Tooltips.Server.NeedsNewerServer") : null;
/// <summary>
/// Why a render of <paramref name="export"/> with <paramref name="settings"/> cannot go to a server that reads
/// <paramref name="serverFormat"/> (owner review 1, phase 5: playback needs format 3); null when it can. The format is the
/// one of the job's own export, its playback included, never the project's export alone (<see cref="ProcessingJobs.RequiredFormat"/>).
/// </summary>
public static string? RenderNeedsNewerServer(ProjectSettings settings, ExportSettings export, int sourceWidth, int sourceHeight, int serverFormat)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(export);
return NeedsNewerServer(ProcessingJobs.RequiredFormat(settings with { Export = export }, export, sourceWidth, sourceHeight), serverFormat);
}
/// <summary>
/// Why "Save frame" cannot go to a server that reads <paramref name="serverFormat"/>: a still job needs
/// <see cref="RenderRules.StillFormat"/>, which an older server's nodes would render as a whole video; null when it can.
/// </summary>
public static string? StillNeedsNewerServer(int serverFormat) => NeedsNewerServer(RenderRules.StillFormat, serverFormat);
/// <summary>Queues <paramref name="request"/> on the server (its priority set after, when it is not the user's); returns the job id.</summary>
/// <exception cref="EditorException">The sequence is gone from the server.</exception>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
+6 -1
View File
@@ -121,6 +121,9 @@
ToolTip="{Binding Project.SaveVersionToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.Sync}" Command="{Binding Project.SyncCommand}" ToolTip="{Binding Project.SyncToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.History}" Command="{Binding Project.HistoryCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.History}" />
<!-- Owner review 1, R3: moved here from the Export step's footer. -->
<MenuItem Header="{l:Loc Editor.ProjectFile.Save}" Command="{Binding Export.SaveProjectCommand}" ToolTip="{Binding Export.SaveProjectToolTip}"
ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
@@ -162,8 +165,10 @@
<Button Content="{l:Loc Editor.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{Binding AnalyseToolTip}" ToolTipService.ShowOnDisabled="True" />
<Button Content="{l:Loc Editor.OptimiseAll}" Command="{Binding OptimiseAllCommand}" ToolTip="{Binding OptimiseAllToolTip}"
ToolTipService.ShowOnDisabled="True" Margin="12,0,0,0" />
<!-- Owner review 1, R3: "Render ▾" whatever the preset, so the header keeps its width; the tooltip gives the details and the
menu, made again at every opening, checks the current preset (Recommended, batch, recent, Other presets ›, Save frame ›). -->
<v:SplitButton x:Name="RenderButton" IsPrimary="True" Margin="12,0,0,0" Content="{Binding RenderText}" Command="{Binding RenderCommand}"
ItemsSource="{Binding RenderChoices}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedRenderChoice}" ToolTip="{Binding RenderToolTip}"
ItemsSource="{Binding RenderMenuItems, Mode=OneWay}" ToolTip="{Binding RenderToolTip}"
ToolTipService.ShowOnDisabled="True" DropDownToolTip="{Binding RenderChoiceToolTip}"
AutomationProperties.Name="{l:Loc Editor.RenderButton}" />
</StackPanel>
+21
View File
@@ -293,6 +293,27 @@
<Setter Property="ui:ControlState.PressedBackground" Value="{DynamicResource Brush.AccentPressed}" />
</Style>
<!-- A structured entry of the ▾ menu (owner review 1, R3): its label, then the muted details line of a preset ("3840×2160 · HEVC
Main10 · 24 fps"); a header is a small muted title. Sizes and numbers read as the rest of the menu. -->
<DataTemplate x:Key="SplitButton.ItemTemplate" DataType="{x:Type v:RenderMenuItem}">
<StackPanel x:Name="Lines" Margin="0,5" VerticalAlignment="Center">
<TextBlock x:Name="Label" Text="{Binding Label}" TextTrimming="CharacterEllipsis" MaxWidth="320" />
<TextBlock x:Name="Details" Text="{Binding Details}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}"
TextTrimming="CharacterEllipsis" MaxWidth="320" Typography.NumeralAlignment="Tabular" Margin="0,1,0,0" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Details}" Value="{x:Null}">
<Setter TargetName="Details" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Lines" Property="Margin" Value="0" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="{x:Static v:RenderMenuItemKind.Header}">
<Setter TargetName="Label" Property="FontSize" Value="{StaticResource Size.Secondary}" />
<Setter TargetName="Label" Property="FontWeight" Value="SemiBold" />
<Setter TargetName="Label" Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<Style TargetType="v:SplitButton">
<Setter Property="Height" Value="{StaticResource Height.Control}" />
<Setter Property="DropDownName" Value="{l:Loc Common.MoreChoices}" />
+159 -16
View File
@@ -10,17 +10,84 @@ using System.Windows.Input;
namespace Chronos.Ui.Visuals;
/// <summary>What a <see cref="RenderMenuItem"/> is in its menu.</summary>
public enum RenderMenuItemKind
{
/// <summary>A choice with a muted details line ("3840×2160 · HEVC Main10 · 24 fps"), checked when it is the current one.</summary>
Preset,
/// <summary>A section title ("Recommended", "Recent"): not clickable, skipped by the keyboard.</summary>
Header,
Separator,
/// <summary>An action ("Add to queue").</summary>
Command,
/// <summary>An entry that opens <see cref="RenderMenuItem.Children"/> ("Other presets ›", "Save frame ›").</summary>
Submenu,
}
/// <summary>
/// Main action on the left, a ▾ part on the right that drops down a menu of choices (Editor: "Render · preset ▾").
/// One entry of a structured <see cref="SplitButton"/> menu (owner review 1, R3: Render ▾ with headers, separators, two-line
/// presets and submenus). A view model builds the list; the button makes the menu items from it each time it opens. An
/// entry runs <see cref="Command"/> with <see cref="CommandParameter"/>; a submenu or command is shown disabled, with its
/// tooltip as the reason, when <see cref="IsEnabled"/> is false or its command cannot run.
/// </summary>
public sealed record RenderMenuItem
{
public RenderMenuItemKind Kind { get; init; }
/// <summary>The visible text, also the accessible name.</summary>
public string Label { get; init; } = string.Empty;
/// <summary>The muted second line of a preset; null for one line.</summary>
public string? Details { get; init; }
public bool IsChecked { get; init; }
public bool IsEnabled { get; init; } = true;
public ICommand? Command { get; init; }
public object? CommandParameter { get; init; }
public IReadOnlyList<RenderMenuItem> Children { get; init; } = [];
/// <summary>What the entry does, or why it is disabled (every actionable entry has one).</summary>
public string? ToolTip { get; init; }
/// <summary>A stable identity for tests and captures ("preset:4k-hevc", "batch", "frame:png"); never shown.</summary>
public string? Id { get; init; }
public static RenderMenuItem Separator { get; } = new() { Kind = RenderMenuItemKind.Separator };
public static RenderMenuItem Header(string label) => new() { Kind = RenderMenuItemKind.Header, Label = label };
/// <summary>The entries of this one and of its submenus, depth first.</summary>
public IEnumerable<RenderMenuItem> Flatten()
{
yield return this;
foreach (var child in Children.SelectMany(c => c.Flatten())) yield return child;
}
}
/// <summary>
/// Main action on the left, a ▾ part on the right that drops down a menu of choices (Editor: "Render ▾").
/// The main part executes <see cref="Command"/>; choosing a menu entry sets <see cref="SelectedItem"/> (checked in
/// the menu) — bind <see cref="CommandParameter"/> to it to act on the chosen preset. The control's ToolTip
/// describes the main action, <see cref="DropDownToolTip"/> the ▾ part. F4 or Alt+Down opens the menu.
/// <see cref="IsPrimary"/> gives the accent look of the screen's primary button. Screen readers see a split button
/// (named by AutomationProperties.Name or the content) that invokes and expands, holding the two parts;
/// the menu) — bind <see cref="CommandParameter"/> to it to act on the chosen preset. When <see cref="ItemsSource"/>
/// holds <see cref="RenderMenuItem"/>s, the menu is structured instead (headers, separators, two-line items, submenus,
/// each with its own command and tooltip) and read again from the binding every time it opens, so it never shows a stale
/// state. The control's ToolTip describes the main action, <see cref="DropDownToolTip"/> the ▾ part. F4 or Alt+Down opens
/// the menu. <see cref="IsPrimary"/> gives the accent look of the screen's primary button. Screen readers see a split
/// button (named by AutomationProperties.Name or the content) that invokes and expands, holding the two parts;
/// <see cref="DropDownName"/> names the ▾ part.
/// </summary>
public class SplitButton : Control
{
/// <summary>The header template of structured entries (Visuals.xaml): the label and, below it, the muted details.</summary>
public const string ItemTemplateKey = "SplitButton.ItemTemplate";
public static readonly DependencyProperty ContentProperty = DependencyProperty.Register(nameof(Content), typeof(object), typeof(SplitButton));
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(SplitButton));
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(SplitButton));
@@ -42,6 +109,9 @@ public class SplitButton : Control
private ContextMenu? _menu;
/// <summary>The open menu was made from <see cref="RenderMenuItem"/>s (its entries run their own commands).</summary>
private bool _structured;
static SplitButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(typeof(SplitButton)));
@@ -114,33 +184,106 @@ public class SplitButton : Control
}
}
/// <summary>The drop-down menu as it is now (made on the first open, filled again on every open); null before.</summary>
internal ContextMenu? Menu => _menu;
/// <summary>
/// The control of one structured entry: a <see cref="Separator"/>, or a <see cref="MenuItem"/> whose header is the entry
/// (shown by <paramref name="template"/>, its label alone without one) with its command, check, tooltip and submenu.
/// </summary>
internal static Control CreateItem(RenderMenuItem entry, DataTemplate? template)
{
ArgumentNullException.ThrowIfNull(entry);
if (entry.Kind == RenderMenuItemKind.Separator) return new Separator();
var item = new MenuItem
{
Header = template is null ? entry.Label : entry,
HeaderTemplate = template,
IsChecked = entry.IsChecked,
Command = entry.Command,
CommandParameter = entry.CommandParameter,
ToolTip = entry.ToolTip,
};
AutomationProperties.SetName(item, entry.Label);
if (entry.Details is { Length: > 0 } details) AutomationProperties.SetHelpText(item, details);
if (entry.Id is { Length: > 0 } id) AutomationProperties.SetAutomationId(item, id);
ToolTipService.SetShowOnDisabled(item, true);
if (!entry.IsEnabled) item.IsEnabled = false;
switch (entry.Kind)
{
case RenderMenuItemKind.Header:
// A title, not a choice: the keyboard and the mouse pass over it, and it keeps its full contrast.
item.Focusable = false;
item.IsHitTestVisible = false;
item.Height = 26;
break;
case RenderMenuItemKind.Submenu:
foreach (var child in entry.Children) item.Items.Add(CreateItem(child, template));
break;
}
if (entry.Details is { Length: > 0 })
{
// Two lines: the menu's 32 px rows give way to the label over its details.
item.Height = double.NaN;
item.MinHeight = 32;
}
return item;
}
private ContextMenu EnsureMenu()
{
if (_menu is not null) return _menu;
var menu = new ContextMenu { PlacementTarget = this, Placement = PlacementMode.Bottom, VerticalOffset = 4 };
if (_menu is null)
{
var menu = new ContextMenu { PlacementTarget = this, Placement = PlacementMode.Bottom, VerticalOffset = 4 };
menu.SetBinding(DataContextProperty, new Binding(nameof(DataContext)) { Source = this });
menu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
menu.Opened += (_, _) => MarkSelected();
menu.Closed += (_, _) => SetCurrentValue(IsDropDownOpenProperty, false);
_menu = menu;
}
Populate(_menu);
return _menu;
}
/// <summary>
/// Fills the menu for this opening: structured entries made again from the binding as it reads now (the state of the
/// commands, the current preset and the reasons may have changed since the last time), otherwise the items bound as a
/// plain list of choices.
/// </summary>
private void Populate(ContextMenu menu)
{
GetBindingExpression(ItemsSourceProperty)?.UpdateTarget();
var entries = ItemsSource?.OfType<RenderMenuItem>().ToList() ?? [];
_structured = entries.Count > 0;
if (_structured)
{
foreach (var property in new[] { ItemsControl.ItemsSourceProperty, ItemsControl.ItemTemplateProperty, ItemsControl.ItemContainerStyleProperty, ItemsControl.DisplayMemberPathProperty })
BindingOperations.ClearBinding(menu, property);
menu.Items.Clear();
var template = TryFindResource(ItemTemplateKey) as DataTemplate;
foreach (var entry in entries) menu.Items.Add(CreateItem(entry, template));
return;
}
if (BindingOperations.IsDataBound(menu, ItemsControl.ItemsSourceProperty)) return;
menu.Items.Clear();
menu.SetBinding(ItemsControl.ItemsSourceProperty, new Binding(nameof(ItemsSource)) { Source = this });
menu.SetBinding(ItemsControl.ItemTemplateProperty, new Binding(nameof(ItemTemplate)) { Source = this });
menu.SetBinding(ItemsControl.ItemContainerStyleProperty, new Binding(nameof(ItemContainerStyle)) { Source = this });
menu.SetBinding(ItemsControl.DisplayMemberPathProperty, new Binding(nameof(DisplayMemberPath)) { Source = this });
menu.SetBinding(DataContextProperty, new Binding(nameof(DataContext)) { Source = this });
menu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
menu.Opened += (_, _) => MarkSelected();
menu.Closed += (_, _) => SetCurrentValue(IsDropDownOpenProperty, false);
_menu = menu;
return menu;
}
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
if (_menu is null || e.OriginalSource is not MenuItem container) return;
// Structured entries run their own commands; a plain list's entry becomes the choice.
if (_menu is null || _structured || e.OriginalSource is not MenuItem container) return;
var item = _menu.ItemContainerGenerator.ItemFromContainer(container);
if (item != DependencyProperty.UnsetValue) SetCurrentValue(SelectedItemProperty, item);
}
/// <summary>Checks the menu entry of the current choice.</summary>
/// <summary>Checks the menu entry of the current choice (structured entries carry their own check).</summary>
private void MarkSelected()
{
if (_menu is null) return;
if (_menu is null || _structured) return;
_menu.UpdateLayout();
for (var i = 0; i < _menu.Items.Count; i++)
if (_menu.ItemContainerGenerator.ContainerFromIndex(i) is MenuItem container)
@@ -0,0 +1,144 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Core.Render;
using Chronos.Testing;
using Chronos.Ui.Visuals;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// The editor's header in the real main window at the 1200 px minimum (owner review 1, R3, decision 1): "Render ▾" keeps one
/// width whatever the preset in every language, and its menu shows the presets as two-line entries with the current one checked.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class RenderHeaderTests
{
private static readonly string[] Presets = ["1080p-h264", "8k-hevc10-archive", "gif-preview", "tiff16-sequence", "vertical-1080x1920"];
[Test]
public Task TheHeaderKeepsItsWidthWhateverThePresetInEveryLanguage() => 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
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
var widths = new List<double>();
foreach (var preset in Presets)
{
editor.SelectPresetCommand.Execute(preset);
await CheckedAsync(editor, preset, app.Window);
var button = RenderButton(app.Window);
Assert.Equal(Loc.L("Editor.RenderButton"), button.Content, $"{language}: no preset name on the button");
var right = button.TranslatePoint(new Point(button.ActualWidth, 0), app.Window).X;
var left = button.TranslatePoint(new Point(0, 0), app.Window).X;
Assert.True(Math.Min(left, right) >= 0 && Math.Max(left, right) <= app.Window.ActualWidth,
$"{language}, {preset}: Render spans {Math.Min(left, right):0}–{Math.Max(left, right):0} px in a {app.Window.ActualWidth:0} px window");
widths.Add(Math.Round(button.ActualWidth, 1));
}
Assert.True(widths.Max() - widths.Min() < 0.5, $"{language}: Render is {string.Join(", ", widths)} px wide across the presets");
}
}
finally
{
UiLanguage.Apply("en");
await app.Shell.Sequence.CloseAsync();
}
});
[Test]
public Task TheRenderMenuShowsTwoLinePresetsWithTheCurrentOneChecked() => 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.SelectPresetCommand.Execute("1080p-h264");
await CheckedAsync(editor, "1080p-h264", app.Window);
var button = RenderButton(app.Window);
button.IsDropDownOpen = true;
await SettleAsync(app.Window);
var menu = Assert.NotNull(button.Menu);
Assert.True(menu.IsOpen);
var items = menu.Items.OfType<Control>().ToList();
var current = items.OfType<MenuItem>().Single(m => m.IsChecked);
Assert.Equal("preset:1080p-h264", ((RenderMenuItem)current.Header).Id);
Assert.Equal(Loc.L("Export.Preset.1080pShare"), System.Windows.Automation.AutomationProperties.GetName(current));
Assert.True(current.ActualHeight >= 32, $"a preset entry has a details line ({current.ActualHeight:0} px)");
var lines = Find<TextBlock>(current).Where(t => t.IsVisible).Select(t => t.Text).ToList();
Assert.Contains(Loc.L("Export.Preset.1080pShare"), lines);
Assert.Contains(lines, l => l.Contains("1920×1080", StringComparison.Ordinal));
Assert.True(items.OfType<Separator>().Any(), "the commands sit under a separator");
var frame = items.OfType<MenuItem>().Single(m => m.Header is RenderMenuItem { Id: "frame" });
Assert.Equal(RenderRules.StillCodecs.Count, frame.Items.Count);
var untipped = items.OfType<MenuItem>().Where(m => m.Header is RenderMenuItem { Kind: not RenderMenuItemKind.Header } && m.ToolTip is not string { Length: > 0 });
Assert.False(untipped.Any(), "every entry but a title has a tooltip: " + string.Join(", ", untipped.Select(m => ((RenderMenuItem)m.Header).Id)));
Assert.True(items.OfType<MenuItem>().Where(m => m.Header is RenderMenuItem { Kind: RenderMenuItemKind.Header }).All(m => !m.Focusable && !m.IsHitTestVisible),
"a title is not an entry");
// Another preset chosen: the menu, made again when it opens, checks that one.
((MenuItem)items.Single(i => i is MenuItem { Header: RenderMenuItem { Id: "preset:1080p-h264" } })).Command.Execute("8k-hevc10-archive");
button.IsDropDownOpen = false;
await CheckedAsync(editor, "8k-hevc10-archive", app.Window);
button.IsDropDownOpen = true;
await SettleAsync(app.Window);
Assert.Equal("preset:8k-hevc10-archive", ((RenderMenuItem)menu.Items.OfType<MenuItem>().Single(m => m.IsChecked).Header).Id);
button.IsDropDownOpen = false;
}
finally
{
await app.Shell.Sequence.CloseAsync();
}
});
private static SplitButton RenderButton(Window window) => Find<SplitButton>(window).Single(b => b.Name == "RenderButton" && b.IsVisible);
/// <summary>Waits until the editor's plan has the preset (it is made off the UI thread), then lets the layout settle.</summary>
private static async Task CheckedAsync(Chronos.App.Editor.EditorViewModel editor, string preset, Window window)
{
for (var i = 0; i < 400 && !editor.RenderMenuItems.SelectMany(m => m.Flatten()).Any(m => m.IsChecked && m.Id == "preset:" + preset); i++) await Task.Delay(10);
Assert.True(editor.RenderMenuItems.SelectMany(m => m.Flatten()).Any(m => m.IsChecked && m.Id == "preset:" + preset), $"{preset} is the current preset");
await SettleAsync(window);
}
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 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;
}
}
@@ -0,0 +1,300 @@
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.NotNull(RenderMenu.SaveFrameBlockedReason(false, null, false, true, sourceSavesFrames: false, null, null), "a workspace project saves no frame yet");
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)];
}
}
}