- Tests for undo after adopted changes, run ending, saver retries and stop, the local source refusing unsaved writes, re-solves without decoding and equal to a fresh preparation, 1:1 pictures, waveform, crop margins and the values of the Optimise toast; the Windows smoke test checks Render, Batch, the waveform, 1:1, the window title and the hidden idle job bar. - The capture sample has a manual value and camera keyframes; the capture adds the overlays, the waveform, the Optimise toast and Export.html's tool state. - Crop margins live in a WPF-free class; a discarded change stops retrying. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
212 lines
10 KiB
C#
212 lines
10 KiB
C#
using Titano.Core.Advice;
|
|
using Titano.Core.Diagnostics;
|
|
using Titano.Core.Export;
|
|
using Titano.Core.Project;
|
|
using Titano.Core.Video;
|
|
using Titano.Data.Archiving.Jobs;
|
|
using Titano.Data.Processing;
|
|
|
|
namespace Titano.App.Editor;
|
|
|
|
/// <summary>
|
|
/// One sequence open in the editor (BRIEF §12.3): its content, the advisor's view of it (§10.3), the project with undo
|
|
/// and redo, and the actions of every section — edit, Optimise (§10.4), Reset, exclusions and hero, analysis and render
|
|
/// jobs. Every change is saved shortly after it is made (<see cref="ProjectSaver"/>); a change stored meanwhile by
|
|
/// someone else (an analysis job, another client) is merged in. Call from one thread (the UI thread).
|
|
/// </summary>
|
|
public sealed class EditorSession : IAsyncDisposable
|
|
{
|
|
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
|
|
|
|
/// <summary>Sections "Optimise all" walks through, in panel order.</summary>
|
|
public static IReadOnlyList<AdvisorSection> OptimisedSections { get; } =
|
|
[AdvisorSection.Frames, AdvisorSection.Timing, AdvisorSection.Exposure, AdvisorSection.Motion, AdvisorSection.Camera, AdvisorSection.Export];
|
|
|
|
private readonly IReadOnlyList<EncoderCapability> _codecs;
|
|
private readonly ProjectSaver _saver;
|
|
private ProjectSettings _basis;
|
|
|
|
public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList<EncoderCapability> codecs, TimeSpan? saveDelay = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(source);
|
|
ArgumentNullException.ThrowIfNull(content);
|
|
Source = source;
|
|
_codecs = codecs ?? [];
|
|
_basis = content.Project;
|
|
History = new ProjectHistory(content.Project);
|
|
History.Changed += OnProjectChanged;
|
|
_saver = new ProjectSaver(SaveAsync, saveDelay ?? DefaultSaveDelay);
|
|
_saver.Failed += OnSaveFailed;
|
|
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
|
}
|
|
|
|
/// <summary>The project changed (edit, undo, redo, Optimise, a merge).</summary>
|
|
public event Action? ProjectChanged;
|
|
|
|
/// <summary>The sequence was read again (after an analysis): frames, reports, advice and presets.</summary>
|
|
public event Action? ContentChanged;
|
|
|
|
/// <summary>Saving the project failed (raised once per run of failures; the save is retried until it succeeds).</summary>
|
|
public event Action<Exception>? SaveFailed;
|
|
|
|
public ISequenceSource Source { get; }
|
|
|
|
public SequenceContent Content { get; private set; }
|
|
|
|
public SequenceContext Context { get; private set; }
|
|
|
|
/// <summary>The advisor's recommendations and findings for the current analyses.</summary>
|
|
public AdvisorResult Advice { get; private set; }
|
|
|
|
/// <summary>Sequence presets that fit the content, best first (BRIEF §10.3).</summary>
|
|
public IReadOnlyList<SequencePreset> Presets { get; private set; }
|
|
|
|
public ProjectHistory History { get; }
|
|
|
|
public ProjectSettings Project => History.Current;
|
|
|
|
/// <summary>A change is waiting for its save, being saved, or waiting for a retry after a failed save.</summary>
|
|
public bool HasPendingSave => _saver.HasPendingChanges;
|
|
|
|
/// <summary>Why the pending change could not be stored; null when the last save succeeded.</summary>
|
|
public Exception? LastSaveError => _saver.LastError;
|
|
|
|
/// <summary>Applies <paramref name="change"/> as an undoable step; false when it changes nothing.</summary>
|
|
/// <param name="mergeKey">Consecutive edits with the same key are one undo step (a slider drag).</param>
|
|
public bool Edit(Func<ProjectSettings, ProjectSettings> change, string? mergeKey = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(change);
|
|
return History.Apply(change(Project), mergeKey);
|
|
}
|
|
|
|
/// <summary>The drag or key press behind a run of merged edits ended (<see cref="ProjectHistory.EndRun"/>).</summary>
|
|
public void EndEditRun() => History.EndRun();
|
|
|
|
public bool Undo() => History.Undo();
|
|
|
|
public bool Redo() => History.Redo();
|
|
|
|
/// <summary>"Optimise section": the advisor's heavier decisions for <paramref name="section"/>, one undo step; returns what changed.</summary>
|
|
public IReadOnlyList<SettingChange> Optimise(AdvisorSection section) => Optimise([section]);
|
|
|
|
/// <summary>"Optimise all": every section, one undo step.</summary>
|
|
public IReadOnlyList<SettingChange> OptimiseAll() => Optimise(OptimisedSections);
|
|
|
|
/// <summary>"Reset": the section's Auto settings back to Auto.</summary>
|
|
public bool ResetSection(AdvisorSection section) => Edit(p => EditorSettings.ResetSection(p, section));
|
|
|
|
/// <summary>Adds frames to, or removes them from, the project's exclusions.</summary>
|
|
public bool SetExcluded(IEnumerable<int> frames, bool excluded)
|
|
{
|
|
var chosen = frames.Where(i => (uint)i < (uint)Content.Count).ToHashSet();
|
|
return Edit(p => p with
|
|
{
|
|
ExcludedFrames = excluded ? [.. p.ExcludedFrames.Union(chosen).Order()] : [.. p.ExcludedFrames.Where(i => !chosen.Contains(i))],
|
|
});
|
|
}
|
|
|
|
/// <summary>Makes <paramref name="frame"/> the hero frame (sequence thumbnail).</summary>
|
|
public bool SetHero(int frame) => (uint)frame < (uint)Content.Count && Edit(p => p with { HeroFrame = frame });
|
|
|
|
/// <summary>
|
|
/// Applies a sequence preset (BRIEF §10.3) as one undoable step: its timing, exposure, motion, aspect and export
|
|
/// preset; the user's frames (exclusions, hero), crop, keyframes, remap curve, exposure offset and output naming stay.
|
|
/// </summary>
|
|
public bool ApplyPreset(SequencePreset preset)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(preset);
|
|
var s = preset.Settings;
|
|
return Edit(p => p with
|
|
{
|
|
Timing = s.Timing with { RemapCurve = p.Timing.RemapCurve, FitToSeconds = p.Timing.FitToSeconds },
|
|
Exposure = s.Exposure with { ExposureOffsetEv = p.Exposure.ExposureOffsetEv, HighlightKnee = p.Exposure.HighlightKnee },
|
|
Motion = s.Motion,
|
|
Camera = p.Camera with { Aspect = s.Camera.Aspect },
|
|
Export = p.Export with { Preset = s.Export.Preset, Overrides = new ExportOverrides() },
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// A render of <paramref name="export"/> with the project as it is now (the job embeds it, so a render queued before
|
|
/// the save lands still renders what the user sees).
|
|
/// </summary>
|
|
public ArchiveJobRequest RenderRequest(ExportSettings export, bool useProxies = false) =>
|
|
ProcessingJobs.Render(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }, useProxies);
|
|
|
|
/// <summary>The export of the project with preset <paramref name="presetId"/> chosen (own values, no batch).</summary>
|
|
public ExportSettings ExportFor(string presetId) =>
|
|
Project.Export with { Preset = Project.Export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] };
|
|
|
|
public ArchiveJobRequest AnalysisRequest() => ProcessingJobs.DeepAnalysis([Content.Sequence.Id], Content.Sequence.DisplayTitle);
|
|
|
|
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken);
|
|
|
|
/// <summary>Reads the sequence again (an analysis finished): new reports and advice, the stored project merged into the open one.</summary>
|
|
public async Task ReloadAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
await _saver.FlushAsync();
|
|
var content = await Source.LoadAsync(cancellationToken);
|
|
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
|
_basis = content.Project;
|
|
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
|
History.Replace(merged);
|
|
ContentChanged?.Invoke();
|
|
}
|
|
|
|
/// <summary>Stores pending changes now; false when the save failed (the change stays pending and is retried).</summary>
|
|
public Task<bool> FlushAsync() => _saver.FlushAsync();
|
|
|
|
/// <summary>
|
|
/// Stores what is pending one last time, stops retrying and releases the source; callers that must not lose an edit
|
|
/// flush and ask first (<c>SequenceViewModel.ConfirmCloseAsync</c>).
|
|
/// </summary>
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
History.Changed -= OnProjectChanged;
|
|
if (!await _saver.FlushAsync()) Log.Warning("editor", $"The last change of {Content.Sequence.DisplayTitle} was not saved", _saver.LastError);
|
|
_saver.Stop();
|
|
await Source.DisposeAsync();
|
|
}
|
|
|
|
private static (SequenceContent, SequenceContext, AdvisorResult, IReadOnlyList<SequencePreset>) Analyse(SequenceContent content,
|
|
IReadOnlyList<EncoderCapability> codecs)
|
|
{
|
|
var context = SequenceContext.FromFrames(content.Frames, codecs);
|
|
return (content, context, Advisor.Recommend(content.Light, content.Deep, context), SequencePresets.Generate(content.Light, content.Deep, context));
|
|
}
|
|
|
|
private IReadOnlyList<SettingChange> Optimise(IReadOnlyList<AdvisorSection> sections)
|
|
{
|
|
var settings = Project;
|
|
var changes = new List<SettingChange>();
|
|
foreach (var section in sections)
|
|
{
|
|
var result = Advisor.Optimise(section, settings, Advice);
|
|
settings = result.Settings;
|
|
changes.AddRange(result.Changes);
|
|
}
|
|
History.Apply(settings);
|
|
return changes;
|
|
}
|
|
|
|
private void OnSaveFailed(Exception ex, int failures)
|
|
{
|
|
Log.Warning("editor", $"Saving the project of {Content.Sequence.DisplayTitle} failed (attempt {failures})", ex);
|
|
if (failures == 1) SaveFailed?.Invoke(ex);
|
|
}
|
|
|
|
private void OnProjectChanged()
|
|
{
|
|
_saver.Schedule(Project);
|
|
ProjectChanged?.Invoke();
|
|
}
|
|
|
|
private async Task SaveAsync(ProjectSettings project)
|
|
{
|
|
var stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
|
_basis = stored;
|
|
// Someone else's change was merged in: show it without an undo step (edits made since the save are kept).
|
|
if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored));
|
|
}
|
|
}
|