merge: phase 5 parcel P5
This commit is contained in:
commit
18cb8c88c0
9 files changed
+1137
-29
No files matched your search
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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}" />
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user