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; /// /// 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 (); tests give their own. /// public sealed class WorkspaceSettingsServices { /// What the workspace takes of its drive (). public required Func> Usage { get; init; } /// The plan of emptying the workspace's trash (). public required Func> PlanTrash { get; init; } /// Erases the entries of a confirmed plan (). public required Func> EmptyTrash { get; init; } /// Asks a confirmation; true when the user chose the action. public required Func Confirm { get; init; } /// Shows a toast: its title, its message, and whether it tells of something that did not happen. public required Action Notify { get; init; } /// Picks a folder, shows the move's plan and queues it (); null where the folder cannot move. public Func? Move { get; init; } /// A move of the workspace folder is queued or running (). public Func IsMoving { get; init; } = () => false; /// The workspace's own operations, with the shell's and toasts (). public static WorkspaceSettingsServices For(WorkspaceHost host, IAppDialogs dialogs, Action notify, Func? 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, }; } } /// /// 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. /// public sealed class WorkspaceSettingsRows(AppSettings settings, Action save, Func folder, Action open, Func? 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 ---------------- /// The workspace folder in use. public string Folder => folder(); /// Shows the folder in Explorer. public RelayCommand OpenCommand { get; } = new(open); /// Uses another folder, after its plan (WorkspaceFolderChange); none where the folder cannot change, nor while it moves. public AsyncRelayCommand ChangeCommand { get; } = new(change ?? (() => Task.CompletedTask), () => change is not null && !(services?.IsMoving() ?? false)); public bool CanChange => change is not null; /// Moves the folder with its projects, after its plan (WorkspaceFolderChange.MoveAsync); none where it cannot move, nor while it moves. public AsyncRelayCommand MoveCommand { get; } = new(services?.Move ?? (() => Task.CompletedTask), () => services?.Move is not null && !services.IsMoving()); public bool CanMove => services?.Move is not null; /// The move button's tooltip: what it does, or that a move is under way. public string MoveToolTip => IsMoving ? Loc.L("Errors.Workspace.Moving") : Loc.L("Tooltips.Settings.Workspace.Move"); /// "12.4 GB used" (the whole folder, its trash included); "Measuring…" meanwhile; null before the first measure or when it failed. public string? UsageText => _isMeasuring ? Loc.L("Settings.Workspace.Measuring") : _usage is { } usage ? Loc.L("Settings.Workspace.Used", Formatting.Bytes(usage.TotalBytes)) : null; /// The usage line shows. public bool HasUsageText => UsageText is not null; public bool IsMeasuring => _isMeasuring; // ---------------- Size limit ---------------- /// The presets in GB, a value set elsewhere among them, then No limit (0). public IReadOnlyList> SizeLimitChoices => [ .. With(SizeLimitPresets, SizeLimit).Where(n => n > 0).Select(n => new SettingsOption(n, Loc.L("Common.Size.GB", Formatting.Count(n)))), new(0, Loc.L("Settings.Workspace.NoLimit")), ]; public SettingsOption 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)); } } /// What the limit chosen does: removes the oldest media past it, or nothing at all. 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> KeptChoices => [.. With(KeptPresets, Kept).Select(n => new SettingsOption(n, Loc.Plural("Settings.Workspace.Versions", n)))]; public SettingsOption 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 ---------------- /// The presets in days, a value set elsewhere among them, then Never (0). public IReadOnlyList> CleanAfterChoices => [ .. With(CleanAfterPresets, CleanAfter).Where(n => n > 0).Select(n => new SettingsOption(n, Loc.Plural("Settings.Workspace.Days", n))), new(0, Loc.L("Settings.Workspace.Never")), ]; public SettingsOption 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)); } } /// What the age chosen does: removes the media of projects not opened so long, or never. 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 ---------------- /// "3 items, 1.2 GB", "Nothing in trash", "Measuring…" meanwhile; null before the first measure or when it failed. 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)); /// The trash holds something, as measured last: Empty… is enabled. public bool HasTrash => _usage is { TrashItems: > 0 }; /// Lists the trash, asks for the typed number of its entries, then erases them (). public AsyncRelayCommand EmptyTrashCommand => _emptyTrash ??= new AsyncRelayCommand((_, token) => EmptyTrashAsync(token), _ => services is not null && HasTrash && !_isMeasuring); private AsyncRelayCommand? _emptyTrash; /// Empty…'s tooltip: what it does, or that there is nothing to erase. public string EmptyTrashToolTip => Loc.L(HasTrash ? "Tooltips.Settings.Workspace.EmptyTrash" : "Tooltips.Settings.Workspace.EmptyTrash.Disabled"); /// /// 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. /// 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); } } } /// /// Empty…: the trash's plan (nothing erased), its confirmation with the number of entries typed /// (), 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. /// 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(); } } /// /// 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. /// 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 { 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 ---------------- /// /// 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. /// 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(); } /// Labels in the current language, values as the settings have them now. internal void Refresh() => OnAllPropertiesChanged(); private bool IsMoving => services?.IsMoving() ?? false; /// The value the workspace applies: at least one version. private int Kept => Math.Max(1, settings.WorkspaceKeptVersions); /// The limit the clean-up applies: none below 1 GB. private int SizeLimit => Math.Max(0, settings.WorkspaceSizeLimitGb); /// The age the clean-up applies: never below 1 day. private int CleanAfter => Math.Max(0, settings.WorkspaceCleanAfterDays); /// Open in workspace copies the originals; any other value stored reads as the proxies, as the open dialog takes it. 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(); } /// /// Stores a choice that differs from the stored value (, 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. /// private bool Store(SettingsOption? choice, int current, Action 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 With(int[] presets, int current) => (presets.Contains(current) ? presets : presets.Append(current)).Order(); }