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

+94 -1
View File
@@ -6,7 +6,7 @@
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
xmlns:shell="clr-namespace:Chronos.App.Shell">
<!-- In-window dialogs of the archive engine's operations, shared by the Archive manager and the Library. -->
<!-- Dry-run rows only show text: focusable, so the arrow keys move through a long list; screen readers hear the name, then the changes. -->
<!-- Dry-run rows (Reorganize, Convert) only show text: focusable, so the arrow keys move through a long list; screen readers hear the name, then the changes. -->
<Style x:Key="ListBoxItem.Reorganize" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
@@ -198,6 +198,99 @@
</Border>
</DataTemplate>
<!-- Convert…: the format, a JPEG's quality and what becomes of the originals (chosen at every run, none at first); the dry run sequence by
sequence with the free space line; Apply asks to type the number of photos a Replace replaces, then queues the job of that plan. -->
<DataTemplate DataType="{x:Type ar:ConvertDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="600">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<Grid Grid.Row="1" Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Each group of choices is one row of radio buttons: the arrow keys move inside it, Tab to the next. -->
<TextBlock Text="{l:Loc Archive.Convert.Format}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,0,14,0" />
<WrapPanel Grid.Column="1" AutomationProperties.Name="{l:Loc Archive.Convert.Format}">
<RadioButton Content="{l:Loc Archive.Convert.Target.Jpeg}" IsChecked="{Binding IsJpeg}" ToolTip="{l:Loc Tooltips.Archive.ConvertJpeg}" Margin="0,4,18,4" />
<RadioButton Content="{l:Loc Archive.Convert.Target.Tiff16}" IsChecked="{Binding IsTiff16}" ToolTip="{l:Loc Tooltips.Archive.ConvertTiff}" Margin="0,4,18,4" />
<RadioButton Content="{l:Loc Archive.Convert.Target.LinearDng}" IsChecked="{Binding IsLinearDng}" ToolTip="{l:Loc Tooltips.Archive.ConvertDng}" Margin="0,4,18,4" />
</WrapPanel>
<TextBlock Grid.Row="1" Text="{l:Loc Archive.Convert.Quality}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,8,14,0"
IsEnabled="{Binding IsQualityEnabled}" />
<TextBox Grid.Row="1" Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left" Margin="0,8,0,0" IsEnabled="{Binding IsQualityEnabled}"
Text="{Binding Quality.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Quality}"
ToolTip="{Binding Quality.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Convert.Quality}" />
<TextBlock Grid.Row="2" Text="{l:Loc Archive.Convert.Mode}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,8,14,0" />
<WrapPanel Grid.Row="2" Grid.Column="1" Margin="0,4,0,0" AutomationProperties.Name="{l:Loc Archive.Convert.Mode}">
<RadioButton Content="{l:Loc Archive.Convert.Replace}" IsChecked="{Binding IsReplace}" ToolTip="{l:Loc Tooltips.Archive.ConvertModeReplace}" Margin="0,4,18,4" />
<RadioButton Content="{l:Loc Archive.Convert.NewSequence}" IsChecked="{Binding IsNewSequence}" ToolTip="{l:Loc Tooltips.Archive.ConvertModeNew}" Margin="0,4,18,4" />
</WrapPanel>
</Grid>
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" TextTrimming="CharacterEllipsis"
ToolTip="{Binding SummaryText}" Typography.NumeralAlignment="Tabular" />
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Reorganize}" MinHeight="140"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" VirtualizingPanel.ScrollUnit="Pixel" AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:ConvertRow}">
<StackPanel Margin="0,8" TextElement.FontSize="12">
<DockPanel>
<TextBlock DockPanel.Dock="Right" Text="{Binding Note}" Foreground="{DynamicResource Brush.TextMuted}" Margin="12,0,0,0" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" Visibility="{Binding HasNote, Converter={StaticResource BoolToVisibility}}" />
<TextBlock x:Name="Name" Text="{Binding Name}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" ToolTip="{Binding Name}" />
</DockPanel>
<!-- Why photos stay as they are, or why the whole sequence does, each line with its reason. -->
<ItemsControl ItemsSource="{Binding Kept}" Focusable="False" Visibility="{Binding HasKept, Converter={StaticResource BoolToVisibility}}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ui:StatusGlyph Kind="Warning" FontSize="12" Margin="0,4,0,0" Text="{Binding}" ToolTip="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsNamePath}" Value="True">
<Setter TargetName="Name" Property="FlowDirection" Value="LeftToRight" />
<Setter TargetName="Name" Property="HorizontalAlignment" Value="Left" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- The free space the converted files need on the archive's volume: a warning when it lacks it (Apply waits). -->
<Grid Grid.Row="4" Margin="0,8,0,0">
<TextBlock Text="{Binding SpaceText}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis" ToolTip="{Binding SpaceText}"
Typography.NumeralAlignment="Tabular" Visibility="{Binding IsSpaceFine, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph Kind="Warning" FontSize="12" Text="{Binding SpaceText}" ToolTip="{Binding SpaceText}" Typography.NumeralAlignment="Tabular"
AutomationProperties.LiveSetting="Polite" Visibility="{Binding IsSpaceShort, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<DockPanel Grid.Row="5" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rename.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True"
IsCancel="True" MinWidth="96" />
<Grid Margin="0,0,12,0">
<TextBlock Style="{StaticResource Text.Live}" Text="{Binding BusyText}" infra:LiveRegion.Text="{Binding BusyText}" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" />
</Grid>
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RetagDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
+12 -2
View File
@@ -5,11 +5,12 @@ namespace Chronos.App.Archiving;
/// <summary>
/// The Archive views that <c>--capture</c> renders (<c>archive-&lt;view&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
/// rebuild dialog, the Reorganize dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
/// rebuild dialog, the Reorganize dialog with its dry run, the Convert dialog with its dry run and New sequence chosen, and
/// the trash (Maintenance › Trash…) with deleted sequences.
/// </summary>
public static class ArchiveScenes
{
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "reorganize", "trash"];
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "reorganize", "convert", "trash"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
@@ -41,6 +42,15 @@ public static class ArchiveScenes
await reorganize.PlanAsync();
}
break;
case "convert":
archive.ViewIndex = 0;
await archive.OpenConvertDialogAsync();
if (archive.Dialog is ConvertDialogViewModel convert && archive.SelectedArchive is { } converted)
{
convert.Show(SampleReports.Convert(converted.Id, locations));
convert.Mode = Core.Conversion.ConvertMode.NewSequence;
}
break;
case "trash":
archive.ViewIndex = 1;
await archive.OpenTrashAsync();
@@ -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);
}
+130
View File
@@ -0,0 +1,130 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.Core.Conversion;
using Chronos.Core.Localization;
namespace Chronos.App.Archiving;
/// <summary>
/// One sequence of the conversion dry run (owner review 2, R7): its name, what converts (photos, size before and after),
/// and the photos that stay as they are or why the whole sequence is left as it is, each line with why.
/// </summary>
/// <param name="IsNamePath">The sequence has no title: <paramref name="Name"/> is its folder, read left to right.</param>
/// <param name="IsBlocked">Nothing of the sequence converts now (busy, offline, unreadable).</param>
public sealed record ConvertRow(Guid SequenceId, string Name, bool IsNamePath, string Note, IReadOnlyList<string> Kept, bool IsBlocked)
{
public bool HasNote => Note.Length > 0;
public bool HasKept => Kept.Count > 0;
/// <summary>What a screen reader says after the name: what converts, then every line of what stays.</summary>
public string Description => string.Join(Environment.NewLine, [.. HasNote ? [Note] : (string[])[], .. Kept]);
}
/// <summary>The free space line of a conversion dry run, and whether the volume lacks the space.</summary>
public sealed record ConvertSpaceLine(string Text, bool IsShort);
/// <summary>
/// The words of a mass conversion (owner review 2, R7; BRIEF §12.5): the engine's dry run (<see cref="ConvertPlan"/>) as
/// rows, a summary and the free space line, and the typed confirmation a Replace asks for.
/// </summary>
public static class ConvertPlans
{
/// <summary>The targets in the order the dialog offers them.</summary>
public static readonly IReadOnlyList<ConvertTarget> Targets = [ConvertTarget.Jpeg, ConvertTarget.Tiff16, ConvertTarget.LinearDng];
/// <summary>The problem of a JPEG quality as typed, localized; null when it is 1–100.</summary>
public static string? ValidateQuality(string? text) =>
int.TryParse(text?.Trim(), NumberStyles.Integer, Loc.Culture, out var quality) && quality is >= 1 and <= 100
? null
: Loc.L("Errors.Number.Range", 1.ToString("N0", Loc.Culture), 100.ToString("N0", Loc.Culture));
/// <summary>A valid quality as typed (see <see cref="ValidateQuality"/>).</summary>
public static int ParseQuality(string text) => int.Parse(text.Trim(), NumberStyles.Integer, Loc.Culture);
/// <summary>The rows of a plan in its order: every sequence that converts, or whose photos stay as they are, with why.</summary>
public static IReadOnlyList<ConvertRow> Rows(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
return [.. plan.Sequences.Where(s => s.Frames.Count > 0 || s.Skipped.Count > 0 || s.Blocked.Count > 0).Select(Row)];
}
public static ConvertRow Row(ConvertSequencePlan step)
{
ArgumentNullException.ThrowIfNull(step);
var named = !string.IsNullOrWhiteSpace(step.Title);
var name = named ? step.Title : step.Folder.Length > 0 ? step.Folder : step.SequenceId.ToString("N")[..8];
var note = step.Converts
? Loc.Plural("Shell.Status.Photos", step.Frames.Count) + Loc.Separator + Sizes(step.BytesBefore, step.BytesAfter)
: string.Empty;
// What blocks the whole sequence comes first: the photos it would skip anyway do not matter until it can convert.
List<string> kept = [.. step.Blocked.Distinct().Select(b => Loc.L("Archive.Convert.Blocked." + b))];
kept.AddRange(step.Skipped.Select(s => Loc.L("Archive.Convert.Skipped." + s.Reason) + Loc.Separator + Loc.Plural("Shell.Status.Photos", s.Frames)));
return new ConvertRow(step.SequenceId, name, !named, note, kept, step.Blocked.Count > 0);
}
/// <summary>"12.4 GB → 9.8 GB".</summary>
public static string Sizes(long before, long after) => Loc.L("Archive.Convert.Sizes", Formatting.Bytes(before), Formatting.Bytes(after));
/// <summary>
/// "12 of 36 change · 3,600 photos · 41 GB → 32 GB · 20 skipped": the sequences converted of those planned, then the
/// photos and their sizes when something converts, the photos skipped when there are any.
/// </summary>
public static string Summary(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var parts = new List<string> { Loc.Plural("Archive.Rename.Summary", plan.Converted.Count(), plan.Sequences.Count) };
if (plan.Frames > 0)
{
parts.Add(Loc.Plural("Shell.Status.Photos", plan.Frames));
parts.Add(Sizes(plan.BytesBefore, plan.BytesAfter));
}
if (plan.Skipped > 0) parts.Add(Loc.Plural("Archive.Convert.SkippedPhotos", plan.Skipped));
return string.Join(Loc.Separator, parts);
}
/// <summary>"Needs 12 GB, free 340 GB", or that the volume lacks it, or that its free space cannot be measured.</summary>
public static ConvertSpaceLine Space(ConvertSpace space)
{
ArgumentNullException.ThrowIfNull(space);
var required = Formatting.Bytes(space.Required);
if (space.Free is not { } free) return new(Loc.L("Archive.Convert.SpaceUnknown", required), false);
return space.Enough
? new(Loc.L("Archive.Convert.Space", required, Formatting.Bytes(free)), false)
: new(Loc.L("Archive.Convert.SpaceShort", required, Formatting.Bytes(free)), true);
}
/// <summary>"Linear DNG": the target as the dialog names it.</summary>
public static string TargetText(ConvertTarget target) => Loc.L("Archive.Convert.Target." + target);
/// <summary>
/// The destructive confirmation of a Replace: the sequences whose photos are replaced, that the originals move to the
/// archive's trash, and the number of photos to type; null when the plan converts nothing.
/// </summary>
public static ConfirmRequest? ReplaceRequest(ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(plan);
var converted = plan.Converted.ToList();
if (converted.Count == 0) return null;
var count = plan.Frames.ToString(CultureInfo.InvariantCulture);
var lines = converted.Take(DeletePlans.ListedLines).Select(s => Loc.L("Archive.Delete.Line", Row(s).Name,
Loc.Plural("Shell.Status.Photos", s.Frames.Count), Formatting.Bytes(s.BytesBefore))).ToList();
if (converted.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", converted.Count - DeletePlans.ListedLines));
return new ConfirmRequest
{
Heading = Loc.Plural("Archive.Convert.ReplaceHeading", converted.Count),
Message = Loc.L("Archive.Convert.ReplaceMessage", Loc.Plural("Shell.Status.Photos", plan.Frames), Formatting.Bytes(plan.BytesBefore),
TargetText(plan.Options.Target)),
Detail = string.Join(Environment.NewLine, lines),
IsDetailMonospaced = false,
DetailToolTip = Loc.L("Tooltips.Archive.ConvertPlan"),
SafeText = Loc.L("Archive.Delete.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"),
ActionText = Loc.L("Archive.Convert.Replace"),
ActionToolTip = Loc.Plural("Tooltips.Archive.ConvertReplace", plan.Frames),
IsDestructive = true,
TypedConfirmation = count,
TypedPrompt = Loc.L("Archive.Delete.Type", count),
};
}
}
+171
View File
@@ -0,0 +1,171 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.App.Jobs;
using Chronos.App.Shell;
using Chronos.Core.Conversion;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Archiving;
/// <summary>What an undo of conversions did: the sequences whose originals came back, how, and what stayed in the trash.</summary>
/// <param name="Restored">Sequences whose converted frames were swapped back to their originals.</param>
/// <param name="AsNew">Sequences changed since their conversion: their originals came back as a new sequence beside them.</param>
/// <param name="Kept">Originals that stayed in the trash, each with why.</param>
/// <param name="Entries">Trash entries of replaced originals the conversions left; 0 when the trash no longer holds any.</param>
/// <param name="Failure">Why the undo stopped; the entries restored before it stay restored.</param>
public sealed record ConvertUndoResult(int Restored, int AsNew, IReadOnlyList<KeptPhoto> Kept, int Entries, Exception? Failure);
/// <summary>
/// The Undo a finished Replace conversion offers (owner review 2, R7): its originals wait in the archive's trash as entries of
/// kind <see cref="TrashKind.Replaced"/>, and restoring them swaps each sequence back (or, for a sequence changed since,
/// brings the originals back as a new sequence beside it), the same as Restore in Maintenance › Trash.
/// </summary>
public static class ConvertUndo
{
/// <summary>The confirmed plan of a conversion job; null for another kind of job or parameters it cannot read.</summary>
public static ConvertJobParameters? Parameters(Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (job.Kind != JobKind.Convert || job.ParametersJson is not { Length: > 0 } json) return null;
try
{
return JsonSerializer.Deserialize(json, ConvertJobJson.Default.ConvertJobParameters);
}
catch (JsonException ex)
{
Log.Warning("archive", $"The parameters of conversion job {job.Id} cannot be read", ex);
return null;
}
}
/// <summary>A conversion whose files replaced the photos of its sequences: its end offers Undo.</summary>
public static bool Replaces(Job job) => Parameters(job) is { Mode: ConvertMode.Replace };
/// <summary>
/// The trash entries an undo of <paramref name="job"/> restores: of each sequence it converted, the newest entry of replaced
/// originals made while it ran (from when it was queued to when it ended, so an entry an undo made of the converted files
/// is never taken for the originals).
/// </summary>
public static IReadOnlyList<TrashEntry> Entries(Job job, ConvertJobParameters parameters, IEnumerable<TrashEntry> trash)
{
ArgumentNullException.ThrowIfNull(job);
ArgumentNullException.ThrowIfNull(parameters);
ArgumentNullException.ThrowIfNull(trash);
var converted = parameters.Sequences.Select(s => s.Id).ToHashSet();
return
[
.. trash.Where(e => e.Kind == TrashKind.Replaced && e.ArchiveId == parameters.ArchiveId && converted.Contains(e.SequenceId) && e.DeletedAt >= job.Created
&& (job.Finished is not { } finished || e.DeletedAt <= finished))
.GroupBy(e => e.SequenceId)
.Select(g => g.MaxBy(e => e.DeletedAt)!)
.OrderBy(e => e.DeletedAt),
];
}
/// <summary>
/// Restores the replaced originals of <paramref name="jobs"/> (Replace conversions), entry by entry; what the frames need
/// again is queued on <paramref name="followUps"/>. A failure stops the undo: what came back before it stays back.
/// </summary>
public static async Task<ConvertUndoResult> UndoAsync(ArchiveService archives, IReadOnlyList<Job> jobs, JobEngine? followUps,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archives);
ArgumentNullException.ThrowIfNull(jobs);
var (restored, asNew, entries) = (0, 0, 0);
var kept = new List<KeptPhoto>();
var taken = new HashSet<string>(StringComparer.Ordinal);
try
{
var replaced = jobs.Select(j => (Job: j, Parameters: Parameters(j))).Where(p => p.Parameters is { Mode: ConvertMode.Replace }).ToList();
foreach (var archive in replaced.GroupBy(p => p.Parameters!.ArchiveId))
{
var trash = await archives.ListTrashAsync(archive.Key, cancellationToken).ConfigureAwait(false);
foreach (var (job, parameters) in archive)
{
foreach (var entry in Entries(job, parameters!, trash).Where(e => taken.Add(e.Name)))
{
entries++;
var result = await archives.RestoreEntryAsync(entry.ArchiveId, entry.Name, followUps, cancellationToken).ConfigureAwait(false);
if (result.NewSequence) asNew++;
else restored++;
kept.AddRange(result.Kept);
Log.Info("archive", $"{entry.Title}: conversion undone ({(result.NewSequence ? "originals as a new sequence" : "swapped back")}, {result.Photos} photo(s))");
}
}
}
return new ConvertUndoResult(restored, asNew, kept, entries, null);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException or ArgumentException
or DatabaseException)
{
Log.Warning("archive", "Undoing a conversion failed", ex);
return new ConvertUndoResult(restored, asNew, kept, entries, ex);
}
}
/// <summary>
/// The toast of finished Replace conversions: what was converted, and Undo, which brings their originals back once
/// (a second click does nothing: the converted files the first one put in the trash are not originals).
/// </summary>
public static Toast Toast(ShellViewModel shell, IReadOnlyList<Job> jobs)
{
ArgumentNullException.ThrowIfNull(shell);
ArgumentNullException.ThrowIfNull(jobs);
var job = jobs[0];
var undone = false;
return new Toast
{
Title = jobs.Count == 1 ? Loc.Plural("Archive.Convert.Done", Math.Max(1, job.TargetIds.Count)) : Loc.Plural("Shell.Job.DonePlural", jobs.Count),
Message = jobs.Count == 1 ? JobText.Name(job) : JobText.Kind(JobKind.Convert),
ActionText = Loc.L("Archive.Delete.Undo"),
ActionToolTip = Loc.L("Tooltips.Archive.ConvertUndo"),
ActionCommand = new AsyncRelayCommand(async () =>
{
if (undone) return;
undone = true;
await RunAsync(shell, jobs);
}),
};
}
/// <summary>Undoes <paramref name="jobs"/>, says how it went, and reads the Library and the Archive screen again.</summary>
public static async Task RunAsync(ShellViewModel shell, IReadOnlyList<Job> jobs)
{
ArgumentNullException.ThrowIfNull(shell);
if (shell.Services.Archives is not { } archives) return;
var engine = shell.Services.Engine;
var result = await Task.Run(() => UndoAsync(archives, jobs, engine));
var (title, message, isError) = Words(result);
shell.Notify(title, message, isError: isError);
if (result.Restored + result.AsNew > 0) await SequenceDeletion.RefreshAsync(shell);
}
/// <summary>The toast that says how an undo went: its title, its line (null for none), and whether it reports a failure.</summary>
internal static (string Title, string? Message, bool IsError) Words(ConvertUndoResult result)
{
ArgumentNullException.ThrowIfNull(result);
if (result.Failure is { } failure) return (Loc.L("Archive.Convert.UndoFailed"), ArchiveFailures.Cause(failure), true);
if (result.Entries == 0) return (Loc.L("Archive.Convert.UndoNothing"), null, true);
string[] lines =
[
result.AsNew > 0 ? Loc.Plural("Archive.Convert.UndoneNew", result.AsNew) : string.Empty,
result.Kept.Count > 0 ? TrashDialogViewModel.KeptText(result.Kept).Text : string.Empty,
];
var message = string.Join(" ", lines.Where(l => l.Length > 0));
return (Loc.Plural("Archive.Convert.Undone", result.Restored + result.AsNew), message.Length > 0 ? message : null, false);
}
}
/// <summary>The parameters of a conversion job as the engine writes them (camelCase, enums by name).</summary>
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
[JsonSerializable(typeof(ConvertJobParameters))]
internal sealed partial class ConvertJobJson : JsonSerializerContext;
+29 -2
View File
@@ -1,13 +1,15 @@
using Chronos.App.DesignTime;
using Chronos.Core.Archiving;
using Chronos.Core.Conversion;
using Chronos.Core.Imaging;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
namespace Chronos.App.Archiving;
/// <summary>
/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts and trash rows over the sample archive's sequences
/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// Capture and smoke-test data ONLY: maintenance reports, rebuild counts, trash rows and a conversion's dry run over the
/// sample archive's sequences (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// </summary>
public static class SampleReports
{
@@ -48,6 +50,31 @@ public static class SampleReports
];
}
/// <summary>
/// The Convert dialog's dry run to linear DNG over the six newest sample sequences: their RAW photos convert, the second
/// keeps 12 that this PC cannot read at full resolution, the fifth 8 never verified, and a job is working on the fourth
/// (nothing on disk is read or written).
/// </summary>
public static ConvertPlan Convert(Guid archiveId, IReadOnlyList<SequenceLocation> sequences)
{
var options = new ConvertOptions(ConvertOptions.ArchivalTarget);
var estimated = ConvertPlanner.EstimateBytes(options, 6_000, 4_000);
int[] counts = [120, 240, 60, 0, 96, 300];
// Newest first, as the tree lists them: the second has no title and is named by its folder.
var newest = sequences.OrderByDescending(s => s.Folder, StringComparer.Ordinal).Take(counts.Length);
var steps = newest.Select((s, i) => new ConvertSequencePlan(s.Id, s.Title ?? string.Empty, s.Folder, 1,
[.. Enumerable.Range(0, counts[i]).Select(n => new ConvertFramePlan(Guid.CreateVersion7(), n, $"IMG_{n + 1:0000}.CR2", ImageFileFormat.Cr2, 25_165_824, estimated))],
i switch
{
1 => [new ConvertSkipped(ConvertSkip.NoNativeDecoder, 12)],
4 => [new ConvertSkipped(ConvertSkip.Unhashed, 8)],
_ => [],
},
i == 3 ? [ConvertBlock.Busy] : [])).ToList();
var bytes = steps.Where(s => s.Converts).Sum(s => s.BytesAfter);
return new ConvertPlan(archiveId, options, ConvertMode.NewSequence, steps, new ConvertSpace(ConvertPlanner.Required(bytes), 2_400_000_000_000));
}
/// <summary>What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.</summary>
public static IReadOnlyList<SequenceFolder> Folders(IReadOnlyList<SequenceLocation> sequences)
{