feat(app): Convert sequences from the Archive manager and the Library, with Undo after a Replace

Owner review 2, R7 asks for mass conversion after import on the desktop too, with a choice at
every run between Replace and New sequence. The desktop now uses the engine's conversion, the
same plan and job as the web panel.

- Convert... in the Archive manager's mass operations (the set) and the Library's mass bar (the
  selection of one archive; server cards are left out, two archives are refused with their own
  reason). The dialog has the format (JPEG, TIFF 16-bit, Linear DNG, the archival default), a
  JPEG's quality (1-100, 95) and the mode, which starts unchosen at every open: Apply waits for
  it. Each choice has a tooltip that says what becomes of the originals.
- The dry run stays in the dialog and follows the choices: each sequence with its photos and
  sizes before and after, the photos that stay as they are with why, the sequences left as they
  are (busy, offline, unreadable), a summary and the free space line; a volume without the space
  blocks Apply. The mode does not change what converts, so choosing it plans nothing again.
- Apply asks to type the number of photos a Replace replaces, then queues the convert job of
  exactly the plan shown; New sequence leaves the originals as they are and asks nothing.
- When a Replace job ends, its toast offers Undo: for each sequence it converted, the newest
  Replaced trash entry made while it ran goes back (a sequence changed since gets its originals
  as a new sequence). Undo runs once and never from the Windows notification.
- The Library and the Archive screen read the sequences again after a conversion; --capture
  renders archive-convert from a sample plan.
- Strings in en and it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 275469284f895fc92e2569339809e18bf59d1d6a)
(cherry picked from commit 76ba41f58983275ae4b1478edd403efb11da7c79)
This commit is contained in:
Alby96 committed 2026-10-27 22:02:04 +01:00
1 parent 2143a093a2
commit a1c1c21ebd
25 files changed
+1409 -19

No files matched your search

