fix(app): archive tree selection, toolbar, filters and dialogs after review

- reloads and expanding never clear the tree selection; only jobs on this
  archive reload it, once they settle
- one-row toolbar with the view switch and last scan on their own row; figure
  tiles shrink instead of cutting at the minimum width
- set filter by camera, status and tag; duplicates and orphans searches can be
  cancelled; health fixes cover every matching sequence
- Right/Left/Enter open and close years; dialogs hold the keyboard and only
  close themselves; disabled commands say why
- adopt folder can copy into the layout (Import screen); database backup in
  Maintenance; Move dialog capture state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:44:22 +00:00
1 parent 29c82eba5c
commit 58ae096061
9 files changed
+614 -124

No files matched your search

+285 -53
View File
@@ -1,9 +1,11 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Archiving;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Shell;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
@@ -22,16 +24,24 @@ namespace Titano.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 set (analyse, proxies, thumbnails, verify, rename, move,
/// retag, CSV), and the operations on the whole archive as jobs (scan, rebuild with its dialog, verify,
/// maintenance), plus the maintenance view: index health, duplicates and orphans with safe fixes, recent runs.
/// figures and charts, mass operations on the selected and filtered set (analyse, proxies, thumbnails, verify, rename,
/// move, retag, CSV), and the operations on the whole archive as jobs (scan, rebuild with its dialog, verify,
/// maintenance), 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.
/// </summary>
public sealed class ArchiveViewModel : SectionViewModel
{
private const int RecentCount = 6;
private const int PageSize = 1000;
private static readonly TimeSpan ReloadDelay = TimeSpan.FromSeconds(2);
private readonly HashSet<ArchiveTreeNode> _selection = [];
/// <summary>Keys of the selected tree nodes (stable across reloads).</summary>
private readonly HashSet<string> _selection = new(StringComparer.Ordinal);
private readonly DispatcherTimer _reloadDelay;
private HashSet<Guid> _sequenceIds = [];
private ArchiveSetFilter _filter = new();
private bool _rebuildingRows;
private CancellationTokenSource? _search;
private IReadOnlyList<Core.Model.Archive> _archives = [];
private Core.Model.Archive? _archive;
private ArchiveAvailability _availability = ArchiveAvailability.Offline;
@@ -59,13 +69,22 @@ public sealed class ArchiveViewModel : SectionViewModel
: base(SectionKey.Archive, "Icon.Archive")
{
Shell = shell;
_reloadDelay = new DispatcherTimer { Interval = ReloadDelay };
_reloadDelay.Tick += (_, _) =>
{
_reloadDelay.Stop();
_ = LoadAsync();
};
ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a)), IsOnline);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
BackupCommand = new AsyncRelayCommand(BackupAsync, () => Services.Database is not null);
MaintenanceCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
MaintenanceDryRunCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a, dryRun: true)), () => _archive is not null);
RebuildProxiesCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, _archive!.Name, force: true), All()), IsOnline);
ClearFilterCommand = new RelayCommand(() => Filter = new ArchiveSetFilter(), () => !_filter.IsEmpty);
RelinkCommand = new AsyncRelayCommand(RelinkAsync);
HistoryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs));
@@ -73,13 +92,14 @@ 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 RelayCommand(() => OpenRename(RenameMode.Titles), () => HasSet() && IsOnline());
MoveSetCommand = new RelayCommand(() => OpenRename(RenameMode.Folders), () => HasSet() && IsOnline());
RenameSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Titles), () => HasSet() && IsOnline());
MoveSetCommand = new AsyncRelayCommand(() => OpenRenameDialogAsync(RenameMode.Folders), () => HasSet() && IsOnline());
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
FindDuplicatesCommand = new AsyncRelayCommand(FindDuplicatesAsync, () => _archive is not null && !_findingDuplicates);
FindOrphansCommand = new AsyncRelayCommand(FindOrphansAsync, () => IsOnline() && !_findingOrphans);
FindDuplicatesCommand = new AsyncRelayCommand(FindDuplicatesAsync, () => _archive is not null && _search is null);
FindOrphansCommand = new AsyncRelayCommand(FindOrphansAsync, () => IsOnline() && _search is null);
CancelSearchCommand = new RelayCommand(() => _search?.Cancel(), () => _search is not null);
MarkDuplicatesCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
}
@@ -128,15 +148,29 @@ public sealed class ArchiveViewModel : SectionViewModel
public string ScanToolTip => WhenOnline("Tooltips.Archive.Scan");
public string VerifyToolTip => WhenOnline("Tooltips.Archive.Verify");
public string OrphansToolTip => WhenOnline("Tooltips.Archive.Orphans");
public string RenameSetToolTip => WhenOnline("Tooltips.Archive.SetRename");
public string MoveSetToolTip => WhenOnline("Tooltips.Archive.SetMove");
public string RetagSetToolTip => WhenOnline("Tooltips.Archive.SetRetag");
public string MaintenanceRunToolTip => WhenOnline("Tooltips.Archive.MaintenanceRun");
public string RebuildProxiesToolTip => WhenOnline("Tooltips.Archive.MaintenanceProxies");
public string MarkDuplicatesToolTip => WhenOnline("Tooltips.Archive.MarkDuplicates");
public string DuplicatesToolTip => _search is not null ? Loc.L("Archive.Blocked.Searching") : Loc.L("Tooltips.Archive.Duplicates");
public string OrphansToolTip => _search is not null ? Loc.L("Archive.Blocked.Searching") : WhenOnline("Tooltips.Archive.Orphans");
public string AnalyseSetToolTip => WhenSet("Tooltips.Archive.SetAnalyse");
public string ProxiesSetToolTip => WhenSet("Tooltips.Archive.SetProxies");
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 RetagSetToolTip => WhenSet("Tooltips.Archive.SetRetag", needsOnline: true);
public ICommand ScanCommand { get; }
public ICommand RebuildCommand { get; }
public ICommand VerifyCommand { get; }
public ICommand AdoptCommand { get; }
/// <summary>"Adopt folder ▾ › Copy into the layout": the Import screen copies the folder into the archive with its templates.</summary>
public ICommand CopyFolderCommand { get; }
public ICommand BackupCommand { get; }
public ICommand MaintenanceCommand { get; }
public ICommand MaintenanceDryRunCommand { get; }
public ICommand RebuildProxiesCommand { get; }
@@ -157,17 +191,45 @@ public sealed class ArchiveViewModel : SectionViewModel
/// <summary>Photos per month in the culture's digits.</summary>
public Func<double, string> CountFormatter { get; } = v => Formatting.Count((long)v);
/// <summary>"412 sequences · all", "36 sequences · 2025", "Harbour sunset".</summary>
/// <summary>"412 sequences · all", "36 sequences", "Harbour sunset", each followed by the filter ("· Canon EOS R5").</summary>
public string SetText
{
get
{
var set = Set();
if (_selection.Count == 0 || _selection.Any(n => n.Kind == TreeNodeKind.Archive)) return Loc.Plural("Archive.Set.All", set.Count);
return set.Count == 1 ? set[0].DisplayTitle : Loc.Plural("Shell.Status.Sequences", set.Count);
var selected = SelectedNodes().ToList();
var text = selected.Count == 0 || selected.Any(n => n.Kind == TreeNodeKind.Archive)
? Loc.Plural("Archive.Set.All", set.Count)
: set.Count == 1 ? set[0].DisplayTitle : Loc.Plural("Shell.Status.Sequences", set.Count);
return _filter.IsEmpty ? text : text + " · " + _filter.Describe();
}
}
/// <summary>Camera, status and tag on top of the tree selection.</summary>
public ArchiveSetFilter Filter
{
get => _filter;
private set
{
if (!Set(ref _filter, value)) return;
OnSetChanged();
}
}
public IReadOnlyList<FilterChoice> CameraChoices => Choices(
(_tree?.Root.Sequences() ?? []).Select(ArchiveSetFilter.CameraOf).Distinct(StringComparer.Ordinal).Order(StringComparer.CurrentCultureIgnoreCase),
c => c, c => _filter.Camera == c, c => _filter with { Camera = c });
public IReadOnlyList<FilterChoice> StatusChoices => Choices(
Enum.GetValues<StatusFilter>().Where(f => f != StatusFilter.Any), ArchiveSetFilter.StatusLabel, f => _filter.Status == f,
f => _filter with { Status = f });
public IReadOnlyList<FilterChoice> TagChoices => Choices(
(_tree?.Root.Sequences() ?? []).SelectMany(q => q.Tags).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.CurrentCultureIgnoreCase),
t => t, t => string.Equals(_filter.Tag, t, StringComparison.OrdinalIgnoreCase), t => _filter with { Tag = t });
public ICommand ClearFilterCommand { get; }
public ICommand AnalyseSetCommand { get; }
public ICommand ProxiesSetCommand { get; }
public ICommand ThumbnailsSetCommand { get; }
@@ -177,19 +239,37 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
/// <summary>The view reports the selected tree rows.</summary>
/// <summary>The view reports the rows the user selected; the list's own clearing while rows are rebuilt is not a choice.</summary>
public void SetSelection(IEnumerable<ArchiveTreeRowViewModel> rows)
{
if (_rebuildingRows) return;
_selection.Clear();
foreach (var row in rows) _selection.Add(row.Node);
OnPropertyChanged(nameof(SetText));
CommandManager.InvalidateRequerySuggested();
foreach (var row in rows) _selection.Add(row.Node.Key);
OnSetChanged();
}
/// <summary>Whether a visible row is part of the selection (the view restores the list's selection after a rebuild).</summary>
public bool IsSelectedRow(ArchiveTreeRowViewModel row) => _selection.Contains(row.Node.Key);
/// <summary>Raised after the rows were rebuilt; the view selects the rows of <see cref="IsSelectedRow"/> again.</summary>
public event Action? RowsRebuilt;
/// <summary>Expands or collapses a year (Right/Left/Enter on its row, or its arrow).</summary>
public void Toggle(ArchiveTreeRowViewModel row) => Toggle(row.Node);
// ---------------- Maintenance view ----------------
public IReadOnlyList<HealthLineViewModel> Health { get => _health; private set => Set(ref _health, value); }
public IReadOnlyList<MaintenanceRow> Recent { get => _recent; private set => Set(ref _recent, value); }
public IReadOnlyList<MaintenanceRow> Recent
{
get => _recent;
private set
{
if (Set(ref _recent, value)) OnPropertyChanged(nameof(HasRecent));
}
}
public bool HasRecent => _recent.Count > 0;
public IReadOnlyList<DuplicateRowViewModel>? Duplicates
{
@@ -209,6 +289,9 @@ public sealed class ArchiveViewModel : SectionViewModel
}
}
/// <summary>A duplicates or orphans search runs; it can be cancelled.</summary>
public bool IsSearching => _search is not null;
/// <summary>"3 groups", "None found", or empty before the first search.</summary>
public string DuplicatesText => _findingDuplicates ? Loc.L("Archive.Find.Searching")
: _duplicates is null ? string.Empty
@@ -222,6 +305,7 @@ public sealed class ArchiveViewModel : SectionViewModel
public ICommand FindDuplicatesCommand { get; }
public ICommand FindOrphansCommand { get; }
public ICommand CancelSearchCommand { get; }
public ICommand MarkDuplicatesCommand { get; }
// ---------------- Dialogs ----------------
@@ -232,12 +316,17 @@ public sealed class ArchiveViewModel : SectionViewModel
get => _dialog;
private set
{
if (Set(ref _dialog, value)) OnPropertyChanged(nameof(IsDialogOpen));
if (!Set(ref _dialog, value)) return;
OnPropertyChanged(nameof(IsDialogOpen));
OnPropertyChanged(nameof(IsContentEnabled));
}
}
public bool IsDialogOpen => _dialog is not null;
/// <summary>The screen behind an open dialog takes neither clicks nor keyboard focus.</summary>
public bool IsContentEnabled => _dialog is null;
public bool IsEmpty => _loaded && _archive is null;
// ---------------- Lifecycle ----------------
@@ -292,7 +381,7 @@ public sealed class ArchiveViewModel : SectionViewModel
await engine.EnqueueAsync(request);
Queued(request.Kind, archive.Name);
}, CloseDialog);
Dialog = dialog;
OpenDialog(dialog);
await dialog.CountAsync();
return dialog;
}
@@ -306,6 +395,8 @@ public sealed class ArchiveViewModel : SectionViewModel
public override void Dispose()
{
_reloadDelay.Stop();
_search?.Cancel();
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
_dialog?.Dispose();
base.Dispose();
@@ -349,22 +440,41 @@ public sealed class ArchiveViewModel : SectionViewModel
private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) =>
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
/// <summary>A reloaded tree keeps the open years and the selection (nodes that still exist).</summary>
private void ShowTree(ArchiveTree tree)
{
var expanded = _tree?.ExpandedKeys();
var expanded = _tree?.Root.Key == tree.Root.Key ? _tree.ExpandedKeys() : null;
if (expanded is not null) tree.Expand(expanded);
else if (tree.Root.Children.Count > 0) tree.Root.Children[0].IsExpanded = true;
else
{
_selection.Clear();
if (tree.Root.Children.Count > 0) tree.Root.Children[0].IsExpanded = true;
}
_tree = tree;
_selection.Clear();
_sequenceIds = [.. tree.Root.Sequences().Select(q => q.Id)];
RebuildRows();
}
/// <summary>
/// The visible rows again (after a reload or a toggle). Selected rows that are now hidden — the user collapsed their
/// year — leave the selection, so the set is always what the list shows selected.
/// </summary>
private void RebuildRows()
{
TreeRows.Clear();
if (_tree is null) return;
foreach (var node in _tree.Visible()) TreeRows.Add(new ArchiveTreeRowViewModel(node, _tree.Availability, Toggle));
OnPropertyChanged(nameof(SetText));
_rebuildingRows = true;
try
{
TreeRows.Clear();
if (_tree is null) return;
foreach (var node in _tree.Visible()) TreeRows.Add(new ArchiveTreeRowViewModel(node, _tree.Availability, Toggle));
_selection.IntersectWith(TreeRows.Select(r => r.Node.Key));
}
finally
{
_rebuildingRows = false;
}
RowsRebuilt?.Invoke();
OnSetChanged();
}
private void Toggle(ArchiveTreeNode node)
@@ -374,6 +484,36 @@ public sealed class ArchiveViewModel : SectionViewModel
RebuildRows();
}
/// <summary>The set changed (selection, filter or tree): its text, the filter menus and the mass commands follow.</summary>
private void OnSetChanged()
{
OnPropertyChanged(nameof(SetText));
OnPropertyChanged(nameof(CameraChoices));
OnPropertyChanged(nameof(StatusChoices));
OnPropertyChanged(nameof(TagChoices));
OnPropertyChanged(nameof(AnalyseSetToolTip));
OnPropertyChanged(nameof(ProxiesSetToolTip));
OnPropertyChanged(nameof(ThumbnailsSetToolTip));
OnPropertyChanged(nameof(VerifySetToolTip));
OnPropertyChanged(nameof(ExportSetToolTip));
OnPropertyChanged(nameof(RenameSetToolTip));
OnPropertyChanged(nameof(MoveSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
CommandManager.InvalidateRequerySuggested();
}
private IEnumerable<ArchiveTreeNode> SelectedNodes() => TreeRows.Where(r => _selection.Contains(r.Node.Key)).Select(r => r.Node);
/// <summary>One filter menu: each value checked when chosen; choosing it again clears it.</summary>
private IReadOnlyList<FilterChoice> Choices<T>(IEnumerable<T> values, Func<T, string> label, Func<T, bool> isChosen, Func<T?, ArchiveSetFilter> choose) =>
[
.. values.Select(v =>
{
var chosen = isChosen(v);
return new FilterChoice(label(v), chosen, new RelayCommand(() => Filter = choose(chosen ? default : v)));
}),
];
private async Task LoadRecentAsync(TitanoDatabase db, Core.Model.Archive archive)
{
var jobs = new List<Job>();
@@ -394,16 +534,25 @@ public sealed class ArchiveViewModel : SectionViewModel
_jobEvents = true;
}
/// <summary>A finished archive job changes the figures: read them again.</summary>
/// <summary>
/// A finished job on this archive or its sequences changes the figures: read them again once the jobs settle (a
/// burst of analyses after an import reloads once). Jobs of other archives are none of this screen's business.
/// </summary>
private void OnJobChanged(Job job)
{
if (job.State is not (JobState.Done or JobState.Failed) || _archive is null) return;
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;
System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{
if (IsSelected) _ = LoadAsync();
else _loaded = false;
if (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return;
if (!IsSelected)
{
_loaded = false;
return;
}
_reloadDelay.Stop();
_reloadDelay.Start();
});
}
@@ -416,7 +565,14 @@ public sealed class ArchiveViewModel : SectionViewModel
private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0;
private IReadOnlyList<Sequence> Set() => _tree is null ? [] : ArchiveTree.SetOf(_tree, _selection);
/// <summary>A mass command's tooltip, or why it is disabled (an empty set; for writes, an archive that is not online).</summary>
private string WhenSet(string key, bool needsOnline = false) =>
_tree is not null && !HasSet() ? Loc.L("Archive.Blocked.EmptySet")
: needsOnline ? WhenOnline(key)
: Loc.L(key);
/// <summary>The set the mass operations act on: the selected rows' sequences (all when nothing is selected), filtered.</summary>
private IReadOnlyList<Sequence> Set() => _tree is null ? [] : [.. ArchiveTree.SetOf(_tree, SelectedNodes()).Where(_filter.Matches)];
private IReadOnlyList<Sequence> All() => _tree is null ? [] : ArchiveTree.SetOf(_tree, []);
@@ -438,12 +594,20 @@ public sealed class ArchiveViewModel : SectionViewModel
Queued(request.Kind, request.Label ?? SetLabel());
}
/// <summary>Health fixes act on the sequences that miss a status (never verified, no proxies).</summary>
/// <summary>Health fixes act on every sequence that misses a status (never verified, no proxies), page by page.</summary>
private async Task QueueStatusAsync(SequenceStatus missing, Func<IReadOnlyList<Guid>, ArchiveJobRequest> build)
{
if (Services.Database is not { } db || _archive is not { } archive) return;
var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = missing, Limit = PageSize });
await QueueSetAsync(build, page.Items);
var all = new List<Sequence>();
string? cursor = null;
do
{
var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = missing, Limit = PageSize, Cursor = cursor });
all.AddRange(page.Items);
cursor = page.NextCursor;
}
while (cursor is not null);
await QueueSetAsync(build, all);
}
private static string CountLabel(IReadOnlyList<Guid> ids) => Loc.Plural("Shell.Status.Sequences", ids.Count);
@@ -452,18 +616,25 @@ 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));
private void OpenRename(RenameMode mode)
/// <summary>Opens Rename or Move on the set and waits for its dry run.</summary>
public async Task OpenRenameDialogAsync(RenameMode mode)
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
var dialog = new RenameDialogViewModel(mode, archives, archive, Set(), Applied, CloseDialog);
Dialog = dialog;
_ = dialog.PlanAsync();
OpenDialog(dialog);
await dialog.PlanAsync();
}
private void OpenRetag()
{
if (Services.Archives is not { } archives) return;
Dialog = new RetagDialogViewModel(archives, Set(), Applied, CloseDialog);
OpenDialog(new RetagDialogViewModel(archives, Set(), Applied, CloseDialog));
}
private void OpenDialog(ArchiveDialogViewModel dialog)
{
_dialog?.Dispose();
Dialog = dialog;
}
private async Task Applied(int changed)
@@ -473,9 +644,11 @@ public sealed class ArchiveViewModel : SectionViewModel
await Shell.Library.RefreshAsync();
}
private void CloseDialog()
/// <summary>Closes <paramref name="dialog"/> if it is still the open one (an apply that finishes late closes nothing else).</summary>
private void CloseDialog(ArchiveDialogViewModel dialog)
{
_dialog?.Dispose();
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
}
@@ -490,6 +663,32 @@ public sealed class ArchiveViewModel : SectionViewModel
}
}
/// <summary>Copies a folder tree into the archive's layout: the Import screen plans it with the archive's templates.</summary>
private void CopyFolder()
{
var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Copy.Title"));
if (folder is null) return;
Shell.Navigate(SectionKey.Import);
_ = Shell.Import.ImportFolderAsync(folder);
}
/// <summary>A consistent copy of the index next to the data folder (the same backup as Settings › Advanced).</summary>
private async Task BackupAsync()
{
if (Services.Database is not { } db) return;
try
{
var path = await db.BackupAsync(Services.Environment.BackupDirectory);
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
() => ShellActions.Reveal(path));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or NotSupportedException)
{
Log.Warning("archive", "Database backup failed", ex);
Shell.Notify(Loc.L("Archive.Backup.Failed"), ex.Message);
}
}
/// <summary>A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).</summary>
private async Task RelinkAsync()
{
@@ -525,16 +724,21 @@ public sealed class ArchiveViewModel : SectionViewModel
() => ShellActions.Reveal(path));
}
/// <summary>Duplicates by hash across the archive (a read of the index); cancellable.</summary>
private async Task FindDuplicatesAsync()
{
if (Services.Archives is not { } archives || Services.Database is not { } db || _archive is not { } archive) return;
ViewIndex = 1;
_findingDuplicates = true;
OnPropertyChanged(nameof(DuplicatesText));
var search = StartSearch();
try
{
var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id));
Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id));
var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id, search.Token), search.Token);
Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
{
}
catch (DatabaseException ex)
{
@@ -543,21 +747,26 @@ public sealed class ArchiveViewModel : SectionViewModel
finally
{
_findingDuplicates = false;
OnPropertyChanged(nameof(DuplicatesText));
CommandManager.InvalidateRequerySuggested();
EndSearch(search);
}
}
/// <summary>Orphans: every sequence folder against its sidecar and the index (a walk of the archive); cancellable.</summary>
private async Task FindOrphansAsync()
{
if (Services.Archives is not { } archives || Services.Database is not { } db || _archive is not { } archive) return;
ViewIndex = 1;
_findingOrphans = true;
OnPropertyChanged(nameof(OrphansText));
var search = StartSearch();
try
{
var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id));
Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id));
var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id, search.Token), search.Token);
Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
Log.Info("archive", $"Orphans search in {archive.RootPath}: {report.UnindexedFiles} unlisted, {report.MissingFiles} missing, "
+ $"{report.MissingSequences.Count} rows without sidecar, {report.UnindexedFolders.Count} new folders");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException)
{
@@ -567,11 +776,34 @@ public sealed class ArchiveViewModel : SectionViewModel
finally
{
_findingOrphans = false;
OnPropertyChanged(nameof(OrphansText));
CommandManager.InvalidateRequerySuggested();
EndSearch(search);
}
}
private CancellationTokenSource StartSearch()
{
_search = new CancellationTokenSource();
OnSearchChanged();
return _search;
}
private void EndSearch(CancellationTokenSource search)
{
if (ReferenceEquals(_search, search)) _search = null;
search.Dispose();
OnSearchChanged();
}
private void OnSearchChanged()
{
OnPropertyChanged(nameof(IsSearching));
OnPropertyChanged(nameof(DuplicatesText));
OnPropertyChanged(nameof(OrphansText));
OnPropertyChanged(nameof(DuplicatesToolTip));
OnPropertyChanged(nameof(OrphansToolTip));
CommandManager.InvalidateRequerySuggested();
}
private IReadOnlyList<DuplicateRowViewModel> DuplicateRows(IReadOnlyList<DuplicateGroup> groups, IReadOnlyList<SequenceLocation> locations) =>
[
.. MaintenanceReports.Duplicates(groups, locations).Select(row => new DuplicateRowViewModel(row,