Files
Chronos/src/Chronos.App/Settings/WorkspaceSettingsRows.cs
T
Alby96andClaude Opus 5.5 8f804b6acb feat(settings): complete the Settings › Workspace page
Phase 5c P5. The page now holds every workspace setting in the plan's
order: the folder with Open, Change… and Move… (bound to
WorkspaceFolderChange.MoveAsync, disabled while a move runs) and what
the folder takes of its drive; Size limit and Clean after, presets then
No limit / Never; Default media and Open project as radio choices;
Sync automatically; Version on render; Kept versions; and Trash, which
shows its entries and size and empties it only after its plan and the
typed entry count (WorkspaceHost.PlanTrashAsync / EmptyTrashAsync),
telling a changed trash apart in a toast.

WorkspaceSettingsRows reaches the workspace through
WorkspaceSettingsServices, so the rows are tested without a shell;
Reset restores every row but keeps the folder and what the workspace
remembers. The page's search finds the new rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:19:16 +01:00

446 lines
20 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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>
/// 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 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 (<see cref="WorkspaceHost.IsMoving"/>).</summary>
public Func<bool> IsMoving { get; init; } = () => false;
/// <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)
{
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,
};
}
}
/// <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;
// ---------------- Folder ----------------
/// <summary>The workspace folder in use.</summary>
public string Folder => folder();
/// <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, nor while it moves.</summary>
public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null && !(services?.IsMoving() ?? false));
public bool CanChange => change is not null;
/// <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 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>"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;
set
{
if (settings.WorkspaceAutoSync == value) return;
settings.WorkspaceAutoSync = value;
save();
OnPropertyChanged();
}
}
// ---------------- 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 =>
[.. 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 (Store(value, settings.WorkspaceKeptVersions, v => settings.WorkspaceKeptVersions = v)) Raise(nameof(KeptChoices), nameof(SelectedKept));
}
}
// ---------------- 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.WorkspaceOpenProject == WorkspaceOpenPolicy.LastUsed || !Enum.IsDefined(settings.WorkspaceOpenProject);
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.LastUsed);
}
}
public bool IsOpenMain
{
get => settings.WorkspaceOpenProject == WorkspaceOpenPolicy.Main;
set
{
if (value) SetOpenProject(WorkspaceOpenPolicy.Main);
}
}
public bool IsOpenAsk
{
get => settings.WorkspaceOpenProject == 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.</summary>
public string EmptyTrashToolTip => Loc.L(HasTrash ? "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 usage = await services.Usage(measure.Token);
if (_measure == measure) _usage = usage;
}
catch (OperationCanceledException) when (measure.IsCancellationRequested)
{
// A newer measure took over.
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
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();
private bool IsMoving => services?.IsMoving() ?? false;
/// <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 => string.Equals(settings.WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase);
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();
}