feat(workspace): copy originals into the workspace and choose the project Edit opens

Phase 5c P1. A workspace copy of kind "originals" now copies each frame's
original beside its proxy, so a later local render has full-quality input:
streamed into a .part file, hashed as written, checked against the home's
SHA-256, renamed and read back. Archive and server homes both work, a stopped
copy resumes (originals: checkpoint), and the space check counts the
originals. A frame whose original is gone, damaged or refused keeps its proxy
and the job says how many; the copy does not fail. Stale originals are
deleted only when the home holds the same SHA-256, otherwise moved to the
workspace's trash.

Proxies only... plans first (every original hashed against the home's
frames), asks for an explicit confirmation, rewrites the media to proxies
before it touches a file, refuses a plan that changed since, and trashes what
the home no longer holds instead of deleting it.

Edit: Open in workspace offers Originals (the settings' default, disabled
when the drive lacks room) with the originals' size for archive and server
homes; Settings > Workspace > Open project picks Last used, Main or asks
which; each open is recorded for the clean-up. The project menu gains Copy
originals... and Proxies only..., refused while changes are unsaved or jobs
of the sequence run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 15:43:42 +01:00
1 parent 2e1c67f531
commit 0c51d11080
14 files changed
+1397 -70

No files matched your search

@@ -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()
{ {
@@ -644,6 +669,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 +936,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 +988,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);
}
}
}
@@ -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,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;
}
@@ -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()
{ {