The convert endpoint planned the whole selection inside the HTTP request, again for every mode, quality keystroke and confirmation, with no limit: behind a proxy an all-sequence conversion could never get past its dry run or its apply. - ReorganizePlanCache becomes PlanCache, shared by Reorganize and Convert: one plan per key made apart from the request, two at once across both kinds, eight kept, 15-minute timeout, 5-minute lifetime, 503 plan_dropped. Keys are typed records (ReorganizePlanKey, ConvertPlanKey) that also say which exceptions are refusals. - A conversion plan is keyed by archive, a convert stamp of the index (SequenceRepository.GetConvertStampAsync: the Reorganize stamp plus, per planned sequence, the photos' count, sizes, formats, pixel sizes and missing, corrupt, preview-only and undecodable flags), the sequences and the target with the quality that counts. Not the mode: the request's mode and options are set on the kept plan, and the free space is measured again at every request through the engine. A plan made while the volume was away is not kept (503 archive_offline). - New sequence holds the converted copies alone: the dry run says the skipped photos are not copied into it (Archive.Convert.NotCopied.*, Server.Convert.OnPcNew), the panel's totals, column and confirmation give the count, and so does the desktop's summary. - Panel: the preview is asked in Replace's neutral words; a dry run cut off by a proxy is asked again while the totals show how long it takes, plan_dropped is retried once; an apply the server let go plans again, a changed one shows Admin.Convert.PlanChanged, and one with no answer is not resent (its job may be queued). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit f0b1e379ce7c08b6d3459ab25ca6214c8f366f6c)
372 lines
15 KiB
C#
372 lines
15 KiB
C#
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,
|
||
_ => OnCommitted(), () => 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;
|
||
// The rows say what becomes of the photos skipped in the mode's words: not copied into a new sequence.
|
||
lock (_gate)
|
||
{
|
||
if (_run.Plan is { } plan) _run = _run with { Rows = RowsOf(plan) };
|
||
}
|
||
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, RowsOf(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 = RowsOf(plan) };
|
||
}
|
||
base.OnLanguageChanged();
|
||
}
|
||
|
||
/// <summary>The rows of <paramref name="plan"/> in the mode chosen (as planned while none is: the skipped photos stay as they are).</summary>
|
||
private IReadOnlyList<ConvertRow> RowsOf(ConvertPlan plan) => ConvertPlans.Rows(_mode is { } mode ? plan with { Mode = mode } : plan);
|
||
|
||
/// <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();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Enter, or the focus leaving the quality, plans at once, unless the dry run on screen or the one under way is already of
|
||
/// these options: a click on Apply takes the focus from the field first, and an identical dry run started then would turn
|
||
/// Apply off under the click.
|
||
/// </summary>
|
||
private void OnCommitted()
|
||
{
|
||
if (IsPlanned()) _delay.Stop();
|
||
else _ = PlanAsync();
|
||
}
|
||
|
||
/// <summary>The options on screen have their plan, or a dry run of them is under way; false after a failed one.</summary>
|
||
private bool IsPlanned()
|
||
{
|
||
lock (_gate) return _run.For is { } options && options == Current() && (_run.Plan is not null || _planning is not null);
|
||
}
|
||
|
||
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);
|
||
// In the mode chosen now: it may have been chosen while the plan was made.
|
||
result = new DryRun(options, plan, RowsOf(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);
|
||
}
|