feat(app): Import and Archive manager screens with capture scenes and resources

Import (cards and folders): the card pool with remembered profiles and the
nickname field for new cards, the form (destination, scan, sessions, names
with live preview and tokens, duplicates, after-import choices), the plan
panel with editable session titles, Show plan, the archive import job or
the folder/server run with progress, the verification result and the
after-import actions (dry run, delete, format through the Windows dialog,
eject, open in Library), card-insertion toasts, automatic import into the
archive and resume after re-insertion. Deep analysis after import is queued
with ProcessingJobs at background priority.

Archive manager: archive picker, tree with availability, figure tiles and
charts, mass operations on the selected set, scan/rebuild (dialog)/verify/
duplicates/orphans/adopt/maintenance as jobs, and the maintenance view with
index health, recent runs and the duplicate and orphan reports with safe
fixes.

--capture renders import-<state> and archive-<view> from a simulated card
and sample reports; en and it resources for both screens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 22:20:10 +00:00
1 parent f7affe7840
commit a0e814885c
31 files changed
+4531 -28

No files matched your search

@@ -0,0 +1,289 @@
using System.IO;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Settings;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Ui.Mvvm;
namespace Titano.App.Archiving;
/// <summary>An in-window dialog of the Archive screen: one primary action, one way out.</summary>
public abstract class ArchiveDialogViewModel(Action close) : LocalizedViewModel
{
private bool _isBusy;
private string? _busyText;
public ICommand CloseCommand { get; } = new RelayCommand(close);
public bool IsBusy
{
get => _isBusy;
protected set
{
if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested();
}
}
public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); }
protected void Close() => CloseCommand.Execute(null);
}
/// <summary>A fact of the rebuild dialog ("Sidecars · 412").</summary>
public sealed record DialogFact(string Label, string Value);
/// <summary>
/// "Rebuild index" (BRIEF §12.5): what the rebuild reads — the sidecars on disk, then a full metadata scan of folders
/// without one — next to what the index holds now. Originals are never touched; the rebuild runs as a job.
/// </summary>
public sealed class RebuildDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<Task> _rebuild;
private IReadOnlyList<DialogFact> _facts;
public RebuildDialogViewModel(Core.Model.Archive archive, ArchiveAvailability availability, int indexed, Func<Task> rebuild, Action close)
: base(close)
{
_rebuild = rebuild;
Archive = archive;
Availability = availability;
Indexed = indexed;
_facts = Facts(null);
RebuildCommand = new AsyncRelayCommand(RebuildAsync, () => !IsBusy && availability == ArchiveAvailability.Online);
}
public Core.Model.Archive Archive { get; }
public ArchiveAvailability Availability { get; }
public int Indexed { get; }
public IReadOnlyList<DialogFact> FactRows { get => _facts; private set => Set(ref _facts, value); }
public ICommand RebuildCommand { get; }
public string RebuildToolTip => Availability == ArchiveAvailability.Online ? Loc.L("Tooltips.Archive.RebuildStart") : Loc.L("Archive.Blocked.NotOnline");
/// <summary>Counts sequence folders with and without a sidecar (a walk of the archive tree, off the UI thread).</summary>
public async Task CountAsync()
{
if (Availability == ArchiveAvailability.Offline) return;
BusyText = Loc.L("Archive.Rebuild.Counting");
try
{
var root = Archive.RootPath;
var folders = await Task.Run(() => ArchiveScanner.FindSequenceFolders(new ArchivePaths(root)));
FactRows = Facts(folders);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", "Counting sidecars failed", ex);
}
finally
{
BusyText = null;
}
}
/// <summary>Shows counts computed elsewhere (capture).</summary>
public void ShowFolders(IReadOnlyList<SequenceFolder> folders) => FactRows = Facts(folders);
private IReadOnlyList<DialogFact> Facts(IReadOnlyList<SequenceFolder>? folders)
{
var waiting = Loc.L("Archive.Rebuild.Counting");
return
[
new(Loc.L("Archive.Rebuild.Archive"), Archive.Name),
new(Loc.L("Archive.Rebuild.Root"), Archive.RootPath),
new(Loc.L("Archive.Rebuild.State"), Loc.L("Archive.Availability." + Availability)),
new(Loc.L("Archive.Rebuild.Indexed"), Loc.Plural("Shell.Status.Sequences", Indexed)),
new(Loc.L("Archive.Rebuild.Sidecars"), folders is null ? waiting : Formatting.Count(folders.Count(f => f.Sidecar is not null))),
new(Loc.L("Archive.Rebuild.Metadata"), folders is null ? waiting : Formatting.Count(folders.Count(f => f.Sidecar is null))),
];
}
private async Task RebuildAsync()
{
IsBusy = true;
try
{
await _rebuild();
Close();
}
finally
{
IsBusy = false;
}
}
}
/// <summary>
/// Mass rename (titles) or move (folder layout) of a set (BRIEF §7, §12.5): the template is checked as it is typed,
/// the dry run lists every change, and Apply makes exactly those changes (journaled, so a crash resumes it).
/// </summary>
public sealed class RenameDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly Core.Model.Archive _archive;
private readonly IReadOnlyList<Sequence> _set;
private readonly Func<int, Task> _applied;
private readonly DispatcherTimer _delay = new() { Interval = TimeSpan.FromMilliseconds(400) };
private RenamePlan? _plan;
private IReadOnlyList<RenameRow> _rows = [];
private CancellationTokenSource? _planning;
public RenameDialogViewModel(RenameMode mode, ArchiveService archives, Core.Model.Archive archive, IReadOnlyList<Sequence> set, Func<int, Task> applied,
Action close)
: base(close)
{
Mode = mode;
_archives = archives;
_archive = archive;
_set = set;
_applied = applied;
var initial = mode == RenameMode.Folders ? archive.FolderTemplate : "{title}";
Template = new EditableField(initial, t => MassRename.Validate(mode, t), committed => _ = PlanAsync(),
() => Loc.L(mode == RenameMode.Folders ? "Tooltips.Archive.FolderTemplate" : "Tooltips.Archive.TitleTemplate"));
Template.PropertyChanged += (_, e) =>
{
if (e.PropertyName != nameof(EditableField.Text)) return;
_delay.Stop();
_delay.Start();
};
_delay.Tick += (_, _) =>
{
_delay.Stop();
_ = PlanAsync();
};
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => !IsBusy && _plan is { Steps.Count: > 0 } && !Template.HasErrors);
}
public RenameMode Mode { get; }
public string Heading => Loc.Plural(Mode == RenameMode.Folders ? "Archive.Rename.MoveHeading" : "Archive.Rename.Heading", _set.Count);
public EditableField Template { get; }
public IReadOnlyList<RenameRow> Rows { get => _rows; private set => Set(ref _rows, value); }
public string SummaryText => _plan is null ? string.Empty : MassRename.Summary(_plan, _set.Count);
public ICommand ApplyCommand { get; }
/// <summary>The dry run of the current template (the engine's plan; nothing changes on disk).</summary>
public async Task PlanAsync()
{
_planning?.Cancel();
_plan = null;
Rows = [];
OnPropertyChanged(nameof(SummaryText));
if (Template.HasErrors) return;
var cts = _planning = new CancellationTokenSource();
var template = Template.Text;
var ids = _set.Select(s => s.Id).ToList();
try
{
var plan = await Task.Run(() => _archives.PlanRenameAsync(_archive.Id, ids, Mode == RenameMode.Folders ? template : null,
Mode == RenameMode.Titles ? template : null, cts.Token), cts.Token);
if (cts.IsCancellationRequested) return;
_plan = plan;
Rows = MassRename.Rows(plan, Mode);
OnPropertyChanged(nameof(SummaryText));
CommandManager.InvalidateRequerySuggested();
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is ArgumentException or DatabaseException or FormatException)
{
Log.Warning("archive", "Rename plan failed", ex);
BusyText = ex.Message;
}
}
private async Task ApplyAsync()
{
if (_plan is not { } plan) return;
IsBusy = true;
var progress = new Progress<int>(n => BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(n), Formatting.Count(plan.Steps.Count)));
try
{
await Task.Run(() => _archives.ApplyRenameAsync(plan, progress));
await _applied(plan.Steps.Count);
Close();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or StaleRenamePlanException or ArchiveOfflineException)
{
Log.Warning("archive", "Rename failed", ex);
BusyText = ex.Message;
}
finally
{
IsBusy = false;
}
}
}
/// <summary>Add and remove tags on a set (BRIEF §12.5 Retag): the dry run counts the sequences that change.</summary>
public sealed class RetagDialogViewModel : ArchiveDialogViewModel
{
private readonly ArchiveService _archives;
private readonly IReadOnlyList<Sequence> _set;
private readonly Func<int, Task> _applied;
public RetagDialogViewModel(ArchiveService archives, IReadOnlyList<Sequence> set, Func<int, Task> applied, Action close)
: base(close)
{
_archives = archives;
_set = set;
_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);
}
public string Heading => Loc.Plural("Archive.Retag.Heading", _set.Count);
public EditableField Add { get; }
public EditableField Remove { get; }
/// <summary>"12 of 36 change".</summary>
public string SummaryText => Loc.Plural("Archive.Rename.Summary", Changes().Count, _set.Count);
public ICommand ApplyCommand { get; }
private IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> Tags)> Changes() =>
Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
private async Task ApplyAsync()
{
var changes = Changes();
IsBusy = true;
try
{
for (var i = 0; i < changes.Count; i++)
{
var (s, tags) = changes[i];
BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(i + 1), Formatting.Count(changes.Count));
await Task.Run(() => _archives.SetSequenceInfoAsync(s.Id, s.Title, tags, s.Rating, s.Notes));
}
await _applied(changes.Count);
Close();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or DatabaseException or ArchiveOfflineException)
{
Log.Warning("archive", "Retag failed", ex);
BusyText = ex.Message;
}
finally
{
IsBusy = false;
}
}
}
@@ -0,0 +1,73 @@
using System.Windows.Input;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Archiving;
/// <summary>A visible row of the archive tree: indentation, expander, title, figures and availability.</summary>
public sealed class ArchiveTreeRowViewModel(ArchiveTreeNode node, ArchiveAvailability availability, Action<ArchiveTreeNode> toggle) : ObservableObject
{
public ArchiveTreeNode Node { get; } = node;
public string Title => Node.Title;
public string Detail => Node.Detail;
/// <summary>16 px per level.</summary>
public System.Windows.Thickness IndentMargin => new(Node.Depth * 16, 0, 0, 0);
public bool HasChildren => Node.HasChildren;
public bool IsExpanded => Node.IsExpanded;
public bool IsArchive => Node.Kind == TreeNodeKind.Archive;
public bool IsYear => Node.Kind == TreeNodeKind.Year;
public string ToggleToolTip => Loc.L(Node.IsExpanded ? "Tooltips.Archive.Collapse" : "Tooltips.Archive.Expand");
public ICommand ToggleCommand { get; } = new RelayCommand(() => toggle(node));
/// <summary>The archive's availability (BRIEF §7: online, read-only, offline) on the archive row.</summary>
public StatusKind AvailabilityKind => availability switch
{
ArchiveAvailability.Online => StatusKind.Online,
ArchiveAvailability.ReadOnly => StatusKind.Warning,
_ => StatusKind.Offline,
};
public string AvailabilityText => Loc.L("Archive.Availability." + availability);
public string AvailabilityToolTip => Loc.L("Tooltips.Archive.Availability." + availability);
}
/// <summary>A line of "Index health" with its fix.</summary>
public sealed class HealthLineViewModel(HealthLine line, ICommand? fix) : ObservableObject
{
public HealthLine Line { get; } = line;
public string Text => Line.Text;
public StatusKind Kind => Line.IsOk ? StatusKind.Done : StatusKind.Warning;
public string KindToolTip => Loc.L(Line.IsOk ? "Tooltips.Archive.HealthOk" : "Tooltips.Archive.HealthWarning");
public bool HasFix => FixCommand is not null && Line.Action != HealthAction.None;
public ICommand? FixCommand { get; } = fix;
public string FixText => HasFix ? Loc.L("Archive.Health.Fix." + Line.Action) : string.Empty;
public string FixToolTip => HasFix ? Loc.L("Tooltips.Archive.Fix." + Line.Action) : string.Empty;
}
/// <summary>A duplicate group with its safe actions: open the first copy's sequence, show its folder.</summary>
public sealed class DuplicateRowViewModel(DuplicateRow row, ICommand open, ICommand reveal) : ObservableObject
{
public DuplicateRow Row { get; } = row;
public string Places => string.Join(" · ", Row.Places);
public ICommand OpenCommand { get; } = open;
public ICommand RevealCommand { get; } = reveal;
}
/// <summary>An orphan line with its fix (index, reconcile, remove the row, scan).</summary>
public sealed class OrphanRowViewModel(OrphanRow row, ICommand fix) : ObservableObject
{
public OrphanRow Row { get; } = row;
public StatusKind Kind => Row.Kind is OrphanKind.MissingFiles or OrphanKind.MissingSequence ? StatusKind.Warning : StatusKind.Queued;
public string KindText => Loc.L("Archive.Orphans.Kind." + Row.Kind);
public ICommand FixCommand { get; } = fix;
public string FixText => Loc.L("Archive.Orphans.Fix." + Row.Kind);
public string FixToolTip => Loc.L("Tooltips.Archive.Orphans." + Row.Kind);
}
+39
View File
@@ -0,0 +1,39 @@
using Titano.App.Shell;
namespace Titano.App.Archiving;
/// <summary>
/// The Archive views that <c>--capture</c> renders (<c>archive-&lt;view&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the sample archive: the tree with figures and charts, the maintenance view with its reports, and
/// the rebuild dialog.
/// </summary>
public static class ArchiveScenes
{
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild"];
public static async Task ShowAsync(ShellViewModel shell, string view)
{
var archive = shell.Archive;
shell.Navigate(SectionKey.Archive);
archive.Dialog?.CloseCommand.Execute(null);
await archive.LoadAsync();
var db = shell.Services.Database ?? throw new InvalidOperationException("The sample index is not open.");
var locations = archive.SelectedArchive is { } selected ? await db.Sequences.ListLocationsAsync(selected.Id) : [];
switch (view)
{
case "overview":
archive.ViewIndex = 0;
break;
case "maintenance":
archive.ViewIndex = 1;
archive.ShowReports(SampleReports.Duplicates(locations), SampleReports.Orphans(locations), locations);
break;
case "rebuild":
archive.ViewIndex = 0;
(await archive.OpenRebuildDialogAsync())?.ShowFolders(SampleReports.Folders(locations));
break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
}
}
+31
View File
@@ -0,0 +1,31 @@
using System.IO;
using Titano.Data;
namespace Titano.App.Archiving;
/// <summary>The archive the Import and Archive screens work on: the one at the remembered root, else the first indexed.</summary>
public static class CurrentArchive
{
public static Core.Model.Archive? Pick(IReadOnlyList<Core.Model.Archive> archives, string? lastRoot)
{
if (archives.Count == 0) return null;
if (string.IsNullOrWhiteSpace(lastRoot)) return archives[0];
var wanted = Normalize(lastRoot);
return archives.FirstOrDefault(a => string.Equals(Normalize(a.RootPath), wanted, StringComparison.OrdinalIgnoreCase)) ?? archives[0];
}
public static async Task<Core.Model.Archive?> FindAsync(TitanoDatabase db, string? lastRoot, CancellationToken cancellationToken = default) =>
Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), lastRoot);
private static string Normalize(string path)
{
try
{
return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return path;
}
}
}
+40
View File
@@ -0,0 +1,40 @@
using Titano.Core.Archiving;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>
/// Capture and smoke-test data ONLY: maintenance reports and rebuild counts over the sample archive's sequences
/// (the sample index has no sidecars on disk, so the real searches would find nothing to show).
/// </summary>
public static class SampleReports
{
private const string Sha = "9f2c41d07be8a6c3e15f0d2b84a97c6e3d1f50a28b9e7c4d6a0f3e2b1c8d9a47";
/// <summary>One photo stored twice: a frame of the first sequence copied into the second.</summary>
public static IReadOnlyList<DuplicateGroup> Duplicates(IReadOnlyList<SequenceLocation> sequences) =>
sequences.Count < 2
? []
:
[
new DuplicateGroup(Sha,
[
new DuplicateFrame(Sha, Guid.CreateVersion7(), sequences[0].Id, 0, sequences[0].Folder + "/IMG_0001.CR2"),
new DuplicateFrame(Sha, Guid.CreateVersion7(), sequences[1].Id, 12, sequences[1].Folder + "/IMG_0001.CR2"),
]),
];
/// <summary>Two photos missing from a sidecar, a row whose sidecar is gone and a folder not indexed yet.</summary>
public static OrphanReport Orphans(IReadOnlyList<SequenceLocation> sequences) =>
sequences.Count < 4
? new OrphanReport([], [], [])
: new OrphanReport([new SequenceOrphans(sequences[2].Folder, ["IMG_0412.CR2", "IMG_0413.CR2"], [])], [sequences[3]], ["2024/2024-12-31 Unsorted"]);
/// <summary>What the rebuild dialog counts: a sidecar in every sequence folder but the last two, read by metadata instead.</summary>
public static IReadOnlyList<SequenceFolder> Folders(IReadOnlyList<SequenceLocation> sequences)
{
var stamp = new FileStamp(4_096, DateTime.UtcNow);
return [.. sequences.Select((s, i) => new SequenceFolder(s.Folder, i < sequences.Count - 2 ? stamp : null, stamp))];
}
}