diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index 951c7220..2148b764 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -4,12 +4,20 @@
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Copy into the layout…
+ Index in place…
{0:N0} sequence changed
{0:N0} sequences changed
offline
online
read-only
+ The database backup stoppedlong
+ Wait until the changes are applied.long
+ The set is empty: change the selection or the filter.long
+ Nothing would change.long
The archive must be online and writable.long
+ Wait for the dry run.long
+ A search is running; cancel it or wait.long
By camera
By format
{0} · {1} · {2}invariant
@@ -25,6 +33,7 @@
Remove row
Remove {0} from the index?long
Its sidecar is gone. Only the index row is removed; no file is deleted.long
+ Folder to copy into the archivelong
Cancel
{0:N0} copy
{0:N0} copies
@@ -45,6 +54,7 @@
{0} changed after the plan was made.long: error sentence
The card or folder {0} is no longer available.long: error sentence
The archive changed after this plan was made.long: error sentence
+ Cancel
None found
Find
Searching…
@@ -82,6 +92,7 @@
{0} folders, {1} indexed, {2} adopted, {3} removedlong: job log line
Sequence not found: {0}long: job log line
{0} photos checked, {1} intact, {2} hashed, {3} with problemslong: job log line
+ Back up database
Dry run
Rebuild proxies
Relink moved archive…
@@ -114,6 +125,7 @@
Sidecars
Rebuild
State
+ No maintenance yet.long
History
{0} · {1}invariant
Recent maintenance
@@ -139,8 +151,10 @@
{0:N0} sequence · all
{0:N0} sequences · all
Analyse
+ Clear filter
Export CSV
- Selected set
+ Set filter
+ Filtered set
Move…
Proxies
Rename…
@@ -159,6 +173,7 @@
sequences
{0} – {1}invariant
Adopt folder…
+ Adopt folder
Archive
Duplicates
Maintenance
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index 8689b0be..fd159c3b 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -4,12 +4,20 @@
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ Copia nella struttura…
+ Indicizza sul posto…
{0:N0} sequenza modificata
{0:N0} sequenze modificate
offline
online
sola lettura
+ La copia del database si è interrotta
+ Attendi che le modifiche siano applicate.
+ La selezione è vuota: cambia la selezione o il filtro.
+ Non cambierebbe nulla.
L'archivio deve essere raggiungibile e scrivibile.
+ Attendi la simulazione.
+ Una ricerca è in corso: annullala o attendi.
Per fotocamera
Per formato
Foto al mese
@@ -17,11 +25,12 @@
{0:N0} altre
Altro
Spazio per anno
- Fotocamera ignota
+ Fotocamera sconosciuta
Mantieni riga
Rimuovi riga
Rimuovere {0} dall'indice?
Il suo sidecar non c'è più. Viene rimossa solo la riga dell'indice; nessun file viene eliminato.
+ Cartella da copiare nell'archivio
Annulla
{0:N0} copia
{0:N0} copie
@@ -41,6 +50,7 @@
{0} è cambiato dopo la creazione del piano.
La scheda o cartella {0} non è più disponibile.
L'archivio è cambiato dopo la creazione del piano.
+ Annulla
Nessuno trovato
Cerca
Ricerca…
@@ -60,12 +70,12 @@
{0:N0} sequenze senza proxy
{0:N0} sequenza non analizzata
{0:N0} sequenze non analizzate
- Proxy pronti per tutte
+ Ogni sequenza ha i proxy
Stato dell'indice
{0:N0} sequenza non verificata
{0:N0} sequenze non verificate
Ultima scansione {0} · {1}
- Prova: nulla è stato modificato.
+ Simulazione: nulla è stato modificato.
Non indicizzata: {0} ({1})
Modificato: {0}
Danneggiato: {0}
@@ -78,6 +88,7 @@
{0} cartelle, {1} indicizzate, {2} adottate, {3} rimosse
Sequenza non trovata: {0}
{0} foto controllate, {1} integre, {2} con impronta nuova, {3} con problemi
+ Copia del database
Simulazione
Ricrea proxy
Ricollega archivio spostato…
@@ -110,6 +121,7 @@
Sidecar
Ricostruisci
Stato
+ Ancora nessuna manutenzione.
Cronologia
Manutenzione recente
{0} ricollegato
@@ -134,8 +146,10 @@
{0:N0} sequenza · tutte
{0:N0} sequenze · tutte
Analizza
+ Togli filtro
Esporta CSV
- Insieme scelto
+ Filtro selezione
+ Selezione
Sposta…
Proxy
Rinomina…
@@ -153,6 +167,7 @@
sequenza
sequenze
Adotta cartella…
+ Adotta cartella
Archivio
Doppioni
Manutenzione
diff --git a/src/Titano.App/Archive/ArchiveDialogViewModels.cs b/src/Titano.App/Archive/ArchiveDialogViewModels.cs
index 8415a930..2ac3c6d0 100644
--- a/src/Titano.App/Archive/ArchiveDialogViewModels.cs
+++ b/src/Titano.App/Archive/ArchiveDialogViewModels.cs
@@ -13,20 +13,29 @@ using Titano.Ui.Mvvm;
namespace Titano.App.Archiving;
-/// An in-window dialog of the Archive screen: one primary action, one way out.
-public abstract class ArchiveDialogViewModel(Action close) : LocalizedViewModel
+///
+/// An in-window dialog of the Archive screen: one primary action, one way out. While its action runs it cannot be
+/// closed; receives the dialog, so a late close never closes another one.
+///
+public abstract class ArchiveDialogViewModel : LocalizedViewModel
{
private bool _isBusy;
private string? _busyText;
- public ICommand CloseCommand { get; } = new RelayCommand(close);
+ protected ArchiveDialogViewModel(Action close) => CloseCommand = new RelayCommand(() => close(this), () => !IsBusy);
+
+ public ICommand CloseCommand { get; }
+
+ public string CloseToolTip => IsBusy ? Loc.L("Archive.Blocked.Applying") : Loc.L("Tooltips.Archive.CloseDialog");
public bool IsBusy
{
get => _isBusy;
protected set
{
- if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested();
+ if (!Set(ref _isBusy, value)) return;
+ OnPropertyChanged(nameof(CloseToolTip));
+ CommandManager.InvalidateRequerySuggested();
}
}
@@ -47,7 +56,8 @@ public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
private readonly Func _rebuild;
private IReadOnlyList _facts;
- public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func rebuild, Action close)
+ public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func rebuild,
+ Action close)
: base(close)
{
_rebuild = rebuild;
@@ -137,7 +147,7 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
private CancellationTokenSource? _planning;
public RenameDialogViewModel(RenameMode mode, ArchiveService archives, Core.Model.Archive archive, IReadOnlyList set, Func applied,
- Action close)
+ Action close)
: base(close)
{
Mode = mode;
@@ -159,9 +169,19 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
_delay.Stop();
_ = PlanAsync();
};
- ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => !IsBusy && _plan is { Steps.Count: > 0 } && !Template.HasErrors);
+ ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
+ /// Why Apply is disabled; null when it can run.
+ private string? ApplyBlocker =>
+ IsBusy ? Loc.L("Archive.Blocked.Applying")
+ : Template.Error is { } error ? error
+ : _plan is null ? 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);
@@ -188,6 +208,7 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
_plan = null;
Rows = [];
OnPropertyChanged(nameof(SummaryText));
+ OnPropertyChanged(nameof(ApplyToolTip));
if (Template.HasErrors) return;
var cts = _planning = new CancellationTokenSource();
var template = Template.Text;
@@ -200,6 +221,7 @@ public sealed class RenameDialogViewModel : ArchiveDialogViewModel
_plan = plan;
Rows = MassRename.Rows(plan, Mode);
OnPropertyChanged(nameof(SummaryText));
+ OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
@@ -242,7 +264,7 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
private readonly IReadOnlyList _set;
private readonly Func _applied;
- public RetagDialogViewModel(ArchiveService archives, IReadOnlyList set, Func applied, Action close)
+ public RetagDialogViewModel(ArchiveService archives, IReadOnlyList set, Func applied, Action close)
: base(close)
{
_archives = archives;
@@ -250,11 +272,19 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
_applied = applied;
Add = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsAdd"));
Remove = new EditableField(string.Empty, Retag.Validate, _ => OnPropertyChanged(nameof(SummaryText)), () => Loc.L("Tooltips.Archive.TagsRemove"));
- Add.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SummaryText));
- Remove.PropertyChanged += (_, _) => OnPropertyChanged(nameof(SummaryText));
- ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => !IsBusy && Changes().Count > 0);
+ Add.PropertyChanged += (_, _) => OnTagsTyped();
+ Remove.PropertyChanged += (_, _) => OnTagsTyped();
+ ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
+ /// Why Apply is disabled; null when it can run.
+ private string? ApplyBlocker =>
+ IsBusy ? Loc.L("Archive.Blocked.Applying")
+ : Add.Error ?? Remove.Error
+ ?? (Changes().Count == 0 ? Loc.L("Archive.Blocked.NoChanges") : null);
+
+ public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RetagApply");
+
public string Heading => Loc.Plural("Archive.Retag.Heading", _set.Count);
public EditableField Add { get; }
@@ -265,6 +295,14 @@ public sealed class RetagDialogViewModel : ArchiveDialogViewModel
public ICommand ApplyCommand { get; }
+ /// Typing changes the dry run, and with it whether Apply can run.
+ private void OnTagsTyped()
+ {
+ OnPropertyChanged(nameof(SummaryText));
+ OnPropertyChanged(nameof(ApplyToolTip));
+ CommandManager.InvalidateRequerySuggested();
+ }
+
private IReadOnlyList<(Sequence Sequence, IReadOnlyList Tags)> Changes() =>
Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
diff --git a/src/Titano.App/Archive/ArchiveRowViewModels.cs b/src/Titano.App/Archive/ArchiveRowViewModels.cs
index b386232e..08b9b5cb 100644
--- a/src/Titano.App/Archive/ArchiveRowViewModels.cs
+++ b/src/Titano.App/Archive/ArchiveRowViewModels.cs
@@ -24,6 +24,9 @@ public sealed class ArchiveTreeRowViewModel(ArchiveTreeNode node, ArchiveAvailab
public string ToggleToolTip => Loc.L(Node.IsExpanded ? "Tooltips.Archive.Collapse" : "Tooltips.Archive.Expand");
+ /// The row's figures; a year also says how the keyboard opens and closes it.
+ public string RowToolTip => IsYear ? Loc.L("Tooltips.Archive.YearRow", Detail) : Detail;
+
public ICommand ToggleCommand { get; } = new RelayCommand(() => toggle(node));
/// The archive's availability (BRIEF §7: online, read-only, offline) on the archive row.
@@ -71,3 +74,6 @@ public sealed class OrphanRowViewModel(OrphanRow row, ICommand fix) : Observable
public string FixText => Loc.L("Archive.Orphans.Fix." + Row.Kind);
public string FixToolTip => Loc.L("Tooltips.Archive.Orphans." + Row.Kind);
}
+
+/// A value of a set filter menu (camera, status, tag): checked while chosen; choosing it again clears it.
+public sealed record FilterChoice(string Label, bool IsChecked, ICommand Command);
diff --git a/src/Titano.App/Archive/ArchiveScenes.cs b/src/Titano.App/Archive/ArchiveScenes.cs
index f9572fc8..c6fa089d 100644
--- a/src/Titano.App/Archive/ArchiveScenes.cs
+++ b/src/Titano.App/Archive/ArchiveScenes.cs
@@ -4,12 +4,12 @@ namespace Titano.App.Archiving;
///
/// The Archive views that --capture renders (archive-<view>-<theme>.png) and the screen smoke
-/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, and
-/// the rebuild dialog.
+/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, the
+/// rebuild dialog, and the Move dialog with its dry run.
///
public static class ArchiveScenes
{
- public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild"];
+ public static readonly IReadOnlyList Views = ["overview", "maintenance", "rebuild", "move"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
@@ -32,6 +32,15 @@ public static class ArchiveScenes
archive.ViewIndex = 0;
(await archive.OpenRebuildDialogAsync())?.ShowFolders(SampleReports.Folders(locations));
break;
+ case "move":
+ archive.ViewIndex = 0;
+ await archive.OpenRenameDialogAsync(RenameMode.Folders);
+ if (archive.Dialog is RenameDialogViewModel move)
+ {
+ move.Template.Text = "{year}/{date} {title}";
+ await move.PlanAsync();
+ }
+ break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
diff --git a/src/Titano.App/Archive/MassOperations.cs b/src/Titano.App/Archive/MassOperations.cs
index 9f953f39..6a6564af 100644
--- a/src/Titano.App/Archive/MassOperations.cs
+++ b/src/Titano.App/Archive/MassOperations.cs
@@ -1,3 +1,4 @@
+using Titano.App.Library;
using Titano.App.Settings;
using Titano.Core.Archiving;
using Titano.Core.Localization;
@@ -80,3 +81,34 @@ public static class Retag
.Where(c => !c.Tags.SequenceEqual(c.Sequence.Tags, StringComparer.Ordinal)),
];
}
+
+///
+/// Narrows the mass-operation set on top of the tree selection (Archive.html "Filtered set ▾"): camera, status and tag;
+/// years and single sequences are chosen in the tree.
+///
+public sealed record ArchiveSetFilter(string? Camera = null, StatusFilter Status = StatusFilter.Any, string? Tag = null)
+{
+ public bool IsEmpty => Camera is null && Status == StatusFilter.Any && Tag is null;
+
+ public bool Matches(Sequence sequence)
+ {
+ if (Camera is not null && CameraOf(sequence) != Camera) return false;
+ if (Tag is not null && !sequence.Tags.Contains(Tag, StringComparer.OrdinalIgnoreCase)) return false;
+ var (with, without) = LibraryFilter.Flags(Status);
+ return (sequence.Status & with) == with && (sequence.Status & without) == 0;
+ }
+
+ /// "Canon EOS R5 · Not analysed · sunset"; empty without a filter.
+ public string Describe() => string.Join(" · ", new[]
+ {
+ Camera ?? string.Empty,
+ Status == StatusFilter.Any ? string.Empty : StatusLabel(Status),
+ Tag ?? string.Empty,
+ }.Where(t => t.Length > 0));
+
+ /// The camera a sequence is filed under, as the camera chart names it.
+ public static string CameraOf(Sequence sequence) =>
+ PathTemplate.CameraName(sequence.CameraMake, sequence.CameraModel) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera");
+
+ public static string StatusLabel(StatusFilter status) => Loc.L(status == StatusFilter.Any ? "Library.Filter.AnyStatus" : "Library.Filter.Status." + status);
+}
diff --git a/src/Titano.App/Sections/ArchiveView.xaml b/src/Titano.App/Sections/ArchiveView.xaml
index ddf723ce..42a18f7b 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml
+++ b/src/Titano.App/Sections/ArchiveView.xaml
@@ -18,6 +18,25 @@
+
+
+
+
+
+
+
@@ -214,7 +252,8 @@
+ Command="{Binding ToggleCommand}" ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleToolTip}" Visibility="Hidden"
+ Focusable="False" />
@@ -250,7 +289,7 @@
-
+
@@ -260,8 +299,11 @@
-
-
+
+
+
+
+
@@ -315,7 +357,7 @@
-
+
@@ -349,6 +391,8 @@
ToolTip="{l:Loc Tooltips.Archive.History}" />
+
@@ -378,13 +422,16 @@
+ Command="{Binding MarkDuplicatesCommand}" ToolTip="{Binding MarkDuplicatesToolTip}" />
+ ToolTip="{Binding DuplicatesToolTip}" Visibility="{Binding IsSearching, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
+
-
+
@@ -409,11 +456,14 @@
+ ToolTip="{Binding OrphansToolTip}" Visibility="{Binding IsSearching, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
+
-
+
@@ -431,37 +481,53 @@
-
-
+
-
-
-
+
-
-
+
+
-
+ ToolTip="{Binding ThumbnailsSetToolTip}" />
+
-
+
-
+
-
-
+
+
-
+
diff --git a/src/Titano.App/Sections/ArchiveView.xaml.cs b/src/Titano.App/Sections/ArchiveView.xaml.cs
index c835b08c..cbbce484 100644
--- a/src/Titano.App/Sections/ArchiveView.xaml.cs
+++ b/src/Titano.App/Sections/ArchiveView.xaml.cs
@@ -1,15 +1,31 @@
+using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
+using System.Windows.Input;
+using System.Windows.Threading;
using Titano.App.Archiving;
namespace Titano.App.Sections;
public partial class ArchiveView : UserControl
{
- public ArchiveView() => InitializeComponent();
+ private bool _restoring;
+ private string? _focusKey;
- /// "Maintenance ▾" opens its menu under itself.
+ public ArchiveView()
+ {
+ InitializeComponent();
+ DataContextChanged += OnDataContextChanged;
+ Tree.GotKeyboardFocus += (_, e) =>
+ {
+ if (e.NewFocus is ListBoxItem { DataContext: ArchiveTreeRowViewModel row }) _focusKey = row.Node.Key;
+ };
+ }
+
+ private ArchiveViewModel? Model => DataContext as ArchiveViewModel;
+
+ /// "Adopt folder ▾", "Maintenance ▾" and the set filter open their menu under themselves.
private void OnOpenMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
@@ -19,9 +35,70 @@ public partial class ArchiveView : UserControl
menu.IsOpen = true;
}
+ private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
+ {
+ if (e.OldValue is ArchiveViewModel old)
+ {
+ old.RowsRebuilt -= RestoreSelection;
+ old.PropertyChanged -= OnModelChanged;
+ }
+ if (e.NewValue is ArchiveViewModel model)
+ {
+ model.RowsRebuilt += RestoreSelection;
+ model.PropertyChanged += OnModelChanged;
+ }
+ }
+
/// The selected tree rows are the set the mass operations act on.
private void OnTreeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
- if (DataContext is ArchiveViewModel model) model.SetSelection(Tree.SelectedItems.OfType());
+ if (!_restoring) Model?.SetSelection(Tree.SelectedItems.OfType());
+ }
+
+ /// The rows were rebuilt (a reload, a year opened or closed): the list shows the same selection and keeps the keyboard where it was.
+ private void RestoreSelection()
+ {
+ if (Model is not { } model) return;
+ // The rebuild removed the focused row's container; the keyboard goes back to the row with the same key.
+ var refocus = Tree.IsKeyboardFocusWithin || Keyboard.FocusedElement is null ? _focusKey : null;
+ _restoring = true;
+ try
+ {
+ Tree.SelectedItems.Clear();
+ foreach (var row in model.TreeRows.Where(model.IsSelectedRow)) Tree.SelectedItems.Add(row);
+ }
+ finally
+ {
+ _restoring = false;
+ }
+ if (refocus is null || model.TreeRows.FirstOrDefault(r => r.Node.Key == refocus) is not { } again) return;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
+ {
+ Tree.ScrollIntoView(again);
+ (Tree.ItemContainerGenerator.ContainerFromItem(again) as ListBoxItem)?.Focus();
+ });
+ }
+
+ /// On a year: Right opens it, Left closes it, Enter toggles it.
+ private void OnTreeKeyDown(object sender, KeyEventArgs e)
+ {
+ if (Model is not { } model || Keyboard.FocusedElement is not ListBoxItem { DataContext: ArchiveTreeRowViewModel row } || !row.HasChildren || row.IsArchive) return;
+ var toggle = e.Key switch
+ {
+ Key.Right => !row.IsExpanded,
+ Key.Left => row.IsExpanded,
+ Key.Enter => true,
+ _ => false,
+ };
+ if (!toggle) return;
+ model.Toggle(row);
+ e.Handled = true;
+ }
+
+ /// A dialog that opens takes the keyboard: its first field or button.
+ private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (e.PropertyName != nameof(ArchiveViewModel.Dialog) || Model?.Dialog is null || !IsVisible) return;
+ Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
}
}
diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs
index 06be5ace..75884631 100644
--- a/src/Titano.App/Sections/ArchiveViewModel.cs
+++ b/src/Titano.App/Sections/ArchiveViewModel.cs
@@ -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;
///
/// 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.
///
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 _selection = [];
+ /// Keys of the selected tree nodes (stable across reloads).
+ private readonly HashSet _selection = new(StringComparer.Ordinal);
+ private readonly DispatcherTimer _reloadDelay;
+ private HashSet _sequenceIds = [];
+ private ArchiveSetFilter _filter = new();
+ private bool _rebuildingRows;
+ private CancellationTokenSource? _search;
private IReadOnlyList _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; }
+
+ /// "Adopt folder ▾ › Copy into the layout": the Import screen copies the folder into the archive with its templates.
+ 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
/// Photos per month in the culture's digits.
public Func CountFormatter { get; } = v => Formatting.Count((long)v);
- /// "412 sequences · all", "36 sequences · 2025", "Harbour sunset".
+ /// "412 sequences · all", "36 sequences", "Harbour sunset", each followed by the filter ("· Canon EOS R5").
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();
}
}
+ /// Camera, status and tag on top of the tree selection.
+ public ArchiveSetFilter Filter
+ {
+ get => _filter;
+ private set
+ {
+ if (!Set(ref _filter, value)) return;
+ OnSetChanged();
+ }
+ }
+
+ public IReadOnlyList 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 StatusChoices => Choices(
+ Enum.GetValues().Where(f => f != StatusFilter.Any), ArchiveSetFilter.StatusLabel, f => _filter.Status == f,
+ f => _filter with { Status = f });
+
+ public IReadOnlyList 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; }
- /// The view reports the selected tree rows.
+ /// The view reports the rows the user selected; the list's own clearing while rows are rebuilt is not a choice.
public void SetSelection(IEnumerable 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();
}
+ /// Whether a visible row is part of the selection (the view restores the list's selection after a rebuild).
+ public bool IsSelectedRow(ArchiveTreeRowViewModel row) => _selection.Contains(row.Node.Key);
+
+ /// Raised after the rows were rebuilt; the view selects the rows of again.
+ public event Action? RowsRebuilt;
+
+ /// Expands or collapses a year (Right/Left/Enter on its row, or its arrow).
+ public void Toggle(ArchiveTreeRowViewModel row) => Toggle(row.Node);
+
// ---------------- Maintenance view ----------------
public IReadOnlyList Health { get => _health; private set => Set(ref _health, value); }
- public IReadOnlyList Recent { get => _recent; private set => Set(ref _recent, value); }
+ public IReadOnlyList Recent
+ {
+ get => _recent;
+ private set
+ {
+ if (Set(ref _recent, value)) OnPropertyChanged(nameof(HasRecent));
+ }
+ }
+
+ public bool HasRecent => _recent.Count > 0;
public IReadOnlyList? Duplicates
{
@@ -209,6 +289,9 @@ public sealed class ArchiveViewModel : SectionViewModel
}
}
+ /// A duplicates or orphans search runs; it can be cancelled.
+ public bool IsSearching => _search is not null;
+
/// "3 groups", "None found", or empty before the first search.
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;
+ /// The screen behind an open dialog takes neither clicks nor keyboard focus.
+ 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 Bars(IReadOnlyList values) =>
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
+ /// A reloaded tree keeps the open years and the selection (nodes that still exist).
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();
}
+ ///
+ /// 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.
+ ///
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();
}
+ /// The set changed (selection, filter or tree): its text, the filter menus and the mass commands follow.
+ 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 SelectedNodes() => TreeRows.Where(r => _selection.Contains(r.Node.Key)).Select(r => r.Node);
+
+ /// One filter menu: each value checked when chosen; choosing it again clears it.
+ private IReadOnlyList Choices(IEnumerable values, Func label, Func isChosen, Func 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();
@@ -394,16 +534,25 @@ public sealed class ArchiveViewModel : SectionViewModel
_jobEvents = true;
}
- /// A finished archive job changes the figures: read them again.
+ ///
+ /// 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.
+ ///
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 Set() => _tree is null ? [] : ArchiveTree.SetOf(_tree, _selection);
+ /// A mass command's tooltip, or why it is disabled (an empty set; for writes, an archive that is not online).
+ private string WhenSet(string key, bool needsOnline = false) =>
+ _tree is not null && !HasSet() ? Loc.L("Archive.Blocked.EmptySet")
+ : needsOnline ? WhenOnline(key)
+ : Loc.L(key);
+
+ /// The set the mass operations act on: the selected rows' sequences (all when nothing is selected), filtered.
+ private IReadOnlyList Set() => _tree is null ? [] : [.. ArchiveTree.SetOf(_tree, SelectedNodes()).Where(_filter.Matches)];
private IReadOnlyList All() => _tree is null ? [] : ArchiveTree.SetOf(_tree, []);
@@ -438,12 +594,20 @@ public sealed class ArchiveViewModel : SectionViewModel
Queued(request.Kind, request.Label ?? SetLabel());
}
- /// Health fixes act on the sequences that miss a status (never verified, no proxies).
+ /// Health fixes act on every sequence that misses a status (never verified, no proxies), page by page.
private async Task QueueStatusAsync(SequenceStatus missing, Func, 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();
+ 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 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)
+ /// Opens Rename or Move on the set and waits for its dry run.
+ 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()
+ /// Closes if it is still the open one (an apply that finishes late closes nothing else).
+ 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
}
}
+ /// Copies a folder tree into the archive's layout: the Import screen plans it with the archive's templates.
+ 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);
+ }
+
+ /// A consistent copy of the index next to the data folder (the same backup as Settings › Advanced).
+ 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);
+ }
+ }
+
/// A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).
private async Task RelinkAsync()
{
@@ -525,16 +724,21 @@ public sealed class ArchiveViewModel : SectionViewModel
() => ShellActions.Reveal(path));
}
+ /// Duplicates by hash across the archive (a read of the index); cancellable.
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);
}
}
+ /// Orphans: every sequence folder against its sidecar and the index (a walk of the archive); cancellable.
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 DuplicateRows(IReadOnlyList groups, IReadOnlyList locations) =>
[
.. MaintenanceReports.Duplicates(groups, locations).Select(row => new DuplicateRowViewModel(row,