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

+6
View File
@@ -327,6 +327,12 @@
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Render.SendAgain}" Command="{Binding SendAgainCommand}"
ToolTip="{Binding SendAgainToolTip}" ToolTipService.ShowOnDisabled="True" Margin="6,0,0,0"
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Editor.Render.NotSent}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}"
VerticalAlignment="Center" Margin="6,0,0,0" ToolTip="{Binding UnsentToolTip}"
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
ToolTip="{Binding HistoryText}" />
</DockPanel>
+15 -7
View File
@@ -241,8 +241,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// <summary>The Export "Sync" option: available, or why not.</summary>
public ExportSyncGate SyncGate { get => _syncGate; private set => Set(ref _syncGate, value); }
/// <summary>The server job the header shows (<see cref="SequenceJobs.Shown"/>).</summary>
private Job? ServerJob => IsRemote ? _jobs.Shown : null;
/// <summary>The server job the header shows (<see cref="SequenceJobs.ShownAtHome"/>): never a workspace project's render on this PC or its send.</summary>
private Job? ServerJob => IsRemote ? _jobs.ShownAtHome : null;
/// <summary>
/// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings"; on the Export tab what the video will be:
@@ -634,7 +634,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var export = batch ? RenderExport : RenderExport with { Batch = [] };
var requests = Session.RenderRequests(export);
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
if (Session.Source is IProjectRenders { RendersLocally: true })
Shell.Notify(Loc.L("Editor.Render.QueuedLocal"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
else if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -957,7 +959,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void RefreshSteps()
{
if (_disposed) return;
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render),
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render) ?? _jobs.Active(JobKind.WorkspaceRender),
_planned ? RenderBlockedReason : null, _rendered.Matches(Session.Project));
foreach (var tab in Tabs) tab.SetStep(EditPath.Of(tab.Key, facts));
Analysis.OnStepChanged();
@@ -1174,7 +1176,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (_disposed)
{
// Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read.
if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
if (job is { State: JobState.Done } && IsRender(job.Kind) && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
AnnounceRender(job, read: false);
return;
}
@@ -1186,13 +1188,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!wasActive) return;
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited();
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
if (job.State == JobState.Done) _ = ReloadAsync(IsRender(job.Kind) && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
// A local render's send home (phase 5c): said once, here or on the Jobs screen.
if (job is { Kind: JobKind.WorkspaceSend, State: JobState.Done } && Shell.Jobs.ClaimRenderToast(job.Id)) Shell.Notify(Loc.L("Editor.Render.SentHome"), Title);
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so.
if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
else if (IsRemote && job.Kind is not (JobKind.WorkspaceRender or JobKind.WorkspaceSend) && job.State is JobState.Failed or JobState.Cancelled)
ReportServerJobEnded(job);
});
}
/// <summary>A render of the sequence: at its home, or on this PC from a workspace project's originals (phase 5c).</summary>
private static bool IsRender(JobKind kind) => kind is JobKind.Render or JobKind.WorkspaceRender;
/// <summary>
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
+43
View File
@@ -3,12 +3,16 @@ using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Workspace;
using Chronos.Core.Advice;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Video;
using Chronos.Data;
using Chronos.Data.Processing;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
@@ -403,6 +407,42 @@ public sealed class ExportTab : EditorTab
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory");
/// <summary>A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".</summary>
public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
/// <summary>Send again: queues the sending home of every render made here not sent yet; disabled while one is queued from here.</summary>
public ICommand SendAgainCommand => _sendAgain ??= new AsyncRelayCommand(SendAgainAsync, () => HasUnsent && !_sendQueued);
private AsyncRelayCommand? _sendAgain;
/// <summary>A send was queued from here and the ledger was not read again since.</summary>
private bool _sendQueued;
/// <summary>What Send again does, worded for the project's home.</summary>
public string SendAgainToolTip => WorkspaceText.ForHome("Tooltips.Editor.Render.SendAgain", Editor.Session.Source is WorkspaceSequenceSource { IsServerHome: true });
private async Task SendAgainAsync()
{
if (Editor.Session.Source is not WorkspaceSequenceSource source) return;
try
{
_sendQueued = await Editor.Shell.Services.Workspace.SendRendersAsync(source.ProjectId);
_sendAgain?.RaiseCanExecuteChanged();
if (_sendQueued)
Editor.Shell.Notify(Loc.L("Editor.Render.Sending"), Editor.Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Editor.Shell.Navigate(SectionKey.Jobs));
}
catch (Exception ex) when (ex is WorkspaceException or IOException or InvalidDataException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("editor", $"The renders of workspace project {source.ProjectId} could not be queued to be sent", ex);
Editor.Shell.Notify(Loc.L("Editor.Render.SendFailed"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), isError: true);
}
}
/// <summary>Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace.</summary>
public string? UnsentToolTip => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 } source
? Loc.L(source.IsServerHome ? "Tooltips.Editor.Render.NotSent.Server" : "Tooltips.Editor.Render.NotSent")
: null;
public IReadOnlyList<string> Batch => Export.Batch;
/// <summary>Completes when the card estimates in flight are done.</summary>
@@ -476,6 +516,9 @@ public sealed class ExportTab : EditorTab
public override void OnContentChanged()
{
// The ledger was read again: Send again goes by what it holds now.
_sendQueued = false;
_sendAgain?.RaiseCanExecuteChanged();
LoadCards();
if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
base.OnContentChanged();
+18 -4
View File
@@ -11,8 +11,8 @@ public sealed class SequenceJobs(Guid sequenceId)
{
private readonly Dictionary<Guid, Job> _active = [];
/// <summary>An analysis or render runs: settings wait.</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
/// <summary>An analysis or render runs: settings wait (a local render's send home does not hold them).</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running && j.Kind != JobKind.WorkspaceSend);
/// <summary>A deep analysis waits, runs or is paused.</summary>
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
@@ -20,16 +20,30 @@ public sealed class SequenceJobs(Guid sequenceId)
/// <summary>The job to show: one running, else one paused, else the oldest waiting; null when there is none.</summary>
public Job? Shown => First(_active.Values);
/// <summary>
/// The job a server sequence's header shows, chosen as <see cref="Shown"/> is among the jobs that run at its home: a
/// workspace project's render on this PC and its send home are this PC's jobs (the Jobs screen and the Export tab say
/// them), never the server's.
/// </summary>
public Job? ShownAtHome => First(_active.Values.Where(j => !IsLocalKind(j.Kind)));
/// <summary>A workspace project's render on this PC or its send home (phase 5c): this PC's job whatever the home.</summary>
public static bool IsLocalKind(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>The job of <paramref name="kind"/> to show, chosen as <see cref="Shown"/> is (the Edit path's steps).</summary>
public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind));
/// <summary>An analysis or render of this sequence.</summary>
/// <summary>An analysis or render of this sequence, a workspace project's render on this PC or its send home (phase 5c).</summary>
public bool Concerns(Job job)
{
ArgumentNullException.ThrowIfNull(job);
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
return job.TargetIds.Contains(sequenceId) && IsSequenceKind(job.Kind);
}
/// <summary>The kinds the editor follows.</summary>
public static bool IsSequenceKind(JobKind kind) =>
kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>The job is one of those that wait, run or are paused.</summary>
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
+1 -1
View File
@@ -208,7 +208,7 @@ internal sealed class ServerJobs : IAsyncDisposable
_changed(job);
}
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && SequenceJobs.IsSequenceKind(job.Kind);
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
internal static async Task<T> Call<T>(Func<Task<T>> call)
+114 -11
View File
@@ -29,6 +29,9 @@ public interface IProjectRenders
{
/// <summary>The jobs that render <paramref name="export"/> of <paramref name="project"/> (the editor's settings, positions on the source's frames).</summary>
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
/// <summary>The renders run on this PC (a workspace project holding its originals, phase 5c), whatever the home.</summary>
bool RendersLocally { get; }
}
/// <summary>
@@ -95,6 +98,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace;
private bool _readOnly;
private bool _holdsOriginals;
private int _unsent;
private int _disposed;
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
@@ -136,6 +141,15 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly);
/// <summary>
/// The media read last hold the originals (phase 5c): the project renders on this PC's engine from them, into its
/// <c>exports/</c>, and the renders are sent home after (<see cref="JobKind.WorkspaceRender"/>), also for a server home.
/// </summary>
public bool RendersLocally => Volatile.Read(ref _holdsOriginals);
/// <summary>The local renders of the project's ledger not at the home yet, as read last.</summary>
public int UnsentRenders => Volatile.Read(ref _unsent);
public bool IsOutdated => false;
/// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
@@ -179,6 +193,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
return await Task.Run(() =>
{
renders = [.. renders, .. UnsentOf(session.Project, home.SequenceId)];
var frames = media.Frames;
Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly);
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
@@ -278,6 +293,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
Created = r.Created,
ProducedBy = r.ProducedBy,
}).ToList() ?? [];
renders = [.. renders.Concat(UnsentOf(session.Project, home.SequenceId)).OrderByDescending(r => r.Created)];
var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count);
var context = SequenceContext.FromFrames(frames);
return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
@@ -495,7 +511,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <remarks>A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so.</remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
{
if (_server is not null) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken);
ArgumentNullException.ThrowIfNull(request);
// A render from the workspace's originals and its send run on this PC's engine, whatever the home (phase 5c).
if (_server is not null && !RunsHere(request.Kind)) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken);
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
return job.Id;
@@ -504,26 +522,40 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <remarks>A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).</remarks>
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{
if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return [];
var local = (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (_server is null) return local;
// This PC's renders from the originals and their sends beside the server's jobs (phase 5c).
IReadOnlyList<Job> here = [.. local.Where(j => RunsHere(j.Kind))];
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return here;
try
{
return await jobs.ListAsync(cancellationToken);
return [.. (await jobs.ListAsync(cancellationToken)).Concat(here)];
}
catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException)
{
Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}");
return [];
return here;
}
}
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
? ServerJobsOrThrow().CancelAsync(jobId, cancellationToken)
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().CancelAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
}
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null
? ServerJobsOrThrow().RetryAsync(jobId, cancellationToken)
: (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().RetryAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
}
/// <summary>The kinds a workspace project runs on this PC's engine whatever its home: a render from its originals and its send home.</summary>
private static bool RunsHere(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>A job of this PC's engine that runs here whatever the home (<see cref="RunsHere"/>).</summary>
private async Task<bool> IsLocalJobAsync(Guid jobId, CancellationToken cancellationToken) =>
await _db.Jobs.GetAsync(jobId, cancellationToken) is { } job && RunsHere(job.Kind);
/// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
@@ -542,6 +574,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
if (RendersLocally && Workspace is { } workspace) return LocalRenderRequests(sequence, workspace.Home, portable, hash, export, sourceWidth, sourceHeight);
if (_server is not null)
{
if (InStepWithHome(project) is { } basis)
@@ -566,6 +599,75 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
/// <summary>
/// The render on this PC from the originals the workspace holds (phase 5c): one <see cref="JobKind.WorkspaceRender"/> per
/// preset with the project's portable settings, naming the head version of <c>versions/</c> when the settings are the
/// ones it holds (the render records it; an unsaved working state renders without a version), sent home after.
/// </summary>
private IReadOnlyList<ArchiveJobRequest> LocalRenderRequests(Sequence sequence, BundleHome home, string portable, string hash, ExportSettings export,
int sourceWidth, int sourceHeight)
{
var head = HeadVersion(hash);
var version = new ProjectVersion { Id = head ?? Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
var root = _sync.Store.Root;
var server = home.IsArchive ? null : home.Server;
return
[
.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => WorkspaceJobs.Render(home.SequenceId,
r.Label ?? sequence.DisplayTitle, root, ProjectId, head, (head is null ? WithoutVersion(r.ParametersJson) : r.ParametersJson)!, server)),
];
}
/// <summary>The id of the newest version the workspace holds when it holds <paramref name="hash"/>; null otherwise.</summary>
private Guid? HeadVersion(string hash)
{
try
{
return Project.Versions() is [.., var last] && string.Equals(last.ContentHash, hash, StringComparison.OrdinalIgnoreCase) ? last.Id : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
return null;
}
}
/// <summary>The local renders of the project's ledger not at the home yet, as renders of <paramref name="sequenceId"/> (newest first).</summary>
private IReadOnlyList<Render> UnsentOf(WorkspaceProject project, Guid sequenceId)
{
try
{
var unsent = project.ReadRenders().Unsent;
Volatile.Write(ref _unsent, unsent.Count);
return
[
.. unsent.OrderByDescending(e => e.Rendered).Select(e => new Render
{
Id = e.RenderId,
SequenceId = sequenceId,
PresetName = e.PresetName,
OutputPath = project.ExportFile(e.File),
Codec = e.Codec,
Width = e.Width,
Height = e.Height,
Fps = e.Fps,
DurationSeconds = e.DurationSeconds,
Bytes = e.Size,
Created = e.Rendered,
ProducedBy = Environment.MachineName,
ProjectId = e.ProjectId,
ProjectVersionId = e.ProjectVersionId,
}),
];
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The render ledger of workspace project {ProjectId} cannot be read", ex);
Volatile.Write(ref _unsent, 0);
return [];
}
}
/// <summary>
/// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project
/// (<paramref name="project"/>) holds what the base holds; null otherwise.
@@ -643,6 +745,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace;
_holdsOriginals = index.HoldsOriginals;
changed = _readOnly != readOnly;
_readOnly = readOnly;
}
+22 -4
View File
@@ -178,15 +178,29 @@ public sealed class AppServices : IAsyncDisposable
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace, from
/// this PC's archive or, through the signed-in session, from a server.</summary>
/// queued (it is never claimed here). The workspace's jobs are the desktop's alone: they write into this PC's workspace
/// (a copy from this PC's archive or, through the signed-in session, from a server; a local render with this PC's
/// encoders; the sending of its renders home; the move of its folder, which Settings › Workspace then names).</summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
.. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives, services.Sync) : [],
.. services.Database is { } db && services.Archives is { } archives
? WorkspaceJobs.CreateHandlers(db, archives, services.Sync, WorkspaceOptions(services, archives))
: [],
];
/// <summary>
/// The workspace jobs' share of the desktop (phase 5c): its processing options for local renders, the metered hold of
/// Settings › Server over transfers with a server, the workspace that follows a moved folder, and the folder in use
/// (a job queued before a move finds its project there).
/// </summary>
private static WorkspaceJobOptions WorkspaceOptions(AppServices services, ArchiveService archives) =>
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
services.Workspace.MovedAsync,
() => services.Workspace.Root);
/// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
/// a background deep analysis when Settings › Analysis asks for it.
@@ -469,7 +483,9 @@ public sealed class AppServices : IAsyncDisposable
Parallelism = () => Parallelism,
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30))],
// The workspace-cleanup schedule removes the media past Settings › Workspace's Clean after and Size limit, and reports its trash (phase 5c).
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30)),
new WorkspaceCleanStep(() => Workspace), new WorkspaceTrashStep(() => Workspace)],
BackupDirectory = Environment.BackupDirectory,
// Told after each step of a Reorganize, and each sequence a conversion replaced or made, while the rest of the job runs.
SequenceChanged = (id, _, _) =>
@@ -485,6 +501,8 @@ public sealed class AppServices : IAsyncDisposable
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
// One job at a time (owner review 1): the parallelism works inside it, the priority queue decides which runs.
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
// The workspace's size limit runs after each copy of media into it (phase 5c).
Engine.JobChanged += Workspace.OnJobChanged;
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
+119 -1
View File
@@ -7,6 +7,7 @@ using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
using Chronos.Ui.Theming;
@@ -39,6 +40,21 @@ public enum HardwarePreference
HardwareForPreviews,
}
/// <summary>
/// Which project Edit opens for a sequence that has several in the workspace (Settings › Workspace › Open project, phase 5c).
/// </summary>
public enum WorkspaceOpenPolicy
{
/// <summary>The project opened last for the sequence (<see cref="AppSettings.WorkspaceRecent"/>), else the one saved last.</summary>
LastUsed,
/// <summary>The sequence's Main project.</summary>
Main,
/// <summary>Ask each time, listing the sequence's projects.</summary>
Ask,
}
/// <summary>A server certificate the user trusted on first use (BRIEF §12.7).</summary>
public sealed class TrustedCertificate
{
@@ -58,6 +74,8 @@ public sealed class AppSettings
public const int DefaultCacheLimitGb = 20;
public const int DefaultScanIntervalMinutes = 10;
public const int DefaultWorkspaceKeptVersions = 20;
public const int DefaultWorkspaceSizeLimitGb = 100;
public const int DefaultWorkspaceCleanAfterDays = 30;
/// <summary>2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).</summary>
public const double DefaultNightBrightnessPercent = 6.25;
@@ -169,6 +187,48 @@ public sealed class AppSettings
/// <summary>The workspace project opened last for each sequence (sequence id → project id); Edit opens it again.</summary>
public Dictionary<Guid, Guid> WorkspaceRecent { get; set; } = [];
/// <summary>
/// Phase 5c: past this size (GB of 2³⁰ bytes) the workspace's clean-up removes the media of the projects used longest ago
/// that are in step with their home (never one open, with jobs, or with renders not sent); 0 = no limit.
/// </summary>
public int WorkspaceSizeLimitGb { get; set; } = DefaultWorkspaceSizeLimitGb;
/// <summary>
/// What "Open in workspace" copies unless chosen otherwise: <see cref="BundleMedia.Proxies"/> or
/// <see cref="BundleMedia.Originals"/> (the proxies plus the originals, to render on this PC).
/// </summary>
public string WorkspaceDefaultMedia { get; set; } = BundleMedia.Proxies;
/// <summary>A render of a project with changes not saved as a version saves one first (and sends it when Sync automatically is on).</summary>
public bool WorkspaceVersionOnRender { get; set; } = true;
/// <summary>
/// The workspace's clean-up removes the media of a project not opened for this many days, once it is in step with its
/// home; 0 = never.
/// </summary>
public int WorkspaceCleanAfterDays { get; set; } = DefaultWorkspaceCleanAfterDays;
/// <summary>Which project Edit opens for a sequence with several in the workspace.</summary>
public WorkspaceOpenPolicy WorkspaceOpenProject { get; set; } = WorkspaceOpenPolicy.LastUsed;
/// <summary>
/// <see cref="WorkspaceDefaultMedia"/> as everything applies it: the originals for any case of "originals", else the
/// proxies (a value set elsewhere reads as the proxies). Settings › Workspace shows the same.
/// </summary>
[System.Text.Json.Serialization.JsonIgnore]
public string EffectiveDefaultMedia =>
string.Equals(WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase) ? BundleMedia.Originals : BundleMedia.Proxies;
/// <summary><see cref="WorkspaceOpenProject"/> as everything applies it: a value this Chronos does not know reads as the last used. Settings › Workspace shows the same.</summary>
[System.Text.Json.Serialization.JsonIgnore]
public WorkspaceOpenPolicy EffectiveOpenPolicy => Enum.IsDefined(WorkspaceOpenProject) ? WorkspaceOpenProject : WorkspaceOpenPolicy.LastUsed;
/// <summary>
/// When each workspace project was last opened in Edit (project id → time), which the clean-up goes by (else the time
/// its working state was saved). This PC's, like <see cref="WorkspaceRecent"/>.
/// </summary>
public Dictionary<Guid, DateTimeOffset> WorkspaceOpened { get; set; } = [];
// ---- Server ----
public string? ServerUrl { get; set; }
public string? ServerUsername { get; set; }
@@ -188,7 +248,7 @@ public sealed class AppSettings
/// <summary>Send and take project settings changed on one side without asking (Server.html).</summary>
public bool SyncSettingsAutomatically { get; set; } = true;
/// <summary>Pause upload jobs while Windows reports the connection as metered (Server.html).</summary>
/// <summary>Pause transfers with a server (uploads, sync downloads, workspace copies and renders sent) while Windows reports the connection as metered (Server.html).</summary>
public bool PauseUploadsOnMetered { get; set; }
// ---- Jobs ----
@@ -285,6 +345,64 @@ public sealed class AppSettings
/// <summary>A deep copy (JSON round trip), used for import and reset.</summary>
public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
/// <summary>
/// Settings › Advanced › Reset: every default, but the values that are this PC's or this user's state rather than
/// preferences: the archive and the session, the window and its rail, the sequence edited last, the first-run flag, the
/// jobs cleared, and the workspace (its folder, moved only by its own operation, the projects opened last and when).
/// </summary>
public AppSettings ResetKeepingState() => new()
{
LastArchivePath = LastArchivePath,
ServerUrl = ServerUrl,
ServerUsername = ServerUsername,
ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers,
Window = Window,
RailCollapsed = RailCollapsed,
LastEditedSequence = LastEditedSequence,
FirstRunCompleted = FirstRunCompleted,
JobsClearedAt = JobsClearedAt,
WorkspaceFolder = WorkspaceFolder,
WorkspaceRecent = WorkspaceRecent,
WorkspaceOpened = WorkspaceOpened,
};
/// <summary>
/// Settings › Export: a copy without secrets and machine-bound values (the session, the window, the workspace's folder and
/// what it remembers of its projects: another PC's ids mean nothing there).
/// </summary>
public AppSettings ForExport()
{
var copy = Clone();
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
return copy;
}
/// <summary>
/// Settings › Import: <paramref name="imported"/> with this PC's own values taken from these settings: the session, the
/// window and its rail, the sequence edited last, the first-run flag, and the workspace (its folder, the projects opened
/// last and when). Changes and returns <paramref name="imported"/>.
/// </summary>
public AppSettings KeepLocalIn(AppSettings imported)
{
ArgumentNullException.ThrowIfNull(imported);
imported.ProtectedToken = ProtectedToken;
imported.ServerUrl = ServerUrl;
imported.Window = Window;
imported.RailCollapsed = RailCollapsed;
imported.LastEditedSequence = LastEditedSequence;
imported.FirstRunCompleted = FirstRunCompleted;
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
return imported;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
+15 -2
View File
@@ -20,8 +20,8 @@ namespace Chronos.App.Jobs;
/// wrote into its archive.json, as the rescans before it did, and counts as none while it is offline (an unplugged
/// drive). The system schedules stand for the timers the desktop used to run out of sight: the archive scan (its interval
/// carried over from the former Settings › Archive › Rescan every, <see cref="AppSettings.ScanIntervalMinutes"/>, once:
/// a row that exists keeps the user's edits), the daily index backup, and the housekeeping clean-up at 04:00 (job history,
/// cache trim). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
/// a row that exists keeps the user's edits), the daily index backup, the housekeeping clean-up at 04:00 (job history,
/// cache trim), and the workspace's clean-up at 04:30 (phase 5c: its media, a report of its trash). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
/// (<see cref="DeepAnalysisAfterScan"/>), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
/// </summary>
public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDatabase?> database, Func<ArchiveService?> archives) : IScheduleHost
@@ -41,6 +41,16 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
/// <summary>When the housekeeping runs.</summary>
public static readonly TimeOnly HousekeepingTime = new(4, 0);
/// <summary>
/// Clean-up of the workspace (phase 5c), daily at 04:30, with catch-up: the media of projects past Settings › Workspace ›
/// Clean after or Size limit (<see cref="WorkspaceCleanStep"/>), and a report of its trash (<see cref="WorkspaceTrashStep"/>),
/// which it never empties. It runs whether an archive is open or not.
/// </summary>
public const string WorkspaceCleanup = "workspace-cleanup";
/// <summary>When the workspace clean-up runs: after the housekeeping.</summary>
public static readonly TimeOnly WorkspaceCleanupTime = new(4, 30);
/// <summary>The PC's zone; tests set another.</summary>
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
@@ -54,6 +64,9 @@ public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDataba
new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(HousekeepingTime),
new ScheduleParametersDto(Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory, CacheTrimStep.StepName],
OlderThanDays: Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays)),
// The ages and the limit are Settings › Workspace's, read at each run: the schedule holds no days of its own.
new(WorkspaceCleanup, "Workspace clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(WorkspaceCleanupTime),
new ScheduleParametersDto(Steps: [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], OlderThanDays: 0)),
];
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
+2 -1
View File
@@ -40,7 +40,8 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert;
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert or JobKind.WorkspaceRender or JobKind.WorkspaceSend
or JobKind.WorkspaceMove;
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
+1 -1
View File
@@ -12,7 +12,7 @@ public static class JobText
/// <summary>True for jobs whose items are frames, so their speed reads in fps.</summary>
public static bool CountsFrames(JobKind kind) =>
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse;
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse or JobKind.WorkspaceRender;
/// <summary>True for jobs whose progress counts bytes (hash verification, card import).</summary>
public static bool CountsBytes(JobKind kind) => kind is JobKind.Verify or JobKind.Import;
+3
View File
@@ -166,6 +166,7 @@ public static class ScheduleText
DesktopScheduleHost.ArchiveScan => "Jobs.Schedule.System.ArchiveScan",
DesktopScheduleHost.IndexBackup => "Jobs.Schedule.System.IndexBackup",
DesktopScheduleHost.Housekeeping => "Jobs.Schedule.System.Housekeeping",
DesktopScheduleHost.WorkspaceCleanup => "Jobs.Schedule.System.WorkspaceCleanup",
_ => null,
};
@@ -175,6 +176,8 @@ public static class ScheduleText
CleanupSteps.Audit => "Audit",
CleanupSteps.TrashReport => "TrashReport",
CacheTrimStep.StepName => "CacheTrim",
WorkspaceCleanStep.StepName => "WorkspaceClean",
WorkspaceTrashStep.StepName => "WorkspaceTrash",
_ => null,
};
@@ -0,0 +1,63 @@
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Workspaces;
namespace Chronos.App.Jobs;
/// <summary>
/// The desktop's clean-up step <c>workspace-clean</c> (phase 5c): removes the media of workspace projects in step with their
/// home, those not opened for Settings › Workspace › Clean after, then the least recently used while the projects take more
/// than Size limit (<see cref="WorkspaceHost.CleanAsync"/>). Each project kept is logged with why. It needs no archive: the
/// <c>workspace-cleanup</c> schedule runs it whether one is open or not. The trash is never emptied here.
/// </summary>
public sealed class WorkspaceCleanStep(Func<WorkspaceHost?> workspace) : ICleanupStep
{
public const string StepName = "workspace-clean";
public string Name => StepName;
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
ArgumentNullException.ThrowIfNull(context);
if (workspace() is not { } host || await host.CleanAsync(cleanAfter: true, cancellationToken: context.Cancellation).ConfigureAwait(false) is not { } report)
return Loc.L("Jobs.Log.WorkspaceUnavailable");
foreach (var kept in report.Kept)
context.Job.Log(Loc.L("Jobs.Log.WorkspaceKept", Named(kept.SequenceTitle, kept.Name, kept.IsMain), Reason(kept.Reason)));
if (report.Cleaned.Count == 0 && report.Kept.Count == 0) return Loc.L("Jobs.Log.WorkspaceNothing", Formatting.Bytes(report.UsedBefore));
foreach (var cleaned in report.Cleaned.Where(c => c.Trashed > 0))
context.Job.Log(Loc.L("Archive.Log.WorkspaceOriginalsTrashed", Named(cleaned.SequenceTitle, cleaned.Name, cleaned.IsMain), Formatting.Count(cleaned.Trashed)));
return Loc.L("Jobs.Log.WorkspaceCleaned", Formatting.Count(report.Cleaned.Count), Formatting.Bytes(report.Freed), Formatting.Count(report.Kept.Count));
}
/// <summary>"open in Edit", "renders not sent", …: why a project was kept, for the job log.</summary>
public static string Reason(WorkspaceKeep reason) => Loc.L("Jobs.Log.WorkspaceSkip." + reason);
/// <summary>"Harbour sunset · Main": a project as the job log names it (its sequence, then its name).</summary>
public static string Named(string sequenceTitle, string name, bool isMain)
{
var project = WorkspaceText.ProjectName(name, isMain);
return sequenceTitle is { Length: > 0 } title ? title + Loc.Separator + project : project;
}
}
/// <summary>
/// The desktop's clean-up step <c>workspace-trash</c> (phase 5c): reports what the workspace's trash holds (entries and
/// size); it never deletes, emptying it stays the user's Settings › Workspace › Trash › Empty….
/// </summary>
public sealed class WorkspaceTrashStep(Func<WorkspaceHost?> workspace) : ICleanupStep
{
public const string StepName = "workspace-trash";
public string Name => StepName;
public async Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
ArgumentNullException.ThrowIfNull(context);
if (workspace() is not { IsEnabled: true } host) return Loc.L("Jobs.Log.WorkspaceUnavailable");
var plan = await host.PlanTrashAsync(context.Cancellation).ConfigureAwait(false);
return Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(plan.Items.Count), Formatting.Bytes(plan.Bytes));
}
}
+1 -1
View File
@@ -303,7 +303,7 @@ public sealed class JobsViewModel : SectionViewModel
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
if (notice == JobNotice.Done && job.Kind == JobKind.Render
if (notice == JobNotice.Done && job.Kind is JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job);
}
@@ -127,6 +127,10 @@
<MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}"
ToolTipService.ShowOnDisabled="True" />
<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}" />
</ContextMenu>
</Button.ContextMenu>
+78 -27
View File
@@ -608,12 +608,20 @@ public sealed class SequenceViewModel : SectionViewModel
ImageDecoder decoder, Sequence row)
{
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),
{ Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain),
_ => await workspace.LastUsedAsync(row.Id),
};
var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, row.Id, row.DisplayTitle, _ => true);
if (cancelled)
{
_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.
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,
@@ -634,10 +642,12 @@ public sealed class SequenceViewModel : SectionViewModel
if (entry is { HasMedia: true })
{
workspace.Remember(row.Id, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
var media = DefaultMedia(services);
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.
@@ -653,12 +663,12 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.KeepSequence(OpenSequenceId);
return null;
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
(projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName, media);
}
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)
{
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,
{ Main: true } => (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true }),
_ => await workspace.LastUsedAsync(remoteId) is { IsServerHome: true } last ? last : null,
};
var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, remoteId, null, p => p.IsServerHome);
if (cancelled)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
entry = chosen;
}
var sync = services.Sync;
if (entry is { IsReadable: false } unreadable)
{
@@ -726,6 +744,7 @@ public sealed class SequenceViewModel : SectionViewModel
{
TakeRequest(remoteId);
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:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server;
@@ -755,6 +774,7 @@ public sealed class SequenceViewModel : SectionViewModel
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
var media = DefaultMedia(services);
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.
@@ -770,12 +790,12 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
(projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(home, projectId, newName);
checkout = await workspace.CheckoutAsync(home, projectId, newName, media);
}
catch (WorkspaceException ex) when (ex.FolderRefused)
{
@@ -811,25 +831,23 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary>
/// "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
/// without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
/// media (Settings › Workspace › Media chosen first), what their copy writes and the room the workspace's drive has; null
/// when closed without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
/// disabled, why in its tooltip.
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain)
{
var projects = await workspace.HomeProjectsAsync(home);
WorkspaceCopyFacts? copy = null;
if (home.IsArchive)
try
{
try
{
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)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
}
copy = await workspace.CopyFactsAsync(home);
}
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)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
}
var unreadable = unreadableMain is { } main
? 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"),
}
: 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.
IsLoading = false;
OpenDialog(dialog);
@@ -851,6 +870,36 @@ 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.EffectiveDefaultMedia;
/// <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.EffectiveOpenPolicy;
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>
private ProjectRequest? TakeRequest(Guid sequenceId)
{
@@ -1071,6 +1120,8 @@ public sealed class SequenceViewModel : SectionViewModel
if (section.Shell.Services.Database is not { } db || await db.Sequences.GetAsync(sequenceId) is not { } row) return;
if (section.Shell.Library.Items.FirstOrDefault(i => i.Id == row.Id) is { } item) item.Update(row);
}
public void ShowJobs() => section.Shell.Navigate(SectionKey.Jobs);
}
}
+1 -1
View File
@@ -160,7 +160,7 @@
</StackPanel>
<CheckBox Content="{l:Loc Server.KeepProxies}" IsChecked="{Binding KeepProxiesOffline}" ToolTip="{l:Loc Tooltips.Server.KeepProxies}" Margin="0,0,22,0" />
<CheckBox Content="{l:Loc Server.AutoSync}" IsChecked="{Binding SyncSettingsAutomatically}" ToolTip="{l:Loc Tooltips.Server.AutoSync}" Margin="0,0,22,0" />
<CheckBox Content="{l:Loc Server.PauseMetered}" IsChecked="{Binding PauseUploadsOnMetered}" ToolTip="{l:Loc Tooltips.Server.PauseMetered}" Margin="0,0,22,0" />
<CheckBox Content="{l:Loc Server.PauseMeteredTransfers}" IsChecked="{Binding PauseUploadsOnMetered}" ToolTip="{l:Loc Tooltips.Server.PauseMeteredTransfers}" Margin="0,0,22,0" />
</WrapPanel>
</Border>
</Grid>
+68 -16
View File
@@ -520,32 +520,84 @@
</HeaderedContentControl>
</StackPanel>
<!-- ================= Workspace (owner review 2, R8) ================= -->
<!-- ================= Workspace (owner review 2, R8; phase 5c) ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Workspace}">
<!-- The folder is shown, opened and changed here (another folder after its plan; nothing is moved: moving it with its projects comes with phase 5c). -->
<!-- The folder is shown, opened, changed (another folder after its plan; nothing is moved) and moved with its projects (after its plan,
by the workspace-move job); what it takes of its drive under it. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Folder}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding WorkspaceRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.WorkspaceFolder}"
AutomationProperties.Name="{l:Loc Settings.Workspace.Folder}" />
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding WorkspaceRows.OpenCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenWorkspace}"
Margin="10,0,0,0" />
<Button Grid.Column="2" Content="{l:Loc Settings.Workspace.Change}" Command="{Binding WorkspaceRows.ChangeCommand}"
ToolTip="{l:Loc Tooltips.Settings.ChangeWorkspace}" Margin="8,0,0,0"
Visibility="{Binding WorkspaceRows.CanChange, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="160" MaxWidth="360" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBox.Path}" IsReadOnly="True" Text="{Binding WorkspaceRows.Folder, Mode=OneWay}" ToolTip="{l:Loc Tooltips.Settings.Workspace.Folder}"
AutomationProperties.Name="{l:Loc Settings.Workspace.Folder}" />
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding WorkspaceRows.OpenCommand}" ToolTip="{l:Loc Tooltips.Settings.OpenWorkspace}"
Margin="10,0,0,0" />
<Button Grid.Column="2" Content="{l:Loc Settings.Workspace.Change}" Command="{Binding WorkspaceRows.ChangeCommand}"
ToolTip="{Binding WorkspaceRows.ChangeToolTip}" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0"
Visibility="{Binding WorkspaceRows.CanChange, Converter={StaticResource BoolToVisibility}}" />
<Button Grid.Column="3" Content="{l:Loc Settings.Workspace.Move}" Command="{Binding WorkspaceRows.MoveCommand}"
ToolTip="{Binding WorkspaceRows.MoveToolTip}" ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0"
Visibility="{Binding WorkspaceRows.CanMove, Converter={StaticResource BoolToVisibility}}" />
<Button Grid.Column="4" Content="{l:Loc Settings.Workspace.ResumeMove}" Command="{Binding WorkspaceRows.ResumeMoveCommand}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.ResumeMove}" Margin="8,0,0,0"
Visibility="{Binding WorkspaceRows.CanResumeMove, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding WorkspaceRows.UsageText}" ToolTip="{l:Loc Tooltips.Settings.Workspace.Used}" Margin="0,6,0,0"
Visibility="{Binding WorkspaceRows.HasUsageText, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.SizeLimit}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding WorkspaceRows.SizeLimitChoices}" SelectedItem="{Binding WorkspaceRows.SelectedSizeLimit}"
DisplayMemberPath="Label" ToolTip="{Binding WorkspaceRows.SizeLimitToolTip}" AutomationProperties.Name="{l:Loc Settings.Workspace.SizeLimit}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.DefaultMedia}">
<WrapPanel Margin="0,4,0,0">
<RadioButton GroupName="WorkspaceMedia" Content="{l:Loc Settings.Workspace.Proxies}" IsChecked="{Binding WorkspaceRows.IsDefaultProxies}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.Proxies}" Margin="0,0,20,0" />
<RadioButton GroupName="WorkspaceMedia" Content="{l:Loc Settings.Workspace.Originals}" IsChecked="{Binding WorkspaceRows.IsDefaultOriginals}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.Originals}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Sync}">
<CheckBox Content="{l:Loc Settings.Workspace.AfterSave}" IsChecked="{Binding WorkspaceRows.AutoSync}" ToolTip="{l:Loc Tooltips.Settings.WorkspaceSync}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.VersionOnRender}">
<CheckBox Content="{l:Loc Settings.Workspace.SaveBeforeRender}" IsChecked="{Binding WorkspaceRows.VersionOnRender}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.VersionOnRender}" Margin="0,4,0,0" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Kept}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding WorkspaceRows.KeptChoices}" SelectedItem="{Binding WorkspaceRows.SelectedKept}"
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.KeptVersions}" AutomationProperties.Name="{l:Loc Settings.Workspace.Kept}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.CleanAfter}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding WorkspaceRows.CleanAfterChoices}" SelectedItem="{Binding WorkspaceRows.SelectedCleanAfter}"
DisplayMemberPath="Label" ToolTip="{Binding WorkspaceRows.CleanAfterToolTip}" AutomationProperties.Name="{l:Loc Settings.Workspace.CleanAfter}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.OpenProject}">
<WrapPanel Margin="0,4,0,0">
<RadioButton GroupName="WorkspaceOpen" Content="{l:Loc Settings.Workspace.LastUsed}" IsChecked="{Binding WorkspaceRows.IsOpenLastUsed}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.LastUsed}" Margin="0,0,20,0" />
<RadioButton GroupName="WorkspaceOpen" Content="{l:Loc Settings.Workspace.Main}" IsChecked="{Binding WorkspaceRows.IsOpenMain}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.Main}" Margin="0,0,20,0" />
<RadioButton GroupName="WorkspaceOpen" Content="{l:Loc Settings.Workspace.Ask}" IsChecked="{Binding WorkspaceRows.IsOpenAsk}"
ToolTip="{l:Loc Tooltips.Settings.Workspace.Ask}" />
</WrapPanel>
</HeaderedContentControl>
<!-- What removed copies and the clean-up set aside; only Empty… erases it, after its plan and the typed number of its entries. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Workspace.Trash}">
<WrapPanel>
<TextBlock Style="{StaticResource Text.Hint}" Text="{Binding WorkspaceRows.TrashText}" ToolTip="{l:Loc Tooltips.Settings.Workspace.Trash}" Margin="0,0,12,0"
VerticalAlignment="Center" />
<Button Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Workspace.EmptyTrash}" Command="{Binding WorkspaceRows.EmptyTrashCommand}"
ToolTip="{Binding WorkspaceRows.EmptyTrashToolTip}" ToolTipService.ShowOnDisabled="True" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
<!-- ================= Server ================= -->
+39 -38
View File
@@ -87,7 +87,9 @@ public sealed class SettingsViewModel : SectionViewModel
"Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
new(SettingsPage.Formats, ["Settings.Formats.Title", "Settings.Formats.Column.Tier", "Settings.Formats.Install"]),
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.Kept"]),
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
@@ -169,7 +171,9 @@ public sealed class SettingsViewModel : SectionViewModel
Logs = new LogSettingsRows(_s, Save);
// ---- Workspace ----
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync);
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
MoveWorkspaceFolderAsync, () => WorkspaceFolderChange.ResumeUnfinishedAsync(Shell)));
// ---- Storage ----
// A capture shows its folders under a sample data folder; what is typed is taken back to the folder it stands for.
@@ -259,6 +263,7 @@ public sealed class SettingsViewModel : SectionViewModel
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
if (value == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
if (value == SettingsPage.Advanced) LoadBackups();
}
}
@@ -726,7 +731,10 @@ public sealed class SettingsViewModel : SectionViewModel
// ---------------- Workspace ----------------
/// <summary>Settings › Workspace (owner review 2, R8): the folder, Sync automatically and Kept versions.</summary>
/// <summary>
/// Settings › Workspace (owner review 2, R8; phase 5c): the folder (Change, Move…, what it takes), Size limit, Default
/// media, Sync automatically, Version on render, Kept versions, Clean after, Open project and Trash.
/// </summary>
public WorkspaceSettingsRows WorkspaceRows { get; }
/// <summary>Shows the workspace folder in Explorer (made, with its manifest, when the workspace was never used).</summary>
@@ -747,8 +755,24 @@ public sealed class SettingsViewModel : SectionViewModel
{
await WorkspaceFolderChange.ChooseAsync(Shell);
WorkspaceRows.Refresh();
await WorkspaceRows.MeasureAsync();
}
/// <summary>The workspace folder moved with its projects, after its plan: the move job takes them, and Edit waits for it.</summary>
private async Task MoveWorkspaceFolderAsync()
{
await WorkspaceFolderChange.MoveAsync(Shell);
WorkspaceRows.Refresh();
}
/// <summary>A move of the workspace folder ended (any thread): the page shows the folder in use, what it takes, and Move… and Change… again.</summary>
private void OnWorkspaceMoveEnded() => System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{
WorkspaceRows.Refresh();
CommandManager.InvalidateRequerySuggested();
if (_page == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
});
// ---------------- Server ----------------
public EditableField DefaultServer { get; }
@@ -859,6 +883,7 @@ public sealed class SettingsViewModel : SectionViewModel
}
LoadCertificates();
Shell.Services.Server.PropertyChanged += OnServerChanged;
Shell.Services.Workspace.MoveEnded += OnWorkspaceMoveEnded;
if (System.Windows.Application.Current is { } app) _interfacePriority = new InterfacePriority(app, () => _s.BackgroundPriority);
_ = LoadArchiveAsync();
switch (Shell.Services.StagedRestore)
@@ -892,6 +917,7 @@ public sealed class SettingsViewModel : SectionViewModel
{
Loc.CultureChanged -= OnCultureChanged;
Shell.Services.Server.PropertyChanged -= OnServerChanged;
Shell.Services.Workspace.MoveEnded -= OnWorkspaceMoveEnded;
_selfTest?.Cancel();
_interfacePriority?.Dispose();
base.Dispose();
@@ -965,6 +991,8 @@ public sealed class SettingsViewModel : SectionViewModel
UpdateArchiveFree();
ArchiveReload = LoadArchiveAsync();
if (_page == SettingsPage.Advanced) LoadBackups();
// What the workspace takes and holds in its trash may have changed elsewhere (a local copy removed in Edit).
if (_page == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
}
/// <summary>
@@ -1207,7 +1235,8 @@ public sealed class SettingsViewModel : SectionViewModel
[
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
JobKind.WorkspaceMove,
];
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
@@ -1632,23 +1661,8 @@ public sealed class SettingsViewModel : SectionViewModel
IsDestructive = true,
});
if (!confirmed) return;
var defaults = new AppSettings
{
LastArchivePath = _s.LastArchivePath,
ServerUrl = _s.ServerUrl,
ServerUsername = _s.ServerUsername,
ProtectedToken = _s.ProtectedToken,
TrustedCertificates = _s.TrustedCertificates,
RecentServers = _s.RecentServers,
Window = _s.Window,
RailCollapsed = _s.RailCollapsed,
LastEditedSequence = _s.LastEditedSequence,
FirstRunCompleted = _s.FirstRunCompleted,
JobsClearedAt = _s.JobsClearedAt,
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
WorkspaceFolder = _s.WorkspaceFolder,
WorkspaceRecent = _s.WorkspaceRecent,
};
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
var defaults = _s.ResetKeepingState();
// Start with Windows lives in the registry, not in the settings file: its default is off.
Startup.SetEnabled(false);
ApplyAll(defaults);
@@ -1690,12 +1704,8 @@ public sealed class SettingsViewModel : SectionViewModel
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
if (folder is null) return;
var copy = _s.Clone();
// Secrets and machine-bound values stay on this PC.
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
var copy = _s.ForExport();
var path = Path.Combine(folder, $"Chronos settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
@@ -1720,18 +1730,9 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Errors.Settings.Import"), isError: true);
return;
}
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here)
// and the first-run flag.
imported.ProtectedToken = _s.ProtectedToken;
imported.ServerUrl = _s.ServerUrl;
imported.Window = _s.Window;
imported.RailCollapsed = _s.RailCollapsed;
imported.LastEditedSequence = _s.LastEditedSequence;
imported.FirstRunCompleted = _s.FirstRunCompleted;
// The workspace is this PC's: its folder and the projects opened last stay.
imported.WorkspaceFolder = _s.WorkspaceFolder;
imported.WorkspaceRecent = _s.WorkspaceRecent;
ApplyAll(imported);
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here),
// the first-run flag and the workspace, which is this PC's (its folder, the projects opened last and when).
ApplyAll(_s.KeepLocalIn(imported));
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
_retarget = RetargetArchiveAsync();
+35 -9
View File
@@ -4,14 +4,17 @@ using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
namespace Chronos.App.Server;
/// <summary>
/// "Pause uploads on metered networks" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and
/// Windows reports the connection as metered, upload jobs are paused (a running one stops after its current chunk and
/// keeps its checkpoint); they are resumed when the connection is no longer metered or the option goes off. Only the
/// uploads it paused are resumed. Checked when the network or an upload job changes, and every minute.
/// "Pause metered transfers" (Server.html): while <see cref="AppSettings.PauseUploadsOnMetered"/> is on and Windows reports
/// the connection as metered, the transfers with a server are paused (a running one stops after its current chunk or file
/// and keeps its checkpoint): upload jobs, the sync's downloads, and since phase 5c the workspace's copies from a server and
/// its renders sent to one (<see cref="Holds"/>); a copy from or a send to this PC's archive is never held. They are resumed when the connection
/// is no longer metered or the option goes off. Only the jobs it paused are resumed. Checked when the network or one of
/// those jobs changes, and every minute.
/// </summary>
public sealed class UploadHold : IDisposable
{
@@ -58,7 +61,27 @@ public sealed class UploadHold : IDisposable
private void OnJobChanged(Job job)
{
if (job is { Kind: JobKind.UploadCommit, State: JobState.Queued or JobState.Running }) Request();
if (job is { State: JobState.Queued or JobState.Running } && Holds(job)) Request();
}
/// <summary>The kinds of job a metered connection may hold (<see cref="Holds"/> says which of them).</summary>
internal static IReadOnlyList<JobKind> Kinds { get; } = [JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend];
/// <summary>
/// Whether a metered connection holds <paramref name="job"/>: an upload, a sync download (every one is from a server), or a
/// workspace copy or send whose home is a server (its parameters name one). One whose parameters cannot be read is not
/// held: it fails with its reason.
/// </summary>
internal static bool Holds(Job job)
{
ArgumentNullException.ThrowIfNull(job);
return job.Kind switch
{
JobKind.UploadCommit or JobKind.Download => true,
JobKind.WorkspaceCopy => WorkspaceJobs.CopyParameters(job)?.Server is { Length: > 0 },
JobKind.WorkspaceSend => WorkspaceJobs.SendParameters(job)?.Server is { Length: > 0 },
_ => false,
};
}
private async Task ApplyAsync()
@@ -71,10 +94,13 @@ public sealed class UploadHold : IDisposable
{
foreach (var state in new[] { JobState.Queued, JobState.Running })
{
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.UploadCommit, 500)).Items)
foreach (var kind in Kinds)
{
await engine.PauseAsync(job.Id);
_held.Add(job.Id);
foreach (var job in (await db.Jobs.ListAsync(state, kind, 500)).Items.Where(Holds))
{
await engine.PauseAsync(job.Id);
_held.Add(job.Id);
}
}
}
return;
@@ -87,7 +113,7 @@ public sealed class UploadHold : IDisposable
}
catch (Data.DatabaseException ex)
{
Log.Warning("sync", "Uploads could not be paused or resumed for the metered connection", ex);
Log.Warning("sync", "Transfers could not be paused or resumed for the metered connection", ex);
}
finally
{
+494 -18
View File
@@ -1,20 +1,103 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Workspace;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Settings;
/// <summary>
/// Settings › Workspace (owner review 2, R8): the workspace folder (shown with Open, and Change, which uses another
/// folder after a plan without moving anything; moving it with its projects comes with phase 5c), Sync automatically (a version saved is sent to its home at once, and the home's
/// new versions taken; on by default) and Kept versions (the versions taken from the home a project keeps in the
/// workspace besides its base and those not sent; 20 by default). Each choice is stored and saved at once. A value set
/// elsewhere (an imported or hand-edited settings file) is listed with the presets; one below 1 is shown as 1, as the
/// workspace applies it.
/// What Settings › Workspace reaches beyond the settings file (phase 5c): what the workspace takes of its drive, the plan
/// and emptying of its trash, the move of its folder with its projects, and the shell's confirmation and toasts. The app
/// takes them from <see cref="WorkspaceHost"/> (<see cref="For"/>); tests give their own.
/// </summary>
public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Func<string> folder, Action open, Func<Task>? change = null) : ObservableObject
public sealed class WorkspaceSettingsServices
{
/// <summary>What the workspace takes of its drive (<see cref="WorkspaceHost.UsageAsync"/>).</summary>
public required Func<CancellationToken, Task<WorkspaceUsage>> Usage { get; init; }
/// <summary>The plan of emptying the workspace's trash (<see cref="WorkspaceHost.PlanTrashAsync"/>).</summary>
public required Func<CancellationToken, Task<WorkspaceTrashPlan>> PlanTrash { get; init; }
/// <summary>Erases the entries of a confirmed plan (<see cref="WorkspaceHost.EmptyTrashAsync"/>).</summary>
public required Func<WorkspaceTrashPlan, CancellationToken, Task<WorkspaceTrashResult>> EmptyTrash { get; init; }
/// <summary>Asks a confirmation; true when the user chose the action.</summary>
public required Func<ConfirmRequest, bool> Confirm { get; init; }
/// <summary>Shows a toast: its title, its message, and whether it tells of something that did not happen.</summary>
public required Action<string, string?, bool> Notify { get; init; }
/// <summary>Picks a folder, shows the move's plan and queues it (<see cref="WorkspaceFolderChange.MoveAsync(Shell.ShellViewModel)"/>); null where the folder cannot move.</summary>
public Func<Task>? Move { get; init; }
/// <summary>A move of the workspace folder is queued or running, or stopped with its journal (<see cref="WorkspaceHost.IsMoving"/>; reads the disk).</summary>
public Func<bool> IsMoving { get; init; } = () => false;
/// <summary>A move stopped before it ended, no job taking it up (<see cref="WorkspaceHost.UnfinishedMoveAsync"/>); null where none is looked for.</summary>
public Func<CancellationToken, Task<bool>>? HasUnfinishedMove { get; init; }
/// <summary>Queues again the move that stopped (<see cref="WorkspaceFolderChange.ResumeUnfinishedAsync"/>); null where it cannot.</summary>
public Func<Task>? ResumeMove { get; init; }
/// <summary>The workspace's own operations, with the shell's <paramref name="dialogs"/> and toasts (<paramref name="notify"/>).</summary>
public static WorkspaceSettingsServices For(WorkspaceHost host, IAppDialogs dialogs, Action<string, string?, bool> notify, Func<Task>? move, Func<Task>? resume = null)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(dialogs);
ArgumentNullException.ThrowIfNull(notify);
return new WorkspaceSettingsServices
{
Usage = host.UsageAsync,
PlanTrash = host.PlanTrashAsync,
EmptyTrash = host.EmptyTrashAsync,
Confirm = dialogs.Confirm,
Notify = notify,
Move = move,
IsMoving = () => host.IsMoving,
HasUnfinishedMove = async token => await host.UnfinishedMoveAsync(token) is not null,
ResumeMove = resume,
};
}
}
/// <summary>
/// Settings › Workspace (owner review 2, R8; completed in phase 5c), its rows in order: the folder (shown with Open; Change,
/// which uses another folder after a plan without moving anything; Move…, which takes the projects along after its plan;
/// and what the folder takes of its drive), Size limit (past it the clean-up removes the media of the projects used longest
/// ago; 100 GB by default), Default media (what Open in workspace copies; proxies by default), Sync automatically (a version
/// saved is sent to its home at once, and the home's new versions taken; on by default), Version on render (a render of
/// changes not saved as a version saves one first; on by default), Kept versions (the versions taken from the home a project
/// keeps in the workspace besides its base and those not sent; 20 by default), Clean after (the media of a project not opened
/// for so long are removed; 30 days by default), Open project (which project Edit opens for a sequence with several; the last
/// used by default) and Trash (what it holds, and Empty…, which erases it after its plan and the typed number of its entries).
/// Each choice is stored and saved at once. A value set elsewhere (an imported or hand-edited settings file) is listed with
/// the presets; a size limit or clean-up age below 1 is shown as none, as the clean-up applies it, and kept versions below 1
/// as the 1 the workspace keeps.
/// </summary>
public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Func<string> folder, Action open, Func<Task>? change = null,
WorkspaceSettingsServices? services = null) : ObservableObject
{
public static readonly int[] KeptPresets = [5, 10, 20, 50, 100, 200];
public static readonly int[] SizeLimitPresets = [25, 50, 100, 200, 500, 1000];
public static readonly int[] CleanAfterPresets = [7, 14, 30, 60, 90];
private WorkspaceUsage? _usage;
private bool _isMeasuring;
private CancellationTokenSource? _measure;
/// <summary>Whether the workspace is held for a move, as read last (the disk is read once per refresh, never at each requery).</summary>
private bool? _moving;
/// <summary>A move stopped before it ended, as the last measure found (Resume shows).</summary>
private bool _unfinished;
// ---------------- Folder ----------------
/// <summary>The workspace folder in use.</summary>
public string Folder => folder();
@@ -22,11 +105,91 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
/// <summary>Shows the folder in Explorer.</summary>
public RelayCommand OpenCommand { get; } = new(open);
/// <summary>Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change.</summary>
public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null);
/// <summary>Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change, nor while it moves.</summary>
public AsyncRelayCommand ChangeCommand => _change ??= new AsyncRelayCommand(() => ThenReadMoveAsync(change), () => change is not null && !IsHeld);
private AsyncRelayCommand? _change;
public bool CanChange => change is not null;
/// <summary>Change…'s tooltip: what it does, or why it waits (a move under way, or one stopped that Resume takes up).</summary>
public string ChangeToolTip => MoveState ?? Loc.L("Tooltips.Settings.ChangeWorkspace");
/// <summary>Moves the folder with its projects, after its plan (WorkspaceFolderChange.MoveAsync); none where it cannot move, nor while it moves.</summary>
public AsyncRelayCommand MoveCommand => _move ??= new AsyncRelayCommand(() => ThenReadMoveAsync(services?.Move), () => services?.Move is not null && !IsHeld);
private AsyncRelayCommand? _move;
public bool CanMove => services?.Move is not null;
/// <summary>The move button's tooltip: what it does, or why it waits (a move under way, or one stopped that Resume takes up).</summary>
public string MoveToolTip => MoveState ?? Loc.L("Tooltips.Settings.Workspace.Move");
/// <summary>A move of the folder stopped before it ended and no job takes it up: Resume shows.</summary>
public bool CanResumeMove => _unfinished && services?.ResumeMove is not null;
/// <summary>Queues again the move that stopped, from its journal; the page is measured again after.</summary>
public AsyncRelayCommand ResumeMoveCommand => _resume ??= new AsyncRelayCommand(ResumeMoveAsync, () => CanResumeMove);
private AsyncRelayCommand? _resume;
/// <summary>Why Change… and Move… wait; null when they do not.</summary>
private string? MoveState => _unfinished ? Loc.L("Tooltips.Settings.Workspace.MoveUnfinished") : IsMoving ? Loc.L("Errors.Workspace.Moving") : null;
/// <summary>"12.4 GB used" (the whole folder, its trash included); "Measuring…" meanwhile; null before the first measure or when it failed.</summary>
public string? UsageText =>
_isMeasuring ? Loc.L("Settings.Workspace.Measuring")
: _usage is { } usage ? Loc.L("Settings.Workspace.Used", Formatting.Bytes(usage.TotalBytes))
: null;
/// <summary>The usage line shows.</summary>
public bool HasUsageText => UsageText is not null;
public bool IsMeasuring => _isMeasuring;
// ---------------- Size limit ----------------
/// <summary>The presets in GB, a value set elsewhere among them, then No limit (0).</summary>
public IReadOnlyList<SettingsOption<int>> SizeLimitChoices =>
[
.. With(SizeLimitPresets, SizeLimit).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Loc.L("Common.Size.GB", Formatting.Count(n)))),
new(0, Loc.L("Settings.Workspace.NoLimit")),
];
public SettingsOption<int> SelectedSizeLimit
{
get => SizeLimitChoices.First(c => c.Value == SizeLimit);
set
{
if (Store(value, settings.WorkspaceSizeLimitGb, v => settings.WorkspaceSizeLimitGb = v)) Raise(nameof(SizeLimitChoices), nameof(SelectedSizeLimit), nameof(SizeLimitToolTip));
}
}
/// <summary>What the limit chosen does: removes the oldest media past it, or nothing at all.</summary>
public string SizeLimitToolTip => Loc.L(SizeLimit == 0 ? "Tooltips.Settings.Workspace.NoLimit" : "Tooltips.Settings.Workspace.SizeLimit");
// ---------------- Default media ----------------
public bool IsDefaultProxies
{
get => !IsOriginalsDefault;
set
{
if (value) SetDefaultMedia(BundleMedia.Proxies);
}
}
public bool IsDefaultOriginals
{
get => IsOriginalsDefault;
set
{
if (value) SetDefaultMedia(BundleMedia.Originals);
}
}
// ---------------- Sync automatically ----------------
public bool AutoSync
{
get => settings.WorkspaceAutoSync;
@@ -39,34 +202,347 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
}
}
// ---------------- Version on render ----------------
public bool VersionOnRender
{
get => settings.WorkspaceVersionOnRender;
set
{
if (settings.WorkspaceVersionOnRender == value) return;
settings.WorkspaceVersionOnRender = value;
save();
OnPropertyChanged();
}
}
// ---------------- Kept versions ----------------
public IReadOnlyList<SettingsOption<int>> KeptChoices =>
[.. (KeptPresets.Contains(Kept) ? KeptPresets : KeptPresets.Append(Kept)).Order().Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Workspace.Versions", n)))];
[.. With(KeptPresets, Kept).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Workspace.Versions", n)))];
public SettingsOption<int> SelectedKept
{
get => KeptChoices.First(c => c.Value == Kept);
set
{
if (value is null || value.Value == settings.WorkspaceKeptVersions) return;
settings.WorkspaceKeptVersions = value.Value;
save();
OnPropertyChanged(nameof(KeptChoices));
OnPropertyChanged();
if (Store(value, settings.WorkspaceKeptVersions, v => settings.WorkspaceKeptVersions = v)) Raise(nameof(KeptChoices), nameof(SelectedKept));
}
}
/// <summary>The defaults of every row (Reset section); the caller saves. The folder stays (Change chooses it, after its plan).</summary>
// ---------------- Clean after ----------------
/// <summary>The presets in days, a value set elsewhere among them, then Never (0).</summary>
public IReadOnlyList<SettingsOption<int>> CleanAfterChoices =>
[
.. With(CleanAfterPresets, CleanAfter).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Workspace.Days", n))),
new(0, Loc.L("Settings.Workspace.Never")),
];
public SettingsOption<int> SelectedCleanAfter
{
get => CleanAfterChoices.First(c => c.Value == CleanAfter);
set
{
if (Store(value, settings.WorkspaceCleanAfterDays, v => settings.WorkspaceCleanAfterDays = v)) Raise(nameof(CleanAfterChoices), nameof(SelectedCleanAfter), nameof(CleanAfterToolTip));
}
}
/// <summary>What the age chosen does: removes the media of projects not opened so long, or never.</summary>
public string CleanAfterToolTip => Loc.L(CleanAfter == 0 ? "Tooltips.Settings.Workspace.Never" : "Tooltips.Settings.Workspace.CleanAfter");
// ---------------- Open project ----------------
public bool IsOpenLastUsed
{
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.LastUsed;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.LastUsed);
}
}
public bool IsOpenMain
{
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.Main;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.Main);
}
}
public bool IsOpenAsk
{
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.Ask;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.Ask);
}
}
// ---------------- Trash ----------------
/// <summary>"3 items, 1.2 GB", "Nothing in trash", "Measuring…" meanwhile; null before the first measure or when it failed.</summary>
public string? TrashText =>
_isMeasuring ? Loc.L("Settings.Workspace.Measuring")
: _usage is not { } usage ? null
: usage.TrashItems == 0 ? Loc.L("Settings.Workspace.TrashIsEmpty")
: Loc.Plural("Settings.Workspace.TrashItems", usage.TrashItems, Formatting.Bytes(usage.TrashBytes));
/// <summary>The trash holds something, as measured last: Empty… is enabled.</summary>
public bool HasTrash => _usage is { TrashItems: > 0 };
/// <summary>Lists the trash, asks for the typed number of its entries, then erases them (<see cref="EmptyTrashAsync"/>).</summary>
public AsyncRelayCommand EmptyTrashCommand => _emptyTrash ??= new AsyncRelayCommand((_, token) => EmptyTrashAsync(token), _ => services is not null && HasTrash && !_isMeasuring);
private AsyncRelayCommand? _emptyTrash;
/// <summary>Empty…'s tooltip: what it does, or that there is nothing to erase (only once a measure said so).</summary>
public string EmptyTrashToolTip => Loc.L(HasTrash || _usage is null ? "Tooltips.Settings.Workspace.EmptyTrash" : "Tooltips.Settings.Workspace.EmptyTrash.Disabled");
/// <summary>
/// Measures what the workspace takes of its drive and what its trash holds (the page shown, after Empty…, Change and Move);
/// a measure started meanwhile replaces this one.
/// </summary>
public async Task MeasureAsync()
{
if (services is null) return;
_measure?.Cancel();
using var measure = new CancellationTokenSource();
_measure = measure;
SetMeasuring(true);
try
{
var measuring = services.Usage(measure.Token);
// Meanwhile, whether a move holds the workspace, or stopped and waits to be taken up, read off the UI thread.
var (moving, unfinished) = await ReadMoveStateAsync(measure.Token);
if (_measure == measure) SetMoveState(moving, unfinished);
var usage = await measuring;
if (_measure == measure) _usage = usage;
}
catch (OperationCanceledException) when (measure.IsCancellationRequested)
{
// A newer measure took over.
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or Data.DatabaseException)
{
Log.Warning("workspace", "The workspace folder could not be measured", ex);
if (_measure == measure) _usage = null;
}
finally
{
if (_measure == measure)
{
_measure = null;
SetMeasuring(false);
}
}
}
/// <summary>
/// Empty…: the trash's plan (nothing erased), its confirmation with the number of entries typed
/// (<see cref="TrashRequest"/>), then the entries of exactly that plan erased, refused when the trash changed since. The
/// result is told in a toast, and the trash measured again.
/// </summary>
public async Task EmptyTrashAsync(CancellationToken cancellationToken = default)
{
if (services is null) return;
try
{
var plan = await services.PlanTrash(cancellationToken);
if (TrashRequest(plan) is not { } request || !services.Confirm(request)) return;
var result = await services.EmptyTrash(plan, cancellationToken);
Log.Info("workspace", $"Workspace trash emptied: {result.Items} entries, {result.Bytes} bytes");
services.Notify(Loc.L("Settings.Workspace.TrashEmptied"), Formatting.Bytes(result.Bytes), false);
}
catch (Exception ex) when (ex is WorkspaceException or IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", "The workspace trash was not emptied", ex);
services.Notify(Loc.L("Settings.Workspace.TrashNotEmptied"), ex is WorkspaceException ? ex.Message : ErrorText.For(ex), true);
}
finally
{
await MeasureAsync();
}
}
/// <summary>
/// The confirmation of emptying the workspace's trash: how many entries and bytes, the newest entries named (the rest
/// counted), and their number typed before the action enables; null when the trash holds nothing.
/// </summary>
public static ConfirmRequest? TrashRequest(WorkspaceTrashPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.IsEmpty) return null;
var count = plan.Items.Count.ToString(CultureInfo.InvariantCulture);
var lines = new List<string>
{
Loc.L("Settings.Workspace.TrashPlan.Items", Formatting.Count(plan.Items.Count)),
Loc.L("Settings.Workspace.TrashPlan.Size", Formatting.Bytes(plan.Bytes)),
};
lines.AddRange(plan.Items.OrderByDescending(i => i.Trashed).Take(DeletePlans.ListedLines)
.Select(i => Loc.L("Settings.Workspace.TrashPlan.Item", i.Name, Formatting.Bytes(i.Bytes), Formatting.Date(i.Trashed))));
if (plan.Items.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", plan.Items.Count - DeletePlans.ListedLines));
return new ConfirmRequest
{
Heading = Loc.L("Settings.Workspace.TrashPlan.Title"),
Message = Loc.L("Settings.Workspace.TrashPlan.Message"),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Settings.Workspace.Trash"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.Workspace.TrashPlan.Keep"),
ActionText = Loc.L("Settings.Workspace.TrashPlan.Action"),
ActionToolTip = Loc.L("Tooltips.Settings.Workspace.TrashPlan.Action"),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Settings.Workspace.TrashPlan.Type", count),
};
}
// ---------------- Reset ----------------
/// <summary>
/// The defaults of every row (Reset section); the caller saves. The folder stays (Change chooses it, after its plan;
/// Move takes it elsewhere), as do the trash and what the workspace remembers of the projects opened.
/// </summary>
public void Reset()
{
var defaults = new AppSettings();
settings.WorkspaceSizeLimitGb = defaults.WorkspaceSizeLimitGb;
settings.WorkspaceDefaultMedia = defaults.WorkspaceDefaultMedia;
settings.WorkspaceAutoSync = defaults.WorkspaceAutoSync;
settings.WorkspaceVersionOnRender = defaults.WorkspaceVersionOnRender;
settings.WorkspaceKeptVersions = defaults.WorkspaceKeptVersions;
settings.WorkspaceCleanAfterDays = defaults.WorkspaceCleanAfterDays;
settings.WorkspaceOpenProject = defaults.WorkspaceOpenProject;
Refresh();
}
/// <summary>Labels in the current language, values as the settings have them now.</summary>
internal void Refresh() => OnAllPropertiesChanged();
/// <summary>Labels in the current language, values as the settings have them now (whether a move holds the workspace read again once).</summary>
internal void Refresh()
{
_moving = null;
OnAllPropertiesChanged();
RaiseMoveCommands();
}
/// <summary>A move holds the workspace, as read last (read once when not known since the last refresh).</summary>
private bool IsMoving => _moving ??= services?.IsMoving() ?? false;
/// <summary>
/// Change… and Move… wait: a move holds the folder, or one stopped and Resume takes it up (also one that switched here
/// and left part of the folder it came from: another folder now would leave that part with no Resume).
/// </summary>
private bool IsHeld => _unfinished || IsMoving;
private async Task ResumeMoveAsync()
{
if (services?.ResumeMove is not { } resume) return;
await resume();
Refresh();
await MeasureAsync();
}
private void SetMoveState(bool moving, bool unfinished)
{
(_moving, _unfinished) = (moving, unfinished);
Raise(nameof(MoveToolTip), nameof(ChangeToolTip), nameof(CanResumeMove));
RaiseMoveCommands();
}
/// <summary>Whether a move holds the workspace, and whether one stopped waits to be taken up; neither when the index cannot say (logged).</summary>
private async Task<(bool Moving, bool Unfinished)> ReadMoveStateAsync(CancellationToken cancellationToken)
{
if (services is null) return (false, false);
try
{
var moving = await Task.Run(services.IsMoving, cancellationToken);
var unfinished = services.HasUnfinishedMove is { } look && await look(cancellationToken);
return (moving, unfinished);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or Data.DatabaseException)
{
Log.Warning("workspace", "Whether the workspace folder is being moved could not be read", ex);
return (false, false);
}
}
/// <summary>Runs Change… or Move…, then reads again whether a move holds the folder (the one just queued, say).</summary>
private async Task ThenReadMoveAsync(Func<Task>? action)
{
if (action is null) return;
try
{
await action();
}
finally
{
_moving = null;
Raise(nameof(MoveToolTip), nameof(ChangeToolTip));
RaiseMoveCommands();
}
}
private void RaiseMoveCommands()
{
_change?.RaiseCanExecuteChanged();
_move?.RaiseCanExecuteChanged();
_resume?.RaiseCanExecuteChanged();
}
/// <summary>The value the workspace applies: at least one version.</summary>
private int Kept => Math.Max(1, settings.WorkspaceKeptVersions);
/// <summary>The limit the clean-up applies: none below 1 GB.</summary>
private int SizeLimit => Math.Max(0, settings.WorkspaceSizeLimitGb);
/// <summary>The age the clean-up applies: never below 1 day.</summary>
private int CleanAfter => Math.Max(0, settings.WorkspaceCleanAfterDays);
/// <summary>Open in workspace copies the originals; any other value stored reads as the proxies, as the open dialog takes it.</summary>
private bool IsOriginalsDefault => settings.EffectiveDefaultMedia == BundleMedia.Originals;
private void SetDefaultMedia(string media)
{
if (string.Equals(settings.WorkspaceDefaultMedia, media, StringComparison.Ordinal)) return;
settings.WorkspaceDefaultMedia = media;
save();
Raise(nameof(IsDefaultProxies), nameof(IsDefaultOriginals));
}
private void SetOpenProject(WorkspaceOpenPolicy policy)
{
if (settings.WorkspaceOpenProject == policy) return;
settings.WorkspaceOpenProject = policy;
save();
Raise(nameof(IsOpenLastUsed), nameof(IsOpenMain), nameof(IsOpenAsk));
}
private void SetMeasuring(bool measuring)
{
_isMeasuring = measuring;
Raise(nameof(IsMeasuring), nameof(UsageText), nameof(HasUsageText), nameof(TrashText), nameof(HasTrash), nameof(EmptyTrashToolTip));
_emptyTrash?.RaiseCanExecuteChanged();
}
/// <summary>
/// Stores a choice that differs from the stored value (<paramref name="current"/>, which may lie out of range: choosing
/// the value shown then saves it as applied) and saves; false when there was nothing to store. The caller raises the
/// choices before the selection, so a list that changes keeps the item chosen.
/// </summary>
private bool Store(SettingsOption<int>? choice, int current, Action<int> set)
{
if (choice is null || choice.Value == current) return false;
set(choice.Value);
save();
return true;
}
private void Raise(params string[] properties)
{
foreach (var property in properties) OnPropertyChanged(property);
}
private static IEnumerable<int> With(int[] presets, int current) => (presets.Contains(current) ? presets : presets.Append(current)).Order();
}
+5
View File
@@ -4,6 +4,7 @@ using System.Windows.Shell;
using Chronos.App.About;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Workspace;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
@@ -41,6 +42,8 @@ public sealed class ShellViewModel : LocalizedViewModel
Library = new LibraryViewModel(this);
Import = new ImportViewModel(this);
Sequence = new SequenceViewModel(this);
// The workspace's clean-up never takes the project open in Edit (phase 5c).
services.Workspace.OpenProject = () => Sequence.OpenProjectId;
Archive = new ArchiveViewModel(this);
Jobs = new JobsViewModel(this);
Server = new ServerViewModel(this);
@@ -172,6 +175,8 @@ public sealed class ShellViewModel : LocalizedViewModel
Settings.Attach();
About.Attach();
await Server.AttachAsync();
// A move of the workspace folder that stopped before it ended is offered again (phase 5c).
await WorkspaceFolderChange.NoticeUnfinishedMoveAsync(this);
}
/// <summary>Opens a sequence in Edit.</summary>
@@ -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>