using System.IO; using System.Windows.Input; using Chronos.App.Infrastructure; using Chronos.App.Settings; using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Data; using Chronos.Data.Archiving; using Chronos.Ui.Mvvm; namespace Chronos.App.Archiving; /// /// An in-window dialog of the Archive screen: one primary action, one way out. While its action runs, the way out /// stops it when it can be stopped, and is disabled otherwise; the close callback receives the dialog, so a late close /// never closes another one. A failure stays on screen as one sentence until the next attempt. /// public abstract class ArchiveDialogViewModel : LocalizedViewModel { private readonly Action _close; private bool _isBusy; private string? _busyText; private string? _errorText; private string? _errorToolTip; protected ArchiveDialogViewModel(Action close) { _close = close; CloseCommand = new RelayCommand(() => { if (IsBusy) Stop(); else Close(); }, () => !IsBusy || CanStop); } /// Cancel: closes the dialog, or stops its running action. public ICommand CloseCommand { get; } public string CloseToolTip => !IsBusy ? Loc.L("Tooltips.Archive.CloseDialog") : CanStop ? Loc.L("Tooltips.Archive.StopApply") : Loc.L("Archive.Blocked.Applying"); /// The running action can stop between two steps. protected virtual bool CanStop => false; protected virtual void Stop() { } public bool IsBusy { get => _isBusy; protected set { if (!Set(ref _isBusy, value)) return; OnPropertyChanged(nameof(CloseToolTip)); CommandManager.InvalidateRequerySuggested(); } } public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); } /// Why the last dry run or apply stopped (), or what it left undone; null when nothing failed. public string? ErrorText { get => _errorText; private set => Set(ref _errorText, value); } /// /// The tooltip of : the whole sentence (the line may cut it), then the failure as the engine /// reported it, or what a names. /// public string? ErrorToolTip { get => _errorToolTip; private set => Set(ref _errorToolTip, value); } protected void Close() => _close(this); protected void ShowError(Exception ex) { ErrorText = ArchiveFailures.Cause(ex); ErrorToolTip = ex.Message == ErrorText ? ErrorText : ErrorText + Environment.NewLine + ex.Message; } /// /// Shows a sentence localized already, such as what an action that half succeeded left undone; /// details it, and repeats the sentence first (the line may cut it). /// protected void ShowMessage(string text, string? tip = null) { ErrorText = text; ErrorToolTip = tip is null || tip.StartsWith(text, StringComparison.Ordinal) ? tip ?? text : text + Environment.NewLine + tip; } protected void ClearError() { ErrorText = null; ErrorToolTip = null; } } /// A fact of the rebuild dialog ("Sidecars · 412"); a path stays left to right, a missing value says why in its tooltip. public sealed record DialogFact(string Label, string Value, bool IsPath = false, string? Reason = null) { public string ToolTip => Reason ?? Value; } /// /// "Rebuild index" (BRIEF §12.5): what the rebuild reads — the sidecars on disk, then a full metadata scan of folders /// without one — next to what the index holds now. Originals are never touched; the rebuild runs as a job. /// public sealed class RebuildDialogViewModel : ArchiveDialogViewModel { private readonly Func _rebuild; private IReadOnlyList _facts; public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func rebuild, Action close) : base(close) { _rebuild = rebuild; Archive = archive; Availability = availability; Indexed = indexed; _facts = Facts(null, availability == ArchiveAvailability.Offline ? Loc.L("Archive.Error.Offline", Formatting.LeftToRight(archive.RootPath)) : null); RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online); } public Core.Model.Archive Archive { get; } public ArchiveAvailability Availability { get; } public int Indexed { get; } public IReadOnlyList FactRows { get => _facts; private set => Set(ref _facts, value); } public ICommand RebuildCommand { get; } public string RebuildToolTip => Availability == ArchiveAvailability.Online ? Loc.L("Tooltips.Archive.RebuildStart") : Loc.L("Archive.Blocked.NotOnline"); /// /// Counts sequence folders with and without a sidecar (a walk of the archive tree, off the UI thread). The counts /// read "Counting…" only while the walk runs; an offline archive or a failed walk leaves "—" with the reason. /// public async Task CountAsync() { if (Availability == ArchiveAvailability.Offline) return; BusyText = Loc.L("Archive.Rebuild.Counting"); try { var root = Archive.RootPath; var folders = await Task.Run(() => ArchiveScanner.FindSequenceFolders(new ArchivePaths(root))); FactRows = Facts(folders, null); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Warning("archive", "Counting sidecars failed", ex); FactRows = Facts(null, ArchiveFailures.Cause(ex)); } finally { BusyText = null; } } /// Shows counts computed elsewhere (capture). public void ShowFolders(IReadOnlyList folders) => FactRows = Facts(folders, null); /// The counted folders; null while counting or when they cannot be counted. /// Why the folders cannot be counted; null while counting. private IReadOnlyList Facts(IReadOnlyList? folders, string? uncounted) { DialogFact Count(string label, Func counted) => folders is not null ? new(label, Formatting.Count(folders.Count(counted))) : uncounted is not null ? new(label, "—", Reason: uncounted) : new(label, Loc.L("Archive.Rebuild.Counting")); return [ new(Loc.L("Archive.Rebuild.Archive"), Archive.Name), new(Loc.L("Archive.Rebuild.Root"), Archive.RootPath, IsPath: true), new(Loc.L("Archive.Rebuild.State"), Loc.L("Archive.Availability." + Availability)), new(Loc.L("Archive.Rebuild.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)), Count(Loc.L("Archive.Rebuild.Sidecars"), f => f.Sidecar is not null), Count(Loc.L("Archive.Rebuild.Metadata"), f => f.Sidecar is null), ]; } private async Task RebuildAsync() { IsBusy = true; try { await _rebuild(); Close(); } finally { IsBusy = false; } } } /// Add and remove tags on a set (BRIEF §12.5 Retag): the dry run counts the sequences that change. public sealed class RetagDialogViewModel : ArchiveDialogViewModel { private readonly ArchiveService _archives; private readonly IReadOnlyList _set; private readonly Func _applied; private CancellationTokenSource? _run; public RetagDialogViewModel(ArchiveService archives, IReadOnlyList set, Func applied, Action close) : base(close) { _archives = archives; _set = set; _applied = applied; Add = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsAdd")); Remove = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsRemove")); Add.PropertyChanged += (_, _) => OnTagsTyped(); Remove.PropertyChanged += (_, _) => OnTagsTyped(); ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null); } /// Why Apply is disabled; null when it can run. private string? ApplyBlocker => IsBusy ? Loc.L("Archive.Blocked.Applying") : Add.Error ?? Remove.Error ?? (Changes().Count == 0 ? Loc.L("Archive.Blocked.NoChanges") : null); public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RetagApply"); public string Heading => Loc.Plural("Archive.Retag.Heading", _set.Count); public EditableField Add { get; } public EditableField Remove { get; } /// "12 of 36 change". public string SummaryText => Loc.Plural("Archive.Rename.Summary", Changes().Count, _set.Count); public ICommand ApplyCommand { get; } /// Typing changes the dry run, and with it whether Apply can run. private void OnTagsTyped() { OnPropertyChanged(nameof(SummaryText)); OnPropertyChanged(nameof(ApplyToolTip)); CommandManager.InvalidateRequerySuggested(); } private IReadOnlyList<(Sequence Sequence, IReadOnlyList Tags)> Changes() => Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text)); protected override bool CanStop => _run is not null; /// Stops after the sequence being written; each sequence is changed completely or not at all. protected override void Stop() => _run?.Cancel(); private async Task ApplyAsync() { var changes = Changes(); var (add, remove) = (Retag.Parse(Add.Text), Retag.Parse(Remove.Text)); var run = _run = new CancellationTokenSource(); var done = 0; ClearError(); IsBusy = true; try { for (; done < changes.Count && !run.IsCancellationRequested; done++) { var id = changes[done].Sequence.Id; BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(done + 1), Formatting.Count(changes.Count)); // The tags as they are now (the set may predate an edit or a sync); title, rating and notes stay untouched. await Task.Run(() => _archives.EditSequenceInfoAsync(id, info => info with { Tags = Retag.Apply(info.Tags, add, remove) })); } Log.Info("archive", $"Retag: {done} of {changes.Count} sequence(s) changed"); await _applied(done); Close(); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException) { Log.Warning("archive", "Retag failed", ex); ShowError(ex); } finally { _run = null; run.Dispose(); IsBusy = false; BusyText = null; } } }