Merge branch 'p5c-p1p2' into review2-p5c

This commit is contained in:
Alby96 committed 2026-11-04 16:04:00 +01:00
commit 5fc7f02abf
25 files changed
+2176 -102

No files matched your search

+3
View File
@@ -327,6 +327,9 @@
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" /> ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}" <Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" /> ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Editor.Render.NotSent}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}"
VerticalAlignment="Center" Margin="6,0,0,0" ToolTip="{Binding UnsentToolTip}"
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" <TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
ToolTip="{Binding HistoryText}" /> ToolTip="{Binding HistoryText}" />
</DockPanel> </DockPanel>
+13 -5
View File
@@ -634,7 +634,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var export = batch ? RenderExport : RenderExport with { Batch = [] }; var export = batch ? RenderExport : RenderExport with { Batch = [] };
var requests = Session.RenderRequests(export); var requests = Session.RenderRequests(export);
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority }); foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label); if (Session.Source is IProjectRenders { RendersLocally: true })
Shell.Notify(Loc.L("Editor.Render.QueuedLocal"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
else if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
} }
@@ -957,7 +959,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void RefreshSteps() private void RefreshSteps()
{ {
if (_disposed) return; if (_disposed) return;
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render), var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render) ?? _jobs.Active(JobKind.WorkspaceRender),
_planned ? RenderBlockedReason : null, _rendered.Matches(Session.Project)); _planned ? RenderBlockedReason : null, _rendered.Matches(Session.Project));
foreach (var tab in Tabs) tab.SetStep(EditPath.Of(tab.Key, facts)); foreach (var tab in Tabs) tab.SetStep(EditPath.Of(tab.Key, facts));
Analysis.OnStepChanged(); Analysis.OnStepChanged();
@@ -1174,7 +1176,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (_disposed) if (_disposed)
{ {
// Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read. // Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read.
if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id)) if (job is { State: JobState.Done } && IsRender(job.Kind) && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
AnnounceRender(job, read: false); AnnounceRender(job, read: false);
return; return;
} }
@@ -1186,13 +1188,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!wasActive) return; if (!wasActive) return;
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited(); 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. // 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); if (job.State == JobState.Done) _ = ReloadAsync(IsRender(job.Kind) && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
// A local render's send home (phase 5c): said once, here or on the Jobs screen.
if (job is { Kind: JobKind.WorkspaceSend, State: JobState.Done } && Shell.Jobs.ClaimRenderToast(job.Id)) Shell.Notify(Loc.L("Editor.Render.SentHome"), Title);
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so. // 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); if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job); else if (IsRemote && job.Kind is not (JobKind.WorkspaceRender or JobKind.WorkspaceSend) && job.State is JobState.Failed or JobState.Cancelled)
ReportServerJobEnded(job);
}); });
} }
/// <summary>A render of the sequence: at its home, or on this PC from a workspace project's originals (phase 5c).</summary>
private static bool IsRender(JobKind kind) => kind is JobKind.Render or JobKind.WorkspaceRender;
/// <summary> /// <summary>
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's /// 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 /// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
+8
View File
@@ -403,6 +403,14 @@ public sealed class ExportTab : EditorTab
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created)) ? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory"); : Loc.L("Editor.Export.NoHistory");
/// <summary>A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".</summary>
public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
/// <summary>Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace.</summary>
public string? UnsentToolTip => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 } source
? Loc.L(source.IsServerHome ? "Tooltips.Editor.Render.NotSent.Server" : "Tooltips.Editor.Render.NotSent")
: null;
public IReadOnlyList<string> Batch => Export.Batch; public IReadOnlyList<string> Batch => Export.Batch;
/// <summary>Completes when the card estimates in flight are done.</summary> /// <summary>Completes when the card estimates in flight are done.</summary>
+8 -4
View File
@@ -11,8 +11,8 @@ public sealed class SequenceJobs(Guid sequenceId)
{ {
private readonly Dictionary<Guid, Job> _active = []; private readonly Dictionary<Guid, Job> _active = [];
/// <summary>An analysis or render runs: settings wait.</summary> /// <summary>An analysis or render runs: settings wait (a local render's send home does not hold them).</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running); public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running && j.Kind != JobKind.WorkspaceSend);
/// <summary>A deep analysis waits, runs or is paused.</summary> /// <summary>A deep analysis waits, runs or is paused.</summary>
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse); public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
@@ -23,13 +23,17 @@ public sealed class SequenceJobs(Guid sequenceId)
/// <summary>The job of <paramref name="kind"/> to show, chosen as <see cref="Shown"/> is (the Edit path's steps).</summary> /// <summary>The job of <paramref name="kind"/> to show, chosen as <see cref="Shown"/> is (the Edit path's steps).</summary>
public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind)); public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind));
/// <summary>An analysis or render of this sequence.</summary> /// <summary>An analysis or render of this sequence, a workspace project's render on this PC or its send home (phase 5c).</summary>
public bool Concerns(Job job) public bool Concerns(Job job)
{ {
ArgumentNullException.ThrowIfNull(job); ArgumentNullException.ThrowIfNull(job);
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render; return job.TargetIds.Contains(sequenceId) && IsSequenceKind(job.Kind);
} }
/// <summary>The kinds the editor follows.</summary>
public static bool IsSequenceKind(JobKind kind) =>
kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>The job is one of those that wait, run or are paused.</summary> /// <summary>The job is one of those that wait, run or are paused.</summary>
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId); public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
+1 -1
View File
@@ -208,7 +208,7 @@ internal sealed class ServerJobs : IAsyncDisposable
_changed(job); _changed(job);
} }
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render; private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && SequenceJobs.IsSequenceKind(job.Kind);
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary> /// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
internal static async Task<T> Call<T>(Func<Task<T>> call) internal static async Task<T> Call<T>(Func<Task<T>> call)
+114 -11
View File
@@ -29,6 +29,9 @@ 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> /// <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); IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
/// <summary>The renders run on this PC (a workspace project holding its originals, phase 5c), whatever the home.</summary>
bool RendersLocally { get; }
} }
/// <summary> /// <summary>
@@ -95,6 +98,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private FramePhotos _photos = new([]); private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace; private BundleWorkspace? _workspace;
private bool _readOnly; private bool _readOnly;
private bool _holdsOriginals;
private int _unsent;
private int _disposed; private int _disposed;
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param> /// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
@@ -136,6 +141,15 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <summary>Settings of a newer Chronos: shown, never saved.</summary> /// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly); public bool IsReadOnly => Volatile.Read(ref _readOnly);
/// <summary>
/// The media read last hold the originals (phase 5c): the project renders on this PC's engine from them, into its
/// <c>exports/</c>, and the renders are sent home after (<see cref="JobKind.WorkspaceRender"/>), also for a server home.
/// </summary>
public bool RendersLocally => Volatile.Read(ref _holdsOriginals);
/// <summary>The local renders of the project's ledger not at the home yet, as read last.</summary>
public int UnsentRenders => Volatile.Read(ref _unsent);
public bool IsOutdated => false; 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> /// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
@@ -179,6 +193,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken); IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
return await Task.Run(() => return await Task.Run(() =>
{ {
renders = [.. renders, .. UnsentOf(session.Project, home.SequenceId)];
var frames = media.Frames; var frames = media.Frames;
Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly); 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(); var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
@@ -278,6 +293,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
Created = r.Created, Created = r.Created,
ProducedBy = r.ProducedBy, ProducedBy = r.ProducedBy,
}).ToList() ?? []; }).ToList() ?? [];
renders = [.. renders.Concat(UnsentOf(session.Project, home.SequenceId)).OrderByDescending(r => r.Created)];
var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count); var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count);
var context = SequenceContext.FromFrames(frames); var context = SequenceContext.FromFrames(frames);
return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, []) return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
@@ -495,7 +511,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <remarks>A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so.</remarks> /// <remarks>A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so.</remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{ {
if (_server is not null) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken); ArgumentNullException.ThrowIfNull(request);
// A render from the workspace's originals and its send run on this PC's engine, whatever the home (phase 5c).
if (_server is not null && !RunsHere(request.Kind)) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken);
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken); var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
return job.Id; return job.Id;
@@ -504,26 +522,40 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <remarks>A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).</remarks> /// <remarks>A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).</remarks>
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{ {
if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items; var local = (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return []; if (_server is null) return local;
// This PC's renders from the originals and their sends beside the server's jobs (phase 5c).
IReadOnlyList<Job> here = [.. local.Where(j => RunsHere(j.Kind))];
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return here;
try try
{ {
return await jobs.ListAsync(cancellationToken); return [.. (await jobs.ListAsync(cancellationToken)).Concat(here)];
} }
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException) catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException)
{ {
Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}"); Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}");
return []; return here;
} }
} }
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
? ServerJobsOrThrow().CancelAsync(jobId, cancellationToken) {
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken); if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().CancelAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
}
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
? ServerJobsOrThrow().RetryAsync(jobId, cancellationToken) {
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken); if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().RetryAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
}
/// <summary>The kinds a workspace project runs on this PC's engine whatever its home: a render from its originals and its send home.</summary>
private static bool RunsHere(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>A job of this PC's engine that runs here whatever the home (<see cref="RunsHere"/>).</summary>
private async Task<bool> IsLocalJobAsync(Guid jobId, CancellationToken cancellationToken) =>
await _db.Jobs.GetAsync(jobId, cancellationToken) is { } job && RunsHere(job.Kind);
/// <summary> /// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset /// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
@@ -542,6 +574,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export); ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos); var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable); var hash = ProjectContent.Hash(portable);
if (RendersLocally && Workspace is { } workspace) return LocalRenderRequests(sequence, workspace.Home, portable, hash, export, sourceWidth, sourceHeight);
if (_server is not null) if (_server is not null)
{ {
if (InStepWithHome(project) is { } basis) if (InStepWithHome(project) is { } basis)
@@ -566,6 +599,75 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })]; return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
} }
/// <summary>
/// The render on this PC from the originals the workspace holds (phase 5c): one <see cref="JobKind.WorkspaceRender"/> per
/// preset with the project's portable settings, naming the head version of <c>versions/</c> when the settings are the
/// ones it holds (the render records it; an unsaved working state renders without a version), sent home after.
/// </summary>
private IReadOnlyList<ArchiveJobRequest> LocalRenderRequests(Sequence sequence, BundleHome home, string portable, string hash, ExportSettings export,
int sourceWidth, int sourceHeight)
{
var head = HeadVersion(hash);
var version = new ProjectVersion { Id = head ?? Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
var root = _sync.Store.Root;
var server = home.IsArchive ? null : home.Server;
return
[
.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => WorkspaceJobs.Render(home.SequenceId,
r.Label ?? sequence.DisplayTitle, root, ProjectId, head, (head is null ? WithoutVersion(r.ParametersJson) : r.ParametersJson)!, server)),
];
}
/// <summary>The id of the newest version the workspace holds when it holds <paramref name="hash"/>; null otherwise.</summary>
private Guid? HeadVersion(string hash)
{
try
{
return Project.Versions() is [.., var last] && string.Equals(last.ContentHash, hash, StringComparison.OrdinalIgnoreCase) ? last.Id : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
return null;
}
}
/// <summary>The local renders of the project's ledger not at the home yet, as renders of <paramref name="sequenceId"/> (newest first).</summary>
private IReadOnlyList<Render> UnsentOf(WorkspaceProject project, Guid sequenceId)
{
try
{
var unsent = project.ReadRenders().Unsent;
Volatile.Write(ref _unsent, unsent.Count);
return
[
.. unsent.OrderByDescending(e => e.Rendered).Select(e => new Render
{
Id = e.RenderId,
SequenceId = sequenceId,
PresetName = e.PresetName,
OutputPath = project.ExportFile(e.File),
Codec = e.Codec,
Width = e.Width,
Height = e.Height,
Fps = e.Fps,
DurationSeconds = e.DurationSeconds,
Bytes = e.Size,
Created = e.Rendered,
ProducedBy = Environment.MachineName,
ProjectId = e.ProjectId,
ProjectVersionId = e.ProjectVersionId,
}),
];
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The render ledger of workspace project {ProjectId} cannot be read", ex);
Volatile.Write(ref _unsent, 0);
return [];
}
}
/// <summary> /// <summary>
/// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project /// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project
/// (<paramref name="project"/>) holds what the base holds; null otherwise. /// (<paramref name="project"/>) holds what the base holds; null otherwise.
@@ -643,6 +745,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_photos = index.Photos; _photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)]; _standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace; _workspace = workspace;
_holdsOriginals = index.HoldsOriginals;
changed = _readOnly != readOnly; changed = _readOnly != readOnly;
_readOnly = readOnly; _readOnly = readOnly;
} }
+1 -1
View File
@@ -303,7 +303,7 @@ public sealed class JobsViewModel : SectionViewModel
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id); else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job); var notice = JobNotices.For(before, job);
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output. // A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
if (notice == JobNotice.Done && job.Kind == JobKind.Render if (notice == JobNotice.Done && job.Kind is JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return; && (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job); _endings.Add(notice, job);
} }
@@ -127,6 +127,10 @@
<MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}" <MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}"
ToolTipService.ShowOnDisabled="True" /> ToolTipService.ShowOnDisabled="True" />
<Separator /> <Separator />
<MenuItem Header="{l:Loc Editor.Project.CopyOriginals}" Command="{Binding Project.CopyOriginalsCommand}" ToolTip="{Binding Project.CopyOriginalsToolTip}"
ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.ProxiesOnly}" Command="{Binding Project.ProxiesOnlyCommand}" ToolTip="{Binding Project.ProxiesOnlyToolTip}"
ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{Binding Project.RemoveCopyToolTip}" /> <MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{Binding Project.RemoveCopyToolTip}" />
</ContextMenu> </ContextMenu>
</Button.ContextMenu> </Button.ContextMenu>
+77 -27
View File
@@ -608,12 +608,20 @@ public sealed class SequenceViewModel : SectionViewModel
ImageDecoder decoder, Sequence row) ImageDecoder decoder, Sequence row)
{ {
var request = TakeRequest(row.Id); var request = TakeRequest(row.Id);
var entry = request switch WorkspaceEntry? entry;
if (request is { ProjectId: { } id }) entry = await workspace.FindAsync(id);
else if (request is { Main: true }) entry = (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain);
else
{ {
{ ProjectId: { } id } => await workspace.FindAsync(id), var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, row.Id, row.DisplayTitle, _ => true);
{ Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain), if (cancelled)
_ => await workspace.LastUsedAsync(row.Id), {
}; _afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return null;
}
entry = chosen;
}
// This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it. // This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it.
if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable); if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable);
// No project of the sequence here opens, and its Main here is such a copy (never among its projects): said at once, // No project of the sequence here opens, and its Main here is such a copy (never among its projects): said at once,
@@ -634,10 +642,12 @@ public sealed class SequenceViewModel : SectionViewModel
if (entry is { HasMedia: true }) if (entry is { HasMedia: true })
{ {
workspace.Remember(row.Id, entry.ProjectId); workspace.Remember(row.Id, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle); return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
} }
var projectId = entry?.ProjectId ?? request?.ProjectId; var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null; string? newName = null;
var media = DefaultMedia(services);
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(row.Id)).All(p => p.Id != wanted)) if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(row.Id)).All(p => p.Id != wanted))
{ {
// A project file of a project this home does not have (another PC's workspace): its sequence's Main takes it. // A project file of a project this home does not have (another PC's workspace): its sequence's Main takes it.
@@ -653,12 +663,12 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.KeepSequence(OpenSequenceId); Shell.KeepSequence(OpenSequenceId);
return null; return null;
} }
(projectId, newName) = (choice.ProjectId, choice.NewName); (projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
} }
WorkspaceCheckout checkout; WorkspaceCheckout checkout;
try try
{ {
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName); checkout = await workspace.CheckoutAsync(row.Id, projectId, newName, media);
} }
catch (WorkspaceException ex) when (ex.FolderRefused) catch (WorkspaceException ex) when (ex.FolderRefused)
{ {
@@ -710,12 +720,20 @@ public sealed class SequenceViewModel : SectionViewModel
private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId) private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId)
{ {
var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null; var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null;
var entry = request switch WorkspaceEntry? entry;
if (request is { ProjectId: { } id }) entry = await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null;
else if (request is { Main: true }) entry = (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true });
else
{ {
{ ProjectId: { } id } => await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null, var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, remoteId, null, p => p.IsServerHome);
{ Main: true } => (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true }), if (cancelled)
_ => await workspace.LastUsedAsync(remoteId) is { IsServerHome: true } last ? last : null, {
}; _afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
entry = chosen;
}
var sync = services.Sync; var sync = services.Sync;
if (entry is { IsReadable: false } unreadable) if (entry is { IsReadable: false } unreadable)
{ {
@@ -726,6 +744,7 @@ public sealed class SequenceViewModel : SectionViewModel
{ {
TakeRequest(remoteId); TakeRequest(remoteId);
workspace.Remember(remoteId, entry.ProjectId); workspace.Remember(remoteId, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server: // Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in. // made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server; var server = entry.Home.Server;
@@ -755,6 +774,7 @@ public sealed class SequenceViewModel : SectionViewModel
} }
var projectId = entry?.ProjectId ?? request?.ProjectId; var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null; string? newName = null;
var media = DefaultMedia(services);
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(home)).All(p => p.Id != wanted)) if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(home)).All(p => p.Id != wanted))
{ {
// A project the server does not have (deleted there, or another server's): the sequence's Main opens instead. // A project the server does not have (deleted there, or another server's): the sequence's Main opens instead.
@@ -770,12 +790,12 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.KeepSequence(OpenSequenceId); Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null); return new ServerOpen(null);
} }
(projectId, newName) = (choice.ProjectId, choice.NewName); (projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
} }
WorkspaceCheckout checkout; WorkspaceCheckout checkout;
try try
{ {
checkout = await workspace.CheckoutAsync(home, projectId, newName); checkout = await workspace.CheckoutAsync(home, projectId, newName, media);
} }
catch (WorkspaceException ex) when (ex.FolderRefused) catch (WorkspaceException ex) when (ex.FolderRefused)
{ {
@@ -811,25 +831,23 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary> /// <summary>
/// "Open in workspace" for a sequence of <paramref name="home"/> (this PC's archive, or a server): its projects, the /// "Open in workspace" for a sequence of <paramref name="home"/> (this PC's archive, or a server): its projects, the
/// media, and for this PC's archive what their copy writes and the room the workspace's drive has; null when closed /// media (Settings › Workspace › Media chosen first), what their copy writes and the room the workspace's drive has; null
/// without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed /// when closed without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
/// disabled, why in its tooltip. /// disabled, why in its tooltip.
/// </summary> /// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain) private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain)
{ {
var projects = await workspace.HomeProjectsAsync(home); var projects = await workspace.HomeProjectsAsync(home);
WorkspaceCopyFacts? copy = null; WorkspaceCopyFacts? copy = null;
if (home.IsArchive) try
{ {
try copy = await workspace.CopyFactsAsync(home);
{ }
copy = await workspace.CopyFactsAsync(home.SequenceId); catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException
} or UnauthorizedAccessException or ChronosApiException or System.Net.Http.HttpRequestException)
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException) {
{ // Only shown: the copy measures again before it writes.
// Only shown: the copy measures again before it writes. Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
}
} }
var unreadable = unreadableMain is { } main var unreadable = unreadableMain is { } main
? new Dictionary<Guid, string> ? new Dictionary<Guid, string>
@@ -837,7 +855,8 @@ public sealed class SequenceViewModel : SectionViewModel
[main.ProjectId] = Loc.L(main.Newer ? "Tooltips.Editor.Workspace.State.NewerCopy" : "Tooltips.Editor.Workspace.State.DamagedCopy"), [main.ProjectId] = Loc.L(main.Newer ? "Tooltips.Editor.Workspace.State.NewerCopy" : "Tooltips.Editor.Workspace.State.DamagedCopy"),
} }
: null; : null;
var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive); var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive,
defaultMedia: DefaultMedia(Shell.Services));
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar. // The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false; IsLoading = false;
OpenDialog(dialog); OpenDialog(dialog);
@@ -851,6 +870,37 @@ public sealed class SequenceViewModel : SectionViewModel
} }
} }
/// <summary>The media a checkout copies unless "Open in workspace" chose: Settings › Workspace › Media.</summary>
private static string DefaultMedia(AppServices services) =>
services.Settings.WorkspaceDefaultMedia == BundleMedia.Originals ? BundleMedia.Originals : BundleMedia.Proxies;
/// <summary>
/// The project of the sequence Edit opens when none was asked for (phase 5c, Settings › Workspace › Open project): the
/// one opened last, Main, or the one chosen in "Open which project?" when the workspace holds several (Cancelled: closed
/// without a choice). Only projects <paramref name="fits"/> takes count; none here: null.
/// </summary>
private async Task<(bool Cancelled, WorkspaceEntry? Entry)> PolicyEntryAsync(AppServices services, WorkspaceHost workspace, Guid sequenceId, string? title,
Func<WorkspaceEntry, bool> fits)
{
var last = await workspace.LastUsedAsync(sequenceId) is { } used && fits(used) ? used : null;
var policy = services.Settings.WorkspaceOpenProject;
if (policy == WorkspaceOpenPolicy.LastUsed) return (false, last);
var here = (await workspace.ProjectsOfAsync(sequenceId)).Where(p => fits(p) && p.IsReadable).ToList();
if (policy == WorkspaceOpenPolicy.Main) return (false, here.FirstOrDefault(p => p.IsMain) ?? last);
if (here.Count < 2) return (false, last ?? here.FirstOrDefault());
var dialog = new OpenProjectDialogViewModel(title ?? here[0].SequenceTitle, here, last?.ProjectId, d => CloseDialog(d));
IsLoading = false;
OpenDialog(dialog);
try
{
return await dialog.Choice is { } chosen ? (false, chosen) : (true, null);
}
finally
{
IsLoading = true;
}
}
/// <summary>The project the next open of <paramref name="sequenceId"/> takes, taken once; null when none was asked for.</summary> /// <summary>The project the next open of <paramref name="sequenceId"/> takes, taken once; null when none was asked for.</summary>
private ProjectRequest? TakeRequest(Guid sequenceId) private ProjectRequest? TakeRequest(Guid sequenceId)
{ {
@@ -81,6 +81,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private bool _isSyncing; private bool _isSyncing;
private bool _homeFramesChanged; private bool _homeFramesChanged;
private Guid _copyJob; private Guid _copyJob;
private bool _copyingOriginals;
private bool _changingMedia;
private bool _disposed; private bool _disposed;
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary> /// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
@@ -110,6 +112,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
RenameCommand = new AsyncRelayCommand(OpenRenameAsync); RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain); DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync); RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
CopyOriginalsCommand = new AsyncRelayCommand(CopyOriginalsAsync, () => !HoldsOriginals && !IsMediaBusy);
ProxiesOnlyCommand = new AsyncRelayCommand(ProxiesOnlyAsync, () => HoldsOriginals && !IsMediaBusy);
source.JobChanged += OnJobChanged; source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged; session.ProjectChanged += OnProjectChanged;
host.HomeChanged += OnHomeChanged; host.HomeChanged += OnHomeChanged;
@@ -193,6 +197,27 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public ICommand UpdateMediaCommand => _updateMedia; public ICommand UpdateMediaCommand => _updateMedia;
/// <summary>The workspace holds the project's originals besides its proxies (phase 5c): renders run on this PC.</summary>
public bool HoldsOriginals => _source.Workspace?.Media.Kind == BundleMedia.Originals;
/// <summary>
/// The media cannot change now: changes not saved as a version, a sync or a copy of the media running (the jobs of the
/// sequence are asked when the command runs).
/// </summary>
public bool IsMediaBusy => _changingMedia || _isSyncing || _copyJob != Guid.Empty || _status is { Modified: true, ReadOnly: false };
/// <summary>Copy originals… (phase 5c): the project's originals into the workspace, to render on this PC.</summary>
public ICommand CopyOriginalsCommand { get; }
/// <summary>Proxies only… (phase 5c): the originals copied here deleted once the home is checked to hold each one.</summary>
public ICommand ProxiesOnlyCommand { get; }
public string CopyOriginalsToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
: WorkspaceText.ForHome("Tooltips.Editor.Project.CopyOriginals", IsServerHome);
public string ProxiesOnlyToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
: WorkspaceText.ForHome("Tooltips.Editor.Project.ProxiesOnly", IsServerHome);
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary> /// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
public async Task RefreshAsync() public async Task RefreshAsync()
{ {
@@ -227,12 +252,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary> /// <summary>
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a /// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here, /// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive /// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive,
/// renders as it is: true. /// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version
/// on render, a changed project is saved as a version first (<see cref="SaveForRenderAsync"/>).
/// </summary> /// </summary>
public async Task<bool> ReadyToRenderAsync() public async Task<bool> ReadyToRenderAsync()
{ {
if (!IsServerHome) return true; if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false;
// Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is.
if (!IsServerHome || _source.RendersLocally) return true;
await StoreEditAsync(); await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId); var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false; if (_disposed) return false;
@@ -271,6 +299,45 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
return !_disposed && _source.InStepWithHome(_session.Project) is not null; return !_disposed && _source.InStepWithHome(_session.Project) is not null;
} }
/// <summary>
/// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version
/// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach,
/// it waits here). False when it could not be saved, or the sync met a conflict to settle first.
/// </summary>
private async Task<bool> SaveForRenderAsync()
{
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (!status.Modified || !CanSaveVersion) return true;
WorkspaceSaveResult result;
try
{
result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote"));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
return false;
}
if (_disposed) return false;
Apply(result.Status);
if (result.Synced is { } taken) await TakeAsync(taken);
if (result.Version is { } version)
{
// The home numbers what it stores: the last one sent is this version.
var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number;
_ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name);
}
if (result.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
if (result.Status.Conflict is not { } conflict) return true;
AskConflict(conflict);
return false;
}
/// <summary> /// <summary>
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the /// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about. /// sync took from the home comes into the editor, a conflict it met is asked about.
@@ -644,6 +711,130 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
} }
} }
/// <summary>
/// Copy originals…: refused while the media cannot change (<see cref="IsMediaBusy"/>, or a job of the sequence waits or
/// runs); otherwise the copy is queued, the banner says it runs, and the editor reads the media again once it is done.
/// </summary>
private async Task CopyOriginalsAsync()
{
try
{
await StoreEditAsync();
if (await MediaRefusalAsync() is { } refusal)
{
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), refusal, isError: true);
return;
}
var job = await _host.QueueOriginalsCopyAsync(ProjectId);
_copyJob = job.Id;
_copyingOriginals = true;
RaiseState();
_ui.Notify(Loc.L("Editor.Workspace.CopyingOriginals"), _session.Content.Sequence.DisplayTitle, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The originals of project {ProjectId} could not be queued for copy", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
/// <summary>
/// Proxies only…: the plan (each original hashed and weighed against the home, read now), confirmed by the user, then
/// applied; the home out of reach, or anything changed since the plan, removes nothing.
/// </summary>
private async Task ProxiesOnlyAsync()
{
try
{
await StoreEditAsync();
if (await MediaRefusalAsync() is { } refusal)
{
_ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), refusal, isError: true);
return;
}
SetChangingMedia(true);
var plan = await _host.PlanProxiesOnlyAsync(ProjectId);
if (_disposed) return;
var detail = new List<string>
{
Loc.L("Editor.ProxiesOnly.Originals", Formatting.Count(plan.Originals)),
Loc.L("Editor.ProxiesOnly.Size", Formatting.Bytes(plan.Bytes)),
};
if (plan.ToTrash > 0) detail.Add(Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(plan.ToTrash)));
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.ProxiesOnly.Title", Name),
Message = WorkspaceText.ForHome("Editor.ProxiesOnly.Message", IsServerHome),
Detail = string.Join(Environment.NewLine, detail),
IsDetailMonospaced = false,
DetailToolTip = plan.ToTrash > 0 ? WorkspaceText.ForHome("Tooltips.Editor.ProxiesOnly.ToTrash", IsServerHome) : null,
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Keep"),
ActionText = Loc.L("Editor.ProxiesOnly.Action"),
ActionToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Action"),
IsDestructive = true,
}))
return;
var trashed = await _host.ProxiesOnlyAsync(ProjectId, plan);
if (_disposed) return;
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.OriginalsRemoved"),
trashed > 0 ? Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(trashed)) : _session.Content.Sequence.DisplayTitle);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The originals of project {ProjectId} were not removed", ex);
_ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
finally
{
SetChangingMedia(false);
await RefreshAsync();
}
}
/// <summary>
/// Why the media cannot change now (<c>Errors.Workspace.MediaBusy</c>): changes not saved as a version, a copy or sync
/// running, or an analysis, render or workspace job of the sequence waiting or running; null when they can.
/// </summary>
private async Task<string?> MediaRefusalAsync()
{
var local = await _host.StatusAsync(ProjectId, askHome: false);
if (_disposed) return null;
Apply(WithLocal(_status, local));
if (IsMediaBusy) return Loc.L("Errors.Workspace.MediaBusy");
var jobs = await _source.ListJobsAsync(CancellationToken.None);
var sequenceId = SequenceId;
return jobs.Any(j => j.State is JobState.Queued or JobState.Running or JobState.Paused && j.TargetIds.Contains(sequenceId)
&& j.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceCopy or JobKind.WorkspaceRender
or JobKind.WorkspaceSend)
? Loc.L("Errors.Workspace.MediaBusy")
: null;
}
/// <summary>The copy of the originals ended: said, with the frames that have none (they stay proxies, and a local render waits for them).</summary>
private void NotifyOriginalsCopied()
{
int missing;
try
{
missing = _source.Project.ReadMedia()?.Frames.Count(f => f.Original is null) ?? 0;
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"The media of project {ProjectId} could not be read after the copy of its originals", ex);
missing = 0;
}
if (missing == 0) _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), _session.Content.Sequence.DisplayTitle);
else _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), Loc.L("Editor.Workspace.OriginalsMissing", Formatting.Count(missing)));
}
private void SetChangingMedia(bool changing)
{
_changingMedia = changing;
RaiseState();
}
/// <summary>The editor's last edit stored in the working state before an operation reads it.</summary> /// <summary>The editor's last edit stored in the working state before an operation reads it.</summary>
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception> /// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
private async Task StoreEditAsync() private async Task StoreEditAsync()
@@ -787,10 +978,13 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{ {
if (_disposed || job.Id != _copyJob) return; if (_disposed || job.Id != _copyJob) return;
_copyJob = Guid.Empty; _copyJob = Guid.Empty;
var originals = _copyingOriginals;
_copyingOriginals = false;
if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true); if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true);
try try
{ {
if (job.State == JobState.Done) await _session.ReloadAsync(); if (job.State == JobState.Done) await _session.ReloadAsync();
if (job.State == JobState.Done && originals) NotifyOriginalsCopied();
} }
catch (Exception ex) when (ex is not OutOfMemoryException) catch (Exception ex) when (ex is not OutOfMemoryException)
{ {
@@ -836,6 +1030,10 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
OnPropertyChanged(nameof(RemoveCopyToolTip)); OnPropertyChanged(nameof(RemoveCopyToolTip));
OnPropertyChanged(nameof(MediaChangedToolTip)); OnPropertyChanged(nameof(MediaChangedToolTip));
OnPropertyChanged(nameof(UpdateMediaToolTip)); OnPropertyChanged(nameof(UpdateMediaToolTip));
OnPropertyChanged(nameof(HoldsOriginals));
OnPropertyChanged(nameof(IsMediaBusy));
OnPropertyChanged(nameof(CopyOriginalsToolTip));
OnPropertyChanged(nameof(ProxiesOnlyToolTip));
_updateMedia.RaiseCanExecuteChanged(); _updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested(); CommandManager.InvalidateRequerySuggested();
} }
+107 -10
View File
@@ -47,8 +47,9 @@ public static class ProjectNames
/// <summary> /// <summary>
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project /// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project
/// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a /// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a
/// new one with its name, and the media to copy (proxies; the originals come in phase 5c). Open queues the copy; the /// new one with its name, and the media to copy: the proxies, or (phase 5c) the originals besides, to render on this PC,
/// sequence opens once it is done. /// offered while the workspace's drive has room for them (Settings › Workspace › Media chooses the default). Open queues
/// the copy; the sequence opens once it is done.
/// </summary> /// </summary>
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{ {
@@ -56,6 +57,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private readonly bool _server; private readonly bool _server;
private ProjectOption? _selected; private ProjectOption? _selected;
private bool _isNew; private bool _isNew;
private bool _isOriginals;
/// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param> /// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param>
/// <param name="copy">What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).</param> /// <param name="copy">What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).</param>
@@ -63,8 +65,10 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen. /// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
/// </param> /// </param>
/// <param name="server">The sequence's home is a server (phase 5b): the texts name the server.</param> /// <param name="server">The sequence's home is a server (phase 5b): the texts name the server.</param>
/// <param name="defaultMedia">The media chosen first (<see cref="AppSettings.WorkspaceDefaultMedia"/>); the proxies when the originals have no room.</param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close, public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false) IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false,
string defaultMedia = BundleMedia.Proxies)
: base(close) : base(close)
{ {
_server = server; _server = server;
@@ -76,7 +80,11 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")), new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")),
new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"), new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"),
Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")), Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")),
.. copy.OriginalsBytes is { } originals
? [new DialogFact(Loc.L("Editor.OpenWorkspace.Originals"), Formatting.Bytes(originals), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsSize"))]
: Array.Empty<DialogFact>(),
]; ];
_isOriginals = defaultMedia == BundleMedia.Originals && CanCopyOriginals;
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))]; Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
_selected = Projects.FirstOrDefault(p => p.IsAvailable); _selected = Projects.FirstOrDefault(p => p.IsAvailable);
_isNew = !HasProjects; _isNew = !HasProjects;
@@ -97,8 +105,8 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// <summary>"Copy size" and "Free space", under the media.</summary> /// <summary>"Copy size" and "Free space", under the media.</summary>
public IReadOnlyList<DialogFact> CopyFacts { get; } public IReadOnlyList<DialogFact> CopyFacts { get; }
/// <summary>The drive lacks room for the copy: the free space says so (the copy would stop saying how much is missing).</summary> /// <summary>The drive lacks room for the copy of the media chosen: the free space says so (the copy would stop saying how much is missing).</summary>
public bool IsShortOfSpace => Copy?.TooLittleSpace == true; public bool IsShortOfSpace => Copy?.TooLittleSpaceFor(Media) == true;
public string Heading => Loc.L("Editor.OpenWorkspace.Title"); public string Heading => Loc.L("Editor.OpenWorkspace.Title");
@@ -147,11 +155,37 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server); public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server);
/// <summary>The proxies, the only media this phase copies.</summary> /// <summary>The proxies alone: light to edit, renders run where the originals are.</summary>
public bool IsProxies => true; public bool IsProxies
{
get => !_isOriginals;
set
{
if (value) IsOriginals = false;
}
}
/// <summary>The originals: offered from phase 5c, to render on this PC.</summary> /// <summary>The proxies and the originals (phase 5c): renders run on this PC.</summary>
public bool CanCopyOriginals => false; public bool IsOriginals
{
get => _isOriginals;
set
{
if (!Set(ref _isOriginals, value && CanCopyOriginals)) return;
OnPropertyChanged(nameof(IsProxies));
OnPropertyChanged(nameof(IsShortOfSpace));
}
}
/// <summary>The media <see cref="Open"/> copies.</summary>
public string Media => _isOriginals ? BundleMedia.Originals : BundleMedia.Proxies;
/// <summary>The originals can be chosen: the drive has room for them besides the proxies (or was not measured: the copy measures again).</summary>
public bool CanCopyOriginals => Copy?.TooLittleSpaceFor(BundleMedia.Originals) != true;
public string OriginalsToolTip => CanCopyOriginals
? WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.OriginalsReady", _server)
: Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals");
public ICommand OpenCommand { get; } public ICommand OpenCommand { get; }
@@ -169,7 +203,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private void Open() private void Open()
{ {
if (!CanOpen) return; if (!CanOpen) return;
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), BundleMedia.Proxies) : new OpenChoice(_selected!.Project.Id, null, BundleMedia.Proxies)); _choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), Media) : new OpenChoice(_selected!.Project.Id, null, Media));
Close(); Close();
} }
@@ -181,6 +215,69 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
} }
} }
/// <summary>A project of the workspace offered by "Open which project?" (Main in the UI language).</summary>
public sealed record WorkspaceProjectChoice(WorkspaceEntry Entry)
{
public string Label => WorkspaceText.ProjectName(Entry.Name, Entry.IsMain);
public override string ToString() => Label;
}
/// <summary>
/// "Open which project?" (phase 5c, Settings › Workspace › Open project: Ask): Edit asks which of the sequence's projects in
/// the workspace opens, the one opened last chosen first.
/// </summary>
public sealed class OpenProjectDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<WorkspaceEntry?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private WorkspaceProjectChoice? _selected;
/// <param name="projects">The sequence's readable projects in the workspace.</param>
/// <param name="last">The project opened last, chosen first; null: Main.</param>
public OpenProjectDialogViewModel(string sequenceTitle, IReadOnlyList<WorkspaceEntry> projects, Guid? last, Action<ArchiveDialogViewModel> close)
: base(close)
{
ArgumentNullException.ThrowIfNull(projects);
Message = Loc.L("Editor.OpenProject.Message", sequenceTitle);
Projects = [.. projects.OrderByDescending(p => p.IsMain).ThenBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase).Select(p => new WorkspaceProjectChoice(p))];
_selected = Projects.FirstOrDefault(p => p.Entry.ProjectId == last) ?? Projects.FirstOrDefault();
OpenCommand = new RelayCommand(Open, () => _selected is not null);
}
/// <summary>Completes with the project chosen, or null when the dialog was closed without one.</summary>
public Task<WorkspaceEntry?> Choice => _choice.Task;
public string Heading => Loc.L("Editor.OpenProject.Title");
public string Message { get; }
public IReadOnlyList<WorkspaceProjectChoice> Projects { get; }
public WorkspaceProjectChoice? SelectedProject
{
get => _selected;
set
{
if (Set(ref _selected, value)) CommandManager.InvalidateRequerySuggested();
}
}
public ICommand OpenCommand { get; }
public override void Dispose()
{
_choice.TrySetResult(null);
base.Dispose();
}
private void Open()
{
if (_selected is null) return;
_choice.TrySetResult(_selected.Entry);
Close();
}
}
/// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary> /// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary>
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{ {
@@ -54,10 +54,10 @@
IsEnabled="{Binding IsNew}" ToolTip="{Binding NewName.ToolTip}" MaxLength="60" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.New}" /> IsEnabled="{Binding IsNew}" ToolTip="{Binding NewName.ToolTip}" MaxLength="60" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.New}" />
<TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" /> <TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" />
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0"> <StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0">
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies, Mode=OneWay}" <RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies}"
ToolTip="{Binding ProxiesToolTip}" Margin="0,0,16,0" /> ToolTip="{Binding ProxiesToolTip}" Margin="0,0,16,0" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False" <RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="{Binding IsOriginals}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" /> ToolTip="{Binding OriginalsToolTip}" ToolTipService.ShowOnDisabled="True" />
</StackPanel> </StackPanel>
</Grid> </Grid>
<!-- What the copy writes and the room the workspace's drive has for it. --> <!-- What the copy writes and the room the workspace's drive has for it. -->
@@ -88,6 +88,30 @@
</DataTemplate> </DataTemplate>
<!-- New project and Rename: the name, checked as it is typed. --> <!-- New project and Rename: the name, checked as it is typed. -->
<!-- Open which project? (Settings › Workspace › Open project: Ask): the sequence's projects in the workspace. -->
<DataTemplate DataType="{x:Type ws:OpenProjectDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<TextBlock Text="{Binding Message}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" TextWrapping="Wrap" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<ComboBox Grid.Column="1" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Editor.OpenProject.Choose}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.OpenWorkspace.Open}" Command="{Binding OpenCommand}"
ToolTip="{l:Loc Tooltips.Editor.OpenProject.Choose}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ws:ProjectNameDialogViewModel}"> <DataTemplate DataType="{x:Type ws:ProjectNameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460"> <Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel> <StackPanel>
@@ -1,4 +1,9 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization; using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces; using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace; namespace Chronos.App.Workspace;
@@ -9,7 +14,13 @@ namespace Chronos.App.Workspace;
/// </summary> /// </summary>
public sealed partial class WorkspaceHost public sealed partial class WorkspaceHost
{ {
/// <summary>The bytes the first copy of a sequence's media writes into the workspace, and the free bytes of the workspace's drive.</summary> /// <summary>A server's proxy when it says nothing of its size: some 1.5 MB, as the copy reckons one at 1920 px.</summary>
private const long ServerProxyEstimate = 1_500_000;
/// <summary>
/// The bytes the first copy of a sequence's media writes into the workspace (the proxies; the originals besides in
/// <see cref="WorkspaceCopyFacts.OriginalsBytes"/>), and the free bytes of the workspace's drive.
/// </summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception> /// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default) public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{ {
@@ -19,7 +30,100 @@ public sealed partial class WorkspaceHost
return Task.Run(async () => return Task.Run(async () =>
{ {
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false); var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free); var originals = await WorkspaceOriginals.ArchiveOriginalsBytesAsync(db, archives, sequenceId, cancellationToken: cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free, originals);
}, cancellationToken); }, cancellationToken);
} }
/// <summary>
/// What the copy of a sequence of <paramref name="home"/> writes: for this PC's archive as
/// <see cref="CopyFactsAsync(Guid, CancellationToken)"/>; for a server, reckoned from its frames (a proxy some 1.5 MB, the
/// originals as large as the server says they are).
/// </summary>
/// <exception cref="HomeUnavailableException">The server cannot be reached now.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(BundleHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
if (home.IsArchive) return CopyFactsAsync(home.SequenceId, cancellationToken);
var reached = Reachable(home);
var root = Root;
return Task.Run(async () =>
{
var frames = (await reached.FramesAsync(cancellationToken).ConfigureAwait(false)).Frames;
var present = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
return new WorkspaceCopyFacts(present.Count * ServerProxyEstimate, FreeBytes(root), present.Sum(f => Math.Max(0, f.Size)));
}, cancellationToken);
}
/// <summary>
/// "Copy originals…": queues the copy of a workspace project's media with its originals (phase 5c), unless a copy is
/// waiting or running already (that one is returned). The project file says originals once the copy commits.
/// </summary>
/// <exception cref="WorkspaceException">The project is not here, or the workspace folder is being moved.</exception>
public Task<Job> QueueOriginalsCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var bundle = Existing(projectId).ReadBundle();
Log.Info("workspace", $"Originals of project {projectId} queued for copy");
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, BundleMedia.Originals, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// The plan of "Proxies only…" (phase 5c): each original of the project hashed and weighed against the home's frames,
/// read now. Nothing is changed.
/// </summary>
/// <exception cref="WorkspaceException">The home cannot be reached to check the originals (<c>Errors.Workspace.OriginalsCheck</c>).</exception>
public Task<WorkspaceProxiesOnlyPlan> PlanProxiesOnlyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = await CheckedHomeFramesAsync(project, cancellationToken).ConfigureAwait(false);
return WorkspaceOriginals.PlanProxiesOnly(project, home);
}, cancellationToken);
/// <summary>
/// Applies "Proxies only…" as planned (the user confirmed it): the home's frames read again, the plan refused when the
/// project or the home changed since; then the originals the home holds are deleted, the others moved to the trash.
/// </summary>
/// <returns>The originals moved to the workspace's trash.</returns>
/// <exception cref="WorkspaceException">The home cannot be reached, or the workspace folder is being moved.</exception>
/// <exception cref="InvalidOperationException">The project or the home changed since the plan (<c>Errors.Workspace.MediaChanged</c>).</exception>
public Task<int> ProxiesOnlyAsync(Guid projectId, WorkspaceProxiesOnlyPlan plan, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
ArgumentNullException.ThrowIfNull(plan);
EnsureNotMoving();
var project = Existing(projectId);
var home = await CheckedHomeFramesAsync(project, cancellationToken).ConfigureAwait(false);
return await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, LockWait, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>The frames of the project's home, as it answers now; one out of reach refuses ("nothing was removed").</summary>
private async Task<HomeFrames> CheckedHomeFramesAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
var named = project.ReadBundle().Workspace!.Home;
var refused = WorkspaceText.ForHome("Errors.Workspace.OriginalsCheck", !named.IsArchive);
var home = HomeOf(named) ?? throw new WorkspaceException(refused);
try
{
return await home.FramesAsync(cancellationToken).ConfigureAwait(false);
}
catch (HomeUnavailableException ex)
{
throw new WorkspaceException(refused, ex);
}
}
/// <summary>Free bytes on the drive of <paramref name="folder"/>; null when it cannot be measured (a network share).</summary>
private static long? FreeBytes(string folder)
{
try
{
var root = Path.GetPathRoot(Path.GetFullPath(folder));
return string.IsNullOrEmpty(root) ? null : new DriveInfo(root).AvailableFreeSpace;
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
{
return null;
}
}
} }
@@ -37,7 +37,14 @@ namespace Chronos.Data.Workspaces;
/// removes the media it wrote itself, once it has stopped writing and under the project's lease, unless another copy of the /// removes the media it wrote itself, once it has stopped writing and under the project's lease, unless another copy of the
/// project goes on with them (<see cref="RemovePartialMediaAsync"/>); one cancelled while paused or failed, which no handler /// project goes on with them (<see cref="RemovePartialMediaAsync"/>); one cancelled while paused or failed, which no handler
/// runs, has them removed the same way (<see cref="CancelledAsync"/>). /// runs, has them removed the same way (<see cref="CancelledAsync"/>).
/// Originals come in phase 5c: asked for, the job fails saying so. /// With <see cref="BundleMedia.Originals"/> (phase 5c) the proxies are copied first as above, then each frame's original into
/// <c>media/originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;</c> (<see cref="WorkspaceProject.OriginalName"/>): streamed into a
/// <c>.part</c> file and hashed as it is written, the SHA-256 checked against the home's (recorded as copied when the home has
/// none), the file read back after its rename; one already there with the same SHA-256 is kept. A frame whose original the
/// home lacks (gone, flagged missing or damaged, refused by a server, not matching its SHA-256 twice) keeps its proxy: the
/// copy finishes saying how many. The space reckoned adds the originals not held yet; the checkpoint of that stage is
/// <c>originals:&lt;frame&gt;:&lt;frames version&gt;:&lt;folder&gt;</c>. Originals the committed media no longer name are deleted
/// only when the home holds a frame of the same SHA-256, else kept in the workspace's trash (<see cref="WorkspaceOriginals"/>).
/// A project whose home is a server (phase 5b, <see cref="WorkspaceJobs.CopyFromServer"/>) has its media downloaded from /// A project whose home is a server (phase 5b, <see cref="WorkspaceJobs.CopyFromServer"/>) has its media downloaded from
/// the server through the desktop's session (<see cref="ISyncConnector"/>), never through this PC's archive: the frames as /// the server through the desktop's session (<see cref="ISyncConnector"/>), never through this PC's archive: the frames as
/// of one frames version with the aliases of the server's conversions (<c>GET …/projects/frames</c>), each frame's proxy as /// of one frames version with the aliases of the server's conversions (<c>GET …/projects/frames</c>), each frame's proxy as
@@ -81,8 +88,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{ {
var ct = context.Cancellation; var ct = context.Cancellation;
var parameters = Parameters(context.Job); var parameters = Parameters(context.Job);
if (parameters.Media == BundleMedia.Originals) throw new NotSupportedException(Loc.L("Errors.Workspace.OriginalsLater")); if (parameters.Media is not (BundleMedia.Proxies or BundleMedia.Originals)) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
if (parameters.Media != BundleMedia.Proxies) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
if (parameters.Server is { Length: > 0 } server) if (parameters.Server is { Length: > 0 } server)
{ {
await RunFromServerAsync(context, parameters, server).ConfigureAwait(false); await RunFromServerAsync(context, parameters, server).ConfigureAwait(false);
@@ -259,6 +265,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// Read only: a read-only archive is copied from like any other. // Read only: a read-only archive is copied from like any other.
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(archive.RootPath, ArchiveAvailability.Offline); if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(archive.RootPath, ArchiveAvailability.Offline);
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint); var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
var withOriginals = parameters.Media == BundleMedia.Originals;
for (var pass = 1; ; pass++) for (var pass = 1; ; pass++)
{ {
var (row, frames) = await FramesAsync(sequenceId, ct).ConfigureAwait(false); var (row, frames) = await FramesAsync(sequenceId, ct).ConfigureAwait(false);
@@ -274,15 +281,18 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// Files kept from an earlier run are this frames version's and this folder's only (a conversion keeps a frame's id, // Files kept from an earlier run are this frames version's and this folder's only (a conversion keeps a frame's id,
// not its photo; a sequence moved meanwhile may have left its photos' names to another sequence's). // not its photo; a sequence moved meanwhile may have left its photos' names to another sequence's).
if ((checkpointVersion is { } version && version != row.FramesVersion) || (checkpointFolder is { } read && read != row.Folder)) copied = 0; if ((checkpointVersion is { } version && version != row.FramesVersion) || (checkpointFolder is { } read && read != row.Folder)) copied = 0;
var total = (long)frames.Count; var total = (long)frames.Count * (withOriginals ? 2 : 1);
var tally = new Tally(); var tally = new Tally();
var entries = new WorkspaceFrame[frames.Count]; var entries = new WorkspaceFrame[frames.Count];
// The media the editor reads until this copy commits: their files stay until then (RemoveStale). // The media the editor reads until this copy commits: their files stay until then (RemoveStale).
var current = TryReadMedia(project)?.Frames.Where(f => f.File is not null).ToDictionary(f => f.Id) ?? []; var held = TryReadMedia(project)?.Frames ?? [];
var current = held.Where(f => f.File is not null).ToDictionary(f => f.Id);
var heldOriginals = held.Where(f => f.Original is not null).ToDictionary(f => f.Id);
Directory.CreateDirectory(project.ProxiesDirectory); Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive, with the index, the settings and the logs: the copy never fills it. // The workspace is on this PC's own drive, with the index, the settings and the logs: the copy never fills it.
var remaining = Remaining(project, folder, frames, policy); var remaining = Remaining(project, folder, frames, policy);
EnsureSpace(parameters.WorkspaceRoot, remaining[0]); var originalsLeft = withOriginals ? RemainingOriginals(project, frames, heldOriginals, (f, _) => f.Size) : new long[frames.Count + 1];
EnsureSpace(parameters.WorkspaceRoot, remaining[0] + originalsLeft[0]);
var clock = System.Diagnostics.Stopwatch.StartNew(); var clock = System.Diagnostics.Stopwatch.StartNew();
for (var i = 0; i < frames.Count; i++) for (var i = 0; i < frames.Count; i++)
{ {
@@ -292,7 +302,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{ {
await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1, row.FramesVersion, row.Folder), i + 1, total).ConfigureAwait(false); await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1, row.FramesVersion, row.Folder), i + 1, total).ConfigureAwait(false);
// Another program may take the space meanwhile. // Another program may take the space meanwhile.
EnsureSpace(parameters.WorkspaceRoot, remaining[i + 1]); EnsureSpace(parameters.WorkspaceRoot, remaining[i + 1] + originalsLeft[0]);
clock.Restart(); clock.Restart();
} }
else else
@@ -300,6 +310,27 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
await context.ReportAsync(i + 1, total).ConfigureAwait(false); await context.ReportAsync(i + 1, total).ConfigureAwait(false);
} }
} }
var originals = new OriginalsTally();
if (withOriginals)
{
for (var i = 0; i < frames.Count; i++)
{
ct.ThrowIfCancellationRequested();
entries[i] = await CopyOriginalAsync(project, paths, frames[i], entries[i], heldOriginals.GetValueOrDefault(frames[i].Id),
originals, ct).ConfigureAwait(false);
var done = frames.Count + i + 1;
if (clock.Elapsed >= CheckpointEvery)
{
await context.CheckpointAsync(Checkpoint(Stage.Originals, i + 1, row.FramesVersion, row.Folder), done, total).ConfigureAwait(false);
EnsureSpace(parameters.WorkspaceRoot, originalsLeft[i + 1]);
clock.Restart();
}
else
{
await context.ReportAsync(done, total).ConfigureAwait(false);
}
}
}
var analysis = CopyAnalysis(folder, project, frames.Count); var analysis = CopyAnalysis(folder, project, frames.Count);
var (after, now) = await FramesAsync(sequenceId, ct).ConfigureAwait(false); var (after, now) = await FramesAsync(sequenceId, ct).ConfigureAwait(false);
var moved = after.Folder != row.Folder || !SequenceFolders.Holds(paths.Sequence(after.Folder), sequenceId) || Renamed(frames, now, entries); var moved = after.Folder != row.Folder || !SequenceFolders.Holds(paths.Sequence(after.Folder), sequenceId) || Renamed(frames, now, entries);
@@ -322,15 +353,16 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
} }
} }
var aliases = await HomePhotos.AliasesAsync(db, sequenceId, ct).ConfigureAwait(false); var aliases = await HomePhotos.AliasesAsync(db, sequenceId, ct).ConfigureAwait(false);
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, row.FramesVersion, entries, var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, parameters.Media, sequenceId, row.FramesVersion, entries,
DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null); DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null);
// The working state is the editor's meanwhile: it is held only while the media index and the positions move. // The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false)) using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{ {
Commit(project, project.ReadBundle(), media, row.Folder, row.DisplayTitle); Commit(project, project.ReadBundle(), media, row.Folder, row.DisplayTitle);
RemoveStale(project, media); RemoveStale(project, media, frames);
} }
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing)); context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
if (withOriginals) originals.LogTo(context, "Archive.Log.WorkspaceOriginals", row.DisplayTitle);
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, row.FramesVersion, row.Folder), total, total).ConfigureAwait(false); await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, row.FramesVersion, row.Folder), total, total).ConfigureAwait(false);
return; return;
} }
@@ -372,6 +404,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
CancellationToken ct) CancellationToken ct)
{ {
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint); var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
var withOriginals = parameters.Media == BundleMedia.Originals;
// What this run downloaded, pass after pass: kept where a frame still shows the same photo. // What this run downloaded, pass after pass: kept where a frame still shows the same photo.
var fetched = new Dictionary<Guid, WorkspaceFrame>(); var fetched = new Dictionary<Guid, WorkspaceFrame>();
for (var pass = 1; ; pass++) for (var pass = 1; ; pass++)
@@ -379,15 +412,20 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
var (sequence, frames, assets, aliases, framesVersion, spec) = await ServerFramesAsync(remote, sequenceId, ct).ConfigureAwait(false); var (sequence, frames, assets, aliases, framesVersion, spec) = await ServerFramesAsync(remote, sequenceId, ct).ConfigureAwait(false);
var folder = sequence.Folder ?? string.Empty; var folder = sequence.Folder ?? string.Empty;
if ((checkpointVersion is { } version && version != framesVersion) || (checkpointFolder is { } read && read != folder)) copied = 0; if ((checkpointVersion is { } version && version != framesVersion) || (checkpointFolder is { } read && read != folder)) copied = 0;
var total = (long)frames.Count; var total = (long)frames.Count * (withOriginals ? 2 : 1);
var tally = new Tally(); var tally = new Tally();
var entries = new WorkspaceFrame[frames.Count]; var entries = new WorkspaceFrame[frames.Count];
// The media the editor reads until this copy commits: their files stay until then (RemoveStale). // The media the editor reads until this copy commits: their files stay until then (RemoveStale).
var current = TryReadMedia(project)?.Frames.Where(f => f.File is not null).ToDictionary(f => f.Id) ?? []; var held = TryReadMedia(project)?.Frames ?? [];
var current = held.Where(f => f.File is not null).ToDictionary(f => f.Id);
var heldOriginals = held.Where(f => f.Original is not null).ToDictionary(f => f.Id);
Directory.CreateDirectory(project.ProxiesDirectory); Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive: the copy never fills it (the server's files estimated at its proxy size). // The workspace is on this PC's own drive: the copy never fills it (the server's files estimated at its proxy size).
var remaining = RemainingDownloads(project, frames, assets, spec); var remaining = RemainingDownloads(project, frames, assets, spec);
EnsureSpace(parameters.WorkspaceRoot, remaining[0]); var originalsLeft = withOriginals
? RemainingOriginals(project, frames, heldOriginals, (f, _) => assets.GetValueOrDefault(f.Id) is { } asset ? asset.Size : 0)
: new long[frames.Count + 1];
EnsureSpace(parameters.WorkspaceRoot, remaining[0] + originalsLeft[0]);
var clock = System.Diagnostics.Stopwatch.StartNew(); var clock = System.Diagnostics.Stopwatch.StartNew();
var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct }; var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct };
for (var start = 0; start < frames.Count; start += DownloadBatch) for (var start = 0; start < frames.Count; start += DownloadBatch)
@@ -401,7 +439,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{ {
await context.CheckpointAsync(Checkpoint(Stage.Copy, end, framesVersion, folder), end, total).ConfigureAwait(false); await context.CheckpointAsync(Checkpoint(Stage.Copy, end, framesVersion, folder), end, total).ConfigureAwait(false);
// Another program may take the space meanwhile. // Another program may take the space meanwhile.
EnsureSpace(parameters.WorkspaceRoot, remaining[end]); EnsureSpace(parameters.WorkspaceRoot, remaining[end] + originalsLeft[0]);
clock.Restart(); clock.Restart();
} }
else else
@@ -410,6 +448,27 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
} }
} }
foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry; foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry;
var originals = new OriginalsTally();
if (withOriginals)
{
for (var start = 0; start < frames.Count; start += DownloadBatch)
{
var end = Math.Min(frames.Count, start + DownloadBatch);
await Parallel.ForEachAsync(Enumerable.Range(start, end - start), options, async (i, token) =>
entries[i] = await DownloadOriginalAsync(remote, project, frames[i], assets.GetValueOrDefault(frames[i].Id), entries[i],
heldOriginals.GetValueOrDefault(frames[i].Id), originals, token).ConfigureAwait(false)).ConfigureAwait(false);
if (clock.Elapsed >= CheckpointEvery || end == frames.Count)
{
await context.CheckpointAsync(Checkpoint(Stage.Originals, end, framesVersion, folder), frames.Count + end, total).ConfigureAwait(false);
EnsureSpace(parameters.WorkspaceRoot, originalsLeft[end]);
clock.Restart();
}
else
{
await context.ReportAsync(frames.Count + end, total).ConfigureAwait(false);
}
}
}
var analysis = await CopyServerAnalysisAsync(remote, sequenceId, project, frames.Count, ct).ConfigureAwait(false); var analysis = await CopyServerAnalysisAsync(remote, sequenceId, project, frames.Count, ct).ConfigureAwait(false);
var after = await remote.GetSequenceAsync(sequenceId, ct).ConfigureAwait(false); var after = await remote.GetSequenceAsync(sequenceId, ct).ConfigureAwait(false);
if (after.FramesVersion != framesVersion && pass < Passes) if (after.FramesVersion != framesVersion && pass < Passes)
@@ -422,15 +481,16 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
continue; continue;
} }
// Frames still arriving are copied as they were read (Update media takes the rest). // Frames still arriving are copied as they were read (Update media takes the rest).
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, framesVersion, entries, var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, parameters.Media, sequenceId, framesVersion, entries,
DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null); DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null);
// The working state is the editor's meanwhile: it is held only while the media index and the positions move. // The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false)) using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{ {
Commit(project, project.ReadBundle(), media, folder, sequence.DisplayTitle); Commit(project, project.ReadBundle(), media, folder, sequence.DisplayTitle);
RemoveStale(project, media); RemoveStale(project, media, frames);
} }
context.Log(Loc.L("Archive.Log.WorkspaceDownloaded", sequence.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing)); context.Log(Loc.L("Archive.Log.WorkspaceDownloaded", sequence.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
if (withOriginals) originals.LogTo(context, "Archive.Log.WorkspaceOriginalsDownloaded", sequence.DisplayTitle);
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, framesVersion, folder), total, total).ConfigureAwait(false); await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, framesVersion, folder), total, total).ConfigureAwait(false);
return; return;
} }
@@ -572,6 +632,166 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
entry is { FileSha256: { } held } && string.Equals(held, sha, StringComparison.OrdinalIgnoreCase) ? entry.FileKind ?? ProxyCache.Proxy : null; entry is { FileSha256: { } held } && string.Equals(held, sha, StringComparison.OrdinalIgnoreCase) ? entry.FileKind ?? ProxyCache.Proxy : null;
} }
/// <summary>
/// A frame's original from this PC's archive into <c>media/originals/</c> (phase 5c), beside its proxy in
/// <paramref name="entry"/>: kept when the workspace holds it already with the same SHA-256, else streamed into a
/// <c>.part</c> file hashed as it is written (never held in memory), checked against the home's SHA-256, renamed and read
/// back. A frame flagged missing or damaged at the home, or whose file is gone, keeps its proxy alone; so does one whose
/// original twice does not match the SHA-256 the home has of it (the part is removed, the copy goes on).
/// </summary>
private static async Task<WorkspaceFrame> CopyOriginalAsync(WorkspaceProject project, ArchivePaths paths, Frame frame, WorkspaceFrame entry,
WorkspaceFrame? held, OriginalsTally tally, CancellationToken cancellationToken)
{
var extension = OriginalExtension(frame);
var expected = string.IsNullOrEmpty(frame.Sha256) ? null : frame.Sha256.ToLowerInvariant();
if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) return tally.Missed(entry, frame.Index);
if (await HeldOriginalAsync(project, frame, expected, extension, held, cancellationToken).ConfigureAwait(false) is { } kept)
{
tally.Keep();
return entry with { Original = kept.Name, OriginalSha256 = kept.Sha256, OriginalBytes = kept.Bytes };
}
var source = paths.FromRelative(frame.RelativePath);
if (!File.Exists(source)) return tally.Missed(entry, frame.Index);
Directory.CreateDirectory(project.OriginalsDirectory);
var part = Path.Combine(project.OriginalsDirectory, frame.Id.ToString("N") + ".part");
for (var attempt = 1; ; attempt++)
{
string sha;
long bytes;
try
{
await using var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, StreamBuffer,
FileOptions.Asynchronous | FileOptions.SequentialScan);
await using var output = new FileStream(part, FileMode.Create, FileAccess.Write, FileShare.None, StreamBuffer, FileOptions.Asynchronous);
using var hashing = new HashingStream(output);
await input.CopyToAsync(hashing, StreamBuffer, cancellationToken).ConfigureAwait(false);
output.Flush(flushToDisk: true);
(sha, bytes) = (hashing.Sha256(), hashing.Written);
}
catch (FileNotFoundException)
{
// Gone while it was read (a Reorganize): the frame keeps its proxy, the pass's check of the folder decides the rest.
TryDelete(part);
return tally.Missed(entry, frame.Index);
}
catch (OperationCanceledException)
{
// A part is never resumed from (a source is read whole): it goes, so a cancel leaves nothing half written.
TryDelete(part);
throw;
}
if (expected is not null && sha != expected)
{
TryDelete(part);
if (attempt == 1) continue;
Log.Warning("workspace", Loc.L("Errors.Workspace.OriginalMismatch", source));
return tally.Missed(entry, frame.Index);
}
var name = WorkspaceProject.OriginalName(frame.Id, sha, extension);
var target = project.MediaFile(name);
File.Move(part, target, overwrite: true);
if (string.Equals(await ContentHash.Sha256Async(target, cancellationToken: cancellationToken).ConfigureAwait(false), sha, StringComparison.OrdinalIgnoreCase))
{
tally.Copy();
return entry with { Original = name, OriginalSha256 = sha, OriginalBytes = bytes };
}
TryDelete(target);
if (attempt == 2) throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", target));
}
}
/// <summary>
/// A frame's original from a server into <c>media/originals/</c> (phase 5c): kept when held already, else downloaded with
/// <see cref="SyncTransfers.FetchOriginalAsync"/> (resumable, checked against the server's SHA-256, two attempts) into a
/// staging folder beside the originals, then renamed into place. A frame the server has no original of (flagged missing
/// or damaged, 404), one this account may not read (403), or one that does not match twice keeps its proxy alone.
/// </summary>
private static async Task<WorkspaceFrame> DownloadOriginalAsync(ISyncRemote remote, WorkspaceProject project, Frame frame, ManifestFrame? asset, WorkspaceFrame entry,
WorkspaceFrame? held, OriginalsTally tally, CancellationToken cancellationToken)
{
if (asset is null || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 || (((FrameFlags)asset.Flags) & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0)
return tally.Missed(entry, frame.Index);
var extension = Path.GetExtension(asset.FileName);
var expected = string.IsNullOrEmpty(asset.Sha256) ? null : asset.Sha256.ToLowerInvariant();
if (await HeldOriginalAsync(project, frame, expected, extension, held, cancellationToken).ConfigureAwait(false) is { } kept)
{
tally.Keep();
return entry with { Original = kept.Name, OriginalSha256 = kept.Sha256, OriginalBytes = kept.Bytes };
}
var staging = Path.Combine(project.OriginalsDirectory, OriginalsStaging);
Directory.CreateDirectory(staging);
string path, sha;
try
{
(path, sha) = await SyncTransfers.FetchOriginalAsync(remote, asset, staging, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status is HttpStatusCode.NotFound or HttpStatusCode.Forbidden)
{
return tally.Missed(entry, frame.Index);
}
catch (InvalidDataException ex)
{
Log.Warning("workspace", $"The original of frame {frame.Id} did not match the server's SHA-256", ex);
return tally.Missed(entry, frame.Index);
}
var name = WorkspaceProject.OriginalName(frame.Id, sha, extension);
var target = project.MediaFile(name);
var bytes = new FileInfo(path).Length;
File.Move(path, target, overwrite: true);
tally.Copy();
return entry with { Original = name, OriginalSha256 = sha, OriginalBytes = bytes };
}
/// <summary>
/// The original the workspace holds of <paramref name="frame"/>, hashed again: the one the media name for it (the same
/// photo, of the SHA-256 the home has when it has one), else the file a copy of <paramref name="expected"/> takes; null when
/// none holds it (a file that no longer matches is copied anew).
/// </summary>
private static async Task<(string Name, string Sha256, long Bytes)?> HeldOriginalAsync(WorkspaceProject project, Frame frame, string? expected, string extension,
WorkspaceFrame? held, CancellationToken cancellationToken)
{
var candidates = new List<(string Name, string? Sha)>();
if (held is { Original: { } heldName, OriginalSha256: { } heldSha } && SamePhoto(held, frame) && (expected is null || string.Equals(heldSha, expected, StringComparison.OrdinalIgnoreCase)))
candidates.Add((heldName, heldSha.ToLowerInvariant()));
if (expected is not null) candidates.Add((WorkspaceProject.OriginalName(frame.Id, expected, extension), expected));
foreach (var (name, sha) in candidates)
{
var path = project.MediaFile(name);
if (!File.Exists(path)) continue;
var found = await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false);
if (string.Equals(found, sha, StringComparison.OrdinalIgnoreCase)) return (name, found.ToLowerInvariant(), new FileInfo(path).Length);
}
return null;
}
/// <summary>
/// The bytes a copy of the originals still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one
/// more entry, 0): <paramref name="size"/> of each frame whose original the workspace does not hold yet under the name a
/// copy gives it, nothing for one the media name already, or flagged missing.
/// </summary>
private static long[] RemainingOriginals(WorkspaceProject project, List<Frame> frames, Dictionary<Guid, WorkspaceFrame> held, Func<Frame, int, long> size)
{
var remaining = new long[frames.Count + 1];
for (var i = frames.Count - 1; i >= 0; i--)
{
var frame = frames[i];
var there = (held.GetValueOrDefault(frame.Id) is { Original: { } name } && File.Exists(project.MediaFile(name)))
|| (!string.IsNullOrEmpty(frame.Sha256) && File.Exists(project.MediaFile(WorkspaceProject.OriginalName(frame.Id, frame.Sha256, OriginalExtension(frame)))));
var bytes = there || (frame.Flags & FrameFlags.Missing) != 0 ? 0 : Math.Max(0, size(frame, i));
remaining[i] = remaining[i + 1] + bytes;
}
return remaining;
}
/// <summary>The extension of a frame's original as its path at the home has it (else its file name), which decoders go by.</summary>
private static string OriginalExtension(Frame frame) => Path.GetExtension(frame.RelativePath) is { Length: > 0 } extension ? extension : Path.GetExtension(frame.FileName);
/// <summary>The folder beside the originals a download from a server stages them in (resumable parts), emptied by the commit.</summary>
private const string OriginalsStaging = ".staging";
/// <summary>The buffer an original is streamed through.</summary>
private const int StreamBuffer = 1 << 20;
/// <summary> /// <summary>
/// The bytes a copy from a server still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one more /// The bytes a copy from a server still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one more
/// entry, 0): nothing for a frame the workspace holds a file of already or the server has neither proxy nor thumbnail of, /// entry, 0): nothing for a frame the workspace holds a file of already or the server has neither proxy nor thumbnail of,
@@ -785,7 +1005,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, string folder, string title) private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, string folder, string title)
{ {
var old = TryReadMedia(project); var old = TryReadMedia(project);
var workspace = bundle.Workspace! with { Media = new BundleMedia(BundleMedia.Proxies, media.FramesVersion) }; var workspace = bundle.Workspace! with { Media = new BundleMedia(media.Kind, media.FramesVersion) };
var sequence = bundle.Sequence with { Folder = folder, Title = title, Frames = media.Frames.Count }; var sequence = bundle.Sequence with { Folder = folder, Title = title, Frames = media.Frames.Count };
var working = bundle.Project; var working = bundle.Project;
// Without the media index the positions were made against, they are taken as naming these frames. // Without the media index the positions were made against, they are taken as naming these frames.
@@ -814,8 +1034,36 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// <summary> /// <summary>
/// Proxies of frames the sequence no longer has, and downloads a stopped copy from a server left half done: regenerable /// Proxies of frames the sequence no longer has, and downloads a stopped copy from a server left half done: regenerable
/// copies, removed so the media folder holds the frames listed. /// copies, removed so the media folder holds the frames listed. Media of kind originals (phase 5c) clear their folder
/// alike, but an original is never erased on a guess: one the media no longer name is deleted only when the home's
/// frames (<paramref name="home"/>, as this copy read them) hold a photo of its SHA-256, else it goes to the workspace's
/// trash (<see cref="WorkspaceOriginals.DeleteOrTrash"/>). A copy of the proxies alone leaves the originals as they are.
/// </summary> /// </summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media, IReadOnlyList<Frame> home)
{
RemoveStale(project, media);
if (!media.HoldsOriginals || !Directory.Exists(project.OriginalsDirectory)) return;
var staging = Path.Combine(project.OriginalsDirectory, OriginalsStaging);
if (Directory.Exists(staging))
{
try
{
Directory.Delete(staging, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{staging} could not be removed", ex);
}
}
var originals = media.Frames.Where(f => f.Original is not null).Select(f => Path.GetFileName(f.Original!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
var stale = Directory.EnumerateFiles(project.OriginalsDirectory).Where(f => !originals.Contains(Path.GetFileName(f))).ToList();
foreach (var part in stale.Where(IsPart)) TryDelete(part);
WorkspaceOriginals.DeleteOrTrash(project, [.. stale.Where(f => !IsPart(f))], home);
}
private static bool IsPart(string file) => file.EndsWith(".part", StringComparison.OrdinalIgnoreCase);
/// <summary>The proxies' folder cleared as <see cref="RemoveStale(WorkspaceProject, WorkspaceMedia, IReadOnlyList{Frame})"/> says.</summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media) private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media)
{ {
var listed = media.Frames.Where(f => f.File is not null).Select(f => Path.GetFileName(f.File!)).ToHashSet(StringComparer.OrdinalIgnoreCase); var listed = media.Frames.Where(f => f.File is not null).Select(f => Path.GetFileName(f.File!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
@@ -889,6 +1137,18 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
return (Remaining([], paths.Sequence(row.Folder), frames, policy)[0], FreeBytes(workspaceRoot)); return (Remaining([], paths.Sequence(row.Folder), frames, policy)[0], FreeBytes(workspaceRoot));
} }
/// <summary>
/// The bytes a copy of the sequence's originals writes (phase 5c): every frame's original the archive has, or, for a
/// workspace project that holds some already (<paramref name="project"/>), only those it lacks.
/// </summary>
internal async Task<long> OriginalsBytesAsync(Guid sequenceId, WorkspaceProject? project, CancellationToken cancellationToken)
{
var (_, frames) = await FramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (project is null || !File.Exists(project.MediaIndexPath)) return frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Sum(f => Math.Max(0, f.Size));
var held = (TryReadMedia(project)?.Frames ?? []).Where(f => f.Original is not null).ToDictionary(f => f.Id);
return RemainingOriginals(project, frames, held, (f, _) => f.Size)[0];
}
/// <summary>A proxy's size when the archive has none to measure: some 1.5 MB at 1920 px, scaled by the area at the copy's long edge.</summary> /// <summary>A proxy's size when the archive has none to measure: some 1.5 MB at 1920 px, scaled by the area at the copy's long edge.</summary>
private static long Estimate(Frame frame, ProxyPolicy policy) private static long Estimate(Frame frame, ProxyPolicy policy)
{ {
@@ -980,6 +1240,9 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{ {
Copy, Copy,
Done, Done,
/// <summary>The proxies are copied; the originals are (phase 5c).</summary>
Originals,
} }
private static string Checkpoint(Stage stage, int frame, int framesVersion, string folder) => private static string Checkpoint(Stage stage, int frame, int framesVersion, string folder) =>
@@ -994,11 +1257,46 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
private static (int Copied, int? FramesVersion, string? Folder) Parse(string? checkpoint) private static (int Copied, int? FramesVersion, string? Folder) Parse(string? checkpoint)
{ {
var parts = checkpoint?.Split(':', 4); var parts = checkpoint?.Split(':', 4);
if (parts is not ([_, _] or [_, _, _] or [_, _, _, _]) || !Enum.TryParse<Stage>(parts[0], ignoreCase: true, out var stage) || stage != Stage.Copy if (parts is not ([_, _] or [_, _, _] or [_, _, _, _]) || !Enum.TryParse<Stage>(parts[0], ignoreCase: true, out var stage) || stage is not (Stage.Copy or Stage.Originals)
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var next)) || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var next))
return (0, null, null); return (0, null, null);
int? version = parts.Length >= 3 && int.TryParse(parts[2], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : null; int? version = parts.Length >= 3 && int.TryParse(parts[2], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : null;
return (next, version, parts.Length == 4 ? parts[3] : null); return (stage == Stage.Originals ? int.MaxValue : next, version, parts.Length == 4 ? parts[3] : null);
}
/// <summary>What a copy of the originals did with each frame (phase 5c), counted from the workers that download them at once.</summary>
private sealed class OriginalsTally
{
/// <summary>Frames named one by one in the job's log when they have no original; the count says the rest.</summary>
private const int Named = 20;
private readonly System.Collections.Concurrent.ConcurrentQueue<(int Index, string Name)> _missed = new();
private int _copied;
private int _kept;
public int Copied => Volatile.Read(ref _copied);
public int Kept => Volatile.Read(ref _kept);
public int Missing => _missed.Count;
public void Copy() => Interlocked.Increment(ref _copied);
public void Keep() => Interlocked.Increment(ref _kept);
/// <summary>The frame keeps its proxy alone: <paramref name="entry"/> with no original.</summary>
public WorkspaceFrame Missed(WorkspaceFrame entry, int index)
{
_missed.Enqueue((index, entry.FileName));
return entry with { Original = null, OriginalSha256 = null, OriginalBytes = 0 };
}
/// <summary>Says in the job's log what was copied (<paramref name="key"/>), and names the first frames without an original.</summary>
public void LogTo(JobContext context, string key, string title)
{
foreach (var (_, name) in _missed.OrderBy(m => m.Index).Take(Named)) context.Log(Loc.L("Archive.Log.WorkspaceOriginalMissing", title, name));
context.Log(Loc.L(key, title, Copied, Kept, Missing));
}
} }
/// <summary>What a copy did with each frame, counted from the workers that download them at once.</summary> /// <summary>What a copy did with each frame, counted from the workers that download them at once.</summary>
@@ -0,0 +1,186 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
namespace Chronos.Data.Workspaces;
/// <summary>
/// What "Proxies only" (phase 5c) does to a workspace project that holds its originals: <paramref name="Originals"/> files
/// of <paramref name="Bytes"/> the home holds with the same SHA-256, deleted; <paramref name="ToTrash"/> files of
/// <paramref name="TrashBytes"/> it does not (gone there, damaged, or another photo now), moved to the workspace's trash.
/// <paramref name="Fingerprint"/> names the files and the home's answer the plan read: an apply refuses a plan the
/// project or the home changed since.
/// </summary>
public sealed record WorkspaceProxiesOnlyPlan(Guid ProjectId, int Originals, long Bytes, int ToTrash, long TrashBytes, string Fingerprint)
{
/// <summary>Nothing to remove: the project holds no originals.</summary>
public bool IsEmpty => Originals == 0 && ToTrash == 0;
}
/// <summary>
/// The originals of a workspace project (phase 5c): what a copy of them writes, and their removal. An original is never
/// erased on a guess: a file is deleted only when the home holds a photo of its SHA-256, read from the file at that moment,
/// that the home has not flagged missing or damaged; any other goes to the workspace's trash
/// (<c>&lt;root&gt;/.trash/&lt;project id&gt;-&lt;ticks&gt;/originals/</c>, which the clean-up empties).
/// </summary>
public static class WorkspaceOriginals
{
/// <summary>The workspace's trash folder, under its root (the App's <c>WorkspaceHost.TrashFolder</c>).</summary>
public const string TrashFolder = ".trash";
/// <summary>
/// The bytes a copy of the sequence's originals writes from this PC's archive: all the archive has, or only those
/// <paramref name="project"/> lacks when it holds some already.
/// </summary>
public static Task<long> ArchiveOriginalsBytesAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, WorkspaceProject? project = null,
CancellationToken cancellationToken = default) =>
new WorkspaceCopyJobHandler(db, archives).OriginalsBytesAsync(sequenceId, project, cancellationToken);
/// <summary>
/// What "Proxies only" removes from <paramref name="project"/>, each original hashed now and weighed against
/// <paramref name="home"/> (the home's frames as read just before): nothing when it holds none.
/// </summary>
/// <exception cref="InvalidDataException">The media index is damaged or newer.</exception>
public static WorkspaceProxiesOnlyPlan PlanProxiesOnly(WorkspaceProject project, HomeFrames home)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(home);
var files = Files(project);
var held = HeldAtHome(home.Frames);
var fingerprint = new StringBuilder(home.FramesVersion.ToString(CultureInfo.InvariantCulture));
int deleted = 0, trashed = 0;
long deletedBytes = 0, trashedBytes = 0;
foreach (var file in files)
{
var (sha, bytes) = Hash(file);
var atHome = sha is not null && held.Contains(sha);
if (atHome) (deleted, deletedBytes) = (deleted + 1, deletedBytes + bytes);
else (trashed, trashedBytes) = (trashed + 1, trashedBytes + bytes);
fingerprint.Append('|').Append(Path.GetFileName(file)).Append(':').Append(sha).Append(':').Append(atHome ? 'd' : 't');
}
var digest = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint.ToString())));
return new WorkspaceProxiesOnlyPlan(project.ProjectId, deleted, deletedBytes, trashed, trashedBytes, digest);
}
/// <summary>
/// Applies a plan of <see cref="PlanProxiesOnly"/> under the project's lease: planned again, refused when anything changed
/// (<c>Errors.Workspace.MediaChanged</c>); then the media index and the project file say proxies first (so a stop
/// half way leaves media that name no original that is gone), and last each original is deleted or trashed as the plan
/// says, hashed again as it goes.
/// </summary>
/// <returns>The files moved to the trash.</returns>
/// <exception cref="InvalidOperationException">The project or the home changed since the plan.</exception>
/// <exception cref="Chronos.Core.Archiving.LeaseUnavailableException">Another writer holds the project.</exception>
public static async Task<int> ApplyProxiesOnlyAsync(WorkspaceProject project, WorkspaceProxiesOnlyPlan plan, HomeFrames home, TimeSpan lockWait,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(home);
using (await project.LockAsync(lockWait, cancellationToken).ConfigureAwait(false))
{
var now = PlanProxiesOnly(project, home);
if (now.ProjectId != plan.ProjectId || now.Fingerprint != plan.Fingerprint) throw new InvalidOperationException(Loc.L("Errors.Workspace.MediaChanged"));
var media = project.ReadMedia();
var files = Files(project);
if (media is not null)
{
project.WriteMedia(media with
{
Kind = BundleMedia.Proxies,
Frames = [.. media.Frames.Select(f => f with { Original = null, OriginalSha256 = null, OriginalBytes = 0 })],
});
}
var bundle = project.ReadBundle();
if (bundle.Workspace is { } workspace && workspace.Media.Kind != BundleMedia.Proxies)
project.WriteBundle(bundle with { Workspace = workspace with { Media = workspace.Media with { Kind = BundleMedia.Proxies } } });
var trashed = DeleteOrTrash(project, files, home.Frames);
var staging = Path.Combine(project.OriginalsDirectory, ".staging");
if (Directory.Exists(staging)) TryDeleteFolder(staging);
if (Directory.Exists(project.OriginalsDirectory) && !Directory.EnumerateFileSystemEntries(project.OriginalsDirectory).Any()) TryDeleteFolder(project.OriginalsDirectory);
Log.Info("workspace", $"Originals of project {project.ProjectId} removed: {plan.Originals} deleted, {trashed} kept in {TrashFolder}");
return trashed;
}
}
/// <summary>
/// Deletes each of <paramref name="files"/> (originals of <paramref name="project"/>) whose SHA-256, read now, is that of a
/// photo <paramref name="home"/> holds, not flagged missing or damaged; moves the others to the workspace's trash.
/// </summary>
/// <returns>The files moved to the trash.</returns>
internal static int DeleteOrTrash(WorkspaceProject project, IReadOnlyList<string> files, IReadOnlyList<Frame> home)
{
if (files.Count == 0) return 0;
var held = HeldAtHome(home);
string? trash = null;
var trashed = 0;
foreach (var file in files)
{
try
{
var (sha, _) = Hash(file);
if (sha is not null && held.Contains(sha))
{
File.Delete(file);
continue;
}
trash ??= Path.Combine(project.Store.Root, TrashFolder,
project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture), WorkspaceProject.OriginalsFolder);
Directory.CreateDirectory(trash);
File.Move(file, Path.Combine(trash, Path.GetFileName(file)), overwrite: true);
trashed++;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{file} could not be removed", ex);
}
}
return trashed;
}
/// <summary>The original files in the project's folder of originals (never a part a copy writes, nor its staging folder).</summary>
private static List<string> Files(WorkspaceProject project)
{
if (!Directory.Exists(project.OriginalsDirectory)) return [];
return [.. Directory.EnumerateFiles(project.OriginalsDirectory)
.Where(f => !f.EndsWith(".part", StringComparison.OrdinalIgnoreCase))
.Order(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>The SHA-256 (lower case) of the photos the home holds, flagged neither missing nor damaged.</summary>
private static HashSet<string> HeldAtHome(IReadOnlyList<Frame> home) =>
home.Where(f => !string.IsNullOrEmpty(f.Sha256) && (f.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0)
.Select(f => f.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
private static (string? Sha256, long Bytes) Hash(string file)
{
try
{
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan);
return (Convert.ToHexStringLower(SHA256.HashData(stream)), stream.Length);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{file} could not be read", ex);
return (null, 0);
}
}
private static void TryDeleteFolder(string folder)
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{folder} could not be removed", ex);
}
}
}
@@ -1,24 +1,286 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model; using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Archiving; using Chronos.Data.Archiving;
using Chronos.Data.Jobs; using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
namespace Chronos.Data.Workspaces; namespace Chronos.Data.Workspaces;
/// <summary> /// <summary>
/// <see cref="JobKind.WorkspaceRender"/> (phase 5c, <see cref="WorkspaceJobs.Render"/>): a workspace project rendered on this /// <see cref="JobKind.WorkspaceRender"/> (phase 5c, <see cref="WorkspaceJobs.Render"/>): a workspace project rendered on this
/// PC from the originals its media hold, as <see cref="Processing.Jobs.RenderJobHandler"/> renders an archive's sequence, /// PC from the originals its media hold, as <see cref="Processing.Jobs.RenderJobHandler"/> renders an archive's sequence,
/// into the project's <c>exports/</c> (each output written as <c>.part</c>, then renamed), each output hashed and recorded in /// into the project's <c>exports/</c> (each output written by the encoder under a hidden temporary name, then renamed), each
/// the project's ledger (<see cref="WorkspaceRenders"/>, its id <c>RenderJobHandler.RenderId(jobId, index)</c>), then a /// output hashed and recorded in the project's ledger (<see cref="WorkspaceRenders"/>, its id
/// <see cref="JobKind.WorkspaceSend"/> queued with the new ids. Media without an original for every placed frame are refused. /// <c>RenderJobHandler.RenderId(jobId, index)</c>), then a <see cref="JobKind.WorkspaceSend"/> queued with the new ids.
/// Media without an original for every placed frame are refused. The project's lease is held while the inputs are read
/// and while each ledger entry is written, not for the whole render: the editor keeps saving its working state meanwhile.
/// The settings rendered are the ones the job embeds (the editor's portable settings), else the version it names from
/// <c>versions/</c>; the version is recorded only when <c>versions/</c> holds it with the content hash of what rendered.
/// Checkpoint: the entries recorded and the output being written; a resumed job removes that output's leftovers (never one
/// the ledger names) and renders only what is not recorded yet.
/// </summary> /// </summary>
internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveService archives, WorkspaceJobOptions options) : IJobHandler internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveService archives, WorkspaceJobOptions options) : IJobHandler
{ {
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
public JobKind Kind => JobKind.WorkspaceRender; public JobKind Kind => JobKind.WorkspaceRender;
public Task RunAsync(JobContext context) public async Task RunAsync(JobContext context)
{ {
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
_ = (db, archives, options); // The index and the archive engine are not read: everything a local render needs is in the workspace project.
throw new NotImplementedException("Local renders of a workspace project come with phase 5c (P2)."); _ = (db, archives);
var cancellation = context.Cancellation;
var parameters = WorkspaceJobs.RenderParameters(context.Job) ?? throw new InvalidDataException(Loc.L("Errors.Workspace.JobParameters"));
var (render, export) = ProcessingJobs.ReadRender(parameters.RenderJson);
var store = new WorkspaceStore(parameters.WorkspaceRoot);
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
var inputs = await ReadInputsAsync(project, parameters, render, cancellation).ConfigureAwait(false);
var (sequence, frames, settings, versionId) = (inputs.Sequence, inputs.Frames, inputs.Settings, inputs.VersionId);
// A local render's outputs stay in the project's exports, from where they are sent home.
var projectSettings = ProjectStore.Parse(settings) with { Export = export with { Folder = null } };
var settingsJson = projectSettings.ToJson();
var settingsHash = ProjectContent.Hash(inputs.Portable);
var exports = project.ExportsDirectory;
Directory.CreateDirectory(exports);
using var names = new OutputNames();
var all = RenderJobHandler.Targets(projectSettings.Export, render.PresetName);
var resume = RenderCheckpoint.Parse(context.Checkpoint);
var done = resume.Done.ToList();
var ledger = project.ReadRenders();
for (var i = 0; i < all.Count; i++)
{
if (!done.Contains(i) && ledger.Find(RenderJobHandler.RenderId(context.Job.Id, i)) is not null) done.Add(i);
}
if (resume is { Pending: { } pending, PendingOutput: { } chosen } && !done.Contains(pending) && Inside(exports, chosen) && names.TryReserve(chosen))
{
Discard(chosen, keepOutput: ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), chosen)));
names.Release(chosen);
}
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
var recorded = new List<Guid>();
if (targets.Count > 0)
{
string? writing = null;
IReadOnlyList<TargetOutcome> outcomes;
try
{
await using var renderer = new SequenceRender(frames, projectSettings, inputs.Analysis, options.Processing, originals: true, companions: null);
outcomes = await renderer.RenderAllAsync(
targets,
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup),
name => taken(name) || ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), name)))),
(index, path) =>
{
writing = path;
return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total);
},
async (index, target, result) =>
{
// The output is complete: recorded even if the job is being cancelled, so it is never orphaned.
var id = RenderJobHandler.RenderId(context.Job.Id, index);
var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false);
using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
{
ledger = project.ReadRenders().With(entry);
project.WriteRenders(ledger);
}
done.Add(index);
recorded.Add(id);
writing = null;
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
if (renderer.StandIns.Count > 0)
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", renderer.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
// What the encoder was writing goes; every output recorded stays, and a resumed job renders the rest.
if (writing is { } partial) Discard(partial, keepOutput: true);
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
throw;
}
var failed = outcomes.Where(o => o.Error is not null).ToList();
foreach (var outcome in failed) context.Log(Loc.L("Export.Log.Failed", outcome.Target.PresetName, outcome.Error));
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
if (failed.Count > 0)
throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
}
}
/// <summary>What the render reads, taken under the project's lease so the media, the versions and the project file agree.</summary>
private sealed record Inputs(Sequence Sequence, SequenceFrames Frames, string Settings, string Portable, Guid? VersionId, DeepAnalysisReport? Analysis);
/// <summary>
/// The sequence over the workspace's originals, the settings to render (placed on its frames) and the version they are,
/// read under the project's lease.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The project is gone (<c>Errors.Workspace.RenderProject</c>), holds no originals (<c>Errors.Workspace.OriginalsMissing</c>),
/// lacks the original of a frame the render places (<c>Errors.Workspace.RenderNoOriginals</c>, with their number), or the
/// version the job names is not in <c>versions/</c> (<c>Errors.Workspace.RenderVersion</c>).
/// </exception>
private static async Task<Inputs> ReadInputsAsync(WorkspaceProject project, WorkspaceRenderParameters parameters, Protocol.RenderJobParameters render,
CancellationToken cancellationToken)
{
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(project.BundlePath)) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
var bundle = project.ReadBundle();
var workspace = bundle.Workspace!;
var media = project.ReadMedia();
if (media is not { HoldsOriginals: true })
throw new InvalidOperationException(Loc.L(workspace.Home.IsArchive ? "Errors.Workspace.OriginalsMissing" : "Errors.Workspace.OriginalsMissing.Server"));
var versions = project.Versions();
var named = parameters.ProjectVersionId ?? render.ProjectVersionId;
var version = named is { } id ? versions.FirstOrDefault(v => v.Id == id) : null;
string portable;
if (render.SettingsJson is { Length: > 0 } embedded) portable = embedded;
else if (named is not null) portable = version?.SettingsJson ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderVersion"));
else portable = versions.Count > 0 ? versions[^1].SettingsJson : ProjectContent.ToPortable(bundle.Project, media.Photos);
// Recorded only for the settings it holds (a version is never named for settings it did not render).
Guid? versionId = version is not null && ProjectContent.Verifies(portable, version.ContentHash) ? version.Id : null;
var settings = portable.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase) ? Place(portable, media.Photos) : portable;
var placed = ProjectStore.Parse(settings);
var excluded = placed.ExcludedFrames.ToHashSet();
var lacking = media.Frames.Count(f => f.Original is null && !excluded.Contains(f.Index) && (f.Flags & SequenceFrames.NotRendered) == 0);
if (lacking > 0) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderNoOriginals", lacking));
var frames = media.ToOriginalFrames();
var files = media.Frames.Select(f => f.Original is { } original ? project.MediaFile(original) : null).ToList();
var sequence = SequenceOf(bundle, media, frames);
return new Inputs(sequence, new SequenceFrames(sequence, frames, files), settings, portable, versionId, Analysis(project, frames.Count));
}
}
/// <summary>The home's sequence as the project file and the media name it (the workspace keeps no index row of it).</summary>
private static Sequence SequenceOf(ProjectBundle bundle, WorkspaceMedia media, IReadOnlyList<Frame> frames)
{
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
var home = bundle.Workspace!.Home;
return new Sequence
{
Id = home.SequenceId,
ArchiveId = bundle.Archive.Id,
Title = bundle.Sequence.Title,
Folder = bundle.Sequence.Folder,
FrameCount = frames.Count,
FirstCapture = times.Count > 0 ? times[0] : null,
LastCapture = times.Count > 0 ? times[^1] : null,
FramesVersion = media.FramesVersion,
Origin = home.IsArchive ? SequenceOrigin.Local : SequenceOrigin.Server,
};
}
/// <summary>The deep report the copy brought from the home, when it describes these frames; null otherwise.</summary>
private static DeepAnalysisReport? Analysis(WorkspaceProject project, int frameCount)
{
if (!File.Exists(project.AnalysisPath)) return null;
try
{
var report = DeepAnalysisReport.Load(project.AnalysisPath);
return report.FrameCount == frameCount ? report : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("workspace", $"{project.AnalysisPath} cannot be read", ex);
return null;
}
}
/// <summary>Portable settings placed on the media's frames; others as they are.</summary>
private static string Place(string portable, FramePhotos photos)
{
try
{
return ProjectContent.Place(portable, photos);
}
catch (JsonException)
{
// Not a project: reading it says so.
return portable;
}
}
/// <summary>The ledger entry of a finished output: hashed as it is on the disk now.</summary>
private static async Task<WorkspaceRenderEntry> EntryAsync(WorkspaceProject project, Guid jobId, Guid renderId, ExportTarget target, RenderResult result,
Guid? versionId, string settingsHash)
{
var sha = await HashAsync(result.OutputPath).ConfigureAwait(false);
var file = Path.GetRelativePath(project.ExportsDirectory, result.OutputPath).Replace('\\', '/');
return new WorkspaceRenderEntry(renderId, jobId, file, sha, result.Bytes, target.PresetName, result.Codec.ToString(), result.Width, result.Height,
result.FrameRate.Value, result.DurationSeconds, project.ProjectId, versionId, settingsHash, DateTimeOffset.UtcNow);
}
/// <summary>
/// The SHA-256 of an output: of the file, or, for an image sequence's folder, of its files' relative paths and SHA-256 in
/// order (a send checks the folder the same way).
/// </summary>
internal static async Task<string> HashAsync(string output)
{
if (File.Exists(output)) return await ContentHash.Sha256Async(output, cancellationToken: CancellationToken.None).ConfigureAwait(false);
var listing = new StringBuilder();
foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
{
var sha = await ContentHash.Sha256Async(file, cancellationToken: CancellationToken.None).ConfigureAwait(false);
listing.Append(Path.GetRelativePath(output, file).Replace('\\', '/')).Append(' ').Append(sha).Append('\n');
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(listing.ToString())));
}
/// <summary>Queues the send home of the renders this run recorded, whatever stops the job now (they are done).</summary>
private static async Task QueueSendAsync(JobContext context, WorkspaceRenderParameters parameters, Sequence sequence, List<Guid> recorded)
{
if (recorded.Count == 0) return;
var send = WorkspaceJobs.Send(sequence.Id, sequence.DisplayTitle, parameters.WorkspaceRoot, parameters.ProjectId, [.. recorded],
parameters.Server, context.Job.Priority);
await context.EnqueueFollowUpAsync(send.Kind, send.Targets, send.Label, send.ParametersJson, send.Priority, CancellationToken.None).ConfigureAwait(false);
}
private static bool Inside(string folder, string path)
{
var relative = Path.GetRelativePath(folder, path);
return !relative.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(relative);
}
private static bool SamePath(string a, string b) =>
string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or folder,
/// and an output completed but never recorded (it renders again under the same name) unless <paramref name="keepOutput"/>.
/// </summary>
private static void Discard(string output, bool keepOutput)
{
var parent = Path.GetDirectoryName(output);
if (parent is null || !Directory.Exists(parent)) return;
var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").ToList();
if (!keepOutput) leftovers.Add(output);
foreach (var leftover in leftovers)
{
try
{
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
else if (File.Exists(leftover)) File.Delete(leftover);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("workspace", $"{leftover} could not be removed", ex);
}
}
} }
} }
@@ -137,7 +137,7 @@ public sealed class ServerHomeTests(TestContext context)
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds() public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{ {
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4); await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false }); var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed); var server = new FakeServer(bed);
Connect(host, server); Connect(host, server);
var projectId = await CheckoutAsync(bed, host); var projectId = await CheckoutAsync(bed, host);
@@ -266,7 +266,8 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.False(facts.TooLittleSpace, "the test drive has room for four small proxies"); Assert.False(facts.TooLittleSpace, "the test drive has room for four small proxies");
var dialog = new OpenInWorkspaceDialogViewModel("Synthetic", await host.HomeProjectsAsync(bed.SequenceId), _ => { }, copy: facts); var dialog = new OpenInWorkspaceDialogViewModel("Synthetic", await host.HomeProjectsAsync(bed.SequenceId), _ => { }, copy: facts);
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], dialog.CopyFacts.Select(f => f.Label)); Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], dialog.CopyFacts.Select(f => f.Label));
Assert.Equal(Formatting.Bytes(facts.OriginalsBytes!.Value), dialog.CopyFacts[2].Value);
Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value); Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value);
Assert.False(dialog.IsShortOfSpace); Assert.False(dialog.IsShortOfSpace);
@@ -0,0 +1,128 @@
using System.Globalization;
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Export;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: a workspace project that holds its originals renders on this PC (<see cref="JobKind.WorkspaceRender"/>),
/// also when its home is a server, and Settings › Workspace › Version on render saves a changed project as a version first.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceLocalRenderTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
static WorkspaceLocalRenderTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheOriginalsRenderOnThisPcEvenForAServerHome()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(source is { IsServerHome: true, RendersLocally: true, UnsentRenders: 0 });
var requests = session.RenderRequests(Mjpeg);
var request = requests.Single();
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
// Queued on this PC's engine and listed beside the server's jobs (the render itself is the Data tests': this bed decodes nothing).
var jobId = await source.SubmitAsync(request, bed.Ct);
var queued = Assert.NotNull(await bed.Db.Jobs.GetAsync(jobId, bed.Ct));
Assert.Equal(JobKind.WorkspaceRender, queued.Kind);
Assert.Contains(await source.ListJobsAsync(bed.Ct), j => j.Id == jobId);
await WorkspaceTestBed.UntilAsync(() => bed.Db.Jobs.GetAsync(jobId).GetAwaiter().GetResult()?.State is JobState.Done or JobState.Failed, "the render ends");
// A render the ledger holds and the home has not taken: listed with the others, not sent.
var output = Path.Combine(folder.ExportsDirectory, "clip-MJPEG.avi");
Directory.CreateDirectory(folder.ExportsDirectory);
await File.WriteAllBytesAsync(output, [1, 2, 3], bed.Ct);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), jobId, "clip-MJPEG.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
projectId, null, null, DateTimeOffset.UtcNow);
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry));
var reread = await source.LoadAsync(bed.Ct);
Assert.Equal(1, source.UnsentRenders);
Assert.Equal((entry.RenderId, output), (reread.Renders[0].Id, reread.Renders[0].OutputPath));
}
}
[Test]
public async Task VersionOnRenderSavesAChangedProjectFirst()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
Assert.True(settings is { WorkspaceVersionOnRender: true, WorkspaceAutoSync: true }, "on by default");
var host = bed.Host(settings);
var projectId = await bed.CheckoutAsync(host);
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
var folder = host.Store.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before, folder.Versions().Count);
// Changed: saved as a version noted Render and sent (Sync automatically); the render names it.
Assert.True(session.SetHero(2));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
var saved = folder.Versions()[^1];
Assert.Equal((before + 1, Loc.L("Editor.Workspace.RenderNote")), (folder.Versions().Count, saved.Note));
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(folder.ReadBundle().Workspace!.Base!.Number)), ui.Toasts[^1].Title);
var (render, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal(folder.ReadBundle().Workspace!.Base!.VersionId, render.ProjectVersionId);
// Off: the project renders as it is, no version saved.
settings.WorkspaceVersionOnRender = false;
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before + 1, folder.Versions().Count);
Assert.Empty(ui.Confirmations);
}
}
}
@@ -0,0 +1,185 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Tests.Editor;
using Chronos.App.Tests.Windows;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: "Open in workspace" offers the originals (Settings › Workspace › Media first, the proxies when the
/// drive has no room), and Settings › Workspace › Open project picks the project a sequence with several opens.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
[Category("workspace")]
public sealed class WorkspaceOpenPolicyTests(TestContext context)
{
private static readonly SequenceProject Main = new() { Id = Guid.CreateVersion7(), SequenceId = Guid.CreateVersion7(), Name = ProjectService.MainName, IsMain = true };
[Test]
public void TheOpenDialogStartsWithTheMediaOfTheSettingsWhenTheyFit()
{
UiLanguage.Apply("en");
var room = new WorkspaceCopyFacts(10_000_000, 100_000_000_000, 4_000_000_000);
using var proxies = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room);
Assert.True(proxies is { IsProxies: true, IsOriginals: false, CanCopyOriginals: true });
Assert.Equal(BundleMedia.Proxies, proxies.Media);
Assert.Contains(proxies.CopyFacts, f => f.Label == Loc.L("Editor.OpenWorkspace.Originals"));
using var originals = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room, defaultMedia: BundleMedia.Originals);
Assert.True(originals is { IsOriginals: true, IsProxies: false, IsShortOfSpace: false });
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady"), originals.OriginalsToolTip);
originals.OpenCommand.Execute(null);
Assert.Equal(new OpenChoice(Main.Id, null, BundleMedia.Originals), originals.Choice.Result);
// The drive has room for the proxies, not the originals: they are offered disabled, why in the tooltip.
var tight = new WorkspaceCopyFacts(10_000_000, WorkspaceJobs.CopySpaceReserve + 20_000_000, 4_000_000_000);
using var refused = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: tight, defaultMedia: BundleMedia.Originals);
Assert.True(refused is { IsProxies: true, CanCopyOriginals: false, IsShortOfSpace: false });
refused.IsOriginals = true;
Assert.False(refused.IsOriginals, "never chosen without room");
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals"), refused.OriginalsToolTip);
refused.OpenCommand.Execute(null);
Assert.Equal(BundleMedia.Proxies, refused.Choice.Result!.Media);
// Not measured (a server out of reach): offered, the copy measures again before it writes.
using var unmeasured = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, server: true);
Assert.True(unmeasured.CanCopyOriginals);
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady.Server"), unmeasured.OriginalsToolTip);
unmeasured.IsOriginals = true;
Assert.Equal(BundleMedia.Originals, unmeasured.Media);
}
[Test]
public Task TheOriginalsAreCopiedAndTheOpenProjectFollowsTheSettings() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-open-policy");
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
UiLanguage.Apply("en");
var settings = new AppSettings
{
Language = "en", FirstRunCompleted = true, CheckForUpdates = false, WorkspaceDefaultMedia = BundleMedia.Originals,
};
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var section = shell.Sequence;
// The originals, as the settings say: copied beside the proxies, and the project's menu offers Proxies only.
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.True(ask.IsOriginals, "the settings' media first");
ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens once its media are copied");
var mainId = section.OpenProjectId!.Value;
var menu = Assert.NotNull(section.Editor!.Project);
Assert.True(menu.HoldsOriginals);
var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
// A second project here, opened last.
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
var checkout = await services.Workspace.CheckoutAsync(sequenceId, vertical, null);
await WorkspaceTestBed.UntilAsync(() => services.Database!.Jobs.GetAsync(checkout.Copy.Id).GetAwaiter().GetResult()?.State == JobState.Done, "its media are copied");
services.Workspace.Remember(sequenceId, vertical);
// Last used: Vertical.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.LastUsed;
Assert.Equal(vertical, await OpenAsync(shell, sequenceId));
// Main, whichever opened last.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Main;
Assert.Equal(mainId, await OpenAsync(shell, sequenceId));
// Ask: the projects here are listed, the one opened last first; closing it opens nothing.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Ask;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks");
var which = (OpenProjectDialogViewModel)section.Dialog!;
Assert.Equal(2, which.Projects.Count);
Assert.Equal(mainId, which.SelectedProject!.Entry.ProjectId);
which.CloseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is null, "closed without a choice");
Assert.Null(section.Editor);
shell.KeepSequence(null);
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks again");
which = (OpenProjectDialogViewModel)section.Dialog!;
which.SelectedProject = which.Projects.Single(p => p.Entry.ProjectId == vertical);
which.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project chosen opens");
Assert.Equal(vertical, section.OpenProjectId);
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// <summary>Opens the sequence in Edit as the settings say and returns the project that opened, closed again.</summary>
private static async Task<Guid> OpenAsync(ShellViewModel shell, Guid sequenceId)
{
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens");
Assert.Null(section.Dialog);
var opened = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
return opened;
}
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
private async Task<Guid> SequenceAsync(AppServices services, string root)
{
var archives = services.Archives!;
var archive = await archives.CreateAsync(root, "Test");
var sequence = EditorFixture.Sequence(6);
var folder = Path.Combine(root, "Synthetic");
Directory.CreateDirectory(folder);
for (var i = 0; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
}
/// <summary>Dialogs that pick nothing and decline every confirmation.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}
@@ -53,7 +53,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time"); await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!; var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.Equal(Loc.L("Editor.Project.Main"), ask.SelectedProject!.Label, "Main, made from the sequence's settings, is offered first"); Assert.Equal(Loc.L("Editor.Project.Main"), ask.SelectedProject!.Label, "Main, made from the sequence's settings, is offered first");
Assert.True(ask.IsProxies && !ask.CanCopyOriginals, "proxies; the originals come later"); Assert.True(ask.IsProxies && ask.CanCopyOriginals, "the proxies first, the originals offered (Settings › Workspace › Media)");
Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar"); Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar");
ask.OpenCommand.Execute(null); ask.OpenCommand.Execute(null);
Assert.Null(section.Dialog); Assert.Null(section.Dialog);
@@ -143,7 +143,8 @@ public sealed class WorkspaceSectionTests(TestContext context)
shell.OpenSequence(sequenceId); shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time"); await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!; var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], ask.CopyFacts.Select(f => f.Label), "the copy's facts reach the dialog"); Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], ask.CopyFacts.Select(f => f.Label),
"the copy's facts reach the dialog");
ask.OpenCommand.Execute(null); ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said"); await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said");
var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")); var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed"));
@@ -0,0 +1,187 @@
using System.Security.Cryptography;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Core.Model;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>A workspace project's originals (phase 5c): their copy from the archive, checked and resumable, and "Proxies only".</summary>
[Category("workspace")]
public abstract class WorkspaceOriginalsTests(TestContext context) : DatabaseTest(context)
{
private async Task<WorkspaceFixture> FixtureAsync(int frames = 3, Func<ArchiveServiceOptions, ArchiveServiceOptions>? configure = null)
{
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true), configure: configure));
var fx = Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
// The archive's own proxies: the copy takes those, so a damaged original never changes a proxy.
await archive.Service.Images.BuildProxiesAsync(archive.Archive, fx.Sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
return fx;
}
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
private static async Task<(WorkspaceStore Store, WorkspaceProject Project)> CheckoutOriginalsAsync(WorkspaceFixture fx)
{
var (store, sync) = fx.Workspace();
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
var project = await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
return (store, project);
}
private string Source(WorkspaceFixture fx, int index) => fx.Archive.Paths.FromRelative(fx.Frames.Single(f => f.Index == index).RelativePath);
[Test]
public async Task ACopyOfTheOriginalsHoldsEachPhotoCheckedAgainstTheHome()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
Assert.Equal(fx.Frames.Sum(f => f.Size), await WorkspaceOriginals.ArchiveOriginalsBytesAsync(fx.Db, fx.Archive.Service, fx.Sequence.Id, cancellationToken: fx.Ct));
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
Assert.True(media.HoldsOriginals);
Assert.Equal(BundleMedia.Originals, project.ReadBundle().Workspace!.Media.Kind);
foreach (var frame in fx.Frames)
{
var entry = media.Frames.Single(f => f.Id == frame.Id);
Assert.NotNull(entry.File);
var original = project.MediaFile(Assert.NotNull(entry.Original));
Assert.Equal(frame.Sha256!.ToLowerInvariant(), entry.OriginalSha256);
Assert.Equal(entry.OriginalSha256, Sha(original));
Assert.Equal(frame.Size, entry.OriginalBytes);
Assert.Equal(WorkspaceProject.OriginalName(frame.Id, frame.Sha256, Path.GetExtension(frame.RelativePath)), entry.Original);
}
Assert.Empty(Directory.GetFiles(project.OriginalsDirectory, "*.part"));
Assert.Equal(0L, await WorkspaceOriginals.ArchiveOriginalsBytesAsync(fx.Db, fx.Archive.Service, fx.Sequence.Id, project, fx.Ct));
// The frames read by a local render are the originals.
Assert.SequenceEqual(media.Frames.Select(f => f.Original), media.ToOriginalFrames().Select(f => f.RelativePath));
}
[Test]
public async Task AnOriginalThatIsGoneOrDamagedAtTheHomeLeavesItsFrameProxied()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
File.Delete(Source(fx, 0));
var damaged = Source(fx, 1);
var bytes = File.ReadAllBytes(damaged);
bytes[^3] ^= 0x5A;
File.WriteAllBytes(damaged, bytes);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
Assert.True(media.HoldsOriginals);
var gone = media.Frames.Single(f => f.Index == 0);
var mismatched = media.Frames.Single(f => f.Index == 1);
Assert.Null(gone.Original);
Assert.Null(mismatched.Original);
Assert.NotNull(mismatched.File);
Assert.NotNull(media.Frames.Single(f => f.Index == 2).Original);
Assert.Equal(1, Directory.GetFiles(project.OriginalsDirectory).Length);
Assert.True(media.ToOriginalFrames().Count(f => (f.Flags & FrameFlags.Missing) != 0) == 2, "a render counts the two frames without an original");
}
[Test]
public async Task ACopyStoppedAmongTheOriginalsResumesWithWhatItHad()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
var kept = project.MediaFile(media.Frames[0].Original!);
var written = File.GetLastWriteTimeUtc(kept);
var lost = project.MediaFile(media.Frames[2].Original!);
File.Delete(lost);
File.WriteAllBytes(Path.Combine(project.OriginalsDirectory, media.Frames[2].Id.ToString("N") + ".part"), [1, 2, 3]);
var row = (await fx.Db.Sequences.GetAsync(fx.Sequence.Id))!;
await fx.CopyAsync(store, project.ProjectId, checkpoint: $"originals:2:{row.FramesVersion}:{row.Folder}", media: BundleMedia.Originals);
Assert.Equal(written, File.GetLastWriteTimeUtc(kept));
Assert.Equal(media.Frames[2].OriginalSha256, Sha(lost));
Assert.Empty(Directory.GetFiles(project.OriginalsDirectory, "*.part"));
Assert.Equal(3, project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
}
[Test]
public async Task TheOriginalsAreNotCopiedWhenTheDriveLacksTheirRoom()
{
long? free = null;
var fx = await FixtureAsync(configure: options => options with { FreeSpace = _ => free });
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId);
free = WorkspaceJobs.CopySpaceReserve + fx.Frames.Sum(f => f.Size) - 1;
var job = await fx.CopyAsync(store, project.ProjectId, JobState.Failed, media: BundleMedia.Originals);
var parts = Loc.L("Errors.Workspace.DiskFull", "\u0001").Split('\u0001');
Assert.True(job.Error!.StartsWith(parts[0], StringComparison.Ordinal), job.Error);
Assert.False(project.ReadMedia()!.HoldsOriginals);
Assert.False(Directory.Exists(project.OriginalsDirectory) && Directory.EnumerateFiles(project.OriginalsDirectory).Any());
}
[Test]
public async Task ProxiesOnlyDeletesWhatTheHomeHoldsAndTrashesTheRest()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
// The home lost frame 1's photo: its only copy is the workspace's, which goes to the trash, not away.
var lostAtHome = project.MediaFile(media.Frames[1].Original!);
var home = await fx.Home.FramesAsync(fx.Ct);
home = home with { Frames = [.. home.Frames.Select(f => f.Index == 1 ? f with { Flags = f.Flags | FrameFlags.Missing } : f)] };
var plan = WorkspaceOriginals.PlanProxiesOnly(project, home);
Assert.Equal((2, 1), (plan.Originals, plan.ToTrash));
Assert.Equal(fx.Frames.Where(f => f.Index != 1).Sum(f => f.Size), plan.Bytes);
var trashed = await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, TimeSpan.FromSeconds(10), fx.Ct);
Assert.Equal(1, trashed);
Assert.False(Directory.Exists(project.OriginalsDirectory));
var after = project.ReadMedia()!;
Assert.False(after.HoldsOriginals);
Assert.True(after.Frames.All(f => f.Original is null && f.File is not null));
Assert.Equal(BundleMedia.Proxies, project.ReadBundle().Workspace!.Media.Kind);
var inTrash = Directory.GetFiles(Path.Combine(store.Root, WorkspaceOriginals.TrashFolder), Path.GetFileName(lostAtHome), SearchOption.AllDirectories);
Assert.Equal(1, inTrash.Length);
Assert.Equal(media.Frames[1].OriginalSha256, Sha(inTrash[0]));
}
[Test]
public async Task ProxiesOnlyRefusesAPlanTheFilesChangedSince()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var home = await fx.Home.FramesAsync(fx.Ct);
var plan = WorkspaceOriginals.PlanProxiesOnly(project, home);
Assert.Equal((3, 0), (plan.Originals, plan.ToTrash));
var changed = project.MediaFile(project.ReadMedia()!.Frames[0].Original!);
File.AppendAllText(changed, "x");
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, TimeSpan.FromSeconds(10), fx.Ct));
Assert.Equal(Loc.L("Errors.Workspace.MediaChanged"), error.Message);
Assert.True(project.ReadMedia()!.HoldsOriginals);
Assert.Equal(3, Directory.GetFiles(project.OriginalsDirectory).Length);
// Planned again, the changed file is no photo the home holds: it goes to the trash.
var again = WorkspaceOriginals.PlanProxiesOnly(project, home);
Assert.Equal((2, 1), (again.Originals, again.ToTrash));
Assert.Equal(1, await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, again, home, TimeSpan.FromSeconds(10), fx.Ct));
}
}
public sealed class SqliteWorkspaceOriginalsTests(TestContext context) : WorkspaceOriginalsTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresWorkspaceOriginalsTests(TestContext context) : WorkspaceOriginalsTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,189 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Processing;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>
/// A workspace project rendered on this PC from the originals its media hold (phase 5c, <see cref="JobKind.WorkspaceRender"/>):
/// into its exports, recorded in its ledger and sent home after; refused without the originals; a cancel leaves nothing half written.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceRenderTests(TestContext context)
{
private const int Frames = 24;
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
private sealed record Bed(ProcessingFixture Fx, Sequence Sequence, WorkspaceStore Store, WorkspaceProject Project, JobEngine Engine) : IAsyncDisposable
{
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Fx.DisposeAsync();
}
}
/// <summary>A sequence of the archive, Main checked out into a workspace with <paramref name="media"/> copied, and an engine running every handler.</summary>
private async Task<Bed> BedAsync(string media = BundleMedia.Originals, Action<ProcessingFixture, Sequence>? beforeCopy = null)
{
var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var engine = new JobEngine(fx.Db,
[
.. fx.Archive.Service.CreateJobHandlers(), .. fx.Processing.CreateJobHandlers(),
.. WorkspaceJobs.CreateHandlers(fx.Db, fx.Archive.Service, null, new WorkspaceJobOptions(fx.Processing.Options, () => false)),
],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(fx.Ct);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("render-ws"), "workspace"));
var sync = new WorkspaceSync(store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, sequence.Id);
var main = await fx.Archive.Service.Projects.MainAsync(sequence.Id, fx.Ct);
var project = await sync.CheckoutAsync(home, main.Id, media, fx.Ct);
beforeCopy?.Invoke(fx, sequence);
var copy = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, store.Root, main.Id, media), cancellationToken: fx.Ct);
await fx.WaitForAsync(copy.Id, JobState.Done);
return new Bed(fx, sequence, store, project, engine);
}
private static ArchiveJobRequest RenderRequest(Bed bed, Guid? versionId = null)
{
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson!;
return WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, versionId, json);
}
[Test]
public async Task ARenderFromTheOriginalsIsWrittenToExportsRecordedAndSentAfter()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var output = Path.Combine(bed.Project.ExportsDirectory, "clip-MJPEG.avi");
Assert.FileExists(output);
Assert.Empty(Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory, ".*"));
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal(RenderJobHandler.RenderId(job.Id, 0), entry.RenderId);
Assert.Equal((job.Id, "clip-MJPEG.avi", new FileInfo(output).Length, WorkspaceRenderEntry.Pending, bed.Project.ProjectId),
(entry.JobId, entry.File, entry.Size, entry.State, entry.ProjectId));
Assert.Equal(await Chronos.Core.Archiving.ContentHash.Sha256Async(output), entry.Sha256);
Assert.Equal(("Mjpeg", 96, 64), (entry.Codec, entry.Width, entry.Height));
Assert.Null(entry.ProjectVersionId, "the working state the job embeds is no version this workspace holds");
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct));
// The send home follows with the new render.
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
var sent = Assert.NotNull(WorkspaceJobs.SendParameters(send));
Assert.SequenceEqual([entry.RenderId], sent.RenderIds);
Assert.Equal((bed.Project.ProjectId, bed.Store.Root), (sent.ProjectId, sent.WorkspaceRoot));
// The same render of the archive's own sequence: the same pictures, at the same size and length.
var archive = await bed.Engine.EnqueueAsync(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64), cancellationToken: fx.Ct);
await fx.WaitForAsync(archive.Id, JobState.Done);
var row = (await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct)).Single();
Assert.Equal((row.Width, row.Height, row.Fps, row.DurationSeconds), (entry.Width, entry.Height, entry.Fps, entry.DurationSeconds));
// Again: another name, the first output and its entry kept.
var again = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.WaitForAsync(again.Id, JobState.Done);
var entries = bed.Project.ReadRenders().Entries;
Assert.Equal(2, entries.Count);
Assert.True(entries[1].File != entries[0].File, entries[1].File);
Assert.Equal(entry, entries[0]);
}
[Test]
public async Task AVersionHeldInTheWorkspaceIsRecordedWithTheRender()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var (_, sync) = (bed.Store, new WorkspaceSync(bed.Store, "test"));
var session = await sync.OpenAsync(bed.Project.ProjectId, fx.Ct);
await sync.SaveAsync(bed.Project.ProjectId, session.Working with { ExcludedFrames = [2] }, fx.Ct);
var version = Assert.NotNull(await sync.CommitAsync(bed.Project.ProjectId, "Render", cancellationToken: fx.Ct));
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!;
// The job names the version alone: the settings come from versions/.
var stripped = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
stripped.Remove("settingsJson");
var job = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, version.Id, stripped.ToJsonString()), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal(version.Id, entry.ProjectVersionId);
Assert.Equal(version.ContentHash, entry.SettingsHash);
// A version the workspace does not hold: refused, saying so.
var unknown = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, Guid.CreateVersion7(), stripped.ToJsonString()),
cancellationToken: fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.RenderVersion"), (await fx.WaitForAsync(unknown.Id, JobState.Failed)).Error);
}
[Test]
public async Task WithoutTheOriginalsTheRenderIsRefusedSayingHowManyLack()
{
await using var bed = await BedAsync(beforeCopy: (fx, sequence) =>
{
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(3)));
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(7)));
});
var fx = bed.Fx;
Assert.Equal(Frames - 2, bed.Project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.RenderNoOriginals", 2), (await fx.WaitForAsync(job.Id, JobState.Failed)).Error);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False(Directory.Exists(bed.Project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory).Any());
}
[Test]
public async Task ProxiesAloneAreRefused()
{
await using var bed = await BedAsync(BundleMedia.Proxies);
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: bed.Fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.OriginalsMissing"), (await bed.Fx.WaitForAsync(job.Id, JobState.Failed)).Error);
}
[Test]
public async Task ACancelledRenderLeavesNoPartialOutput()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
fx.Decoder.HoldPurpose = DecodePurpose.Render;
fx.Decoder.Hold = Path.GetFileName(bed.Project.ReadMedia()!.Frames[12].Original);
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await bed.Engine.CancelAsync(job.Id, fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Cancelled);
var until = DateTime.UtcNow.AddSeconds(30);
while (bed.Engine.RunningJobIds.Contains(job.Id))
{
Assert.True(DateTime.UtcNow < until, "the render did not stop");
await Task.Delay(20, fx.Ct);
}
var left = Directory.Exists(bed.Project.ExportsDirectory) ? Directory.GetFileSystemEntries(bed.Project.ExportsDirectory) : [];
Assert.Empty(left);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False((await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Any(j => j.Kind == JobKind.WorkspaceSend), "nothing to send");
}
}
@@ -192,14 +192,17 @@ public abstract class WorkspaceTests(TestContext context) : DatabaseTest(context
} }
[Test] [Test]
public async Task CopyingTheOriginalsIsRefusedForNowWithItsReason() public async Task CopyingTheOriginalsCopiesTheProxiesToo()
{ {
var fx = await FixtureAsync(2); var fx = await FixtureAsync(2);
var (store, sync) = fx.Workspace(); var (store, sync) = fx.Workspace();
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct); var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct); var project = await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
var job = await fx.CopyAsync(store, main.Id, JobState.Failed, media: BundleMedia.Originals); await fx.CopyAsync(store, main.Id, media: BundleMedia.Originals);
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), job.Error); var media = project.ReadMedia()!;
Assert.True(media.HoldsOriginals);
Assert.True(media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.Equal(media.Frames.Count, (await sync.OpenAsync(main.Id, fx.Ct)).Media!.Frames.Count);
} }
[Test] [Test]
@@ -197,14 +197,45 @@ public sealed class ServerWorkspaceTests(TestContext context)
// Another server's job for this project, or this server's for another sequence: refused, nothing downloaded. // Another server's job for this project, or this server's for another sequence: refused, nothing downloaded.
var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id)); var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error); Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error);
var originals = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), (await a.WaitAsync(originals.Id, JobState.Failed)).Error);
a.Connected = false; a.Connected = false;
var signedOut = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id)); var signedOut = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), (await a.WaitAsync(signedOut.Id, JobState.Failed)).Error); Assert.Equal(Loc.L("Errors.Sync.NotConnected"), (await a.WaitAsync(signedOut.Id, JobState.Failed)).Error);
Assert.Null(a.Store.Find(main.Id)!.ReadMedia()); Assert.Null(a.Store.Find(main.Id)!.ReadMedia());
} }
[Test]
public async Task TheOriginalsAreDownloadedCheckedAndKeptBesideTheProxies()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 3);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var main = (await home.ListAsync(context.Cancellation)).Single();
var project = await a.Sync.CheckoutAsync(home, main.Id, BundleMedia.Originals, context.Cancellation);
var library = Listing(a.Archive.RootPath);
var job = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
job = await a.WaitAsync(job.Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceOriginalsDownloaded", Title, 3, 0, 0), job.LogTail!);
var media = Assert.NotNull(project.ReadMedia());
Assert.True(media.HoldsOriginals);
Assert.Equal(BundleMedia.Originals, project.ReadBundle().Workspace!.Media.Kind);
var manifest = await a.Client.GetManifestAsync(sid, context.Cancellation);
foreach (var (frame, entry) in manifest.Frames.OrderBy(f => f.Index).Zip(media.Frames))
{
Assert.Equal(frame.Sha256.ToLowerInvariant(), entry.OriginalSha256);
Assert.Equal(entry.OriginalSha256, Sha(project.MediaFile(Assert.NotNull(entry.Original))));
Assert.NotNull(entry.File);
}
Assert.False(Directory.Exists(Path.Combine(project.OriginalsDirectory, ".staging")));
Assert.SequenceEqual(library, Listing(a.Archive.RootPath), "this PC's library is as it was");
// Again: every original held is kept, hashed again.
job = await a.WaitAsync((await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals))).Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceOriginalsDownloaded", Title, 0, 3, 0), job.LogTail!);
}
[Test] [Test]
public async Task AProjectDeletedOnTheServerIsGoneAndItsCopyStays() public async Task AProjectDeletedOnTheServerIsGoneAndItsCopyStays()
{ {