Merge branch 'p5c-p4' into review2-p5c

This commit is contained in:
Alby96 committed 2026-11-04 16:04:09 +01:00
commit 66163542f9
19 files changed
+1595 -44

No files matched your search

@@ -481,7 +481,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, _, _) =>
@@ -497,6 +499,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.
+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() ?? [];
+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));
}
}
+2
View File
@@ -41,6 +41,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);
@@ -648,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);
@@ -1,5 +1,11 @@
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;
@@ -36,67 +42,246 @@ public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList<WorkspaceTr
public sealed record WorkspaceTrashResult(int Items, long Bytes);
/// <summary>
/// The workspace's clean-up side (phase 5c, P4): its usage, the plan and emptying of its trash, and what a local copy's removal
/// keeps of renders not sent and originals the home lost. Stubs until the clean-up lands: usage and the trash read as empty,
/// and a removal finds nothing more to keep.
/// 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
{
/// <summary>What the workspace takes of its drive (<see cref="WorkspaceUsage"/>), measured off the UI thread.</summary>
public Task<WorkspaceUsage> UsageAsync(CancellationToken cancellationToken = default)
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(() =>
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(WorkspaceUsage.None);
}
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)
public Task<WorkspaceTrashPlan> PlanTrashAsync(CancellationToken cancellationToken = default) => Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(new WorkspaceTrashPlan(Path.Combine(Root, TrashFolder), [], 0, string.Empty));
}
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);
throw new NotImplementedException("Emptying the workspace's trash comes with phase 5c (P4).");
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.
/// <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 Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
private async Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult((0, 0));
var unsent = WorkspaceCleaner.UnsentRenders(project);
var last = (await LastOriginalsOfAsync(project, cancellationToken).ConfigureAwait(false)).Count;
return (unsent, last);
}
/// <summary>A removal without Discard is refused while the project's ledger holds renders not sent (Send first sends them).</summary>
/// <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 Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
private async Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(workspace);
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
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: the originals the home no longer holds with the
/// same SHA-256 moved into <paramref name="aside"/> (the copy's trash entry), never deleted.
/// </summary>
private Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
private async Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentException.ThrowIfNullOrEmpty(aside);
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
// 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 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}");
}
/// <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"/>.
/// </summary>
private async Task<IReadOnlyList<WorkspaceFrame>> LastOriginalsOfAsync(WorkspaceProject project, CancellationToken cancellationToken, BundleHome? named = null,
bool known = false)
{
WorkspaceMedia? media;
try
{
media = project.ReadMedia();
}
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 [];
}
if (media is null || !media.Frames.Any(f => f.HasOriginal)) return [];
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);
}
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 WorkspaceCleaner.LastOriginals(media, held);
}
/// <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})");
}
}
+1 -1
View File
@@ -1087,7 +1087,7 @@ public sealed partial 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>
@@ -0,0 +1,109 @@
using System.Globalization;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>One entry of the workspace's trash as Empty… lists it: "name · 1.2 GB · 04/11/2026".</summary>
public sealed class WorkspaceTrashRowViewModel(WorkspaceTrashItem item)
{
public WorkspaceTrashItem Item { get; } = item;
public string Text => Loc.L("Settings.Workspace.TrashPlan.Item", Item.Name, Formatting.Bytes(Item.Bytes),
Formatting.Date(Item.Trashed) + " " + Formatting.TimeOfDay(Item.Trashed));
}
/// <summary>
/// Settings › Workspace › Trash › Empty… (phase 5c): the plan (every entry of the workspace's trash, their number and size,
/// <see cref="WorkspaceTrashPlan"/>), then Erase for good, which enables only once the user typed the number of entries; the
/// emptying erases exactly the entries listed, and is refused when the trash changed since (the plan is shown again then).
/// Keep closes it, erasing nothing.
/// </summary>
public sealed class WorkspaceTrashDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<WorkspaceTrashPlan, Task<WorkspaceTrashResult>> _empty;
private readonly Action<WorkspaceTrashResult>? _emptied;
private string _typed = string.Empty;
/// <param name="empty">Erases the plan's entries (<see cref="WorkspaceHost.EmptyTrashAsync"/>).</param>
/// <param name="emptied">Told what was erased, once the dialog closes on it (the page measures the workspace again).</param>
public WorkspaceTrashDialogViewModel(WorkspaceTrashPlan plan, Func<WorkspaceTrashPlan, Task<WorkspaceTrashResult>> empty, Action<WorkspaceTrashResult>? emptied,
Action<ArchiveDialogViewModel> close)
: base(close)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(empty);
Plan = plan;
_empty = empty;
_emptied = emptied;
Rows = [.. plan.Items.Select(i => new WorkspaceTrashRowViewModel(i))];
EraseCommand = new AsyncRelayCommand(EraseAsync, () => CanErase);
}
public WorkspaceTrashPlan Plan { get; }
public IReadOnlyList<WorkspaceTrashRowViewModel> Rows { get; }
public string Heading => Loc.L("Settings.Workspace.TrashPlan.Title");
public string Message => Loc.L("Settings.Workspace.TrashPlan.Message");
/// <summary>"Entries: 3".</summary>
public string ItemsText => Loc.L("Settings.Workspace.TrashPlan.Items", Formatting.Count(Plan.Items.Count));
/// <summary>"Size: 1.2 GB".</summary>
public string SizeText => Loc.L("Settings.Workspace.TrashPlan.Size", Formatting.Bytes(Plan.Bytes));
/// <summary>What the user types to confirm: the number of entries, in plain digits.</summary>
public string Confirmation => Plan.Items.Count.ToString(CultureInfo.InvariantCulture);
/// <summary>"Type the number of entries, 3, to confirm".</summary>
public string TypedPrompt => Loc.L("Settings.Workspace.TrashPlan.Type", Confirmation);
/// <summary>What the user typed; Erase for good enables once it is <see cref="Confirmation"/>.</summary>
public string Typed
{
get => _typed;
set
{
if (!Set(ref _typed, value ?? string.Empty)) return;
OnPropertyChanged(nameof(CanErase));
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>The trash holds something, the number typed matches, and nothing runs.</summary>
public bool CanErase => !IsBusy && !Plan.IsEmpty && string.Equals(_typed.Trim(), Confirmation, StringComparison.Ordinal);
public ICommand EraseCommand { get; }
public string EraseToolTip => Plan.IsEmpty ? Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled") : Loc.L("Tooltips.Settings.Workspace.TrashPlan.Action");
public string KeepToolTip => Loc.L("Tooltips.Settings.Workspace.TrashPlan.Keep");
private async Task EraseAsync()
{
if (!CanErase) return;
ClearError();
IsBusy = true;
OnPropertyChanged(nameof(CanErase));
try
{
var result = await _empty(Plan);
IsBusy = false;
Close();
_emptied?.Invoke(result);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "The workspace's trash was not emptied", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
IsBusy = false;
OnPropertyChanged(nameof(CanErase));
}
}
}
@@ -0,0 +1,58 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:ws="clr-namespace:Chronos.App.Workspace">
<!-- Settings › Workspace › Trash › Empty… (phase 5c), in-window, with the dialog kit of the Archive screen. -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- The plan of emptying the workspace's trash: every entry, their number and size, then the number typed before Erase for good enables. -->
<DataTemplate DataType="{x:Type ws:WorkspaceTrashDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560" MaxHeight="560">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Grid.Row="1" Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,12,0,8">
<TextBlock Text="{Binding ItemsText}" Typography.NumeralAlignment="Tabular" ToolTip="{Binding ItemsText}" />
<TextBlock Text="{Binding SizeText}" Margin="16,0,0,0" Typography.NumeralAlignment="Tabular" ToolTip="{Binding SizeText}" />
</StackPanel>
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" MinHeight="96" AutomationProperties.Name="{l:Loc Settings.Workspace.Trash}" KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Text}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ws:WorkspaceTrashRowViewModel}">
<TextBlock Text="{Binding Text}" Height="32" Padding="0,8,0,0" TextTrimming="CharacterEllipsis" ToolTip="{Binding Text}" FlowDirection="LeftToRight"
Typography.NumeralAlignment="Tabular" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Row="4" Margin="0,16,0,0">
<TextBlock Text="{Binding TypedPrompt}" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" />
<TextBox Margin="0,6,0,0" Text="{Binding Typed, UpdateSourceTrigger=PropertyChanged}" ui:Field.Placeholder="{Binding Confirmation}" ToolTip="{Binding TypedPrompt}"
AutomationProperties.Name="{Binding TypedPrompt}" />
</StackPanel>
<DockPanel Grid.Row="5" Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Content="{l:Loc Editor.Project.Keep}" Command="{Binding CloseCommand}" ToolTip="{Binding KeepToolTip}" IsCancel="True"
IsDefault="True" MinWidth="96" />
<!-- Erasing for good: enabled once the number of entries is typed, never the default button. -->
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Destructive}" Content="{l:Loc Settings.Workspace.TrashPlan.Action}" Command="{Binding EraseCommand}"
ToolTip="{Binding EraseToolTip}" ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="0,0,8,0" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
</Grid>
</Border>
</DataTemplate>
</ResourceDictionary>