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)
{
+1 -1
View File
@@ -40,7 +40,7 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash;
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert;
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
+6 -2
View File
@@ -16,6 +16,9 @@ public enum MassAction
/// <summary>Folders, file names and titles from templates (owner review 2, R7), for the sequences of one archive.</summary>
Reorganize,
/// <summary>JPEG, 16-bit TIFF or linear DNG after import (owner review 2, R7), for the sequences of one archive.</summary>
Convert,
Upload,
Download,
Delete,
@@ -73,8 +76,9 @@ public static class MassActions
return null;
}
if (targets.Count == 0) return Loc.L("Library.Blocked.ServerOnly");
// One plan, one job: a Reorganize renames inside one archive, never across two.
return action == MassAction.Reorganize && targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() > 1 ? Loc.L("Library.Blocked.OneArchive") : null;
// One plan, one job: a Reorganize renames and a conversion writes inside one archive, never across two.
if (action is not (MassAction.Reorganize or MassAction.Convert) || targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() <= 1) return null;
return Loc.L(action == MassAction.Reorganize ? "Library.Blocked.OneArchive" : "Library.Blocked.OneArchiveConvert");
}
/// <summary>The enabled tooltip: what the action does to how many sequences.</summary>
+3 -1
View File
@@ -425,6 +425,8 @@
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Verify}" Command="{Binding VerifySetCommand}" ToolTip="{Binding VerifySetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Reorganize}" Command="{Binding ReorganizeSetCommand}"
ToolTip="{Binding ReorganizeSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Convert}" Command="{Binding ConvertSetCommand}"
ToolTip="{Binding ConvertSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Retag}" Command="{Binding RetagSetCommand}" ToolTip="{Binding RetagSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Export}" Command="{Binding ExportSetCommand}" ToolTip="{Binding ExportSetToolTip}" />
</WrapPanel>
@@ -438,7 +440,7 @@
</ui:EmptyState>
</Grid>
<!-- In-window dialogs (rebuild, rename, retag, trash) over a scrim; the keyboard stays inside the dialog. -->
<!-- In-window dialogs (rebuild, reorganize, convert, retag, trash) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
+19 -3
View File
@@ -26,7 +26,7 @@ namespace Chronos.App.Sections;
/// <summary>
/// Archive manager (BRIEF §12.5, Archive.html): the archive's tree (years, sequences) with its availability, its
/// figures and charts, mass operations on the selected and filtered set (analyse, proxies, thumbnails, verify,
/// reorganize, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with its
/// reorganize, convert, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with its
/// dialog, verify, maintenance), the trash, plus the maintenance view: index health, duplicates and orphans with safe
/// fixes, recent runs. The
/// tree selection is only ever changed by the user: reloads and expanding keep it.
@@ -110,6 +110,7 @@ public sealed class ArchiveViewModel : SectionViewModel
ThumbnailsSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Thumbnails(ids, SetLabel()), Set()), HasSet);
VerifySetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Verify(_archive!, ids), Set()), HasSet);
ReorganizeSetCommand = new AsyncRelayCommand(() => OpenReorganizeDialogAsync(), () => HasSet() && IsOnline());
ConvertSetCommand = new AsyncRelayCommand(() => OpenConvertDialogAsync(), () => HasSet() && IsOnline());
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
DeleteSetCommand = new AsyncRelayCommand(DeleteSetAsync, () => HasSet() && IsOnline());
@@ -179,6 +180,7 @@ public sealed class ArchiveViewModel : SectionViewModel
public string VerifySetToolTip => WhenSet("Tooltips.Archive.SetVerify");
public string ExportSetToolTip => WhenSet("Tooltips.Archive.SetExport");
public string ReorganizeSetToolTip => WhenSet("Tooltips.Archive.SetReorganize", needsOnline: true);
public string ConvertSetToolTip => WhenSet("Tooltips.Archive.SetConvert", needsOnline: true);
public string RetagSetToolTip => WhenSet("Tooltips.Archive.SetRetag", needsOnline: true);
public string DeleteSetToolTip => WhenSet("Tooltips.Archive.SetDelete", needsOnline: true);
@@ -282,6 +284,9 @@ public sealed class ArchiveViewModel : SectionViewModel
/// <summary>Reorganize…: the set's folders, file names and titles from templates, a dry run first, then a job.</summary>
public ICommand ReorganizeSetCommand { get; }
/// <summary>Convert…: the set's photos to JPEG, 16-bit TIFF or linear DNG, Replace or New sequence, a dry run first, then a job.</summary>
public ICommand ConvertSetCommand { get; }
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
@@ -364,7 +369,7 @@ public sealed class ArchiveViewModel : SectionViewModel
// ---------------- Dialogs ----------------
/// <summary>The open in-window dialog (rebuild, reorganize, retag, delete, trash); null when none.</summary>
/// <summary>The open in-window dialog (rebuild, reorganize, convert, retag, delete, trash); null when none.</summary>
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
@@ -634,6 +639,7 @@ public sealed class ArchiveViewModel : SectionViewModel
OnPropertyChanged(nameof(VerifySetToolTip));
OnPropertyChanged(nameof(ExportSetToolTip));
OnPropertyChanged(nameof(ReorganizeSetToolTip));
OnPropertyChanged(nameof(ConvertSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
OnPropertyChanged(nameof(DeleteSetToolTip));
CommandManager.InvalidateRequerySuggested();
@@ -680,7 +686,7 @@ public sealed class ArchiveViewModel : SectionViewModel
{
if (job.State is not (JobState.Done or JobState.Failed)) return;
if (job.Kind is not (JobKind.Scan or JobKind.Rebuild or JobKind.Verify or JobKind.Maintenance or JobKind.Import or JobKind.Proxies or JobKind.Thumbs
or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move)) return;
or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move or JobKind.Convert)) return;
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{
if (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return;
@@ -805,6 +811,16 @@ public sealed class ArchiveViewModel : SectionViewModel
await OpenReorganizeAllAsync(await FreshAsync(waiting.Archive), waiting.Parts);
}
/// <summary>Opens Convert on the set and waits for its dry run (the archival format, no mode chosen yet).</summary>
public async Task OpenConvertDialogAsync()
{
if (Services.Archives is not { } archives || Services.Engine is not { } engine || _archive is not { } archive) return;
IReadOnlyList<Guid> set = [.. Set().Select(s => s.Id)];
var dialog = new ConvertDialogViewModel(archives, archive, set, r => EnqueueAsync(engine, r), Services.Dialogs.Confirm, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
/// <summary>The archive's record as the index holds it now; <paramref name="archive"/> when it cannot be read.</summary>
private async Task<Core.Model.Archive> FreshAsync(Core.Model.Archive archive)
{
+4 -1
View File
@@ -1,6 +1,7 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Library;
@@ -318,12 +319,14 @@ public sealed class JobsViewModel : SectionViewModel
/// <summary>
/// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch
/// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a
/// toast opens what it names; a retry waits until the user has seen why the job failed.
/// toast opens what it names; a retry waits until the user has seen why the job failed. Conversions that replaced photos
/// offer Undo instead (<see cref="ConvertUndo"/>), which never runs from the Windows notification.
/// </summary>
private Toast ToastFor(JobEnding ending)
{
var job = ending.Jobs[0];
var failed = ending.Notice == JobNotice.Failed;
if (!failed && ending.Jobs.All(ConvertUndo.Replaces)) return ConvertUndo.Toast(Shell, ending.Jobs);
if (ending.Jobs.Count > 1)
{
return new Toast
+2 -1
View File
@@ -423,6 +423,7 @@
</Button.ContextMenu>
</Button>
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Reorganize}" Command="{Binding ReorganizeCommand}" ToolTip="{Binding ReorganizeToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Convert}" Command="{Binding ConvertCommand}" ToolTip="{Binding ConvertToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Upload}" Command="{Binding UploadCommand}" ToolTip="{Binding UploadToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Download}" Command="{Binding DownloadCommand}" ToolTip="{Binding DownloadToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.ExportList}" Command="{Binding ExportListCommand}" ToolTip="{Binding ExportListToolTip}" />
@@ -435,7 +436,7 @@
</Border>
</Grid>
<!-- In-window dialogs (tags, move, view name, delete) over a scrim; the keyboard stays inside the dialog. -->
<!-- In-window dialogs (tags, reorganize, convert, view name, delete) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
+29 -3
View File
@@ -130,6 +130,7 @@ public sealed class LibraryViewModel : SectionViewModel
TagCommand = Mass(MassAction.Tag, OpenRetag);
RateCommand = new AsyncRelayCommand((p, _) => p is int rating ? RateAsync(rating) : Task.CompletedTask, _ => CanRun(MassAction.Rate));
ReorganizeCommand = Mass(MassAction.Reorganize, OpenReorganizeAsync);
ConvertCommand = Mass(MassAction.Convert, OpenConvertAsync);
UploadCommand = Mass(MassAction.Upload, _ => TransferAsync(MassAction.Upload));
DownloadCommand = Mass(MassAction.Download, _ => TransferAsync(MassAction.Download));
DeleteCommand = Mass(MassAction.Delete, t => DeleteAsync([.. t.Select(s => s.Id)]));
@@ -182,6 +183,9 @@ public sealed class LibraryViewModel : SectionViewModel
/// <summary>Reorganize…: the selection's folders, file names and titles from templates, a dry run first, then a job.</summary>
public ICommand ReorganizeCommand { get; }
/// <summary>Convert…: the selection's photos to JPEG, 16-bit TIFF or linear DNG, a dry run first, then a job.</summary>
public ICommand ConvertCommand { get; }
public ICommand UploadCommand { get; }
public ICommand DownloadCommand { get; }
public ICommand DeleteCommand { get; }
@@ -492,6 +496,7 @@ public sealed class LibraryViewModel : SectionViewModel
public string TagToolTip => MassToolTip(MassAction.Tag);
public string RateToolTip => MassToolTip(MassAction.Rate);
public string ReorganizeToolTip => MassToolTip(MassAction.Reorganize);
public string ConvertToolTip => MassToolTip(MassAction.Convert);
public string UploadToolTip => MassToolTip(MassAction.Upload);
public string DownloadToolTip => MassToolTip(MassAction.Download);
public string DeleteToolTip => MassToolTip(MassAction.Delete);
@@ -509,7 +514,7 @@ public sealed class LibraryViewModel : SectionViewModel
// ---------------- Dialogs ----------------
/// <summary>The open in-window dialog (tags, reorganize, view name, delete); null when none.</summary>
/// <summary>The open in-window dialog (tags, reorganize, convert, view name, delete); null when none.</summary>
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
@@ -1035,6 +1040,7 @@ public sealed class LibraryViewModel : SectionViewModel
OnPropertyChanged(nameof(TagToolTip));
OnPropertyChanged(nameof(RateToolTip));
OnPropertyChanged(nameof(ReorganizeToolTip));
OnPropertyChanged(nameof(ConvertToolTip));
OnPropertyChanged(nameof(UploadToolTip));
OnPropertyChanged(nameof(DownloadToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
@@ -1068,7 +1074,8 @@ public sealed class LibraryViewModel : SectionViewModel
foreach (var item in Items.Where(i => job.TargetIds.Contains(i.Id))) item.IsAnalysing = _analysing.Contains(item.Id);
}
OpenWhenCached(job);
if (job.State == JobState.Done) _ = RefreshTargetsAsync(job);
// A conversion that failed for some sequences converted the others.
if (job.State == JobState.Done || job is { Kind: JobKind.Convert, State: JobState.Failed }) _ = RefreshTargetsAsync(job);
}
/// <summary>A remote card's "Open" waited for this proxy download; it opens if the Library is still in front.</summary>
@@ -1089,7 +1096,8 @@ public sealed class LibraryViewModel : SectionViewModel
if (await _db.Sequences.GetAsync(item.Id) is { } fresh) item.Update(fresh);
}
// Downloads of proxies only fill the proxy cache, so the Library is read again for originals and exports only.
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit
// A conversion makes new sequences, or changes the formats and sizes of the converted ones.
if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit or JobKind.Convert
|| SyncService.TransferKind(job) is SyncTransferKind.DownloadOriginals or SyncTransferKind.GetExports)
await RefreshAsync();
else if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse)
@@ -1188,6 +1196,24 @@ public sealed class LibraryViewModel : SectionViewModel
await dialog.PlanAsync();
}
/// <summary>
/// Convert…: the selection of one archive to JPEG, 16-bit TIFF or linear DNG, Replace or New sequence chosen in the
/// dialog, a dry run first, then the engine's job, which the Library follows to read the sequences again.
/// </summary>
private async Task OpenConvertAsync(IReadOnlyList<Sequence> targets)
{
if (Shell.Services.Archives is not { } archives || Shell.Services.Engine is not { } engine || _db is null || targets.Count == 0) return;
if (await _db.Archives.GetAsync(targets[0].ArchiveId) is not { } archive) return;
var dialog = new ConvertDialogViewModel(archives, archive, [.. targets.Select(t => t.Id)], async request =>
{
await engine.EnqueueAsync(request);
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(request.Kind), request.Label ?? archive.Name), actionText: Loc.L("Shell.Nav.Jobs"),
actionToolTip: Loc.L("Tooltips.Nav.Jobs"), action: () => Shell.Navigate(SectionKey.Jobs));
}, Shell.Services.Dialogs.Confirm, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
private async Task AppliedAsync(int changed)
{
Shell.Notify(Loc.Plural("Archive.Applied", changed));