Files
Chronos/src/Chronos.App/Archive/ArchiveDialogViewModels.cs
T
Alby96andClaude Opus 5.5 7e4a3b481d
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-27 21:58:39 +01:00

288 lines
11 KiB
C#

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;
/// <summary>
/// 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.
/// </summary>
public abstract class ArchiveDialogViewModel : LocalizedViewModel
{
private readonly Action<ArchiveDialogViewModel> _close;
private bool _isBusy;
private string? _busyText;
private string? _errorText;
private string? _errorToolTip;
protected ArchiveDialogViewModel(Action<ArchiveDialogViewModel> close)
{
_close = close;
CloseCommand = new RelayCommand(() =>
{
if (IsBusy) Stop();
else Close();
}, () => !IsBusy || CanStop);
}
/// <summary>Cancel: closes the dialog, or stops its running action.</summary>
public ICommand CloseCommand { get; }
public string CloseToolTip => !IsBusy ? Loc.L("Tooltips.Archive.CloseDialog")
: CanStop ? Loc.L("Tooltips.Archive.StopApply")
: Loc.L("Archive.Blocked.Applying");
/// <summary>The running action can stop between two steps.</summary>
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); }
/// <summary>Why the last dry run or apply stopped (<see cref="ArchiveFailures.Cause"/>), or what it left undone; null when nothing failed.</summary>
public string? ErrorText { get => _errorText; private set => Set(ref _errorText, value); }
/// <summary>
/// The tooltip of <see cref="ErrorText"/>: the whole sentence (the line may cut it), then the failure as the engine
/// reported it, or what a <see cref="ShowMessage"/> names.
/// </summary>
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;
}
/// <summary>
/// Shows a sentence localized already, such as what an action that half succeeded left undone; <paramref name="tip"/>
/// details it, and repeats the sentence first (the line may cut it).
/// </summary>
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;
}
}
/// <summary>A fact of the rebuild dialog ("Sidecars · 412"); a path stays left to right, a missing value says why in its tooltip.</summary>
public sealed record DialogFact(string Label, string Value, bool IsPath = false, string? Reason = null)
{
public string ToolTip => Reason ?? Value;
}
/// <summary>
/// "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.
/// </summary>
public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<Task> _rebuild;
private IReadOnlyList<DialogFact> _facts;
public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func<Task> rebuild,
Action<ArchiveDialogViewModel> 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<DialogFact> 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");
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>Shows counts computed elsewhere (capture).</summary>
public void ShowFolders(IReadOnlyList<SequenceFolder> folders) => FactRows = Facts(folders, null);
/// <param name="folders">The counted folders; null while counting or when they cannot be counted.</param>
/// <param name="uncounted">Why the folders cannot be counted; null while counting.</param>
private IReadOnlyList<DialogFact> Facts(IReadOnlyList<SequenceFolder>? folders, string? uncounted)
{
DialogFact Count(string label, Func<SequenceFolder, bool> 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;
}
}
}
/// <summary>Add and remove tags on a set (BRIEF §12.5 Retag): the dry run counts the sequences that change.</summary>
public sealed class RetagDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly IReadOnlyList<Sequence> _set;
private readonly Func<int, Task> _applied;
private CancellationTokenSource? _run;
public RetagDialogViewModel(ArchiveService archives, IReadOnlyList<Sequence> set, Func<int, Task> applied, Action<ArchiveDialogViewModel> 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);
}
/// <summary>Why Apply is disabled; null when it can run.</summary>
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; }
/// <summary>"12 of 36 change".</summary>
public string SummaryText => Loc.Plural("Archive.Rename.Summary", Changes().Count, _set.Count);
public ICommand ApplyCommand { get; }
/// <summary>Typing changes the dry run, and with it whether Apply can run.</summary>
private void OnTagsTyped()
{
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> 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;
/// <summary>Stops after the sequence being written; each sequence is changed completely or not at all.</summary>
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;
}
}
}