feat: owner review 2 phase 5a: workspace and projects with a local home (#14)
CI / Build and test (push) Successful in 9m43s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 27s
CI / PostgreSQL 16 integration (push) Failing after 8m41s
CI / PostgreSQL 17 integration (push) Successful in 12m37s
CI / Docker image (push) Successful in 56s
Release / Build, test and publish (push) Successful in 14m59s
Release / Server image (push) Successful in 1m51s

Edit opens a sequence as a project of a workspace folder outside the library. Projects have linear version histories kept as sidecars in .chronos/projects/, Main mirrors the sequence's settings, and sync merges setting by setting. Migration 0009, JobKind.WorkspaceCopy = 20, Settings › Workspace, and 241 new strings in 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #14.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 09:22:08 +01:00
1 parent efa87f68ce
commit 9b24cf74fc
370 files changed
+29237 -287

No files matched your search

+127 -19
View File
@@ -5,6 +5,7 @@ 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;
@@ -45,7 +46,8 @@ public sealed class EditorSession : IAsyncDisposable
Source = source;
_codecs = codecs ?? [];
_basis = content.Project;
History = new ProjectHistory(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;
@@ -67,6 +69,12 @@ public sealed class EditorSession : IAsyncDisposable
/// <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>
@@ -165,11 +173,15 @@ public sealed class EditorSession : IAsyncDisposable
/// <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).
/// 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) => IsRemote
? ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })
: [RenderRequest(export)];
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>
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
@@ -185,10 +197,11 @@ public sealed class EditorSession : IAsyncDisposable
}
/// <summary>
/// Settles <see cref="Conflict"/> against the server's settings as the last save read them. Both choices first take
/// in what only the server changed (like any merge, without an undo step). <paramref name="keepMine"/> then saves
/// the editor's values of the settings both changed; otherwise the server's values become the project as one
/// undoable step, so Ctrl+Z brings the editor's back (and saves them).
/// 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)
@@ -197,8 +210,17 @@ public sealed class EditorSession : IAsyncDisposable
Conflict = null;
var basis = _basis;
_basis = theirs;
History.Replace(ProjectMerge.Merge(basis, Project, theirs));
if (!keepMine) History.Apply(ProjectMerge.Merge(basis, theirs, Project));
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;
@@ -230,7 +252,9 @@ public sealed class EditorSession : IAsyncDisposable
/// <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.
/// 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)
{
@@ -240,13 +264,21 @@ public sealed class EditorSession : IAsyncDisposable
{
var content = await Source.LoadAsync(cancellationToken);
Follow(content);
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
// retry meets them and asks (Conflict).
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
// 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))
{
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
_basis = content.Project;
History.Replace(merged);
History.Replace(merge.Merged);
}
}
finally
@@ -256,6 +288,46 @@ public sealed class EditorSession : IAsyncDisposable
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();
@@ -304,6 +376,40 @@ public sealed class EditorSession : IAsyncDisposable
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.
@@ -352,7 +458,9 @@ public sealed class EditorSession : IAsyncDisposable
private void OnProjectChanged()
{
_saver.Schedule(Project);
// 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();
}
@@ -405,7 +513,7 @@ public sealed class EditorSession : IAsyncDisposable
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(ProjectMerge.Merge(project, Project, stored));
if (!ProjectMerge.SameValues(stored, project)) History.Replace(Source.Merge(project, Project, stored).Merged);
}
}
+64 -7
View File
@@ -8,6 +8,7 @@ using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.App.Workspace;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Diagnostics;
@@ -89,6 +90,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>The user chose a step since the editor opened.</summary>
private bool _stepChosen;
private Workspace.ProjectMenuViewModel? _project;
private bool _disposed;
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host)
@@ -147,6 +149,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
session.ContentChanged += OnContentChanged;
session.SaveFailed += OnSaveFailed;
session.ConflictFound += OnConflictFound;
session.EditSetAside += OnEditSetAside;
session.Source.JobChanged += OnJobChanged;
session.Source.ReadOnlyChanged += OnReadOnlyChanged;
shell.Services.Sync.Changed += OnSyncChanged;
@@ -175,6 +178,23 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>A server sequence edited with proxies (the header says where it lives).</summary>
public bool IsRemote => Session.IsRemote;
/// <summary>
/// The project menu beside the title (owner review 2, R8) when the sequence is open as a workspace project: its state,
/// Save version, Sync, History and the rest; null otherwise (a server sequence, a capture's library sequence).
/// </summary>
public Workspace.ProjectMenuViewModel? Project
{
get => _project;
internal set
{
_project?.Dispose();
Set(ref _project, value);
OnPropertyChanged(nameof(HasProject));
}
}
public bool HasProject => _project is not null;
/// <summary>The server a server sequence lives on ("Studio NAS"); null for a sequence of this PC.</summary>
public string? ServerName => IsRemote ? Shell.Services.Server.ServerName ?? Loc.L("Server.Label.Server") : null;
@@ -462,7 +482,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>Why the controls that change the project are disabled; null while they are not.</summary>
public string? LockedToolTip => IsOutdated ? Loc.L("Tooltips.Editor.Outdated", ServerName)
: IsReadOnly ? Loc.L("Tooltips.Editor.ReadOnly")
: IsReadOnly ? Loc.L(Session.Source is WorkspaceSequenceSource ? "Errors.Workspace.ReadOnly" : "Tooltips.Editor.ReadOnly")
: IsBusy ? Loc.L("Tooltips.Editor.Busy")
: null;
@@ -706,11 +726,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Session.ContentChanged -= OnContentChanged;
Session.SaveFailed -= OnSaveFailed;
Session.ConflictFound -= OnConflictFound;
Session.EditSetAside -= OnEditSetAside;
Session.Source.JobChanged -= OnJobChanged;
Session.Source.ReadOnlyChanged -= OnReadOnlyChanged;
Shell.Services.Sync.Changed -= OnSyncChanged;
Shell.Services.SequenceReorganized -= OnSequenceReorganized;
foreach (var tab in Tabs) tab.Dispose();
_project?.Dispose();
base.Dispose();
await Session.DisposeAsync();
}
@@ -1034,17 +1056,43 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
});
/// <summary>
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"): the
/// dialog lists them; Keep mine overwrites the server's, Take server (the safe default, also on Esc) shows theirs as
/// one undoable step. Saving waits until then.
/// An edit not stored yet met a newer Chronos's settings a sync took (owner review 2, R8): it was kept aside in the
/// project's folder, never dropped, and the toast says so; the newer settings show read-only.
/// </summary>
private void OnEditSetAside(string path) => _dispatcher.BeginInvoke(() =>
{
if (_disposed) return;
Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.EditSetAside"), Message = Loc.L("Editor.Workspace.EditSetAsideMessage") });
});
/// <summary>
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"), or, for
/// a workspace project, that a sync took from the library while the edit waited (owner review 2, R8): the dialog lists
/// them; Keep mine overwrites the other side's, Take server or the library's (the safe default, also on Esc) shows theirs
/// as one undoable step. Saving waits until then.
/// </summary>
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
{
if (_disposed || Session.Conflict is null) return;
var keepMine = Shell.Services.Dialogs.Confirm(ConflictRequest(conflict, Title, ServerName ?? string.Empty));
var request = Session.Source is WorkspaceSequenceSource ? LibraryConflictRequest(conflict, Title) : ConflictRequest(conflict, Title, ServerName ?? string.Empty);
var keepMine = Shell.Services.Dialogs.Confirm(request);
if (!_disposed) Session.ResolveConflict(keepMine);
});
/// <summary>The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.</summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new()
{
Heading = Loc.L("Editor.Workspace.Conflict.Title"),
Message = Loc.L("Editor.Workspace.Edited.Message", title),
Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10)),
DetailToolTip = Loc.L("Tooltips.Editor.Workspace.Differences"),
SafeText = Loc.L("Editor.Workspace.Conflict.TakeHome"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.TakeHomeUndo"),
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.KeepMine"),
IsDestructive = true,
};
/// <summary>The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces.</summary>
internal static ConfirmRequest ConflictRequest(ProjectConflictException conflict, string title, string server) => new()
{
@@ -1134,13 +1182,16 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited();
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so.
if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
});
}
/// <summary>
/// The frames of the server sequence changed while it is open (any thread): everything that changes the project is
/// disabled and says why, and a toast offers to fetch the proxies again.
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
/// server sequence, offering to fetch the proxies again).
/// </summary>
private void OnReadOnlyChanged() => _dispatcher.BeginInvoke(() =>
{
@@ -1152,6 +1203,12 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
OnPropertyChanged(nameof(RenderChoiceToolTip));
OnRenderStateChanged();
OnBusyChanged();
// A workspace project a sync turned read-only (a newer Chronos saved it): said once, the controls say why too.
if (IsReadOnly && Session.Source is WorkspaceSequenceSource)
{
Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.ReadOnly"), Message = Loc.L("Errors.Workspace.ReadOnly") });
return;
}
if (!IsOutdated) return;
var (id, title) = (Session.Content.Sequence.Id, Title);
Shell.ShowToast(new Toast
+21
View File
@@ -4,6 +4,7 @@ using Chronos.Core.Imaging;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Projects;
namespace Chronos.App.Editor;
@@ -34,6 +35,12 @@ public interface ISequenceSource : IAsyncDisposable
/// </summary>
bool IsOutdated { get; }
/// <summary>
/// A change stored meanwhile by someone else to settings the editor changed too is asked about
/// (<see cref="ProjectConflictException"/>), never merged over the editor's: a server sequence, a workspace project.
/// </summary>
bool AsksConflicts => IsRemote;
/// <summary><see cref="IsReadOnly"/> changed (any thread).</summary>
event Action? ReadOnlyChanged;
@@ -67,6 +74,20 @@ public interface ISequenceSource : IAsyncDisposable
/// <exception cref="EditorException">The editor's own reason the project was not stored, worded for the user.</exception>
Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
/// <summary>
/// The three-way merge of the editor's projects, all three naming this source's frames (<see cref="ProjectMerge"/>): member
/// by member, a member both sides changed listed as a conflict and settled for <paramref name="ours"/>. A workspace
/// project merges its frame positions photo by photo, as its sync does.
/// </summary>
ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs);
/// <summary>
/// Keeps <paramref name="unsaved"/>, an edit that can no longer be stored (the stored project became a newer Chronos's,
/// which this one never merges with), where the user finds it and nothing sends it; returns where, or null when this
/// source keeps nothing aside (the edit then stays in the editor as it is).
/// </summary>
Task<string?> SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
@@ -1,3 +1,4 @@
using Chronos.Data.Projects;
using System.IO;
using System.Text.Json;
using Chronos.Core.Advice;
+23 -5
View File
@@ -1,5 +1,6 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
@@ -36,7 +37,10 @@ public sealed class ProjectFiles(ShellViewModel shell)
/// <summary>
/// Opens the project file at <paramref name="path"/>: its sequence in the editor (found by id, else by archive and
/// folder), then the file's settings as one undo step. Says in one sentence why when the file cannot be read, its
/// sequence is not in the library, or the sequence cannot take the settings now.
/// sequence is not in the library, or the sequence cannot take the settings now. With the workspace (owner review 2,
/// R8), a file of format 2 opens its project there (a workspace's own <c>project.chronos</c> as it is; a copy of one
/// gives that project its settings), and a file of format 1 gives its settings to the sequence's Main project, which
/// opens in the workspace (copied first when it is not there yet).
/// </summary>
public async Task OpenAsync(string path)
{
@@ -53,16 +57,30 @@ public sealed class ProjectFiles(ShellViewModel shell)
return;
}
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
if (await ProjectBundles.ResolveAsync(db, bundle) is not { } sequence)
var home = bundle.Workspace is { Home: { IsArchive: true } h } ? await db.Sequences.GetAsync(h.SequenceId) : null;
if ((home ?? await ProjectBundles.ResolveAsync(db, bundle)) is not { } sequence)
{
Log.Info("project", $"Project file '{path}': sequence {bundle.Sequence.Id} ('{bundle.Sequence.Folder}' in archive {bundle.Archive.Id}) not in the index");
shell.Notify(Loc.L("Editor.ProjectFile.NotFound"), bundle.Sequence.Title ?? Path.GetFileName(path), Loc.L("Shell.Nav.Archive"),
Loc.L("Tooltips.Nav.Archive"), () => shell.Navigate(SectionKey.Archive), isError: true);
return;
}
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
if (await shell.Sequence.ShowAsync(sequence.Id) is not { } editor) return;
Apply(editor, bundle);
if (!shell.Services.Workspace.IsEnabled)
{
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
if (await shell.Sequence.ShowAsync(sequence.Id) is { } editor) Apply(editor, bundle);
return;
}
if (bundle.Workspace is { } workspace)
{
// A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings.
var own = shell.Services.Workspace.Store.Find(workspace.ProjectId) is { } project
&& string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
return;
}
// Format 1: the settings go to the sequence's Main project, once it is open (now, or after its copy into the workspace).
await shell.Sequence.ShowAsync(sequence.Id, ProjectRequest.MainOf(sequence.Id), editor => Apply(editor, bundle));
}
/// <summary>Gives the open sequence the file's settings, unless the editor cannot change them now (a job runs, read-only).</summary>
+22 -5
View File
@@ -1,4 +1,5 @@
using Chronos.Core.Project;
using Chronos.Data.Projects;
namespace Chronos.App.Editor;
@@ -8,7 +9,11 @@ namespace Chronos.App.Editor;
/// <see cref="EndRun"/> (the drag or key press ended); any other edit, undo or redo also ends the run. The oldest steps
/// are dropped beyond <see cref="Capacity"/>.
/// </summary>
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
/// <param name="merge">
/// The three-way merge (basis, ours, theirs) that gives each step an outside change (<see cref="Replace"/>): the source's,
/// which merges a workspace project's frame positions photo by photo; <see cref="ProjectMerge.Merge"/> when null.
/// </param>
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200, Func<ProjectSettings, ProjectSettings, ProjectSettings, ProjectSettings>? merge = null)
{
private readonly LinkedList<ProjectSettings> _undo = new();
private readonly LinkedList<ProjectSettings> _redo = new();
@@ -64,13 +69,25 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
/// <summary>
/// Adopts a project changed outside the editor (analysis advice, another client's edit merged on save) without an
/// undo step. Every undo and redo snapshot takes the same outside change, so undo reverts only the user's own steps
/// and never brings back a value that predates the adopted change.
/// and never brings back a value that predates the adopted change. Settings of a newer Chronos on either side (a pull
/// took them: the project is shown read-only) are never merged with this one's (<see cref="ProjectMerge"/>), so no step
/// can take that change: the undo and redo steps go instead, and undo never brings back values from before it.
/// </summary>
public void Replace(ProjectSettings current)
{
ArgumentNullException.ThrowIfNull(current);
if (ProjectMerge.SameValues(current, Current)) return;
var rebase = new ProjectMerge.Rebase(Current, current);
if (current.IsNewerFormat || Current.IsNewerFormat || _undo.Any(s => s.IsNewerFormat) || _redo.Any(s => s.IsNewerFormat))
{
_undo.Clear();
_redo.Clear();
_runKey = null;
Current = current;
Changed?.Invoke();
return;
}
var (basis, theirs) = (Current, current);
Func<ProjectSettings, ProjectSettings> rebase = merge is null ? new ProjectMerge.Rebase(basis, theirs).Apply : step => merge(basis, step, theirs);
Rebase(_undo, rebase);
Rebase(_redo, rebase);
_runKey = null;
@@ -97,9 +114,9 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
Changed?.Invoke();
}
private static void Rebase(LinkedList<ProjectSettings> steps, ProjectMerge.Rebase rebase)
private static void Rebase(LinkedList<ProjectSettings> steps, Func<ProjectSettings, ProjectSettings> rebase)
{
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value);
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase(node.Value);
}
private bool Move(ProjectSettings target)
-82
View File
@@ -1,82 +0,0 @@
using System.Text.Json.Nodes;
using Chronos.Core.Project;
using Chronos.Data.Sync;
namespace Chronos.App.Editor;
/// <summary>
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server), both made from <c>basis</c>.
/// Values are compared member by member down the JSON tree; a member only one side changed takes that side's value, a
/// member both changed takes the editor's (the user is looking at it). <see cref="Conflicts"/> lists those members for
/// a source that asks the user instead (a server sequence, BRIEF §14.5).
/// </summary>
public static class ProjectMerge
{
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
{
ArgumentNullException.ThrowIfNull(basis);
ArgumentNullException.ThrowIfNull(ours);
ArgumentNullException.ThrowIfNull(theirs);
return new Rebase(basis, theirs).Apply(ours);
}
/// <summary>
/// The members both sides changed to different values, in document order: the path below the project
/// ("exposure.deflickerWindow.manual"), the editor's value and theirs as JSON (null when absent).
/// </summary>
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
{
ArgumentNullException.ThrowIfNull(basis);
ArgumentNullException.ThrowIfNull(ours);
ArgumentNullException.ThrowIfNull(theirs);
var conflicts = new List<SettingsDifference>();
Collect(JsonNode.Parse(basis.ToJson()), JsonNode.Parse(ours.ToJson()), JsonNode.Parse(theirs.ToJson()), string.Empty, conflicts);
return conflicts;
}
/// <summary>True when both projects store the same values.</summary>
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
private static JsonNode? Merge(JsonNode? basis, JsonNode? ours, JsonNode? theirs)
{
if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone();
if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone();
if (ours is not JsonObject mine || theirs is not JsonObject other) return ours?.DeepClone();
var common = basis as JsonObject;
var merged = new JsonObject();
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
{
var value = Merge(common?[name], mine[name], other[name]);
if (value is not null || mine.ContainsKey(name)) merged[name] = value;
}
return merged;
}
/// <summary>The members <see cref="Merge(JsonNode?, JsonNode?, JsonNode?)"/> settles for the editor although both sides changed them.</summary>
private static void Collect(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts)
{
if (JsonNode.DeepEquals(ours, basis) || JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return;
if (ours is JsonObject mine && theirs is JsonObject other)
{
var common = basis as JsonObject;
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
Collect(common?[name], mine[name], other[name], path.Length == 0 ? name : path + "." + name, conflicts);
return;
}
conflicts.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, ours?.ToJsonString(), theirs?.ToJsonString()));
}
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
{
private readonly JsonNode? _basis = JsonNode.Parse(basis.ToJson());
private readonly JsonNode? _theirs = JsonNode.Parse(theirs.ToJson());
public ProjectSettings Apply(ProjectSettings ours)
{
ArgumentNullException.ThrowIfNull(ours);
return ProjectSettings.FromJson(Merge(_basis, JsonNode.Parse(ours.ToJson()), _theirs)?.ToJsonString() ?? "{}");
}
}
}
+29 -1
View File
@@ -21,6 +21,9 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
private bool _flushRequested;
private bool _stopped;
private int _failures;
/// <summary>Changes dropped (<see cref="Drop"/>): a write that fails after one is not retried.</summary>
private int _drops;
private CancellationTokenSource? _wait;
/// <summary>No write starts until <see cref="Release"/> (or <see cref="Stop"/>): the user is being asked about the pending change.</summary>
@@ -103,6 +106,22 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
lock (_gate) ReleaseHold();
}
/// <summary>
/// Drops what is pending, a write under way included should it fail, and keeps saving what is scheduled from now on: the
/// change was kept elsewhere (set aside when the stored project became a newer Chronos's, where it can never be stored).
/// </summary>
public void Drop()
{
lock (_gate)
{
_pending = null;
_drops++;
_failures = 0;
LastError = null;
_wait?.Cancel();
}
}
/// <summary>Drops what is pending and stops retrying (the editor closed and the user chose to discard the change).</summary>
public void Stop()
{
@@ -153,8 +172,10 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
continue;
}
ProjectSettings next;
int drops;
lock (_gate)
{
drops = _drops;
_flushRequested = false;
if (_pending is null)
{
@@ -184,9 +205,16 @@ public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan dela
}
catch (Exception ex)
{
LastError = ex;
lock (_gate)
{
if (_drops != drops)
{
// Dropped while it was written (kept elsewhere): not retried, and no failure to report.
EndWrite();
wait = TimeSpan.Zero;
continue;
}
LastError = ex;
// A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry.
if (!_stopped) _pending ??= next;
failures = ++_failures;
@@ -1,3 +1,4 @@
using Chronos.Data.Projects;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
@@ -0,0 +1,435 @@
using System.IO;
using System.Text.Json;
using Chronos.Core.Advice;
using Chronos.Core.Analysis;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
namespace Chronos.App.Editor;
/// <summary>A source whose renders are made otherwise than from the project as the editor holds it (a workspace project: at its home).</summary>
public interface IProjectRenders
{
/// <summary>The jobs that render <paramref name="export"/> of <paramref name="project"/> (the editor's settings, positions on the source's frames).</summary>
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
}
/// <summary>
/// A workspace project open in the editor (owner review 2, R8: editing happens in the workspace, never inside the
/// library): the frames and pixels of the media the workspace holds (<c>media/media.json</c>, the proxies), the project
/// from its working state (<c>project.chronos</c>, positions placed on those frames), saved there atomically under the
/// project's lease and merged against the basis like <see cref="LocalSequenceSource"/> (a pull or a copy job writes it
/// too): frame positions photo by photo as the sync merges them (<see cref="Merge"/>), and settings the editor changed to
/// other values than those stored meanwhile asked about (<see cref="ProjectConflictException"/>), never decided for the
/// editor. A pull that brings a newer Chronos's settings turns it read-only (<see cref="ReadOnlyChanged"/>). Jobs run on
/// this PC's engine against the home's sequence (same id): an analysis reads the home's originals, a
/// render renders the home's originals with the project's portable settings and records the project and the version
/// (<see cref="RenderRequests"/>). The deep report is the home's while its frames are the media's, else the copy the
/// workspace took. A copy job that changed the media (Update media) makes saves made against the frames read before refused
/// (<see cref="FramesChangedException"/>) until the editor has read them again and moved its positions by frame.
/// </summary>
public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
{
private const int JobsListed = 200;
private readonly WorkspaceSync _sync;
private readonly ChronosDatabase _db;
private readonly ImageDecoder _decoder;
private readonly JobEngine? _engine;
private readonly Lock _gate = new();
private readonly List<IRenderFrameSource> _retired = [];
private IRenderFrameSource? _frames;
private IFrameSource? _pixels;
private int _frameCount;
private int _framesVersion = -1;
private Guid[] _frameIds = [];
private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace;
private bool _readOnly;
private int _disposed;
public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine)
{
ArgumentNullException.ThrowIfNull(sync);
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(decoder);
_sync = sync;
_db = db;
_decoder = decoder;
_engine = engine;
ProjectId = projectId;
if (engine is not null) engine.JobChanged += OnJobChanged;
}
public Guid ProjectId { get; }
/// <summary>The project's folder in the workspace.</summary>
public WorkspaceProject Project => _sync.Store.Project(ProjectId);
/// <summary>The workspace section of the project file as read last (name, Main, home, base, media); null before the first read.</summary>
public BundleWorkspace? Workspace => Volatile.Read(ref _workspace);
/// <summary>The frames version of the home the media read last were copied at; -1 before the first read.</summary>
public int MediaFramesVersion => Volatile.Read(ref _framesVersion);
/// <summary>The photos of the media read last, in frame order (what positions name).</summary>
public FramePhotos Photos => Volatile.Read(ref _photos);
public bool IsRemote => false;
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly);
public bool IsOutdated => false;
/// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
public bool AsksConflicts => true;
/// <summary>The working state read again holds a newer Chronos's settings (a pull took them), or no longer does.</summary>
public event Action? ReadOnlyChanged;
public event Action<Job>? JobChanged;
/// <exception cref="EditorException">
/// The workspace holds no media for the project (copy them again), the project is gone, or a sync or a copy kept it for
/// longer than the sync waits (<see cref="WorkspaceSync.LockWait"/>).
/// </exception>
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
{
WorkspaceSession session;
try
{
session = await _sync.OpenAsync(ProjectId, cancellationToken);
}
catch (InvalidOperationException ex)
{
throw new EditorException(Loc.L("Errors.Workspace.NotCheckedOut"), ex);
}
catch (InvalidDataException ex)
{
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
}
catch (LeaseUnavailableException ex)
{
// A long sync or copy holds the project: nothing was read, opening it again later reads it whole.
Log.Info("editor", $"Workspace project {ProjectId} is busy: {ex.Message}");
throw new EditorException(Loc.L("Errors.Workspace.Busy"), ex);
}
if (session is not { Sequence: { } media, Media: { } index }) throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
var home = session.Bundle.Workspace!.Home;
var row = await _db.Sequences.GetAsync(home.SequenceId, cancellationToken);
var archive = row is null ? null : await _db.Archives.GetAsync(row.ArchiveId, cancellationToken);
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
return await Task.Run(() =>
{
var frames = media.Frames;
Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly);
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
// The home's row (camera, interval, tags) with the frames this workspace holds.
var sequence = (row ?? media.Sequence) with
{
FrameCount = frames.Count,
FramesVersion = index.FramesVersion,
FirstCapture = times.Count > 0 ? times[0] : null,
LastCapture = times.Count > 0 ? times[^1] : null,
SettingsJson = session.Working.ToJson(),
};
var folder = archive is null ? null : new ArchivePaths(archive.RootPath).Sequence(row!.Folder);
var (deep, otherFrames) = ReadReport(folder, row?.FramesVersion == index.FramesVersion, session.Project.AnalysisPath, frames.Count);
var context = SequenceContext.FromFrames(frames);
return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight,
folder?.Exports, [.. renders.OrderByDescending(r => r.Created)], [])
{
DeepOfOtherFrames = otherFrames,
};
}, cancellationToken);
}
/// <remarks>Only a copy job changes the workspace's frames (Update media): its media index is compared with the one read last.</remarks>
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken) => Task.Run(() =>
{
var (framesVersion, ids) = (Volatile.Read(ref _framesVersion), Volatile.Read(ref _frameIds));
try
{
return Project.ReadMedia() is { } media && media.FramesVersion == framesVersion && media.Frames.Select(f => f.Id).SequenceEqual(ids);
}
catch (InvalidDataException ex)
{
Log.Warning("editor", $"The media index of workspace project {ProjectId} cannot be read", ex);
return false;
}
}, cancellationToken);
/// <summary>Whether the home's frames moved past those the workspace holds (frames added or removed there): "Update media" copies them again.</summary>
public async Task<bool> HomeFramesChangedAsync(CancellationToken cancellationToken)
{
if (Workspace is not { } workspace || MediaFramesVersion < 0) return false;
return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion;
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
IFrameSource? pixels;
int count;
lock (_gate) (pixels, count) = (_pixels, _frameCount);
if (pixels is null || (uint)index >= (uint)count) return null;
// The loader decodes synchronously: an async delegate keeps a superseded decode's cancellation in user code (R4).
return await Task.Run(async () => await pixels.LoadAsync(index, maxLongEdge, cancellationToken).ConfigureAwait(false), cancellationToken);
}
/// <exception cref="EditorException">The project is read-only, or its media are gone.</exception>
/// <exception cref="FramesChangedException">The media changed since they were read (a copy job): read them again first.</exception>
/// <exception cref="ProjectConflictException">
/// The working state stored meanwhile (a sync took the library's versions) holds other values of settings this edit
/// changed too: nothing is stored until the user keeps theirs or takes the library's.
/// </exception>
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(basis);
var framesVersion = Volatile.Read(ref _framesVersion);
if (framesVersion < 0) throw new InvalidOperationException("LoadAsync first.");
var folder = Project;
return Task.Run(async () =>
{
using (await folder.LockAsync(_sync.LockWait, cancellationToken))
{
var bundle = folder.ReadBundle();
if (bundle.IsReadOnly || project.IsNewerFormat) throw new EditorException(Loc.L("Errors.Workspace.ReadOnly"));
var media = folder.ReadMedia() ?? throw new EditorException(Loc.L("Errors.Workspace.MediaMissing"));
// A copy job moved the working state onto other frames: the editor reads them and moves its positions first.
if (media.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Errors.Workspace.MediaChanged"));
var stored = ProjectSettings.FromJson(ProjectContent.Place(bundle.Project.ToJson(), media.Photos), allowNewer: true);
var merged = project;
if (!ProjectMerge.SameValues(stored, basis))
{
var merge = Merge(basis, project, stored, media.Photos);
if (merge.HasConflicts) throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, merge.Conflicts);
merged = merge.Merged;
}
if (ProjectMerge.SameValues(merged, stored)) return merged;
folder.WriteBundle(bundle with { Project = merged, Saved = DateTimeOffset.UtcNow });
return merged;
}
}, cancellationToken);
}
/// <summary>
/// The editor's merges as the sync merges (owner review 2, R8): member by member, and frame positions photo by photo and
/// flag by flag in the portable form, so an exclusion or a keyframe a sync wrote meanwhile stays beside the editor's own
/// (positional arrays would take one side whole). All three name the frames of the media read last.
/// </summary>
public ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => Merge(basis, ours, theirs, Photos);
private static ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, FramePhotos photos)
{
ArgumentNullException.ThrowIfNull(basis);
ArgumentNullException.ThrowIfNull(ours);
ArgumentNullException.ThrowIfNull(theirs);
var merge = ProjectMerge.MergeWithConflicts(basis, ours, theirs);
// Positions only one side moved, or none, merge alike either way; the portable form is needed where both did.
if (photos.Count == 0 || !merge.Conflicts.Any(c => NamesPosition(c.Path)) || basis.IsNewerFormat || ours.IsNewerFormat || theirs.IsNewerFormat) return merge;
var portable = ProjectMerge.MergeWithConflicts(Portable(basis, photos), Portable(ours, photos), Portable(theirs, photos));
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(portable.Merged.ToJson()), photos), allowNewer: true);
return portable with { Merged = placed };
static ProjectSettings Portable(ProjectSettings settings, FramePhotos photos) =>
ProjectSettings.FromJson(ProjectContent.ToPortable(settings, photos), allowNewer: true);
}
/// <summary>
/// Keeps an edit the working state can no longer take (a sync brought a newer Chronos's settings) as a version file in
/// <c>versions/.replaced</c>, where a take of the library's values keeps the working state it replaces: outside the chain
/// of versions, so it is never sent, and never lost. Written under the project's lease, its positions parked by photo.
/// </summary>
/// <exception cref="Core.Archiving.LeaseUnavailableException">Another writer kept the project for longer than the sync waits.</exception>
public Task<string?> SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(unsaved);
var folder = Project;
var (photos, framesVersion, basis) = (Photos, MediaFramesVersion, Workspace?.Base);
return Task.Run<string?>(async () =>
{
using (await folder.LockAsync(_sync.LockWait, cancellationToken))
{
var portable = ProjectContent.ToPortable(unsaved, photos);
var version = new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = ProjectId,
ParentId = basis?.VersionId,
Number = (basis?.Number ?? 0) + 1,
Kind = ProjectVersionKind.Commit,
ClientName = Environment.MachineName,
SettingsJson = portable,
ContentHash = ProjectContent.Hash(portable),
SettingsFormat = ProjectContent.FormatOf(portable),
FramesVersion = Math.Max(0, framesVersion),
CreatedAt = DateTimeOffset.UtcNow,
};
var path = Path.Combine(folder.VersionsDirectory, WorkspaceProject.ReplacedFolder, Path.GetFileName(folder.VersionPath(version)));
ProjectSidecars.WriteVersion(path, version);
return path;
}
}, cancellationToken);
}
/// <summary>A merge path of a frame position (an exclusion, the hero, a camera keyframe, a frame waiting for its photo).</summary>
private static bool NamesPosition(string path) =>
path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal);
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
return job.Id;
}
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) =>
(await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) =>
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) =>
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
/// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job of this PC's
/// engine per preset, with the project's portable settings (positions parked by photo, placed on the home's frames by
/// the render) and the project recorded on the render; the version too when the settings are those of the last
/// version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, without a version).
/// </summary>
public IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
var (tipId, tipHash) = Tip();
var version = new ProjectVersion
{
Id = tipId ?? Guid.Empty,
ProjectId = ProjectId,
Number = 0,
SettingsJson = portable,
ContentHash = hash,
};
var requests = ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight);
if (tipId is not null && string.Equals(tipHash, hash, StringComparison.OrdinalIgnoreCase)) return requests;
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
List<IRenderFrameSource> sources;
lock (_gate)
{
sources = [.. _retired];
if (_frames is not null) sources.Add(_frames);
_retired.Clear();
(_frames, _pixels) = (null, null);
}
foreach (var source in sources)
{
if (source is IAsyncDisposable disposable) await disposable.DisposeAsync();
}
}
/// <summary>
/// Takes the media read now: a frame source over them when they differ from those read before (the old one is disposed
/// with this source, as a decode may still read it), their frames and photos, the project's workspace section, and
/// whether the settings are a newer Chronos's (said by <see cref="ReadOnlyChanged"/> when that changed).
/// </summary>
private void Swap(WorkspaceSequence media, WorkspaceMedia index, BundleWorkspace workspace, bool readOnly)
{
var ids = media.Frames.Select(f => f.Id).ToArray();
bool changed;
lock (_gate)
{
if (_frames is null || index.FramesVersion != _framesVersion || !ids.AsSpan().SequenceEqual(_frameIds))
{
if (_frames is not null) _retired.Add(_frames);
_frames = media.OpenFrames(_decoder);
_pixels = (IFrameSource)_frames;
_frameCount = media.Frames.Count;
}
_frameIds = ids;
_framesVersion = index.FramesVersion;
_photos = index.Photos;
_workspace = workspace;
changed = _readOnly != readOnly;
_readOnly = readOnly;
}
if (changed) ReadOnlyChanged?.Invoke();
}
/// <summary>
/// The version a render may name, with its content hash: the base, which the home holds, while no version waits to be
/// sent; none otherwise. A version not sent yet may never reach the home under its id (a replay or a save-both sends it
/// under another), so a render of it names the project alone.
/// </summary>
private (Guid? Id, string? Hash) Tip()
{
try
{
if (_sync.Unpushed(ProjectId).Count > 0) return (null, null);
return Project.ReadBundle().Workspace?.Base is { } basis ? (basis.VersionId, basis.ContentHash) : (null, null);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException)
{
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
return (null, null);
}
}
private static string? WithoutVersion(string? parametersJson)
{
if (parametersJson is null || JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is not { } parameters) return parametersJson;
return JsonSerializer.Serialize(parameters with { ProjectVersionId = null }, ProtocolJson.Default.RenderJobParameters);
}
/// <summary>
/// The deep report the editor shows: the home's while its frames are the workspace's, else the copy the workspace took;
/// whether one of another number of frames was read instead.
/// </summary>
private static (DeepAnalysisReport? Report, bool OtherFrames) ReadReport(SequencePaths? home, bool sameFrames, string copied, int frameCount)
{
var otherFrames = false;
foreach (var path in new[] { sameFrames ? home?.AnalysisPath : null, copied })
{
if (path is null || !File.Exists(path)) continue;
try
{
var report = DeepAnalysisReport.Load(path);
if (report.FrameCount == frameCount) return (report, false);
otherFrames = true;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException or UnauthorizedAccessException)
{
Log.Warning("editor", $"{path} cannot be read", ex);
}
}
return (null, otherFrames);
}
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
}