Files
Chronos/src/Chronos.App/Archive/TrashDialogViewModel.cs
T
Alby96andClaude Opus 5.5 efa87f68ce
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s
feat: owner review 2 phase 4b: mass conversion after import (#13)
Convert photos already in the archive to JPEG, TIFF-16 or Linear DNG, from the panel's Library and the desktop's Archive and Library. Each run asks Replace (same frames, originals to the trash, recoverable) or New sequence. A dry run lists what converts, what is skipped and why, size before and after, and free space; the job converts exactly the confirmed photos, resumes, and commits all or nothing per sequence. A conversion never changes what Chronos reads from a photo. Replaced originals are erased only on the archive's own word that their conversion is gone. Desktop TIFFs that WIC showed black or as noise now go to the managed reader; the Edit picker no longer spins a core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-03 10:41:50 +01:00

263 lines
12 KiB
C#

using System.Globalization;
using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>One entry of the trash: a deleted sequence or photos deleted from one, when it went, and Restore.</summary>
public sealed class TrashRowViewModel(TrashEntry entry, ICommand restore)
{
public TrashEntry Entry { get; } = entry;
public string Title => Entry.Title;
/// <summary>"Photos", "Sequence": what the entry holds.</summary>
public string KindText => TrashEmptyPlans.KindText(Entry.Kind);
/// <summary>"Photos · 12 photos · 340 MB · 2026/2026-09-28 Canon EOS R5" (the folder left to right in every language).</summary>
public string Detail => string.Join(Loc.Separator, KindText, Loc.Plural("Shell.Status.Photos", Entry.Frames), Formatting.Bytes(Entry.Bytes),
Formatting.LeftToRight(Entry.Folder));
/// <summary>"Deleted 02/10/2026 18:04".</summary>
public string DeletedText => Loc.L("Archive.Trash.Deleted", Formatting.Date(Entry.DeletedAt) + " " + Formatting.TimeOfDay(Entry.DeletedAt));
public ICommand RestoreCommand { get; } = restore;
}
/// <summary>The words of an emptying of the trash (<see cref="TrashEmptyPlan"/>): the destructive, typed confirmation.</summary>
public static class TrashEmptyPlans
{
/// <summary>"Photos", "Sequence", "Replaced".</summary>
public static string KindText(TrashKind kind) => Loc.L("Archive.Trash.Kind." + kind);
/// <summary>
/// The confirmation of erasing the planned entries for good; null when the plan holds none. An entry of replaced originals
/// whose conversion was deleted since says so (<see cref="TrashEntry.ConversionDeleted"/>): erasing it may erase the last
/// copy of those photos, so every such entry is named first, with why, wherever the trash lists it; the other entries
/// fill the lines left (<see cref="DeletePlans.ListedLines"/>) and the rest are counted.
/// </summary>
public static ConfirmRequest? Request(TrashEmptyPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.Entries.Count == 0) return null;
var count = plan.Entries.Count.ToString(CultureInfo.InvariantCulture);
var lastCopies = plan.Entries.Where(e => e.ConversionDeleted).ToList();
var others = plan.Entries.Where(e => !e.ConversionDeleted).ToList();
var listed = Math.Max(0, DeletePlans.ListedLines - lastCopies.Count);
var lines = lastCopies.Concat(others.Take(listed)).Select(e => Loc.L("Archive.Delete.Line", e.Title,
KindText(e.Kind) + Loc.Separator + Loc.Plural("Shell.Status.Photos", e.Frames)
+ (e.ConversionDeleted ? Loc.Separator + Loc.L("Archive.Trash.ConversionDeleted") : string.Empty), Formatting.Bytes(e.Bytes))).ToList();
if (others.Count > listed) lines.Add(Loc.Plural("Archive.Delete.More", others.Count - listed));
return new ConfirmRequest
{
Heading = Loc.Plural("Archive.Trash.EmptyHeading", plan.Entries.Count),
Message = Loc.L("Archive.Trash.EmptyMessage", Loc.Plural("Shell.Status.Photos", plan.Photos), Loc.Plural("Archive.Delete.Files", plan.Files),
Formatting.Bytes(plan.Bytes)),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Archive.TrashEmptyPlan"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
ActionText = Loc.L("Archive.Trash.Erase"),
ActionToolTip = Loc.Plural("Tooltips.Archive.TrashErase", plan.Entries.Count),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Archive.Delete.Type", count),
};
}
}
/// <summary>
/// The archive's trash (BRIEF §0.2 rule 8, §12.5): every sequence deleted from the Library or the Archive manager and the
/// photos deleted from sequences (owner review 2, R6), newest first, each restorable — a sequence into its folder (or a
/// free one next to it) with its ids, settings and renders, photos into their sequence after their files are re-hashed.
/// Empty… erases the entries for good: a dry run, a typed confirmation, then the <c>EmptyTrash</c> job, which refuses when
/// the trash changed since.
/// </summary>
public sealed class TrashDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly Func<Task> _restored;
private readonly Func<ConfirmRequest, bool>? _confirm;
private readonly Func<ArchiveJobRequest, Task>? _enqueue;
private readonly JobEngine? _followUps;
private IReadOnlyList<TrashRowViewModel> _rows = [];
/// <param name="confirm">Asks the typed confirmation of an emptying (null: the trash cannot be emptied here).</param>
/// <param name="enqueue">Queues the emptying job and says so (null: the trash cannot be emptied here).</param>
/// <param name="followUps">The engine that takes the analyses and images restored photos need again.</param>
public TrashDialogViewModel(ArchiveService archives, Core.Model.Archive archive, Func<Task> restored, Action<ArchiveDialogViewModel> close,
Func<ConfirmRequest, bool>? confirm = null, Func<ArchiveJobRequest, Task>? enqueue = null, JobEngine? followUps = null)
: base(close)
{
_archives = archives;
_archive = archive;
_restored = restored;
_confirm = confirm;
_enqueue = enqueue;
_followUps = followUps;
EmptyCommand = new AsyncRelayCommand(EmptyAsync, () => CanEmpty);
}
public string Heading => Loc.L("Archive.Trash.Heading", _archive.Name);
public IReadOnlyList<TrashRowViewModel> Rows
{
get => _rows;
private set
{
if (!Set(ref _rows, value)) return;
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(EmptyToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
public bool IsEmpty => _rows.Count == 0;
/// <summary>The list shows; an empty trash is its summary sentence alone.</summary>
public bool HasRows => _rows.Count > 0;
/// <summary>"3 entries · 182 GB", or "The trash is empty".</summary>
public string SummaryText => _rows.Count == 0 ? Loc.L("Archive.Trash.Empty")
: Loc.Plural("Archive.Trash.Entries", _rows.Count) + Loc.Separator + Formatting.Bytes(_rows.Sum(r => r.Entry.Bytes));
/// <summary>Empty…: the dry run, the typed confirmation, then the job.</summary>
public ICommand EmptyCommand { get; }
/// <summary>Emptying is offered here, and there is something to erase.</summary>
public bool CanEmpty => !IsBusy && HasRows && _confirm is not null && _enqueue is not null;
public string EmptyToolTip => HasRows ? Loc.L("Tooltips.Archive.TrashEmpty") : Loc.L("Archive.Trash.Empty");
/// <summary>Reads the trash of the archive (off the UI thread).</summary>
public async Task LoadAsync()
{
ClearError();
BusyText = Loc.L("Archive.Trash.Reading");
try
{
var entries = await Task.Run(() => _archives.ListTrashAsync(_archive.Id));
Rows = [.. entries.Select(Row)];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
{
Log.Warning("archive", "Reading the trash failed", ex);
ShowError(ex);
}
finally
{
BusyText = null;
}
}
/// <summary>Shows entries read elsewhere (capture).</summary>
public void Show(IReadOnlyList<TrashEntry> entries) =>
Rows = [.. entries.Select(e => new TrashRowViewModel(e, new AsyncRelayCommand(() => Task.CompletedTask)))];
private TrashRowViewModel Row(TrashEntry entry) => new(entry, new AsyncRelayCommand(() => RestoreAsync(entry), () => !IsBusy));
private async Task RestoreAsync(TrashEntry entry)
{
ClearError();
IsBusy = true;
BusyText = Loc.L("Archive.Trash.Restoring", entry.Title);
try
{
var result = await Task.Run(() => _archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, _followUps));
Log.Info("archive", $"{entry.Title} restored from the trash ({entry.Kind}, {result.Photos} photo(s), {result.Kept.Count} kept)");
BusyText = null;
if (result.Kept.Count > 0)
{
// Photos that stay in the trash keep their entry, with what is left; the line says how many stayed and why,
// and the tooltip repeats it with their names.
await LoadAsync();
var (text, tip) = KeptText(result.Kept);
ShowMessage(text, tip);
}
else
{
Rows = [.. _rows.Where(r => r.Entry != entry)];
}
await _restored();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or SequenceInLibraryException or NewerFormatException
or DatabaseException or ArgumentException)
{
Log.Warning("archive", $"Restoring {entry.Title} failed", ex);
ShowError(ex);
}
finally
{
IsBusy = false;
BusyText = null;
}
}
/// <summary>
/// The line of what a restore kept in the trash, and its tooltip: one reason's sentence ("2 photos stayed in the trash:
/// they could not be moved back."), or how many stayed when they stayed for different reasons. The tooltip holds that
/// line, then each reason's sentence (when there are several) with its photos' names, one per line, the names counted
/// past <see cref="DeletePlans.ListedLines"/> in all.
/// </summary>
internal static (string Text, string ToolTip) KeptText(IReadOnlyList<KeptPhoto> kept)
{
var groups = kept.GroupBy(k => k.Reason).OrderBy(g => g.Key).ToList();
var text = groups.Count == 1 ? KeptPhoto.Sentence(groups[0].Key, groups[0].Count(), Loc.Culture) : Loc.Plural("Archive.Trash.KeptPhotos", kept.Count);
var lines = new List<string> { text };
var listed = 0;
foreach (var group in groups)
{
if (groups.Count > 1) lines.Add(KeptPhoto.Sentence(group.Key, group.Count(), Loc.Culture));
foreach (var photo in group)
{
if (listed++ < DeletePlans.ListedLines) lines.Add(Formatting.LeftToRight(photo.Name));
}
}
if (kept.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Trash.KeptMore", kept.Count - DeletePlans.ListedLines));
return (text, string.Join(Environment.NewLine, lines));
}
/// <summary>
/// Empty…: measures every entry (the dry run), asks to type how many entries go, and queues the job that erases exactly
/// those; the dialog closes, and the job says how it ended.
/// </summary>
private async Task EmptyAsync()
{
if (_confirm is null || _enqueue is null) return;
ClearError();
IsBusy = true;
BusyText = Loc.L("Archive.Trash.Checking");
TrashEmptyPlan plan;
try
{
plan = await Task.Run(() => _archives.PlanEmptyTrashAsync(_archive.Id));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or ArgumentException)
{
Log.Warning("archive", "The dry run of emptying the trash failed", ex);
ShowError(ex);
return;
}
finally
{
IsBusy = false;
BusyText = null;
}
if (TrashEmptyPlans.Request(plan) is not { } request || !_confirm(request)) return;
await _enqueue(ArchiveJobs.EmptyTrash(_archive, plan));
Close();
}
}