Files
Chronos/src/Titano.App/Sections/ArchiveViewModel.cs
T
Claude 78a6f59c42 fix(archive): an archive picked again is not read until its read ends
Picking archive A, then B, then A again before B's read ended left A's read
marker set while its tree and figures were already cleared: Rebuild, Scan,
Verify and Maintenance were enabled and the rebuild dialog counted 0
sequences. ForgetRead now clears the marker too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 16:21:19 +00:00

1042 lines
47 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Processing;
using Titano.Data.Repositories;
using Titano.Ui.Mvvm;
using Titano.Ui.Visuals;
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 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
/// 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.
/// </summary>
public sealed class ArchiveViewModel : SectionViewModel
{
private const int RecentCount = 6;
private const int PageSize = 1000;
private static readonly TimeSpan ReloadDelay = TimeSpan.FromSeconds(2);
/// <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;
/// <summary>The archive whose availability, figures and tree were read last: until it is the picked one, nothing acts on them.</summary>
private Guid? _readId;
private ArchiveStats? _stats;
private int _withoutProxies;
private ArchiveTree? _tree;
private int _viewIndex;
private bool _loaded;
private Task _load = Task.CompletedTask;
private bool _reloadPending;
private bool _jobEvents;
private string _lastScanText = string.Empty;
private ArchiveDialogViewModel? _dialog;
private IReadOnlyList<ArchiveTile> _tiles = [];
private IReadOnlyList<ChartRow> _months = [];
private IReadOnlyList<ChartItem> _storage = [];
private IReadOnlyList<ChartItem> _cameras = [];
private IReadOnlyList<ChartItem> _formats = [];
private IReadOnlyList<HealthLineViewModel> _health = [];
private IReadOnlyList<MaintenanceRow> _recent = [];
private IReadOnlyList<DuplicateRowViewModel>? _duplicates;
private IReadOnlyList<OrphanRowViewModel>? _orphans;
private bool _findingDuplicates;
private bool _findingOrphans;
public ArchiveViewModel(ShellViewModel shell)
: 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, deepAnalysis: Services.Settings.DeepAnalysisAfterScan)), IsOnline);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), IsRead);
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);
RestoreCommand = new RelayCommand(() =>
{
Shell.Settings.Page = Titano.App.Settings.SettingsPage.Advanced;
Shell.Navigate(SectionKey.Settings);
});
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));
AnalyseSetCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ProcessingJobs.DeepAnalysis(ids, SetLabel()), Set()), HasSet);
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());
RetagSetCommand = new RelayCommand(OpenRetag, () => HasSet() && IsOnline());
ExportSetCommand = new AsyncRelayCommand(ExportAsync, HasSet);
DeleteSetCommand = new AsyncRelayCommand(DeleteSetAsync, () => HasSet() && IsOnline());
TrashCommand = new AsyncRelayCommand(OpenTrashAsync, () => _archive is not null);
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);
}
public ShellViewModel Shell { get; }
private AppServices Services => Shell.Services;
// ---------------- Toolbar ----------------
public IReadOnlyList<Core.Model.Archive> Archives { get => _archives; private set => Set(ref _archives, value); }
public Core.Model.Archive? SelectedArchive
{
get => _archive;
set
{
if (value is null || value == _archive) return;
var other = value.Id != _archive?.Id;
_archive = value;
_duplicates = null;
_orphans = null;
if (other) ForgetRead();
_ = LoadAsync();
}
}
public bool HasArchive => _archive is not null;
public string ArchiveToolTip => _archive is null ? Loc.L("Tooltips.Archive.Pick") : Loc.L("Tooltips.Archive.PickRoot", Formatting.LeftToRight(_archive.RootPath));
/// <summary>0 = overview (tree and figures), 1 = maintenance.</summary>
public int ViewIndex
{
get => _viewIndex;
set
{
if (!Set(ref _viewIndex, value)) return;
OnPropertyChanged(nameof(IsOverview));
OnPropertyChanged(nameof(IsMaintenance));
}
}
public bool IsOverview => HasArchive && _viewIndex == 0;
public bool IsMaintenance => HasArchive && _viewIndex == 1;
/// <summary>"Last scan 29/09/2026 07:12 · 14 min".</summary>
public string LastScanText { get => _lastScanText; private set => Set(ref _lastScanText, value); }
public string ScanToolTip => WhenOnline("Tooltips.Archive.Scan");
public string VerifyToolTip => WhenOnline("Tooltips.Archive.Verify");
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 string DeleteSetToolTip => WhenSet("Tooltips.Archive.SetDelete", needsOnline: true);
public ICommand ScanCommand { get; }
public ICommand RebuildCommand { get; }
public ICommand VerifyCommand { get; }
public ICommand AdoptCommand { get; }
/// <summary>"Adopt folder ▾ › Copy into archive": the Import screen copies the folder into the archive with its templates.</summary>
public ICommand CopyFolderCommand { get; }
public ICommand BackupCommand { get; }
/// <summary>"Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a daily copy is compared and restored (§6.2).</summary>
public ICommand RestoreCommand { get; }
public ICommand MaintenanceCommand { get; }
public ICommand MaintenanceDryRunCommand { get; }
public ICommand RebuildProxiesCommand { get; }
public ICommand RelinkCommand { get; }
public ICommand HistoryCommand { get; }
/// <summary>"Maintenance ▾ › Trash…": the sequences deleted from this archive, each restorable.</summary>
public ICommand TrashCommand { get; }
// ---------------- Overview ----------------
public ObservableCollection<ArchiveTreeRowViewModel> TreeRows { get; } = [];
public IReadOnlyList<ArchiveTile> Tiles { get => _tiles; private set => Set(ref _tiles, value); }
public IReadOnlyList<ChartRow> MonthRows { get => _months; private set => Set(ref _months, value); }
public IReadOnlyList<string> MonthLabels => ArchiveFigures.MonthLabels();
public IReadOnlyList<ChartItem> StorageBars { get => _storage; private set => Set(ref _storage, value); }
public IReadOnlyList<ChartItem> CameraBars { get => _cameras; private set => Set(ref _cameras, value); }
public IReadOnlyList<ChartItem> FormatBars { get => _formats; private set => Set(ref _formats, value); }
/// <summary>The heatmap's scale in the card header (Archive.html: "0 ▭ 21,000"); hidden without photos.</summary>
public bool HasMonthScale => MonthScaleMax > 0;
public string MonthScaleLow => Formatting.Count(0);
public string MonthScaleHigh => Formatting.Count((long)MonthScaleMax);
private double MonthScaleMax => _months.SelectMany(r => r.Values).Where(double.IsFinite).DefaultIfEmpty(0).Max();
/// <summary>What each chart shows, value by value, for screen readers (the charts themselves are images).</summary>
public string MonthsDescription => Describe(_months.SelectMany(r => r.Values.Select((photos, month) => photos > 0 ? r.ToolTips?[month] : null)));
public string StorageDescription => Describe(_storage.Select(b => b.ToolTip));
public string CamerasDescription => Describe(_cameras.Select(b => b.ToolTip));
public string FormatsDescription => Describe(_formats.Select(b => b.ToolTip));
/// <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", "Harbour sunset", each followed by the filter ("· Canon EOS R5").</summary>
public string SetText
{
get
{
var set = Set();
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 + Loc.Separator + _filter.Describe();
}
}
/// <summary>The set button's accessible name: what it is and the set it shows.</summary>
public string SetFilterName => Loc.L("Archive.Set.Filter") + Loc.Separator + SetText;
/// <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; }
public ICommand VerifySetCommand { get; }
public ICommand RenameSetCommand { get; }
public ICommand MoveSetCommand { get; }
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
/// <summary>Moves the set to the archive's trash after its dry run and a typed confirmation.</summary>
public ICommand DeleteSetCommand { get; }
/// <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.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
{
if (Set(ref _recent, value)) OnPropertyChanged(nameof(HasRecent));
}
}
public bool HasRecent => _recent.Count > 0;
public IReadOnlyList<DuplicateRowViewModel>? Duplicates
{
get => _duplicates;
private set
{
if (!Set(ref _duplicates, value)) return;
OnPropertyChanged(nameof(DuplicatesText));
ShowHealth();
}
}
public IReadOnlyList<OrphanRowViewModel>? Orphans
{
get => _orphans;
private set
{
if (Set(ref _orphans, value)) OnPropertyChanged(nameof(OrphansText));
}
}
/// <summary>The duplicates search runs: its card offers Cancel; the other card's Find waits for it.</summary>
public bool IsFindingDuplicates => _findingDuplicates;
/// <summary>The orphans search runs: its card offers Cancel; the other card's Find waits for it.</summary>
public bool IsFindingOrphans => _findingOrphans;
/// <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
: _duplicates.Count == 0 ? Loc.L("Archive.Find.None")
: Loc.Plural("Archive.Duplicates.Groups", _duplicates.Count);
public string OrphansText => _findingOrphans ? Loc.L("Archive.Find.Searching")
: _orphans is null ? string.Empty
: _orphans.Count == 0 ? Loc.L("Archive.Find.None")
: Loc.Plural("Archive.Orphans.Count", _orphans.Count);
public ICommand FindDuplicatesCommand { get; }
public ICommand FindOrphansCommand { get; }
public ICommand CancelSearchCommand { get; }
public ICommand MarkDuplicatesCommand { get; }
// ---------------- Dialogs ----------------
/// <summary>The open in-window dialog (rebuild, rename, retag, trash); null when none.</summary>
public ArchiveDialogViewModel? Dialog
{
get => _dialog;
private set
{
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 ----------------
protected override void OnActivated()
{
if (_loaded) return;
_ = LoadAsync();
}
/// <summary>
/// Reads archives, figures, tree, health and recent maintenance of the selected archive. A call during a read joins
/// it and reads once more when it ends, so a newly picked archive, a language switch or a finished job is never lost
/// behind the read in progress.
/// </summary>
public Task LoadAsync()
{
if (!_load.IsCompleted)
{
_reloadPending = true;
return _load;
}
return _load = ReadUntilCurrentAsync();
}
private async Task ReadUntilCurrentAsync()
{
do
{
_reloadPending = false;
await ReadAsync();
}
while (_reloadPending);
}
private async Task ReadAsync()
{
if (Services.Database is not { } db) return;
try
{
AttachJobEvents();
Archives = await db.Archives.ListAsync();
var shown = _archive;
_archive = shown is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null;
_archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath);
// The archive shown is gone from the index: another one (or none) takes its place, without its figures.
if (shown is not null && _archive?.Id != shown.Id) ForgetRead();
if (_archive is not { } archive) return;
var root = archive.RootPath;
var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
var stats = await db.Sequences.GetStatsAsync(archive.Id);
var sequences = await ListSequencesAsync(db, archive.Id);
var withoutProxies = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt });
// Another archive was picked meanwhile: the read its pick queued shows it, never this one's tree.
if (!IsShowing(archive)) return;
_availability = availability;
_stats = stats;
_readId = archive.Id;
ShowFigures(stats, withoutProxies);
ShowTree(ArchiveTree.Build(archive, availability, sequences));
await LoadRecentAsync(db, archive);
}
catch (DatabaseException ex)
{
Log.Warning("archive", "Archive figures unavailable", ex);
}
finally
{
_loaded = true;
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>
/// Another archive is shown: until it is read (IsRead), nothing of the previous one stays actionable or on screen. No
/// tree to take a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes,
/// no search results, and none of its tiles, charts, last scan, recent runs or rail badge under the new archive's
/// name, which a slow or failed read would leave there. The tooltips say the archive is being read.
/// </summary>
private void ForgetRead()
{
// Picking A, then B, then A again before B's read ends must not find A "read" with none of its figures.
_readId = null;
_search?.Cancel();
_duplicates = null;
_orphans = null;
_tree = null;
_sequenceIds = [];
_stats = null;
_withoutProxies = 0;
_health = [];
_tiles = [];
_months = [];
_storage = [];
_cameras = [];
_formats = [];
_recent = [];
_lastScanText = string.Empty;
Badge = 0;
RebuildRows();
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
/// <summary>Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.</summary>
public async Task<RebuildDialogViewModel?> OpenRebuildDialogAsync()
{
if (_archive is not { } archive || !IsRead() || Services.Engine is not { } engine) return null;
var dialog = new RebuildDialogViewModel(archive, _availability, _stats?.Sequences ?? 0, async () =>
{
var request = ArchiveJobs.Rebuild(archive);
await engine.EnqueueAsync(request);
Queued(request.Kind, archive.Name);
}, CloseDialog);
OpenDialog(dialog);
await dialog.CountAsync();
return dialog;
}
/// <summary>Shows reports computed elsewhere (capture).</summary>
public void ShowReports(IReadOnlyList<DuplicateGroup> duplicates, OrphanReport orphans, IReadOnlyList<SequenceLocation> locations)
{
Duplicates = DuplicateRows(duplicates, locations);
Orphans = OrphanRows(orphans, locations);
}
/// <summary>The UI language changed: the figures, tree and health rows are read again in the new language.</summary>
protected override void OnLanguageChanged()
{
if (_loaded) _ = LoadAsync();
base.OnLanguageChanged();
}
public override void Dispose()
{
_reloadDelay.Stop();
_search?.Cancel();
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
_dialog?.Dispose();
base.Dispose();
}
private static async Task<List<Sequence>> ListSequencesAsync(TitanoDatabase db, Guid archiveId)
{
var all = new List<Sequence>();
string? cursor = null;
do
{
var page = await db.Sequences.ListAsync(new SequenceQuery { ArchiveId = archiveId, Sort = SequenceSort.Newest, Limit = PageSize, Cursor = cursor });
all.AddRange(page.Items);
cursor = page.NextCursor;
}
while (cursor is not null);
return all;
}
private void ShowFigures(ArchiveStats stats, int withoutProxies)
{
_withoutProxies = withoutProxies;
Tiles = ArchiveFigures.Tiles(stats);
MonthRows = [.. ArchiveFigures.PhotosPerMonth(stats, AppClock.Today).Select(r => new ChartRow(r.Label, r.Values, r.ToolTips))];
StorageBars = Bars(ArchiveFigures.StorageByYear(stats));
CameraBars = Bars(ArchiveFigures.ByCamera(stats));
FormatBars = Bars(ArchiveFigures.ByFormat(stats));
ShowHealth();
}
/// <summary>The health lines of the last figures; the duplicates line follows the last duplicates search.</summary>
private void ShowHealth()
{
if (_stats is not { } stats) return;
Health =
[
.. ArchiveFigures.Health(stats, _withoutProxies, _duplicates?.Count).Select(line => new HealthLineViewModel(line, line.Action switch
{
HealthAction.Verify => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.Verified, ids => ArchiveJobs.Verify(_archive!, ids))),
HealthAction.Proxies => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.ProxiesBuilt, ids => ArchiveJobs.Proxies(ids, CountLabel(ids)))),
HealthAction.Analyse => new AsyncRelayCommand(() => QueueStatusAsync(SequenceStatus.AnalyzedLight, ids => ProcessingJobs.LightAnalysis(ids, CountLabel(ids)))),
HealthAction.Duplicates => FindDuplicatesCommand,
HealthAction.MarkDuplicates => MarkDuplicatesCommand,
HealthAction.Orphans => FindOrphansCommand,
_ => null,
})),
];
// The rail badge counts the health lines that need attention (BRIEF §12.1 "badge counts (warnings, …)").
Badge = Health.Count(h => !h.IsOk);
}
private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) =>
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
private static string Describe(IEnumerable<string?> values) => string.Join(Environment.NewLine, values.Where(v => !string.IsNullOrEmpty(v)));
/// <summary>A reloaded tree keeps the open years and the selection (nodes that still exist).</summary>
private void ShowTree(ArchiveTree tree)
{
var expanded = _tree?.Root.Key == tree.Root.Key ? _tree.ExpandedKeys() : null;
if (expanded is not null) tree.Expand(expanded);
else
{
_selection.Clear();
if (tree.Root.Children.Count > 0) tree.Root.Children[0].IsExpanded = true;
}
_tree = tree;
_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()
{
_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)
{
if (node.Kind == TreeNodeKind.Archive) return;
node.IsExpanded = !node.IsExpanded;
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(SetFilterName));
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));
OnPropertyChanged(nameof(DeleteSetToolTip));
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>();
foreach (var kind in MaintenanceReports.MaintenanceKinds)
jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id)));
if (!IsShowing(archive)) return;
Recent = MaintenanceReports.Recent(jobs, RecentCount);
var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null })
.MaxBy(j => j.Finished);
LastScanText = scan is { Started: { } started, Finished: { } finished }
? Loc.L("Archive.LastScan", Formatting.Date(finished) + " " + Formatting.TimeOfDay(finished), Formatting.Duration(finished - started))
: string.Empty;
}
private void AttachJobEvents()
{
if (_jobEvents || Services.Jobs is not { } jobs) return;
jobs.JobChanged += OnJobChanged;
_jobEvents = true;
}
/// <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)) 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 (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return;
if (!IsSelected)
{
_loaded = false;
return;
}
_reloadDelay.Stop();
_reloadDelay.Start();
});
}
// ---------------- Actions ----------------
private bool IsOnline() => IsRead() && _availability == ArchiveAvailability.Online;
/// <summary>The picked archive's availability and figures are known (a slow volume is probed for seconds).</summary>
private bool IsRead() => _archive is { } archive && _readId == archive.Id;
/// <summary>The archive a read started with is still the one picked.</summary>
private bool IsShowing(Core.Model.Archive archive) => _archive?.Id == archive.Id;
/// <summary>A command's tooltip, or why it is disabled: these commands write to the archive or read all of it.</summary>
private string WhenOnline(string key) =>
_archive is null || IsOnline() ? Loc.L(key)
: !IsRead() ? Loc.L("Archive.Blocked.Reading")
: Loc.L("Archive.Blocked.NotOnline");
private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0;
/// <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, []);
private string SetLabel() => SetText;
private async Task QueueAsync(Func<Core.Model.Archive, ArchiveJobRequest> build)
{
if (Services.Engine is not { } engine || _archive is not { } archive) return;
var request = build(archive);
await engine.EnqueueAsync(request);
Queued(request.Kind, request.Label ?? archive.Name);
}
private async Task QueueSetAsync(Func<IReadOnlyList<Guid>, ArchiveJobRequest> build, IReadOnlyList<Sequence> set)
{
if (Services.Engine is not { } engine || set.Count == 0) return;
var request = build([.. set.Select(s => s.Id)]);
await engine.EnqueueAsync(request);
Queued(request.Kind, request.Label ?? SetLabel());
}
/// <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 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);
private void Queued(JobKind kind, string label) =>
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)
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
var dialog = new RenameDialogViewModel(mode, archives, archive, Set(), Applied, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
/// <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.
/// </summary>
public async Task<bool> DeleteSetAsync()
{
var dialog = new DeleteDialogViewModel(Shell, [.. Set().Select(s => s.Id)], CloseDialog);
OpenDialog(dialog);
return await dialog.RunAsync();
}
/// <summary>Opens the trash of the archive and reads it.</summary>
public async Task OpenTrashAsync()
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
var dialog = new TrashDialogViewModel(archives, archive, async () =>
{
await LoadAsync();
await Shell.Library.RefreshAsync();
}, CloseDialog);
OpenDialog(dialog);
await dialog.LoadAsync();
}
private void OpenRetag()
{
if (Services.Archives is not { } archives) return;
OpenDialog(new RetagDialogViewModel(archives, Set(), Applied, CloseDialog));
}
private void OpenDialog(ArchiveDialogViewModel dialog)
{
_dialog?.Dispose();
Dialog = dialog;
}
private async Task Applied(int changed)
{
Shell.Notify(Loc.Plural("Archive.Applied", changed));
await LoadAsync();
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>
private void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
}
private async Task AdoptAsync()
{
var folder = Services.Dialogs.PickFolder(Loc.L("Library.Adopt.Title"));
if (folder is null) return;
if (await ArchiveActions.TryAsync(Shell, s => s.AdoptAsync(folder)))
{
_archive = null;
await LoadAsync();
}
}
/// <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"), Formatting.LeftToRight(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);
NotifyFailure("Archive.Backup.Failed", ex, BackupCommand);
}
}
/// <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()
{
if (Services.Archives is not { } archives) return;
var folder = Services.Dialogs.PickFolder(Loc.L("Archive.Relink.Title"));
if (folder is null) return;
try
{
var archive = await Task.Run(() => archives.OpenAsync(folder));
Services.Settings.LastArchivePath = archive.RootPath;
Services.SaveSettings();
_archive = archive;
await Services.QueueScanAsync(archive, full: false);
Shell.Notify(Loc.L("Archive.Relink.Done", archive.Name), Formatting.LeftToRight(archive.RootPath));
await LoadAsync();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", $"Relinking {folder} failed", ex);
// Retry asks for the folder again: the same one once its drive is back, or the right one.
NotifyFailure("Archive.Relink.Failed", ex, RelinkCommand);
}
}
private async Task ExportAsync()
{
var set = Set();
var folder = Services.Dialogs.PickFolder(Loc.L("Library.Export.Title"));
if (folder is null || set.Count == 0) return;
var path = Path.Combine(folder, $"Titano sequences {DateTime.Now:yyyy-MM-dd HHmm}.csv");
var csv = LibraryCsv.Write(set);
await Task.Run(() => AtomicFile.WriteAllText(path, csv));
Shell.Notify(Loc.L("Library.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
() => 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;
var search = StartSearch();
try
{
var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id, search.Token), search.Token);
var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token);
// Picking another archive cancels the search; one that ended just then is not the picked archive's.
if (!IsShowing(archive)) return;
Duplicates = DuplicateRows(groups, locations);
Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
{
}
catch (DatabaseException ex)
{
Log.Warning("archive", "Duplicates search failed", ex);
NotifyFailure("Archive.Duplicates.Failed", ex, FindDuplicatesCommand);
}
finally
{
_findingDuplicates = false;
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;
var search = StartSearch();
try
{
var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id, search.Token), search.Token);
var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token);
if (!IsShowing(archive)) return;
Orphans = OrphanRows(report, locations);
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 DatabaseException)
{
Log.Warning("archive", "Orphan search failed", ex);
NotifyFailure("Archive.Orphans.Failed", ex, FindOrphansCommand);
}
finally
{
_findingOrphans = false;
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(IsFindingDuplicates));
OnPropertyChanged(nameof(IsFindingOrphans));
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,
new RelayCommand(() => Shell.OpenSequence(row.SequenceId)),
new RelayCommand(() =>
{
if (_archive is { } archive && locations.FirstOrDefault(l => l.Id == row.SequenceId) is { } location)
ShellActions.Reveal(new ArchivePaths(archive.RootPath).Sequence(location.Folder).Folder);
}))),
];
private IReadOnlyList<OrphanRowViewModel> OrphanRows(OrphanReport report, IReadOnlyList<SequenceLocation> locations) =>
[.. MaintenanceReports.Orphans(report, locations).Select(row => new OrphanRowViewModel(row, new AsyncRelayCommand(() => FixAsync(row))))];
/// <summary>The safe fix of an orphan line; removing an index row asks first (its sidecar is gone, its files are not touched).</summary>
private async Task FixAsync(OrphanRow row)
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
try
{
switch (row.Kind)
{
case OrphanKind.UnlistedFiles or OrphanKind.MissingFiles when row.SequenceId is { } id:
await Task.Run(() => archives.ReconcileAsync(id));
break;
case OrphanKind.MissingSequence when row.SequenceId is { } id:
var confirmed = Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Archive.Confirm.RemoveHeading", row.Title),
Message = Loc.L("Archive.Confirm.RemoveMessage"),
SafeText = Loc.L("Archive.Confirm.Keep"),
SafeToolTip = Loc.L("Tooltips.Archive.KeepRow"),
ActionText = Loc.L("Archive.Confirm.Remove"),
ActionToolTip = Loc.L("Tooltips.Archive.Orphans.MissingSequence"),
IsDestructive = true,
});
if (!confirmed) return;
await Task.Run(() => archives.RemoveMissingSequencesAsync(archive.Id, [id]));
break;
case OrphanKind.NewFolder:
await Services.QueueScanAsync(archive, full: false);
Queued(JobKind.Scan, archive.Name);
return;
default:
return;
}
Orphans = Orphans?.Where(o => o.Row != row).ToList();
await LoadAsync();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
{
Log.Warning("archive", $"Fixing {row.Title} failed", ex);
NotifyFailure("Archive.Orphans.FixFailed", ex, new AsyncRelayCommand(() => FixAsync(row)));
}
}
/// <summary>An action stopped: what stopped, why in one sentence, and Retry to run it again (BRIEF §0.2 rule 6).</summary>
private void NotifyFailure(string titleKey, Exception ex, ICommand retry) =>
Shell.Notify(Loc.L(titleKey), ArchiveFailures.Cause(ex), Loc.L("Archive.Failed.Retry"), Loc.L("Tooltips.Archive.Retry"), () => retry.Execute(null),
isError: true);
}