merge: card import and archive manager screens (card pool, plan, verified erase and format, server destination, tree, charts, maintenance)

Union of the Tooltips resources; sample data keeps the sync server and the
simulated cards; the import test names App.Infrastructure.Formatting fully now
that a test namespace of the same name exists.

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-03 11:01:34 +00:00
commit 828c64a485
57 files changed
+8742 -23

No files matched your search

@@ -0,0 +1,366 @@
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. While its action runs, the way out
/// stops it when it can be stopped, and is disabled otherwise; the close callback receives the dialog, so a late close
/// never closes another one.
/// </summary>
public abstract class ArchiveDialogViewModel : LocalizedViewModel
{
private readonly Action<ArchiveDialogViewModel> _close;
private bool _isBusy;
private string? _busyText;
protected ArchiveDialogViewModel(Action<ArchiveDialogViewModel> close)
{
_close = close;
CloseCommand = new RelayCommand(() =>
{
if (IsBusy) Stop();
else Close();
}, () => !IsBusy || CanStop);
}
/// <summary>Cancel: closes the dialog, or stops its running action.</summary>
public ICommand CloseCommand { get; }
public string CloseToolTip => !IsBusy ? Loc.L("Tooltips.Archive.CloseDialog")
: CanStop ? Loc.L("Tooltips.Archive.StopApply")
: Loc.L("Archive.Blocked.Applying");
/// <summary>The running action can stop between two steps.</summary>
protected virtual bool CanStop => false;
protected virtual void Stop()
{
}
public bool IsBusy
{
get => _isBusy;
protected set
{
if (!Set(ref _isBusy, value)) return;
OnPropertyChanged(nameof(CloseToolTip));
CommandManager.InvalidateRequerySuggested();
}
}
public string? BusyText { get => _busyText; protected set => Set(ref _busyText, value); }
protected void Close() => _close(this);
}
/// <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<ArchiveDialogViewModel> 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<ArchiveDialogViewModel> 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, () => ApplyBlocker is null);
}
/// <summary>Why Apply is disabled; null when it can run.</summary>
private string? ApplyBlocker =>
IsBusy ? Loc.L("Archive.Blocked.Applying")
: Template.Error is { } error ? error
: _plan is null ? Loc.L("Archive.Blocked.Planning")
: _plan.Steps.Count == 0 ? Loc.L("Archive.Blocked.NoChanges")
: null;
public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RenameApply");
public RenameMode Mode { get; }
public string Heading => Loc.Plural(Mode == RenameMode.Folders ? "Archive.Rename.MoveHeading" : "Archive.Rename.Heading", _set.Count);
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; }
public override void Dispose()
{
_delay.Stop();
_planning?.Cancel();
base.Dispose();
}
/// <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));
OnPropertyChanged(nameof(ApplyToolTip));
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));
OnPropertyChanged(nameof(ApplyToolTip));
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));
Log.Info("archive", $"{Mode} applied to {plan.Steps.Count} sequence(s)");
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;
private CancellationTokenSource? _run;
public RetagDialogViewModel(ArchiveService archives, IReadOnlyList<Sequence> set, Func<int, Task> applied, Action<ArchiveDialogViewModel> 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 += (_, _) => OnTagsTyped();
Remove.PropertyChanged += (_, _) => OnTagsTyped();
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
}
/// <summary>Why Apply is disabled; null when it can run.</summary>
private string? ApplyBlocker =>
IsBusy ? Loc.L("Archive.Blocked.Applying")
: Add.Error ?? Remove.Error
?? (Changes().Count == 0 ? Loc.L("Archive.Blocked.NoChanges") : null);
public string ApplyToolTip => ApplyBlocker ?? Loc.L("Tooltips.Archive.RetagApply");
public string Heading => Loc.Plural("Archive.Retag.Heading", _set.Count);
public EditableField Add { get; }
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; }
/// <summary>Typing changes the dry run, and with it whether Apply can run.</summary>
private void OnTagsTyped()
{
OnPropertyChanged(nameof(SummaryText));
OnPropertyChanged(nameof(ApplyToolTip));
CommandManager.InvalidateRequerySuggested();
}
private IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> Tags)> Changes() =>
Add.HasErrors || Remove.HasErrors ? [] : Retag.Changes(_set, Retag.Parse(Add.Text), Retag.Parse(Remove.Text));
protected override bool CanStop => _run is not null;
/// <summary>Stops after the sequence being written; each sequence is changed completely or not at all.</summary>
protected override void Stop() => _run?.Cancel();
private async Task ApplyAsync()
{
var changes = Changes();
var run = _run = new CancellationTokenSource();
var done = 0;
IsBusy = true;
try
{
for (; done < changes.Count && !run.IsCancellationRequested; done++)
{
var (s, tags) = changes[done];
BusyText = Loc.L("Archive.Rename.Applying", Formatting.Count(done + 1), Formatting.Count(changes.Count));
await Task.Run(() => _archives.SetSequenceInfoAsync(s.Id, s.Title, tags, s.Rating, s.Notes));
}
Log.Info("archive", $"Retag: {done} of {changes.Count} sequence(s) changed");
await _applied(done);
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
{
_run = null;
run.Dispose();
IsBusy = false;
}
}
}
+168
View File
@@ -0,0 +1,168 @@
using System.Globalization;
using Titano.App.Infrastructure;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Naming;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>A bar of a chart: label, magnitude, the text after the bar and the hover text.</summary>
public sealed record BarValue(string Label, double Value, string ValueText, string ToolTip);
/// <summary>A heatmap row (one year): photos per month, NaN for months still to come.</summary>
public sealed record HeatRow(string Label, IReadOnlyList<double> Values, IReadOnlyList<string?> ToolTips);
/// <summary>A figure tile of the Archive screen ("618,204" over "photos").</summary>
public sealed record ArchiveTile(string Value, string Caption);
public enum HealthAction
{
None,
Verify,
Proxies,
Analyse,
Duplicates,
Orphans,
}
/// <summary>One line of "Index health": ok or warning, what it found, and the fix it offers.</summary>
public sealed record HealthLine(bool IsOk, string Text, HealthAction Action);
/// <summary>
/// Turns the index statistics into the Archive screen's figures (BRIEF §12.5, Archive.html): tiles, photos per month
/// (heatmap, year rows × 12 months), storage by year, the top cameras and formats by photos (the rest folded into one
/// bar), and the index health lines.
/// </summary>
public static class ArchiveFigures
{
public const int TopCameras = 5;
public const int TopFormats = 6;
public static IReadOnlyList<ArchiveTile> Tiles(ArchiveStats stats)
{
var years = stats.ByYear.Select(y => y.Year).ToList();
var range = years.Count == 0 ? "—"
: years.Min() == years.Max() ? Year(years.Min())
: Loc.L("Archive.Tile.YearRange", Year(years.Min()), Year(years.Max()));
var cameras = stats.ByCamera.Count(c => !string.IsNullOrWhiteSpace(c.Model) || !string.IsNullOrWhiteSpace(c.Make));
return
[
new(Formatting.Count(stats.Photos), Loc.Plural("Archive.Tile.Photos", stats.Photos)),
new(Formatting.Count(stats.Sequences), Loc.Plural("Archive.Tile.Sequences", stats.Sequences)),
new(Formatting.Bytes(stats.Bytes), Loc.L("Archive.Tile.Originals")),
new(Formatting.Count(cameras), Loc.Plural("Archive.Tile.Cameras", cameras) + " · " + Loc.Plural("Archive.Tile.Formats", stats.ByFormat.Count)),
new(range, Loc.L("Archive.Tile.Pending", Formatting.Count(stats.Health.NotAnalyzed), Formatting.Count(stats.Health.Unverified))),
];
}
/// <summary>Culture month initials for the heatmap columns ("J F M …", "G F M …").</summary>
public static IReadOnlyList<string> MonthLabels() =>
[.. Loc.Culture.DateTimeFormat.AbbreviatedMonthNames.Take(12).Select(m => m.Length == 0 ? string.Empty : char.ToUpper(m[0], Loc.Culture).ToString())];
/// <summary>One row per year from the first to the last with photos, oldest first; months after <paramref name="today"/> are NaN.</summary>
public static IReadOnlyList<HeatRow> PhotosPerMonth(ArchiveStats stats, DateTime today)
{
if (stats.ByMonth.Count == 0) return [];
var byKey = stats.ByMonth.ToDictionary(m => (m.Year, m.Month));
var first = stats.ByMonth.Min(m => m.Year);
var last = System.Math.Max(stats.ByMonth.Max(m => m.Year), first);
var rows = new List<HeatRow>(last - first + 1);
for (var year = first; year <= last; year++)
{
var values = new double[12];
var tips = new string?[12];
for (var month = 1; month <= 12; month++)
{
var future = year > today.Year || (year == today.Year && month > today.Month);
byKey.TryGetValue((year, month), out var bucket);
values[month - 1] = future ? double.NaN : bucket?.Photos ?? 0;
tips[month - 1] = future ? null : Loc.L("Archive.Chart.MonthTip", new DateTime(year, month, 1).ToString("Y", Loc.Culture),
Loc.Plural("Shell.Status.Photos", bucket?.Photos ?? 0), Loc.Plural("Shell.Status.Sequences", bucket?.Sequences ?? 0));
}
rows.Add(new HeatRow(Year(year), values, tips));
}
return rows;
}
/// <summary>Bytes of originals per capture year, oldest first.</summary>
public static IReadOnlyList<BarValue> StorageByYear(ArchiveStats stats) =>
[
.. stats.ByYear.OrderBy(y => y.Year).Select(y => new BarValue(Year(y.Year), y.Bytes, Formatting.Bytes(y.Bytes),
Loc.L("Archive.Chart.YearTip", Year(y.Year), Formatting.Bytes(y.Bytes), Loc.Plural("Shell.Status.Sequences", y.Sequences)))),
];
/// <summary>Photos per camera: the <see cref="TopCameras"/> largest, then "n others".</summary>
public static IReadOnlyList<BarValue> ByCamera(ArchiveStats stats)
{
var cameras = stats.ByCamera
.GroupBy(c => PathTemplate.CameraName(c.Make, c.Model) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera"), StringComparer.Ordinal)
.Select(g => (Name: g.Key, Photos: g.Sum(c => c.Photos)))
.OrderByDescending(c => c.Photos).ThenBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase)
.ToList();
return Shares(cameras, TopCameras, rest => Loc.Plural("Archive.Chart.OtherCameras", rest), stats.Photos);
}
/// <summary>Photos per file format: the <see cref="TopFormats"/> largest, then "Other".</summary>
public static IReadOnlyList<BarValue> ByFormat(ArchiveStats stats)
{
var formats = stats.ByFormat
.GroupBy(f => FormatName(f.Format), StringComparer.Ordinal)
.Select(g => (Name: g.Key, Photos: g.Sum(f => f.Photos)))
.OrderByDescending(f => f.Photos).ThenBy(f => f.Name, StringComparer.Ordinal)
.ToList();
return Shares(formats, TopFormats, _ => Loc.L("Archive.Chart.OtherFormats"), formats.Sum(f => f.Photos));
}
/// <summary>"CR2", "JPEG", "3FR": the format as photographers name it.</summary>
public static string FormatName(ImageFileFormat format) => format switch
{
ImageFileFormat.Unknown => Loc.L("Archive.Chart.OtherFormats"),
ImageFileFormat.ThreeFr => "3FR",
ImageFileFormat.JpegXl => "JXL",
ImageFileFormat.JpegXr => "JXR",
ImageFileFormat.WebP => "WebP",
_ => format.ToString().ToUpperInvariant(),
};
/// <summary>Index health (Archive.html): what needs attention, each with its fix.</summary>
public static IReadOnlyList<HealthLine> Health(ArchiveStats stats, int withoutProxies)
{
var h = stats.Health;
var damaged = h.MissingFrames + h.CorruptFrames;
return
[
h.Unverified == 0
? new HealthLine(true, Loc.L("Archive.Health.AllVerified"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.Unverified", h.Unverified), HealthAction.Verify),
damaged == 0
? new HealthLine(true, Loc.L("Archive.Health.FramesOk"), HealthAction.None)
: new HealthLine(false, Loc.L("Archive.Health.Damaged", Formatting.Count(h.MissingFrames), Formatting.Count(h.CorruptFrames)), HealthAction.Orphans),
withoutProxies == 0
? new HealthLine(true, Loc.L("Archive.Health.ProxiesOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NoProxies", withoutProxies), HealthAction.Proxies),
h.NotAnalyzed == 0
? new HealthLine(true, Loc.L("Archive.Health.AnalysedOk"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.NotAnalysed", h.NotAnalyzed), HealthAction.Analyse),
h.DuplicateFrames == 0
? new HealthLine(true, Loc.L("Archive.Health.NoDuplicates"), HealthAction.None)
: new HealthLine(false, Loc.Plural("Archive.Health.Duplicates", h.DuplicateFrames), HealthAction.Duplicates),
];
}
private static IReadOnlyList<BarValue> Shares(List<(string Name, long Photos)> ranked, int top, Func<int, string> restLabel, long total)
{
var bars = new List<BarValue>(top + 1);
foreach (var (name, photos) in ranked.Take(top)) bars.Add(Bar(name, photos, total));
if (ranked.Count > top) bars.Add(Bar(restLabel(ranked.Count - top), ranked.Skip(top).Sum(c => c.Photos), total));
return bars;
}
private static BarValue Bar(string label, long photos, long total)
{
var share = Formatting.Percent(total > 0 ? photos / (double)total : 0);
return new BarValue(label, photos, share, Loc.L("Archive.Chart.ShareTip", label, Loc.Plural("Shell.Status.Photos", photos), share));
}
private static string Year(int year) => year.ToString(CultureInfo.InvariantCulture);
}
@@ -0,0 +1,79 @@
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");
/// <summary>The row's figures; a year also says how the keyboard opens and closes it.</summary>
public string RowToolTip => IsYear ? Loc.L("Tooltips.Archive.YearRow", Detail) : Detail;
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);
}
/// <summary>A value of a set filter menu (camera, status, tag): checked while chosen; choosing it again clears it.</summary>
public sealed record FilterChoice(string Label, bool IsChecked, ICommand Command);
+48
View File
@@ -0,0 +1,48 @@
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, the
/// rebuild dialog, and the Move dialog with its dry run.
/// </summary>
public static class ArchiveScenes
{
public static readonly IReadOnlyList<string> Views = ["overview", "maintenance", "rebuild", "move"];
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;
case "move":
archive.ViewIndex = 0;
await archive.OpenRenameDialogAsync(RenameMode.Folders);
if (archive.Dialog is RenameDialogViewModel move)
{
move.Template.Text = "{year}/{date} {title}";
await move.PlanAsync();
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(view), view, "Unknown Archive view.");
}
}
}
+130
View File
@@ -0,0 +1,130 @@
using System.Globalization;
using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
namespace Titano.App.Archiving;
public enum TreeNodeKind
{
Archive,
Year,
Sequence,
}
/// <summary>A node of the archive tree: the archive, a capture year, or a sequence.</summary>
public sealed class ArchiveTreeNode
{
private readonly List<ArchiveTreeNode> _children = [];
internal ArchiveTreeNode(TreeNodeKind kind, string key, int depth)
{
Kind = kind;
Key = key;
Depth = depth;
}
public TreeNodeKind Kind { get; }
/// <summary>Stable across rebuilds: the archive id, the year, or the sequence id.</summary>
public string Key { get; }
public int Depth { get; }
public required string Title { get; init; }
/// <summary>"18 sequences · 2.1 TB", "3,600 photos · 72 GB".</summary>
public required string Detail { get; init; }
public Sequence? Sequence { get; init; }
public bool IsExpanded { get; set; }
public IReadOnlyList<ArchiveTreeNode> Children => _children;
public bool HasChildren => _children.Count > 0;
internal void Add(ArchiveTreeNode child) => _children.Add(child);
/// <summary>The sequences this node stands for (itself, or all below it).</summary>
public IEnumerable<Sequence> Sequences() => Sequence is { } own ? [own] : _children.SelectMany(c => c.Sequences());
}
/// <summary>
/// The Archive screen's tree (BRIEF §12.5): the archive with its availability, its capture years (newest first) and
/// their sequences (newest first), flattened into the visible rows of a virtualised list. Undated sequences sit under
/// their own node after the years.
/// </summary>
public sealed class ArchiveTree
{
private ArchiveTree(ArchiveTreeNode root, ArchiveAvailability availability)
{
Root = root;
Availability = availability;
}
public ArchiveTreeNode Root { get; }
public ArchiveAvailability Availability { get; }
public static ArchiveTree Build(Core.Model.Archive archive, ArchiveAvailability availability, IReadOnlyList<Sequence> sequences)
{
var root = new ArchiveTreeNode(TreeNodeKind.Archive, archive.Id.ToString("N"), 0)
{
Title = archive.Name,
Detail = Summary(sequences),
IsExpanded = true,
};
foreach (var year in sequences.GroupBy(s => s.FirstCapture?.Year).OrderByDescending(g => g.Key ?? int.MinValue))
{
var members = year.OrderByDescending(s => s.FirstCapture).ThenBy(s => s.DisplayTitle, StringComparer.CurrentCultureIgnoreCase).ToList();
var node = new ArchiveTreeNode(TreeNodeKind.Year, year.Key?.ToString(CultureInfo.InvariantCulture) ?? "undated", 1)
{
Title = year.Key?.ToString(CultureInfo.InvariantCulture) ?? Loc.L("Archive.Tree.Undated"),
Detail = Summary(members),
};
foreach (var s in members)
{
node.Add(new ArchiveTreeNode(TreeNodeKind.Sequence, s.Id.ToString("N"), 2)
{
Title = s.DisplayTitle,
Detail = Loc.Plural("Shell.Status.Photos", s.FrameCount) + " · " + Formatting.Bytes(s.TotalBytes),
Sequence = s,
});
}
root.Add(node);
}
return new ArchiveTree(root, availability);
}
/// <summary>Rows to show: every node whose ancestors are all expanded, depth first.</summary>
public IReadOnlyList<ArchiveTreeNode> Visible()
{
var rows = new List<ArchiveTreeNode>();
void Walk(ArchiveTreeNode node)
{
rows.Add(node);
if (!node.IsExpanded) return;
foreach (var child in node.Children) Walk(child);
}
Walk(Root);
return rows;
}
/// <summary>Expands the nodes whose keys are given (restoring the state after a refresh).</summary>
public void Expand(IReadOnlySet<string> keys)
{
foreach (var year in Root.Children) year.IsExpanded = keys.Contains(year.Key);
}
/// <summary>Keys of the expanded year nodes.</summary>
public IReadOnlySet<string> ExpandedKeys() => Root.Children.Where(c => c.IsExpanded).Select(c => c.Key).ToHashSet(StringComparer.Ordinal);
/// <summary>The set mass operations act on: the sequences of the selected nodes, each once; all of them when nothing is selected.</summary>
public static IReadOnlyList<Sequence> SetOf(ArchiveTree tree, IEnumerable<ArchiveTreeNode> selected)
{
var chosen = selected.ToList();
var source = chosen.Count == 0 ? tree.Root.Sequences() : chosen.SelectMany(n => n.Sequences());
var seen = new HashSet<Guid>();
return [.. source.Where(s => seen.Add(s.Id))];
}
private static string Summary(IReadOnlyCollection<Sequence> sequences) =>
Loc.Plural("Shell.Status.Sequences", sequences.Count) + " · " + Formatting.Bytes(sequences.Sum(s => s.TotalBytes));
}
+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;
}
}
}
@@ -0,0 +1,93 @@
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>A group of identical photos: the copies and where they are; the first one counts as the original.</summary>
public sealed record DuplicateRow(string Title, string Detail, IReadOnlyList<string> Places, Guid SequenceId);
/// <summary>What an orphan line is about, which decides its fix.</summary>
public enum OrphanKind
{
/// <summary>Photos in a sequence folder that its sidecar does not list: fix = index them.</summary>
UnlistedFiles,
/// <summary>Frames whose file is gone: fix = reconcile (flags them missing in sidecar and index).</summary>
MissingFiles,
/// <summary>An index row whose folder has no sidecar any more: fix = remove the row (after confirmation).</summary>
MissingSequence,
/// <summary>A folder with photos the index does not know yet: fix = scan.</summary>
NewFolder,
}
/// <summary>One line of the orphans report and the target of its fix.</summary>
public sealed record OrphanRow(OrphanKind Kind, string Title, string Detail, Guid? SequenceId);
/// <summary>A line of "Recent maintenance": date, operation and outcome.</summary>
public sealed record MaintenanceRow(Guid JobId, string DateText, string Text, string StateText, JobState State);
/// <summary>
/// The Maintenance view's reports (BRIEF §12.5): duplicates across sequences, orphans with their safe fixes, and the
/// recent archive jobs. Nothing here deletes a file; the only removal is of index rows whose sidecar is gone.
/// </summary>
public static class MaintenanceReports
{
/// <summary>Kinds of jobs listed under "Recent maintenance".</summary>
public static readonly IReadOnlyList<JobKind> MaintenanceKinds = [JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.Maintenance];
public static IReadOnlyList<DuplicateRow> Duplicates(IReadOnlyList<DuplicateGroup> groups, IReadOnlyList<SequenceLocation> locations)
{
var titles = locations.ToDictionary(l => l.Id, l => l.Title ?? l.Folder[(l.Folder.LastIndexOf('/') + 1)..]);
return
[
.. groups.Where(g => g.Frames.Count > 1).Select(g =>
{
var first = g.Frames[0];
var name = first.RelativePath[(first.RelativePath.LastIndexOf('/') + 1)..];
var places = g.Frames.Select(f => Loc.L("Archive.Duplicates.Place", titles.GetValueOrDefault(f.SequenceId, f.RelativePath), f.RelativePath)).ToList();
return new DuplicateRow(name, Loc.Plural("Archive.Duplicates.Copies", g.Frames.Count), places, first.SequenceId);
}),
];
}
public static IReadOnlyList<OrphanRow> Orphans(OrphanReport report, IReadOnlyList<SequenceLocation> locations)
{
var byFolder = locations.ToDictionary(l => l.Folder, StringComparer.Ordinal);
var rows = new List<OrphanRow>();
foreach (var s in report.Sequences)
{
byFolder.TryGetValue(s.Folder, out var location);
var title = location?.Title ?? s.Folder;
if (s.UnindexedFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.UnlistedFiles, title, Loc.Plural("Archive.Orphans.Unlisted", s.UnindexedFiles.Count), location?.Id));
if (s.MissingFiles.Count > 0)
rows.Add(new OrphanRow(OrphanKind.MissingFiles, title, Loc.Plural("Archive.Orphans.Missing", s.MissingFiles.Count), location?.Id));
}
foreach (var missing in report.MissingSequences)
rows.Add(new OrphanRow(OrphanKind.MissingSequence, missing.Title ?? missing.Folder, Loc.L("Archive.Orphans.NoSidecar", missing.Folder), missing.Id));
foreach (var folder in report.UnindexedFolders)
rows.Add(new OrphanRow(OrphanKind.NewFolder, folder.Length == 0 ? "/" : folder, Loc.L("Archive.Orphans.NewFolder"), null));
return rows;
}
public static IReadOnlyList<MaintenanceRow> Recent(IEnumerable<Job> jobs, int count) =>
[
.. jobs.OrderByDescending(j => j.Finished ?? j.Started ?? j.Created).Take(count).Select(j =>
{
var when = j.Finished ?? j.Started ?? j.Created;
var text = string.IsNullOrWhiteSpace(j.TargetLabel) ? JobText.Kind(j.Kind) : Loc.L("Archive.Recent.Line", JobText.Kind(j.Kind), j.TargetLabel);
var state = j.State switch
{
JobState.Running when j.ProgressTotal > 0 => Formatting.Percent(j.ProgressDone / (double)j.ProgressTotal),
_ => Loc.L("Jobs.State." + j.State),
};
return new MaintenanceRow(j.Id, Formatting.Date(when), text, state, j.State);
}),
];
}
+114
View File
@@ -0,0 +1,114 @@
using Titano.App.Library;
using Titano.App.Settings;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data.Repositories;
namespace Titano.App.Archiving;
/// <summary>What a mass rename changes: the sequence titles (Rename) or the folder layout (Move).</summary>
public enum RenameMode
{
Titles,
Folders,
}
/// <summary>One line of the rename dry run: before → after.</summary>
public sealed record RenameRow(Guid SequenceId, string From, string To);
/// <summary>
/// Mass rename and move of sequences (BRIEF §7, §12.5): the template is checked live, the engine's dry run
/// (<see cref="RenamePlan"/>) is listed line by line, and applying makes exactly those changes.
/// </summary>
public static class MassRename
{
/// <summary>The first problem of a template, localized; null when it can be used.</summary>
public static string? Validate(RenameMode mode, string? template)
{
if (string.IsNullOrWhiteSpace(template)) return Loc.L("Errors.Template.Empty", string.Empty, 1);
if (mode == RenameMode.Folders) return NamingPreview.Validate(template, isFolder: true);
var parsed = PathTemplate.Parse(template);
return parsed.Errors is [var error, ..] ? Loc.L("Errors.Template." + error.Code, error.Token ?? string.Empty, error.Position + 1) : null;
}
/// <summary>The changes of a plan as rows: titles or folders, whichever the mode changes.</summary>
public static IReadOnlyList<RenameRow> Rows(RenamePlan plan, RenameMode mode) =>
[
.. plan.Steps.Select(s => mode == RenameMode.Folders
? new RenameRow(s.SequenceId, s.FromFolder, s.ToFolder)
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
];
/// <summary>"12 of 36 sequences change".</summary>
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count, setSize);
}
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
public static class Retag
{
/// <summary>"sunset, harbour; Holy grail" → normalized, distinct tags; entries that cannot be tags are left out.</summary>
public static IReadOnlyList<string> Parse(string? text)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return [.. Split(text).Where(IsValid).Select(TagRepository.Normalize).Where(seen.Add)];
}
/// <summary>The problem of a tag list as one sentence; null when every entry can be a tag.</summary>
public static string? Validate(string? text) => Split(text).All(IsValid) ? null : Loc.L("Archive.Retag.Invalid", TagRepository.MaxLength);
private static IEnumerable<string> Split(string? text) =>
string.IsNullOrWhiteSpace(text) ? [] : text.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private static bool IsValid(string tag) => tag.Length is > 0 and <= TagRepository.MaxLength && !tag.Any(char.IsControl);
/// <summary>The new tag list of one sequence: removals first, then additions not already present.</summary>
public static IReadOnlyList<string> Apply(IReadOnlyList<string> current, IReadOnlyList<string> add, IReadOnlyList<string> remove)
{
var removed = new HashSet<string>(remove, StringComparer.OrdinalIgnoreCase);
var result = current.Where(t => !removed.Contains(t)).ToList();
var present = new HashSet<string>(result, StringComparer.OrdinalIgnoreCase);
result.AddRange(add.Where(present.Add));
return result;
}
/// <summary>Only the sequences whose tags change, with their new tags (the dry run).</summary>
public static IReadOnlyList<(Sequence Sequence, IReadOnlyList<string> Tags)> Changes(IEnumerable<Sequence> sequences, IReadOnlyList<string> add,
IReadOnlyList<string> remove) =>
[
.. sequences.Select(s => (Sequence: s, Tags: Apply(s.Tags, add, remove)))
.Where(c => !c.Tags.SequenceEqual(c.Sequence.Tags, StringComparer.Ordinal)),
];
}
/// <summary>
/// Narrows the mass-operation set on top of the tree selection (Archive.html "Filtered set ▾"): camera, status and tag;
/// years and single sequences are chosen in the tree.
/// </summary>
public sealed record ArchiveSetFilter(string? Camera = null, StatusFilter Status = StatusFilter.Any, string? Tag = null)
{
public bool IsEmpty => Camera is null && Status == StatusFilter.Any && Tag is null;
public bool Matches(Sequence sequence)
{
if (Camera is not null && CameraOf(sequence) != Camera) return false;
if (Tag is not null && !sequence.Tags.Contains(Tag, StringComparer.OrdinalIgnoreCase)) return false;
var (with, without) = LibraryFilter.Flags(Status);
return (sequence.Status & with) == with && (sequence.Status & without) == 0;
}
/// <summary>"Canon EOS R5 · Not analysed · sunset"; empty without a filter.</summary>
public string Describe() => string.Join(" · ", new[]
{
Camera ?? string.Empty,
Status == StatusFilter.Any ? string.Empty : StatusLabel(Status),
Tag ?? string.Empty,
}.Where(t => t.Length > 0));
/// <summary>The camera a sequence is filed under, as the camera chart names it.</summary>
public static string CameraOf(Sequence sequence) =>
PathTemplate.CameraName(sequence.CameraMake, sequence.CameraModel) is { Length: > 0 } name ? name : Loc.L("Archive.Chart.UnknownCamera");
public static string StatusLabel(StatusFilter status) => Loc.L(status == StatusFilter.Any ? "Library.Filter.AnyStatus" : "Library.Filter.Status." + status);
}
+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))];
}
}
+7
View File
@@ -2,6 +2,7 @@ using System.IO;
using System.Net;
using Titano.App.About;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Infrastructure;
using Titano.App.Server;
using Titano.App.Settings;
@@ -56,6 +57,8 @@ public sealed class SampleData
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
services.Encoders = new SampleEncoders();
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
services.Devices.Dispose();
services.Devices = new SampleDeviceMonitor();
var sample = new SampleData(services);
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
return sample;
@@ -77,6 +80,9 @@ public sealed class SampleData
Directory.CreateDirectory(root);
var archive = new Archive { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) };
await db.Archives.UpsertAsync(archive);
var paths = new ArchivePaths(root);
Directory.CreateDirectory(paths.MetaDirectory);
ManifestStore.WriteArchive(paths.ManifestPath, new ArchiveManifest { Id = archive.Id, Name = archive.Name, Created = archive.Created });
var sequences = Sequences(archive.Id).ToList();
foreach (var (sequence, colours, raw) in sequences)
@@ -89,6 +95,7 @@ public sealed class SampleData
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
settings.LastArchivePath = @"D:\TitanoArchive";
settings.ServerUrl = "https://nas.local:8443";
@@ -0,0 +1,47 @@
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Data;
namespace Titano.App.Import;
/// <summary>
/// The verification result of an archive import job (BRIEF §12.4): every planned copy matched to its own committed frame,
/// and the job's own error text for the copies that did not arrive.
/// </summary>
public static class ArchiveImportCheck
{
/// <param name="cardId">The card the job recorded its history for; null for a folder source.</param>
public static async Task<ImportOutcome> CheckAsync(TitanoDatabase db, Guid archiveId, ImportPlan plan, Job job, Guid? cardId, bool verified,
CancellationToken cancellationToken)
{
var errors = ImportOutcome.JobErrors(job.LogTail);
if (cardId is { } card)
{
// A card import records each committed file with the job and its frame.
var records = (await db.MediaCards.ListImportsByJobAsync(card, job.Id, cancellationToken).ConfigureAwait(false))
.Where(r => r.FrameId is not null)
.ToDictionary(r => (r.Key.Path, r.Key.Size));
return await ImportOutcome.CheckAsync(plan, verified, (item, _) => Task.FromResult(
!records.TryGetValue((item.SourcePath, item.Size), out var record) ? CommitCheck.Missing
: record.FrameId == item.ExistingFrameId ? CommitCheck.AlreadyThere
: CommitCheck.Copied), errors, cancellationToken).ConfigureAwait(false);
}
// A folder has no import history: the copy is a frame of its session's sequence with the photo's size, capture time
// and (when the plan hashed it) content, other than the frame it duplicates.
var sessionOf = plan.Sessions.SelectMany(s => s.Items.Select(i => (i.SourcePath, s.SessionKey))).ToDictionary(x => x.SourcePath, x => x.SessionKey);
var sequences = new Dictionary<string, Guid?>(StringComparer.Ordinal);
return await ImportOutcome.CheckAsync(plan, verified, async (item, ct) =>
{
var key = sessionOf[item.SourcePath];
if (!sequences.TryGetValue(key, out var sequence))
sequences[key] = sequence = await db.Sequences.FindBySessionKeyAsync(archiveId, key, ct).ConfigureAwait(false);
var matches = (await db.Frames.FindBySizeAndCaptureAsync(archiveId, item.Size, item.CapturedAt, ct).ConfigureAwait(false))
.Where(f => f.SequenceId == sequence && (item.Sha256 is null || string.Equals(f.Sha256, item.Sha256, StringComparison.OrdinalIgnoreCase)))
.ToList();
return matches.Any(f => f.Id != item.ExistingFrameId) ? CommitCheck.Copied
: matches.Count > 0 ? CommitCheck.AlreadyThere
: CommitCheck.Missing;
}, errors, cancellationToken).ConfigureAwait(false);
}
}
+57
View File
@@ -0,0 +1,57 @@
using System.Text.Json.Serialization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
namespace Titano.App.Import;
/// <summary>
/// A camera profile (BRIEF §13): import settings shared by every card of one camera model. The cards in
/// <see cref="Cards"/> follow it: they import with these settings, and an import started from any of them saves its
/// settings here for all of them.
/// </summary>
public sealed record CameraProfile(string? Make, string Model, CardProfile Profile, IReadOnlyList<Guid> Cards)
{
public bool Follows(Guid cardId) => Cards.Contains(cardId);
public CameraProfile With(Guid cardId) => Follows(cardId) ? this : this with { Cards = [.. Cards, cardId] };
public CameraProfile Without(Guid cardId) => this with { Cards = [.. Cards.Where(c => c != cardId)] };
}
/// <summary>The settings a card imports with, and whether they are its camera's shared profile.</summary>
public sealed record ResolvedProfile(CardProfile Profile, bool FollowsCamera);
public static class CameraProfiles
{
/// <summary>
/// A card follows its camera's profile when it joined it, or when it has no settings of its own yet (a new card for a
/// known camera needs no setup, and joins); otherwise it keeps its own settings, and a card without any starts from
/// <paramref name="defaults"/>.
/// </summary>
public static ResolvedProfile Resolve(MediaCard card, CameraProfile? camera, CardProfile defaults) =>
camera is not null && (camera.Follows(card.Id) || card.ProfileJson is not { Length: > 0 })
? new ResolvedProfile(camera.Profile, true)
: new ResolvedProfile(card.ProfileJson is { Length: > 0 } ? ImportService.ProfileOf(card) : defaults, false);
}
/// <summary>Camera profiles in the index's application settings, one per camera model.</summary>
public sealed class CameraProfileStore(TitanoDatabase db)
{
private const string KeyPrefix = "import.cameraProfile.";
/// <summary>The profile of a camera; null when the camera is unknown or has none.</summary>
public async Task<CameraProfile?> FindAsync(string? make, string? model, CancellationToken cancellationToken = default) =>
model is null ? null : await db.Settings.GetAsync(SettingScope.App, null, Key(make, model), CameraProfileJson.Default.CameraProfile, cancellationToken)
.ConfigureAwait(false);
public Task SaveAsync(CameraProfile profile, CancellationToken cancellationToken = default) =>
db.Settings.SetAsync(SettingScope.App, null, Key(profile.Make, profile.Model), profile, CameraProfileJson.Default.CameraProfile, cancellationToken);
private static string Key(string? make, string model) => KeyPrefix + (make ?? string.Empty).Trim().ToLowerInvariant() + "|" + model.Trim().ToLowerInvariant();
}
[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(CameraProfile))]
internal sealed partial class CameraProfileJson : JsonSerializerContext;
+76
View File
@@ -0,0 +1,76 @@
using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Localization;
namespace Titano.App.Import;
/// <summary>
/// What may be done to the card after an import (BRIEF §0.2 rule 8, §12.4, §13). Deleting needs a recorded,
/// verified import into this PC's archive and a dry run that re-hashed every card file and its copy; formatting
/// needs, on top, a complete verified import and a dry run in which every photo on the card is safe to delete; files
/// that are not photos (videos, camera folders) never block it but are named in its confirmation. Ejecting only needs
/// a removable card. Each refusal comes with the sentence the button's tooltip shows.
/// </summary>
/// <param name="Card">Every file on the card when the dry run ran; null until then.</param>
public sealed record CardActions(ImportDestinationKind Destination, bool IsKnownCard, bool IsInserted, bool IsRemovable, ImportOutcome? Outcome,
ErasePlan? Erase, CardSnapshot? Card)
{
/// <summary>The dry run of "Delete imported" may start.</summary>
public bool CanCheck => CheckBlocker is null;
public string? CheckBlocker =>
Destination != ImportDestinationKind.Archive ? Loc.L("Import.Blocked.NotArchive")
: !IsKnownCard || !IsInserted ? Loc.L("Import.Blocked.NoCard")
: Outcome is not { Imported: > 0 } and not { Skipped: > 0 } ? Loc.L("Import.Blocked.NothingImported")
: null;
public bool CanDelete => DeleteBlocker is null;
public string? DeleteBlocker =>
CheckBlocker ?? (Erase is null || Card is null ? Loc.L("Import.Blocked.NoDryRun") : DeleteCount == 0 ? Loc.L("Import.Blocked.NothingVerified") : null);
public bool CanFormat => FormatBlocker is null;
public string? FormatBlocker =>
DeleteBlocker
?? (Outcome is not { IsComplete: true, Verified: true } ? Loc.L("Import.Blocked.Incomplete")
: KeptCount > 0 || DeleteCount < Card!.Photos ? Loc.L("Import.Blocked.NotAllVerified")
: null);
public bool CanEject => IsInserted && IsRemovable;
public int DeleteCount => Erase?.ToDelete.Count() ?? 0;
public long DeleteBytes => Erase?.ToDelete.Sum(i => i.Candidate.Size) ?? 0;
public int KeptCount => Erase?.Items.Count(i => i.Verdict != EraseVerdict.Delete) ?? 0;
/// <summary>Files on the card that are not verified photos (videos, camera folders): formatting would lose them.</summary>
public IReadOnlyList<string> NotImported
{
get
{
if (Card is null || Erase is null) return [];
var verified = Erase.ToDelete.Select(i => i.Candidate.SourcePath).ToHashSet(StringComparer.OrdinalIgnoreCase);
return [.. Card.Files.Keys.Where(p => !verified.Contains(p) && !ArchiveScanner.IsPhoto(p)).Order(StringComparer.OrdinalIgnoreCase)];
}
}
/// <summary>"4,812 verified on the card · 96.2 GB · 2 kept": the dry run in one line; empty before it ran.</summary>
public string EraseText => Erase is null
? string.Empty
: string.Join(" · ", new[]
{
Loc.Plural("Import.Erase.Verified", DeleteCount),
Formatting.Bytes(DeleteBytes),
KeptCount > 0 ? Loc.Plural("Import.Erase.Kept", KeptCount) : string.Empty,
NotImported.Count > 0 ? Loc.Plural("Import.Erase.Other", NotImported.Count) : string.Empty,
}.Where(t => t.Length > 0));
/// <summary>Why each kept photo stays on the card ("IMG_0042.CR2 · the archive copy no longer matches").</summary>
public IReadOnlyList<string> KeptReasons =>
Erase is null ? [] : [.. Erase.Items.Where(i => i.Verdict != EraseVerdict.Delete).Select(i => Loc.L("Import.Erase.Reason", i.Candidate.SourcePath, Verdict(i.Verdict)))];
public static string Verdict(EraseVerdict verdict) => Loc.L("Import.Erase.Verdict." + verdict);
}
+61
View File
@@ -0,0 +1,61 @@
using System.Globalization;
using Titano.Data.Archiving;
namespace Titano.App.Import;
/// <summary>
/// A volume the Import screen offers (BRIEF §12.4, §13): a removable volume, or any volume with a <c>DCIM</c> folder.
/// Card identity is <c>{serial:X8}-{label}-{capacity}</c>, stable across readers and drive letters.
/// </summary>
/// <param name="Root">Root with trailing separator, e.g. <c>E:\</c>.</param>
public sealed record CardDevice(string Root, string Label, uint SerialNumber, long TotalBytes, long FreeBytes, bool IsRemovable, bool HasDcim)
{
public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}");
public long UsedBytes => System.Math.Max(0, TotalBytes - FreeBytes);
public CardVolume ToVolume() => new(Identity, SerialNumber, Label.Length == 0 ? null : Label, TotalBytes);
}
/// <summary>Outcome of a safe removal.</summary>
public enum EjectOutcome
{
Ejected,
/// <summary>Files on the card are still open; nothing changed.</summary>
InUse,
/// <summary>Not a removable drive, or Windows refused.</summary>
Failed,
}
/// <summary>Outcome of the operating system's format dialog (BRIEF §8.6).</summary>
public enum FormatOutcome
{
Formatted,
Cancelled,
Failed,
}
/// <summary>
/// Card detection and the two OS actions on a card (BRIEF §8.6, §13): safe removal and the Windows format dialog.
/// Events may arrive on any thread.
/// </summary>
public interface IDeviceMonitor : IDisposable
{
event Action<CardDevice>? Arrived;
event Action<CardDevice>? Removed;
/// <summary>Candidate volumes present now.</summary>
IReadOnlyList<CardDevice> Devices { get; }
/// <summary>Starts watching (idempotent); the first snapshot raises no events.</summary>
void Start();
/// <summary>Locks, dismounts and ejects the volume; blocks for up to a few seconds.</summary>
EjectOutcome Eject(CardDevice device);
/// <summary>Shows the Windows format dialog for the volume; call on the UI thread.</summary>
FormatOutcome Format(CardDevice device);
}
+147
View File
@@ -0,0 +1,147 @@
using System.Globalization;
using System.IO;
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Core.Naming;
namespace Titano.App.Import;
public enum SourceKind
{
/// <summary>A card with a DCIM tree, or a remembered card.</summary>
Card,
/// <summary>A removable drive without DCIM: imported as a plain folder tree.</summary>
Drive,
/// <summary>A folder picked with "Folder…".</summary>
Folder,
}
/// <summary>What an inserted card holds: its photos and the camera of the first one (Devices list, insertion toast).</summary>
public sealed record CardContents(int Photos, string? Camera)
{
/// <summary>Lists the card's photos (no metadata but the first photo's); blocks for a directory walk.</summary>
public static CardContents Read(string root, CancellationToken cancellationToken = default)
{
var photos = CardScanner.Find(root, includeSubfolders: true, cancellationToken);
string? camera = null;
if (photos.Count > 0)
{
try
{
var first = MetadataReader.Read(Path.Combine(root, photos[0].RelativePath), cancellationToken);
camera = PathTemplate.CameraName(first.Make, first.Model) is { Length: > 0 } name ? name : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", $"Cannot read the first photo of {root}", ex);
}
}
return new CardContents(photos.Count, camera);
}
}
/// <summary>
/// One entry of the Devices list (BRIEF §12.4, §13 card pool): an inserted volume joined with its remembered card, a
/// remembered card that is not inserted, or a picked folder. <see cref="Key"/> is the card identity or the folder path.
/// </summary>
/// <param name="Contents">What an inserted card holds, once listed.</param>
public sealed record ImportSource(string Key, SourceKind Kind, CardDevice? Device, MediaCard? Card, string? FolderPath, CardContents? Contents = null)
{
public bool IsInserted => Device is not null || FolderPath is not null;
public bool IsKnown => Card is not null;
/// <summary>Where the photos are read from; null for a remembered card that is not inserted.</summary>
public string? Root => Device?.Root ?? FolderPath;
/// <summary>"EOS R5 · card A", the volume label, or the drive.</summary>
public string Title => Card?.Nickname is { Length: > 0 } nickname ? nickname
: Device is { Label.Length: > 0 } labelled ? labelled.Label
: Device?.Root ?? FolderPath ?? Card?.Label ?? string.Empty;
/// <summary>"128 GB · 96.2 GB used · 4,812 photos", "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", Formatting.Bytes(Device!.FreeBytes)),
_ when Device is not null && Contents is { } contents => Loc.L("Import.Device.CardPhotos", Formatting.Bytes(Device.TotalBytes),
Formatting.Bytes(Device.UsedBytes), Loc.Plural("Shell.Status.Photos", contents.Photos)),
_ 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)),
};
/// <summary>"Known card", "New card", … for the state dot's tooltip.</summary>
public string StateText => Loc.L(Kind switch
{
SourceKind.Folder => "Import.Device.State.Folder",
SourceKind.Drive => "Import.Device.State.Drive",
_ when !IsInserted => "Import.Device.State.Away",
_ when IsKnown => "Import.Device.State.Known",
_ => "Import.Device.State.New",
});
/// <summary>"Canon EOS R5 · 4,812 photos": the insertion toast's line; "not yet known to Titano" for a new card.</summary>
public string ToastText
{
get
{
var parts = new List<string>();
if ((CameraText(Card) is { Length: > 0 } known ? known : Contents?.Camera) is { } camera) parts.Add(camera);
if (Contents is { } contents) parts.Add(Loc.Plural("Shell.Status.Photos", contents.Photos));
if (!IsKnown) parts.Add(Loc.L("Import.Toast.Unknown"));
return string.Join(" · ", parts);
}
}
/// <summary>"128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431": the identity line of the profile header.</summary>
public string IdentityText
{
get
{
var parts = new List<string>();
var capacity = Device?.TotalBytes ?? Card?.Capacity ?? 0;
if (capacity > 0) parts.Add(Formatting.Bytes(capacity));
var serial = Device?.SerialNumber ?? Card?.VolumeSerial;
if (serial is { } s && Kind != SourceKind.Folder) parts.Add(Loc.L("Import.Device.Serial", SerialText(s)));
if (CameraText(Card) is { Length: > 0 } camera) parts.Add(Card?.CameraSerial is { Length: > 0 } body ? Loc.L("Import.Device.Body", camera, body) : camera);
return string.Join(" · ", parts);
}
}
/// <summary>"3F2A-9C11", as Windows shows a volume serial.</summary>
public static string SerialText(uint serial)
{
var hex = serial.ToString("X8", CultureInfo.InvariantCulture);
return hex[..4] + "-" + hex[4..];
}
private static string CameraText(MediaCard? card) => card is null ? string.Empty : PathTemplate.CameraName(card.CameraMake, card.CameraModel);
}
/// <summary>Builds the Devices list: inserted volumes first (in drive order), then remembered cards, then a picked folder.</summary>
public static class CardPool
{
/// <param name="contents">What the inserted cards hold, by card identity, as far as listed.</param>
public static IReadOnlyList<ImportSource> Build(IEnumerable<CardDevice> devices, IEnumerable<MediaCard> cards, string? folder,
IReadOnlyDictionary<string, CardContents>? contents = null)
{
var known = cards.ToDictionary(c => c.Identity, StringComparer.Ordinal);
var list = new List<ImportSource>();
foreach (var device in devices.OrderBy(d => d.Root, StringComparer.OrdinalIgnoreCase))
{
known.Remove(device.Identity, out var card);
var kind = device.HasDcim || card is not null ? SourceKind.Card : SourceKind.Drive;
list.Add(new ImportSource(device.Identity, kind, device, card, null, contents?.GetValueOrDefault(device.Identity)));
}
foreach (var card in known.Values.OrderByDescending(c => c.LastSeen))
list.Add(new ImportSource(card.Identity, SourceKind.Card, null, card, null));
if (folder is not null) list.Add(new ImportSource(folder, SourceKind.Folder, null, null, folder));
return list;
}
}
+41
View File
@@ -0,0 +1,41 @@
using System.IO;
using Titano.Core.Archiving;
namespace Titano.App.Import;
/// <summary>A card file's size and write time.</summary>
public readonly record struct CardFileStamp(long Size, DateTime ModifiedUtc);
/// <summary>
/// Every file on a card when its dry run ran (BRIEF §0.2 rule 8), hidden and system files aside: the format gate
/// compares it with the verified photos, and formatting refuses a card that changed since — another card, a photo shot
/// meanwhile, a file touched.
/// </summary>
public sealed record CardSnapshot(string Identity, IReadOnlyDictionary<string, CardFileStamp> Files)
{
private static readonly EnumerationOptions Listing = new()
{
IgnoreInaccessible = true,
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint | FileAttributes.System | FileAttributes.Hidden,
};
/// <summary>Lists the card below <paramref name="root"/> (forward-slash paths, as the import history keys them).</summary>
public static CardSnapshot Take(string root, string identity, CancellationToken cancellationToken = default)
{
var files = new Dictionary<string, CardFileStamp>(StringComparer.OrdinalIgnoreCase);
foreach (var file in new DirectoryInfo(root).EnumerateFiles("*", Listing))
{
cancellationToken.ThrowIfCancellationRequested();
files[Path.GetRelativePath(root, file.FullName).Replace('\\', '/')] = new CardFileStamp(file.Length, file.LastWriteTimeUtc);
}
return new CardSnapshot(identity, files);
}
/// <summary>Photos on the card, wherever they are.</summary>
public int Photos => Files.Keys.Count(p => ArchiveScanner.IsPhoto(p));
/// <summary>True when <paramref name="now"/> is the same card holding exactly the same files, unchanged.</summary>
public bool IsUnchanged(CardSnapshot now) =>
Identity == now.Identity && Files.Count == now.Files.Count && Files.All(f => now.Files.TryGetValue(f.Key, out var stamp) && stamp == f.Value);
}
+101
View File
@@ -0,0 +1,101 @@
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data.Archiving;
namespace Titano.App.Import;
/// <summary>Where the photos go (BRIEF §12.4): this PC's archive, a plain folder, or the signed-in server.</summary>
public enum ImportDestinationKind
{
Archive,
Folder,
Server,
}
/// <summary>
/// The Import form (Import.html): scan, sessions, names, duplicates and after-import choices. Remembered per card as
/// its <see cref="CardProfile"/>; a session gap of 0 minutes in a profile means "do not split into sessions".
/// </summary>
public sealed record ImportChoices
{
public ImportDestinationKind Destination { get; init; } = ImportDestinationKind.Archive;
public string? FolderPath { get; init; }
public bool IncludeSubfolders { get; init; } = true;
public bool SplitSessions { get; init; } = true;
public int GapMinutes { get; init; } = 45;
public int MinimumFrames { get; init; } = 8;
public bool VerifyCopies { get; init; } = true;
public string FolderTemplate { get; init; } = TemplateDefaults.Folder;
public string FileTemplate { get; init; } = TemplateDefaults.File;
public DuplicatePolicy Duplicates { get; init; } = DuplicatePolicy.Skip;
public AfterImport AfterImport { get; init; } = AfterImport.Keep;
public bool Eject { get; init; } = true;
public bool DeepAnalysis { get; init; } = true;
/// <summary>A card's remembered choices.</summary>
public static ImportChoices FromProfile(CardProfile profile) => new()
{
IncludeSubfolders = profile.IncludeSubfolders,
SplitSessions = profile.SessionGapMinutes > 0,
GapMinutes = profile.SessionGapMinutes > 0 ? profile.SessionGapMinutes : new CardProfile().SessionGapMinutes,
MinimumFrames = profile.MinimumSessionFrames,
VerifyCopies = profile.VerifyCopies,
FolderTemplate = profile.FolderTemplate,
FileTemplate = profile.FileTemplate,
Duplicates = profile.Duplicates,
AfterImport = profile.AfterImport,
Eject = profile.Eject,
DeepAnalysis = profile.DeepAnalysis,
};
public CardProfile ToProfile() => new()
{
FolderTemplate = FolderTemplate,
FileTemplate = FileTemplate,
SessionGapMinutes = SplitSessions ? GapMinutes : 0,
MinimumSessionFrames = MinimumFrames,
IncludeSubfolders = IncludeSubfolders,
VerifyCopies = VerifyCopies,
Duplicates = Duplicates,
AfterImport = AfterImport,
Eject = Eject,
DeepAnalysis = DeepAnalysis,
};
/// <summary>
/// Planner options; <paramref name="titles"/> are the session titles typed in the plan, by session key;
/// <paramref name="splits"/> and <paramref name="merges"/> the card paths where the user split or merged sessions.
/// </summary>
public ImportOptions ToOptions(IReadOnlyDictionary<string, string>? titles = null, IReadOnlySet<string>? splits = null, IReadOnlySet<string>? merges = null) =>
new()
{
FolderTemplate = FolderTemplate,
FileTemplate = FileTemplate,
// Without session splitting every camera body and format stays one session.
SessionGap = SplitSessions ? TimeSpan.FromMinutes(System.Math.Max(1, GapMinutes)) : TimeSpan.MaxValue,
MinimumSessionFrames = System.Math.Max(1, MinimumFrames),
IncludeSubfolders = IncludeSubfolders,
VerifyCopies = VerifyCopies,
Duplicates = Duplicates,
Titles = titles ?? new Dictionary<string, string>(),
SplitBefore = splits ?? new HashSet<string>(),
MergeAt = merges ?? new HashSet<string>(),
};
/// <summary>True when a choice changes which photos form which session or where they go, so the card must be planned again.</summary>
public bool NeedsNewPlan(ImportChoices previous) =>
previous.Destination != Destination
|| !string.Equals(previous.FolderPath, FolderPath, StringComparison.OrdinalIgnoreCase)
|| previous.IncludeSubfolders != IncludeSubfolders
|| previous.SplitSessions != SplitSessions
|| (SplitSessions && previous.GapMinutes != GapMinutes)
|| previous.MinimumFrames != MinimumFrames
|| previous.FolderTemplate != FolderTemplate
|| previous.FileTemplate != FileTemplate;
/// <summary>Session titles feed the names only when a template uses <c>{title}</c>.</summary>
public bool TitlesChangeNames => UsesTitle(FolderTemplate) || UsesTitle(FileTemplate);
private static bool UsesTitle(string template) => template.Contains("{title", StringComparison.OrdinalIgnoreCase);
}
+245
View File
@@ -0,0 +1,245 @@
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Protocol.Client;
namespace Titano.App.Import;
/// <summary>Plans an import into one destination (BRIEF §12.4); nothing is written.</summary>
public interface IImportDestination
{
ImportDestinationKind Kind { get; }
/// <param name="progress">Photos read so far.</param>
Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken);
}
/// <summary>This PC's archive: the planner knows the card's history, the archive's duplicates and its sequences.</summary>
public sealed class ArchiveDestination(ArchiveService archives, Archive archive) : IImportDestination
{
public Archive Archive { get; } = archive;
public ImportDestinationKind Kind => ImportDestinationKind.Archive;
public Task<ImportPlan> PlanAsync(string sourceRoot, ImportOptions options, Guid? cardId, IProgress<int>? progress, CancellationToken cancellationToken) =>
archives.PlanImportAsync(Archive.Id, sourceRoot, options, cardId, progress, cancellationToken);
}
/// <summary>
/// A plain folder or the server: nothing is indexed on this PC, so every photo is copied; a folder destination finds
/// identical files by name and hash while copying, the server by hash before any byte is sent.
/// </summary>
public sealed class UnindexedDestination(ImportDestinationKind kind, string root) : IImportDestination
{
public ImportDestinationKind Kind { get; } = kind;
/// <summary>The folder, or the local staging folder of server uploads.</summary>
public string Root { get; } = root;
/// <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);
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>
private sealed class NoIndex : IImportLookup
{
public static readonly NoIndex Instance = new();
public Task<bool> WasImportedAsync(CardFile file, CancellationToken cancellationToken) => Task.FromResult(false);
public Task<IReadOnlyList<ArchiveMatch>> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<ArchiveMatch>>([]);
public Task<string?> FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
public bool IsFolderTaken(string folder) => false;
}
}
/// <summary>A failed photo of an import: where it is on the card and why.</summary>
public sealed record ImportFailure(string SourcePath, string Message);
/// <summary>Whether a planned copy reached the archive after an archive import job.</summary>
public enum CommitCheck
{
/// <summary>No frame of the archive is this photo's copy.</summary>
Missing,
/// <summary>The job committed a new frame for the photo.</summary>
Copied,
/// <summary>The job found the same content already at the destination and kept that frame.</summary>
AlreadyThere,
}
/// <summary>
/// What a destination did per card file beyond the executor's commit results (server imports): the files it committed,
/// also those of a batch an abort interrupted, and the files it refused with the reason.
/// </summary>
public sealed class ImportSinkReport
{
public Dictionary<string, SinkCommit> Committed { get; } = new(StringComparer.Ordinal);
public Dictionary<string, string> Rejected { get; } = new(StringComparer.Ordinal);
}
/// <summary>What an import did (BRIEF §12.4 verification result).</summary>
/// <param name="Copied">Copied and committed (verified by read-back when <paramref name="Verified"/>).</param>
/// <param name="Duplicates">Copied, but the destination already held the same content.</param>
/// <param name="Skipped">Not copied: imported before, or already in the archive.</param>
public sealed record ImportOutcome(int Copied, int Duplicates, int Skipped, IReadOnlyList<ImportFailure> Failures, bool Verified)
{
public bool IsComplete => Failures.Count == 0;
/// <summary>Photos the destination now holds a verified copy of.</summary>
public int Imported => Copied + Duplicates;
/// <summary>
/// Totals of an executor run (folder or server destination): the executor's per-file results, corrected by what the
/// sink reported (refused files fail, files committed in a batch an abort interrupted count); after an abort
/// (<paramref name="stopped"/>) every copy not reached fails with that reason.
/// </summary>
public static ImportOutcome From(ImportPlan plan, IEnumerable<ImportItemResult> results, bool verified, ImportSinkReport? report = null,
string? stopped = null)
{
var byPath = new Dictionary<string, ImportItemResult>(StringComparer.Ordinal);
foreach (var r in results) byPath[r.Item.SourcePath] = r;
int copied = 0, duplicates = 0, skipped = 0;
var failures = new List<ImportFailure>();
foreach (var item in plan.Items)
{
if (report?.Rejected.TryGetValue(item.SourcePath, out var refused) == true)
{
failures.Add(new ImportFailure(item.SourcePath, refused));
continue;
}
var status = byPath.TryGetValue(item.SourcePath, out var result) ? result.Status
: report?.Committed.TryGetValue(item.SourcePath, out var commit) == true ? commit.Duplicate ? ImportItemStatus.Duplicate : ImportItemStatus.Copied
: item.Action != ImportAction.Copy ? ImportItemStatus.Skipped
: ImportItemStatus.Failed;
switch (status)
{
case ImportItemStatus.Copied:
copied++;
break;
case ImportItemStatus.Duplicate:
duplicates++;
break;
case ImportItemStatus.Skipped:
skipped++;
break;
default:
failures.Add(new ImportFailure(item.SourcePath, result?.Error ?? stopped ?? Loc.L("Import.Result.NotCommitted")));
break;
}
}
return new ImportOutcome(copied, duplicates, skipped, failures, verified);
}
/// <summary>
/// After an archive import job: each planned copy is matched to its own committed frame (<paramref name="check"/>);
/// a copy that did not arrive shows the job's own error for that file (<paramref name="errors"/>, from its log) or
/// that it was not committed. The copies were hashed and read back while the job ran.
/// </summary>
public static async Task<ImportOutcome> CheckAsync(ImportPlan plan, bool verified, Func<PlannedItem, CancellationToken, Task<CommitCheck>> check,
IReadOnlyDictionary<string, string> errors, CancellationToken cancellationToken)
{
int copied = 0, duplicates = 0, skipped = 0;
var failures = new List<ImportFailure>();
foreach (var item in plan.Items)
{
if (item.Action != ImportAction.Copy)
{
skipped++;
continue;
}
switch (await check(item, cancellationToken).ConfigureAwait(false))
{
case CommitCheck.Copied:
copied++;
break;
case CommitCheck.AlreadyThere:
duplicates++;
break;
default:
failures.Add(new ImportFailure(item.SourcePath,
errors.TryGetValue(item.SourcePath, out var error) ? error : Loc.L("Import.Result.NotCommitted")));
break;
}
}
return new ImportOutcome(copied, duplicates, skipped, failures, verified);
}
/// <summary>
/// The per-file errors an import job wrote to its log ("Not copied: path (error)", in the language it ran in), by card
/// path. The log keeps its last lines only, so older errors fall back to "not committed".
/// </summary>
public static IReadOnlyDictionary<string, string> JobErrors(string? logTail)
{
var errors = new Dictionary<string, string>(StringComparer.Ordinal);
if (string.IsNullOrEmpty(logTail)) return errors;
var line = Regex.Escape(Loc.L("Archive.Log.ImportFailed", "\u0001", "\u0002"))
.Replace("\u0001", "(?<path>.+?)", StringComparison.Ordinal)
.Replace("\u0002", "(?<error>.*)", StringComparison.Ordinal);
var pattern = new Regex("^(?:\\S+ )?" + line + "$", RegexOptions.CultureInvariant);
foreach (var entry in logTail.Split('\n'))
{
if (pattern.Match(entry.TrimEnd('\r')) is { Success: true } match) errors[match.Groups["path"].Value] = match.Groups["error"].Value;
}
return errors;
}
}
/// <summary>
/// Runs a confirmed plan into a folder or the server on this PC (no job handler exists for those destinations): copies
/// with hashing and read-back, commits each batch to the sink and collects the per-file results. A card that leaves or
/// a destination that fails as a whole (disk, connection, sign-in) stops the run; what was done until then is kept in
/// the outcome and every copy not reached fails with the reason.
/// </summary>
public static class LocalImport
{
public static async Task<ImportOutcome> RunAsync(ImportPlan plan, IImportSink sink, bool verify, IProgress<ImportProgress>? progress,
CancellationToken cancellationToken, ImportSinkReport? report = null)
{
var results = new List<ImportItemResult>(plan.FileCount);
string? stopped = null;
try
{
await new ImportExecutor(plan, sink).RunAsync(0, verify, batch =>
{
results.AddRange(batch.Results);
progress?.Report(batch.Progress);
return ValueTask.CompletedTask;
}, p =>
{
progress?.Report(p);
return ValueTask.CompletedTask;
}, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex))
{
Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", ex);
// The server's own sentence (in the user's language) rather than the status line.
stopped = ex is TitanoApiException api ? api.Error.Message : ex.Message;
}
return ImportOutcome.From(plan, results, verify, report, stopped);
}
/// <summary>The card left, or the destination as a whole failed: its disk, the connection, the sign-in or the server (a timeout too).</summary>
private static bool Stops(Exception ex) =>
ex is IOException or UnauthorizedAccessException or HttpRequestException or TitanoApiException or UntrustedCertificateException
or InvalidOperationException or OperationCanceledException;
}
+234
View File
@@ -0,0 +1,234 @@
using Titano.App.Infrastructure;
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Naming;
namespace Titano.App.Import;
/// <summary>Figures of a plan for the Plan panel header and the Import button (Import.html).</summary>
public sealed record PlanTotals(int Sessions, int Photos, int CopyCount, long CopyBytes, int Duplicates, int ImportedBefore, int Problems,
long? FreeAfter, TimeSpan Estimate)
{
public bool HasEnoughSpace => FreeAfter is not < 0;
/// <summary>"3 sessions · 4,812 photos · 96.2 GB · about 12 min".</summary>
public string Text => string.Join(" · ",
Loc.Plural("Import.Plan.Sessions", Sessions),
Loc.Plural("Shell.Status.Photos", Photos),
Formatting.Bytes(CopyBytes),
Loc.L("Import.Plan.About", Formatting.Duration(Estimate)));
/// <summary>"0 duplicates" (already in the archive by hash).</summary>
public string DuplicatesText => Loc.Plural("Import.Plan.Duplicates", Duplicates);
/// <summary>"12 imported before" (same file from this card), or empty.</summary>
public string ImportedBeforeText => ImportedBefore > 0 ? Loc.Plural("Import.Plan.ImportedBefore", ImportedBefore) : string.Empty;
/// <summary>"2.1 TB free after import", "3.2 GB missing", or empty when the volume does not report its space.</summary>
public string SpaceText => FreeAfter switch
{
null => string.Empty,
< 0 => Loc.L("Import.Plan.SpaceMissing", Formatting.Bytes(-FreeAfter.Value)),
_ => Loc.L("Import.Plan.FreeAfter", Formatting.Bytes(FreeAfter.Value)),
};
/// <summary>"Import 4,812 photos".</summary>
public string ImportText => Loc.Plural("Import.Start", CopyCount);
}
/// <summary>One row of the session table: what the planner grouped and where it goes.</summary>
/// <param name="DefaultTitle">Title the sequence gets when the user types none (its folder name).</param>
/// <param name="IsNew">The session starts a new sequence (false: it continues one imported before).</param>
/// <param name="FirstPath">Card path of the session's first photo (where a merge joins it to the previous session).</param>
/// <param name="MergesInto">Number of the earlier session of the same camera and format it can merge into; null for none.</param>
public sealed record PlanSessionRow(int Number, string SessionKey, string? Title, string DefaultTitle, string TimeText, string FramesText,
string SizeText, string CameraText, string TargetText, bool IsNew, string FirstPath, int? MergesInto);
public enum PlanRowKind
{
Session,
File,
}
/// <summary>A line of "Show plan": a session heading or one file and its destination.</summary>
/// <param name="CanSplit">A file that is not the first of its session: a new session can start there.</param>
public sealed record PlanDetailRow(PlanRowKind Kind, string Source, string Destination, string ActionText, string SizeText, bool IsSkipped, bool CanSplit);
/// <summary>Everything "Show plan" lists: every file to its destination, the totals and the conflicts.</summary>
public sealed record PlanDetails(IReadOnlyList<PlanDetailRow> Rows, string TotalsText, IReadOnlyList<string> Conflicts);
/// <summary>
/// Turns an <see cref="ImportPlan"/> into what the Import screen shows (BRIEF §12.4 "Plan before touching disk") and
/// applies the choices that need no new scan of the card: the duplicate choice and session titles.
/// </summary>
public static class ImportPlans
{
/// <summary>Planning speed assumption for the estimate: a UHS-I card read plus the read-back of the copy.</summary>
public const double BytesPerSecond = 80e6;
public const double VerifiedBytesPerSecond = 55e6;
public static TimeSpan Estimate(long bytes, bool verify) =>
TimeSpan.FromSeconds(System.Math.Ceiling(bytes / (verify ? VerifiedBytesPerSecond : BytesPerSecond)));
public static PlanTotals Totals(ImportPlan plan, bool verify) => new(
plan.Sessions.Count,
plan.FileCount,
plan.CopyCount,
plan.CopyBytes,
plan.Items.Count(i => i.ExistingFrameId is not null),
plan.Items.Count(i => i.Action == ImportAction.SkipImported),
plan.Problems.Count,
plan.AvailableBytes is { } free ? free - plan.CopyBytes : null,
Estimate(plan.CopyBytes, verify));
/// <summary>
/// The plan with every photo already in the archive skipped or imported again, as the planner would have decided
/// (BRIEF §13: skip, or import again; never overwrite).
/// </summary>
public static ImportPlan WithDuplicates(ImportPlan plan, DuplicatePolicy policy) => plan with
{
Sessions =
[
.. plan.Sessions.Select(s => s with
{
Items =
[
.. s.Items.Select(i => i.ExistingFrameId is null || i.Action == ImportAction.SkipImported
? i
: i with { Action = policy == DuplicatePolicy.Skip ? ImportAction.SkipInArchive : ImportAction.Copy }),
],
}),
],
};
/// <summary>The plan with the typed session titles (when no template uses <c>{title}</c>, so no name changes).</summary>
public static ImportPlan WithTitles(ImportPlan plan, IReadOnlyDictionary<string, string> titles) => plan with
{
Sessions = [.. plan.Sessions.Select(s => s with { Title = titles.TryGetValue(s.SessionKey, out var t) && !string.IsNullOrWhiteSpace(t) ? t.Trim() : null })],
};
/// <param name="existingFolders">Folders of sequences already in the archive (a session there continues it).</param>
public static IReadOnlyList<PlanSessionRow> Sessions(ImportPlan plan, ImportDestinationKind destination, IReadOnlySet<string> existingFolders) =>
[
.. plan.Sessions.Select(s =>
{
var isNew = !existingFolders.Contains(s.Folder);
var leaf = s.Folder[(s.Folder.LastIndexOf('/') + 1)..];
var target = destination switch
{
ImportDestinationKind.Server => Loc.L("Import.Session.Server"),
ImportDestinationKind.Folder => s.Folder,
_ => Loc.L(isNew ? "Import.Session.New" : "Import.Session.Adds", s.Folder),
};
return new PlanSessionRow(s.Number, s.SessionKey, s.Title, leaf, TimeText(s), FramesText(s), Formatting.Bytes(s.Items.Sum(i => i.Size)),
PathTemplate.CameraName(s.CameraMake, s.CameraModel), target, isNew, s.Items.Count > 0 ? s.Items[0].SourcePath : string.Empty,
MergeTarget(plan, s)?.Number);
}),
];
/// <summary>
/// The session <paramref name="session"/> joins when the user merges it (BRIEF §13): the one before it of the same
/// camera body and format, whose last photo precedes its first; sessions of other cameras or formats never merge.
/// </summary>
public static PlannedSession? MergeTarget(ImportPlan plan, PlannedSession session) =>
plan.Sessions.TakeWhile(s => !ReferenceEquals(s, session))
.LastOrDefault(s => s.CameraMake == session.CameraMake && s.CameraModel == session.CameraModel && s.CameraSerial == session.CameraSerial
&& s.Format == session.Format);
/// <summary>"Show plan": every file and where it goes, with the conflicts the plan resolved or reports.</summary>
public static PlanDetails Details(ImportPlan plan, ImportDestinationKind destination, bool verify)
{
var rows = new List<PlanDetailRow>(plan.FileCount + plan.Sessions.Count);
foreach (var s in plan.Sessions)
{
var folder = DestinationFolder(s, destination);
rows.Add(new PlanDetailRow(PlanRowKind.Session, Loc.L("Import.Details.Session", s.Number, TimeText(s)), folder,
Loc.Plural("Shell.Status.Photos", s.Items.Count), Formatting.Bytes(s.Items.Sum(i => i.Size)), false, false));
for (var i = 0; i < s.Items.Count; i++)
{
var item = s.Items[i];
rows.Add(new PlanDetailRow(PlanRowKind.File, item.SourcePath, folder + "/" + item.FileName, ActionText(item),
Formatting.Bytes(item.Size), item.Action != ImportAction.Copy, i > 0));
}
}
var totals = Totals(plan, verify);
var conflicts = new List<string>();
foreach (var problem in plan.Problems) conflicts.Add(Loc.L("Import.Details.Unreadable", problem.RelativePath, problem.Message));
if (totals.Duplicates > 0) conflicts.Add(totals.DuplicatesText);
if (!totals.HasEnoughSpace) conflicts.Add(totals.SpaceText);
var text = string.Join(" · ", new[]
{
Loc.Plural("Import.Details.Files", plan.FileCount),
Loc.L("Import.Details.Copy", Formatting.Count(plan.CopyCount), Formatting.Bytes(plan.CopyBytes)),
totals.ImportedBeforeText,
totals.Duplicates > 0 ? totals.DuplicatesText : string.Empty,
}.Where(t => t.Length > 0));
return new PlanDetails(rows, text, conflicts);
}
/// <summary>The destination of a session as the user will find it: the archive's originals folder, the folder, or the server.</summary>
public static string DestinationFolder(PlannedSession session, ImportDestinationKind destination) => destination switch
{
ImportDestinationKind.Archive => session.Folder + "/" + ArchiveLayout.OriginalsFolder,
ImportDestinationKind.Server => Loc.L("Import.Session.Server"),
_ => session.Folder,
};
/// <summary>The first <paramref name="count"/> files the plan copies, as folder/name (the name alone for the server).</summary>
public static IReadOnlyList<string> FirstDestinations(ImportPlan plan, ImportDestinationKind destination, int count = 3) =>
[
.. plan.Sessions.SelectMany(s => s.Items.Where(i => i.Action == ImportAction.Copy)
.Select(i => destination == ImportDestinationKind.Server ? i.FileName : s.Folder + "/" + i.FileName))
.Take(count),
];
/// <summary>
/// "→ 2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2 · 2026-09-28_18-02-13_0002.CR2 · …" (BRIEF §7.1: the first
/// three names): a name in the same folder as the one before it is shown without the folder. Empty without names.
/// </summary>
public static string NamePreview(IReadOnlyList<string> paths)
{
if (paths.Count == 0) return string.Empty;
var shown = new List<string>(paths.Count);
for (var i = 0; i < paths.Count; i++)
{
var folder = FolderOf(paths[i]);
shown.Add(i > 0 && folder == FolderOf(paths[i - 1]) ? paths[i][(folder.Length == 0 ? 0 : folder.Length + 1)..] : paths[i]);
}
return Loc.L("Import.Names.Preview", string.Join(" · ", shown));
}
private static string FolderOf(string path) => path.LastIndexOf('/') is var slash and >= 0 ? path[..slash] : string.Empty;
private static string ActionText(PlannedItem item) => item.Action switch
{
ImportAction.SkipImported => Loc.L("Import.Action.ImportedBefore"),
ImportAction.SkipInArchive => Loc.L("Import.Action.Duplicate"),
_ when item.ExistingFrameId is not null => Loc.L("Import.Action.Again"),
_ => Loc.L("Import.Action.Copy"),
};
/// <summary>"28/09/2026 · 18:02 → 20:04".</summary>
private static string TimeText(PlannedSession s) =>
Loc.L("Import.Session.Time", Formatting.Date(s.Start), s.Start.ToString("t", Loc.Culture), s.End.ToString("t", Loc.Culture));
/// <summary>"3,600 · 2 s": photos and the median interval between them.</summary>
private static string FramesText(PlannedSession s)
{
var interval = MedianInterval(s.Items);
var count = Formatting.Count(s.Items.Count);
return interval is { } median ? Loc.L("Import.Session.Frames", count, Formatting.Duration(median)) : count;
}
internal static TimeSpan? MedianInterval(IReadOnlyList<PlannedItem> items)
{
if (items.Count < 2) return null;
var gaps = new List<double>(items.Count - 1);
for (var i = 1; i < items.Count; i++) gaps.Add((items[i].CapturedAt - items[i - 1].CapturedAt).TotalSeconds);
gaps.Sort();
var middle = gaps.Count / 2;
var seconds = gaps.Count % 2 == 1 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
return TimeSpan.FromSeconds(System.Math.Max(0, seconds));
}
}
@@ -0,0 +1,297 @@
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; a card that leaves needs a new check, and formatting refuses a card that changed
/// since its check.
/// </summary>
public sealed class ImportResultViewModel : LocalizedViewModel
{
private const int ListedFailures = 100;
private const int ListedOther = 8;
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, null);
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 AsyncRelayCommand(FormatAsync, () => _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…" once the card was checked; "Delete photos…" before.</summary>
public string DeleteText => _actions.Erase is null ? Loc.L("Import.Erase.DeletePlain") : 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 is listed again, left, or came back (Devices list); actions follow. A card that left may come back
/// changed (photos shot meanwhile), so its dry run no longer counts: a new check is needed.
/// </summary>
public void SetDevice(CardDevice? device)
{
var same = device is not null && _device is not null && device.Identity == _device.Identity && device.Root == _device.Root;
_device = device;
Actions = _actions with
{
IsInserted = device is not null,
IsRemovable = device?.IsRemovable == true,
Erase = same ? _actions.Erase : null,
Card = same ? _actions.Card : null,
};
}
/// <summary>Shows a dry run computed elsewhere (capture, tests).</summary>
public void ShowErase(ErasePlan erase, CardSnapshot card) => Actions = _actions with { Erase = erase, Card = card };
/// <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 device = _device;
IsBusy = true;
try
{
var progress = new Progress<int>(n => BusyText = Loc.Plural("Import.Erase.Checking", n));
var (erase, snapshot) = await Task.Run(async () =>
{
// Listed before hashing: formatting later compares the card with this list.
var card = CardSnapshot.Take(device.Root, device.Identity);
return (await archives.PlanCardEraseAsync(_archive.Id, _card.Id, device.Root, progress).ConfigureAwait(false), card);
});
if (_device == device) ShowErase(erase, snapshot);
}
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, Card = 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 async Task FormatAsync()
{
if (_device is not { } device || _actions.Card is not { } checkedCard) return;
var name = _card?.Nickname ?? device.Label;
var notImported = _actions.NotImported;
var confirmed = _shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Import.Confirm.FormatHeading", name),
Message = notImported.Count == 0
? Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount)
: Loc.Plural("Import.Confirm.FormatMessage", _actions.DeleteCount) + " " + Loc.Plural("Import.Confirm.FormatOther", notImported.Count),
Detail = notImported.Count == 0 ? null : OtherFilesDetail(notImported),
DetailToolTip = Loc.L("Tooltips.Import.NotImported"),
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;
// Right before formatting: the same card, holding exactly what was checked (BRIEF §0.2 rule 8).
IsBusy = true;
bool unchanged;
try
{
var present = _shell.Services.Devices.Devices.FirstOrDefault(d => d.Identity == device.Identity && d.Root == device.Root);
unchanged = present is not null && checkedCard.IsUnchanged(await Task.Run(() => CardSnapshot.Take(present.Root, present.Identity)));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", "The card could not be listed before formatting", ex);
unchanged = false;
}
finally
{
IsBusy = false;
}
if (!unchanged)
{
Actions = _actions with { Erase = null, Card = null };
_shell.Notify(Loc.L("Import.Toast.CardChanged", name), Loc.L("Import.Blocked.NoDryRun"));
return;
}
var outcome = _shell.Services.Devices.Format(device);
if (outcome == FormatOutcome.Formatted) Actions = _actions with { Erase = null, Card = null };
if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name));
}
/// <summary>The first files that were never imported, one per line.</summary>
private static string OtherFilesDetail(IReadOnlyList<string> files)
{
var shown = files.Take(ListedOther).ToList();
if (files.Count > ListedOther) shown.Add("…");
return string.Join(Environment.NewLine, shown);
}
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;
}
}
}
+92
View File
@@ -0,0 +1,92 @@
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Data;
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 cards of <see cref="SampleCards"/>: the card just inserted (with its toast) and its plan and
/// sessions, "Show plan", the import copying, an import that stopped, the verification result with the after-import
/// actions, and a card seen for the first time (its nickname field and toast). The caller dismisses toasts before each
/// state, and after it unless <see cref="ShowsToast"/>.
/// </summary>
public static class ImportScenes
{
public static readonly IReadOnlyList<string> States = ["inserted", "plan", "showplan", "running", "failed", "done", "newcard"];
/// <summary>States that show a toast on purpose (the insertion toasts); the caller dismisses the others' toasts.</summary>
public static bool ShowsToast(string state) => state is "inserted" or "newcard";
public static async Task ShowAsync(ShellViewModel shell, string state)
{
var import = shell.Import;
var data = shell.Services.Environment.DataDirectory;
shell.Navigate(SectionKey.Import);
switch (state)
{
case "inserted":
await ShowPlanAsync(import, SampleCards.Card(data));
await import.CardInsertedAsync(SampleCards.Card(data));
break;
case "plan":
await ShowPlanAsync(import, SampleCards.Card(data));
break;
case "showplan":
import.ShowPlanCommand.Execute(null);
break;
case "running":
import.CloseDetailsCommand.Execute(null);
var plan = Plan(import);
import.ShowRunning(new ImportProgress(31, plan.FileCount, plan.CopyBytes * 31 / plan.FileCount, plan.CopyBytes, 31, 0, 0, null));
break;
case "failed":
import.ShowFailed(Loc.L("Archive.Error.SourceGone", SampleCards.Card(data).Root));
break;
case "done":
await ShowPlanAsync(import, SampleCards.Card(data));
import.DeleteImported = true;
var done = Plan(import);
var card = SampleCards.Card(data);
import.ShowResult(SampleCards.Outcome(done)).ShowErase(SampleCards.Erase(done), CardSnapshot.Take(card.Root, card.Identity));
break;
case "newcard":
// Inserted first (its toast says it is new), then chosen: its first plan registers it and asks for a nickname.
var fresh = SampleCards.NewCard(data);
await ForgetAsync(shell, fresh.Identity);
await import.CardInsertedAsync(fresh);
await ShowPlanAsync(import, fresh);
break;
default:
throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown Import state.");
}
}
/// <summary>The card selected, its plan ready, the sunset session titled.</summary>
private static async Task ShowPlanAsync(ImportViewModel import, CardDevice card)
{
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 == 3)
{
var sunset = import.Sessions[^1].Title;
sunset.Text = "Harbour sunset";
sunset.Commit();
}
}
private static ImportPlan Plan(ImportViewModel import) => import.Plan ?? throw new InvalidOperationException("The sample card has no plan.");
/// <summary>The new card stays new in every theme: an earlier state registered it on its first plan.</summary>
private static async Task ForgetAsync(ShellViewModel shell, string identity)
{
if (shell.Services.Database is not { } db || await db.MediaCards.FindByIdentityAsync(identity) is not { } known) return;
await db.MediaCards.DeleteAsync(known.Id);
}
}
@@ -0,0 +1,54 @@
using System.Windows.Input;
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) and its merge into
/// the earlier session of the same camera (BRIEF §13). Both can change only while the plan is not running.
/// </summary>
public sealed class ImportSessionRowViewModel : ObservableObject
{
private bool _isEditable = true;
public ImportSessionRowViewModel(PlanSessionRow row, Action<string, string> titleChanged, Action<PlanSessionRow> merge)
{
Row = row;
Title = new EditableField(row.Title ?? string.Empty, _ => null, text => titleChanged(row.SessionKey, text), () => Loc.L("Tooltips.Import.SessionTitle"));
MergeCommand = new RelayCommand(() => merge(row), () => CanMerge);
}
public PlanSessionRow Row { get; }
public EditableField Title { get; }
public string Placeholder => Row.DefaultTitle;
public ICommand MergeCommand { get; }
/// <summary>False while the import copies: the plan it runs is fixed.</summary>
public bool IsEditable
{
get => _isEditable;
set
{
if (!Set(ref _isEditable, value)) return;
OnPropertyChanged(nameof(TitleToolTip));
OnPropertyChanged(nameof(MergeToolTip));
OnPropertyChanged(nameof(CanMerge));
}
}
public bool CanMerge => IsEditable && Row.MergesInto is not null;
/// <summary>The merge button is shown only where a merge is possible.</summary>
public bool HasMerge => Row.MergesInto is not null;
public string TitleToolTip => IsEditable ? Title.ToolTip : Loc.L("Import.Blocked.Copying");
public string MergeToolTip => !IsEditable ? Loc.L("Import.Blocked.Copying")
: Row.MergesInto is { } target ? Loc.L("Tooltips.Import.Merge", target)
: string.Empty;
}
+184
View File
@@ -0,0 +1,184 @@
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 Sony card seen for the first time, 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 new card's one session: a morning harbour series.</summary>
private static readonly (DateTime Start, int Photos, int Interval)[] NewSessions = [(new DateTime(2026, 9, 30, 7, 15, 0), 12, 5)];
/// <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>A Sony card Titano has never seen (the nickname field and the "new card" toast).</summary>
public static CardDevice NewCard(string dataDirectory) =>
new(Path.Combine(dataDirectory, "newcard") + Path.DirectorySeparatorChar, "SONY", 0x2B7E1A09, 63_864_569_856, 60_120_000_000, IsRemovable: true,
HasDcim: true);
/// <summary>Writes the cards' photos, remembers two cards (the inserted one with its last import) and inserts both cards and a USB drive.</summary>
public static async Task InsertAsync(TitanoDatabase db, SampleDeviceMonitor devices, string dataDirectory)
{
var card = Card(dataDirectory);
WritePhotos(Path.Combine(card.Root, "DCIM", "100CANON"), "IMG_", Sessions, "Canon", "Canon EOS R5", "0431");
var newCard = NewCard(dataDirectory);
WritePhotos(Path.Combine(newCard.Root, "DCIM", "100MSDCF"), "DSC0", NewSessions, "SONY", "ILCE-7M4", "4410287");
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(newCard);
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 folder, string prefix, (DateTime Start, int Photos, int Interval)[] sessions, string make, string model, string body)
{
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, $"{prefix}{n:0000}.JPG");
File.WriteAllBytes(path, Photo(captured, n, make, model, body));
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, string make, string model, string body)
{
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 = make,
Model = model,
BodySerial = body,
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()
{
}
}
+82
View File
@@ -0,0 +1,82 @@
using System.IO;
using System.Net;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.App.Import;
/// <summary>
/// Import destination "Server" (BRIEF §12.4, §14.4): each verified copy staged on this PC is uploaded with the
/// protocol's resumable chunks and the hash computed while copying; the server checks that hash before it commits the
/// frame, and only then does the photo count as imported. Photos of one plan session share its session key, so the
/// server files them in one sequence — the same one when an interrupted import is started again. A typed session
/// title is set on that sequence once. A file the server refuses (a hash mismatch, a format it rejects) is listed in
/// <see cref="Report"/> and the import goes on (BRIEF §13: errors per file); a failed connection, sign-in or server
/// stops it.
/// </summary>
public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
{
private readonly HashSet<Guid> _titled = [];
public string StagingDirectory { get; } = stagingDirectory;
/// <summary>Every file committed or refused so far, by card path; pass it to <see cref="LocalImport.RunAsync"/>.</summary>
public ImportSinkReport Report { get; } = new();
public async Task<IReadOnlyList<SinkCommit>> CommitAsync(PlannedSession session, IReadOnlyList<StagedFile> files, CancellationToken cancellationToken)
{
var results = new List<SinkCommit>(files.Count);
foreach (var file in files)
{
// The server records the uploaded file name as the original name: upload the card's name, not the staging name.
var folder = Path.Combine(StagingDirectory, Path.GetFileNameWithoutExtension(file.StagedPath));
var named = Path.Combine(folder, Path.GetFileName(file.Item.SourcePath));
Directory.CreateDirectory(folder);
File.Move(file.StagedPath, named);
CompleteUploadResponse? committed = null;
try
{
committed = await client.UploadFileAsync(named, null, file.Item.CapturedAt, session.SessionKey, file.Sha256, null, cancellationToken)
.ConfigureAwait(false);
// An upload the server already held reports no position in a sequence.
var result = new SinkCommit(committed?.FrameId, file.Item.FileName, committed is null || committed.Index < 0);
Report.Committed[file.Item.SourcePath] = result;
results.Add(result);
}
catch (TitanoApiException ex) when (IsRefusal(ex))
{
// The executor has no failed commit: the refusal travels in the report, which turns this result into a failure.
Report.Rejected[file.Item.SourcePath] = ex.Error.Message;
results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false));
}
finally
{
// Our own staged copy; the original stays on the card.
File.Delete(named);
Directory.Delete(folder);
}
if (committed is { Index: >= 0 } && session.Title is { Length: > 0 } title && _titled.Add(committed.SequenceId))
await SetTitleAsync(committed.SequenceId, title, cancellationToken).ConfigureAwait(false);
}
return results;
}
/// <summary>A refused title leaves the photos imported under the sequence's own name.</summary>
private async Task SetTitleAsync(Guid sequenceId, string title, CancellationToken cancellationToken)
{
try
{
await client.UpdateSequenceAsync(sequenceId, new UpdateSequenceRequest(title, null, null, null, null, null), cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (IsRefusal(ex))
{
Log.Warning("import", $"The server refused the title of sequence {sequenceId}", ex);
}
}
/// <summary>The server refused this file; other files may still go through (unlike a busy server or a lost sign-in).</summary>
private static bool IsRefusal(TitanoApiException ex) =>
!ex.IsTransient && ex.Status is not (HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) && (int)ex.Status is >= 400 and < 500;
}
@@ -3,6 +3,7 @@ using System.IO;
using System.Net.Http;
using System.Reflection;
using Titano.App.About;
using Titano.App.Import;
using Titano.App.Jobs;
using Titano.App.Library;
using Titano.App.Server;
@@ -103,6 +104,9 @@ public sealed class AppServices : IAsyncDisposable
public IEncoderInventory Encoders { get; set; }
/// <summary>Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.</summary>
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
/// <summary>Latest public release (GitHub Releases API of the releases repository, BRIEF §18).</summary>
public Func<CancellationToken, Task<ReleaseInfo?>> CheckForUpdateAsync { get; set; }
@@ -188,6 +192,7 @@ public sealed class AppServices : IAsyncDisposable
}
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
Devices.Start();
if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token);
}
@@ -212,6 +217,7 @@ public sealed class AppServices : IAsyncDisposable
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Devices.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
@@ -17,6 +17,12 @@ public sealed record ConfirmRequest
/// <summary>Warning-outlined action (never a primary) for data-destroying choices.</summary>
public bool IsDestructive { get; init; }
/// <summary>Text the user must type before the action enables (formatting a card: its name); null asks no typing.</summary>
public string? TypedConfirmation { get; init; }
/// <summary>Label of the typing field ("Type the card name to confirm").</summary>
public string? TypedPrompt { get; init; }
}
/// <summary>Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login).</summary>
@@ -0,0 +1,74 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using Titano.App.Import;
using Titano.Core.Diagnostics;
using Titano.Core.Windows.Devices;
namespace Titano.App.Infrastructure;
/// <summary>
/// Card detection on this PC (BRIEF §13): <see cref="RemovableVolumeWatcher"/> (WM_DEVICECHANGE plus a 3-second poll),
/// safe removal through <see cref="VolumeEjector"/> and formatting only through the Windows format dialog
/// (<see cref="FormatDialog"/>, BRIEF §8.6).
/// </summary>
public sealed class WindowsDeviceMonitor : IDeviceMonitor
{
private RemovableVolumeWatcher? _watcher;
public event Action<CardDevice>? Arrived;
public event Action<CardDevice>? Removed;
public IReadOnlyList<CardDevice> Devices => _watcher is { } watcher ? [.. watcher.Volumes.Select(Map)] : [];
public void Start()
{
if (_watcher is not null) return;
var watcher = new RemovableVolumeWatcher();
watcher.VolumeArrived += (_, e) => Arrived?.Invoke(Map(e.Volume));
watcher.VolumeRemoved += (_, e) => Removed?.Invoke(Map(e.Volume));
try
{
watcher.Start();
_watcher = watcher;
}
catch (Win32Exception ex)
{
// Without the watcher cards are still listed by "Folder…"; nothing else depends on it.
Log.Warning("devices", "Card detection is unavailable", ex);
watcher.Dispose();
}
}
public EjectOutcome Eject(CardDevice device) => VolumeEjector.Eject(device.Root[0]) switch
{
EjectResult.Ejected => EjectOutcome.Ejected,
EjectResult.InUse => EjectOutcome.InUse,
_ => EjectOutcome.Failed,
};
public FormatOutcome Format(CardDevice device)
{
var owner = Application.Current?.MainWindow is { } window ? new WindowInteropHelper(window).Handle : 0;
try
{
return FormatDialog.Show(owner, device.Root[0]) switch
{
FormatDialogResult.Formatted => FormatOutcome.Formatted,
FormatDialogResult.Cancelled => FormatOutcome.Cancelled,
_ => FormatOutcome.Failed,
};
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
Log.Warning("devices", $"The format dialog cannot open for {device.Root}", ex);
return FormatOutcome.Failed;
}
}
public void Dispose() => _watcher?.Dispose();
private static CardDevice Map(VolumeInfo v) =>
new(v.RootPath, v.Label, v.SerialNumber, v.TotalBytes, v.FreeBytes, v.DriveType == VolumeDriveType.Removable, v.HasDcim);
}
+525 -3
View File
@@ -2,8 +2,530 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
<Grid Margin="20">
<ui:EmptyState Message="{l:Loc Archive.Empty}" />
xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:ar="clr-namespace:Titano.App.Archiving"
xmlns:shell="clr-namespace:Titano.App.Shell">
<UserControl.Resources>
<Style x:Key="Text.PanelHeading" TargetType="TextBlock" BasedOn="{StaticResource Text.Section}">
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style x:Key="Button.Bar" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="0,0,8,0" />
</Style>
<Style x:Key="Button.Tool" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Margin" Value="0,0,8,8" />
</Style>
<!-- Rows that only show text: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.Preview" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding To}" />
</Style>
<!-- Report rows with their own buttons: Tab reaches every button. -->
<Style x:Key="ListBoxItem.Duplicate" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Row.Title}" />
</Style>
<!-- A filter menu: its values, each checked while chosen. -->
<Style x:Key="MenuItem.Choice" TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Label}" />
<Setter Property="IsChecked" Value="{Binding IsChecked, Mode=OneWay}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Archive.FilterChoice}" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
</Style>
<!-- Dialog card (DESIGN §4: Surface, Stroke, radius 12, 24 px shadow, two buttons). -->
<Style x:Key="Border.Dialog" TargetType="Border">
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="{StaticResource Radius.Dialog}" />
<Setter Property="Padding" Value="24,18,24,20" />
<Setter Property="Effect" Value="{StaticResource Shadow.Popup}" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<DataTemplate DataType="{x:Type ar:RebuildDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{l:Loc Archive.Rebuild.Heading}" Style="{StaticResource Text.Title}" />
<ItemsControl ItemsSource="{Binding FactRows}" Focusable="False" Margin="0,14,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.Label}" />
<TextBlock Grid.Column="1" Text="{Binding Value}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Value}" Typography.NumeralAlignment="Tabular" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Text="{Binding BusyText}" Foreground="{DynamicResource Brush.TextMuted}" Visibility="{Binding BusyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,18,0,0">
<Button Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsDefault="True" IsCancel="True"
MinWidth="96" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rebuild.Start}" Command="{Binding RebuildCommand}" ToolTip="{Binding RebuildToolTip}"
MinWidth="96" Margin="8,0,0,0" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RenameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="720" MaxHeight="560">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Grid.Row="1" Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Archive.Rename.Template}" Style="{StaticResource Text.Label}" />
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Mono}" Text="{Binding Template.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Template}" ToolTip="{Binding Template.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Rename.Template}" />
</Grid>
<TextBlock Grid.Row="2" Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,6" Typography.NumeralAlignment="Tabular" />
<ListBox Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Preview}" MinHeight="120"
AutomationProperties.Name="{l:Loc Archive.Rename.Preview}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:RenameRow}">
<Grid Height="30" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="120" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="120" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding From}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{Binding From}" />
<ui:Icon Grid.Column="1" Glyph="{StaticResource Icon.Forward}" Margin="10,0" Foreground="{DynamicResource Brush.TextFaint}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding To}" ToolTip="{Binding To}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<DockPanel Grid.Row="4" Margin="0,16,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Rename.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
MinWidth="96" />
<TextBlock Text="{Binding BusyText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
</DockPanel>
</Grid>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ar:RetagDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource Grid.LabelColumn}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Archive.Retag.Add}" Style="{StaticResource Text.Label}" />
<TextBox Grid.Column="1" Text="{Binding Add.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding Add}"
ToolTip="{Binding Add.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Add}" />
<TextBlock Grid.Row="1" Text="{l:Loc Archive.Retag.Remove}" Style="{StaticResource Text.Label}" Margin="0,10,14,0" />
<TextBox Grid.Row="1" Grid.Column="1" Margin="0,10,0,0" Text="{Binding Remove.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding Remove}" ToolTip="{Binding Remove.ToolTip}" AutomationProperties.Name="{l:Loc Archive.Retag.Remove}" />
</Grid>
<TextBlock Text="{Binding SummaryText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,12,0,0" Typography.NumeralAlignment="Tabular" />
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Retag.Apply}" Command="{Binding ApplyCommand}"
ToolTip="{Binding ApplyToolTip}" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True"
MinWidth="96" />
<TextBlock Text="{Binding BusyText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid Margin="20,16" IsEnabled="{Binding IsContentEnabled}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- ===================== Toolbar (Archive.html: one row) ===================== -->
<DockPanel Margin="0,0,0,4">
<ComboBox DockPanel.Dock="Left" Width="220" VerticalAlignment="Top" ItemsSource="{Binding Archives}" SelectedItem="{Binding SelectedArchive}" DisplayMemberPath="Name"
ToolTip="{Binding ArchiveToolTip}" AutomationProperties.Name="{l:Loc Archive.Toolbar.Archive}" Margin="0,0,8,8" />
<Border DockPanel.Dock="Left" Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="4,5,12,0" VerticalAlignment="Top" />
<WrapPanel>
<Button Style="{StaticResource Button.Tool}" Content="{l:Loc Archive.Toolbar.Scan}" Command="{Binding ScanCommand}" ToolTip="{Binding ScanToolTip}" />
<Button Style="{StaticResource Button.Tool}" Content="{l:Loc Archive.Toolbar.Rebuild}" Command="{Binding RebuildCommand}" ToolTip="{l:Loc Tooltips.Archive.Rebuild}" />
<Button Style="{StaticResource Button.Tool}" Content="{l:Loc Archive.Toolbar.Verify}" Command="{Binding VerifyCommand}" ToolTip="{Binding VerifyToolTip}" />
<Button Style="{StaticResource Button.Tool}" Content="{l:Loc Archive.Toolbar.Duplicates}" Command="{Binding FindDuplicatesCommand}"
ToolTip="{Binding DuplicatesToolTip}" />
<Button Style="{StaticResource Button.Tool}" Content="{l:Loc Archive.Toolbar.Orphans}" Command="{Binding FindOrphansCommand}" ToolTip="{Binding OrphansToolTip}" />
<Button Style="{StaticResource Button.Tool}" Click="OnOpenMenu" ToolTip="{l:Loc Tooltips.Archive.Adopt}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Archive.Toolbar.AdoptMenu}" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Archive.Adopt.InPlace}" Command="{Binding AdoptCommand}" ToolTip="{l:Loc Tooltips.Archive.AdoptInPlace}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Adopt.Copy}" Command="{Binding CopyFolderCommand}" ToolTip="{l:Loc Tooltips.Archive.AdoptCopy}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
</Button.ContextMenu>
</Button>
<Button x:Name="MaintenanceButton" Style="{StaticResource Button.Tool}" Click="OnOpenMenu" ToolTip="{l:Loc Tooltips.Archive.Maintenance}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Archive.Toolbar.Maintenance}" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Archive.Maintenance.Run}" Command="{Binding MaintenanceCommand}" ToolTip="{Binding MaintenanceRunToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.DryRun}" Command="{Binding MaintenanceDryRunCommand}" ToolTip="{l:Loc Tooltips.Archive.MaintenanceDryRun}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Proxies}" Command="{Binding RebuildProxiesCommand}" ToolTip="{Binding RebuildProxiesToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Archive.Maintenance.Backup}" Command="{Binding BackupCommand}" ToolTip="{l:Loc Tooltips.Archive.Backup}" ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Archive.Maintenance.Relink}" Command="{Binding RelinkCommand}" ToolTip="{l:Loc Tooltips.Archive.Relink}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</WrapPanel>
</DockPanel>
<!-- Overview or maintenance, and when the archive was last scanned. -->
<DockPanel Grid.Row="1" Margin="0,0,0,12" Visibility="{Binding HasArchive, Converter={StaticResource BoolToVisibility}}">
<v:SegmentedControl DockPanel.Dock="Left" SelectedIndex="{Binding ViewIndex}" AutomationProperties.Name="{l:Loc Archive.View.Name}">
<v:SegmentedItem Content="{l:Loc Archive.View.Overview}" ToolTip="{l:Loc Tooltips.Archive.Overview}" AutomationProperties.Name="{l:Loc Archive.View.Overview}" />
<v:SegmentedItem Content="{l:Loc Archive.View.Maintenance}" ToolTip="{l:Loc Tooltips.Archive.MaintenanceView}"
AutomationProperties.Name="{l:Loc Archive.View.Maintenance}" />
</v:SegmentedControl>
<TextBlock Text="{Binding LastScanText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="14,0,0,0"
TextTrimming="CharacterEllipsis" Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Archive.LastScan}" />
</DockPanel>
<!-- ===================== Overview: tree, figures, charts ===================== -->
<Grid Grid.Row="2" Visibility="{Binding IsOverview, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*" MinWidth="200" MaxWidth="320" />
<ColumnDefinition Width="14" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="6,8">
<ListBox x:Name="Tree" ItemsSource="{Binding TreeRows}" SelectionMode="Extended" SelectionChanged="OnTreeSelectionChanged" PreviewKeyDown="OnTreeKeyDown"
AutomationProperties.Name="{l:Loc Archive.Tree.Name}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="MinHeight" Value="32" />
<Setter Property="Padding" Value="6,0" />
<Setter Property="ToolTip" Value="{Binding RowToolTip}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding Detail}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:ArchiveTreeRowViewModel}">
<Grid Margin="{Binding IndentMargin}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="24" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}"
Command="{Binding ToggleCommand}" ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleToolTip}" Visibility="Hidden"
Focusable="False" />
<TextBlock x:Name="Title" Grid.Column="1" Text="{Binding Title}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
<TextBlock x:Name="Detail" Grid.Column="2" Text="{Binding Detail}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" Margin="8,0,0,0"
Visibility="Collapsed" Typography.NumeralAlignment="Tabular" />
<ui:StatusGlyph x:Name="State" Grid.Column="2" Kind="{Binding AvailabilityKind}" Text="{Binding AvailabilityText}" VerticalAlignment="Center"
Margin="8,0,0,0" ToolTip="{Binding AvailabilityToolTip}" Visibility="Collapsed" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding HasChildren}" Value="True">
<Setter TargetName="Toggle" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
</DataTrigger>
<DataTrigger Binding="{Binding IsArchive}" Value="True">
<Setter TargetName="Title" Property="FontWeight" Value="SemiBold" />
<Setter TargetName="State" Property="Visibility" Value="Visible" />
<Setter TargetName="Toggle" Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding IsYear}" Value="True">
<Setter TargetName="Title" Property="FontWeight" Value="SemiBold" />
<Setter TargetName="Detail" Property="Visibility" Value="Visible" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Figure tiles (Archive.html). -->
<ItemsControl ItemsSource="{Binding Tiles}" Focusable="False" Margin="0,0,-10,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:ArchiveTile}">
<Border Style="{StaticResource Border.Panel}" Padding="14,8" Margin="0,0,10,0" ToolTip="{Binding Caption}">
<StackPanel>
<!-- A narrow tile (the window at its minimum width) shrinks the figure rather than cutting it. -->
<Viewbox StretchDirection="DownOnly" HorizontalAlignment="Left">
<TextBlock Text="{Binding Value}" FontSize="24" FontWeight="SemiBold" Typography.NumeralAlignment="Tabular" />
</Viewbox>
<TextBlock Text="{Binding Caption}" Style="{StaticResource Text.Secondary}" TextWrapping="Wrap" />
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid Grid.Row="1" Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.2*" />
<ColumnDefinition Width="12" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="14,10">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Archive.Chart.Months}" Style="{StaticResource Text.PanelHeading}" Margin="0,0,0,8" />
<v:HeatmapStrip Rows="{Binding MonthRows}" ColumnLabels="{Binding MonthLabels}" ValueFormatter="{Binding CountFormatter}" MaxCellSize="18"
ToolTip="{l:Loc Tooltips.Archive.Months}" AutomationProperties.Name="{l:Loc Archive.Chart.Months}" />
</DockPanel>
</Border>
<Border Grid.Column="2" Style="{StaticResource Border.Panel}" Padding="14,10">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Archive.Chart.Storage}" Style="{StaticResource Text.PanelHeading}" Margin="0,0,0,8" />
<v:BarChart Items="{Binding StorageBars}" MinimumOpacity="0.55" BarThickness="12" ToolTip="{l:Loc Tooltips.Archive.Storage}"
AutomationProperties.Name="{l:Loc Archive.Chart.Storage}" />
</DockPanel>
</Border>
</Grid>
<Grid Grid.Row="2" Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="12" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="14,10">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Archive.Chart.Cameras}" Style="{StaticResource Text.PanelHeading}" Margin="0,0,0,8" />
<v:BarChart Items="{Binding CameraBars}" BrushKey="Brush.Sun" MinimumOpacity="0.45" BarThickness="12" ToolTip="{l:Loc Tooltips.Archive.Cameras}"
AutomationProperties.Name="{l:Loc Archive.Chart.Cameras}" />
</DockPanel>
</Border>
<Border Grid.Column="2" Style="{StaticResource Border.Panel}" Padding="14,10">
<DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Archive.Chart.Formats}" Style="{StaticResource Text.PanelHeading}" Margin="0,0,0,8" />
<v:BarChart Items="{Binding FormatBars}" MinimumOpacity="0.35" BarThickness="12" ToolTip="{l:Loc Tooltips.Archive.Formats}"
AutomationProperties.Name="{l:Loc Archive.Chart.Formats}" />
</DockPanel>
</Border>
</Grid>
</Grid>
</Grid>
<!-- ===================== Maintenance: health, recent runs, duplicates, orphans ===================== -->
<Grid Grid.Row="2" Visibility="{Binding IsMaintenance, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="14" />
<ColumnDefinition Width="1.1*" />
</Grid.ColumnDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="16,12">
<StackPanel>
<TextBlock Text="{l:Loc Archive.Health.Title}" Style="{StaticResource Text.PanelHeading}" Margin="0,0,0,8" />
<ItemsControl ItemsSource="{Binding Health}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:HealthLineViewModel}">
<DockPanel Height="32">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="8,0,0,0" Content="{Binding FixText}" Command="{Binding FixCommand}"
ToolTip="{Binding FixToolTip}" Visibility="{Binding HasFix, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph Kind="{Binding Kind}" Text="{Binding Text}" FontSize="13" VerticalAlignment="Center" ToolTip="{Binding KindToolTip}" />
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Padding="16,12" Margin="0,14,0,0">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,8">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="0" Content="{l:Loc Archive.Recent.History}" Command="{Binding HistoryCommand}"
ToolTip="{l:Loc Tooltips.Archive.History}" />
<TextBlock Text="{l:Loc Archive.Recent.Title}" Style="{StaticResource Text.PanelHeading}" />
</DockPanel>
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Archive.Recent.Empty}" Foreground="{DynamicResource Brush.TextMuted}"
Visibility="{Binding HasRecent, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<ItemsControl ItemsSource="{Binding Recent}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:MaintenanceRow}">
<Grid Height="28">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="90" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding DateText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
<TextBlock Grid.Column="1" Text="{Binding Text}" Margin="12,0" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding Text}" />
<TextBlock Grid.Column="2" Text="{Binding StateText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DockPanel>
</Border>
</Grid>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Style="{StaticResource Border.Panel}" Padding="16,12">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,8">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="8,0,0,0" Content="{l:Loc Archive.Duplicates.Mark}"
Command="{Binding MarkDuplicatesCommand}" ToolTip="{Binding MarkDuplicatesToolTip}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="0" Content="{l:Loc Archive.Find.Run}" Command="{Binding FindDuplicatesCommand}"
ToolTip="{Binding DuplicatesToolTip}" Visibility="{Binding IsSearching, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="0" Content="{l:Loc Archive.Find.Cancel}" Command="{Binding CancelSearchCommand}"
ToolTip="{l:Loc Tooltips.Archive.CancelSearch}" Visibility="{Binding IsSearching, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{l:Loc Archive.Duplicates.Title}" Style="{StaticResource Text.PanelHeading}" />
<TextBlock Text="{Binding DuplicatesText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" VerticalAlignment="Center" />
</DockPanel>
<ListBox ItemsSource="{Binding Duplicates}" ItemContainerStyle="{StaticResource ListBoxItem.Duplicate}" AutomationProperties.Name="{l:Loc Archive.Duplicates.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DuplicateRowViewModel}">
<DockPanel Height="44">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{l:Loc Archive.Duplicates.Folder}" Command="{Binding RevealCommand}"
ToolTip="{l:Loc Tooltips.Archive.DuplicateFolder}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{l:Loc Archive.Duplicates.Open}" Command="{Binding OpenCommand}"
ToolTip="{l:Loc Tooltips.Archive.DuplicateOpen}" />
<StackPanel VerticalAlignment="Center">
<TextBlock TextTrimming="CharacterEllipsis">
<Run Text="{Binding Row.Title, Mode=OneWay}" FontWeight="SemiBold" />
<Run Text="{Binding Row.Detail, Mode=OneWay}" Foreground="{DynamicResource Brush.TextMuted}" />
</TextBlock>
<TextBlock Text="{Binding Places}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Places}" />
</StackPanel>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Border>
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Padding="16,12" Margin="0,14,0,0">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,8">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="0" Content="{l:Loc Archive.Find.Run}" Command="{Binding FindOrphansCommand}"
ToolTip="{Binding OrphansToolTip}" Visibility="{Binding IsSearching, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Margin="0" Content="{l:Loc Archive.Find.Cancel}" Command="{Binding CancelSearchCommand}"
ToolTip="{l:Loc Tooltips.Archive.CancelSearch}" Visibility="{Binding IsSearching, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{l:Loc Archive.Orphans.Title}" Style="{StaticResource Text.PanelHeading}" />
<TextBlock Text="{Binding OrphansText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" VerticalAlignment="Center" />
</DockPanel>
<ListBox ItemsSource="{Binding Orphans}" ItemContainerStyle="{StaticResource ListBoxItem.Duplicate}" AutomationProperties.Name="{l:Loc Archive.Orphans.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type ar:OrphanRowViewModel}">
<DockPanel Height="44">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Row}" Content="{Binding FixText}" Command="{Binding FixCommand}" ToolTip="{Binding FixToolTip}" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Row.Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" ToolTip="{Binding Row.Title}" />
<ui:StatusGlyph Kind="{Binding Kind}" Text="{Binding Row.Detail}" FontSize="12" ToolTip="{Binding KindText}" />
</StackPanel>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Border>
</Grid>
</Grid>
<!-- ===================== Mass operations on the selected, filtered set ===================== -->
<Border Grid.Row="3" Style="{StaticResource Border.Panel}" Padding="14,8,6,0" Margin="0,14,0,0" MinHeight="48"
Visibility="{Binding IsOverview, Converter={StaticResource BoolToVisibility}}">
<WrapPanel VerticalAlignment="Center">
<TextBlock Text="{l:Loc Archive.Set.Label}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="0,0,10,8" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" BorderBrush="{DynamicResource Brush.Accent}" Click="OnOpenMenu" ToolTip="{l:Loc Tooltips.Archive.Set}"
AutomationProperties.Name="{l:Loc Archive.Set.Filter}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding SetText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" MaxWidth="260" TextTrimming="CharacterEllipsis" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Library.Filter.Camera}" ItemsSource="{Binding CameraChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterCamera}" />
<MenuItem Header="{l:Loc Library.Filter.Status}" ItemsSource="{Binding StatusChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterStatus}" />
<MenuItem Header="{l:Loc Library.Filter.Tags}" ItemsSource="{Binding TagChoices}" ItemContainerStyle="{StaticResource MenuItem.Choice}"
ToolTip="{l:Loc Tooltips.Archive.FilterTag}" />
<Separator />
<MenuItem Header="{l:Loc Archive.Set.ClearFilter}" Command="{Binding ClearFilterCommand}" ToolTip="{l:Loc Tooltips.Archive.ClearFilter}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
</Button.ContextMenu>
</Button>
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="4,0,12,8" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Analyse}" Command="{Binding AnalyseSetCommand}" ToolTip="{Binding AnalyseSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Proxies}" Command="{Binding ProxiesSetCommand}" ToolTip="{Binding ProxiesSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Thumbnails}" Command="{Binding ThumbnailsSetCommand}"
ToolTip="{Binding ThumbnailsSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Verify}" Command="{Binding VerifySetCommand}" ToolTip="{Binding VerifySetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Rename}" Command="{Binding RenameSetCommand}" ToolTip="{Binding RenameSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Move}" Command="{Binding MoveSetCommand}" ToolTip="{Binding MoveSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Retag}" Command="{Binding RetagSetCommand}" ToolTip="{Binding RetagSetToolTip}" />
<Button Style="{StaticResource Button.Bar}" Margin="0,0,8,8" Content="{l:Loc Archive.Set.Export}" Command="{Binding ExportSetCommand}" ToolTip="{Binding ExportSetToolTip}" />
</WrapPanel>
</Border>
<ui:EmptyState Grid.Row="2" Message="{l:Loc Archive.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Archive.Toolbar.Adopt}" Command="{Binding AdoptCommand}" ToolTip="{l:Loc Tooltips.Archive.Adopt}" />
</ui:EmptyState>
</Grid>
<!-- In-window dialogs (rebuild, rename, retag) over a scrim; the keyboard stays inside the dialog. -->
<Grid Visibility="{Binding IsDialogOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border Background="{DynamicResource Brush.Scrim}" />
<ContentPresenter x:Name="DialogHost" Content="{Binding Dialog}" Margin="20" />
</Grid>
</Grid>
</UserControl>
+97 -1
View File
@@ -1,8 +1,104 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using Titano.App.Archiving;
namespace Titano.App.Sections;
public partial class ArchiveView : UserControl
{
public ArchiveView() => InitializeComponent();
private bool _restoring;
private string? _focusKey;
public ArchiveView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
Tree.GotKeyboardFocus += (_, e) =>
{
if (e.NewFocus is ListBoxItem { DataContext: ArchiveTreeRowViewModel row }) _focusKey = row.Node.Key;
};
}
private ArchiveViewModel? Model => DataContext as ArchiveViewModel;
/// <summary>"Adopt folder ▾", "Maintenance ▾" and the set filter open their menu under themselves.</summary>
private void OnOpenMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
menu.DataContext = DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is ArchiveViewModel old)
{
old.RowsRebuilt -= RestoreSelection;
old.PropertyChanged -= OnModelChanged;
}
if (e.NewValue is ArchiveViewModel model)
{
model.RowsRebuilt += RestoreSelection;
model.PropertyChanged += OnModelChanged;
}
}
/// <summary>The selected tree rows are the set the mass operations act on.</summary>
private void OnTreeSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!_restoring) Model?.SetSelection(Tree.SelectedItems.OfType<ArchiveTreeRowViewModel>());
}
/// <summary>The rows were rebuilt (a reload, a year opened or closed): the list shows the same selection and keeps the keyboard where it was.</summary>
private void RestoreSelection()
{
if (Model is not { } model) return;
// The rebuild removed the focused row's container; the keyboard goes back to the row with the same key.
var refocus = Tree.IsKeyboardFocusWithin || Keyboard.FocusedElement is null ? _focusKey : null;
_restoring = true;
try
{
Tree.SelectedItems.Clear();
foreach (var row in model.TreeRows.Where(model.IsSelectedRow)) Tree.SelectedItems.Add(row);
}
finally
{
_restoring = false;
}
if (refocus is null || model.TreeRows.FirstOrDefault(r => r.Node.Key == refocus) is not { } again) return;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
{
Tree.ScrollIntoView(again);
(Tree.ItemContainerGenerator.ContainerFromItem(again) as ListBoxItem)?.Focus();
});
}
/// <summary>On a year: Right opens it, Left closes it, Enter toggles it.</summary>
private void OnTreeKeyDown(object sender, KeyEventArgs e)
{
if (Model is not { } model || Keyboard.FocusedElement is not ListBoxItem { DataContext: ArchiveTreeRowViewModel row } || !row.HasChildren || row.IsArchive) return;
var toggle = e.Key switch
{
Key.Right => !row.IsExpanded,
Key.Left => row.IsExpanded,
Key.Enter => true,
_ => false,
};
if (!toggle) return;
model.Toggle(row);
e.Handled = true;
}
/// <summary>A dialog that opens takes the keyboard: its first field or button.</summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(ArchiveViewModel.Dialog) || Model?.Dialog is null || !IsVisible) return;
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
}
}
+857 -3
View File
@@ -1,9 +1,863 @@
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).</summary>
public sealed class ArchiveViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Archive, "Icon.Archive")
/// <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), and the operations on the whole archive as jobs (scan, rebuild with its dialog, verify,
/// maintenance), plus the maintenance view: index health, duplicates and orphans with safe fixes, recent runs. The
/// tree selection is only ever changed by the user: reloads and expanding keep it.
/// </summary>
public sealed class ArchiveViewModel : SectionViewModel
{
public ShellViewModel Shell { get; } = shell;
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;
private ArchiveStats? _stats;
private ArchiveTree? _tree;
private int _viewIndex;
private bool _loaded;
private Task _load = Task.CompletedTask;
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)), IsOnline);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
BackupCommand = new AsyncRelayCommand(BackupAsync, () => Services.Database is not null);
MaintenanceCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a)), IsOnline);
MaintenanceDryRunCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Maintenance(a, dryRun: true)), () => _archive is not null);
RebuildProxiesCommand = new AsyncRelayCommand(() => QueueSetAsync(ids => ArchiveJobs.Proxies(ids, _archive!.Name, force: true), All()), IsOnline);
ClearFilterCommand = new RelayCommand(() => Filter = new ArchiveSetFilter(), () => !_filter.IsEmpty);
RelinkCommand = new AsyncRelayCommand(RelinkAsync);
HistoryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs));
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);
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;
_archive = value;
_duplicates = null;
_orphans = null;
_ = LoadAsync();
}
}
public bool HasArchive => _archive is not null;
public string ArchiveToolTip => _archive is null ? Loc.L("Tooltips.Archive.Pick") : Loc.L("Tooltips.Archive.PickRoot", _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 ICommand ScanCommand { get; }
public ICommand RebuildCommand { get; }
public ICommand VerifyCommand { get; }
public ICommand AdoptCommand { get; }
/// <summary>"Adopt folder ▾ › Copy into the layout": the Import screen copies the folder into the archive with its templates.</summary>
public ICommand CopyFolderCommand { get; }
public ICommand BackupCommand { get; }
public ICommand MaintenanceCommand { get; }
public ICommand MaintenanceDryRunCommand { get; }
public ICommand RebuildProxiesCommand { get; }
public ICommand RelinkCommand { get; }
public ICommand HistoryCommand { 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>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 + " · " + _filter.Describe();
}
}
/// <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>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)) OnPropertyChanged(nameof(DuplicatesText));
}
}
public IReadOnlyList<OrphanRowViewModel>? Orphans
{
get => _orphans;
private set
{
if (Set(ref _orphans, value)) OnPropertyChanged(nameof(OrphansText));
}
}
/// <summary>A duplicates or orphans search runs; it can be cancelled.</summary>
public bool IsSearching => _search is not null;
/// <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); 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; joins a read in progress.</summary>
public Task LoadAsync() => _load.IsCompleted ? _load = ReadAsync() : _load;
private async Task ReadAsync()
{
if (Services.Database is not { } db) return;
try
{
AttachJobEvents();
Archives = await db.Archives.ListAsync();
_archive = _archive is { } current ? Archives.FirstOrDefault(a => a.Id == current.Id) : null;
_archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath);
if (_archive is not { } archive) return;
var root = archive.RootPath;
_availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
_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 });
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>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 || 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);
}
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)
{
Tiles = ArchiveFigures.Tiles(stats);
MonthRows = [.. ArchiveFigures.PhotosPerMonth(stats, DateTime.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));
Health =
[
.. ArchiveFigures.Health(stats, withoutProxies).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.Orphans => FindOrphansCommand,
_ => null,
})),
];
}
private static IReadOnlyList<ChartItem> Bars(IReadOnlyList<BarValue> values) =>
[.. values.Select(v => new ChartItem(v.Label, v.Value, v.ValueText, v.ToolTip))];
/// <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(CameraChoices));
OnPropertyChanged(nameof(StatusChoices));
OnPropertyChanged(nameof(TagChoices));
OnPropertyChanged(nameof(AnalyseSetToolTip));
OnPropertyChanged(nameof(ProxiesSetToolTip));
OnPropertyChanged(nameof(ThumbnailsSetToolTip));
OnPropertyChanged(nameof(VerifySetToolTip));
OnPropertyChanged(nameof(ExportSetToolTip));
OnPropertyChanged(nameof(RenameSetToolTip));
OnPropertyChanged(nameof(MoveSetToolTip));
OnPropertyChanged(nameof(RetagSetToolTip));
CommandManager.InvalidateRequerySuggested();
}
private IEnumerable<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)));
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() => _archive is not null && _availability == ArchiveAvailability.Online;
/// <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) : 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();
}
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"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
() => ShellActions.Reveal(path));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or NotSupportedException)
{
Log.Warning("archive", "Database backup failed", ex);
Shell.Notify(Loc.L("Archive.Backup.Failed"), ex.Message);
}
}
/// <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), archive.RootPath);
await LoadAsync();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", $"Relinking {folder} failed", ex);
Shell.Notify(Loc.L("Archive.Relink.Failed"), ex.Message);
}
}
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 = LibraryViewModel.Csv(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);
Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
{
}
catch (DatabaseException ex)
{
Shell.ReportError(ex);
}
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);
Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
Log.Info("archive", $"Orphans search in {archive.RootPath}: {report.UnindexedFiles} unlisted, {report.MissingFiles} missing, "
+ $"{report.MissingSequences.Count} rows without sidecar, {report.UnindexedFolders.Count} new folders");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArchiveOfflineException or DatabaseException)
{
Log.Warning("archive", "Orphan search failed", ex);
Shell.Notify(Loc.L("Archive.Orphans.Failed"), ex.Message);
}
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(IsSearching));
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 ArchiveOfflineException or DatabaseException
or ArgumentException)
{
Log.Warning("archive", $"Fixing {row.Title} failed", ex);
Shell.Notify(Loc.L("Archive.Orphans.FixFailed"), ex.Message);
}
}
}
+587 -3
View File
@@ -2,8 +2,592 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
<Grid Margin="20">
<ui:EmptyState Message="{l:Loc Import.Empty}" />
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
xmlns:imp="clr-namespace:Titano.App.Import"
xmlns:shell="clr-namespace:Titano.App.Shell">
<UserControl.InputBindings>
<KeyBinding Key="Enter" Modifiers="Control" Command="{Binding StartCommand}" />
</UserControl.InputBindings>
<UserControl.Resources>
<!-- Devices list entry (Import.html): 54 px, Surface fill, Stroke border; selected = accent border. -->
<Style x:Key="ListBoxItem.Device" TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="Height" Value="54" />
<Setter Property="Margin" Value="0,0,0,8" />
<Setter Property="Padding" Value="12,0" />
<Setter Property="Background" Value="{DynamicResource Brush.Surface}" />
<Setter Property="ToolTip" Value="{Binding StateText}" />
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="Bd" Background="{DynamicResource Brush.Surface}" BorderThickness="1" BorderBrush="{DynamicResource Brush.Stroke}"
CornerRadius="{StaticResource Radius.Control}" Padding="{TemplateBinding Padding}">
<ContentPresenter VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- One form line: a label column at least 116 px wide, as wide as the longest label of the form, then the controls (Import.html grid). -->
<Style x:Key="Import.Row" TargetType="HeaderedContentControl">
<Setter Property="Focusable" Value="False" />
<Setter Property="Margin" Value="0,0,0,10" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="HeaderedContentControl">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="ImportLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{TemplateBinding Header}" Style="{StaticResource Text.Label}" TextTrimming="None" VerticalAlignment="Top" Margin="0,6,12,0" />
<ContentPresenter Grid.Column="1" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Import.Choice" TargetType="FrameworkElement">
<Setter Property="Margin" Value="0,4,18,4" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="RadioButton" BasedOn="{StaticResource {x:Type RadioButton}}">
<Setter Property="Margin" Value="0,4,18,4" />
</Style>
<Style TargetType="CheckBox" BasedOn="{StaticResource {x:Type CheckBox}}">
<Setter Property="Margin" Value="0,4,18,4" />
</Style>
<Style x:Key="TextBox.Small" TargetType="TextBox" BasedOn="{StaticResource TextBox.Number}">
<Setter Property="Width" Value="56" />
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="6,0" />
</Style>
<!-- Session table columns, shared by header and rows. -->
<Style x:Key="Session.Grid" TargetType="Grid">
<Setter Property="Height" Value="34" />
</Style>
<Style x:Key="ListBoxItem.Session" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
<Setter Property="AutomationProperties.Name" Value="{Binding Row.TimeText}" />
</Style>
<!-- Show plan and failure rows: focusable, so the arrow keys move through a long list. -->
<Style x:Key="ListBoxItem.PlanRow" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding Source}" />
</Style>
<Style x:Key="ListBoxItem.Failure" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="Padding" Value="0" />
<Setter Property="AutomationProperties.Name" Value="{Binding}" />
</Style>
<!-- "Folder…" (Import.html): transparent, 1 px dashed Stroke border. -->
<Style x:Key="Button.Dashed" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Rectangle x:Name="Edge" Fill="Transparent" Stroke="{DynamicResource Brush.Stroke}" StrokeThickness="1" StrokeDashArray="4 3" RadiusX="6" RadiusY="6" />
<ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Edge" Property="Fill" Value="{DynamicResource Brush.Card}" />
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="Edge" Property="Stroke" Value="{DynamicResource Brush.Accent}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.4" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid Margin="20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.36*" MinWidth="220" MaxWidth="300" />
<ColumnDefinition Width="16" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- ===================== Devices ===================== -->
<DockPanel>
<DockPanel DockPanel.Dock="Top" Height="32" Margin="0,0,0,8">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Icon}" ui:ButtonIcon.Glyph="{StaticResource Icon.Refresh}" Command="{Binding RefreshCommand}"
ToolTip="{l:Loc Tooltips.Import.Refresh}" AutomationProperties.Name="{l:Loc Import.Devices.Refresh}" />
<TextBlock Text="{l:Loc Import.Devices.Title}" Style="{StaticResource Text.Section}" VerticalAlignment="Center" />
</DockPanel>
<CheckBox DockPanel.Dock="Bottom" Margin="0,8,0,0" IsChecked="{Binding AutoImport}" IsEnabled="{Binding CanAutoImport}" ToolTip="{Binding AutoImportToolTip}"
VerticalContentAlignment="Top">
<TextBlock Text="{l:Loc Import.Devices.Auto}" TextWrapping="Wrap" Foreground="{DynamicResource Brush.TextMuted}" />
</CheckBox>
<ScrollViewer VerticalScrollBarVisibility="Auto" Focusable="False" IsEnabled="{Binding CanChangeSource}">
<StackPanel>
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}" ItemContainerStyle="{StaticResource ListBoxItem.Device}"
AutomationProperties.Name="{l:Loc Import.Devices.Title}">
<!-- The surrounding ScrollViewer scrolls the list and "Folder…" together (Import.html: Folder… follows the cards). -->
<ListBox.Template>
<ControlTemplate TargetType="ListBox">
<ItemsPresenter />
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:ImportSource}">
<Grid x:Name="Root">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:Icon x:Name="Glyph" Glyph="{StaticResource Icon.Card}" Size="18" Margin="0,0,10,0" VerticalAlignment="Center" />
<StackPanel Grid.Column="1" VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding Subtitle}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" Margin="0,2,0,0" />
</StackPanel>
<ui:StatusGlyph x:Name="State" Grid.Column="2" Kind="Online" Margin="8,0,0,0" VerticalAlignment="Center" ToolTip="{Binding StateText}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Kind}" Value="Drive">
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Drive}" />
<Setter TargetName="State" Property="Kind" Value="Offline" />
<Setter TargetName="Root" Property="TextElement.Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Folder">
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Folder}" />
<Setter TargetName="State" Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding IsKnown}" Value="False">
<Setter TargetName="State" Property="Kind" Value="Offline" />
</DataTrigger>
<DataTrigger Binding="{Binding IsInserted}" Value="False">
<Setter TargetName="Root" Property="Opacity" Value="0.6" />
<Setter TargetName="State" Property="Kind" Value="Offline" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Style="{StaticResource Button.Dashed}" Height="44" HorizontalContentAlignment="Left" Command="{Binding PickFolderCommand}" ToolTip="{l:Loc Tooltips.Import.Folder}">
<StackPanel Orientation="Horizontal">
<ui:Icon Glyph="{StaticResource Icon.Folder}" Margin="0,0,10,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Text="{l:Loc Import.Devices.Folder}" Foreground="{DynamicResource Brush.TextMuted}" />
</StackPanel>
</Button>
</StackPanel>
</ScrollViewer>
</DockPanel>
<!-- ===================== Profile, form and plan ===================== -->
<Border Grid.Column="2" Style="{StaticResource Border.Panel}" Padding="20,16">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Profile header: nickname (or its field for a new card), identity, Edit ▾. -->
<DockPanel Margin="0,0,0,14" MinHeight="32">
<Button x:Name="EditButton" DockPanel.Dock="Right" Click="OnOpenMenu" IsEnabled="{Binding CanEditProfile}" ToolTip="{Binding EditToolTip}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Import.Profile.Edit}" VerticalAlignment="Center" />
<ui:Icon Glyph="{StaticResource Icon.ChevronDown}" Margin="6,0,0,0" />
</StackPanel>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="{l:Loc Import.Profile.Rename}" Command="{Binding RenameCommand}" ToolTip="{l:Loc Tooltips.Import.Rename}" />
<MenuItem Header="{l:Loc Import.Profile.Camera}" Command="{Binding FollowCameraCommand}" IsCheckable="False" IsChecked="{Binding FollowsCamera, Mode=OneWay}"
ToolTip="{Binding FollowCameraToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Import.Profile.CopyFrom}" ItemsSource="{Binding OtherCards}" ToolTip="{l:Loc Tooltips.Import.CopyFrom}">
<MenuItem.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Import.CopyFrom}" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
<Separator />
<MenuItem Header="{l:Loc Import.Profile.Forget}" Command="{Binding ForgetCommand}" ToolTip="{l:Loc Tooltips.Import.Forget}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding SourceTitle}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" MaxWidth="320" TextTrimming="CharacterEllipsis"
Visibility="{Binding IsNicknameOpen, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<TextBox x:Name="NicknameBox" Width="240" Text="{Binding Nickname.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Nickname}"
ui:Field.Placeholder="{l:Loc Import.Profile.Nickname}" ToolTip="{Binding Nickname.ToolTip}" AutomationProperties.Name="{l:Loc Import.Profile.Nickname}"
Visibility="{Binding IsNicknameOpen, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
<TextBlock Text="{Binding IdentityText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" Margin="12,0,12,0"
TextTrimming="CharacterEllipsis" ToolTip="{Binding IdentityText}" />
</DockPanel>
<!-- The form (Import.html grid). -->
<StackPanel Grid.Row="1" IsEnabled="{Binding IsFormEnabled}" Grid.IsSharedSizeScope="True">
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Destination}">
<WrapPanel>
<RadioButton GroupName="Destination" Content="{l:Loc Import.Destination.Archive}" IsChecked="{Binding IsArchiveDestination}"
IsEnabled="{Binding CanUseArchive}" ToolTip="{Binding ArchiveToolTip}" />
<RadioButton GroupName="Destination" Content="{l:Loc Import.Destination.Folder}" IsChecked="{Binding IsFolderDestination}"
ToolTip="{l:Loc Tooltips.Import.FolderDestination}" Margin="0,4,8,4" />
<TextBox Width="190" Height="30" Text="{Binding FolderPath.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding FolderPath}" ToolTip="{Binding FolderPath.ToolTip}" AutomationProperties.Name="{l:Loc Import.Destination.Folder}"
ui:Field.Placeholder="{l:Loc Import.Destination.FolderPlaceholder}" />
<Button Style="{StaticResource Button.Icon}" Width="30" MinWidth="30" Height="30" Margin="6,0,18,0" Content="…" Command="{Binding ChooseDestinationCommand}"
ToolTip="{l:Loc Tooltips.Import.ChooseFolder}" AutomationProperties.Name="{l:Loc Import.Destination.Choose}" />
<RadioButton GroupName="Destination" IsChecked="{Binding IsServerDestination}" IsEnabled="{Binding CanUseServer}" ToolTip="{Binding ServerToolTip}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{l:Loc Import.Destination.Server}" />
<ui:Icon Glyph="{StaticResource Icon.Server}" Margin="10,0,6,0" Foreground="{DynamicResource Brush.Accent}" />
<TextBlock Text="{Binding ServerName}" Foreground="{DynamicResource Brush.Accent}" />
</StackPanel>
</RadioButton>
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Scan}">
<WrapPanel>
<CheckBox Content="{l:Loc Import.Scan.Subfolders}" IsChecked="{Binding IncludeSubfolders}" ToolTip="{l:Loc Tooltips.Import.Subfolders}" />
<CheckBox Content="{l:Loc Import.Scan.Sessions}" IsChecked="{Binding SplitSessions}" ToolTip="{l:Loc Tooltips.Import.Sessions}" />
<StackPanel Orientation="Horizontal" Style="{StaticResource Import.Choice}" IsEnabled="{Binding SplitSessions}">
<TextBlock Text="{l:Loc Import.Scan.Gap}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
<TextBox Style="{StaticResource TextBox.Small}" Text="{Binding GapMinutes.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding GapMinutes}" ToolTip="{Binding GapMinutes.ToolTip}" AutomationProperties.Name="{l:Loc Import.Scan.GapName}" />
<TextBlock Text="{l:Loc Import.Scan.Minutes}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal" Style="{StaticResource Import.Choice}">
<TextBlock Text="{l:Loc Import.Scan.Minimum}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
<TextBox Style="{StaticResource TextBox.Small}" Text="{Binding MinimumFrames.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding MinimumFrames}" ToolTip="{Binding MinimumFrames.ToolTip}" AutomationProperties.Name="{l:Loc Import.Scan.MinimumName}" />
<TextBlock Text="{l:Loc Import.Scan.Frames}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" />
</StackPanel>
<CheckBox Content="{l:Loc Import.Scan.Verify}" IsChecked="{Binding VerifyCopies}" ToolTip="{l:Loc Tooltips.Import.Verify}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Names}">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="140" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" MinWidth="140" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Style="{StaticResource TextBox.Mono}" Height="30" Text="{Binding FolderTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding FolderTemplate}" ToolTip="{Binding FolderTemplate.ToolTip}" GotKeyboardFocus="OnFolderTemplateFocus"
AutomationProperties.Name="{l:Loc Import.Names.Folder}" />
<TextBlock Grid.Column="1" Text="/" Foreground="{DynamicResource Brush.TextFaint}" Margin="10,0" VerticalAlignment="Center" />
<TextBox Grid.Column="2" Style="{StaticResource TextBox.Mono}" Height="30"
Text="{Binding FileTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" shell:EditBehavior.Field="{Binding FileTemplate}"
ToolTip="{Binding FileTemplate.ToolTip}" GotKeyboardFocus="OnFileTemplateFocus" AutomationProperties.Name="{l:Loc Import.Names.File}" />
<Button x:Name="TokensButton" Grid.Column="3" Style="{StaticResource Button.Icon}" Width="30" MinWidth="30" Height="30" Margin="10,0,0,0" Content="{}{ }"
Click="OnOpenMenu" ToolTip="{l:Loc Tooltips.Import.Tokens}" AutomationProperties.Name="{l:Loc Import.Names.Tokens}">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding Tokens}" MaxHeight="420">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<Setter Property="Header" Value="{Binding Text}" />
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
<Setter Property="Command" Value="{Binding DataContext.InsertTokenCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
<Setter Property="CommandParameter" Value="{Binding}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
<TextBlock Text="{Binding NamePreview}" Style="{StaticResource Text.Secondary}" Foreground="{DynamicResource Brush.TextFaint}" Margin="0,6,0,0"
TextTrimming="CharacterEllipsis" ToolTip="{Binding NamePreview}" />
</StackPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.Duplicates}">
<WrapPanel>
<RadioButton GroupName="Duplicates" Content="{l:Loc Import.Duplicates.Skip}" IsChecked="{Binding SkipDuplicates}" ToolTip="{l:Loc Tooltips.Import.Skip}" />
<RadioButton GroupName="Duplicates" Content="{l:Loc Import.Duplicates.Again}" IsChecked="{Binding ImportDuplicatesAgain}" ToolTip="{l:Loc Tooltips.Import.Again}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Import.Row}" Header="{l:Loc Import.Label.After}" Margin="0">
<WrapPanel>
<RadioButton GroupName="After" Content="{l:Loc Import.After.Keep}" IsChecked="{Binding KeepCard}" ToolTip="{l:Loc Tooltips.Import.Keep}" />
<RadioButton GroupName="After" Content="{l:Loc Import.After.Delete}" IsChecked="{Binding DeleteImported}" IsEnabled="{Binding CardActionsApply}"
ToolTip="{Binding DeleteChoiceToolTip}" />
<RadioButton GroupName="After" Content="{l:Loc Import.After.Format}" IsChecked="{Binding FormatCard}" IsEnabled="{Binding CardActionsApply}"
ToolTip="{Binding FormatChoiceToolTip}" />
<Border Width="1" Height="20" Background="{DynamicResource Brush.Stroke}" Margin="0,0,18,0" VerticalAlignment="Center" />
<CheckBox Content="{l:Loc Import.After.Eject}" IsChecked="{Binding Eject}" ToolTip="{l:Loc Tooltips.Import.EjectChoice}" />
<CheckBox Content="{l:Loc Import.After.Deep}" IsChecked="{Binding DeepAnalysis}" IsEnabled="{Binding IsArchiveDestination}" ToolTip="{Binding DeepToolTip}" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
<!-- ===================== Plan panel ===================== -->
<Border Grid.Row="2" Style="{StaticResource Border.Card}" Padding="16,14" Margin="0,14,0,0" IsEnabled="{Binding IsPlanPanelEnabled}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel Margin="0,0,0,10">
<TextBlock DockPanel.Dock="Left" Text="{l:Loc Import.Plan.Title}" Style="{StaticResource Text.Section}" VerticalAlignment="Center" />
<TextBlock DockPanel.Dock="Right" Text="{Binding SpaceText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="12,0,0,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Import.Space}" Visibility="{Binding IsSpaceShort, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Warning" Text="{Binding SpaceText}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Import.Space}" Visibility="{Binding IsSpaceShort, Converter={StaticResource BoolToVisibility}}" />
<TextBlock DockPanel.Dock="Right" Text="{Binding ImportedBeforeText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="12,0,0,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Import.ImportedBefore}" />
<ui:StatusGlyph DockPanel.Dock="Right" Kind="{Binding DuplicatesKind}" Text="{Binding DuplicatesText}" FontSize="13" Margin="12,0,0,0" VerticalAlignment="Center"
ToolTip="{l:Loc Tooltips.Import.Duplicates}" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding TotalsText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="12,0,0,0" VerticalAlignment="Center"
Typography.NumeralAlignment="Tabular" TextTrimming="CharacterEllipsis" ToolTip="{Binding TotalsText}" />
</DockPanel>
<!-- No source, reading the card, or the reason no plan can be made. -->
<StackPanel Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding ShowsStatus, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding StatusText}" Foreground="{DynamicResource Brush.TextMuted}" TextAlignment="Center" TextWrapping="Wrap" MaxWidth="420" />
<ProgressBar IsIndeterminate="{Binding IsBusyPlanning}" Width="240" Margin="0,12,0,0"
Visibility="{Binding IsBusyPlanning, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
<!-- Sessions of the plan with editable titles. -->
<Grid Grid.Row="1" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}" Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid TextElement.FontSize="12" Margin="0,0,0,4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.35*" MinWidth="110" />
<ColumnDefinition Width="0.85*" MinWidth="70" />
<ColumnDefinition Width="0.6*" MinWidth="56" />
<ColumnDefinition Width="0.8*" MinWidth="64" />
<ColumnDefinition Width="1.9*" MinWidth="150" />
<ColumnDefinition Width="Auto" SharedSizeGroup="SessionAction" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Session}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Frames}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Size}" Margin="10,0,0,0" TextAlignment="Right" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Camera}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Sequence}" Margin="10,0,0,0" />
</Grid>
<ListBox Grid.Row="1" ItemsSource="{Binding Sessions}" ItemContainerStyle="{StaticResource ListBoxItem.Session}" AutomationProperties.Name="{l:Loc Import.Plan.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:ImportSessionRowViewModel}">
<Grid Style="{StaticResource Session.Grid}" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.35*" MinWidth="110" />
<ColumnDefinition Width="0.85*" MinWidth="70" />
<ColumnDefinition Width="0.6*" MinWidth="56" />
<ColumnDefinition Width="0.8*" MinWidth="64" />
<ColumnDefinition Width="1.9*" MinWidth="150" />
<ColumnDefinition Width="Auto" SharedSizeGroup="SessionAction" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Row.TimeText}" ToolTip="{Binding Row.TimeText}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Row.FramesText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.CellNumber}" Text="{Binding Row.SizeText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding Row.CameraText}" Margin="10,0,0,0" ToolTip="{Binding Row.CameraText}" />
<DockPanel Grid.Column="4" Margin="10,0,0,0">
<TextBlock x:Name="Target" DockPanel.Dock="Right" Text="{l:Loc Import.Session.NewShort}" Foreground="{DynamicResource Brush.Accent}"
VerticalAlignment="Center" Margin="8,0,0,0" ToolTip="{Binding Row.TargetText}" />
<TextBox Height="26" Padding="8,0" Text="{Binding Title.Text, UpdateSourceTrigger=PropertyChanged}" shell:EditBehavior.Field="{Binding Title}"
IsEnabled="{Binding IsEditable}" ui:Field.Placeholder="{Binding Placeholder}" ToolTip="{Binding TitleToolTip}" ToolTipService.ShowOnDisabled="True"
AutomationProperties.Name="{l:Loc Import.Session.Column.Sequence}" />
</DockPanel>
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Margin="8,0,0,0" Content="{l:Loc Import.Session.Merge}" Command="{Binding MergeCommand}"
ToolTip="{Binding MergeToolTip}" Visibility="{Binding HasMerge, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Row.IsNew}" Value="False">
<Setter TargetName="Target" Property="Text" Value="{l:Loc Import.Session.AddsShort}" />
<Setter TargetName="Target" Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
<!-- The verification result and the after-import actions. -->
<Grid Grid.Row="1" Grid.RowSpan="2" DataContext="{Binding Result}" Visibility="{Binding DataContext.IsDone, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BoolToVisibility}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<ui:StatusGlyph Kind="{Binding ResultKind}" Text="{Binding ResultText}" FontSize="16" FontWeight="SemiBold" ToolTip="{l:Loc Tooltips.Import.Result}" />
<TextBlock Text="{Binding DetailText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Failures}" Margin="0,8,0,0" ItemContainerStyle="{StaticResource ListBoxItem.Failure}"
Visibility="{Binding HasFailures, Converter={StaticResource BoolToVisibility}}" AutomationProperties.Name="{l:Loc Import.Result.FailuresName}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Style="{StaticResource Text.Cell}" Foreground="{DynamicResource Brush.Error}" Height="28" Padding="0,6,0,0" ToolTip="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Grid.Row="2" Margin="0,10,0,0" Visibility="{Binding OffersCheck, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{Binding EraseText}" Typography.NumeralAlignment="Tabular" />
<TextBlock Text="{Binding BusyText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,4,0,0"
Visibility="{Binding BusyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<ItemsControl ItemsSource="{Binding KeptReasons}" Focusable="False" MaxHeight="80" Margin="0,4,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ui:StatusGlyph Kind="Warning" Text="{Binding}" FontSize="12" ToolTip="{l:Loc Tooltips.Import.Kept}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<WrapPanel Grid.Row="3" Margin="0,12,0,0">
<Button Content="{l:Loc Import.Result.Check}" Command="{Binding CheckCommand}" ToolTip="{Binding CheckToolTip}" Margin="0,0,8,0"
Visibility="{Binding OffersCheck, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Destructive}" Content="{Binding DeleteText}" Command="{Binding DeleteCommand}" ToolTip="{Binding DeleteToolTip}"
Margin="0,0,8,0" Visibility="{Binding OffersDelete, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Destructive}" Content="{l:Loc Import.Result.Format}" Command="{Binding FormatCommand}" ToolTip="{Binding FormatToolTip}"
Margin="0,0,8,0" Visibility="{Binding OffersFormat, Converter={StaticResource BoolToVisibility}}" />
<Button Command="{Binding EjectCommand}" ToolTip="{Binding EjectToolTip}" Margin="0,0,8,0">
<StackPanel Orientation="Horizontal">
<ui:Icon Glyph="{StaticResource Icon.Eject}" Margin="0,0,6,0" />
<TextBlock Text="{l:Loc Import.Result.Eject}" />
</StackPanel>
</Button>
<Button Content="{l:Loc Import.Result.Library}" Command="{Binding OpenLibraryCommand}" ToolTip="{l:Loc Tooltips.Import.Library}" Margin="0,0,8,0" />
<Button Content="{l:Loc Import.Result.New}" Command="{Binding DataContext.NewImportCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
ToolTip="{l:Loc Tooltips.Import.New}" />
</WrapPanel>
</Grid>
<!-- The import failed or was cancelled. -->
<StackPanel Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding IsFailed, Converter={StaticResource BoolToVisibility}}">
<ui:StatusGlyph Kind="Failed" Text="{Binding ErrorText}" FontSize="13" HorizontalAlignment="Center" ToolTip="{l:Loc Tooltips.Import.Failed}" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,12,0,0">
<Button Content="{l:Loc Import.Failed.Retry}" Command="{Binding RetryCommand}" ToolTip="{l:Loc Tooltips.Import.Retry}" Margin="0,0,8,0" />
<Button Content="{l:Loc Shell.Nav.Jobs}" Command="{Binding Shell.NavigateCommand}" CommandParameter="Jobs" ToolTip="{l:Loc Tooltips.Nav.Jobs}" />
</StackPanel>
</StackPanel>
<!-- Footer: Show plan and Import, or the progress while copying. -->
<DockPanel Grid.Row="2" Margin="0,10,0,0" Visibility="{Binding HasPlan, Converter={StaticResource BoolToVisibility}}">
<Button x:Name="ShowPlanButton" DockPanel.Dock="Left" Content="{l:Loc Import.Plan.Show}" Command="{Binding ShowPlanCommand}" ToolTip="{l:Loc Tooltips.Import.ShowPlan}"
Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Height="36" Padding="22,0" Content="{Binding StartText}" Command="{Binding StartCommand}"
ToolTip="{Binding StartToolTip}" Visibility="{Binding IsRunning, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<Button DockPanel.Dock="Right" Content="{l:Loc Import.Progress.Cancel}" Command="{Binding CancelCommand}" ToolTip="{l:Loc Tooltips.Import.Cancel}" Margin="12,0,0,0"
Visibility="{Binding IsRunning, Converter={StaticResource BoolToVisibility}}" />
<Grid Visibility="{Binding IsRunning, Converter={StaticResource BoolToVisibility}}" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ProgressBar Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Text="{Binding ProgressText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="12,0,0,0" Typography.NumeralAlignment="Tabular" />
</Grid>
</DockPanel>
</Grid>
</Border>
<!-- ===================== Show plan ===================== -->
<Border Grid.RowSpan="3" Style="{StaticResource Border.Panel}" Background="{DynamicResource Brush.Surface}" Padding="0" Margin="-8"
Visibility="{Binding IsDetailsOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
<Border.InputBindings>
<KeyBinding Key="Escape" Command="{Binding CloseDetailsCommand}" />
</Border.InputBindings>
<Grid DataContext="{Binding Details}" Margin="16,12" Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DockPanel>
<Button x:Name="ClosePlanButton" DockPanel.Dock="Right" Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}"
Command="{Binding DataContext.CloseDetailsCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" ToolTip="{l:Loc Tooltips.Import.ClosePlan}"
AutomationProperties.Name="{l:Loc Import.Details.Close}" />
<TextBlock Text="{l:Loc Import.Details.Title}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" />
<TextBlock Text="{Binding TotalsText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,0,0,0" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
Typography.NumeralAlignment="Tabular" />
</DockPanel>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Conflicts}" Focusable="False" Margin="0,8,0,0" MaxHeight="96">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ui:StatusGlyph Kind="Warning" Text="{Binding}" FontSize="12" Margin="0,2" ToolTip="{l:Loc Tooltips.Import.Conflict}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid Grid.Row="2" Margin="0,10,0,4" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.2*" MinWidth="140" />
<ColumnDefinition Width="1.8*" MinWidth="180" />
<ColumnDefinition Width="0.8*" MinWidth="90" />
<ColumnDefinition Width="0.5*" MinWidth="64" />
<ColumnDefinition Width="Auto" SharedSizeGroup="PlanAction" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Source}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Destination}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Details.Column.Action}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Import.Session.Column.Size}" Margin="10,0,0,0" TextAlignment="Right" />
</Grid>
<ListBox x:Name="PlanRows" Grid.Row="3" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.PlanRow}" AutomationProperties.Name="{l:Loc Import.Details.Title}"
KeyboardNavigation.TabNavigation="Continue">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type imp:PlanDetailRow}">
<Grid x:Name="Row" Height="30" TextElement.FontSize="12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.2*" MinWidth="140" />
<ColumnDefinition Width="1.8*" MinWidth="180" />
<ColumnDefinition Width="0.8*" MinWidth="90" />
<ColumnDefinition Width="0.5*" MinWidth="64" />
<ColumnDefinition Width="Auto" SharedSizeGroup="PlanAction" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="Source" Style="{StaticResource Text.Cell}" Text="{Binding Source}" ToolTip="{Binding Source}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Destination}" Margin="10,0,0,0" ToolTip="{Binding Destination}" />
<TextBlock x:Name="Action" Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding ActionText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<Button x:Name="Split" Grid.Column="4" Style="{StaticResource Button.Row}" Margin="10,0,4,0" Content="{l:Loc Import.Details.Split}"
Command="{Binding DataContext.SplitCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Import.Split}" Visibility="Hidden" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding CanSplit}" Value="True">
<Setter TargetName="Split" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding Kind}" Value="Session">
<Setter TargetName="Source" Property="FontWeight" Value="SemiBold" />
<Setter TargetName="Row" Property="Height" Value="34" />
</DataTrigger>
<DataTrigger Binding="{Binding IsSkipped}" Value="True">
<Setter TargetName="Row" Property="Opacity" Value="0.6" />
<Setter TargetName="Action" Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
+55 -1
View File
@@ -1,8 +1,62 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
namespace Titano.App.Sections;
public partial class ImportView : UserControl
{
public ImportView() => InitializeComponent();
private bool _nicknameOpen;
public ImportView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
}
private ImportViewModel? Model => DataContext as ImportViewModel;
/// <summary>"Edit ▾" and "{ }" open their menu under themselves.</summary>
private void OnOpenMenu(object sender, RoutedEventArgs e)
{
if (sender is not Button { ContextMenu: { } menu } button) return;
menu.DataContext = DataContext;
menu.PlacementTarget = button;
menu.Placement = PlacementMode.Bottom;
menu.IsOpen = true;
}
/// <summary>The "{ }" menu writes into the template field used last.</summary>
private void OnFolderTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: true);
private void OnFileTemplateFocus(object sender, KeyboardFocusChangedEventArgs e) => Model?.SetActiveTemplate(folder: false);
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is INotifyPropertyChanged old) old.PropertyChanged -= OnModelChanged;
if (e.NewValue is INotifyPropertyChanged model) model.PropertyChanged += OnModelChanged;
}
/// <summary>
/// Keyboard focus follows what opens: the nickname field when it appears (a new card, Rename), and "Show plan"
/// (focus returns to its button when it closes).
/// </summary>
private void OnModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (Model is not { } model) return;
if (e.PropertyName is nameof(ImportViewModel.IsNicknameOpen) or "")
{
var opened = model.IsNicknameOpen && !_nicknameOpen;
_nicknameOpen = model.IsNicknameOpen;
if (opened && IsVisible) FocusLater(NicknameBox);
}
if (e.PropertyName is nameof(ImportViewModel.IsDetailsOpen) && IsVisible)
FocusLater(model.IsDetailsOpen ? ClosePlanButton : ShowPlanButton);
}
/// <summary>After layout: an element that just became visible cannot take focus yet.</summary>
private void FocusLater(UIElement element) => Dispatcher.BeginInvoke(DispatcherPriority.Input, () => element.Focus());
}
File diff suppressed because it is too large. Load diff
+5
View File
@@ -14,6 +14,11 @@
Visibility="{Binding Detail, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
<TextBlock Text="{Binding Detail}" FontFamily="{StaticResource Font.Mono}" FontSize="{StaticResource Size.Secondary}" TextWrapping="Wrap" TextTrimming="None" LineHeight="18" />
</Border>
<StackPanel x:Name="Typing" Margin="0,16,0,0" Visibility="Collapsed">
<TextBlock Text="{Binding TypedPrompt}" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" />
<TextBox x:Name="Typed" Margin="0,6,0,0" ui:Field.Placeholder="{Binding TypedConfirmation}" ToolTip="{Binding TypedPrompt}"
AutomationProperties.Name="{Binding TypedPrompt}" TextChanged="OnTyped" />
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,24,0,0">
<Button Content="{Binding SafeText}" ToolTip="{Binding SafeToolTip}" IsDefault="True" IsCancel="True" MinWidth="96" Click="OnSafe" />
<Button x:Name="Action" Content="{Binding ActionText}" ToolTip="{Binding ActionToolTip}" MinWidth="96" Margin="8,0,0,0" Click="OnAction" />
@@ -12,6 +12,10 @@ public sealed partial class ConfirmDialog : TitanoWindow
DataContext = request;
InitializeComponent();
Action.SetResourceReference(StyleProperty, request.IsDestructive ? "Button.Destructive" : "Button.Primary");
if (request.TypedConfirmation is null) return;
Typing.Visibility = Visibility.Visible;
Loaded += (_, _) => Typed.Focus();
EnableAction(false);
}
/// <summary>True when the user chose the action.</summary>
@@ -26,4 +30,15 @@ public sealed partial class ConfirmDialog : TitanoWindow
private void OnSafe(object sender, RoutedEventArgs e) => DialogResult = false;
private void OnAction(object sender, RoutedEventArgs e) => DialogResult = true;
private void OnTyped(object sender, System.Windows.Controls.TextChangedEventArgs e) =>
EnableAction(string.Equals(Typed.Text.Trim(), ((ConfirmRequest)DataContext).TypedConfirmation, StringComparison.CurrentCultureIgnoreCase));
/// <summary>The action waits for the typed confirmation; until then its tooltip says what to type (DESIGN §4 disabled states).</summary>
private void EnableAction(bool enabled)
{
var request = (ConfirmRequest)DataContext;
Action.IsEnabled = enabled;
Action.ToolTip = enabled ? request.ActionToolTip : request.TypedPrompt;
}
}
+2 -2
View File
@@ -9,7 +9,7 @@ namespace Titano.App.Shell;
/// <summary>
/// Attaches an <see cref="EditableField"/> to a text box (DESIGN §4 inputs): Enter commits, Esc reverts, leaving
/// the field commits a valid value.
/// the field commits a valid value. Ctrl+Enter commits and still reaches the screen's shortcut (Import · Ctrl+Enter).
/// </summary>
public static class EditBehavior
{
@@ -37,7 +37,7 @@ public static class EditBehavior
{
field.Commit();
box.SelectAll();
e.Handled = true;
e.Handled = Keyboard.Modifiers != ModifierKeys.Control;
}
else if (e.Key == Key.Escape)
{
+22 -3
View File
@@ -3,8 +3,10 @@ using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Titano.App.Archiving;
using Titano.App.DesignTime;
using Titano.App.Editor;
using Titano.App.Import;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.Core.Diagnostics;
@@ -95,10 +97,21 @@ public static class ScreenCapture
shell.Navigate(SectionKey.About);
written += await SaveAsync(window, directory, "about", theme);
foreach (var key in new[] { SectionKey.Import, SectionKey.Sequence, SectionKey.Archive })
shell.Navigate(SectionKey.Sequence);
written += await SaveAsync(window, directory, "sequence", theme);
foreach (var state in ImportScenes.States)
{
shell.Navigate(key);
written += await SaveAsync(window, directory, key.ToString().ToLowerInvariant(), theme);
DismissToasts(window);
await ImportScenes.ShowAsync(shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(window);
written += await SaveAsync(window, directory, "import-" + state, theme);
}
DismissToasts(window);
foreach (var view in ArchiveScenes.Views)
{
await ArchiveScenes.ShowAsync(shell, view);
written += await SaveAsync(window, directory, "archive-" + view, theme);
}
}
// The sync table with proxies kept here and transfers in every state, then filtered to the conflict, then the
@@ -218,6 +231,12 @@ public static class ScreenCapture
return await SaveAsync(window, directory, screen, theme);
}
/// <summary>Toasts of one screen's scene stay out of the next screen's picture.</summary>
private static void DismissToasts(MainWindow window)
{
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
}
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
{
await Settle(window);
+2
View File
@@ -268,6 +268,8 @@ public sealed class ShellViewModel : LocalizedViewModel
{
Jobs.Dispose();
Library.Dispose();
Import.Dispose();
Archive.Dispose();
Server.Dispose();
Settings.Dispose();
About.Dispose();