using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Library;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Repositories;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Visuals;
namespace Chronos.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 and filtered set (analyse, proxies, thumbnails, verify,
/// reorganize, convert, 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.
///
public sealed class ArchiveViewModel : SectionViewModel
{
private const int RecentCount = 6;
private static readonly TimeSpan RecentInterval = TimeSpan.FromMilliseconds(500);
private const int PageSize = 1000;
private static readonly TimeSpan ReloadDelay = TimeSpan.FromSeconds(2);
/// 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;
/// The archive whose availability, figures and tree were read last: until it is the picked one, nothing acts on them.
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;
/// A Reorganize the Settings toast asked for while a dialog was open: it opens once that one closes.
private (Core.Model.Archive Archive, ReorganizeParts Parts)? _waitingReorganize;
private IReadOnlyList _tiles = [];
private IReadOnlyList _months = [];
private IReadOnlyList _storage = [];
private IReadOnlyList _cameras = [];
private IReadOnlyList _formats = [];
private IReadOnlyList _health = [];
private IReadOnlyList _recent = [];
/// The jobs behind , their running ones' latest progress, and the ids whose progress counts here.
private IReadOnlyList _recentJobs = [];
private readonly Dictionary _recentLive = [];
private readonly System.Collections.Concurrent.ConcurrentDictionary _recentPending = new();
private HashSet _recentRunning = [];
private CoalescingThrottle? _recentThrottle;
private IReadOnlyList? _duplicates;
private IReadOnlyList? _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 = Chronos.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);
ReorganizeSetCommand = new AsyncRelayCommand(() => OpenReorganizeDialogAsync(), () => HasSet() && IsOnline());
ConvertSetCommand = new AsyncRelayCommand(() => OpenConvertDialogAsync(), () => 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 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));
/// 0 = overview (tree and figures), 1 = maintenance.
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;
/// "Last scan 29/09/2026 07:12 · 14 min".
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 ReorganizeSetToolTip => WhenSet("Tooltips.Archive.SetReorganize", needsOnline: true);
public string ConvertSetToolTip => WhenSet("Tooltips.Archive.SetConvert", 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; }
/// "Adopt folder ▾ › Copy into archive": the Import screen copies the folder into the archive with its templates.
public ICommand CopyFolderCommand { get; }
public ICommand BackupCommand { get; }
/// "Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a backup copy is compared and restored (§6.2).
public ICommand RestoreCommand { get; }
public ICommand MaintenanceCommand { get; }
public ICommand MaintenanceDryRunCommand { get; }
public ICommand RebuildProxiesCommand { get; }
public ICommand RelinkCommand { get; }
public ICommand HistoryCommand { get; }
/// "Maintenance ▾ › Trash…": the sequences deleted from this archive, each restorable.
public ICommand TrashCommand { get; }
// ---------------- Overview ----------------
public ObservableCollection TreeRows { get; } = [];
public IReadOnlyList Tiles { get => _tiles; private set => Set(ref _tiles, value); }
public IReadOnlyList MonthRows { get => _months; private set => Set(ref _months, value); }
public IReadOnlyList MonthLabels => ArchiveFigures.MonthLabels();
public IReadOnlyList StorageBars { get => _storage; private set => Set(ref _storage, value); }
public IReadOnlyList CameraBars { get => _cameras; private set => Set(ref _cameras, value); }
public IReadOnlyList FormatBars { get => _formats; private set => Set(ref _formats, value); }
/// The heatmap's scale in the card header (Archive.html: "0 ▭ 21,000"); hidden without photos.
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();
/// What each chart shows, value by value, for screen readers (the charts themselves are images).
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));
/// Photos per month in the culture's digits.
public Func CountFormatter { get; } = v => Formatting.Count((long)v);
/// "412 sequences · all", "36 sequences", "Harbour sunset", each followed by the filter ("· Canon EOS R5").
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();
}
}
/// The set button's accessible name: what it is and the set it shows.
public string SetFilterName => Loc.L("Archive.Set.Filter") + Loc.Separator + SetText;
/// 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; }
public ICommand VerifySetCommand { get; }
/// Reorganize…: the set's folders, file names and titles from templates, a dry run first, then a job.
public ICommand ReorganizeSetCommand { get; }
/// Convert…: the set's photos to JPEG, 16-bit TIFF or linear DNG, Replace or New sequence, a dry run first, then a job.
public ICommand ConvertSetCommand { get; }
public ICommand RetagSetCommand { get; }
public ICommand ExportSetCommand { get; }
/// Moves the set to the archive's trash after its dry run and a typed confirmation.
public ICommand DeleteSetCommand { get; }
/// 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.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
{
if (Set(ref _recent, value)) OnPropertyChanged(nameof(HasRecent));
}
}
public bool HasRecent => _recent.Count > 0;
public IReadOnlyList? Duplicates
{
get => _duplicates;
private set
{
if (!Set(ref _duplicates, value)) return;
OnPropertyChanged(nameof(DuplicatesText));
ShowHealth();
}
}
public IReadOnlyList? Orphans
{
get => _orphans;
private set
{
if (Set(ref _orphans, value)) OnPropertyChanged(nameof(OrphansText));
}
}
/// The duplicates search runs: its card offers Cancel; the other card's Find waits for it.
public bool IsFindingDuplicates => _findingDuplicates;
/// The orphans search runs: its card offers Cancel; the other card's Find waits for it.
public bool IsFindingOrphans => _findingOrphans;
/// "3 groups", "None found", or empty before the first search.
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 ----------------
/// The open in-window dialog (rebuild, reorganize, convert, retag, delete, trash); null when none.
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;
/// 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 ----------------
protected override void OnActivated()
{
if (_loaded) return;
_ = LoadAsync();
}
///
/// 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.
///
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();
}
}
///
/// 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.
///
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();
}
/// Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.
public async Task 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;
}
/// Shows reports computed elsewhere (capture).
public void ShowReports(IReadOnlyList duplicates, OrphanReport orphans, IReadOnlyList locations)
{
Duplicates = DuplicateRows(duplicates, locations);
Orphans = OrphanRows(orphans, locations);
}
/// The UI language changed: the figures, tree and health rows are read again in the new language.
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;
jobs.Progress -= OnProgress;
}
_recentThrottle?.Dispose();
_waitingReorganize = null;
_dialog?.Dispose();
base.Dispose();
}
private static async Task> ListSequencesAsync(ChronosDatabase db, Guid archiveId)
{
var all = new List();
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();
}
/// The health lines of the last figures; the duplicates line follows the last duplicates search.
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 Bars(IReadOnlyList values) =>
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
private static string Describe(IEnumerable values) => string.Join(Environment.NewLine, values.Where(v => !string.IsNullOrEmpty(v)));
/// A reloaded tree keeps the open years and the selection (nodes that still exist).
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();
}
///
/// 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()
{
_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();
}
/// 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(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(ReorganizeSetToolTip));
OnPropertyChanged(nameof(ConvertSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
OnPropertyChanged(nameof(DeleteSetToolTip));
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(ChronosDatabase db, Core.Model.Archive archive)
{
var jobs = new List();
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;
_recentJobs = jobs;
_recentLive.Clear();
_recentPending.Clear();
Volatile.Write(ref _recentRunning, [.. jobs.Where(j => j.State == JobState.Running).Select(j => j.Id)]);
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;
// A running Recent line follows its job (owner review 5, #65), at most twice a second.
_recentThrottle = new CoalescingThrottle(RecentInterval, SynchronizationContext.Current, FlushRecent);
jobs.Progress += OnProgress;
_jobEvents = true;
}
/// Progress of a running job of "Recent maintenance" (any thread): kept until the next flush.
private void OnProgress(JobProgressInfo progress)
{
if (!Volatile.Read(ref _recentRunning).Contains(progress.JobId)) return;
_recentPending[progress.JobId] = progress;
_recentThrottle?.Signal();
}
/// The running Recent lines with their latest progress (UI thread).
private void FlushRecent()
{
var changed = false;
foreach (var id in _recentPending.Keys)
{
if (!_recentPending.TryRemove(id, out var progress) || !_recentRunning.Contains(id)) continue;
_recentLive[id] = progress;
changed = true;
}
if (changed) Recent = MaintenanceReports.Recent(_recentJobs, RecentCount, _recentLive);
}
///
/// 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)) 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 or JobKind.Move or JobKind.Convert)) 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;
/// The picked archive's availability and figures are known (a slow volume is probed for seconds).
private bool IsRead() => _archive is { } archive && _readId == archive.Id;
/// The archive a read started with is still the one picked.
private bool IsShowing(Core.Model.Archive archive) => _archive?.Id == archive.Id;
/// A command's tooltip, or why it is disabled: these commands write to the archive or read all of it.
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;
/// 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, []);
private string SetLabel() => SetText;
private async Task QueueAsync(Func 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, ArchiveJobRequest> build, IReadOnlyList 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());
}
/// 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 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);
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));
/// Opens Reorganize on the set, the archive's layout (folders and file names) switched on, and waits for its dry run.
public async Task OpenReorganizeDialogAsync()
{
if (Services.Archives is not { } archives || Services.Engine is not { } engine || _archive is not { } shown) return;
IReadOnlyList set = [.. Set().Select(s => s.Id)];
// The templates as they are now: Settings › Archive may have changed them since this screen read the archive.
var archive = await FreshAsync(shown);
var dialog = new ReorganizeDialogViewModel(archives, archive, set, ReorganizePlans.Layout, r => EnqueueAsync(engine, r), CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
///
/// Opens Reorganize on every sequence of (Settings › Archive offers it after its templates
/// changed), with switched on; the screen shows that archive. The toast is reached from
/// another screen, so a dialog may be open here, a Delete moving sequences say: it is never replaced nor its archive
/// switched under it; Reorganize waits, says so, and opens once that dialog closes.
///
public async Task OpenReorganizeAllAsync(Core.Model.Archive archive, ReorganizeParts parts)
{
ArgumentNullException.ThrowIfNull(archive);
if (_dialog is not null)
{
_waitingReorganize = _waitingReorganize is { } waiting && waiting.Archive.Id == archive.Id ? (archive, waiting.Parts | parts) : (archive, parts);
Shell.Notify(Loc.L("Archive.Reorganize.Waiting"));
return;
}
if (Services.Archives is not { } archives || Services.Engine is not { } engine) return;
if (_archive != archive) SelectedArchive = archive;
var dialog = new ReorganizeDialogViewModel(archives, archive, null, parts, r => EnqueueAsync(engine, r), CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
/// The Reorganize that waited for the dialog that just closed, with the archive's templates as they are now.
private async Task OpenWaitingReorganizeAsync()
{
if (_waitingReorganize is not { } waiting) return;
_waitingReorganize = null;
await OpenReorganizeAllAsync(await FreshAsync(waiting.Archive), waiting.Parts);
}
/// Opens Convert on the set and waits for its dry run (the archival format, no mode chosen yet).
public async Task OpenConvertDialogAsync()
{
if (Services.Archives is not { } archives || Services.Engine is not { } engine || _archive is not { } archive) return;
IReadOnlyList set = [.. Set().Select(s => s.Id)];
var dialog = new ConvertDialogViewModel(archives, archive, set, r => EnqueueAsync(engine, r), Services.Dialogs.Confirm, CloseDialog);
OpenDialog(dialog);
await dialog.PlanAsync();
}
/// The archive's record as the index holds it now; when it cannot be read.
private async Task FreshAsync(Core.Model.Archive archive)
{
if (Services.Database is not { } db) return archive;
try
{
return await db.Archives.GetAsync(archive.Id) ?? archive;
}
catch (DatabaseException ex)
{
Log.Warning("archive", "The archive's templates were not read again", ex);
return archive;
}
}
private async Task EnqueueAsync(JobEngine engine, ArchiveJobRequest request)
{
await engine.EnqueueAsync(request);
Queued(request.Kind, request.Label ?? SetLabel());
}
///
/// 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.
///
public async Task DeleteSetAsync()
{
var dialog = new DeleteDialogViewModel(Shell, [.. Set().Select(s => s.Id)], CloseDialog);
OpenDialog(dialog);
return await dialog.RunAsync();
}
/// Opens the trash of the archive and reads it.
public async Task OpenTrashAsync()
{
if (Services.Archives is not { } archives || _archive is not { } archive) return;
var engine = Services.Engine;
var dialog = new TrashDialogViewModel(archives, archive, async () =>
{
await LoadAsync();
await Shell.Library.RefreshAsync();
}, CloseDialog, Services.Dialogs.Confirm, engine is null ? null : async request =>
{
await engine.EnqueueAsync(request);
Queued(request.Kind, archive.Name);
}, engine);
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();
}
///
/// Closes if it is still the open one (an apply that finishes late closes nothing else); a
/// Reorganize asked for meanwhile opens then.
///
private void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
_ = OpenWaitingReorganizeAsync();
}
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();
}
}
/// 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, await DatabaseBackups.KeptAsync(db));
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);
}
}
/// A moved archive keeps its id: opening it at the new root relinks every sequence (BRIEF §12.5 Move archive).
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, $"Chronos 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));
}
/// 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;
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);
}
}
/// 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;
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 DuplicateRows(IReadOnlyList groups, IReadOnlyList 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 OrphanRows(OrphanReport report, IReadOnlyList locations) =>
[.. MaintenanceReports.Orphans(report, locations).Select(row => new OrphanRowViewModel(row, new AsyncRelayCommand(() => FixAsync(row))))];
/// The safe fix of an orphan line; removing an index row asks first (its sidecar is gone, its files are not touched).
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:
// The photos it indexes are analysed in the background, as after a scan.
var (followUps, deep) = (Services.Engine, Services.Settings.DeepAnalysisAfterScan);
await Task.Run(() => archives.ReconcileAsync(id, followUps, deep));
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)));
}
}
/// An action stopped: what stopped, why in one sentence, and Retry to run it again (BRIEF §0.2 rule 6).
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);
}