feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings (#18)
CI / Build and test (push) Successful in 9m26s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 8s
Release / Build, test and publish (push) Successful in 14m31s
CI / PostgreSQL 16 integration (push) Successful in 9m53s
CI / PostgreSQL 17 integration (push) Successful in 9m22s
CI / Docker image (push) Successful in 44s
Release / Server image (push) Successful in 1m36s

Originals in the workspace, local render and send home with provenance, the workspace clean-up, size limit and trash, moving the workspace folder, and the complete Settings › Workspace page (owner review 2, R8, phase 5c). One adversarial review round (35 findings, 32 fixed), a copy-cancel race fixed, 184 strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #18.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 20:03:52 +01:00
1 parent 81c303f484
commit db389a54f2
364 files changed
+17417 -595

No files matched your search

@@ -45,6 +45,11 @@ public interface IWorkspaceUi
/// <summary>The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.</summary>
Task SequenceChangedAsync(Guid sequenceId);
/// <summary>Shows the Jobs screen (a toast's Jobs action); nothing where there is none.</summary>
void ShowJobs()
{
}
}
/// <summary>
@@ -81,6 +86,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private bool _isSyncing;
private bool _homeFramesChanged;
private Guid _copyJob;
private bool _copyingOriginals;
private bool _changingMedia;
private bool _disposed;
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
@@ -110,6 +117,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
CopyOriginalsCommand = new AsyncRelayCommand(CopyOriginalsAsync, () => !HoldsOriginals && !IsMediaBusy);
ProxiesOnlyCommand = new AsyncRelayCommand(ProxiesOnlyAsync, () => HoldsOriginals && !IsMediaBusy);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
host.HomeChanged += OnHomeChanged;
@@ -193,6 +202,31 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
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; }
/// <summary>What Copy originals… does, or why it is disabled (the media busy, or the originals here already).</summary>
public string CopyOriginalsToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
: HoldsOriginals ? Loc.L("Tooltips.Editor.Project.HasOriginals")
: WorkspaceText.ForHome("Tooltips.Editor.Project.CopyOriginals", IsServerHome);
/// <summary>What Proxies only… does, or why it is disabled (the media busy, or proxies only here already).</summary>
public string ProxiesOnlyToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
: !HoldsOriginals ? Loc.L("Tooltips.Editor.Project.ProxiesAlready")
: WorkspaceText.ForHome("Tooltips.Editor.Project.ProxiesOnly", IsServerHome);
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
public async Task RefreshAsync()
{
@@ -227,12 +261,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary>
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive
/// renders as it is: true.
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive,
/// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version
/// on render, a changed project is saved as a version first (<see cref="SaveForRenderAsync"/>).
/// </summary>
public async Task<bool> ReadyToRenderAsync()
{
if (!IsServerHome) return true;
if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false;
// Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is.
if (!IsServerHome || _source.RendersLocally) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
@@ -271,6 +308,45 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
/// <summary>
/// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version
/// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach,
/// it waits here). False when it could not be saved, or the sync met a conflict to settle first.
/// </summary>
private async Task<bool> SaveForRenderAsync()
{
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (!status.Modified || !CanSaveVersion) return true;
WorkspaceSaveResult result;
try
{
result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote"));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
return false;
}
if (_disposed) return false;
Apply(result.Status);
if (result.Synced is { } taken) await TakeAsync(taken);
if (result.Version is { } version)
{
// The home numbers what it stores: the last one sent is this version.
var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number;
_ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name);
}
if (result.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
if (result.Status.Conflict is not { } conflict) return true;
AskConflict(conflict);
return false;
}
/// <summary>
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
@@ -644,6 +720,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"), _ui.ShowJobs);
}
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>
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
private async Task StoreEditAsync()
@@ -787,10 +987,13 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
if (_disposed || job.Id != _copyJob) return;
_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);
try
{
if (job.State == JobState.Done) await _session.ReloadAsync();
if (job.State == JobState.Done && originals) NotifyOriginalsCopied();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -836,6 +1039,10 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
OnPropertyChanged(nameof(RemoveCopyToolTip));
OnPropertyChanged(nameof(MediaChangedToolTip));
OnPropertyChanged(nameof(UpdateMediaToolTip));
OnPropertyChanged(nameof(HoldsOriginals));
OnPropertyChanged(nameof(IsMediaBusy));
OnPropertyChanged(nameof(CopyOriginalsToolTip));
OnPropertyChanged(nameof(ProxiesOnlyToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
+116 -10
View File
@@ -47,8 +47,9 @@ public static class ProjectNames
/// <summary>
/// "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
/// new one with its name, and the media to copy (proxies; the originals come in phase 5c). Open queues the copy; the
/// sequence opens once it is done.
/// new one with its name, and the media to copy: the proxies, or (phase 5c) the originals besides, to render on this PC,
/// 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>
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
@@ -56,6 +57,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private readonly bool _server;
private ProjectOption? _selected;
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="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.
/// </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,
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)
{
_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.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")),
.. 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 = string.Equals(defaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase) && CanCopyOriginals;
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
_selected = Projects.FirstOrDefault(p => p.IsAvailable);
_isNew = !HasProjects;
@@ -97,8 +105,8 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// <summary>"Copy size" and "Free space", under the media.</summary>
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>
public bool IsShortOfSpace => Copy?.TooLittleSpace == true;
/// <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?.TooLittleSpaceFor(Media) == true;
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);
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
/// <summary>The proxies alone: light to edit, renders run where the originals are.</summary>
public bool IsProxies
{
get => !_isOriginals;
set
{
if (value) IsOriginals = false;
}
}
/// <summary>The originals: offered from phase 5c, to render on this PC.</summary>
public bool CanCopyOriginals => false;
/// <summary>The proxies and the originals (phase 5c): renders run on this PC.</summary>
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; }
@@ -169,7 +203,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private void Open()
{
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();
}
@@ -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>
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
@@ -551,6 +648,15 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
new DialogFact(Loc.L("Editor.RemoveCopy.Size"), Formatting.Bytes(plan.Bytes)),
new DialogFact(Loc.L("Editor.RemoveCopy.Unsent"), Formatting.Count(plan.Unsent)),
new DialogFact(Loc.L("Editor.RemoveCopy.Changed"), Loc.L(plan.Modified ? "Editor.RemoveCopy.Yes" : "Editor.RemoveCopy.No")),
// Phase 5c: renders made here not sent yet, and originals the home lost (they go to the trash): shown only when there are some.
.. plan.UnsentRenders > 0
? [new DialogFact(Loc.L("Editor.RemoveCopy.UnsentRenders"), Formatting.Count(plan.UnsentRenders),
Reason: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.UnsentRenders", server))]
: Array.Empty<DialogFact>(),
.. plan.LastOriginals > 0
? [new DialogFact(Loc.L("Editor.RemoveCopy.LastOriginals"), Formatting.Count(plan.LastOriginals),
Reason: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.LastOriginals", server))]
: Array.Empty<DialogFact>(),
];
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline && !plan.Gone);
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone && !plan.Damaged);
@@ -54,10 +54,10 @@
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" />
<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" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="{Binding IsOriginals}"
ToolTip="{Binding OriginalsToolTip}" ToolTipService.ShowOnDisabled="True" />
</StackPanel>
</Grid>
<!-- What the copy writes and the room the workspace's drive has for it. -->
@@ -88,6 +88,30 @@
</DataTemplate>
<!-- 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}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
@@ -4,6 +4,8 @@ using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
@@ -12,7 +14,8 @@ namespace Chronos.App.Workspace;
/// inside a library, where Edit cannot be used until one is chosen. The folder is picked, its plan shown and confirmed
/// (the projects the folder in use keeps, those the new one holds), a workspace project open in the editor closes (its
/// last edit stored first), and only then does the setting change. Nothing is moved or deleted: the projects of the
/// folder left stay there, listed again once it is chosen back. Moving a workspace with its projects comes in phase 5c.
/// folder left stay there, listed again once it is chosen back. Settings › Workspace › Move… (phase 5c) moves the folder
/// with its projects instead, after its plan, by a job; a move that stopped before it ended is offered again at start.
/// </summary>
public static class WorkspaceFolderChange
{
@@ -20,14 +23,8 @@ public static class WorkspaceFolderChange
public static async Task<bool> ChooseAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
var changed = await ChooseAsync(shell.Services.Workspace, shell.Services.Dialogs, async () =>
{
if (shell.Sequence.Editor?.Session.Source is not WorkspaceSequenceSource) return true;
if (!await shell.Sequence.ConfirmCloseAsync()) return false;
await shell.Sequence.CloseAsync();
shell.KeepSequence(null);
return true;
}, message => shell.Notify(Loc.L("Settings.Workspace.NotChanged"), message, isError: true));
var changed = await ChooseAsync(shell.Services.Workspace, shell.Services.Dialogs, () => CloseProjectAsync(shell),
message => shell.Notify(Loc.L("Settings.Workspace.NotChanged"), message, isError: true));
if (changed) shell.Notify(Loc.L("Settings.Workspace.Changed"), shell.Services.Workspace.Root);
return changed;
}
@@ -66,6 +63,139 @@ public static class WorkspaceFolderChange
}
}
/// <summary>
/// Settings › Workspace › Move… (phase 5c): the shell's flow over <see cref="MoveAsync(WorkspaceHost, IAppDialogs, Func{Task{bool}}, Action{string})"/>,
/// with its folder picker, confirmation, editor and toasts. True when the move was queued.
/// </summary>
public static async Task<bool> MoveAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
var host = shell.Services.Workspace;
var from = host.Root;
var queued = await MoveAsync(host, shell.Services.Dialogs, () => CloseProjectAsync(shell),
message => shell.Notify(Loc.L("Settings.Workspace.NotMoved"), message, isError: true));
if (queued) shell.Notify(Loc.L("Settings.Workspace.Moving"), from);
return queued;
}
/// <summary>
/// Picks the folder the workspace moves to through <paramref name="dialogs"/>, shows its plan
/// (<see cref="WorkspaceHost.PlanMoveAsync"/>) and asks for the user's word, lets <paramref name="closeProject"/> close a
/// workspace project open in the editor (false keeps everything as it is), then queues the move
/// (<see cref="WorkspaceHost.QueueMoveAsync"/>) of the plan read again once the project is closed (its last edit
/// stored), unless that one refuses. <paramref name="failed"/> hears why it was refused. True when it was queued.
/// </summary>
public static async Task<bool> MoveAsync(WorkspaceHost host, IAppDialogs dialogs, Func<Task<bool>> closeProject, Action<string> failed)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(dialogs);
ArgumentNullException.ThrowIfNull(closeProject);
ArgumentNullException.ThrowIfNull(failed);
if (host.IsMoving)
{
failed(Loc.L("Errors.Workspace.Moving"));
return false;
}
if (dialogs.PickFolder(Loc.L("Settings.Workspace.MoveTitle"), Directory.Exists(host.Root) ? Path.GetDirectoryName(host.Root) : null) is not { } folder)
return false;
try
{
var plan = await host.PlanMoveAsync(folder);
if (plan.Refusal is { } refused)
{
failed(refused);
return false;
}
if (!dialogs.Confirm(MoveRequest(plan))) return false;
if (!await closeProject()) return false;
// Closing stored the last edit: the job checks the plan of the workspace as it is now.
plan = await host.PlanMoveAsync(folder);
if (plan.Refusal is { } refusedNow)
{
failed(refusedNow);
return false;
}
await host.QueueMoveAsync(plan);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException or WorkspaceException)
{
Log.Warning("workspace", $"The workspace folder was not moved to {folder}", ex);
failed(ex is WorkspaceException ? ex.Message : Loc.L("Errors.Workspace.FolderUnusable", folder));
return false;
}
}
/// <summary>
/// At start: a move of the workspace folder that stopped before it ended (its journal in the folder in use, no move job
/// waiting) is said, with Resume, which queues it again to go on from its journal. A move job still waiting holds the
/// workspace until it ends.
/// </summary>
public static async Task NoticeUnfinishedMoveAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
var host = shell.Services.Workspace;
if (!host.IsAvailable) return;
try
{
if (await host.UnfinishedMoveAsync() is not { } journal) return;
shell.Notify(Loc.L("Settings.Workspace.MoveUnfinished"), Loc.L("Settings.Workspace.MoveUnfinishedMessage", journal.To, journal.From),
Loc.L("Settings.Workspace.ResumeMove"), Loc.L("Tooltips.Settings.Workspace.ResumeMove"), () => _ = ResumeAsync(shell, journal), isError: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("workspace", "An unfinished move of the workspace could not be looked for", ex);
}
}
/// <summary>
/// Settings › Workspace › Resume: the move that stopped before it ended (<see cref="WorkspaceHost.UnfinishedMoveAsync"/>)
/// queued again from its journal; nothing when there is none any more.
/// </summary>
public static async Task ResumeUnfinishedAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
try
{
if (await shell.Services.Workspace.UnfinishedMoveAsync() is { } journal) await ResumeAsync(shell, journal);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("workspace", "An unfinished move of the workspace could not be looked for", ex);
shell.Notify(Loc.L("Settings.Workspace.NotMoved"), ErrorText.For(ex), isError: true);
}
}
/// <summary>
/// The move's plan as a confirmation: where the projects go, how many and how big, the free bytes at the target, whether
/// folders are renamed or files copied and checked, and how many projects hold work not at their home (they move with it).
/// </summary>
public static ConfirmRequest MoveRequest(WorkspaceMovePlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var lines = new List<string>
{
Loc.L("Settings.Workspace.MovePlan.Projects", Formatting.Count(plan.Projects.Count)),
Loc.L("Settings.Workspace.MovePlan.Files", Formatting.Count(plan.Files)),
Loc.L("Settings.Workspace.MovePlan.Size", Formatting.Bytes(plan.Bytes)),
};
if (plan.Free is { } free) lines.Add(Loc.L("Settings.Workspace.MovePlan.Free", Formatting.Bytes(free)));
lines.Add(Loc.L(plan.SameVolume ? "Settings.Workspace.MovePlan.SameVolume" : "Settings.Workspace.MovePlan.OtherVolume"));
if (plan.Warnings > 0) lines.Add(Loc.L("Settings.Workspace.MovePlan.Unsent", Formatting.Count(plan.Warnings)));
return new ConfirmRequest
{
Heading = Loc.L("Settings.Workspace.MovePlan.Title"),
Message = Loc.L("Settings.Workspace.MovePlan.Message", plan.From, plan.To),
Detail = string.Join(Environment.NewLine, lines),
DetailToolTip = plan.Warnings > 0 ? Loc.L("Tooltips.Settings.Workspace.MovePlan.Unsent") : null,
IsDetailMonospaced = false,
SafeText = Loc.L("Archive.Dialog.Cancel"),
SafeToolTip = Loc.L("Tooltips.Settings.Workspace.MovePlan.Keep"),
ActionText = Loc.L("Settings.Workspace.MovePlan.Action"),
ActionToolTip = Loc.L("Tooltips.Settings.Workspace.MovePlan.Action"),
};
}
/// <summary>The plan as a confirmation: where Edit's projects come from now, and what stays where it is.</summary>
public static ConfirmRequest Request(WorkspaceFolderPlan plan)
{
@@ -83,4 +213,30 @@ public static class WorkspaceFolderChange
ActionToolTip = Loc.L("Tooltips.Settings.UseWorkspace"),
};
}
/// <summary>Queues again the move a journal records, the project open in the editor closed first.</summary>
private static async Task ResumeAsync(ShellViewModel shell, WorkspaceMoveJournal journal)
{
try
{
if (!await CloseProjectAsync(shell)) return;
await shell.Services.Workspace.ResumeMoveAsync(journal);
shell.Notify(Loc.L("Settings.Workspace.Moving"), journal.From);
}
catch (Exception ex) when (ex is IOException or WorkspaceException or DatabaseException)
{
Log.Warning("workspace", $"The move of the workspace to {journal.To} could not be queued again", ex);
shell.Notify(Loc.L("Settings.Workspace.NotMoved"), ex is WorkspaceException ? ex.Message : null, isError: true);
}
}
/// <summary>A workspace project open in the editor closes (its last edit stored first); false when the user kept it open.</summary>
private static async Task<bool> CloseProjectAsync(ShellViewModel shell)
{
if (shell.Sequence.Editor?.Session.Source is not WorkspaceSequenceSource) return true;
if (!await shell.Sequence.ConfirmCloseAsync()) return false;
await shell.Sequence.CloseAsync();
shell.KeepSequence(null);
return true;
}
}
@@ -0,0 +1,338 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>
/// What the workspace takes of its drive (Settings › Workspace, phase 5c): the projects' media (proxies and originals, which
/// the clean-up and the size limit may remove), the whole folder, and its trash (<see cref="WorkspaceHost.TrashFolder"/>).
/// </summary>
/// <param name="MediaBytes">The bytes of every project's <c>media/</c> folder.</param>
/// <param name="TotalBytes">The bytes of the whole workspace folder, its trash included.</param>
/// <param name="TrashBytes">The bytes of the workspace's trash.</param>
/// <param name="TrashItems">The entries of the workspace's trash (one per copy removed or originals set aside).</param>
public sealed record WorkspaceUsage(long MediaBytes, long TotalBytes, long TrashBytes, int TrashItems)
{
/// <summary>A workspace that holds nothing.</summary>
public static WorkspaceUsage None { get; } = new(0, 0, 0, 0);
}
/// <summary>One entry of the workspace's trash as Empty… lists it: its folder name, size, files and when it was put there.</summary>
public sealed record WorkspaceTrashItem(string Name, long Bytes, int Files, DateTimeOffset Trashed);
/// <summary>
/// The plan of Settings › Workspace › Trash › Empty… (phase 5c): every entry of the workspace's trash and their bytes, and a
/// fingerprint over their names, sizes and times. Emptying erases exactly these entries, and only while the fingerprint
/// still matches (the user types the number of entries to confirm); schedules and the size limit never empty the trash.
/// </summary>
public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList<WorkspaceTrashItem> Items, long Bytes, string Fingerprint)
{
/// <summary>Nothing to erase: Empty… is disabled.</summary>
public bool IsEmpty => Items.Count == 0;
}
/// <summary>What emptying the workspace's trash erased.</summary>
public sealed record WorkspaceTrashResult(int Items, long Bytes);
/// <summary>
/// The workspace's clean-up side (phase 5c, P4): its usage, the clean-up of media (<see cref="WorkspaceCleaner"/>: Settings ›
/// Workspace › Clean after and Size limit, run by the <c>workspace-cleanup</c> schedule and, for the size limit, after each
/// copy of media), the plan and emptying of its trash, and what a local copy's removal keeps of renders not sent and
/// originals the home lost.
/// </summary>
public sealed partial class WorkspaceHost
{
private readonly SemaphoreSlim _cleaning = new(1, 1);
/// <summary>
/// The workspace project open in Edit now (any thread may ask); null when none is. The clean-up never removes the media of
/// that one. Unset (as in a test without the shell), no project counts as open.
/// </summary>
public Func<Guid?>? OpenProject { get; set; }
/// <summary>What the workspace takes of its drive (<see cref="WorkspaceUsage"/>), measured off the UI thread; none while its folder is not made.</summary>
public Task<WorkspaceUsage> UsageAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
var root = Root;
if (!Directory.Exists(root)) return WorkspaceUsage.None;
var media = 0L;
foreach (var folder in Directory.EnumerateDirectories(root).Where(d => Guid.TryParseExact(Path.GetFileName(d), "N", out _)))
{
cancellationToken.ThrowIfCancellationRequested();
media += WorkspaceCleaner.Measure(Path.Combine(folder, WorkspaceProject.MediaFolder)).Bytes;
}
var trash = WorkspaceTrash.List(root, cancellationToken);
return new WorkspaceUsage(media, WorkspaceCleaner.Measure(root).Bytes, trash.Bytes, trash.Entries.Count);
}, cancellationToken);
/// <summary>The plan of emptying the workspace's trash (<see cref="WorkspaceTrashPlan"/>); nothing is erased.</summary>
public Task<WorkspaceTrashPlan> PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
var listing = WorkspaceTrash.List(Root, cancellationToken);
return new WorkspaceTrashPlan(listing.Folder, [.. listing.Entries.Select(e => new WorkspaceTrashItem(e.Name, e.Bytes, e.Files, e.Trashed))], listing.Bytes,
listing.Fingerprint);
}, cancellationToken);
/// <summary>
/// Erases the entries of <paramref name="plan"/> from the workspace's trash for good, after the user typed their number;
/// refused when the trash changed since the plan (<c>Errors.Workspace.TrashChanged</c>).
/// </summary>
/// <exception cref="WorkspaceException">The trash changed since the plan; nothing was erased.</exception>
/// <exception cref="IOException">An entry could not be erased (a file held open); the others were.</exception>
public Task<WorkspaceTrashResult> EmptyTrashAsync(WorkspaceTrashPlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
return Task.Run(() =>
{
EnsureNotMoving();
var listing = new WorkspaceTrashListing(plan.Folder, [.. plan.Items.Select(i => new WorkspaceTrashEntry(i.Name, i.Bytes, i.Files, i.Trashed))], plan.Bytes,
plan.Fingerprint);
try
{
var (items, bytes) = WorkspaceTrash.Empty(Root, listing, cancellationToken);
return new WorkspaceTrashResult(items, bytes);
}
catch (WorkspaceTrashChangedException ex)
{
Log.Info("workspace", $"The workspace's trash was not emptied: {ex.Message}");
throw new WorkspaceException(Loc.L("Errors.Workspace.TrashChanged"), ex);
}
}, cancellationToken);
}
/// <summary>
/// One run of the workspace's clean-up (<see cref="WorkspaceCleaner"/>): with <paramref name="cleanAfter"/>, Settings ›
/// Workspace › Clean after, then Size limit (the <c>workspace-clean</c> step of the schedule); without, the size limit
/// alone, never taking <paramref name="justCopied"/> (after a copy of its media). Null when the workspace cannot be
/// cleaned now (the index not open, the folder being moved); a folder not made yet has nothing to clean. One run at a time.
/// </summary>
public async Task<WorkspaceCleanReport?> CleanAsync(bool cleanAfter, Guid? justCopied = null, CancellationToken cancellationToken = default)
{
if (_db() is not { } db || IsMoving || !IsEnabled) return null;
var root = Root;
if (!Directory.Exists(root)) return WorkspaceCleanReport.Nothing;
var options = new WorkspaceCleanOptions
{
CleanAfterDays = cleanAfter ? Math.Max(0, _settings.WorkspaceCleanAfterDays) : 0,
SizeLimitBytes = Math.Max(0, _settings.WorkspaceSizeLimitGb) * (1L << 30),
Opened = OpenedSnapshot(),
IsOpen = id => OpenProject?.Invoke() == id,
JustCopied = justCopied,
};
if (options is { CleanAfterDays: 0, SizeLimitBytes: 0 }) return WorkspaceCleanReport.Nothing;
await _cleaning.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var cleaner = new WorkspaceCleaner(Sync, db, HomeOf) { LockWait = LockWait };
return await Task.Run(() => cleaner.CleanAsync(options, cancellationToken), cancellationToken).ConfigureAwait(false);
}
finally
{
_cleaning.Release();
}
}
/// <summary>
/// A job of the engine changed (any thread): once a copy of media into this workspace is done, the size limit runs, never
/// taking the project just copied. Nothing else follows from a job here.
/// </summary>
public void OnJobChanged(Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (job is not { Kind: JobKind.WorkspaceCopy, State: JobState.Done } || _settings.WorkspaceSizeLimitGb <= 0) return;
if (WorkspaceJobs.CopyParameters(job) is not { } copied
|| !string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(copied.WorkspaceRoot)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root)),
StringComparison.OrdinalIgnoreCase))
return;
_ = Task.Run(async () =>
{
try
{
if (await CleanAsync(cleanAfter: false, copied.ProjectId).ConfigureAwait(false) is { Cleaned.Count: > 0 } report)
Log.Info("workspace", $"Size limit after the copy of project {copied.ProjectId}: {report.Cleaned.Count} project(s) cleaned, {report.Freed} bytes freed");
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The size limit after the copy of project {copied.ProjectId} did not run", ex);
}
});
}
/// <summary>When each project was opened last, as Settings hold it now (written on the UI thread: copied until a copy reads whole).</summary>
private IReadOnlyDictionary<Guid, DateTimeOffset> OpenedSnapshot()
{
for (var attempt = 0; ; attempt++)
{
try
{
return new Dictionary<Guid, DateTimeOffset>(_settings.WorkspaceOpened);
}
catch (InvalidOperationException) when (attempt < 5)
{
// Written while it was copied: copied again.
}
}
}
/// <summary>
/// What a local copy's removal plan counts besides its versions (<see cref="WorkspaceRemovalPlan.UnsentRenders"/>,
/// <see cref="WorkspaceRemovalPlan.LastOriginals"/>): renders of its ledger not sent, and originals the home no longer
/// holds (all of them while the home cannot be asked: they go to the trash then, never deleted).
/// </summary>
private async Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
var unsent = WorkspaceCleaner.UnsentRenders(project);
var last = await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false);
return (unsent, last);
}
/// <summary>
/// A removal without Discard is refused while the project's ledger holds renders not sent: Send first queues their
/// sending home (unless one is queued or running already), and the copy goes once they are there.
/// </summary>
/// <exception cref="WorkspaceException">Renders wait to be sent.</exception>
private async Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(workspace);
if (WorkspaceCleaner.UnsentRenders(project) == 0) return;
try
{
await QueueRenderSendAsync(project, workspace, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or InvalidOperationException or IOException or InvalidDataException)
{
Log.Warning("workspace", $"The renders of project {project.ProjectId} could not be queued to be sent", ex);
}
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.UnsentRenders", !workspace.Home.IsArchive));
}
/// <summary>
/// Before a removed copy's media are deleted, under the project's lease: every file of its folder of originals, named by
/// the media index or not (an index that cannot be read names none), hashed now and deleted only when the home's frames,
/// read now, hold a photo of that SHA-256; every other one moved into <paramref name="aside"/> (the copy's trash entry),
/// never deleted, and every one when the home cannot be asked (<see cref="WorkspaceOriginals.ClearOriginals"/>).
/// </summary>
/// <returns>The originals that could be neither deleted nor moved: they stay in the folder of originals.</returns>
private async Task<int> ClearOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentException.ThrowIfNullOrEmpty(aside);
if (!WorkspaceCleaner.HoldsOriginalFiles(project)) return 0;
// The working state went into the entry first: the home is read from there.
BundleHome? home = null;
try
{
home = ProjectBundle.Load(Path.Combine(aside, WorkspaceProject.BundleFile)).Workspace?.Home;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"The home of removed project {project.ProjectId} is not known: every original it holds is kept ({ex.Message})");
}
var held = home is null ? null : await HomeFramesAsync(project, home, cancellationToken).ConfigureAwait(false);
var (deleted, trashed, _, left) = WorkspaceOriginals.ClearOriginals(project, held?.Frames, aside);
Log.Info("workspace", $"Originals of removed project {project.ProjectId}: {deleted} deleted (the home holds them), {trashed} kept in {aside}"
+ (left > 0 ? $", {left} left where they are (held open)" : string.Empty));
return left;
}
/// <summary>The frames of <paramref name="home"/> as it holds them now; null (logged) when it cannot be asked.</summary>
private async Task<HomeFrames?> HomeFramesAsync(WorkspaceProject project, BundleHome home, CancellationToken cancellationToken)
{
try
{
return HomeOf(home) is { } reached ? await reached.FramesAsync(cancellationToken).ConfigureAwait(false) : null;
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException or IOException or InvalidDataException)
{
// Not known: every original counts as the last one, and goes to the trash.
Log.Info("workspace", $"The home of project {project.ProjectId} could not be asked for its frames: {ex.Message}");
return null;
}
}
/// <summary>
/// What a removal plan counts of the originals that go to the trash rather than away: the files of the folder of
/// originals the media index does not name (every one when the index cannot be read), plus the frames whose recorded
/// original the home no longer holds as it is (every one while the home cannot be asked). The removal hashes each file
/// itself; this count is what the plan says, never what decides.
/// </summary>
private async Task<int> LastOriginalsOfAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
if (!WorkspaceCleaner.HoldsOriginalFiles(project)) return 0;
var files = Directory.EnumerateFiles(project.OriginalsDirectory)
.Where(f => !f.EndsWith(".part", StringComparison.OrdinalIgnoreCase)).Select(Path.GetFileName).OfType<string>().ToList();
WorkspaceMedia? media;
try
{
media = project.ReadMedia();
}
catch (InvalidDataException ex)
{
Log.Info("workspace", $"The media index of project {project.ProjectId} cannot be read: every original counts as one to keep ({ex.Message})");
return files.Count;
}
var named = media?.Frames.Where(f => f.Original is not null).Select(f => Path.GetFileName(f.Original!)).ToHashSet(StringComparer.OrdinalIgnoreCase) ?? [];
var unnamed = files.Count(f => !named.Contains(f));
if (media is null || named.Count == 0) return unnamed;
HomeFrames? held = null;
try
{
held = await HomeFramesAsync(project, project.ReadBundle().Workspace!.Home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"The home of project {project.ProjectId} is not known: {ex.Message}");
}
return unnamed + WorkspaceCleaner.LastOriginals(media, held).Count(f => files.Contains(Path.GetFileName(f.Original!), StringComparer.OrdinalIgnoreCase));
}
/// <summary>
/// Edit › Export › Send again: queues the sending home of every render of the project not sent yet
/// (<see cref="JobKind.WorkspaceSend"/>), unless one is queued, running or paused already.
/// </summary>
/// <returns>True when a send is queued or waits already; false when nothing waits to be sent.</returns>
/// <exception cref="WorkspaceException">The workspace is being moved, or the index or the engine is not open.</exception>
public Task<bool> SendRendersAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
if (_engine() is null || _db() is null) throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var project = Existing(projectId);
if (WorkspaceCleaner.UnsentRenders(project) == 0) return false;
await QueueRenderSendAsync(project, project.ReadBundle().Workspace!, cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
/// <summary>A send of the project's renders is queued, running or paused (Send again waits for it).</summary>
public async Task<bool> RenderSendPendingAsync(Guid projectId, Guid sequenceId, CancellationToken cancellationToken = default)
{
if (_db() is not { } db) return false;
foreach (var pending in await db.Jobs.ListPendingAsync(JobKind.WorkspaceSend, sequenceId, cancellationToken).ConfigureAwait(false))
{
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == projectId) return true;
}
return false;
}
/// <summary>Queues the sending of the project's renders not sent yet (<see cref="JobKind.WorkspaceSend"/>), unless one is queued or running.</summary>
private async Task QueueRenderSendAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
{
if (_engine() is not { } engine || _db() is not { } db) return;
foreach (var pending in await db.Jobs.ListPendingAsync(JobKind.WorkspaceSend, workspace.Home.SequenceId, cancellationToken).ConfigureAwait(false))
{
if (WorkspaceJobs.SendParameters(pending)?.ProjectId == project.ProjectId) return;
}
var title = project.ReadBundle().Sequence.Title ?? string.Empty;
var job = await engine.EnqueueAsync(WorkspaceJobs.Send(workspace.Home.SequenceId, title, Store.Root, project.ProjectId, [], workspace.Home.Server),
cancellationToken: cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"The renders of project {project.ProjectId} not sent yet are queued to be sent (job {job.Id})");
}
}
@@ -0,0 +1,129 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>
/// The workspace's media (phase 5c, P1): what a copy writes (proxies, and the originals besides), copying the originals of a
/// project, and going back to proxies only.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <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>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var root = Root;
return Task.Run(async () =>
{
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
var originals = await WorkspaceOriginals.ArchiveOriginalsBytesAsync(db, archives, sequenceId, cancellationToken: cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free, originals);
}, 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;
}
}
}
@@ -0,0 +1,288 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>A project of the workspace as the plan of a move lists it: its size, and work not at its home yet (a warning, never a refusal).</summary>
/// <param name="Unsent">Versions or renders wait to be sent to its home.</param>
/// <param name="Modified">Changes not saved as a version.</param>
public sealed record WorkspaceMoveProject(Guid ProjectId, string Name, int Files, long Bytes, bool Unsent, bool Modified);
/// <summary>
/// The plan of Settings › Workspace › Move… (phase 5c): the workspace folder <see cref="From"/> moved with its projects to
/// <see cref="To"/>: the projects and their bytes, the free bytes at the target, whether both lie on one volume (folders
/// renamed) or not (files copied and hash-verified), why it is refused (null when it can go), and a fingerprint of what
/// the plan read, which the move job checks again.
/// </summary>
/// <param name="Free">The free bytes of the target's drive; null when they cannot be measured.</param>
/// <param name="Refusal">
/// Why the move cannot go, one localized sentence: the target is the folder itself or inside it
/// (<c>Errors.Workspace.MoveSameFolder</c>), already holds a workspace or a project of the same id
/// (<c>Errors.Workspace.MoveTargetNotEmpty</c>), lies inside a library (<c>Errors.Workspace.InsideLibraryFolder</c>), lacks
/// the room (<c>Errors.Workspace.MoveNoRoom</c>), or a workspace job is pending or running (<c>Errors.Workspace.JobsRunning</c>);
/// null when it can go.
/// </param>
public sealed record WorkspaceMovePlan(string From, string To, IReadOnlyList<WorkspaceMoveProject> Projects, int Files, long Bytes, long? Free, bool SameVolume,
string? Refusal, string Fingerprint)
{
/// <summary>Nothing refuses the move.</summary>
public bool CanMove => Refusal is null;
/// <summary>Projects with work not at their home: the move keeps it, the plan says so.</summary>
public int Warnings => Projects.Count(p => p.Unsent || p.Modified);
}
/// <summary>
/// Moving the workspace folder with its projects (phase 5c, P6): the plan, the <see cref="JobKind.WorkspaceMove"/> that
/// carries it out, and the workspace that follows the folder once every file is verified there. While a move is queued,
/// running or paused, and while the folder in use holds a move's journal (a move under way, or one stopped before it
/// ended), the workspace is refused for checkouts, copies, saves, syncs, opens and another folder
/// (<see cref="EnsureNotMoving"/>).
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>The kinds of job that write into the workspace folder: none may wait or run when a move starts.</summary>
private static readonly JobKind[] WorkspaceJobKinds = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove];
/// <summary>The thread the host was made on (the UI's): the settings are written there when a move ends.</summary>
private readonly SynchronizationContext? _moveContext = SynchronizationContext.Current;
/// <summary>The move job queued from here (or found waiting at start), until it ends; empty when there is none.</summary>
private Guid _moveJob;
/// <summary>The engine whose job changes the host follows, to see a move end.</summary>
private JobEngine? _followed;
/// <summary>
/// A move of the workspace folder is queued, running or paused, or the folder in use holds the journal of one that has
/// not ended: syncs, saves and opens wait for it.
/// </summary>
public bool IsMoving
{
get
{
lock (_gate)
{
if (_moveJob != Guid.Empty) return true;
}
return WorkspaceMover.HasJournal(Root);
}
}
/// <summary>
/// A move of the workspace folder followed here ended, however it ended (any thread): the folder in use may have changed,
/// and the workspace is no longer held for it (Settings › Workspace shows the folder and what it takes again).
/// </summary>
public event Action? MoveEnded;
/// <summary>A move job followed here waits, runs or is paused (no disk is read).</summary>
public bool IsMoveQueued
{
get
{
lock (_gate) return _moveJob != Guid.Empty;
}
}
/// <summary>
/// A move stopped before it ended: the folder in use holds its journal and no move job waits, runs or is paused; or a
/// move switched to the folder in use and left part of the folder it came from (its journal there names what is left
/// to clear). Null when there is none (a move under way is no move to take up). A move job waiting at start is followed
/// from now on, so the workspace waits for it (<see cref="IsMoving"/>).
/// </summary>
public Task<WorkspaceMoveJournal?> UnfinishedMoveAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (_db() is not { } db) return null;
foreach (var state in new[] { JobState.Running, JobState.Queued, JobState.Paused })
{
if ((await db.Jobs.ListAsync(state, JobKind.WorkspaceMove, 1, cancellationToken: cancellationToken).ConfigureAwait(false)).Items is [var pending, ..])
{
Follow(pending.Id);
return null;
}
}
if (WorkspaceMover.HasJournal(Root)) return WorkspaceMover.ReadJournal(Root);
// The folder in use is a move's target: the folder it left may hold what could not be cleared after the switch.
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root));
foreach (var state in new[] { JobState.Done, JobState.Failed, JobState.Cancelled })
{
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.WorkspaceMove, 5, cancellationToken: cancellationToken).ConfigureAwait(false)).Items)
{
if (WorkspaceJobs.MoveParameters(job) is not { From.Length: > 0 } moved || !WorkspaceMover.HasJournal(moved.From)) continue;
if (WorkspaceMover.ReadJournal(moved.From) is { Stage: WorkspaceMoveStage.Switched } left
&& string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(left.To)), root, StringComparison.OrdinalIgnoreCase))
return left;
}
}
return null;
}, cancellationToken);
/// <summary>
/// The plan of moving the workspace folder to <paramref name="to"/> (<see cref="WorkspaceMovePlan"/>); nothing is
/// written. Each project is read here, never at its home: a move keeps whatever is not sent yet, the plan only says so.
/// </summary>
/// <exception cref="IOException">The workspace folder cannot be read.</exception>
public Task<WorkspaceMovePlan> PlanMoveAsync(string to, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(to);
var root = Root;
var free = _archives()?.FreeSpace;
return Task.Run(async () =>
{
var target = Path.GetFullPath(to);
var survey = new WorkspaceMover(root, target) { FreeSpace = free }.Survey();
var projects = new List<WorkspaceMoveProject>();
foreach (var folder in survey.Projects.Where(p => p.IsProject))
{
cancellationToken.ThrowIfCancellationRequested();
projects.Add(await MoveProjectAsync(folder, cancellationToken).ConfigureAwait(false));
}
var refusal = survey.RefusalText;
if (refusal is null && await InsideALibraryAsync(survey.To, cancellationToken).ConfigureAwait(false))
refusal = Loc.L("Errors.Workspace.InsideLibraryFolder", survey.To);
if (refusal is null && (IsMoving || WorkspaceMover.HasJournal(survey.From))) refusal = Loc.L("Errors.Workspace.Moving");
if (refusal is null && _db() is { } db && await db.Jobs.HasPendingAsync(WorkspaceJobKinds, cancellationToken: cancellationToken).ConfigureAwait(false))
refusal = Loc.L("Errors.Workspace.JobsRunning");
return new WorkspaceMovePlan(survey.From, survey.To, projects, survey.Files, survey.Bytes, survey.Free, survey.SameVolume, refusal, survey.Fingerprint);
}, cancellationToken);
}
/// <summary>
/// Queues the <see cref="JobKind.WorkspaceMove"/> of a plan the user confirmed: from now until it ends the workspace is
/// refused for writes and opens (<see cref="IsMoving"/>).
/// </summary>
/// <exception cref="WorkspaceException">The plan refuses the move, or a move is under way already.</exception>
public async Task<Job> QueueMoveAsync(WorkspaceMovePlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.Refusal is { } refusal) throw new WorkspaceException(refusal);
EnsureNotMoving();
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(plan.From, plan.To, plan.Fingerprint), cancellationToken: cancellationToken).ConfigureAwait(false);
Follow(job.Id);
Log.Info("workspace", $"Move {job.Id} of the workspace {plan.From} to {plan.To} queued ({plan.Projects.Count} project(s), {plan.Bytes} bytes)");
return job;
}
/// <summary>
/// Queues again the move a journal records (<see cref="UnfinishedMoveAsync"/>): it goes on from the journal, nothing
/// verified is copied twice.
/// </summary>
/// <exception cref="WorkspaceException">The index or the engine is not open.</exception>
public async Task<Job> ResumeMoveAsync(WorkspaceMoveJournal journal, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(journal);
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(journal.From, journal.To, journal.Fingerprint), cancellationToken: cancellationToken).ConfigureAwait(false);
Follow(job.Id);
Log.Info("workspace", $"Move {job.Id} of the workspace {journal.From} to {journal.To} queued again from its journal");
return job;
}
/// <summary>
/// Told by the move job once every file of the workspace is verified at <paramref name="to"/>
/// (<c>WorkspaceJobOptions.Moved</c>, any thread): on the thread the host was made on, Settings › Workspace names the new
/// folder (none when it is the default) and the workspace opens there. A workspace that is no longer in
/// <paramref name="from"/> (another folder chosen meanwhile) keeps its folder.
/// </summary>
public Task MovedAsync(string from, string to)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
if (_moveContext is not { } context) return Task.Run(() => FollowFolder(from, to));
if (SynchronizationContext.Current == context)
{
FollowFolder(from, to);
return Task.CompletedTask;
}
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
context.Post(_ =>
{
try
{
FollowFolder(from, to);
done.TrySetResult();
}
catch (Exception ex)
{
done.TrySetException(ex);
}
}, null);
return done.Task;
}
/// <summary>The settings name the folder a move verified everything in.</summary>
private void FollowFolder(string from, string to)
{
var target = Full(to);
if (!string.Equals(Full(Root), Full(from), StringComparison.OrdinalIgnoreCase) && !string.Equals(Full(Root), target, StringComparison.OrdinalIgnoreCase))
{
Log.Warning("workspace", $"The workspace moved from {from} to {to}, but {Root} is in use now: it stays so");
return;
}
_settings.WorkspaceFolder = string.Equals(target, Full(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : target;
_savePreferences();
lock (_gate) _open = null;
Log.Info("workspace", $"The workspace folder is now {target}, moved from {from}");
static string Full(string folder) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
}
/// <summary>Refuses an operation that writes into the workspace while its folder is being moved.</summary>
/// <exception cref="WorkspaceException">A move is queued or running (<c>Errors.Workspace.Moving</c>).</exception>
private void EnsureNotMoving()
{
if (IsMoving) throw new WorkspaceException(Loc.L("Errors.Workspace.Moving"));
}
/// <summary>Holds the workspace while move job <paramref name="jobId"/> waits, runs or is paused; lets go once it ends, however it ends.</summary>
private void Follow(Guid jobId)
{
var engine = _engine();
lock (_gate)
{
_moveJob = jobId;
if (engine is null || ReferenceEquals(engine, _followed)) return;
if (_followed is { } before) before.JobChanged -= OnMoveJobChanged;
_followed = engine;
engine.JobChanged += OnMoveJobChanged;
}
}
private void OnMoveJobChanged(Job job)
{
if (job.Kind != JobKind.WorkspaceMove || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
lock (_gate)
{
if (_moveJob != job.Id) return;
_moveJob = Guid.Empty;
}
MoveEnded?.Invoke();
}
/// <summary>A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).</summary>
private async Task<WorkspaceMoveProject> MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken)
{
var project = Store.Project(folder.ProjectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
// What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home.
if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false);
try
{
var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
var renders = WorkspaceCleaner.UnsentRenders(project);
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
status.Modified && !status.ReadOnly);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"Where project {folder.ProjectId} stands could not be read for the move's plan: {ex.Message}");
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, true, false);
}
}
}
@@ -0,0 +1,9 @@
namespace Chronos.App.Workspace;
/// <summary>
/// The workspace's local renders (phase 5c, P2): rendering a project from the originals it holds on this PC, and sending its
/// renders home.
/// </summary>
public sealed partial class WorkspaceHost
{
}
+89 -30
View File
@@ -70,8 +70,17 @@ public sealed record WorkspaceFolderPlan(string Current, string Folder, int Proj
}
/// <summary>What "Open in workspace" shows of the copy it queues: its bytes (as the copy reckons them) and the free bytes of the workspace's drive.</summary>
public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
/// <param name="Bytes">What the copy of the proxies writes.</param>
/// <param name="OriginalsBytes">What the copy of the originals writes besides (phase 5c); null when not known.</param>
public sealed record WorkspaceCopyFacts(long Bytes, long? Free, long? OriginalsBytes = null)
{
/// <summary>
/// The drive lacks room for the copy of <paramref name="media"/> (<see cref="BundleMedia.Originals"/>: the proxies and the
/// originals) and the reserve the copy keeps free.
/// </summary>
public bool TooLittleSpaceFor(string media) =>
Free is { } free && free < Bytes + (media == BundleMedia.Originals ? OriginalsBytes ?? 0 : 0) + WorkspaceJobs.CopySpaceReserve;
/// <summary>The drive lacks the copy and the reserve the copy keeps: it would stop saying so.</summary>
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
}
@@ -113,8 +122,20 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// </summary>
public string? KnownName { get; init; }
/// <summary>
/// Local renders not at the home yet (phase 5c, the project's ledger): Send first sends them, Discard keeps them in the
/// workspace's trash with the rest of the work not sent.
/// </summary>
public int UnsentRenders { get; init; }
/// <summary>
/// Originals the workspace holds that the home no longer holds with the same SHA-256 (phase 5c): they go to the
/// workspace's trash, never deleted, when the copy is removed.
/// </summary>
public int LastOriginals { get; init; }
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict && !Damaged;
public bool IsSafe => Unsent == 0 && UnsentRenders == 0 && !Modified && !Conflict && !Damaged;
}
/// <summary>
@@ -129,7 +150,7 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// Workspace › Kept versions only after the home returned each, a page of its history at a time. A capture (sample data, no
/// engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
public sealed partial class WorkspaceHost
{
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
public const string TrashFolder = ".trash";
@@ -275,7 +296,9 @@ public sealed class WorkspaceHost
{
try
{
if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
// Nothing is written into a folder being moved: the next status read takes the name.
if (IsMoving) Log.Info("workspace", $"The new name of project {change.ProjectId} on {server} waits for the workspace's move");
else if (HomeOf(home) is { } reached) await Sync.FollowNameAsync(change.ProjectId, reached).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -308,13 +331,19 @@ public sealed class WorkspaceHost
return (IReadOnlyList<WorkspaceEntry>)entries;
}, cancellationToken);
/// <summary>The workspace projects of one sequence.</summary>
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
/// <summary>The workspace projects of one sequence, as Edit opens one.</summary>
/// <exception cref="WorkspaceException">The workspace folder is being moved (<c>Errors.Workspace.Moving</c>).</exception>
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
EnsureNotMoving();
return [.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
}
/// <summary>A workspace project by id (damaged or newer when this Chronos cannot read its working state); null when the workspace has none.</summary>
/// <exception cref="WorkspaceException">The workspace folder is being moved (<c>Errors.Workspace.Moving</c>).</exception>
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null;
}, cancellationToken);
@@ -342,11 +371,12 @@ public sealed class WorkspaceHost
/// Edit's workspace becomes <paramref name="folder"/> (made, with its manifest, when it is new): Settings › Workspace ›
/// Folder names it from now on (none when it is the default). The projects of the folder left stay there, untouched.
/// </summary>
/// <exception cref="WorkspaceException">The folder lies inside a library (<see cref="WorkspaceException.FolderRefused"/>).</exception>
/// <exception cref="WorkspaceException">The folder lies inside a library (<see cref="WorkspaceException.FolderRefused"/>), or the workspace is being moved.</exception>
/// <exception cref="IOException">The folder cannot be made or read.</exception>
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
public async Task UseFolderAsync(string folder, CancellationToken cancellationToken = default)
{
EnsureNotMoving();
var plan = await PlanFolderAsync(folder, cancellationToken).ConfigureAwait(false);
if (plan.IsSame) return;
if (plan.InsideLibrary) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryFolder", plan.Folder)) { FolderRefused = true };
@@ -358,20 +388,6 @@ public sealed class WorkspaceHost
Log.Info("workspace", $"The workspace folder is now {plan.Folder} ({plan.ProjectsLeft} project(s) stay in {plan.Current})");
}
/// <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>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var root = Root;
return Task.Run(async () =>
{
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free);
}, cancellationToken);
}
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
@@ -388,6 +404,16 @@ public sealed class WorkspaceHost
_savePreferences();
}
/// <summary>
/// Records that Edit opened <paramref name="projectId"/> at <paramref name="at"/> (now when null): the clean-up's Clean
/// after goes by it (phase 5c, <see cref="AppSettings.WorkspaceOpened"/>). Call it on the UI thread, which writes the settings.
/// </summary>
public void RecordOpened(Guid projectId, DateTimeOffset? at = null)
{
_settings.WorkspaceOpened[projectId] = at ?? DateTimeOffset.UtcNow;
_savePreferences();
}
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
@@ -426,6 +452,7 @@ public sealed class WorkspaceHost
var sequenceId = home.SequenceId;
var checkout = await Task.Run(async () =>
{
EnsureNotMoving();
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false))
throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root)) { FolderRefused = true };
@@ -461,6 +488,7 @@ public sealed class WorkspaceHost
/// </summary>
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
@@ -516,6 +544,7 @@ public sealed class WorkspaceHost
{
var version = await Task.Run(async () =>
{
EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -538,6 +567,7 @@ public sealed class WorkspaceHost
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
@@ -551,6 +581,7 @@ public sealed class WorkspaceHost
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
@@ -570,6 +601,7 @@ public sealed class WorkspaceHost
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
WorkspaceConflict? shown = null, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
if (choice == ConflictChoice.SaveBoth)
@@ -619,6 +651,7 @@ public sealed class WorkspaceHost
/// </summary>
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
@@ -676,6 +709,7 @@ public sealed class WorkspaceHost
/// <exception cref="HomeUnavailableException">The home cannot be reached now: the name stays.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var project = Existing(projectId);
var renamed = await HomeOfProject(projectId).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
@@ -701,6 +735,7 @@ public sealed class WorkspaceHost
{
var (sequenceId, removed) = await Task.Run(async () =>
{
EnsureNotMoving();
var project = Existing(projectId);
var workspace = project.ReadBundle().Workspace!;
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
@@ -766,8 +801,10 @@ public sealed class WorkspaceHost
// A conflict recorded counts as work not at the home, also once the library no longer has the project (Gone asks none);
// one a settling replay took past its commit point is over, as the status reads it.
var conflict = status.Conflict is not null || project.OpenConflict() is not null;
var (unsentRenders, lastOriginals) = await RemovalMediaAsync(project, cancellationToken).ConfigureAwait(false);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, conflict, status.Offline,
status.State == WorkspaceState.Gone);
status.State == WorkspaceState.Gone)
{ UnsentRenders = unsentRenders, LastOriginals = lastOriginals };
}, cancellationToken);
/// <summary>
@@ -784,6 +821,8 @@ public sealed class WorkspaceHost
{
var sequenceId = await Task.Run(async () =>
{
// A move takes every project folder as it stands: none goes to the trash meanwhile.
EnsureNotMoving();
var project = Existing(projectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
if (entry.Newer) throw Unreadable(entry);
@@ -802,6 +841,7 @@ public sealed class WorkspaceHost
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Unsent(workspace.Home));
await EnsureRendersSentAsync(project, workspace, cancellationToken).ConfigureAwait(false);
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -907,10 +947,11 @@ public sealed class WorkspaceHost
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
{ State: JobState.Queued or JobState.Running or JobState.Paused })
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
var aside = Path.Combine(Store.Root, TrashFolder, project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture));
// Filled under a staging name Empty… never lists, and named once whole.
using var trash = WorkspaceTrash.Begin(Store.Root, project.ProjectId, DateTime.UtcNow);
var aside = trash.Path;
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
Directory.CreateDirectory(aside);
var moved = new List<(string From, string To)>();
try
{
@@ -950,7 +991,21 @@ public sealed class WorkspaceHost
}
throw;
}
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
// Every original is hashed and goes aside unless the home holds the same bytes; only what the home can make again
// is deleted. One that can be neither deleted nor moved stays where it is, and the media folder with it.
if (await ClearOriginalsAsync(project, aside, cancellationToken).ConfigureAwait(false) == 0)
{
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
}
else
{
foreach (var entry in Directory.EnumerateFileSystemEntries(project.MediaDirectory).ToList())
{
if (string.Equals(Path.GetFileName(entry), WorkspaceProject.OriginalsFolder, StringComparison.OrdinalIgnoreCase)) continue;
if (Directory.Exists(entry)) Directory.Delete(entry, recursive: true);
else File.Delete(entry);
}
}
void Move(string from, string to)
{
@@ -1007,9 +1062,13 @@ public sealed class WorkspaceHost
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
_settings.WorkspaceRecent.Remove(sequenceId);
_savePreferences();
var changed = _settings.WorkspaceOpened.Remove(projectId);
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId)
{
_settings.WorkspaceRecent.Remove(sequenceId);
changed = true;
}
if (changed) _savePreferences();
}
/// <summary>
@@ -1055,7 +1114,7 @@ public sealed class WorkspaceHost
{
var workspace = bundle.Workspace!;
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, WorkspaceCleaner.HoldsMedia(project), bundle.Saved);
}
/// <summary>