using Chronos.Core.Advice;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
namespace Chronos.App.Editor;
///
/// 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 (); 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 (). 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).
///
public sealed class EditorSession : IAsyncDisposable
{
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
/// Times a save reads the frames again when frames keep changing under it.
private const int FollowAttempts = 3;
/// Sections "Optimise all" walks through, in panel order.
public static IReadOnlyList OptimisedSections { get; } =
[AdvisorSection.Frames, AdvisorSection.Timing, AdvisorSection.Exposure, AdvisorSection.Motion, AdvisorSection.Camera, AdvisorSection.Export];
private readonly IReadOnlyList _codecs;
private readonly ProjectSaver _saver;
private ProjectSettings _basis;
///
/// The sequence being read again () until its content is taken: saves and other reads wait
/// for it.
///
private Task _reading = Task.CompletedTask;
public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList 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);
}
/// The project changed (edit, undo, redo, Optimise, a merge).
public event Action? ProjectChanged;
/// The sequence was read again (after an analysis): frames, reports, advice and presets.
public event Action? ContentChanged;
///
/// Saving the project failed (raised once per run of failures; the save is retried until it succeeds). A conflict
/// raises instead.
///
public event Action? SaveFailed;
/// A save met settings changed on the server too ( was null): the user picks a side.
public event Action? ConflictFound;
public ISequenceSource Source { get; }
/// A server sequence edited with proxies: saved, analysed and rendered on the server.
public bool IsRemote => Source.IsRemote;
/// The project is shown, not changed (): edits, undo and redo do nothing.
public bool IsReadOnly => Source.IsReadOnly;
public SequenceContent Content { get; private set; }
public SequenceContext Context { get; private set; }
/// The advisor's recommendations and findings for the current analyses.
public AdvisorResult Advice { get; private set; }
/// Sequence presets that fit the content, best first (BRIEF §10.3).
public IReadOnlyList Presets { get; private set; }
public ProjectHistory History { get; }
public ProjectSettings Project => History.Current;
/// A change is waiting for its save, being saved, or waiting for a retry after a failed save.
public bool HasPendingSave => _saver.HasPendingChanges;
/// Why the pending change could not be stored; null when the last save succeeded.
public Exception? LastSaveError => _saver.LastError;
///
/// 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 .
///
public ProjectConflictException? Conflict { get; private set; }
/// Applies as an undoable step; false when it changes nothing.
/// Consecutive edits with the same key are one undo step (a slider drag).
public bool Edit(Func change, string? mergeKey = null)
{
ArgumentNullException.ThrowIfNull(change);
return !IsReadOnly && History.Apply(change(Project), mergeKey);
}
/// The drag or key press behind a run of merged edits ended ().
public void EndEditRun() => History.EndRun();
public bool Undo() => !IsReadOnly && History.Undo();
public bool Redo() => !IsReadOnly && History.Redo();
/// "Optimise section": the advisor's heavier decisions for , one undo step; returns what changed.
public IReadOnlyList Optimise(AdvisorSection section) => Optimise([section]);
/// "Optimise all": every section, one undo step.
public IReadOnlyList OptimiseAll() => Optimise(OptimisedSections);
/// "Reset": the section's Auto settings back to Auto.
public bool ResetSection(AdvisorSection section) => Edit(p => EditorSettings.ResetSection(p, section));
/// Adds frames to, or removes them from, the project's exclusions.
public bool SetExcluded(IEnumerable 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))],
});
}
/// Makes the hero frame (sequence thumbnail).
public bool SetHero(int frame) => (uint)frame < (uint)Content.Count && Edit(p => p with { HeroFrame = frame });
///
/// 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.
///
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() },
});
}
///
/// A render of 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).
///
public ArchiveJobRequest RenderRequest(ExportSettings export, bool useProxies = false) =>
ProcessingJobs.Render(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }, useProxies);
///
/// The jobs that render 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 (, owner review 2, R8).
///
public IReadOnlyList 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)],
};
///
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
///
/// The restore, which its toast can take back while it is the last change.
/// The copy cannot be read.
public async Task 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;
}
///
/// Settles 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). 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).
///
/// False when there is no conflict to settle (a later save already went through).
public bool ResolveConflict(bool keepMine)
{
if (Conflict is not { Server: var theirs }) return false;
Conflict = null;
var basis = _basis;
_basis = theirs;
History.Replace(Source.Merge(basis, Project, theirs).Merged);
if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged);
// The change waiting for its retry goes now, on top of the server's settings.
_ = _saver.FlushAsync();
return true;
}
/// The export of the project with preset chosen (own values, no batch).
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 SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken);
///
/// 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 (). A server sequence whose frames changed
/// becomes outdated instead (: read-only, its renders refused).
///
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);
}
///
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
/// following them (), 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.
///
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).
var merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null;
if (merge is not null && (!Source.AsksConflicts || !merge.HasConflicts))
{
_basis = content.Project;
History.Replace(merge.Merged);
}
}
finally
{
taken.SetResult();
}
ContentChanged?.Invoke();
}
///
/// 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 (: 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 does for a server's.
///
/// That step, which a toast's Undo can take back while it is the last change; null when it changed nothing.
public async Task 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;
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);
}
finally
{
taken.SetResult();
}
ContentChanged?.Invoke();
return step;
}
/// Stores pending changes now; false when the save failed (the change stays pending and is retried).
public Task FlushAsync() => _saver.FlushAsync();
///
/// Stops retrying a change that could not be stored while the user decides about it ();
/// end it with or .
///
/// True when a change is still not stored; false when a retry stored it meanwhile (nothing to decide).
public Task HoldPendingAsync() => _saver.HoldAsync();
/// The user kept the change: it is retried in the background as before.
public void KeepPending() => _saver.Release();
/// The user discarded the change: it is dropped and never written, and nothing more is saved (the editor closes).
public void DiscardPending() => _saver.Stop();
///
/// Stores what is pending one last time, stops retrying and releases the source; callers that must not lose an edit
/// flush and ask first (SequenceViewModel.ConfirmCloseAsync).
///
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();
}
///
/// Takes 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 (), so
/// they keep naming the frames the user chose. Call while the read is under way ().
///
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;
}
///
/// 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.
///
private async Task BeginReadAsync()
{
while (!_reading.IsCompleted) await _reading;
var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_reading = taken.Task;
return taken;
}
/// Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames.
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) Analyse(SequenceContent content,
IReadOnlyList 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 Optimise(IReadOnlyList sections)
{
if (IsReadOnly) return [];
var settings = Project;
var changes = new List();
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)
{
// 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);
}
}
///
/// A "Save both" copy made the project (). 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.
///
public sealed class ProjectRestore(EditorSession session, ProjectSettings before, ProjectSettings restored)
{
public bool CanUndo => ReferenceEquals(session.Project, restored);
public bool Undo() => CanUndo && session.Edit(_ => before);
}