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

Closes #21

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

662 lines
35 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using 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;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
namespace Chronos.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. On a server sequence, settings both sides changed to
/// different values wait for the user's choice (<see cref="Conflict"/>). Frames inserted under the editor (a sync
/// download, an import of earlier photos, a scan) are read again before the next save or render, and the project's frame
/// positions, its undo steps included, move with their frames as the stored ones did. Call from one thread (the UI thread).
/// </summary>
public sealed class EditorSession : IAsyncDisposable
{
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
/// <summary>Times a save reads the frames again when frames keep changing under it.</summary>
private const int FollowAttempts = 3;
/// <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;
/// <summary>
/// The sequence being read again (<see cref="BeginReadAsync"/>) until its content is taken: saves and other reads wait
/// for it.
/// </summary>
private Task _reading = Task.CompletedTask;
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;
// Undo steps take outside changes as the source merges them (a workspace project: positions photo by photo).
History = new ProjectHistory(content.Project, merge: (basis, ours, theirs) => source.Merge(basis, ours, theirs).Merged);
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). A conflict
/// raises <see cref="ConflictFound"/> instead.
/// </summary>
public event Action<Exception>? SaveFailed;
/// <summary>A save met settings changed on the server too (<see cref="Conflict"/> was null): the user picks a side.</summary>
public event Action<ProjectConflictException>? ConflictFound;
/// <summary>
/// An edit not stored yet met a newer Chronos's settings stored meanwhile, which this one never merges with: the edit
/// was kept aside at the path given (<see cref="ISequenceSource.SetAsideAsync"/>) and the newer settings shown read-only.
/// </summary>
public event Action<string>? EditSetAside;
public ISequenceSource Source { get; }
/// <summary>A server sequence edited with proxies: saved, analysed and rendered on the server.</summary>
public bool IsRemote => Source.IsRemote;
/// <summary>The project is shown, not changed (<see cref="ISequenceSource.IsReadOnly"/>): edits, undo and redo do nothing.</summary>
public bool IsReadOnly => Source.IsReadOnly;
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>
/// Settings this editor and someone on the server changed to different values, as the last save found them; null
/// when there are none. Saves wait (they are retried and meet it again) until <see cref="ResolveConflict"/>.
/// </summary>
public ProjectConflictException? Conflict { get; private set; }
/// <summary>
/// Applies <paramref name="change"/> as an undoable step; false when it changes nothing. A crop box locked to the
/// output proportions follows a change of them (<see cref="KeepCropLocked"/>) in the same step.
/// </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);
if (IsReadOnly) return false;
var before = Project;
return History.Apply(KeepCropLocked(before, change(before), Content.SourceWidth, Content.SourceHeight), mergeKey);
}
/// <summary>
/// One press of the Camera step's orientation controls (Rotate left or right, Mirror, Flip) as one undo step: the
/// picture turns or mirrors as the user sees it, and the crop and the keyframes with it (<see cref="OrientationEdit"/>,
/// owner review 1, R6).
/// </summary>
public bool Orient(OrientationOp op) => Edit(p => OrientationEdit.Apply(p, op));
/// <summary>
/// "Reset framing": the crop, its offsets, the rotation, mirror, flip and straighten cleared as one undo step; the
/// keyframes stay (<see cref="WithoutFraming"/>).
/// </summary>
public bool ResetFraming() => Edit(WithoutFraming);
/// <summary>The crop's width over its height in normalised view units for <paramref name="project"/> (<see cref="LockRatioOf"/>).</summary>
public double CropLockRatio(ProjectSettings project) => LockRatioOf(project, Content.SourceWidth, Content.SourceHeight);
/// <summary>
/// The lock ratio of the Camera step's crop (<see cref="RenderGeometry.LockRatio"/>): the output ratio the render fits
/// the crop to, in units of the view frame of a source of the given size; a 1×1 view when the size is unknown.
/// </summary>
public static double LockRatioOf(ProjectSettings project, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(project);
var (width, height) = sourceWidth > 0 && sourceHeight > 0 ? (sourceWidth, sourceHeight) : (1, 1);
return RenderGeometry.Create(project.Camera, ExportResolver.Resolve(project.Export), width, height).LockRatio;
}
/// <summary>
/// The project without framing: no crop, no offsets, no rotation, mirror, flip or straighten. The orientation is undone
/// press by press (<see cref="OrientationEdit"/>: the flip, the mirror, then quarter turns back), so the keyframes, the
/// parked ones and the aspect stay on the content they framed: a 9:16 set on a quarter-turned landscape is 16:9 again.
/// </summary>
public static ProjectSettings WithoutFraming(ProjectSettings project)
{
ArgumentNullException.ThrowIfNull(project);
var upright = project;
if (upright.Camera.Flip) upright = OrientationEdit.Apply(upright, OrientationOp.Flip);
if (upright.Camera.Mirror) upright = OrientationEdit.Apply(upright, OrientationOp.Mirror);
for (var turns = FrameOrientation.TurnsOf(upright.Camera.Rotate); turns > 0; turns--) upright = OrientationEdit.Apply(upright, OrientationOp.RotateLeft);
return upright with { Camera = upright.Camera with { Crop = null, OffsetX = 0, OffsetY = 0, Rotate = 0, Mirror = false, Flip = false, Straighten = 0 } };
}
/// <summary>Something <see cref="ResetFraming"/> clears is set.</summary>
public static bool HasFraming(CameraSettings camera)
{
ArgumentNullException.ThrowIfNull(camera);
return camera.Crop is not null || camera.OffsetX != 0 || camera.OffsetY != 0 || camera.Rotate != 0 || camera.Mirror || camera.Flip || camera.Straighten != 0;
}
/// <summary>
/// <paramref name="after"/> with its crop refitted to new output proportions (owner review 1, R5: an aspect change, a
/// turn of a "source" aspect, an export preset of another shape): a box that was locked to the proportions before keeps
/// its centre and area at the new ratio (<see cref="CropFrame.Refit"/>). A legacy free crop, one placed by offsets, and a
/// box already at the new ratio stay as they are (the render fits them, <see cref="AspectRatio.FitCrop"/>).
/// </summary>
public static ProjectSettings KeepCropLocked(ProjectSettings before, ProjectSettings after, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(before);
ArgumentNullException.ThrowIfNull(after);
var camera = after.Camera;
if (CropFrame.IsWhole(camera.Crop) || camera.OffsetX != 0 || camera.OffsetY != 0) return after;
if (ReferenceEquals(before.Camera, camera) && ReferenceEquals(before.Export, after.Export)) return after;
var ratio = LockRatioOf(after, sourceWidth, sourceHeight);
var box = CropFrame.Of(camera.Crop);
if (IsLocked(box, ratio)) return after;
if (before.Camera.OffsetX != 0 || before.Camera.OffsetY != 0 || !IsLocked(CropFrame.Of(before.Camera.Crop), LockRatioOf(before, sourceWidth, sourceHeight)))
return after;
return after with { Camera = camera with { Crop = CropFrame.ToCrop(CropFrame.Refit(box, ratio)) } };
static bool IsLocked(RectD box, double lockRatio) => double.Abs(box.Width / box.Height / lockRatio - 1) < 1e-6;
}
/// <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() => !IsReadOnly && History.Undo();
public bool Redo() => !IsReadOnly && 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 (refitted to the preset's aspect), orientation, keyframes, remap
/// curve, exposure offset, look 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 jobs that render <paramref name="export"/> and its batch: one job on this PC (the sequence is prepared once),
/// one per preset on a server, where a render node uploads one file per job (BRIEF §14.7), and for a workspace project
/// one per preset at its home with the project's portable settings (<see cref="IProjectRenders"/>, owner review 2, R8).
/// </summary>
public IReadOnlyList<ArchiveJobRequest> RenderRequests(ExportSettings export) => Source switch
{
IProjectRenders renders => renders.RenderRequests(Content.Sequence, Project, export, Content.SourceWidth, Content.SourceHeight),
_ when IsRemote => ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }),
_ => [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). A source that renders
/// elsewhere (<see cref="IProjectRenders"/>) without still jobs of its own saves none.
/// </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>
/// <returns>The restore, which its toast can take back while it is the last change.</returns>
/// <exception cref="System.IO.InvalidDataException">The copy cannot be read.</exception>
public async Task<ProjectRestore?> RestoreAsync(SavedCopy copy)
{
ArgumentNullException.ThrowIfNull(copy);
var restored = await Task.Run(() => SavedCopies.Read(copy));
var before = Project;
return Edit(_ => restored) ? new ProjectRestore(this, before, Project) : null;
}
/// <summary>
/// Settles <see cref="Conflict"/> against the settings stored meanwhile (the server's, a workspace's working state a sync
/// wrote) as the last save read them. Both choices first take in what only the other side changed (like any merge,
/// without an undo step). <paramref name="keepMine"/> then saves the editor's values of the settings both changed;
/// otherwise the other side's values become the project as one undoable step, so Ctrl+Z brings the editor's back (and
/// saves them).
/// </summary>
/// <returns>False when there is no conflict to settle (a later save already went through).</returns>
public bool ResolveConflict(bool keepMine)
{
if (Conflict is not { Server: var theirs }) return false;
Conflict = null;
var basis = _basis;
_basis = theirs;
try
{
History.Replace(Source.Merge(basis, Project, theirs).Merged);
if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged);
}
catch (NewerSettingsException ex)
{
// Never merged with a newer Chronos's settings: the edit is kept aside, those settings shown read-only.
_ = TakeNewerAsync(theirs, ex, CancellationToken.None);
return true;
}
// The change waiting for its retry goes now, on top of the server's settings.
_ = _saver.FlushAsync();
return true;
}
/// <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>
/// Makes the project's frame positions name the sequence's frames as they are now, before the project is taken along
/// (a render embeds it): frames inserted since the last read (a sync download, an import of earlier photos, a scan)
/// are read again and the positions follow them (<see cref="ReloadAsync"/>). A server sequence whose frames changed
/// becomes outdated instead (<see cref="ISequenceSource.IsOutdated"/>: read-only, its renders refused).
/// </summary>
public async Task EnsureFramesAsync(CancellationToken cancellationToken = default)
{
while (!_reading.IsCompleted) await _reading;
var current = await Source.FramesCurrentAsync(cancellationToken);
// A read that began meanwhile (a save that met the new frames) may have taken them already: it ends first.
while (!_reading.IsCompleted) await _reading;
if (!current && !IsRemote) await ReloadAsync(cancellationToken);
}
/// <summary>
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken,
/// and a read waits for the one under way, so each follows the frames the one before it took. A stored project of a
/// newer Chronos met with an edit not stored yet is never merged: the edit is kept aside and the newer settings shown
/// read-only (<see cref="EditSetAside"/>).
/// </summary>
public async Task ReloadAsync(CancellationToken cancellationToken = default)
{
await _saver.FlushAsync();
var taken = await BeginReadAsync();
try
{
var content = await Source.LoadAsync(cancellationToken);
Follow(content);
// Settings a server or a sync stored that conflict with the editor's waiting change are not merged over it: that
// change's retry meets them and asks (Conflict).
ProjectMergeResult? merge = null;
try
{
merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null;
}
catch (NewerSettingsException ex)
{
await TakeNewerAsync(content.Project, ex, cancellationToken);
}
if (merge is not null && (!Source.AsksConflicts || !merge.HasConflicts))
{
_basis = content.Project;
History.Replace(merge.Merged);
}
}
finally
{
taken.SetResult();
}
ContentChanged?.Invoke();
}
/// <summary>
/// Reads the project again after the user took the other side's values of the settings both changed (a workspace
/// project's "Take the library's", settled by its sync): what only the other side changed comes in as any merge does,
/// without an undo step (<paramref name="kept"/>: the stored project as keeping the editor's values would have left
/// it), then the values taken become the project as one undoable step, so Ctrl+Z brings the editor's back (and saves
/// them), as <see cref="ResolveConflict"/> does for a server's.
/// </summary>
/// <returns>That step, which a toast's Undo can take back while it is the last change; null when it changed nothing.</returns>
public async Task<ProjectRestore?> TakeOverAsync(ProjectSettings kept, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(kept);
await _saver.FlushAsync();
var taken = await BeginReadAsync();
ProjectRestore? step = null;
try
{
var content = await Source.LoadAsync(cancellationToken);
Follow(content);
var basis = _basis;
_basis = content.Project;
try
{
History.Replace(Source.Merge(basis, Project, kept).Merged);
var before = Project;
if (!IsReadOnly && History.Apply(Source.Merge(kept, Project, content.Project).Merged)) step = new ProjectRestore(this, before, Project);
}
catch (NewerSettingsException ex)
{
_basis = basis;
await TakeNewerAsync(content.Project, ex, cancellationToken);
}
}
finally
{
taken.SetResult();
}
ContentChanged?.Invoke();
return step;
}
/// <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>
/// Stops retrying a change that could not be stored while the user decides about it (<see cref="ProjectSaver.HoldAsync"/>);
/// end it with <see cref="KeepPending"/> or <see cref="DiscardPending"/>.
/// </summary>
/// <returns>True when a change is still not stored; false when a retry stored it meanwhile (nothing to decide).</returns>
public Task<bool> HoldPendingAsync() => _saver.HoldAsync();
/// <summary>The user kept the change: it is retried in the background as before.</summary>
public void KeepPending() => _saver.Release();
/// <summary>The user discarded the change: it is dropped and never written, and nothing more is saved (the editor closes).</summary>
public void DiscardPending() => _saver.Stop();
/// <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();
}
/// <summary>
/// Takes <paramref name="content"/> as the sequence. Frames inserted or removed since the last read (a sync download,
/// an import of earlier photos, a scan) moved the stored project's frame positions with their frames: the editor's
/// project, its undo and redo steps and its basis move the same way (<see cref="ProjectSettings.FollowFrames"/>), so
/// they keep naming the frames the user chose. Call while the read is under way (<see cref="BeginReadAsync"/>).
/// </summary>
private void Follow(SequenceContent content)
{
var before = Content.Frames.Select(f => f.Id).ToList();
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return;
var after = content.Frames;
Log.Info("editor", $"The frames of {content.Sequence.DisplayTitle} changed while it was open; its frame positions follow them");
_basis = Move(_basis);
History.Remap(Move);
ProjectSettings Move(ProjectSettings project) =>
NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project;
}
/// <summary>
/// The stored project is a newer Chronos's (<paramref name="newer"/>) while the editor holds an edit not stored yet,
/// which this Chronos can neither merge with it nor store over it (<see cref="NewerSettingsException"/>): the edit is
/// kept aside by the source (<see cref="ISequenceSource.SetAsideAsync"/>, said by <see cref="EditSetAside"/>), never
/// dropped silently, and only then are the newer settings taken, read-only, the pending save dropped with it. A source
/// that keeps nothing aside, or a set-aside that fails, leaves the editor as it is (logged): the next read tries again.
/// Never throws.
/// </summary>
private async Task TakeNewerAsync(ProjectSettings newer, NewerSettingsException cause, CancellationToken cancellationToken)
{
var unsaved = Project;
string? kept;
try
{
kept = await Source.SetAsideAsync(unsaved, cancellationToken);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet could not be kept aside; it stays in the editor", ex);
return;
}
if (kept is null)
{
Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet meets newer settings and stays in the editor: {cause.Message}");
return;
}
Log.Info("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet was kept in {kept}: the stored project is a newer Chronos's ({cause.Message})");
_saver.Drop();
Conflict = null;
_basis = newer;
History.Replace(newer);
EditSetAside?.Invoke(kept);
}
/// <summary>
/// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new
/// one under way until the returned source is completed.
/// </summary>
private async Task<TaskCompletionSource> BeginReadAsync()
{
while (!_reading.IsCompleted) await _reading;
var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_reading = taken.Task;
return taken;
}
/// <summary>Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames.</summary>
private static bool NamesFrames(ProjectSettings project) =>
project.ExcludedFrames.Count > 0 || project.HeroFrame is not null || project.Camera.Keyframes.Count > 0 || project.PendingFrames is { Count: > 0 };
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)
{
if (IsReadOnly) return [];
var settings = Project;
var advice = AdviceFor(settings.Camera);
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(KeepCropLocked(Project, settings, Content.SourceWidth, Content.SourceHeight));
return changes;
}
/// <summary>
/// The advice for the view of <paramref name="camera"/>: <see cref="Advice"/> while the camera is not turned, flipped or straightened,
/// else worked out again on the turned view (<see cref="SequenceContext.ForCamera"/>), so that "Optimise" after a turn
/// keeps the transposed aspect <see cref="OrientationEdit"/> wrote instead of the unturned one.
/// </summary>
private AdvisorResult AdviceFor(CameraSettings camera) =>
camera.Rotate == Context.Rotate && camera.Flip == Context.Flip && camera.Straighten.Equals(Context.Straighten)
? Advice
: Advisor.Recommend(Content.Light, Content.Deep, Context.ForCamera(camera));
private void OnSaveFailed(Exception ex, int failures)
{
// A conflict is retried without the network until the user settles it: noted once, when it is found.
if (ex is ProjectConflictException) return;
Log.Warning("editor", $"Saving the project of {Content.Sequence.DisplayTitle} failed (attempt {failures})", ex);
if (failures == 1) SaveFailed?.Invoke(ex);
}
private void OnProjectChanged()
{
// A read-only project takes what is read again (a workspace pull of a newer Chronos's settings) without a save that
// could never be stored and would be retried for ever.
if (!IsReadOnly) _saver.Schedule(Project);
ProjectChanged?.Invoke();
}
private async Task SaveAsync(ProjectSettings project)
{
if (!_reading.IsCompleted)
{
// A read under way decides the frames the project's positions name. Once it is taken, the project as it is
// then contains this change (projects are whole snapshots), with its positions on those frames.
while (!_reading.IsCompleted) await _reading;
project = Project;
}
ProjectSettings stored;
for (var attempt = 1; ; attempt++)
{
try
{
stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
break;
}
catch (FramesChangedException) when (attempt < FollowAttempts)
{
// Frames were inserted under the editor and the stored positions moved with them: the frames are read
// again (after a read under way, whose move this edit's snapshot missed), the project's positions follow
// them, and the project as it is then, which contains this edit, is saved in the new order.
var taken = await BeginReadAsync();
try
{
Follow(await Source.LoadAsync(CancellationToken.None));
}
finally
{
taken.SetResult();
}
project = Project;
ContentChanged?.Invoke();
}
catch (ProjectConflictException ex)
{
var found = Conflict is null;
Conflict = ex;
if (found)
{
Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}");
ConflictFound?.Invoke(ex);
}
throw;
}
}
Conflict = null;
_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(Source.Merge(project, Project, stored).Merged);
}
}
/// <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
/// save it would take that change back instead.
/// </summary>
public sealed class ProjectRestore(EditorSession session, ProjectSettings before, ProjectSettings restored)
{
public bool CanUndo => ReferenceEquals(session.Project, restored);
public bool Undo() => CanUndo && session.Edit(_ => before);
}