feat(app): Reorganize existing sequences from the Archive manager, the Library and Settings
Owner review 2, R7 asks to rename and move sequences after import on the desktop too.
The desktop now uses the engine's Reorganize, the same plan and job as the web panel.
- One Reorganize… dialog replaces Rename… and Move… in the Archive manager and Move… in
the Library. It has three templates: folders, file names and titles. Each one has a
switch and is checked as it is typed. Folders and file names start on, filled from the
archive's settings; titles start off as {title}. Renaming only titles is the Titles
switch alone.
- The dry run stays in the dialog and follows the typing. Each sequence shows its folder,
title and first file names before and after. Sequences carried along with a folder are
marked, and photos that keep their names are listed with the reason. A summary counts
the sequences that change, the files renamed and the names kept.
- Apply no longer changes the archive from the dialog. It queues the engine's move job
with exactly the plan shown (its fingerprint), so the work can be paused, resumed after
a restart and followed in Jobs. The job refuses the plan if the archive changed after
the dry run.
- The Library's Reorganize… works on the selected sequences of one archive. The Archive
screen reads the archive again when a move job ends.
- After Settings › Archive saves a new folder or file template to an archive that holds
sequences, a toast offers Reorganize… for every sequence. Its templates are the ones
changed since; a second change made while the toast is up adds to that toast instead of
opening another.
- Strings in en and it. The keys of the old Rename and Move were removed and pruned from
every translation, so the 36 other languages show the new keys as untranslated instead
of keeping "Move".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7bbf451f737a71b768dcd70a77b998daaef851f3)
This commit is contained in:
1 parent
17efb50e11
commit
ad72501f11
134 files changed
+998
-888
No files matched your search
@@ -1,6 +1,5 @@
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Archiving;
|
||||
@@ -196,160 +195,6 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename (titles) or move (folder layout) of a set (BRIEF §7, §12.5): the template is checked as it is typed,
|
||||
/// the dry run lists every change, and Apply makes exactly those changes (journaled, so a crash resumes it).
|
||||
/// </summary>
|
||||
public sealed class RenameDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly ArchiveService _archives;
|
||||
private readonly Core.Model.Archive _archive;
|
||||
private readonly IReadOnlyList<Sequence> _set;
|
||||
private readonly Func<int, Task> _applied;
|
||||
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
|
||||
private RenamePlan? _plan;
|
||||
private string? _planError;
|
||||
private IReadOnlyList<RenameRow> _rows = [];
|
||||
private CancellationTokenSource? _planning;
|
||||
|
||||
public RenameDialogViewModel(RenameMode mode, ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Sequence> set, Func<int, Task> applied,
|
||||
Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
Mode = mode;
|
||||
_archives = archives;
|
||||
_archive = archive;
|
||||
_set = set;
|
||||
_applied = applied;
|
||||
var initial = mode == RenameMode.Folders ? archive.FolderTemplate : "{title}";
|
||||
Template = new EditableField(initial, t => MassRename.Validate(mode, t), committed => _ = PlanAsync(),
|
||||
() => Loc.L(mode == RenameMode.Folders ? "Tooltips.Archive.FolderTemplate" : "Tooltips.Archive.TitleTemplate"));
|
||||
Template.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName != nameof(EditableField.Text)) return;
|
||||
_delay.Stop();
|
||||
_delay.Start();
|
||||
};
|
||||
_delay.Tick += (_, _) =>
|
||||
{
|
||||
_delay.Stop();
|
||||
_ = PlanAsync();
|
||||
};
|
||||
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
|
||||
}
|
||||
|
||||
/// <summary>Why Apply is disabled; null when it can run.</summary>
|
||||
private string? ApplyBlocker =>
|
||||
IsBusy ? Loc.L("Archive.Blocked.Applying")
|
||||
: Template.Error is { } error ? error
|
||||
: _plan is null ? _planError ?? Loc.L("Archive.Blocked.Planning")
|
||||
: _plan.Steps.Count == 0 ? Loc.L("Archive.Blocked.NoChanges")
|
||||
: null;
|
||||
|
||||
public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RenameApply");
|
||||
|
||||
public RenameMode Mode { get; }
|
||||
|
||||
public string Heading => Loc.Plural(Mode == RenameMode.Folders ? "Archive.Rename.MoveHeading" : "Archive.Rename.Heading", _set.Count);
|
||||
|
||||
public EditableField Template { get; }
|
||||
|
||||
public IReadOnlyList<RenameRow> Rows { get => _rows; private set => Set(ref _rows, value); }
|
||||
|
||||
public string SummaryText => _plan is null ? string.Empty : MassRename.Summary(_plan, _set.Count);
|
||||
|
||||
public ICommand ApplyCommand { get; }
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_delay.Stop();
|
||||
_planning?.Cancel();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of the current template (the engine's plan; nothing changes on disk); it clears the last failure and
|
||||
/// stands in for a dry run still waiting on typing, which would otherwise throw this plan away.
|
||||
/// </summary>
|
||||
public Task PlanAsync()
|
||||
{
|
||||
_delay.Stop();
|
||||
ClearError();
|
||||
return DryRunAsync();
|
||||
}
|
||||
|
||||
private async Task DryRunAsync()
|
||||
{
|
||||
_planning?.Cancel();
|
||||
_plan = null;
|
||||
_planError = null;
|
||||
Rows = [];
|
||||
OnPlanChanged();
|
||||
if (Template.HasErrors) return;
|
||||
var cts = _planning = new CancellationTokenSource();
|
||||
var template = Template.Text;
|
||||
var ids = _set.Select(s => s.Id).ToList();
|
||||
try
|
||||
{
|
||||
var plan = await Task.Run(() => _archives.PlanRenameAsync(_archive.Id, ids, Mode == RenameMode.Folders ? template : null,
|
||||
Mode == RenameMode.Titles ? template : null, cts.Token), cts.Token);
|
||||
if (cts.IsCancellationRequested) return;
|
||||
_plan = plan;
|
||||
Rows = MassRename.Rows(plan, Mode);
|
||||
}
|
||||
catch (OperationCanceledException) when (cts.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or DatabaseException or FormatException)
|
||||
{
|
||||
Log.Warning("archive", "Rename plan failed", ex);
|
||||
_planError = ArchiveFailures.Cause(ex);
|
||||
ShowError(ex);
|
||||
}
|
||||
OnPlanChanged();
|
||||
}
|
||||
|
||||
private void OnPlanChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(SummaryText));
|
||||
OnPropertyChanged(nameof(ApplyToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private async Task ApplyAsync()
|
||||
{
|
||||
if (_plan is not { } plan) return;
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
// A tick posted before the apply ended must not bring its progress back.
|
||||
var progress = new Progress<int>(n =>
|
||||
{
|
||||
if (IsBusy) BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(n), Formatting.Count(plan.Steps.Count));
|
||||
});
|
||||
try
|
||||
{
|
||||
await Task.Run(() => _archives.ApplyRenameAsync(plan, progress));
|
||||
Log.Info("archive", $"{Mode} applied to {plan.Steps.Count} sequence(s)");
|
||||
await _applied(plan.Steps.Count);
|
||||
Close();
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or StaleRenamePlanException or DatabaseException)
|
||||
{
|
||||
Log.Warning("archive", "Rename failed", ex);
|
||||
ShowError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
BusyText = null;
|
||||
}
|
||||
// Part of the plan may have been applied, or the archive changed under it: the dry run shows what is left.
|
||||
await DryRunAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Add and remove tags on a set (BRIEF §12.5 Retag): the dry run counts the sequences that change.</summary>
|
||||
public sealed class RetagDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
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. -->
|
||||
<!-- Rows that only show text: focusable, so the arrow keys move through a long list. -->
|
||||
<Style x:Key="ListBoxItem.Preview" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<!-- Dry-run rows 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}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding To}" />
|
||||
<Setter Property="AutomationProperties.HelpText" Value="{Binding From}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
|
||||
<Setter Property="AutomationProperties.HelpText" Value="{Binding Description}" />
|
||||
</Style>
|
||||
|
||||
<!-- Dialog labels: a column at least 116 px wide that grows with the longest label (DESIGN §2: no fixed-width labels). -->
|
||||
@@ -88,8 +88,9 @@
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type ar:RenameDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="560">
|
||||
<!-- Reorganize…: three templates, each with its switch; the dry run sequence by sequence; Apply queues the job of that plan. -->
|
||||
<DataTemplate DataType="{x:Type ar:ReorganizeDialogViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="760" MaxHeight="600">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
@@ -98,40 +99,86 @@
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<!-- Naming templates keep their tokens and separators in order in every language. -->
|
||||
<Grid Grid.Row="1" Margin="0,14,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Archive.Rename.Template}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<!-- A naming template keeps its tokens and separators in order in every language. -->
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Mono}"
|
||||
Text="{Binding Template.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Template}"
|
||||
ToolTip="{Binding Template.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Rename.Template}" />
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<CheckBox Content="{l:Loc Archive.Reorganize.Folders}" IsChecked="{Binding Folders.IsEnabled}" ToolTip="{l:Loc Tooltips.Archive.ReorganizeFolders}" Margin="0,0,14,0" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Mono}" IsEnabled="{Binding Folders.IsEnabled}"
|
||||
Text="{Binding Folders.Field.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Folders.Field}"
|
||||
ToolTip="{Binding Folders.Field.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Reorganize.Folders}" />
|
||||
<CheckBox Grid.Row="1" Content="{l:Loc Archive.Reorganize.Files}" IsChecked="{Binding Files.IsEnabled}" ToolTip="{l:Loc Tooltips.Archive.ReorganizeFiles}"
|
||||
Margin="0,8,14,0" />
|
||||
<TextBox Grid.Row="1" Grid.Column="1" Margin="0,8,0,0" Style="{StaticResource TextBox.Mono}" IsEnabled="{Binding Files.IsEnabled}"
|
||||
Text="{Binding Files.Field.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Files.Field}"
|
||||
ToolTip="{Binding Files.Field.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Reorganize.Files}" />
|
||||
<CheckBox Grid.Row="2" Content="{l:Loc Archive.Reorganize.Titles}" IsChecked="{Binding Titles.IsEnabled}" ToolTip="{l:Loc Tooltips.Archive.ReorganizeTitles}"
|
||||
Margin="0,8,14,0" />
|
||||
<TextBox Grid.Row="2" Grid.Column="1" Margin="0,8,0,0" Style="{StaticResource TextBox.Mono}" IsEnabled="{Binding Titles.IsEnabled}"
|
||||
Text="{Binding Titles.Field.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Titles.Field}"
|
||||
ToolTip="{Binding Titles.Field.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Reorganize.Titles}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" Typography.NumeralAlignment="Tabular" />
|
||||
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Preview}" MinHeight="120"
|
||||
AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
|
||||
<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" Grid.IsSharedSizeScope="True"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" VirtualizingPanel.ScrollUnit="Pixel" AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ar:RenameRow}">
|
||||
<Grid Height="30" TextElement.FontSize="12">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="120" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" MinWidth="120" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock x:Name="From" Style="{StaticResource Text.Cell}" Text="{Binding From}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{Binding From}" />
|
||||
<ui:Icon Grid.Column="1" Glyph="{StaticResource Icon.Forward}" Margin="10,0" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock x:Name="To" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding To}" ToolTip="{Binding To}" />
|
||||
</Grid>
|
||||
<DataTemplate DataType="{x:Type ar:ReorganizeRow}">
|
||||
<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>
|
||||
<ItemsControl ItemsSource="{Binding Lines}" Focusable="False" Margin="0,4,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type ar:ReorganizeLine}">
|
||||
<Grid Height="22">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="56" SharedSizeGroup="ReorganizeLabel" />
|
||||
<ColumnDefinition Width="*" MinWidth="120" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" MinWidth="120" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Label}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,10,0" />
|
||||
<TextBlock x:Name="From" Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding From}" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
ToolTip="{Binding From}" />
|
||||
<ui:Icon Grid.Column="2" Glyph="{StaticResource Icon.Forward}" Margin="10,0" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<TextBlock x:Name="To" Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding To}" ToolTip="{Binding To}" />
|
||||
</Grid>
|
||||
<DataTemplate.Triggers>
|
||||
<!-- Folders and file names stay left to right; titles read in the language's direction. -->
|
||||
<DataTrigger Binding="{Binding IsPath}" Value="True">
|
||||
<Setter TargetName="From" Property="FlowDirection" Value="LeftToRight" />
|
||||
<Setter TargetName="From" Property="HorizontalAlignment" Value="Left" />
|
||||
<Setter TargetName="To" Property="FlowDirection" Value="LeftToRight" />
|
||||
<Setter TargetName="To" Property="HorizontalAlignment" Value="Left" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<!-- Photos that keep their names, each line with why. -->
|
||||
<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>
|
||||
<!-- Move lists folders: paths stay left to right; Rename lists titles, which read in the language's direction. -->
|
||||
<DataTrigger Binding="{Binding DataContext.Mode, RelativeSource={RelativeSource AncestorType=ListBox}}" Value="Folders">
|
||||
<Setter TargetName="From" Property="FlowDirection" Value="LeftToRight" />
|
||||
<Setter TargetName="From" Property="HorizontalAlignment" Value="Left" />
|
||||
<Setter TargetName="To" Property="FlowDirection" Value="LeftToRight" />
|
||||
<Setter TargetName="To" Property="HorizontalAlignment" Value="Left" />
|
||||
<DataTrigger Binding="{Binding IsNamePath}" Value="True">
|
||||
<Setter TargetName="Name" Property="FlowDirection" Value="LeftToRight" />
|
||||
<Setter TargetName="Name" Property="HorizontalAlignment" Value="Left" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
@@ -5,11 +5,11 @@ namespace Chronos.App.Archiving;
|
||||
/// <summary>
|
||||
/// The Archive views that <c>--capture</c> renders (<c>archive-<view>-<theme>.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 Move dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
|
||||
/// rebuild dialog, the Reorganize dialog with its dry run, and the trash (Maintenance › Trash…) with deleted sequences.
|
||||
/// </summary>
|
||||
public static class ArchiveScenes
|
||||
{
|
||||
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "move", "trash"];
|
||||
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "reorganize", "trash"];
|
||||
|
||||
public static async Task ShowAsync(ShellViewModel shell, string view)
|
||||
{
|
||||
@@ -32,13 +32,13 @@ public static class ArchiveScenes
|
||||
archive.ViewIndex = 0;
|
||||
(await archive.OpenRebuildDialogAsync())?.ShowFolders(SampleReports.Folders(locations));
|
||||
break;
|
||||
case "move":
|
||||
case "reorganize":
|
||||
archive.ViewIndex = 0;
|
||||
await archive.OpenRenameDialogAsync(RenameMode.Folders);
|
||||
if (archive.Dialog is RenameDialogViewModel move)
|
||||
await archive.OpenReorganizeDialogAsync();
|
||||
if (archive.Dialog is ReorganizeDialogViewModel reorganize)
|
||||
{
|
||||
move.Template.Text = "{year}/{date} {title}";
|
||||
await move.PlanAsync();
|
||||
reorganize.Folders.Field.Text = "{year}/{date} {title}";
|
||||
await reorganize.PlanAsync();
|
||||
}
|
||||
break;
|
||||
case "trash":
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Naming;
|
||||
@@ -8,46 +6,6 @@ using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.App.Archiving;
|
||||
|
||||
/// <summary>What a mass rename changes: the sequence titles (Rename) or the folder layout (Move).</summary>
|
||||
public enum RenameMode
|
||||
{
|
||||
Titles,
|
||||
Folders,
|
||||
}
|
||||
|
||||
/// <summary>One line of the rename dry run: before → after.</summary>
|
||||
public sealed record RenameRow(Guid SequenceId, string From, string To);
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename and move of sequences (BRIEF §7, §12.5): the template is checked live, the engine's dry run
|
||||
/// (<see cref="RenamePlan"/>) is listed line by line, and applying makes exactly those changes.
|
||||
/// </summary>
|
||||
public static class MassRename
|
||||
{
|
||||
/// <summary>The first problem of a template, localized; null when it can be used.</summary>
|
||||
public static string? Validate(RenameMode mode, string? template)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(template)) return Loc.L("Errors.Template.Empty", string.Empty, 1);
|
||||
if (mode == RenameMode.Folders) return NamingPreview.Validate(template, isFolder: true);
|
||||
var parsed = PathTemplate.Parse(template);
|
||||
return parsed.Errors is [var error, ..] ? Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1) : null;
|
||||
}
|
||||
|
||||
/// <summary>The changes of a plan as rows: titles or folders, whichever the mode changes.</summary>
|
||||
public static IReadOnlyList<RenameRow> Rows(RenamePlan plan, RenameMode mode) =>
|
||||
[
|
||||
.. plan.Steps.Select(s => mode == RenameMode.Folders
|
||||
? new RenameRow(s.SequenceId, s.FromFolder, s.ToFolder)
|
||||
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// "12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted, and so are
|
||||
/// those that change nothing (their files keep their names).
|
||||
/// </summary>
|
||||
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => s.Changes && !s.Carried), setSize);
|
||||
}
|
||||
|
||||
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
|
||||
public static class Retag
|
||||
{
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// One template of a Reorganize: its switch and its text, checked as it is typed while the switch is on (an unused
|
||||
/// template never blocks the others).
|
||||
/// </summary>
|
||||
public sealed class ReorganizeTemplate : ObservableObject
|
||||
{
|
||||
private readonly Action _toggled;
|
||||
private bool _isEnabled;
|
||||
|
||||
internal ReorganizeTemplate(ReorganizeParts part, string text, bool isEnabled, string toolTipKey, Action typed, Action toggled, Action committed)
|
||||
{
|
||||
Part = part;
|
||||
_isEnabled = isEnabled;
|
||||
_toggled = toggled;
|
||||
Field = new EditableField(text, t => _isEnabled ? ReorganizePlans.Validate(part, t) : null, _ => committed(), () => Loc.L(toolTipKey));
|
||||
Field.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(EditableField.Text)) typed();
|
||||
};
|
||||
}
|
||||
|
||||
public ReorganizeParts Part { get; }
|
||||
|
||||
public EditableField Field { get; }
|
||||
|
||||
/// <summary>The template is applied; off, that part of every sequence stays as it is.</summary>
|
||||
public bool IsEnabled
|
||||
{
|
||||
get => _isEnabled;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _isEnabled, value)) return;
|
||||
// An error of a template turned off no longer counts, and one turned on is shown again.
|
||||
Field.Refresh();
|
||||
_toggled();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The template the dry run uses; null while the switch is off.</summary>
|
||||
public string? Template => _isEnabled ? Field.Text : null;
|
||||
|
||||
/// <summary>The problem that keeps the dry run from running; null when the template is off or usable.</summary>
|
||||
public string? Error => _isEnabled ? Field.Error : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize (owner review 2, R7; BRIEF §7.1, §12.5): new folder, file and title templates applied to sequences already in
|
||||
/// the archive — a set, or every sequence. Each template has its switch and starts from the archive's settings; the dry run
|
||||
/// (the engine's plan, nothing changes on disk) follows the typing and lists each sequence that changes with its new
|
||||
/// folder, title and first file names, and the photos that keep their names with why. Apply queues the Reorganize job of
|
||||
/// exactly that plan (<see cref="ArchiveJobs.Reorganize"/>): resumable, paused and followed in Jobs, refused when the
|
||||
/// archive changed after the dry run.
|
||||
/// </summary>
|
||||
public sealed class ReorganizeDialogViewModel : ArchiveDialogViewModel
|
||||
{
|
||||
private readonly ArchiveService _archives;
|
||||
private readonly Core.Model.Archive _archive;
|
||||
private readonly IReadOnlyList<Guid>? _set;
|
||||
private readonly Func<ArchiveJobRequest, Task> _enqueue;
|
||||
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;
|
||||
|
||||
/// <param name="set">The sequences to reorganize; null for every sequence of <paramref name="archive"/>.</param>
|
||||
/// <param name="enabled">The templates switched on at the start.</param>
|
||||
/// <param name="enqueue">Queues the Reorganize job and says so.</param>
|
||||
public ReorganizeDialogViewModel(ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Guid>? set, ReorganizeParts enabled,
|
||||
Func<ArchiveJobRequest, Task> enqueue, Action<ArchiveDialogViewModel> close)
|
||||
: base(close)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
_archives = archives;
|
||||
_archive = archive;
|
||||
_set = set;
|
||||
_enqueue = enqueue;
|
||||
Folders = Template(ReorganizeParts.Folders, archive.FolderTemplate, "Tooltips.Archive.FolderTemplate");
|
||||
Files = Template(ReorganizeParts.Files, archive.FileTemplate, "Tooltips.Archive.FileTemplate");
|
||||
Titles = Template(ReorganizeParts.Titles, "{title}", "Tooltips.Archive.TitleTemplate");
|
||||
_delay.Tick += (_, _) => _ = PlanAsync();
|
||||
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
|
||||
|
||||
ReorganizeTemplate Template(ReorganizeParts part, string text, string toolTip) =>
|
||||
new(part, text, enabled.HasFlag(part), toolTip, OnTyped, () => _ = PlanAsync(), () => _ = PlanAsync());
|
||||
}
|
||||
|
||||
public ReorganizeTemplate Folders { get; }
|
||||
public ReorganizeTemplate Files { get; }
|
||||
public ReorganizeTemplate Titles { get; }
|
||||
|
||||
public IReadOnlyList<ReorganizeTemplate> Templates => [Folders, Files, Titles];
|
||||
|
||||
/// <summary>"Reorganize 36 sequences", or "Reorganize ChronosArchive" for every sequence.</summary>
|
||||
public string Heading => _set is null ? Loc.L("Archive.Reorganize.HeadingAll", _archive.Name) : Loc.Plural("Archive.Reorganize.Heading", _set.Count);
|
||||
|
||||
/// <summary>The last dry run, one row per sequence that changes or keeps photo names, in the order the job applies them.</summary>
|
||||
public IReadOnlyList<ReorganizeRow> Rows => _run.Rows ?? [];
|
||||
|
||||
/// <summary>The plan of the templates on screen; null while it is made, when it failed, or once the templates changed.</summary>
|
||||
public RenamePlan? Plan => _run is { Plan: { } plan } run && run.For == Current() ? plan : null;
|
||||
|
||||
public string SummaryText => Plan is { } plan ? ReorganizePlans.Summary(plan, _set?.Count ?? plan.Subjects.Count) : string.Empty;
|
||||
|
||||
/// <summary>Queues the job of the plan on screen and closes.</summary>
|
||||
public ICommand ApplyCommand { get; }
|
||||
|
||||
public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.ReorganizeApply");
|
||||
|
||||
/// <summary>Why Apply is disabled; null when it can run.</summary>
|
||||
private string? ApplyBlocker
|
||||
{
|
||||
get
|
||||
{
|
||||
if (IsBusy) return Loc.L("Archive.Blocked.Applying");
|
||||
if (!Templates.Any(t => t.IsEnabled)) return Loc.L("Archive.Blocked.NoTemplate");
|
||||
if (Templates.Select(t => t.Error).FirstOrDefault(e => e is not null) is { } error) return error;
|
||||
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");
|
||||
return plan.Steps.Any(s => s.Changes) ? null : Loc.L("Archive.Blocked.NoChanges");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The templates switched on, as the engine takes them; null when none is on or one of them cannot be used.</summary>
|
||||
public RenameTemplates? Current()
|
||||
{
|
||||
if (Templates.Any(t => t.Error is not null)) return null;
|
||||
var templates = new RenameTemplates(Folders.Template, Files.Template, Titles.Template);
|
||||
return templates.IsEmpty ? null : templates;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of the templates 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();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_delay.Stop();
|
||||
lock (_gate) _planning?.Cancel();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>The rows, the templates' messages and the summary in the new language.</summary>
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
foreach (var template in Templates) template.Field.Refresh();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_run.Plan is { } plan) _run = _run with { Rows = ReorganizePlans.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 templates = Current();
|
||||
// The checks of the fields are the stricter ones; this is the engine's last word on what it can expand.
|
||||
var unusable = templates?.Problem() is not null ? Loc.L("Errors.Template.Format") : null;
|
||||
var cts = templates is null || unusable is not null ? null : new CancellationTokenSource();
|
||||
lock (_gate)
|
||||
{
|
||||
_planning?.Cancel();
|
||||
_planning = cts;
|
||||
_run = new DryRun(templates, Error: unusable);
|
||||
}
|
||||
BusyText = cts is null ? null : Loc.L("Archive.Reorganize.Planning");
|
||||
OnPlanChanged();
|
||||
if (cts is null) return;
|
||||
|
||||
var set = _set;
|
||||
DryRun result;
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
var plan = await Task.Run(() => _archives.PlanReorganizeAsync(_archive.Id, set, templates!, cts.Token), cts.Token);
|
||||
result = new DryRun(templates, plan, ReorganizePlans.Rows(plan));
|
||||
}
|
||||
catch (OperationCanceledException) when (cts.IsCancellationRequested)
|
||||
{
|
||||
// A newer dry run took its place, or the dialog closed.
|
||||
result = new DryRun(templates);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException
|
||||
or FormatException)
|
||||
{
|
||||
Log.Warning("archive", "Reorganize dry run failed", ex);
|
||||
failure = ex;
|
||||
result = new DryRun(templates, 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(ApplyToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private async Task ApplyAsync()
|
||||
{
|
||||
var run = _run;
|
||||
if (run is not { Plan: { } plan, For: { } templates } || templates != Current()) return;
|
||||
ClearError();
|
||||
IsBusy = true;
|
||||
try
|
||||
{
|
||||
await _enqueue(ArchiveJobs.Reorganize(_archive, plan, templates));
|
||||
Log.Info("archive", $"Reorganize of {plan.Steps.Count(s => s.Changes)} sequence(s) in {_archive.RootPath} queued");
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", "The reorganize was not queued", ex);
|
||||
ShowError(ex);
|
||||
return;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
Close();
|
||||
}
|
||||
|
||||
/// <summary>A dry run: the templates it is for and, once it ended, its plan and rows, or why it failed.</summary>
|
||||
private sealed record DryRun(RenameTemplates? For, RenamePlan? Plan = null, IReadOnlyList<ReorganizeRow>? Rows = null, string? Error = null);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.App.Archiving;
|
||||
|
||||
/// <summary>What a Reorganize changes (owner review 2, R7): the sequences' folders, their photos' file names, their titles.</summary>
|
||||
[Flags]
|
||||
public enum ReorganizeParts
|
||||
{
|
||||
None = 0,
|
||||
Folders = 1,
|
||||
Files = 2,
|
||||
Titles = 4,
|
||||
}
|
||||
|
||||
/// <summary>One change of a dry-run row, before and after: a folder or a file name (read left to right) or a title.</summary>
|
||||
public sealed record ReorganizeLine(string Label, string From, string To, bool IsPath);
|
||||
|
||||
/// <summary>
|
||||
/// One sequence of the Reorganize dry run: its name, what concerns it as a whole (it follows its folder, how many of its
|
||||
/// files get a new name), its changes (the first renamed files as samples) and the photos that keep their names, with why.
|
||||
/// </summary>
|
||||
/// <param name="IsNamePath">The sequence has no title: <paramref name="Name"/> is its folder, read left to right.</param>
|
||||
public sealed record ReorganizeRow(Guid SequenceId, string Name, bool IsNamePath, string Note, IReadOnlyList<ReorganizeLine> Lines, IReadOnlyList<string> Kept)
|
||||
{
|
||||
public bool HasNote => Note.Length > 0;
|
||||
|
||||
public bool HasKept => Kept.Count > 0;
|
||||
|
||||
/// <summary>What a screen reader says after the name: the note, every change and every kept line.</summary>
|
||||
public string Description => string.Join(Environment.NewLine,
|
||||
[.. HasNote ? [Note] : (string[])[], .. Lines.Select(l => Loc.L("Archive.Reorganize.Change", l.Label, l.From, l.To)), .. Kept]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The words of a Reorganize (owner review 2, R7; BRIEF §7.1, §12.5): each template checked as it is typed, the engine's
|
||||
/// dry run (<see cref="RenamePlan"/>) as rows and a summary.
|
||||
/// </summary>
|
||||
public static class ReorganizePlans
|
||||
{
|
||||
/// <summary>What Reorganize… changes when opened from a mass bar: the archive's layout, folders and file names.</summary>
|
||||
public const ReorganizeParts Layout = ReorganizeParts.Folders | ReorganizeParts.Files;
|
||||
|
||||
/// <summary>
|
||||
/// The first problem of <paramref name="template"/> for <paramref name="part"/>, localized; null when it can be used.
|
||||
/// Folders and files follow the rules of the archive's templates (Settings › Archive); a title may use any token.
|
||||
/// </summary>
|
||||
public static string? Validate(ReorganizeParts part, string? template)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(template)) return Loc.L("Errors.Template.Empty", string.Empty, 1);
|
||||
switch (part)
|
||||
{
|
||||
case ReorganizeParts.Folders:
|
||||
return NamingPreview.Validate(template, isFolder: true);
|
||||
case ReorganizeParts.Files:
|
||||
return NamingPreview.Validate(template, isFolder: false);
|
||||
}
|
||||
var parsed = PathTemplate.Parse(template);
|
||||
if (parsed.Errors is [var error, ..]) return Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1);
|
||||
try
|
||||
{
|
||||
foreach (var frame in NamingPreview.SampleFrames) parsed.ExpandFile(frame);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return Loc.L("Errors.Template.Format");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The rows of a plan, in the order it applies them; a step that changes nothing lists why photos keep their names.</summary>
|
||||
public static IReadOnlyList<ReorganizeRow> Rows(RenamePlan plan) => [.. plan.Steps.Where(s => s.Changes || s.Blocked.Count > 0).Select(Row)];
|
||||
|
||||
public static ReorganizeRow Row(RenameStep step)
|
||||
{
|
||||
var title = string.IsNullOrWhiteSpace(step.ToTitle) ? step.FromTitle : step.ToTitle;
|
||||
var named = !string.IsNullOrWhiteSpace(title);
|
||||
var lines = new List<ReorganizeLine>();
|
||||
if (step.MovesFolder) lines.Add(new(Loc.L("Archive.Reorganize.Folder"), step.FromFolder, step.ToFolder, IsPath: true));
|
||||
if (step.Retitles) lines.Add(new(Loc.L("Archive.Reorganize.Title"), step.FromTitle ?? string.Empty, step.ToTitle ?? string.Empty, IsPath: false));
|
||||
lines.AddRange(step.FileSamples.Select(f => new ReorganizeLine(Loc.L("Archive.Reorganize.File"), f.From, f.To, IsPath: true)));
|
||||
string[] notes =
|
||||
[
|
||||
step.Carried ? Loc.L("Archive.Reorganize.Carried") : string.Empty,
|
||||
step.FileChanges > 0 ? Loc.Plural("Archive.Reorganize.Renamed", step.FileChanges) : string.Empty,
|
||||
];
|
||||
var kept = step.Blocked.Select(b => b.Frames > 0
|
||||
? Loc.L("Archive.Reorganize.Blocked." + b.Reason) + Loc.Separator + Loc.Plural("Shell.Status.Photos", b.Frames)
|
||||
: Loc.L("Archive.Reorganize.Blocked." + b.Reason)).ToList();
|
||||
var name = named ? title! : step.ToFolder.Length > 0 ? step.ToFolder : step.SequenceId.ToString("N")[..8];
|
||||
return new ReorganizeRow(step.SequenceId, name, !named, string.Join(Loc.Separator, notes.Where(n => n.Length > 0)), lines, kept);
|
||||
}
|
||||
|
||||
/// <summary>The sequences that change as chosen; those that only follow a folder they are in are listed, not counted.</summary>
|
||||
public static int Changed(RenamePlan plan) => plan.Steps.Count(s => s.Changes && !s.Carried);
|
||||
|
||||
/// <summary>
|
||||
/// "12 of 36 change · 3,600 files renamed · 20 names kept": the files only when the plan renames files, the names kept
|
||||
/// only when photos keep theirs.
|
||||
/// </summary>
|
||||
/// <remarks>The set is every sequence planned, including those that change nothing.</remarks>
|
||||
public static string Summary(RenamePlan plan, int setSize)
|
||||
{
|
||||
var parts = new List<string> { Loc.Plural("Archive.Rename.Summary", Changed(plan), setSize) };
|
||||
if (plan.FileTemplate is not null) parts.Add(Loc.Plural("Archive.Reorganize.Renamed", plan.Steps.Sum(s => s.FileChanges)));
|
||||
var kept = plan.Steps.Sum(s => s.Blocked.Sum(b => b.Frames));
|
||||
if (kept > 0) parts.Add(Loc.Plural("Archive.Reorganize.Kept", kept));
|
||||
return string.Join(Loc.Separator, parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What Settings › Archive offers to reorganize after its templates changed (owner review 2, R7): the archive and every
|
||||
/// template changed since the offer was last taken. A change while the toast is still up joins the offer on screen
|
||||
/// instead of raising another toast; a change in another archive raises its own.
|
||||
/// </summary>
|
||||
/// <param name="toastTime">How long a toast stays up.</param>
|
||||
public sealed class ReorganizeOffer(TimeSpan toastTime)
|
||||
{
|
||||
private (Core.Model.Archive Archive, ReorganizeParts Parts)? _pending;
|
||||
private DateTime _raised;
|
||||
|
||||
/// <summary>Records that <paramref name="part"/> of <paramref name="archive"/> changed at <paramref name="now"/>; true when a toast should offer it.</summary>
|
||||
public bool Add(Core.Model.Archive archive, ReorganizeParts part, DateTime now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
var same = _pending is { } pending && pending.Archive.Id == archive.Id;
|
||||
_pending = same ? (archive, _pending!.Value.Parts | part) : (archive, part);
|
||||
if (same && now - _raised < toastTime) return false;
|
||||
_raised = now;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The offer when a toast's action runs: the archive as it was last saved and every template changed; null when taken already.</summary>
|
||||
public (Core.Model.Archive Archive, ReorganizeParts Parts)? Take()
|
||||
{
|
||||
var pending = _pending;
|
||||
_pending = null;
|
||||
_raised = default;
|
||||
return pending;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,9 @@ public enum MassAction
|
||||
Verify,
|
||||
Tag,
|
||||
Rate,
|
||||
Move,
|
||||
|
||||
/// <summary>Folders, file names and titles from templates (owner review 2, R7), for the sequences of one archive.</summary>
|
||||
Reorganize,
|
||||
Upload,
|
||||
Download,
|
||||
Delete,
|
||||
@@ -71,7 +73,8 @@ public static class MassActions
|
||||
return null;
|
||||
}
|
||||
if (targets.Count == 0) return Loc.L("Library.Blocked.ServerOnly");
|
||||
return action == MassAction.Move && targets.Select(t => t.Sequence.ArchiveId).Distinct().Count() > 1 ? Loc.L("Library.Blocked.Archives") : null;
|
||||
// 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;
|
||||
}
|
||||
|
||||
/// <summary>The enabled tooltip: what the action does to how many sequences.</summary>
|
||||
|
||||
@@ -423,8 +423,8 @@
|
||||
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Thumbnails}" Command="{Binding ThumbnailsSetCommand}"
|
||||
ToolTip="{Binding ThumbnailsSetToolTip}" />
|
||||
<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.Rename}" Command="{Binding RenameSetCommand}" ToolTip="{Binding RenameSetToolTip}" />
|
||||
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Move}" Command="{Binding MoveSetCommand}" ToolTip="{Binding MoveSetToolTip}" />
|
||||
<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.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>
|
||||
|
||||
@@ -15,6 +15,7 @@ using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Ui.Mvvm;
|
||||
@@ -24,8 +25,8 @@ 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, rename,
|
||||
/// move, retag, CSV, delete into the trash), and the operations on the whole archive as jobs (scan, rebuild with 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
|
||||
/// 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.
|
||||
@@ -104,8 +105,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
ProxiesSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, SetLabel()), Set()), HasSet);
|
||||
ThumbnailsSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Thumbnails(ids, SetLabel()), Set()), HasSet);
|
||||
VerifySetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Verify(_archive!, ids), Set()), HasSet);
|
||||
RenameSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Titles), () => HasSet() && IsOnline());
|
||||
MoveSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Folders), () => HasSet() && IsOnline());
|
||||
ReorganizeSetCommand = new AsyncRelayCommand(() => OpenReorganizeDialogAsync(), () => HasSet() && IsOnline());
|
||||
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
|
||||
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
|
||||
DeleteSetCommand = new AsyncRelayCommand(DeleteSetAsync, () => HasSet() && IsOnline());
|
||||
@@ -174,8 +174,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
public string ThumbnailsSetToolTip => WhenSet("Tooltips.Archive.SetThumbnails");
|
||||
public string VerifySetToolTip => WhenSet("Tooltips.Archive.SetVerify");
|
||||
public string ExportSetToolTip => WhenSet("Tooltips.Archive.SetExport");
|
||||
public string RenameSetToolTip => WhenSet("Tooltips.Archive.SetRename", needsOnline: true);
|
||||
public string MoveSetToolTip => WhenSet("Tooltips.Archive.SetMove", needsOnline: true);
|
||||
public string ReorganizeSetToolTip => WhenSet("Tooltips.Archive.SetReorganize", needsOnline: true);
|
||||
public string RetagSetToolTip => WhenSet("Tooltips.Archive.SetRetag", needsOnline: true);
|
||||
public string DeleteSetToolTip => WhenSet("Tooltips.Archive.SetDelete", needsOnline: true);
|
||||
|
||||
@@ -275,8 +274,10 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
public ICommand ProxiesSetCommand { get; }
|
||||
public ICommand ThumbnailsSetCommand { get; }
|
||||
public ICommand VerifySetCommand { get; }
|
||||
public ICommand RenameSetCommand { get; }
|
||||
public ICommand MoveSetCommand { get; }
|
||||
|
||||
/// <summary>Reorganize…: the set's folders, file names and titles from templates, a dry run first, then a job.</summary>
|
||||
public ICommand ReorganizeSetCommand { get; }
|
||||
|
||||
public ICommand RetagSetCommand { get; }
|
||||
public ICommand ExportSetCommand { get; }
|
||||
|
||||
@@ -359,7 +360,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
|
||||
// ---------------- Dialogs ----------------
|
||||
|
||||
/// <summary>The open in-window dialog (rebuild, rename, retag, trash); null when none.</summary>
|
||||
/// <summary>The open in-window dialog (rebuild, reorganize, retag, delete, trash); null when none.</summary>
|
||||
public ArchiveDialogViewModel? Dialog
|
||||
{
|
||||
get => _dialog;
|
||||
@@ -627,8 +628,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
OnPropertyChanged(nameof(ThumbnailsSetToolTip));
|
||||
OnPropertyChanged(nameof(VerifySetToolTip));
|
||||
OnPropertyChanged(nameof(ExportSetToolTip));
|
||||
OnPropertyChanged(nameof(RenameSetToolTip));
|
||||
OnPropertyChanged(nameof(MoveSetToolTip));
|
||||
OnPropertyChanged(nameof(ReorganizeSetToolTip));
|
||||
OnPropertyChanged(nameof(RetagSetToolTip));
|
||||
OnPropertyChanged(nameof(DeleteSetToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
@@ -675,7 +675,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)) return;
|
||||
or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move)) return;
|
||||
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return;
|
||||
@@ -758,15 +758,53 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
Shell.Notify(Loc.L("Library.Queued", JobText.Kind(kind), label), actionText: Loc.L("Shell.Nav.Jobs"), actionToolTip: Loc.L("Tooltips.Nav.Jobs"),
|
||||
action: () => Shell.Navigate(SectionKey.Jobs));
|
||||
|
||||
/// <summary>Opens Rename or Move on the set and waits for its dry run.</summary>
|
||||
public async Task OpenRenameDialogAsync(RenameMode mode)
|
||||
/// <summary>Opens Reorganize on the set, the archive's layout (folders and file names) switched on, and waits for its dry run.</summary>
|
||||
public async Task OpenReorganizeDialogAsync()
|
||||
{
|
||||
if (Services.Archives is not { } archives || _archive is not { } archive) return;
|
||||
var dialog = new RenameDialogViewModel(mode, archives, archive, Set(), Applied, CloseDialog);
|
||||
if (Services.Archives is not { } archives || Services.Engine is not { } engine || _archive is not { } shown) return;
|
||||
IReadOnlyList<Guid> set = [.. Set().Select(s => s.Id)];
|
||||
// The templates as they are now: Settings › Archive may have changed them since this screen read the archive.
|
||||
var archive = await FreshAsync(shown);
|
||||
var dialog = new ReorganizeDialogViewModel(archives, archive, set, ReorganizePlans.Layout, r => EnqueueAsync(engine, r), CloseDialog);
|
||||
OpenDialog(dialog);
|
||||
await dialog.PlanAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens Reorganize on every sequence of <paramref name="archive"/> (Settings › Archive offers it after its templates
|
||||
/// changed), with <paramref name="parts"/> switched on; the screen shows that archive.
|
||||
/// </summary>
|
||||
public async Task OpenReorganizeAllAsync(Core.Model.Archive archive, ReorganizeParts parts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archive);
|
||||
if (Services.Archives is not { } archives || Services.Engine is not { } engine) return;
|
||||
if (_archive != archive) SelectedArchive = archive;
|
||||
var dialog = new ReorganizeDialogViewModel(archives, archive, null, parts, r => EnqueueAsync(engine, r), 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)
|
||||
{
|
||||
if (Services.Database is not { } db) return archive;
|
||||
try
|
||||
{
|
||||
return await db.Archives.GetAsync(archive.Id) ?? archive;
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("archive", "The archive's templates were not read again", ex);
|
||||
return archive;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task EnqueueAsync(JobEngine engine, ArchiveJobRequest request)
|
||||
{
|
||||
await engine.EnqueueAsync(request);
|
||||
Queued(request.Kind, request.Label ?? SetLabel());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete… on the set: the dry run, the typed confirmation and the move into the trash, in the in-window dialog the
|
||||
/// Library shares, which says how far it is and stops on Cancel. True when something left the archive.
|
||||
|
||||
@@ -422,7 +422,7 @@
|
||||
<ContextMenu ItemsSource="{Binding RatingChoices}" ItemContainerStyle="{StaticResource MenuItem.Rating}" />
|
||||
</Button.ContextMenu>
|
||||
</Button>
|
||||
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Library.Action.Move}" Command="{Binding MoveCommand}" ToolTip="{Binding MoveToolTip}" />
|
||||
<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.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}" />
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.App.Library;
|
||||
using Chronos.App.Server;
|
||||
using Chronos.App.Shell;
|
||||
@@ -14,6 +15,7 @@ using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
@@ -28,8 +30,9 @@ namespace Chronos.App.Sections;
|
||||
/// have no copy here (remote cards) — in a virtualised card grid, a table, or a timeline of year bands over the grid;
|
||||
/// filtered by search, year, camera, status, tag and origin, sorted, loaded page by page (keyset paging) as the view
|
||||
/// scrolls. Filters and sort can be saved as named views. Cards and rows reveal quick actions (open, analyse, render
|
||||
/// the sequence's preset, sync); a selection gets the mass actions bar (analyse, proxies, verify, tag, rate, move,
|
||||
/// upload, download, delete into the trash, CSV), each disabled with its reason when it cannot run on the selection.
|
||||
/// the sequence's preset, sync); a selection gets the mass actions bar (analyse, proxies, verify, tag, rate,
|
||||
/// reorganize, upload, download, delete into the trash, CSV), each disabled with its reason when it cannot run on the
|
||||
/// selection.
|
||||
/// </summary>
|
||||
public sealed class LibraryViewModel : SectionViewModel
|
||||
{
|
||||
@@ -126,7 +129,7 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
VerifyCommand = Mass(MassAction.Verify, t => _actions.VerifyAsync(t));
|
||||
TagCommand = Mass(MassAction.Tag, OpenRetag);
|
||||
RateCommand = new AsyncRelayCommand((p, _) => p is int rating ? RateAsync(rating) : Task.CompletedTask, _ => CanRun(MassAction.Rate));
|
||||
MoveCommand = Mass(MassAction.Move, OpenMoveAsync);
|
||||
ReorganizeCommand = Mass(MassAction.Reorganize, OpenReorganizeAsync);
|
||||
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)]));
|
||||
@@ -176,7 +179,9 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
/// <summary>Parameter: the rating, 0 (none) to 5.</summary>
|
||||
public ICommand RateCommand { get; }
|
||||
|
||||
public ICommand MoveCommand { get; }
|
||||
/// <summary>Reorganize…: the selection's folders, file names and titles from templates, a dry run first, then a job.</summary>
|
||||
public ICommand ReorganizeCommand { get; }
|
||||
|
||||
public ICommand UploadCommand { get; }
|
||||
public ICommand DownloadCommand { get; }
|
||||
public ICommand DeleteCommand { get; }
|
||||
@@ -486,7 +491,7 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
public string VerifyToolTip => MassToolTip(MassAction.Verify);
|
||||
public string TagToolTip => MassToolTip(MassAction.Tag);
|
||||
public string RateToolTip => MassToolTip(MassAction.Rate);
|
||||
public string MoveToolTip => MassToolTip(MassAction.Move);
|
||||
public string ReorganizeToolTip => MassToolTip(MassAction.Reorganize);
|
||||
public string UploadToolTip => MassToolTip(MassAction.Upload);
|
||||
public string DownloadToolTip => MassToolTip(MassAction.Download);
|
||||
public string DeleteToolTip => MassToolTip(MassAction.Delete);
|
||||
@@ -504,7 +509,7 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
|
||||
// ---------------- Dialogs ----------------
|
||||
|
||||
/// <summary>The open in-window dialog (tags, move, view name, delete); null when none.</summary>
|
||||
/// <summary>The open in-window dialog (tags, reorganize, view name, delete); null when none.</summary>
|
||||
public ArchiveDialogViewModel? Dialog
|
||||
{
|
||||
get => _dialog;
|
||||
@@ -1029,7 +1034,7 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
OnPropertyChanged(nameof(VerifyToolTip));
|
||||
OnPropertyChanged(nameof(TagToolTip));
|
||||
OnPropertyChanged(nameof(RateToolTip));
|
||||
OnPropertyChanged(nameof(MoveToolTip));
|
||||
OnPropertyChanged(nameof(ReorganizeToolTip));
|
||||
OnPropertyChanged(nameof(UploadToolTip));
|
||||
OnPropertyChanged(nameof(DownloadToolTip));
|
||||
OnPropertyChanged(nameof(DeleteToolTip));
|
||||
@@ -1165,12 +1170,20 @@ public sealed class LibraryViewModel : SectionViewModel
|
||||
OpenDialog(new RetagDialogViewModel(archives, targets, AppliedAsync, CloseDialog));
|
||||
}
|
||||
|
||||
/// <summary>Move: the archive engine's folder rename with its dry run, for sequences of one archive.</summary>
|
||||
private async Task OpenMoveAsync(IReadOnlyList<Sequence> targets)
|
||||
/// <summary>
|
||||
/// Reorganize…: the archive's folder and file templates (titles on request) applied to the selection of one archive,
|
||||
/// a dry run first, then the engine's job, which the Library follows to read the sequences again.
|
||||
/// </summary>
|
||||
private async Task OpenReorganizeAsync(IReadOnlyList<Sequence> targets)
|
||||
{
|
||||
if (Shell.Services.Archives is not { } archives || _db is null || targets.Count == 0) return;
|
||||
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 RenameDialogViewModel(RenameMode.Folders, archives, archive, targets, AppliedAsync, CloseDialog);
|
||||
var dialog = new ReorganizeDialogViewModel(archives, archive, [.. targets.Select(t => t.Id)], ReorganizePlans.Layout, 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));
|
||||
}, CloseDialog);
|
||||
OpenDialog(dialog);
|
||||
await dialog.PlanAsync();
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ using Chronos.Core.Naming;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Theming;
|
||||
|
||||
@@ -56,6 +58,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
|
||||
/// <summary>Drops a read of the open archive's settings that may have missed an edit being written meanwhile.</summary>
|
||||
private readonly ArchiveReadGate _archiveReads = new();
|
||||
|
||||
/// <summary>The archive whose templates changed and which of them, offered by a toast (as long as a toast stays up).</summary>
|
||||
private readonly ReorganizeOffer _reorganize = new(new Toast { Title = string.Empty }.Lifetime);
|
||||
private bool _isDetectingFormats;
|
||||
private IReadOnlyList<BackupOption> _backups = [];
|
||||
private BackupOption? _selectedBackup;
|
||||
@@ -104,13 +109,13 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
_s.FolderTemplate = v;
|
||||
Save();
|
||||
_ = UpdateArchiveAsync(a => a with { Templates = a.Templates with { Folder = v } });
|
||||
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { Folder = v } }), ReorganizeParts.Folders);
|
||||
}, () => Loc.L("Tooltips.Settings.FolderTemplate"));
|
||||
FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v =>
|
||||
{
|
||||
_s.FileTemplate = v;
|
||||
Save();
|
||||
_ = UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } });
|
||||
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } }), ReorganizeParts.Files);
|
||||
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
|
||||
FolderTemplate.PropertyChanged += (_, e) =>
|
||||
{
|
||||
@@ -1015,18 +1020,19 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
/// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again. An edit made
|
||||
/// while the archive at a folder just chosen is opening waits for it, then goes to that archive (or stays this PC's
|
||||
/// default when there is none), instead of being lost. <paramref name="retarget"/> is the folder change the edit was
|
||||
/// made after, the latest one by default.
|
||||
/// made after, the latest one by default. Returns the archive as the edit left it; null when no archive took it.
|
||||
/// </summary>
|
||||
private async Task UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit, Task<Archive?>? retarget = null)
|
||||
private async Task<Archive?> UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit, Task<Archive?>? retarget = null)
|
||||
{
|
||||
retarget ??= _retarget;
|
||||
var waited = !retarget.IsCompleted;
|
||||
if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return;
|
||||
if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return null;
|
||||
bool reload;
|
||||
Archive? saved = null;
|
||||
_archiveReads.BeginWrite();
|
||||
try
|
||||
{
|
||||
var updated = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
|
||||
var updated = saved = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
|
||||
// The archive folder may have changed meanwhile: the rows then belong to another archive.
|
||||
if (_archive?.Id == updated.Id) _archive = updated;
|
||||
// The open showed the archive's values over the edit: unless another folder was chosen since, the rows (and
|
||||
@@ -1047,6 +1053,36 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
}
|
||||
// Only once the write ended: a read begun while it is written waits for that end.
|
||||
if (reload) await LoadArchiveAsync();
|
||||
return saved;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A template names only what is filed from now on: once the archive took a new one (<paramref name="update"/>), a toast
|
||||
/// offers Reorganize, which applies the templates changed since to every sequence already in the archive, after a dry
|
||||
/// run (owner review 2, R7). A template changed while the toast is still up joins it instead of raising another.
|
||||
/// </summary>
|
||||
private async Task OfferReorganizeAsync(Task<Archive?> update, ReorganizeParts part)
|
||||
{
|
||||
if (await update is not { } archive || Shell.Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
// An empty archive has nothing to reorganize.
|
||||
if (await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id }) == 0) return;
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("settings", "The sequences of the archive were not counted", ex);
|
||||
return;
|
||||
}
|
||||
if (!_reorganize.Add(archive, part, DateTime.UtcNow)) return;
|
||||
Shell.Notify(Loc.L("Settings.Archive.TemplatesSaved"), Loc.L("Settings.Archive.ExistingKept"), Loc.L("Settings.Archive.Reorganize"),
|
||||
Loc.L("Tooltips.Settings.Reorganize"), () =>
|
||||
{
|
||||
// Every template changed since; what this toast offered when another one was used since.
|
||||
var (target, parts) = _reorganize.Take() ?? (archive, part);
|
||||
Shell.Navigate(SectionKey.Archive);
|
||||
_ = Shell.Archive.OpenReorganizeAllAsync(target, parts);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user