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

+3 -4
View File
@@ -36,12 +36,12 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic
: Device is { Label.Length: > 0 } labelled ? labelled.Label
: Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty;
/// <summary>"E:\ · 128 GB · 96.2 GB used", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted".</summary>
/// <summary>"128 GB · 96.2 GB used", "no DCIM · 1.8 TB free", "Canon EOS R5 · not inserted".</summary>
public string Subtitle => Kind switch
{
SourceKind.Folder => FolderPath ?? string.Empty,
SourceKind.Drive => Loc.L("Import.Device.NoDcim", Device!.Root, Formatting.Bytes(Device.FreeBytes)),
_ when Device is not null => Loc.L("Import.Device.Card", Device.Root, Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)),
SourceKind.Drive => Loc.L("Import.Device.NoDcim", Formatting.Bytes(Device!.FreeBytes)),
_ when Device is not null => Loc.L("Import.Device.Card", Formatting.Bytes(Device.TotalBytes), Formatting.Bytes(Device.UsedBytes)),
_ => Loc.L("Import.Device.Away", CameraText(Card) is { Length: > 0 } camera ? camera : Formatting.Bytes(Card!.Capacity)),
};
@@ -61,7 +61,6 @@ public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Devic
get
{
var parts = new List<string>();
if (Device is not null) parts.Add(Device.Root);
var capacity = Device?.TotalBytes ?? Card?.Capacity ?? 0;
if (capacity > 0) parts.Add(Formatting.Bytes(capacity));
var serial = Device?.SerialNumber ?? Card?.VolumeSerial;
+7 -2
View File
@@ -35,12 +35,17 @@ public sealed class UnindexedDestination(ImportDestinationKind kind, string root
/// <summary>The folder, or the local staging folder of server uploads.</summary>
public string Root { get; } = root;
public Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken)
/// <summary>Room left on the server (the user's quota); null when unlimited or unknown. A folder reports its volume's space.</summary>
public long? ServerSpace { get; init; }
public async Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken)
{
var problems = new List<ImportProblem>();
var files = CardScanner.Find(sourceRoot, options.IncludeSubfolders, cancellationToken);
var photos = CardScanner.ReadMetadata(sourceRoot, files, problems, progress, cancellationToken);
return ImportPlanner.PlanAsync(sourceRoot, Root, photos, problems, options, NoIndex.Instance, cancellationToken);
var plan = await ImportPlanner.PlanAsync(sourceRoot, Root, photos, problems, options, NoIndex.Instance, cancellationToken).ConfigureAwait(false);
// Staging only ever holds one batch; the space that matters for a server import is the quota.
return Kind == ImportDestinationKind.Server ? plan with { AvailableBytes = ServerSpace } : plan;
}
/// <summary>No history and no index; folders are reused so a repeated import lands next to the first one.</summary>
@@ -0,0 +1,249 @@
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Import;
/// <summary>
/// The end of an import (BRIEF §12.4, §13): the verification result and the after-import actions — check the card
/// (dry run: every card file and its archive copy hashed again), delete the verified photos or format the card
/// (each after a confirmation, never by default), eject, open in the Library. <see cref="CardActions"/> decides
/// what is allowed and why not.
/// </summary>
public sealed class ImportResultViewModel : LocalizedViewModel
{
private const int ListedFailures = 100;
private readonly ShellViewModel _shell;
private readonly ImportPlan _plan;
private readonly ImportChoices _choices;
private readonly Core.Model.Archive? _archive;
private readonly MediaCard? _card;
private CardDevice? _device;
private CardActions _actions;
private bool _isBusy;
private string? _busyText;
public ImportResultViewModel(ShellViewModel shell, ImportPlan plan, ImportOutcome outcome, ImportChoices choices, Core.Model.Archive? archive,
MediaCard? card, CardDevice? device)
{
_shell = shell;
_plan = plan;
_choices = choices;
_archive = archive;
_card = card;
_device = device;
Outcome = outcome;
_actions = new CardActions(choices.Destination, card is not null, device is not null, device?.IsRemovable == true, outcome, null,
plan.FileCount + plan.Problems.Count);
Failures = [.. outcome.Failures.Take(ListedFailures).Select(f => Loc.L("Import.Result.Failure", f.SourcePath, f.Message))];
CheckCommand = new AsyncRelayCommand(CheckAsync, () => _actions.CanCheck && !_isBusy);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => _actions.CanDelete && !_isBusy);
FormatCommand = new RelayCommand(Format, () => _actions.CanFormat && !_isBusy);
EjectCommand = new AsyncRelayCommand(EjectAsync, () => _actions.CanEject && !_isBusy);
OpenLibraryCommand = new AsyncRelayCommand(async () =>
{
await _shell.Library.RefreshAsync();
_shell.Navigate(SectionKey.Library);
});
}
public ImportOutcome Outcome { get; }
public CardActions Actions
{
get => _actions;
private set
{
_actions = value;
OnAllPropertiesChanged();
CommandManager.InvalidateRequerySuggested();
}
}
public ICommand CheckCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand FormatCommand { get; }
public ICommand EjectCommand { get; }
public ICommand OpenLibraryCommand { get; }
/// <summary>"4,812 copied and verified", "4,800 copied · 12 failed".</summary>
public string ResultText => Outcome.IsComplete
? Loc.Plural(Outcome.Verified ? "Import.Result.Verified" : "Import.Result.Copied", Outcome.Imported)
: Loc.L("Import.Result.Partial", Formatting.Count(Outcome.Imported), Formatting.Count(Outcome.Failures.Count));
/// <summary>"12 skipped · 3 already there", or empty.</summary>
public string DetailText => string.Join(" · ", new[]
{
Outcome.Skipped > 0 ? Loc.Plural("Import.Result.Skipped", Outcome.Skipped) : string.Empty,
Outcome.Duplicates > 0 ? Loc.Plural("Import.Result.AlreadyThere", Outcome.Duplicates) : string.Empty,
}.Where(t => t.Length > 0));
public bool IsComplete => Outcome.IsComplete;
public StatusKind ResultKind => Outcome.IsComplete ? StatusKind.Done : StatusKind.Warning;
public IReadOnlyList<string> Failures { get; }
public bool HasFailures => Failures.Count > 0;
/// <summary>The profile chose "Delete imported": the dry run and the delete button are offered.</summary>
public bool OffersDelete => _choices.AfterImport == AfterImport.DeleteImported;
/// <summary>The profile chose "Format card".</summary>
public bool OffersFormat => _choices.AfterImport == AfterImport.FormatCard;
public bool OffersCheck => OffersDelete || OffersFormat;
public bool IsBusy
{
get => _isBusy;
private set
{
if (Set(ref _isBusy, value)) CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>"Checking 1,240 photos" while the dry run hashes.</summary>
public string? BusyText { get => _busyText; private set => Set(ref _busyText, value); }
public string EraseText => _actions.EraseText;
public IReadOnlyList<string> KeptReasons => _actions.KeptReasons;
public string CheckToolTip => _actions.CheckBlocker ?? Loc.L("Tooltips.Import.Check");
/// <summary>"Delete 4,812 photos…".</summary>
public string DeleteText => Loc.Plural("Import.Erase.Delete", _actions.DeleteCount);
public string DeleteToolTip => _actions.DeleteBlocker ?? Loc.L("Tooltips.Import.Delete");
public string FormatToolTip => _actions.FormatBlocker ?? Loc.L("Tooltips.Import.Format");
public string EjectToolTip => _actions.CanEject ? Loc.L("Tooltips.Import.Eject") : Loc.L("Import.Blocked.NotRemovable");
/// <summary>The card left or came back (Devices list); actions follow.</summary>
public void SetDevice(CardDevice? device)
{
_device = device;
Actions = _actions with { IsInserted = device is not null, IsRemovable = device?.IsRemovable == true };
}
/// <summary>Shows a dry run computed elsewhere (capture, tests).</summary>
public void ShowErase(ErasePlan erase, int cardPhotos) => Actions = _actions with { Erase = erase, CardPhotos = cardPhotos };
/// <summary>Ejects when the profile asks for it and nothing more is to be done on the card.</summary>
public async Task AutoEjectAsync()
{
if (_choices.Eject && _choices.AfterImport == AfterImport.Keep && Outcome.IsComplete && _actions.CanEject) await EjectAsync();
}
private async Task CheckAsync()
{
if (_shell.Services.Archives is not { } archives || _archive is null || _card is null || _device is null) return;
var root = _device.Root;
IsBusy = true;
try
{
var progress = new Progress<int>(n => BusyText = Loc.Plural("Import.Erase.Checking", n));
var (erase, photos) = await Task.Run(async () =>
{
var plan = await archives.PlanCardEraseAsync(_archive.Id, _card.Id, root, progress).ConfigureAwait(false);
return (plan, CardScanner.Find(root, includeSubfolders: true).Count);
});
ShowErase(erase, photos);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("import", "Card check failed", ex);
_shell.Notify(Loc.L("Import.Toast.CheckFailed"), ex.Message);
}
finally
{
BusyText = null;
IsBusy = false;
}
}
private async Task DeleteAsync()
{
if (_actions.Erase is not { } erase) return;
var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.Plural("Import.Confirm.DeleteHeading", _actions.DeleteCount),
Message = Loc.L("Import.Confirm.DeleteMessage"),
SafeText = Loc.L("Import.Confirm.Keep"),
SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
ActionText = Loc.L("Import.Confirm.Delete"),
ActionToolTip = Loc.L("Tooltips.Import.Delete"),
IsDestructive = true,
});
if (!confirmed) return;
IsBusy = true;
try
{
var result = await Task.Run(() => CardEraser.Execute(erase));
_shell.Notify(Loc.Plural("Import.Toast.Deleted", result.Deleted),
result.Kept.Count > 0 ? Loc.Plural("Import.Erase.Kept", result.Kept.Count) : null);
// The card changed: a new dry run is needed before anything else is deleted.
Actions = _actions with { Erase = null };
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", "Deleting imported photos failed", ex);
_shell.Notify(Loc.L("Import.Toast.DeleteFailed"), ex.Message);
}
finally
{
IsBusy = false;
}
if (_choices.Eject && _actions.CanEject) await EjectAsync();
}
private void Format()
{
if (_device is not { } device) return;
var name = _card?.Nickname ?? device.Label;
var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Import.Confirm.FormatHeading", name),
Message = Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount),
SafeText = Loc.L("Import.Confirm.Keep"),
SafeToolTip = Loc.L("Tooltips.Import.KeepCard"),
ActionText = Loc.L("Import.Confirm.Format"),
ActionToolTip = Loc.L("Tooltips.Import.FormatConfirm"),
IsDestructive = true,
TypedConfirmation = name,
TypedPrompt = Loc.L("Import.Confirm.TypeName"),
});
if (!confirmed) return;
var outcome = _shell.Services.Devices.Format(device);
if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null };
if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name));
}
private async Task EjectAsync()
{
if (_device is not { } device) return;
IsBusy = true;
try
{
var outcome = await Task.Run(() => _shell.Services.Devices.Eject(device));
_shell.Notify(Loc.L("Import.Toast.Eject." + outcome, _card?.Nickname ?? device.Label));
if (outcome == EjectOutcome.Ejected) SetDevice(null);
}
finally
{
IsBusy = false;
}
}
}
+49
View File
@@ -0,0 +1,49 @@
using Titano.App.Shell;
namespace Titano.App.Import;
/// <summary>
/// The Import states that <c>--capture</c> renders (<c>import-&lt;state&gt;-&lt;theme&gt;.png</c>) and the screen smoke
/// tests check, on the card of <see cref="SampleCards"/>: the card just inserted with its plan and sessions (and the
/// insertion toast), "Show plan", and the verification result with the after-import actions.
/// </summary>
public static class ImportScenes
{
public static readonly IReadOnlyList<string> States = ["plan", "showplan", "done"];
public static async Task ShowAsync(ShellViewModel shell, string state)
{
var import = shell.Import;
shell.Navigate(SectionKey.Import);
switch (state)
{
case "plan":
var card = SampleCards.Card(shell.Services.Environment.DataDirectory);
if (import.Result is not null) import.NewImportCommand.Execute(null);
import.CloseDetailsCommand.Execute(null);
await import.RefreshSourcesAsync();
import.SelectSource(card.Identity);
import.KeepCard = true;
await import.WaitForPlanAsync();
if (import.Sessions.Count > 0)
{
var sunset = import.Sessions[^1].Title;
sunset.Text = "Harbour sunset";
sunset.Commit();
}
await import.CardInsertedAsync(card);
break;
case "showplan":
import.ShowPlanCommand.Execute(null);
break;
case "done":
import.CloseDetailsCommand.Execute(null);
import.DeleteImported = true;
var plan = import.Plan ?? throw new InvalidOperationException("The sample card has no plan.");
import.ShowResult(SampleCards.Outcome(plan)).ShowErase(SampleCards.Erase(plan), plan.FileCount);
break;
default:
throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown Import state.");
}
}
}
@@ -0,0 +1,21 @@
using Titano.App.Settings;
using Titano.Core.Localization;
using Titano.Ui.Mvvm;
namespace Titano.App.Import;
/// <summary>A session of the plan with its editable title (the sequence title; empty keeps the folder name).</summary>
public sealed class ImportSessionRowViewModel : ObservableObject
{
public ImportSessionRowViewModel(PlanSessionRow row, Action<string, string> titleChanged)
{
Row = row;
Title = new EditableField(row.Title ?? string.Empty, _ => null, text => titleChanged(row.SessionKey, text), () => Loc.L("Tooltips.Import.SessionTitle"));
}
public PlanSessionRow Row { get; }
public EditableField Title { get; }
public string Placeholder => Row.DefaultTitle;
}
+173
View File
@@ -0,0 +1,173 @@
using System.IO;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Import;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Repositories;
namespace Titano.App.Import;
/// <summary>
/// Capture and smoke-test data ONLY (<c>--capture</c>, never the user's data): a simulated Canon EOS R5 card in the
/// capture folder — a night, a dawn and a sunset session of small JPEGs with Exif — remembered as "EOS R5 · card A",
/// a second remembered card that is not inserted, a USB drive without DCIM, and the import result shown afterwards.
/// </summary>
public static class SampleCards
{
private const uint Serial = 0x3F2A9C11;
private static readonly DateTimeOffset LastImport = new(2026, 9, 21, 19, 40, 0, TimeSpan.Zero);
/// <summary>Night, dawn and sunset: start, photos, seconds between photos.</summary>
private static readonly (DateTime Start, int Photos, int Interval)[] Sessions =
[
(new DateTime(2026, 9, 26, 21, 10, 0), 10, 120),
(new DateTime(2026, 9, 27, 5, 41, 0), 16, 4),
(new DateTime(2026, 9, 28, 18, 2, 11), 24, 2),
];
/// <summary>The inserted card: its root is a folder of the capture environment.</summary>
public static CardDevice Card(string dataDirectory) =>
new(Path.Combine(dataDirectory, "card") + Path.DirectorySeparatorChar, "EOS_DIGITAL", Serial, 127_865_454_592, 31_665_454_592, IsRemovable: true,
HasDcim: true);
/// <summary>Writes the card's photos, remembers both cards (the inserted one with its last import) and inserts the card and a USB drive.</summary>
public static async Task InsertAsync(TitanoDatabase db, SampleDeviceMonitor devices, string dataDirectory)
{
var card = Card(dataDirectory);
WritePhotos(card.Root);
var known = new MediaCard
{
Id = Guid.CreateVersion7(),
Identity = card.Identity,
VolumeSerial = card.SerialNumber,
Label = card.Label,
Capacity = card.TotalBytes,
Nickname = "EOS R5 · card A",
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
CameraSerial = "0431",
FirstSeen = LastImport.AddMonths(-7),
LastSeen = DateTimeOffset.UtcNow,
};
await db.MediaCards.UpsertAsync(known);
await db.MediaCards.RecordImportsAsync([new ImportRecord(known.Id, new ImportKey("DCIM/100CANON/IMG_9001.CR2", 24_000_000, LastImport), null, null, null,
LastImport)]);
await db.MediaCards.UpsertAsync(new MediaCard
{
Id = Guid.CreateVersion7(),
Identity = "7C1D0E42-GOPRO-63864569856",
VolumeSerial = 0x7C1D0E42,
Label = "GOPRO",
Capacity = 63_864_569_856,
Nickname = "GoPro 12",
CameraMake = "GoPro",
CameraModel = "HERO12 Black",
FirstSeen = LastImport.AddMonths(-3),
LastSeen = LastImport.AddDays(-6),
});
devices.Insert(card);
devices.Insert(new CardDevice(@"F:\", "USB DRIVE", 0x51E02B44, 2_000_398_934_016, 1_800_000_000_000, IsRemovable: true, HasDcim: false));
}
/// <summary>What the import of <paramref name="plan"/> reports: every planned copy committed and read back.</summary>
public static ImportOutcome Outcome(ImportPlan plan) => new(plan.CopyCount, 0, plan.FileCount - plan.CopyCount, [], Verified: true);
/// <summary>The dry run of "Delete imported" after that import: every copy matches except the last photo, touched since.</summary>
public static ErasePlan Erase(ImportPlan plan)
{
var copied = plan.Sessions.SelectMany(s => s.Items.Where(i => i.Action == ImportAction.Copy).Select(i => (Session: s, Item: i))).ToList();
return new ErasePlan(plan.SourceRoot,
[
.. copied.Select((c, n) => new EraseItem(
new EraseCandidate(c.Item.SourcePath, c.Item.Size, string.Empty,
Path.Combine(plan.DestinationRoot, c.Session.Folder, ArchiveLayout.OriginalsFolder, c.Item.FileName)),
n == copied.Count - 1 ? EraseVerdict.SourceChanged : EraseVerdict.Delete, c.Item.ModifiedUtc)),
]);
}
private static void WritePhotos(string root)
{
var folder = Path.Combine(root, "DCIM", "100CANON");
if (Directory.Exists(folder)) return;
Directory.CreateDirectory(folder);
var n = 1;
foreach (var (start, photos, interval) in Sessions)
{
for (var i = 0; i < photos; i++, n++)
{
var captured = start.AddSeconds(i * interval);
var path = Path.Combine(folder, $"IMG_{n:0000}.JPG");
File.WriteAllBytes(path, Photo(captured, n));
File.SetLastWriteTime(path, captured);
}
}
}
/// <summary>A small sky gradient with grain (distinct bytes per photo) and the camera's Exif.</summary>
private static byte[] Photo(DateTime captured, int seed)
{
const int Width = 96, Height = 64;
using var image = new ImageBuffer(Width, Height, 3, clear: false);
var random = new Random(seed);
var dusk = captured.Hour is >= 18 or < 6 ? 0.15f : 0.6f;
for (var y = 0; y < Height; y++)
{
for (var x = 0; x < Width; x++)
{
var sky = dusk * (1 - y / (float)Height) + 0.05f;
var grain = (float)random.NextDouble() * 0.04f;
image.Plane(0)[y * Width + x] = sky * 1.2f + grain;
image.Plane(1)[y * Width + x] = sky * 0.8f + grain;
image.Plane(2)[y * Width + x] = sky * 0.6f + grain;
}
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata
{
Make = "Canon",
Model = "Canon EOS R5",
BodySerial = "0431",
CapturedAt = captured,
Iso = 100,
ExposureTime = 1.0 / 250,
FNumber = 8,
});
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
}
/// <summary>The capture's device monitor: lists the sample volumes; it raises no events and never ejects or formats.</summary>
public sealed class SampleDeviceMonitor : IDeviceMonitor
{
private readonly List<CardDevice> _devices = [];
public event Action<CardDevice>? Arrived
{
add { }
remove { }
}
public event Action<CardDevice>? Removed
{
add { }
remove { }
}
public IReadOnlyList<CardDevice> Devices => [.. _devices];
public void Insert(CardDevice device) => _devices.Add(device);
public void Start()
{
}
public EjectOutcome Eject(CardDevice device) => EjectOutcome.Failed;
public FormatOutcome Format(CardDevice device) => FormatOutcome.Cancelled;
public void Dispose()
{
}
}