fix(workspace): close the phase 5c review findings

Originals are now judged by their bytes, never by the media index: a removal
or clean-up hashes every file under media/originals and deletes it only when
the home holds that SHA-256; every other file, named or not, goes to the
workspace trash. Trash entries are filled under a staging name that Empty
never lists. A ledger can only name files inside exports/.

Jobs follow the workspace: a copy, render or send resolves the folder that
holds its project now (a moved workspace, a retry after a move) and waits
while a move has not switched yet. A clean-up failure after the switch is a
warning that keeps the journal for a later resume; entries that changed
since they were copied are kept, and a same-volume rename refused across
volumes falls back to copy and verify.

Sends map a replayed version by content hash, or go with the project only,
and note an old server that drops provenance. The media index (format 2) and
project file (format 3) refuse older readers while they hold originals.
Metered connections also hold sync downloads and server copies. The editor
gains Send again, the Settings page can resume a stopped move, the disabled
tooltips say why, and unused strings are pruned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-04 17:32:48 +01:00
1 parent 09fcff4eb2
commit 2654683a12
125 files changed
+1618 -401

No files matched your search

+3
View File
@@ -327,6 +327,9 @@
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
<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}}" />
+2 -2
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:
+35
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;
@@ -406,6 +410,34 @@ public sealed class ExportTab : EditorTab
/// <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")
@@ -484,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();
+10
View File
@@ -20,6 +20,16 @@ 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));
@@ -192,12 +192,14 @@ public sealed class AppServices : IAsyncDisposable
/// <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, and the workspace that follows a moved folder.
/// 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.MovedAsync,
() => services.Workspace.Root);
/// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
+13 -1
View File
@@ -211,6 +211,18 @@ public sealed class AppSettings
/// <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"/>.
@@ -236,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 transfers with a server (uploads, workspace copies and renders sent) 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 ----
@@ -871,8 +871,7 @@ public sealed class SequenceViewModel : SectionViewModel
}
/// <summary>The media a checkout copies unless "Open in workspace" chose: Settings › Workspace › Media.</summary>
private static string DefaultMedia(AppServices services) =>
services.Settings.WorkspaceDefaultMedia == BundleMedia.Originals ? BundleMedia.Originals : BundleMedia.Proxies;
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
@@ -883,7 +882,7 @@ public sealed class SequenceViewModel : SectionViewModel
Func<WorkspaceEntry, bool> fits)
{
var last = await workspace.LastUsedAsync(sequenceId) is { } used && fits(used) ? used : null;
var policy = services.Settings.WorkspaceOpenProject;
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);
@@ -1121,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);
}
}
+5 -1
View File
@@ -532,17 +532,21 @@
<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="{l:Loc Tooltips.Settings.ChangeWorkspace}" Margin="8,0,0,0"
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}}" />
@@ -173,7 +173,7 @@ public sealed class SettingsViewModel : SectionViewModel
// ---- Workspace ----
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));
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.
@@ -991,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>
+7 -6
View File
@@ -11,8 +11,8 @@ namespace Chronos.App.Server;
/// <summary>
/// "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, 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
/// 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>
@@ -65,18 +65,19 @@ public sealed class UploadHold : IDisposable
}
/// <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.WorkspaceCopy, JobKind.WorkspaceSend];
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, 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.
/// 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 => true,
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,
+114 -17
View File
@@ -36,11 +36,17 @@ public sealed class WorkspaceSettingsServices
/// <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 (<see cref="WorkspaceHost.IsMoving"/>).</summary>
/// <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)
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);
@@ -54,6 +60,8 @@ public sealed class WorkspaceSettingsServices
Notify = notify,
Move = move,
IsMoving = () => host.IsMoving,
HasUnfinishedMove = async token => await host.UnfinishedMoveAsync(token) is not null,
ResumeMove = resume,
};
}
}
@@ -83,6 +91,12 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
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>
@@ -92,17 +106,35 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
public RelayCommand OpenCommand { get; } = new(open);
/// <summary>Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change, nor while it moves.</summary>
public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null && !(services?.IsMoving() ?? false));
public AsyncRelayCommand ChangeCommand => _change ??= new AsyncRelayCommand(() => ThenReadMoveAsync(change), () => change is not null && !IsMoving);
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 { get; } = new(services?.Move ?? (() => Task.CompletedTask), () => services?.Move is not null && !services.IsMoving());
public AsyncRelayCommand MoveCommand => _move ??= new AsyncRelayCommand(() => ThenReadMoveAsync(services?.Move), () => services?.Move is not null && !IsMoving);
private AsyncRelayCommand? _move;
public bool CanMove => services?.Move is not null;
/// <summary>The move button's tooltip: what it does, or that a move is under way.</summary>
public string MoveToolTip => IsMoving ? Loc.L("Errors.Workspace.Moving") : Loc.L("Tooltips.Settings.Workspace.Move");
/// <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 =>
@@ -223,7 +255,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
public bool IsOpenLastUsed
{
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.LastUsed || !Enum.IsDefined(settings.WorkspaceOpenProject);
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.LastUsed;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.LastUsed);
@@ -232,7 +264,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
public bool IsOpenMain
{
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.Main;
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.Main;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.Main);
@@ -241,7 +273,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
public bool IsOpenAsk
{
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.Ask;
get => settings.EffectiveOpenPolicy == WorkspaceOpenPolicy.Ask;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.Ask);
@@ -265,8 +297,8 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
private AsyncRelayCommand? _emptyTrash;
/// <summary>Empty…'s tooltip: what it does, or that there is nothing to erase.</summary>
public string EmptyTrashToolTip => Loc.L(HasTrash ? "Tooltips.Settings.Workspace.EmptyTrash" : "Tooltips.Settings.Workspace.EmptyTrash.Disabled");
/// <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);
@@ -281,14 +313,18 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
SetMeasuring(true);
try
{
var usage = await services.Usage(measure.Token);
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)
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;
@@ -383,10 +419,71 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
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();
}
private bool IsMoving => services?.IsMoving() ?? false;
/// <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;
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);
@@ -398,7 +495,7 @@ public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Fun
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 => string.Equals(settings.WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase);
private bool IsOriginalsDefault => settings.EffectiveDefaultMedia == BundleMedia.Originals;
private void SetDefaultMedia(string media)
{
@@ -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>
@@ -212,10 +217,14 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <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>
@@ -729,7 +738,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
_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.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)
{
@@ -84,7 +84,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
? [new DialogFact(Loc.L("Editor.OpenWorkspace.Originals"), Formatting.Bytes(originals), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsSize"))]
: Array.Empty<DialogFact>(),
];
_isOriginals = defaultMedia == BundleMedia.Originals && CanCopyOriginals;
_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;
@@ -148,6 +148,24 @@ public static class WorkspaceFolderChange
}
}
/// <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).
@@ -190,7 +190,7 @@ public sealed partial class WorkspaceHost
{
ArgumentNullException.ThrowIfNull(project);
var unsent = WorkspaceCleaner.UnsentRenders(project);
var last = (await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false)).Count;
var last = await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false);
return (unsent, last);
}
@@ -216,13 +216,17 @@ public sealed partial class WorkspaceHost
}
/// <summary>
/// Before a removed copy's media are deleted, under the project's lease: the originals the home no longer holds with the
/// same SHA-256 moved into <paramref name="aside"/> (the copy's trash entry), never deleted.
/// 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>
private async Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
/// <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
@@ -233,19 +237,39 @@ public sealed partial class WorkspaceHost
{
Log.Info("workspace", $"The home of removed project {project.ProjectId} is not known: every original it holds is kept ({ex.Message})");
}
var last = await LastOriginalsOfAsync(project, cancellationToken, home, known: true).ConfigureAwait(false);
if (last.Count == 0) return;
var moved = WorkspaceCleaner.SetOriginalsAside(project, last, aside);
Log.Info("workspace", $"{moved} original(s) of project {project.ProjectId} its home no longer holds kept in {aside}");
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>
/// The frames whose original the workspace holds and the home no longer holds as it is (every one while the home cannot
/// be asked); the home is the working state's, else (<paramref name="known"/>) <paramref name="named"/>.
/// 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<IReadOnlyList<WorkspaceFrame>> LastOriginalsOfAsync(WorkspaceProject project, CancellationToken cancellationToken, BundleHome? named = null,
bool known = false)
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
{
@@ -253,22 +277,49 @@ public sealed partial class WorkspaceHost
}
catch (InvalidDataException ex)
{
Log.Info("workspace", $"The media index of project {project.ProjectId} cannot be read: no original is counted from it ({ex.Message})");
return [];
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;
}
if (media is null || !media.Frames.Any(f => f.HasOriginal)) return [];
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
{
var homeOf = known ? named : project.ReadBundle().Workspace!.Home;
if (homeOf is not null && HomeOf(homeOf) is { } home) held = await home.FramesAsync(cancellationToken).ConfigureAwait(false);
held = await HomeFramesAsync(project, project.ReadBundle().Workspace!.Home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException or IOException or InvalidDataException)
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
// 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}");
Log.Info("workspace", $"The home of project {project.ProjectId} is not known: {ex.Message}");
}
return WorkspaceCleaner.LastOriginals(media, held);
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>
@@ -80,10 +80,20 @@ public sealed partial class WorkspaceHost
/// </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. 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"/>).
/// 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 () =>
{
@@ -96,7 +106,20 @@ public sealed partial class WorkspaceHost
return null;
}
}
return WorkspaceMover.HasJournal(Root) ? WorkspaceMover.ReadJournal(Root) : 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>
+21 -6
View File
@@ -296,7 +296,9 @@ public sealed partial 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)
{
@@ -944,10 +946,11 @@ public sealed partial 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
{
@@ -987,9 +990,21 @@ public sealed partial class WorkspaceHost
}
throw;
}
// Originals the home no longer holds go aside with the rest; only what the home can make again is deleted.
await KeepLastOriginalsAsync(project, aside, cancellationToken).ConfigureAwait(false);
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)
{