fix(app): editor review fixes for saving, undo, preview, commands and layout

- Undo/redo snapshots take outside changes (advice, merged edits) on Replace;
  a drag, click or key press ends a merged run; Reset to Auto is its own step.
- A failed save stays pending and is retried with backoff; closing or switching
  asks before discarding it; the local source throws unless the index took it.
- Opening a sequence survives any failure; the window title follows the editor;
  the job bar hides when idle in the editor.
- Render, Add to queue and Batch re-read their state; disabled commands say why;
  Analyse is disabled while queued and announces its cost and Ctrl+Shift+A.
- Preview: 1:1 and wheel zoom render the source's own pixels, the view keeps its
  place across resolutions, crop mask result mode, unreadable frames say so,
  labelled tools, keyboard focus on open, tools hidden on Export lose their effect.
- Preparation re-solves from measured series (no re-decode per slider step) with
  a half-precision frame cache.
- Exposure flicker and waveform charts, Time plan chart, Camera crop margins,
  sortable frame table, wrapped findings, responsive preset cards, render-done
  follow-up, Jobs history filtered on the sequence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:36:50 +00:00
1 parent 596b748c5c
commit 25e85aee57
32 files changed
+1612 -369

No files matched your search

+218 -104
View File
@@ -1,9 +1,8 @@
using System.Collections;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Advice;
using Titano.Core.Analysis;
@@ -14,6 +13,7 @@ using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Core.Render;
using Titano.Core.Video;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
using Titano.Ui.Visuals;
@@ -21,10 +21,11 @@ namespace Titano.App.Editor;
/// <summary>
/// The sequence editor of one open sequence (BRIEF §12.3, Editor.html): header actions, the preview with its tools
/// (wipe compare, zoom, overlays) rendered through the pipeline at preview size, the filmstrip with markers, the
/// section tabs and the keyboard (space, arrows, Ctrl+Z/Y, Ctrl+0/1, Ctrl+R). Preview frames, corrections, the export
/// plan and the card estimates are computed off the UI thread; each request cancels the previous one. While an analysis
/// or render of this sequence runs, settings are disabled and viewing tools stay live.
/// (wipe compare, zoom, overlays) rendered through the pipeline at preview size (at the source's own size for 1:1 and
/// wheel zoom), the filmstrip with markers, the section tabs and the keyboard (space, arrows, Ctrl+Z/Y, Ctrl+0/1,
/// Ctrl+R, Ctrl+Shift+A). Preview frames, corrections, the export plan and the card estimates are computed off the UI
/// thread; each request cancels the previous one. While an analysis or render of this sequence runs, settings are
/// disabled and viewing tools stay live.
/// </summary>
public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
{
@@ -39,15 +40,21 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private readonly LatestRunner _plans = new(Debounce);
private readonly DispatcherTimer _player;
private readonly Dictionary<Guid, Job> _jobs = [];
private readonly AsyncRelayCommand _analyse;
private readonly AsyncRelayCommand _render;
private PreviewRenderer _renderer;
private int _currentIndex;
private EditorTab _selectedTab;
private ImageSource? _previewImage;
private ImageSource? _originalImage;
private ImageSource? _waveformImage;
private string? _previewMessage;
private bool _isCompare = true;
private bool _showVectors;
private bool _showRegions;
private bool _showCropMask;
private bool _exportCropMask = true;
private CropMaskMode _cropMaskMode = CropMaskMode.ShowLoss;
private PreviewZoomMode _zoomMode = PreviewZoomMode.Fit;
private Rect _cropRect = new(0, 0, 1, 1);
private IReadOnlyList<Point>? _regionBoundary;
@@ -57,9 +64,11 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private bool _previewBusy;
private RenderCorrections? _correctionsValue;
private ExportPlan? _plan;
private bool _planned;
private IReadOnlyList<TimelineMarker> _markers = [];
private IThumbnailSource _thumbnails;
private int _playLimit;
private double? _analysisSecondsPerFrame;
private bool _disposed;
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host)
@@ -75,17 +84,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
_player = new DispatcherTimer(DispatcherPriority.Background, _dispatcher);
_player.Tick += (_, _) => Advance();
Frames = new FramesTab(this);
Exposure = new ExposureTab(this);
Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
_selectedTab = Exposure;
_currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0;
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
AnalyseCommand = new AsyncRelayCommand(AnalyseAsync, () => !IsBusy);
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsBusy && !IsAnalysing);
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsBusy);
RenderCommand = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: false), () => CanRender);
_render = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: false), () => CanRender);
UndoCommand = new RelayCommand(() => Session.Undo(), () => !IsBusy && Session.History.CanUndo);
RedoCommand = new RelayCommand(() => Session.Redo(), () => !IsBusy && Session.History.CanRedo);
PlayCommand = new RelayCommand(() => TogglePlay(limit: 0));
@@ -93,7 +95,14 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
StepBackCommand = new RelayCommand(() => CurrentIndex--);
StepForwardCommand = new RelayCommand(() => CurrentIndex++);
FitCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Fit);
ActualSizeCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Actual);
ActualSizeCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Actual, () => !IsExportTab);
Frames = new FramesTab(this);
Exposure = new ExposureTab(this);
Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
_selectedTab = Exposure;
_currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0;
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
session.ProjectChanged += OnProjectChanged;
session.ContentChanged += OnContentChanged;
@@ -113,8 +122,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
public string Title => Session.Content.Sequence.DisplayTitle;
/// <summary>"3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings".</summary>
public string Summary => EditorText.Summary(Session.Content, Session.Advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning));
/// <summary>
/// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings"; on the Export tab what the video will be:
/// "3,600 frames · 24 fps · 2 min 30 s · 3840×2160 · source 8192×5464" (Export.html).
/// </summary>
public string Summary => IsExportTab && Plan is { } plan
? EditorText.OutputSummary(Session.Content, plan)
: EditorText.Summary(Session.Content, Session.Advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning));
public FramesTab Frames { get; }
@@ -129,8 +143,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
{
if (value is null || !Set(ref _selectedTab, value)) return;
OnPropertyChanged(nameof(IsExportTab));
if (IsExportTab && !ShowCropMask) ShowCropMask = true;
OnPropertyChanged(nameof(Summary));
OnToolsChanged();
// 1:1 is not a tool of the Export tab (Export.html): its picture fits the view.
if (IsExportTab) ZoomMode = PreviewZoomMode.Fit;
UpdateInfo();
RequestPreview(immediate: true);
CommandManager.InvalidateRequerySuggested();
}
}
@@ -149,9 +168,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
{
var clamped = FrameCount == 0 ? 0 : int.Clamp(value, 0, FrameCount - 1);
if (!Set(ref _currentIndex, clamped)) return;
Frames.OnCurrentFrameChanged();
foreach (var tab in Tabs.OfType<CameraTab>()) tab.OnCurrentFrameChanged();
foreach (var tab in Tabs.OfType<TimeTab>()) tab.OnCurrentFrameChanged();
foreach (var tab in Tabs) tab.OnCurrentFrameChanged();
UpdateInfo();
RequestPreview(immediate: _player.IsEnabled);
}
@@ -168,14 +185,23 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
public ImageSource? OriginalImage { get => _originalImage; private set => Set(ref _originalImage, value); }
/// <summary>Luma waveform of the corrected preview (Exposure tab), as an alpha mask drawn in the accent colour.</summary>
public ImageSource? WaveformImage { get => _waveformImage; private set => Set(ref _waveformImage, value); }
/// <summary>One sentence over the preview when the frame on screen cannot be shown; null otherwise.</summary>
public string? PreviewMessage { get => _previewMessage; private set => Set(ref _previewMessage, value); }
public bool IsCompare { get => _isCompare; set => Set(ref _isCompare, value); }
/// <summary>The Vectors tool (kept while the Export tab hides it, shown again on the other tabs).</summary>
public bool ShowVectors
{
get => _showVectors;
set
{
if (Set(ref _showVectors, value)) RequestPreview(immediate: true);
if (!Set(ref _showVectors, value)) return;
OnPropertyChanged(nameof(ViewVectors));
RequestPreview(immediate: true);
}
}
@@ -184,25 +210,56 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
get => _showRegions;
set
{
if (Set(ref _showRegions, value)) RequestPreview(immediate: true);
if (!Set(ref _showRegions, value)) return;
OnPropertyChanged(nameof(ViewRegions));
RequestPreview(immediate: true);
}
}
/// <summary>The Crop mask tool of the current tab: the Export tab has its own, on by default (Export.html).</summary>
public bool ShowCropMask
{
get => _showCropMask;
get => IsExportTab ? _exportCropMask : _showCropMask;
set
{
if (Set(ref _showCropMask, value)) RequestPreview(immediate: true);
if (value == ShowCropMask) return;
if (IsExportTab) _exportCropMask = value;
else _showCropMask = value;
OnPropertyChanged();
RequestPreview(immediate: true);
}
}
/// <summary>Overlays the viewport draws: only tools that have a button on the current tab.</summary>
public bool ViewVectors => ShowVectors && !IsExportTab;
public bool ViewRegions => ShowRegions && !IsExportTab;
/// <summary>The crop mask shows "how it will look" (outside hidden) instead of "what I lose" (outside dimmed).</summary>
public bool IsCropResult
{
get => _cropMaskMode == CropMaskMode.ShowResult;
set
{
if (!Set(ref _cropMaskMode, value ? CropMaskMode.ShowResult : CropMaskMode.ShowLoss, nameof(CropMaskMode))) return;
OnPropertyChanged();
OnPropertyChanged(nameof(CropModeToolTip));
}
}
public CropMaskMode CropMaskMode => _cropMaskMode;
public string CropModeToolTip => Loc.L(IsCropResult ? "Tooltips.Editor.Preview.CropLoss" : "Tooltips.Editor.Preview.CropResult");
public PreviewZoomMode ZoomMode
{
get => _zoomMode;
set
{
if (Set(ref _zoomMode, value)) OnPropertyChanged(nameof(IsActualSize));
if (!Set(ref _zoomMode, value)) return;
OnPropertyChanged(nameof(IsActualSize));
// Fit renders at the view's size; 1:1 and wheel zoom need the source's own pixels.
RequestPreview(immediate: true);
}
}
@@ -227,17 +284,22 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>Shot data (bottom-right pill): frame, time, exposure; on the Export tab output time and size.</summary>
public string? InfoText { get; private set; }
/// <summary>Long edge of the preview picture in device pixels (the view reports its size).</summary>
/// <summary>Long edge of the view in device pixels (the view reports its size); Fit renders at this size.</summary>
public int PreviewEdge
{
get => _previewEdge;
set
{
var rounded = int.Clamp((value + 63) / 64 * 64, 256, 4096);
if (Set(ref _previewEdge, rounded)) RequestPreview();
if (Set(ref _previewEdge, rounded) && _zoomMode == PreviewZoomMode.Fit) RequestPreview();
}
}
/// <summary>Long edge the preview renders at: the view's in Fit, the source's own when zoomed (1:1 shows raw pixels).</summary>
public int RenderEdge => _zoomMode == PreviewZoomMode.Fit || SourceEdge <= 0 ? PreviewEdge : SourceEdge;
private int SourceEdge => int.Max(Session.Content.SourceWidth, Session.Content.SourceHeight);
// ---- Analysis, plan, jobs ----
/// <summary>The corrections of the current exposure settings, once prepared (target curves).</summary>
@@ -249,14 +311,30 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>An analysis or render of this sequence is running: settings wait, viewing tools stay live.</summary>
public bool IsBusy => _jobs.Values.Any(j => j.State == JobState.Running);
/// <summary>A deep analysis of this sequence is queued or running (Analyse would queue it twice).</summary>
public bool IsAnalysing => _jobs.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
public bool IsEditable => !IsBusy;
public string? BusyToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy") : null;
/// <summary>What Analyse does and costs ("about 6 min" from the speed of the last analysis), or why it is disabled.</summary>
public string AnalyseToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy")
: IsAnalysing ? Loc.L("Tooltips.Editor.AnalyseQueued")
: _analysisSecondsPerFrame is { } perFrame ? Loc.L("Tooltips.Editor.AnalyseCost", Formatting.Duration(TimeSpan.FromSeconds(perFrame * FrameCount)))
: Loc.L("Tooltips.Editor.Analyse");
public string OptimiseAllToolTip => Loc.L(IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.OptimiseAll");
public bool IsPlaying => _player.IsEnabled;
public string PlayToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Play");
public string PlayName => Loc.L(IsPlaying ? "Editor.Preview.Pause" : "Editor.Preview.Play");
/// <summary>"Preview 10 s" (Export tab): plays ten seconds of the video's frames, or pauses them.</summary>
public string ClipToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Preview.Clip");
// ---- Render ----
public IReadOnlyList<Choice> RenderChoices { get; }
@@ -276,16 +354,27 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>"Render · 4K archive".</summary>
public string RenderText => Loc.L("Editor.Render", Plan?.PresetName ?? string.Empty);
public string RenderToolTip => Plan is { } plan && !plan.Setup.Encoder.IsReady && plan.Setup.Encoder.Notices.LastOrDefault() is { } notice
? Loc.L(notice.Key, [.. notice.Args])
: Loc.L("Tooltips.Editor.Render");
public string RenderToolTip => RenderBlockedReason ?? Loc.L("Tooltips.Editor.Render");
public bool CanRender => Plan is { NameError: null, Setup: { Encoder.IsReady: true, Plan.Frames.Count: > 0 } };
public bool CanRender => RenderBlockedReason is null;
/// <summary>Why the project's export cannot be rendered now, localised; null when it can.</summary>
public string? RenderBlockedReason => Plan switch
{
null when _planned => Loc.L("Tooltips.Editor.Render.NoSource"),
null => Loc.L("Tooltips.Editor.Render.Planning"),
{ NameError: { } error } => Loc.L("Tooltips.Editor.Render.NameError", error),
{ Setup.Encoder.IsReady: false } plan => plan.Setup.Encoder.Notices.LastOrDefault() is { } notice
? Loc.L(notice.Key, [.. notice.Args])
: Loc.L("Editor.Export.Unavailable"),
{ Setup.Plan.Frames.Count: 0 } => Loc.L("Tooltips.Editor.Render.NoFrames"),
_ => null,
};
public ICommand BackCommand { get; }
public ICommand AnalyseCommand { get; }
public ICommand AnalyseCommand => _analyse;
public ICommand OptimiseAllCommand { get; }
public ICommand RenderCommand { get; }
public ICommand RenderCommand => _render;
public ICommand UndoCommand { get; }
public ICommand RedoCommand { get; }
public ICommand PlayCommand { get; }
@@ -302,9 +391,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (content.Deep is { } deep)
{
return [.. deep.Exposure.Steps.Select(s => new TimelineMarker(s.Index, s.Received ? MarkerKind.ExposureStep : MarkerKind.Warning,
Loc.L(s.Received ? "Editor.Marker.Step" : "Editor.Marker.StepIgnored", Ev(s.MeasuredEv ?? s.ExpectedEv))))];
Loc.L(s.Received ? "Editor.Marker.Step" : "Editor.Marker.StepIgnored", EditorText.Ev(s.MeasuredEv ?? s.ExpectedEv))))];
}
return [.. content.Light.ExposureSteps.Select(s => new TimelineMarker(s.Index, MarkerKind.ExposureStep, Loc.L("Editor.Marker.Step", Ev(s.DeltaEv))))];
return [.. content.Light.ExposureSteps.Select(s => new TimelineMarker(s.Index, MarkerKind.ExposureStep, Loc.L("Editor.Marker.Step", EditorText.Ev(s.DeltaEv))))];
}
/// <summary>"Optimise section": the advisor's heavier decisions, reported in a toast (what changed, from what to what).</summary>
@@ -319,6 +408,18 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Shell.Notify(Loc.L("Editor.Render.Queued"), request.Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
/// <summary>Re-reads the enabled state of every command (the async ones keep their own event).</summary>
public void RefreshCommands()
{
_analyse.RaiseCanExecuteChanged();
_render.RaiseCanExecuteChanged();
foreach (var tab in Tabs) tab.RefreshCommands();
CommandManager.InvalidateRequerySuggested();
}
/// <summary>The Exposure tab switched to or from its waveform: the preview measures it.</summary>
public void OnWaveformNeeded() => RequestPreview(immediate: true);
/// <summary>
/// Completes once the preview, corrections, plan, estimates and filmstrip thumbnails in flight are done (capture and
/// tests); a finished step may start the next (corrections re-render the preview), so it waits until all are quiet.
@@ -351,12 +452,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Task[] Work() => [_preview.Idle, _corrections.Idle, _plans.Idle, .. Tabs.OfType<ExportTab>().Select(t => t.EstimatesIdle)];
}
/// <summary>Loads the jobs of this sequence already queued or running (busy state).</summary>
/// <summary>Loads the jobs of this sequence already queued or running (busy state) and the speed of the last analysis.</summary>
public async Task AttachJobsAsync()
{
if (Shell.Services.Jobs is not { } jobs) return;
var page = await jobs.ListAsync(null, 200);
foreach (var job in page.Items) Track(job);
foreach (var job in page.Items.OrderBy(j => j.Finished)) LearnAnalysisSpeed(job);
OnBusyChanged();
}
@@ -384,8 +486,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void RequestPreview(bool immediate = false)
{
if (_disposed || FrameCount == 0) return;
var framing = ShowCropMask || ShowRegions ? PreviewFraming.Source : PreviewFraming.Output;
var request = new PreviewRequest(CurrentIndex, Session.Project, PreviewEdge, framing, ShowVectors);
var framing = ShowCropMask || ViewRegions ? PreviewFraming.Source : PreviewFraming.Output;
var waveform = SelectedTab is ExposureTab { ChartMode: ExposureChart.Waveform };
var request = new PreviewRequest(CurrentIndex, Session.Project, RenderEdge, framing, ViewVectors, waveform);
var version = ++_previewVersion;
_ = RunPreviewAsync(request, version, immediate);
}
@@ -394,6 +497,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
{
var renderer = _renderer;
PreviewResult? result = null;
var ran = false;
_previewBusy = true;
try
{
@@ -401,22 +505,35 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
{
using var frame = await renderer.RenderAsync(request, renderer.Cached(request.Project) ?? renderer.Latest, token);
if (frame is not null) result = PreviewResult.From(frame);
ran = true;
}, immediate);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Log.Warning("editor", $"Preview of frame {request.Index + 1} failed", ex);
ran = true;
}
finally
{
if (version == _previewVersion) _previewBusy = false;
}
if (result is not { } r || version != _previewVersion || _disposed) return;
if (version != _previewVersion || _disposed || !ran) return;
if (result is not { } r)
{
// The frame on screen cannot be shown: never leave the previous frame's picture under this frame's shot data.
PreviewImage = OriginalImage = null;
MotionVectors = null;
WaveformImage = null;
PreviewMessage = Loc.L("Editor.Preview.Unreadable");
return;
}
PreviewMessage = null;
PreviewImage = r.Corrected;
OriginalImage = r.Original;
CropRect = r.Crop;
RegionBoundary = ShowRegions ? r.Horizon : null;
MotionVectors = ShowVectors ? r.Vectors : null;
RegionBoundary = ViewRegions ? r.Horizon : null;
MotionVectors = ViewVectors ? r.Vectors : null;
WaveformImage = r.Waveform;
}
private void RequestCorrections()
@@ -473,13 +590,17 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Log.Warning("editor", "Planning the export failed", ex);
}
if (_disposed || !ReferenceEquals(planner, Planner) || !ReferenceEquals(project, Session.Project)) return;
_planned = true;
Plan = plan;
OnPropertyChanged(nameof(RenderText));
OnPropertyChanged(nameof(RenderToolTip));
OnPropertyChanged(nameof(RenderBlockedReason));
OnPropertyChanged(nameof(CanRender));
OnPropertyChanged(nameof(SelectedRenderChoice));
OnPropertyChanged(nameof(Summary));
foreach (var tab in Tabs) tab.OnPlanChanged();
UpdateInfo();
CommandManager.InvalidateRequerySuggested();
RefreshCommands();
}
// ---- Playback ----
@@ -500,6 +621,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
}
OnPropertyChanged(nameof(IsPlaying));
OnPropertyChanged(nameof(PlayToolTip));
OnPropertyChanged(nameof(PlayName));
OnPropertyChanged(nameof(ClipToolTip));
}
/// <summary>Next frame while playing; frames are skipped rather than queued when the preview is slower than the clock.</summary>
@@ -523,6 +646,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
// ---- Changes ----
private void OnToolsChanged()
{
OnPropertyChanged(nameof(ShowCropMask));
OnPropertyChanged(nameof(ViewVectors));
OnPropertyChanged(nameof(ViewRegions));
}
private void OnProjectChanged()
{
foreach (var tab in Tabs) tab.Refresh();
@@ -530,7 +660,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
RequestCorrections();
RequestPlan();
RequestPreview();
CommandManager.InvalidateRequerySuggested();
RefreshCommands();
}
private void OnContentChanged()
@@ -549,7 +679,15 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
RequestPreview(immediate: true);
}
private void OnSaveFailed(Exception ex) => Shell.ReportError(ex);
/// <summary>The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once.</summary>
private void OnSaveFailed(Exception ex) => Shell.ShowToast(new Toast
{
Title = Loc.L("Editor.Save.Failed"),
Message = ex.Message,
ActionText = Loc.L("Editor.Save.Retry"),
ActionToolTip = Loc.L("Tooltips.Editor.Save.Retry"),
ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()),
});
private void UpdateMarkers()
{
@@ -575,7 +713,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var settings = plan.Setup.Encoder.Settings;
var position = plan.Setup.Plan.DurationSeconds * CurrentIndex / double.Max(1, FrameCount - 1);
InfoText = string.Join(" · ", EditorText.Position(CurrentIndex, FrameCount),
Loc.L("Editor.Preview.OutputTime", Clock(position), Clock(plan.Setup.Plan.DurationSeconds)),
Loc.L("Editor.Preview.OutputTime", EditorText.Clock(position), EditorText.Clock(plan.Setup.Plan.DurationSeconds)),
Loc.L("Editor.Preview.OutputSize", EditorText.Size(settings.Width, settings.Height)));
}
else
@@ -594,7 +732,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Shell.Notify(Loc.L("Editor.Optimise.Nothing"));
return;
}
var lines = changes.Select(c => Loc.L("Editor.Optimise.Change", ParameterLabel(c.Parameter), ValueText(c.Before), ValueText(c.After)));
var lines = changes.Select(c => Loc.L("Editor.Optimise.Change", EditorText.ParameterLabel(c.Parameter), EditorText.Value(c.Parameter, c.Before),
EditorText.Value(c.Parameter, c.After)));
Shell.Notify(Loc.Plural("Editor.Optimise.Done", changes.Count), string.Join(Environment.NewLine, lines));
}
@@ -612,8 +751,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (_disposed) return;
var wasActive = _jobs.ContainsKey(job.Id);
Track(job);
LearnAnalysisSpeed(job);
OnBusyChanged();
if (wasActive && job.State == JobState.Done) _ = ReloadAsync();
if (wasActive && job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null);
});
}
@@ -624,84 +764,58 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
else _jobs.Remove(job.Id);
}
private async Task ReloadAsync()
/// <summary>Seconds per frame of the latest finished deep analysis (any sequence): the cost Analyse announces.</summary>
private void LearnAnalysisSpeed(Job job)
{
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done, ItemsPerSecond: > 0 and var speed }) _analysisSecondsPerFrame = 1 / speed;
}
/// <summary>Reads the sequence again after a job; a finished render offers its follow-ups (BRIEF §11.5).</summary>
private async Task ReloadAsync(Job? render)
{
try
{
await Session.ReloadAsync();
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException)
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException)
{
Shell.ReportError(ex);
return;
}
if (render is null || _disposed) return;
var output = Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath;
Shell.ShowToast(new Toast
{
Title = Loc.L("Editor.Render.Done"),
Message = output is null ? render.TargetLabel : System.IO.Path.GetFileName(output),
ActionText = output is null ? null : Loc.L("Editor.Render.Reveal"),
ActionToolTip = output is null ? null : Loc.L("Tooltips.Editor.Render.Reveal"),
ActionCommand = output is null ? null : new RelayCommand(() => ShellActions.Reveal(output)),
});
}
private void OnBusyChanged()
{
OnPropertyChanged(nameof(IsBusy));
OnPropertyChanged(nameof(IsAnalysing));
OnPropertyChanged(nameof(IsEditable));
OnPropertyChanged(nameof(BusyToolTip));
CommandManager.InvalidateRequerySuggested();
OnPropertyChanged(nameof(AnalyseToolTip));
OnPropertyChanged(nameof(OptimiseAllToolTip));
foreach (var tab in Tabs) tab.OnBusyChanged();
RefreshCommands();
}
private static string Clock(double seconds)
{
var t = TimeSpan.FromSeconds(double.Max(0, seconds));
return ((int)t.TotalMinutes).ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture) + Loc.Culture.NumberFormat.NumberDecimalSeparator
+ (t.Milliseconds / 100).ToString(Loc.Culture);
}
private static string Ev(double ev) => ev.ToString("+0.0;−0.0;0.0", Loc.Culture);
private static string ParameterLabel(string parameter) => parameter switch
{
AdvisorParameters.Hero => Loc.L("Editor.Frames.HeroLabel"),
AdvisorParameters.Excluded => Loc.L("Editor.Frames.ExcludedLabel"),
AdvisorParameters.TimingMode => Loc.L("Editor.Time.Mode"),
AdvisorParameters.FrameRate => Loc.L("Editor.Time.Rate"),
AdvisorParameters.FitToSeconds => Loc.L("Editor.Time.Fit"),
AdvisorParameters.Deflicker => Loc.L("Editor.Exposure.Deflicker"),
AdvisorParameters.DeflickerWindow => Loc.L("Editor.Exposure.Window"),
AdvisorParameters.DeflickerStrength => Loc.L("Editor.Exposure.Strength"),
AdvisorParameters.Regions => Loc.L("Editor.Exposure.Regions"),
AdvisorParameters.HolyGrail => Loc.L("Editor.Exposure.HolyGrail"),
AdvisorParameters.TransitionLength => Loc.L("Editor.Exposure.Transitions"),
AdvisorParameters.WhiteBalanceSmoothing => Loc.L("Editor.Exposure.WhiteBalance"),
AdvisorParameters.MotionBlur => Loc.L("Editor.Motion.Blur"),
AdvisorParameters.TargetShutterAngle => Loc.L("Editor.Motion.Shutter"),
AdvisorParameters.FlowQuality => Loc.L("Editor.Motion.Flow"),
AdvisorParameters.Stabilize => Loc.L("Editor.Motion.Stabilize"),
AdvisorParameters.StabilizeSmoothing => Loc.L("Editor.Motion.Smoothing"),
AdvisorParameters.Aspect => Loc.L("Editor.Camera.Aspect"),
AdvisorParameters.OffsetY => Loc.L("Editor.Camera.OffsetY"),
AdvisorParameters.ExportPreset => Loc.L("Editor.Export.Preset"),
AdvisorParameters.Resolution => Loc.L("Editor.Export.Resolution"),
_ => parameter,
};
private static string ValueText(object? value) => value switch
{
null => Loc.L("Editor.Value.None"),
bool b => Loc.L(b ? "Editor.Value.On" : "Editor.Value.Off"),
TimingMode m => Loc.L("Editor.Timing." + m),
RegionMode m => m == RegionMode.Off ? Loc.L("Editor.Value.Off") : Loc.L("Editor.Regions." + m),
FlowQualitySetting q => Loc.L("Editor.Flow." + q),
string id when ExportPresets.Find(id) is { } preset => Loc.L(preset.NameKey),
string text => text,
double d => d.ToString("0.##", Loc.Culture),
IEnumerable list => Loc.Plural("Editor.Value.Frames", list.Cast<object>().LongCount()),
IFormattable f => f.ToString(null, Loc.Culture),
_ => value.ToString() ?? string.Empty,
};
/// <summary>A rendered preview as frozen bitmaps and overlays in picture pixels (built off the UI thread).</summary>
private sealed record PreviewResult(ImageSource Corrected, ImageSource Original, Rect Crop, IReadOnlyList<Point> Horizon, IReadOnlyList<MotionVector> Vectors)
private sealed record PreviewResult(ImageSource Corrected, ImageSource Original, Rect Crop, IReadOnlyList<Point> Horizon, IReadOnlyList<MotionVector> Vectors,
ImageSource? Waveform)
{
public static PreviewResult From(PreviewFrame frame) => new(
EditorImages.ToBitmap(frame.Corrected),
EditorImages.ToBitmap(frame.Original),
new Rect(frame.Crop.X, frame.Crop.Y, frame.Crop.Width, frame.Crop.Height),
[.. frame.Horizon.Select(p => new Point(p.X, p.Y))],
[.. frame.Vectors.Select(v => new MotionVector(v.X, v.Y, v.Dx, v.Dy))]);
[.. frame.Vectors.Select(v => new MotionVector(v.X, v.Y, v.Dx, v.Dy))],
frame.Waveform is { } waveform ? EditorImages.ToMask(waveform) : null);
}
}