@@ -0,0 +1,345 @@
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>
/// Convert… (owner review 2, R7; BRIEF §12.2, §12.5): the photos of a set of sequences, or of every sequence of the archive,
/// converted to JPEG, 16-bit TIFF or linear DNG. The format starts on the archival one (<see cref="ConvertOptions.ArchivalTarget"/>)
/// and the JPEG quality on <see cref="ConvertOptions.DefaultQuality"/>; the mode starts unchosen, so every run says whether
/// the converted files replace the photos (the originals go to the archive's trash) or go into new sequences (the originals
/// stay as they are). The dry run (the engine's plan, nothing changes on disk) follows the choices and lists each sequence
/// with what converts and what stays as it is, a summary and the free space line. Apply asks to type the number of photos a
/// Replace replaces, then queues the conversion job of exactly that plan (<see cref="ArchiveJobs.Convert"/>): resumable,
/// paused and followed in Jobs; a sequence changed after the dry run is left as it is.
/// </summary>
public sealed class ConvertDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly IReadOnlyList<Guid>? _set;
private readonly Func<ArchiveJobRequest, Task> _enqueue;
private readonly Func<ConfirmRequest, bool> _confirm;
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
/// <summary>Guards <see cref="_planning"/> and <see cref="_run"/>: only the latest dry run started ever publishes its result.</summary>
private readonly Lock _gate = new();
private DryRun _run = new(null);
private CancellationTokenSource? _planning;
private ConvertTarget _target = ConvertOptions.ArchivalTarget;
private ConvertMode? _mode;
/// <param name="set">The sequences to convert; null for every sequence of <paramref name="archive"/>.</param>
/// <param name="enqueue">Queues the conversion job and says so.</param>
/// <param name="confirm">Asks the typed confirmation of a Replace; true when the user typed it and chose Replace.</param>
public ConvertDialogViewModel(ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Guid>? set, Func<ArchiveJobRequest, Task> enqueue,
Func<ConfirmRequest, bool> confirm, Action<ArchiveDialogViewModel> close)
: base(close)
{
ArgumentNullException.ThrowIfNull(archive);
_archives = archives;
_archive = archive;
_set = set;
_enqueue = enqueue;
_confirm = confirm;
// Only a JPEG has a quality: for the other formats the field neither counts nor blocks.
Quality = new EditableField(ConvertOptions.DefaultQuality.ToString(Loc.Culture), t => _target == ConvertTarget.Jpeg ? ConvertPlans.ValidateQuality(t) : null,
committed => _ = PlanAsync(), () => Loc.L("Tooltips.Archive.ConvertQuality"));
Quality.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) OnTyped();
};
_delay.Tick += (_, _) => _ = PlanAsync();
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
/// <summary>"Convert 36 sequences", or "Convert ChronosArchive" for every sequence.</summary>
public string Heading => _set is null ? Loc.L("Archive.Convert.HeadingAll", _archive.Name) : Loc.Plural("Archive.Convert.Heading", _set.Count);
/// <summary>The format the converted files have; a change plans again.</summary>
public ConvertTarget Target
{
get => _target;
set
{
if (!Enum.IsDefined(value) || !Set(ref _target, value)) return;
// The quality's problem counts for a JPEG only.
Quality.Refresh();
OnPropertyChanged(nameof(IsJpeg));
OnPropertyChanged(nameof(IsTiff16));
OnPropertyChanged(nameof(IsLinearDng));
OnPropertyChanged(nameof(IsQualityEnabled));
_ = PlanAsync();
}
}
public bool IsJpeg
{
get => _target == ConvertTarget.Jpeg;
set
{
if (value) Target = ConvertTarget.Jpeg;
}
}
public bool IsTiff16
{
get => _target == ConvertTarget.Tiff16;
set
{
if (value) Target = ConvertTarget.Tiff16;
}
}
public bool IsLinearDng
{
get => _target == ConvertTarget.LinearDng;
set
{
if (value) Target = ConvertTarget.LinearDng;
}
}
/// <summary>The JPEG quality, 1–100; typing plans again once it pauses, Enter at once.</summary>
public EditableField Quality { get; }
public bool IsQualityEnabled => _target == ConvertTarget.Jpeg;
/// <summary>What becomes of the originals, chosen at every run; null until the user picks one, and Apply waits for it.</summary>
public ConvertMode? Mode
{
get => _mode;
set
{
if (value is { } mode && !Enum.IsDefined(mode)) return;
if (!Set(ref _mode, value)) return;
OnPropertyChanged(nameof(IsReplace));
OnPropertyChanged(nameof(IsNewSequence));
OnPlanChanged();
}
}
public bool IsReplace
{
get => _mode == ConvertMode.Replace;
set
{
if (value) Mode = ConvertMode.Replace;
}
}
public bool IsNewSequence
{
get => _mode == ConvertMode.NewSequence;
set
{
if (value) Mode = ConvertMode.NewSequence;
}
}
/// <summary>The last dry run, one row per sequence that converts or keeps photos as they are, in the order the job takes them.</summary>
public IReadOnlyList<ConvertRow> Rows => _run.Rows ?? [];
/// <summary>
/// The plan of the options on screen, in the mode chosen (as planned while none is); null while it is made, when it
/// failed, or once the options changed. The mode does not change what converts, so choosing it plans nothing again.
/// </summary>
public ConvertPlan? Plan => _run is { Plan: { } plan } run && run.For is { } options && options == Current()
? _mode is { } mode ? plan with { Mode = mode } : plan
: null;
public string SummaryText => Plan is { } plan ? ConvertPlans.Summary(plan) : string.Empty;
/// <summary>The free space line of a dry run that converts something; null otherwise.</summary>
public string? SpaceText => Plan is { Frames: > 0 } plan ? ConvertPlans.Space(plan.Space).Text : null;
/// <summary>The archive's volume lacks the space the conversion needs: the line is a warning and Apply waits.</summary>
public bool IsSpaceShort => Plan is { Frames: > 0 } plan && !plan.Space.Enough;
/// <summary>The space line shows and says nothing is missing (or that the free space cannot be measured).</summary>
public bool IsSpaceFine => Plan is { Frames: > 0 } plan && plan.Space.Enough;
/// <summary>Asks the typed confirmation of a Replace, then queues the job of the plan on screen and closes.</summary>
public ICommand ApplyCommand { get; }
public string ApplyToolTip => ApplyBlocker
?? Loc.L(_mode == ConvertMode.Replace ? "Tooltips.Archive.ConvertApplyReplace" : "Tooltips.Archive.ConvertApplyNew");
/// <summary>Why Apply is disabled; null when it can run. The mode is asked last: first whether there is anything to convert.</summary>
private string? ApplyBlocker
{
get
{
if (IsBusy) return Loc.L("Archive.Blocked.Applying");
if (Quality.Error is { } quality) return quality;
var run = _run;
if (run.For is null || run.For != Current()) return Loc.L("Archive.Blocked.Planning");
if (run.Plan is not { } plan) return run.Error ?? Loc.L("Archive.Blocked.Planning");
if (plan.Frames == 0) return Loc.L("Archive.Blocked.NothingToConvert");
if (!plan.Space.Enough) return ConvertPlans.Space(plan.Space).Text;
return _mode is null ? Loc.L("Archive.Blocked.NoMode") : null;
}
}
/// <summary>The format and quality on screen, as the engine takes them; null while the quality of a JPEG cannot be used.</summary>
public ConvertOptions? Current()
{
if (Quality.Error is not null) return null;
return new ConvertOptions(_target, _target == ConvertTarget.Jpeg ? ConvertPlans.ParseQuality(Quality.Text) : ConvertOptions.DefaultQuality);
}
/// <summary>
/// The dry run of the options on screen; it clears the last failure and stands in for one still waiting on typing.
/// </summary>
public Task PlanAsync()
{
_delay.Stop();
ClearError();
return DryRunAsync();
}
/// <summary>Shows a dry run made elsewhere (capture) as the one of the options on screen.</summary>
public void Show(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
_delay.Stop();
lock (_gate)
{
_planning?.Cancel();
_planning = null;
_run = new DryRun(Current(), plan, ConvertPlans.Rows(plan));
}
BusyText = null;
ClearError();
OnPlanChanged();
}
public override void Dispose()
{
_delay.Stop();
lock (_gate) _planning?.Cancel();
base.Dispose();
}
/// <summary>The rows, the quality's message, the summary and the space line in the new language.</summary>
protected override void OnLanguageChanged()
{
Quality.Refresh();
lock (_gate)
{
if (_run.Plan is { } plan) _run = _run with { Rows = ConvertPlans.Rows(plan) };
}
base.OnLanguageChanged();
}
/// <summary>Typing makes the dry run on screen old at once (Apply waits) and plans again once the typing pauses.</summary>
private void OnTyped()
{
OnPlanChanged();
_delay.Stop();
_delay.Start();
}
private async Task DryRunAsync()
{
var options = Current();
var cts = options is null ? null : new CancellationTokenSource();
lock (_gate)
{
_planning?.Cancel();
_planning = cts;
_run = new DryRun(options);
}
BusyText = cts is null ? null : Loc.L("Archive.Reorganize.Planning");
OnPlanChanged();
if (cts is null) return;
var set = _set;
// What converts is the same in either mode: the plan made with one serves the other (Plan).
var mode = _mode ?? ConvertMode.Replace;
DryRun result;
Exception? failure = null;
try
{
var plan = await Task.Run(() => _archives.PlanConvertAsync(_archive.Id, set, options!, mode, cts.Token), cts.Token);
result = new DryRun(options, plan, ConvertPlans.Rows(plan));
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
// A newer dry run took its place, or the dialog closed.
result = new DryRun(options);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", "Conversion dry run failed", ex);
failure = ex;
result = new DryRun(options, Error: ArchiveFailures.Cause(ex));
}
bool latest;
lock (_gate)
{
latest = ReferenceEquals(_planning, cts);
if (latest)
{
_planning = null;
_run = result;
}
}
cts.Dispose();
if (!latest) return;
BusyText = null;
if (failure is not null) ShowError(failure);
OnPlanChanged();
}
private void OnPlanChanged()
{
OnPropertyChanged(nameof(Rows));
OnPropertyChanged(nameof(Plan));
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(SpaceText));
OnPropertyChanged(nameof(IsSpaceShort));
OnPropertyChanged(nameof(IsSpaceFine));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private async Task ApplyAsync()
{
if (ApplyBlocker is not null || Plan is not { } plan || _mode is not { } mode) return;
ClearError();
// Replace changes the photos of the archive: the number of photos it replaces is typed first.
if (mode == ConvertMode.Replace && (ConvertPlans.ReplaceRequest(plan) is not { } request || !_confirm(request))) return;
IsBusy = true;
try
{
await _enqueue(ArchiveJobs.Convert(_archive, plan));
Log.Info("archive", $"Conversion of {plan.Frames} photo(s) in {plan.Converted.Count()} sequence(s) of {_archive.RootPath} to {plan.Options.Target} ({mode}) queued");
}
catch (DatabaseException ex)
{
Log.Warning("archive", "The conversion was not queued", ex);
ShowError(ex);
return;
}
finally
{
IsBusy = false;
}
Close();
}
/// <summary>A dry run: the options it is for and, once it ended, its plan and rows, or why it failed.</summary>
private sealed record DryRun(ConvertOptions? For, ConvertPlan? Plan = null, IReadOnlyList<ConvertRow>? Rows = null, string? Error = null);
}