feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s

- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 21:58:39 +01:00
1 parent 9aa818ed47
commit 7e4a3b481d
416 files changed
+15304 -1572

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
{
+79 -32
View File
@@ -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; or why the whole sequence stays as it is. -->
<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>
+7 -7
View File
@@ -5,11 +5,11 @@ 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 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":
-39
View File
@@ -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,43 +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.</summary>
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !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,291 @@
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, or why the whole sequence stays as
/// it is (a sidecar that cannot be read). 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(), OnCommitted);
}
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();
}
/// <summary>
/// Enter, or the focus leaving a field, plans at once, unless the dry run on screen or the one under way is already of
/// these templates: a click on Apply takes the focus from the field first, and an identical dry run started then
/// would turn Apply off under the click.
/// </summary>
private void OnCommitted()
{
if (IsPlanned()) _delay.Stop();
else _ = PlanAsync();
}
/// <summary>The templates on screen have their plan, or a dry run of them is under way; false after a failed one.</summary>
private bool IsPlanned()
{
lock (_gate) return _run.For is { } templates && templates == Current() && (_run.Plan is not null || _planning is not null);
}
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);
}
+160
View File
@@ -0,0 +1,160 @@
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,
/// or why the whole sequence stays as it is.
/// </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.ExpandText(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, or
/// why the whole sequence stays as it is.
/// </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): per archive, every
/// template changed since its offer was last taken. A change while that archive's toast is still up joins the offer on
/// screen instead of raising another toast; a change in another archive raises its own, and each toast takes only its
/// archive's offer.
/// </summary>
/// <param name="toastTime">How long a toast stays up.</param>
public sealed class ReorganizeOffer(TimeSpan toastTime)
{
private readonly Dictionary<Guid, Pending> _pending = [];
/// <summary>
/// Records that <paramref name="part"/> of <paramref name="archive"/> changed at <paramref name="now"/>; true when a
/// toast should offer it (none of that archive is up), raised at <paramref name="now"/>.
/// </summary>
public bool Add(Core.Model.Archive archive, ReorganizeParts part, DateTime now)
{
ArgumentNullException.ThrowIfNull(archive);
var known = _pending.TryGetValue(archive.Id, out var pending);
var shown = known && pending!.Raised is { } raised && now - raised < toastTime;
_pending[archive.Id] = new Pending(archive, (known ? pending!.Parts : ReorganizeParts.None) | part, shown ? pending!.Raised : now);
return !shown;
}
/// <summary>
/// The toast of <paramref name="archiveId"/> raised at <paramref name="raised"/> left the screen (dismissed, timed out,
/// pushed out by newer ones): the next change raises a new one. A toast older than the one up now changes nothing.
/// </summary>
public void Closed(Guid archiveId, DateTime raised)
{
if (_pending.TryGetValue(archiveId, out var pending) && pending.Raised == raised) _pending[archiveId] = pending with { Raised = null };
}
/// <summary>
/// The offer of <paramref name="archiveId"/> when its toast's action runs: the archive as it was last saved and every
/// template changed; null when taken already. Other archives' offers stay.
/// </summary>
public (Core.Model.Archive Archive, ReorganizeParts Parts)? Take(Guid archiveId) =>
_pending.Remove(archiveId, out var pending) ? (pending.Archive, pending.Parts) : null;
/// <param name="Raised">When the toast on screen was raised; null once it left.</param>
private sealed record Pending(Core.Model.Archive Archive, ReorganizeParts Parts, DateTime? Raised);
}
+11
View File
@@ -150,6 +150,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
session.Source.JobChanged += OnJobChanged;
session.Source.ReadOnlyChanged += OnReadOnlyChanged;
shell.Services.Sync.Changed += OnSyncChanged;
shell.Services.SequenceReorganized += OnSequenceReorganized;
UpdateMarkers();
RefreshSteps();
RequestCorrections();
@@ -708,6 +709,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Session.Source.JobChanged -= OnJobChanged;
Session.Source.ReadOnlyChanged -= OnReadOnlyChanged;
Shell.Services.Sync.Changed -= OnSyncChanged;
Shell.Services.SequenceReorganized -= OnSequenceReorganized;
foreach (var tab in Tabs) tab.Dispose();
base.Dispose();
await Session.DisposeAsync();
@@ -1182,6 +1184,15 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (ServerJob is { } job) await Session.Source.CancelJobAsync(job.Id, CancellationToken.None);
}
/// <summary>
/// A Reorganize of this PC moved the folder of a sequence or renamed it or its files (any thread): the open sequence of
/// this PC is read again where it is now, so its frames decode and its project goes there.
/// </summary>
private void OnSequenceReorganized(Guid sequenceId) => _dispatcher.BeginInvoke(() =>
{
if (!_disposed && !IsRemote && sequenceId == Session.Content.Sequence.Id) _ = ReloadAsync(null);
});
/// <summary>The session, the sync links or the rights changed (any thread): whether the Export "Sync" option applies.</summary>
private void OnSyncChanged() => _dispatcher.BeginInvoke(() => _ = OnSyncChangedAsync());
+4 -3
View File
@@ -45,9 +45,10 @@ public interface ISequenceSource : IAsyncDisposable
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
/// <summary>
/// Whether the frames <see cref="LoadAsync"/> read last are still the sequence's, in the same order: frames inserted
/// or removed since (a sync download, an import of earlier photos, a scan) moved the stored project's positions. A
/// server sequence whose frames changed becomes <see cref="IsOutdated"/>.
/// Whether the frames <see cref="LoadAsync"/> read last are still the sequence's, in the same order and folder: frames
/// inserted or removed since (a sync download, an import of earlier photos, a scan) moved the stored project's
/// positions, and a Reorganize may have moved the folder. A server sequence whose frames changed becomes
/// <see cref="IsOutdated"/>.
/// </summary>
/// <exception cref="EditorException">The sequence is gone.</exception>
Task<bool> FramesCurrentAsync(CancellationToken cancellationToken);
+26 -12
View File
@@ -51,6 +51,9 @@ public sealed class LocalSequenceSource : ISequenceSource
/// <summary>The frames version of the frames last read (<see cref="LoadAsync"/>), whose order the project's positions follow.</summary>
private int _framesVersion = -1;
/// <summary>The archive-relative folder the last read found the sequence in (<see cref="LoadAsync"/>); a Reorganize moves it.</summary>
private string? _relativeFolder;
private ArchivePaths? _paths;
private SequencePaths? _folder;
@@ -98,7 +101,8 @@ public sealed class LocalSequenceSource : ISequenceSource
if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath);
}
_companions = [.. frames.Select(f => companions.GetValueOrDefault(f.Id))];
(_paths, _folder, _files, _frameIds, _framesVersion) = (paths, folder, files, [.. frames.Select(f => f.Id)], sequence.FramesVersion);
(_paths, _folder, _relativeFolder, _files, _frameIds, _framesVersion) =
(paths, folder, sequence.Folder, files, [.. frames.Select(f => f.Id)], sequence.FramesVersion);
var context = SequenceContext.FromFrames(frames);
var (report, otherFrames) = ReadReport(folder, frames.Count);
return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), report,
@@ -109,12 +113,15 @@ public sealed class LocalSequenceSource : ISequenceSource
}, cancellationToken);
}
/// <remarks>An insertion bumps the row's frames version in the transaction that renumbers the frames.</remarks>
/// <remarks>
/// An insertion bumps the row's frames version in the transaction that renumbers the frames; a Reorganize that moved
/// the folder leaves the version but not the files where they were read.
/// </remarks>
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
{
var framesVersion = _framesVersion;
var (framesVersion, folder) = (_framesVersion, _relativeFolder);
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
return row.FramesVersion == framesVersion;
return row.FramesVersion == framesVersion && row.Folder == folder;
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
@@ -157,7 +164,7 @@ public sealed class LocalSequenceSource : ISequenceSource
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(basis);
var (paths, folder, frameIds, framesVersion) = (_paths, _folder, _frameIds, _framesVersion);
var (paths, folder, relativeFolder, frameIds, framesVersion) = (_paths, _folder, _relativeFolder, _frameIds, _framesVersion);
if (paths is null || folder is null) throw new InvalidOperationException("LoadAsync first.");
return Task.Run(async () =>
{
@@ -168,8 +175,13 @@ public sealed class LocalSequenceSource : ISequenceSource
{
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
// Frames were inserted or removed since the editor read them, so its positions name the old order. Insertions
// hold this lease, so the frames do not change again before this save ends.
if (row.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Editor.Error.FramesArriving"));
// hold this lease, so the frames do not change again before this save ends. A Reorganize moves the folder under
// it too: moved since the read, the project goes to the new folder once the editor read the sequence there,
// and the folder it left is never created again.
if (row.FramesVersion != framesVersion || row.Folder != relativeFolder) throw new FramesChangedException(Loc.L("Editor.Error.FramesArriving"));
// Moved by another index of the archive (a server's Reorganize), which this index finds at its next scan; the folder
// it left may hold another sequence that index moved into it since.
if (!SequenceFolders.Holds(folder, _sequenceId)) throw Missing();
var stored = ReadProject(row, folder);
var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
var json = merged.ToJson();
@@ -218,9 +230,10 @@ public sealed class LocalSequenceSource : ISequenceSource
/// <summary>
/// The sequence row with its frames as one state: the frames are listed between two reads of the row that find the
/// same frames version (an insertion renumbers the frames and moves the row's positions in one transaction, and
/// bumps the version), so the project's positions name these frames.
/// bumps the version), so the project's positions name these frames, and the same folder (a Reorganize moves the
/// folder and rewrites the frames' paths in one transaction, the version kept), so the files are where they were read.
/// </summary>
/// <exception cref="EditorException">The sequence is gone, or an insertion landed during every attempt.</exception>
/// <exception cref="EditorException">The sequence is gone, or an insertion or a move landed during every attempt.</exception>
private async Task<(Sequence Row, List<Frame> Frames)> ReadFramesAsync(CancellationToken cancellationToken)
{
for (var attempt = 0; attempt < ReadAttempts; attempt++)
@@ -234,7 +247,7 @@ public sealed class LocalSequenceSource : ISequenceSource
if (page.Count < PageSize) break;
}
var after = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
if (after.FramesVersion == before.FramesVersion) return (after, frames);
if (after.FramesVersion == before.FramesVersion && after.Folder == before.Folder) return (after, frames);
}
throw new EditorException(Loc.L("Editor.Error.FramesArriving"));
}
@@ -281,7 +294,8 @@ public sealed class LocalSequenceSource : ISequenceSource
}
/// <summary>
/// The frames of a sequence of this PC changed since the editor read them (frames inserted or removed): nothing was
/// saved. The editor reads them again, moves its positions as the index moved the stored ones, and saves again.
/// The frames of a sequence of this PC changed since the editor read them (frames inserted or removed, or their folder
/// moved by a Reorganize): nothing was saved. The editor reads them again, moves its positions as the index moved the
/// stored ones, and saves again.
/// </summary>
public sealed class FramesChangedException(string message) : EditorException(message);
@@ -111,6 +111,12 @@ public sealed class AppServices : IAsyncDisposable
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
public SyncHost Sync { get; }
/// <summary>
/// A job of this PC moved a sequence's folder or changed its title or file names (a Reorganize step), with the
/// sequence's id (any thread): an open editor reads it again where it is now.
/// </summary>
public event Action<Guid>? SequenceReorganized;
public IEncoderInventory Encoders { get; set; }
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
@@ -452,6 +458,12 @@ public sealed class AppServices : IAsyncDisposable
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30))],
BackupDirectory = Environment.BackupDirectory,
// Told after each step of a Reorganize, while the rest of the job runs.
SequenceChanged = (id, _, _) =>
{
SequenceReorganized?.Invoke(id);
return Task.CompletedTask;
},
};
Archives = new ArchiveService(database, archive);
Processing = new ProcessingService(database, ProcessingOptions(archive));
+5 -2
View File
@@ -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>
+2 -2
View File
@@ -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>
+80 -17
View File
@@ -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.
@@ -60,6 +61,10 @@ public sealed class ArchiveViewModel : SectionViewModel
private bool _jobEvents;
private string _lastScanText = string.Empty;
private ArchiveDialogViewModel? _dialog;
/// <summary>A Reorganize the Settings toast asked for while a dialog was open: it opens once that one closes.</summary>
private (Core.Model.Archive Archive, ReorganizeParts Parts)? _waitingReorganize;
private IReadOnlyList<ArchiveTile> _tiles = [];
private IReadOnlyList<ChartRow> _months = [];
private IReadOnlyList<ChartItem> _storage = [];
@@ -104,8 +109,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 +178,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 +278,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 +364,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;
@@ -515,6 +520,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_reloadDelay.Stop();
_search?.Cancel();
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
_waitingReorganize = null;
_dialog?.Dispose();
base.Dispose();
}
@@ -627,8 +633,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 +680,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 +763,69 @@ 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. The toast is reached from
/// another screen, so a dialog may be open here, a Delete moving sequences say: it is never replaced nor its archive
/// switched under it; Reorganize waits, says so, and opens once that dialog closes.
/// </summary>
public async Task OpenReorganizeAllAsync(Core.Model.Archive archive, ReorganizeParts parts)
{
ArgumentNullException.ThrowIfNull(archive);
if (_dialog is not null)
{
_waitingReorganize = _waitingReorganize is { } waiting && waiting.Archive.Id == archive.Id ? (archive, waiting.Parts | parts) : (archive, parts);
Shell.Notify(Loc.L("Archive.Reorganize.Waiting"));
return;
}
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 Reorganize that waited for the dialog that just closed, with the archive's templates as they are now.</summary>
private async Task OpenWaitingReorganizeAsync()
{
if (_waitingReorganize is not { } waiting) return;
_waitingReorganize = null;
await OpenReorganizeAllAsync(await FreshAsync(waiting.Archive), waiting.Parts);
}
/// <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.
@@ -815,12 +874,16 @@ public sealed class ArchiveViewModel : SectionViewModel
await Shell.Library.RefreshAsync();
}
/// <summary>Closes <paramref name="dialog"/> if it is still the open one (an apply that finishes late closes nothing else).</summary>
/// <summary>
/// Closes <paramref name="dialog"/> if it is still the open one (an apply that finishes late closes nothing else); a
/// Reorganize asked for meanwhile opens then.
/// </summary>
private void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
_ = OpenWaitingReorganizeAsync();
}
private async Task AdoptAsync()
+1 -1
View File
@@ -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}" />
+24 -11
View File
@@ -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();
}
+52 -6
View File
@@ -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,46 @@ 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;
}
var raised = DateTime.UtcNow;
if (!_reorganize.Add(archive, part, raised)) return;
var toast = new Toast
{
Title = Loc.L("Settings.Archive.TemplatesSaved"),
Message = Loc.L("Settings.Archive.ExistingKept"),
ActionText = Loc.L("Settings.Archive.Reorganize"),
ActionToolTip = Loc.L("Tooltips.Settings.Reorganize"),
ActionCommand = new RelayCommand(() =>
{
// Every template of this archive changed since; what this toast offered when another toast of it took them.
var (target, parts) = _reorganize.Take(archive.Id) ?? (archive, part);
Shell.Navigate(SectionKey.Archive);
_ = Shell.Archive.OpenReorganizeAllAsync(target, parts);
}),
};
// Gone from the screen early (dismissed, pushed out), the next change of this archive raises a toast of its own.
toast.Closed += (_, _) => _reorganize.Closed(archive.Id, raised);
Shell.ShowToast(toast);
}
/// <summary>
+6 -32
View File
@@ -15,7 +15,10 @@ public static class NamingPreview
/// </summary>
public static IReadOnlyList<NamingContext> SampleFrames => BuildSample();
/// <summary>The first problem of <paramref name="template"/>, localized; null when it is valid.</summary>
/// <summary>
/// The first problem of <paramref name="template"/>, localized; null when it is valid. Beyond parsing and expanding,
/// the rules every place a template is used shares (<see cref="TemplateRules"/>), as the server checks them.
/// </summary>
public static string? Validate(string? template, bool isFolder)
{
var text = template ?? string.Empty;
@@ -33,12 +36,12 @@ public static class NamingPreview
var name = isFolder ? parsed.ExpandFolder(frame) : parsed.ExpandFile(frame);
if (name.Length == 0) return Loc.L("Errors.Template.Empty", string.Empty, 1);
}
if ((isFolder ? TemplateRules.FolderRule(parsed) : TemplateRules.FileRule(parsed)) is { } rule) return Loc.L("Errors.Template." + rule);
}
catch (FormatException)
{
return Loc.L("Errors.Template.Format");
}
if (!isFolder && !NumbersFrames(text)) return Loc.L("Errors.Template.NotUnique");
return null;
}
@@ -53,34 +56,5 @@ public static class NamingPreview
private static string Combine(string folder, string file) => folder.Length == 0 ? file : folder + "/" + file;
/// <summary>File names must tell frames apart: a frame number, the time of day or the original name.</summary>
private static bool NumbersFrames(string template)
{
var parsed = PathTemplate.Parse(template);
var names = SampleFrames.Select(parsed.ExpandFile).ToList();
return names.Distinct(StringComparer.OrdinalIgnoreCase).Count() == names.Count;
}
private static List<NamingContext> BuildSample()
{
var start = new DateTime(2026, 9, 28, 18, 2, 11);
var title = Loc.L("Settings.Naming.SampleTitle");
return Enumerable.Range(0, 3).Select(i => new NamingContext
{
CapturedAt = start.AddSeconds(2 * i),
SessionStart = start,
Session = 1,
Number = i + 1,
NumberInSession = i + 1,
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
Lens = "RF15-35mm F2.8 L IS USM",
Iso = 100,
ExposureTime = 1.0 / 250,
FNumber = 8,
OriginalName = "IMG_" + (4211 + i).ToString("0000", System.Globalization.CultureInfo.InvariantCulture),
Extension = "CR2",
Title = title,
}).ToList();
}
private static IReadOnlyList<NamingContext> BuildSample() => TemplateRules.Sample(Loc.L("Settings.Naming.SampleTitle"));
}
+2
View File
@@ -42,6 +42,8 @@ public static class ErrorText
{
LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException
or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message,
// A template an archive refused (Settings › Archive, or this PC's templates for a new archive): the rule it breaks.
TemplateRuleException rule => Loc.L("Errors.Template." + rule.Rule),
// The server words its errors in the client's language (Accept-Language).
ChronosApiException api when FromServer(api.Error) => api.Error.Message,
// Any other reply (a reverse proxy's 502 page while the server restarts, its 413 for a large body, a bare 500) holds